# docmd docs - Full Context > Generated by docmd --- ## [Browser API (Client-Side)](https://docs.docmd.io/04/advanced/browser-api/) --- title: "Browser API (Client-Side)" description: "How to use the docmd engine directly in the browser to render documentation dynamically without a server." --- `docmd` features an **isomorphic core**. This means the exact same engine that builds your static site in Node.js can also run entirely inside a web browser. This is powerful for: * Building **CMS Previews** (Type markdown, see result instantly). * Creating **Playgrounds** (Like [CodePen](https://codepen.io) for docs). * Embedding documentation rendering into existing React/Vue/Angular apps. ## Installation via CDN You don't need to install Node.js. You can simply include the scripts and styles from a CDN like `unpkg` or `jsdelivr`. ```html ``` ## Usage Once the script loads, it exposes a global `docmd` object. ### `docmd.compile(markdown, config)` Compiles Markdown text into a complete HTML document string. **Parameters:** * `markdown` (String): The raw Markdown content. * `config` (Object): Configuration overrides (same structure as `docmd.config.js`). **Returns:** * `String`: The full HTML string (including ``, ``, ``, ``). ### Example: Live Preview Iframe The safest way to render the output is inside an ` ``` ## Advanced: Raw Content (No-Style) If you only want the HTML content *without* the `docmd` sidebar, header, or footer (for example, to inject into a `div` on your own site), use the `noStyle` frontmatter option in your input. ```javascript const markdown = `--- noStyle: true components: css: true --- # Just Content This will render without the sidebar layout.`; const html = docmd.compile(markdown, { /* config */ }); ``` ## Limitations The Browser API has a few limitations compared to the Node.js CLI: 1. **No File System Access:** It cannot scan folders to auto-generate navigation. You must provide the `navigation` array explicitly in the config object if you want a sidebar. 2. **Plugins:** Some Node.js-specific plugins (like Sitemap generation) will not run. However, client-side plugins (like Mermaid diagrams) work perfectly. --- ## [Client-Side Events](https://docs.docmd.io/04/advanced/client-side-events/) --- title: Client-Side Events description: Hook into the docmd SPA router for custom interactive features. --- `docmd` uses a lightweight Single Page Application (SPA) router to provide instant page transitions. Because the page does not fully reload when navigating, standard `DOMContentLoaded` scripts might not trigger on subsequent page views. To solve this, `docmd` dispatches a custom event called `docmd:page-mounted` whenever a new page renders. ## The `docmd:page-mounted` Event You can listen for this event in your custom JavaScript files to re-initialise libraries or trigger custom logic. ### Usage Create a custom script (e.g., `assets/js/my-plugin.js`) and add it to your `docmd.config.js` under `customJs`. ```javascript document.addEventListener('docmd:page-mounted', (e) => { console.log('New page loaded:', e.detail.url); // Re-initialise your libraries here // Example: MathJax.typeset(); }); ``` ### Event Detail The event object contains a `detail` property with the following data: | Property | Type | Description | | :--- | :--- | :--- | | `url` | `string` | The full URL of the page that just loaded. | | `initial` | `boolean` | `true` if this is the first initial load, `undefined` on navigation. | ## Example: Integrating MathJax If you want to use MathJax for LaTeX equations, standard integration won't work with SPA navigation. Use the event listener: ```javascript // assets/js/math-support.js (function() { // 1. Load MathJax (if not using CDN in head) // ... // 2. Define the render function function renderMath() { if (window.MathJax) { window.MathJax.typesetPromise(); } } // 3. Hook into events document.addEventListener('DOMContentLoaded', renderMath); document.addEventListener('docmd:page-mounted', renderMath); })(); ``` --- ## [Programmatic API](https://docs.docmd.io/04/advanced/node-api/) --- title: "Programmatic API" description: "Programmatic API for building docmd sites from your own scripts." --- You can use `docmd` programmatically inside your own Node.js scripts or task runners (Gulp, Grunt, custom CI). ## Installation ```bash npm install @docmd/core ``` ## Usage ```javascript const { build, buildLive } = require('@docmd/core'); async function generateDocs() { try { console.log('Starting build...'); // 1. Build the Static Site await build('./docmd.config.js', { isDev: false, // true = enables hot-reload logic (internal) offline: false // true = optimise links for file:// access }); console.log('Static site generated in ./site'); // 2. Build the Live Editor (Optional) // Generates the browser-based editor bundle in ./dist await buildLive({ serve: false // true = starts local server, false = build only }); } catch (error) { console.error('Build failed:', error); process.exit(1); } } generateDocs(); ``` --- ## [CLI Commands](https://docs.docmd.io/04/cli-commands/) --- title: "CLI Commands" description: "A complete reference guide to the docmd command-line interface and its available options." --- The Command Line Interface (CLI) is the primary way you will interact with `docmd` while building and testing your documentation. ## `docmd init` Initialises a new `docmd` project in your current directory. **Usage:** ```bash docmd init ``` This command safely generates the necessary boilerplate to get you started without overwriting existing files. It creates: * A `docs/` folder containing a sample `index.md` file. * An `assets/` folder structure for your custom CSS, JS, and images. * A modern `docmd.config.js` file pre-filled with sensible defaults. * A `package.json` file with standard build scripts. ## `docmd dev` Starts a local development server with hot-reloading. **Usage:** ```bash docmd dev [options] ``` This is the command you will use most often. It builds your site into memory, starts a local web server (usually at `http://localhost:3000`), and watches your `docs/` folder and config file. Whenever you save a file, it instantly rebuilds the changes and triggers a live reload in your browser. **Options:** * `-c, --config `: Specify a custom path to your configuration file (defaults to `docmd.config.js`). * `-p, --port `: Force the server to start on a specific port. If the port is busy, `docmd` will ask if you want to try the next available one. ## `docmd build` Compiles your Markdown files into a production-ready static website. **Usage:** ```bash docmd build [options] ``` This command reads your source directory, processes all Markdown and assets, minifies CSS/JS, and outputs a complete static website into your `site/` folder (or whatever you defined as your `outputDir`). The resulting folder can be uploaded to any static web host. **Options:** * `-c, --config `: Specify a custom configuration file. * `--offline`: Optimises the generated HTML links to end in `/index.html` so the site can be browsed directly from a local hard drive without a web server (using `file:///` protocols). ## `docmd migrate` Upgrades an older configuration file to the newest architecture. **Usage:** ```bash docmd migrate ``` If you are upgrading from an older version of `docmd` that used a "flat" configuration structure, this command will intelligently rewrite your config file to the modern layout. * It creates a safe backup named `docmd.config.legacy.js`. * It maps your old settings into the new `layout`, `optionsMenu`, and `footer` objects. * It preserves your existing plugins and navigation arrays. ## `docmd live` Builds and launches the browser-based Live Editor. **Usage:** ```bash docmd live [options] ``` This command bundles the core `docmd` engine into a standalone web application. It starts a local server where you can write Markdown in a split-pane view and see the rendered documentation instantly, demonstrating our isomorphic browser engine. **Options:** * `--build-only`: Generates the `dist/` folder containing the Live Editor but does not start the local server. Use this if you want to host the Live Editor itself on a platform like GitHub Pages. ## Global Options These flags can be appended to any command. * `-v, --version`: Displays the currently installed version of `docmd`. * `-h, --help`: Displays help information and available options for the CLI. --- ## [Comparing Documentation Tools](https://docs.docmd.io/04/comparison/) --- title: "Comparing Documentation Tools" description: "See how docmd stacks up against Docusaurus, MkDocs, Mintlify, and other documentation generators." --- Choosing the right tool depends on your team's workflow and your project's scale. `docmd` was engineered to fill a specific gap: the space between "too simple" (basic Markdown parsers) and "too heavy" (full React/framework applications). ## Feature Matrix Here is how `docmd` compares to the industry standards across key metrics. | Feature | docmd | Docusaurus | MkDocs (Material) | Mintlify | | :--- | :--- | :--- | :--- | :--- | | **Core Architecture** | Node.js (Isomorphic) | React.js | Python | Proprietary | | **Navigation** | **Instant SPA** | React SPA | Page Reloads | Hosted SPA | | **Client JS Payload** | **Tiny (< 20kb)** | Heavy (> 200kb) | Minimal | Medium | | **Search Engine** | **Built-in (Offline)** | Algolia (Cloud) | Built-in (Lunr) | Built-in (Cloud) | | **Custom Containers** | **Deep Nesting** | MDX / React | Admonitions | MDX | | **Setup Time** | **< 1 minute** | ~15 mins | ~10 mins | Instant | | **Browser API**| **Yes (Live Editor)** | No | No | No | | **Cost** | **Free OSS** | Free OSS | Free OSS | Freemium | ## The docmd Advantage If you are trying to decide if `docmd` is right for you, here are the three areas where it truly shines. ### 1. The "Isomorphic" Engine Unlike Docusaurus or MkDocs, which are strictly "Build Tools" that must run on a server or CI/CD pipeline, `docmd` has a modular core. You can run the exact same `docmd` compilation engine directly inside a web browser. This enables features like our Live Editor, allowing you to build CMS interfaces or live preview tools for your users without needing a backend server. ### 2. Privacy-First, Offline Search Most documentation generators push you toward third-party services like Algolia DocSearch. While Algolia is fantastic for enterprise scale, it requires API keys, crawler configurations, and sends user search data to external servers. `docmd` includes a production-grade search engine out of the box. It generates a highly optimised local index during the build. This means your documentation is searchable even if the user loses their internet connection, and respects user privacy completely. ### 3. Pure HTML + SPA Speed We believe reading documentation shouldn't require downloading a massive JavaScript framework. When you build a `docmd` site, it generates pure, semantic HTML. This results in perfect SEO and instant initial page loads. However, once the page is open, our lightweight client-side router takes over. Clicking links feels exactly like a modern React or Next.js app-content swaps instantly without the browser ever flashing or reloading. ## When to choose something else We are proud of what `docmd` does, but it isn't for everyone. * **Choose Docusaurus if:** You need to embed highly interactive, custom React components directly inside your Markdown files, or if you are building a massive corporate portal with extreme internationalization needs. * **Choose MkDocs if:** Your entire engineering team strictly works in Python and you want to utilize the existing Python plugin ecosystem. --- ## [General Configuration](https://docs.docmd.io/04/configuration/general/) --- title: "General Configuration" description: "Configure the core settings, layout, and appearance of your docmd site." --- The `docmd.config.js` file is the heart of your project. It exports a JavaScript object that controls everything from your site title to the footer layout. ## Core Metadata These settings define the identity of your site. ```javascript const { defineConfig } = require('@docmd/core'); module.exports = { siteTitle: 'My Project', siteUrl: 'https://mysite.com', // Important for SEO & Sitemap plugins srcDir: 'docs', // Default: 'docs' outputDir: 'site', // Default: 'site' // Branding logo: { light: 'assets/logo-dark.png', // Shown in light mode dark: 'assets/logo-light.png', // Shown in dark mode href: '/', // Link destination alt: 'Project Logo' }, favicon: 'assets/favicon.ico' } ``` ## Layout Architecture `docmd` (v0.4.8+) uses a nested `layout` object to organise UI components. ```javascript layout: { // 1. Single Page Application Router // Enables seamless page transitions without refresh. spa: true, // 2. Header Configuration header: { enabled: true }, // 3. Sidebar Configuration sidebar: { collapsible: true, // Adds the toggle button to header defaultCollapsed: false // Initial state }, // 4. Options Menu (Search, Theme, Sponsor) // Consolidates utility buttons into one location. optionsMenu: { position: 'header', // 'header' or 'sidebar-bottom' components: { search: true, themeSwitch: true, sponsor: 'https://github.com/sponsors/my-name' } }, // 5. Footer Configuration footer: { style: 'complete', // 'minimal' or 'complete' copyright: '© 2026 My Project', description: 'Documentation built with docmd.', // Only used if style is 'complete' columns: [ { title: 'Resources', links: [ { text: 'Guide', url: '/guide' }, { text: 'API', url: '/api' } ] } ] } } ``` ## Theme & Styles Control the visual appearance. ```javascript theme: { name: 'default', // 'default', 'sky', 'ruby', 'retro' defaultMode: 'system', // 'light', 'dark', or 'system' codeHighlight: true, // Enable syntax highlighting // Array of paths relative to outputDir customCss: ['assets/css/custom.css'] } ``` ## Feature Toggles Disable specific features if you don't need them. ```javascript // Global Feature Flags minify: true, // Minify HTML/CSS/JS in production autoTitleFromH1: true, // Use first # Heading as title if frontmatter missing copyCode: true, // Show copy button on code blocks pageNavigation: true, // Show Next/Prev links at bottom of pages ``` --- ## [Layout & UI Slots](https://docs.docmd.io/04/configuration/layout-slots/) --- title: "Layout & UI Slots" description: "Master the structure of docmd by controlling headers, sidebars, and functional slots." --- `docmd` treats the interface as a series of "Slots." Every major component-from the navigation sidebar to the search bar, can be toggled, moved, or customised to fit your project's specific needs. ## Visual Overview A standard `docmd` page is divided into the following structural areas: 1. **Header:** The top bar containing the title and utility buttons. 2. **Sidebar:** The left-hand navigation and category tree. 3. **Content Area:** The primary Markdown rendering zone. 4. **TOC (Table of Contents):** The right-hand heading navigation. 5. **Footer:** The bottom area for copyright, links, and branding. ## The Header Slot The header is enabled by default. You can disable it site-wide or customise its content. ```javascript // docmd.config.js layout: { header: { enabled: true, // Set to false to hide the entire top bar } } ``` ### Hiding the Page Title in Header By default, the header displays the `title` defined in your page frontmatter. If you prefer to show the title only within the text body (using an `

`), you can hide it in the header on a per-page basis. **In your Markdown file:** ```yaml --- title: "Advanced Guide" hideTitle: true // Hides "Advanced Guide" from the sticky header --- ``` ## Functional "Options Menu" The `optionsMenu` is a unique functional slot that bundles the **Search**, **Theme Toggle**, and **Sponsor** buttons. You have full control over where this bundle appears. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom' components: { search: true, themeSwitch: true, sponsor: 'https://github.com/sponsors/yourname' } } } ``` ## Sidebar & Navigation The sidebar is your project's backbone. It can be made collapsible to give users more reading space. ```javascript layout: { sidebar: { collapsible: true, // Adds the toggle icon to the header defaultCollapsed: false, // Initial state for new visitors position: 'left' // Standard docs layout } } ``` ## The Footer Slot `docmd` offers two footer designs. The choice depends on the scale of your project. ### 1. Minimal Style A single-line footer for copyright and branding. Great for clean, simple projects. ```javascript footer: { style: 'minimal', content: '© 2026 My Project' } ``` ### 2. Complete Style A multi-column footer designed for professional ecosystems. Supports descriptions and categorized links. ```javascript footer: { style: 'complete', description: 'Built with docmd.', columns: [ { title: 'Community', links: [{ text: 'GitHub', url: '...' }] } ] } ``` ## Hiding docmd Branding While we appreciate you sharing the love, you can natively hide the "Built with docmd" badge in the footer for white-label or enterprise projects. ```javascript layout: { footer: { hideBranding: true // Removes the docmd logo/link from the footer } } ``` --- ## [Navigation Configuration](https://docs.docmd.io/04/configuration/navigation/) --- title: "Navigation Configuration" description: "Configure your sidebar links, nested groups, icons, and category labels." --- The sidebar navigation is controlled by the `navigation` array in your `docmd.config.js`. It allows you to define links, nest items into groups, and add visual icons. ## Basic Structure Each item in the array is an object representing a link or a group. ```javascript module.exports = { navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Installation', path: '/guide/install', icon: 'download' } ] } ``` ## Properties | Property | Type | Description | | :--- | :--- | :--- | | **`title`** | `String` | **Required.** Text displayed in the sidebar. | | **`path`** | `String` | Path to the page relative to your `srcDir`. Starts with `/`. | | **`icon`** | `String` | Name of a [Lucide](https://lucide.dev/icons) icon (e.g., `rocket`, `settings`). | | **`children`** | `Array` | An array of nested navigation items. | | **`collapsible`**| `Boolean` | If `true` (on a parent), allows the user to expand/collapse the group. | | **`external`** | `Boolean` | If `true`, opens the link in a new tab. | ## Grouping & Nesting You can nest items infinitely. Groups can be either **Clickable Pages** or **Static Labels**. ### 1. Clickable Parent (Folder Page) If you provide a `path` to a parent item, clicking it will take the user to that page *and* expand the menu. ```javascript { title: 'Guides', path: '/guides/index', // Clicking "Guides" goes here children: [ { title: 'Setup', path: '/guides/setup' } ] } ``` ### 2. Static Label (Category Header) If you **omit the `path`** (or set it to `'#'`), the item becomes a non-clickable category label. This is useful for grouping related links visually. ```javascript { title: 'Advanced Settings', icon: 'settings', // No path defined = Label only children: [ { title: 'Theme Config', path: '/config/theme' }, { title: 'Plugins', path: '/config/plugins' } ] } ``` ## Icons `docmd` includes the full **Lucide** icon set. You can use any icon name (kebab-case) in the `icon` property. * `home` → 🏠 * `book-open` → 📖 * `rocket` → 🚀 * `puzzle` → 🧩 ## External Links You can link to external websites directly from your sidebar. ```javascript { title: 'GitHub Repo', path: 'https://github.com/my-project', icon: 'github', external: true } ``` --- ## [Buttons](https://docs.docmd.io/04/content/containers/buttons/) --- title: "Buttons" description: "Create call-to-action buttons for links, downloads, and external resources." --- Buttons are perfect for "Call to Action" links, such as downloads, sign-ups, or navigating to key sections. ::: callout warning Self-Closing The button container is **self-closing**. Do not add a closing `:::` tag, or it may accidentally close parent containers (like Cards). ::: ## Syntax ```markdown ::: button "Label Text" Link [Options] ``` ## Examples ### Internal Links Use relative paths to link to other pages in your documentation. ```markdown ::: button "Get Started" /getting-started/installation ``` ::: button "Get Started" /getting-started/installation ### External Links Prepend `external:` to the URL to force it to open in a new tab with `target="_blank"`. ```markdown ::: button "View Source" external:https://github.com/docmd-io/docmd ``` ::: button "View Source" external:https://github.com/docmd-io/docmd ### Custom Colours You can customise the button colour using a hex code or CSS colour name. ```markdown ::: button "Critical Action" /delete-account color:#ef4444 ::: button "Success" /confirm color:green ``` ::: button "Critical Action" /delete-account color:#ef4444 ::: button "Success" /confirm color:green --- ## [Callouts](https://docs.docmd.io/04/content/containers/callouts/) --- title: "Callouts" description: "Highlight important information using semantic callout blocks." --- Callouts allow you to highlight specific information that exists outside the normal flow of text. `docmd` supports five semantic types. ## Syntax ```markdown ::: callout type Title Content goes here. ::: ``` If you omit the title, it defaults to the type name (e.g., "Info"). ## Available Types ### Info General information or "Did you know?" boxes. ```markdown ::: callout info Note This is a standard informational callout. ::: ``` ::: callout info Note This is a standard informational callout. ::: ### Tip Best practices and shortcuts. ```markdown ::: callout tip Pro Tip You can nest other containers inside callouts! ::: ``` ::: callout tip Pro Tip You can nest other containers inside callouts! ::: ### Warning Things the user should be careful about. ```markdown ::: callout warning Caution Proceed with care. ::: ``` ::: callout warning Caution Proceed with care. ::: ### Danger Critical warnings, data loss risks, or errors. ```markdown ::: callout danger **Critical Error:** Do not delete the database file. ::: ``` ::: callout danger **Critical Error:** Do not delete the database file. ::: ### Success Confirmation of actions or positive outcomes. ```markdown ::: callout success Build completed successfully! ::: ``` ::: callout success Build completed successfully! ::: --- ## [Cards](https://docs.docmd.io/04/content/containers/cards/) --- title: "Cards" description: "Group content into visually distinct, framed boxes." --- Cards are versatile containers used to group related content. They are excellent for creating grid layouts, feature lists, or summarizing sections. ## Syntax ```markdown ::: card Optional Title Card content goes here. ::: ``` ## Examples ### Basic Card With a title and simple text. ```markdown ::: card Features * Fast Build * Offline Search * No Config ::: ``` ::: card Features * Fast Build * Offline Search * No Config ::: ### Nested Content Cards are structural elements. You can put almost anything inside them, including buttons and code blocks. ````markdown ::: card Download Get the latest version. ```bash npm i -g @docmd/core ``` ::: button "Download Now" /install color:#2563eb ::: ```` ::: card Download Get the latest version. ```bash npm i -g @docmd/core ``` ::: button "Download Now" /install color:#2563eb ::: --- ## [Changelogs](https://docs.docmd.io/04/content/containers/changelogs/) --- title: "Changelogs" description: "Create beautiful, timeline-based version history pages." --- The `changelog` container formats version history into a clean, vertical timeline. It is specifically designed to parse date/version headers and body content separately. ## Syntax Use `==` to separate entries. The text on the `==` line becomes the timeline badge (left side), and the content below becomes the body (right side). ```markdown ::: changelog == Version 2.0 Description of version 2.0. == Version 1.0 Description of version 1.0. ::: ``` ## Example ```markdown ::: changelog == v2.0.0 (2026) ### Major Overhaul We rewrote the core engine for better performance. * Added SPA Router * Added Plugin System == v1.5.0 (2025) ### Maintenance Bug fixes and performance improvements. ::: callout info This was the last version to support Node 14. ::: == v1.0.0 (2024) Initial Release. ::: button "Just Getting Started" # ::: ``` **Rendered Output:** ::: changelog == v2.0.0 (2026) ### Major Overhaul We rewrote the core engine for better performance. * Added SPA Router * Added Plugin System == v1.5.0 (2025) ### Maintenance Bug fixes and performance improvements. ::: callout info This was the last version to support Node 14. ::: == v1.0.0 (2024) Initial Release. ::: button "Just Getting Started" # ::: --- ## [Collapsible](https://docs.docmd.io/04/content/containers/collapsible/) --- title: "Collapsible" description: "Create toggleable accordion sections for FAQs and advanced details." --- The `collapsible` container creates an accordion-style toggle. It is perfect for FAQs, spoilers, or hiding complex configuration options that aren't relevant to every reader. ## Syntax ```markdown ::: collapsible [open] Title Text Content goes here. ::: ``` * **`open`**: (Optional) If present, the section defaults to expanded. * **`Title Text`**: The text shown on the clickable bar. Defaults to "Click to expand". ## Examples ### Default (Closed) Useful for FAQs or spoilers. ```markdown ::: collapsible How do I reset my password? Go to **Settings > Account** and click "Reset Password". ::: ``` ::: collapsible How do I reset my password? Go to **Settings > Account** and click "Reset Password". ::: ### Default (Open) Useful for sections that should be visible but optional to hide. ```markdown ::: collapsible open Prerequisites 1. Node.js v18+ 2. A text editor ::: ``` ::: collapsible open Prerequisites 1. Node.js v18+ 2. A text editor ::: ### Nested Content You can put anything inside a collapsible, including code blocks. ````markdown ::: collapsible View JSON Response ```json { "status": "success", "data": { "id": 123 } } ``` ::: ```` ::: collapsible View JSON Response ```json { "status": "success", "data": { "id": 123 } } ``` ::: --- ## [Custom Containers](https://docs.docmd.io/04/content/containers/) --- title: "Custom Containers" description: "A gallery of the rich UI components available in docmd." --- Standard Markdown is great for text, but sometimes you need more. `docmd` extends Markdown with a set of "Containers" to help you structure complex documentation. Use the syntax `::: container_name` to start a block. ## Nesting Thanks to our advanced parser, you can nest these containers inside each other infinitely. See [Nested Containers](./nested-containers) for examples. --- ## [Nested Containers](https://docs.docmd.io/04/content/containers/nested-containers/) --- title: "Nested Containers" description: "Learn how to use the advanced nested container system to create complex, interactive documentation layouts with seamless container nesting." --- The advanced nested container system in docmd allows you to create complex, interactive documentation layouts by nesting containers within each other. This powerful feature enables you to build rich, structured content that was previously impossible. ## Nesting Rules ### Best Practices 1. **Logical Structure** - Nest containers in a way that makes logical sense 2. **Readability** - Don't nest too deeply (3-4 levels maximum for readability) 3. **Performance** - Complex nesting is supported but keep it reasonable 4. **Content Organisation** - Use nesting to organise related content 5. **Use the Right Tool** - Use steps for simple sequences, cards/tabs for complex content ### Limitations While `docmd` has improved the parser significantly over the period, there are still logical limits: 1. **Steps inside Tabs:** This is technically difficult to parse in Markdown. We recommend keeping Steps as top-level elements or inside Cards, but not inside Tabs. 2. **Buttons:** Buttons are now **self-closing**. Do not add a `:::` after a button line, or it might close a parent container (like a Card) accidentally. ## Examples ### Cards with Nested Content ```markdown ::: card Installation Guide Here's how to install the application: ::: callout tip Pro Tip Make sure to download the correct version for your platform. ::: ::: button "Download Now" /downloads ::: ``` ::: card Installation Guide Here's how to install the application: ::: callout tip Pro Tip Make sure to download the correct version for your platform. ::: ::: button "Download Now" # ::: ### Tabs with Nested Content ```markdown ::: tabs == tab "Windows" Download the Windows installer (.exe) file. ::: callout tip Make sure to run as administrator for best results. ::: ::: button "Download Windows" /downloads/windows == tab "macOS" Download the macOS package (.pkg) file. ::: callout warning You may need to allow the app in Security & Privacy settings. ::: ::: button "Download macOS" /downloads/macos == tab "Linux" Download the Linux tarball (.tar.gz) file. ::: button "Download Linux" /downloads/linux ::: ``` ::: tabs == tab "Windows" Download the Windows installer (.exe) file. ::: callout tip Make sure to run as administrator for best results. ::: ::: button "Download Windows" # == tab "macOS" Download the macOS package (.pkg) file. ::: callout warning You may need to allow the app in Security & Privacy settings. ::: ::: button "Download macOS" # == tab "Linux" Download the Linux tarball (.tar.gz) file. ::: button "Download Linux" # ::: ### Steps Container with Nested Elements Steps containers are designed for simple, sequential instructions and work well with other containers: ```markdown ::: steps 1. **Download the Application** Get the latest version from our download page. ::: button "Download Now" /downloads 2. **Install the Application** Run the installer and follow the setup wizard. ::: callout tip Pro Tip Check our system requirements page for detailed information. ::: 3. **Configure Settings** Set up your preferences and start using the app. ::: card Configuration - Choose your theme - Set up notifications - Configure integrations ::: ::: ``` ::: steps 1. **Download the Application** Get the latest version from our download page. ::: button "Download Now" # 2. **Install the Application** Run the installer and follow the setup wizard. ::: callout tip Pro Tip Check our system requirements page for detailed information. ::: 3. **Configure Settings** Set up your preferences and start using the app. ::: card Configuration - Choose your theme - Set up notifications - Configure integrations ::: ::: ## Troubleshooting ### Common Issues 1. **Container not rendering** - Ensure proper spacing and syntax 2. **Nested content not showing** - Check for proper closing tags 3. **Performance issues** - Reduce nesting depth if experiencing slowdowns ### Debugging Tips - **Check syntax** - Ensure all containers have proper opening and closing tags - **Verify nesting** - Make sure containers are properly nested - **Test incrementally** - Build complex structures step by step - **Use browser dev tools** - Inspect the generated HTML for issues - **Use the right container** - Steps for simple sequences, cards/tabs for complex content --- ## [Steps](https://docs.docmd.io/04/content/containers/steps/) --- title: "Steps" description: "Create beautiful numbered instruction lists for tutorials." --- The `steps` container transforms a standard ordered list into a visual timeline of instructions. It is designed for "How-to" guides. ## Syntax Wrap a standard numbered list in `::: steps`. ```markdown ::: steps 1. **Step Title** Step description. 2. **Next Step** Description. ::: ``` ## Example ```markdown ::: steps 1. **Initialise Project** Run the init command to scaffold your folder. ```bash docmd init ``` 2. **Start Server** Launch the local dev environment. ```bash docmd dev ``` 3. **Deploy** Upload the `site/` folder. ::: ``` **Rendered Output:** ::: steps 1. **Initialise Project** Run the init command to scaffold your folder. ```bash docmd init ``` 2. **Start Server** Launch the local dev environment. ```bash docmd dev ``` 3. **Deploy** Upload the `site/` folder. ::: ## With Nested Elements You can use other containers inside a step to provide extra context. ```markdown ::: steps 1. **Configure Database** Edit your `.env` file. ::: callout danger Do not commit this file to Git! ::: 2. **Run Migrations** Update the schema. ::: ``` ::: steps 1. **Configure Database** Edit your `.env` file. ::: callout danger Do not commit this file to Git! ::: 2. **Run Migrations** Update the schema. ::: ## Customisation Steps containers automatically apply consistent styling and numbering. The container handles: - **Automatic numbering** - Steps are numbered sequentially - **Consistent spacing** - Proper spacing between steps - **Responsive design** - Works on all screen sizes - **Theme integration** - Matches your site's theme - **Smart list handling** - Only step items get special styling, nested lists remain normal --- ## [Tabs](https://docs.docmd.io/04/content/containers/tabs/) --- title: "Tabs" description: "Organise content into switchable tabbed panes." --- Tabs are essential for showing alternative content (like code snippets for different languages or instructions for different OSs) without cluttering the page. ## Syntax Use `== tab "Name"` to define a new tab pane. ```markdown ::: tabs == tab "Tab 1 Name" Content for tab 1. == tab "Tab 2 Name" Content for tab 2. ::: ``` ## Example ### Code Switching ````markdown ::: tabs == tab "JavaScript" ```javascript console.log("Hello World"); ``` == tab "Python" ```python print("Hello World") ``` ::: ```` **Rendered Output:** ::: tabs == tab "JavaScript" ```javascript console.log("Hello World"); ``` == tab "Python" ```python print("Hello World") ``` ::: ## Lazy Rendering `docmd` is smart. If you put heavy content (like a **Mermaid diagram**) inside a hidden tab, it will wait to render it until the user actually clicks the tab. This keeps your page load fast. ## Best Practices 1. **Clear Labels** - Use descriptive tab names 2. **Consistent Content** - Keep similar content types in each tab 3. **Logical Order** - Arrange tabs in a logical sequence 4. **Not Too Many** - Limit to 5-7 tabs for best usability 5. **Mobile Friendly** - Consider mobile users when organising content ## Nesting Limitations - **Tabs cannot contain tabs** - This prevents infinite recursion - **Steps inside tabs not supported** - Use regular ordered lists instead - **Maximum depth** - While technically unlimited, keep it under 3-4 levels for readability - **Performance** - Very deep nesting may impact rendering performance ::: callout warning Steps Inside Tabs **Steps containers cannot be used inside tabs** due to parsing conflicts. If you need step-by-step instructions within tabs, use regular numbered lists or consider restructuring your content. ::: --- ## [Frontmatter Reference](https://docs.docmd.io/04/content/frontmatter/) --- title: "Frontmatter Reference" description: "The complete guide to page-level metadata and configuration in docmd." --- Frontmatter allows you to override global settings on a per-page basis. It must be written in YAML format at the very top of your Markdown file. ## Core Metadata | Key | Type | Description | | :--- | :--- | :--- | | `title` | `String` | **Required.** Sets the HTML `` and the primary page header. | | `description` | `String` | Sets the meta description for SEO and search results. | | `keywords` | `Array` | A list of keywords for the `<meta name="keywords">` tag. | ## Visibility & SEO | Key | Type | Description | | :--- | :--- | :--- | | `noindex` | `Boolean` | Excludes the page from the search index and search engines. | | `llms` | `Boolean` | Set to `false` to exclude this page from the `llms.txt` file. | | `sitemap` | `Object` | Custom sitemap settings: `priority` (0.0-1.0) and `changefreq` (e.g., `daily`). | ## Page Layout | Key | Type | Description | | :--- | :--- | :--- | | `layout` | `String` | Set to `full` to hide the Table of Contents and use the full width. | | `hideTitle` | `Boolean` | If `true`, the title is hidden from the sticky top header. | | `toc` | `Boolean` | Set to `false` to disable the Table of Contents entirely. | | `bodyClass` | `String` | Adds a custom CSS class to the `<body>` tag of this page. | ## Injection Slots Use these keys to add custom HTML/JS to specific pages without changing your global config. * **`customHead`**: Injects HTML into the `<head>`. * **`customScripts`**: Injects HTML at the very end of the `<body>`. ## No-Style Mode (`noStyle: true`) When `noStyle` is enabled, the docmd layout is removed. You must explicitly opt-in to components: ```yaml --- noStyle: true components: meta: true # Injects SEO tags favicon: true # Injects favicon css: true # Injects docmd-main.css theme: true # Injects theme CSS highlight: true # Injects syntax highlighting scripts: true # Injects docmd-main.js layout: true # Injects the content-area wrapper sidebar: true # Injects the navigation sidebar footer: true # Injects the footer branding: true # Injects the "Built with docmd" badge --- ``` ## Plugin Overrides ### SEO Plugin (`seo`) * `description`: Page-specific social description. * `image`: Social share image URL. * `ogType`: Open Graph type (default: `website`). * `twitterCard`: Twitter card type. * `canonicalUrl`: Sets a custom canonical link. --- ## [Live Preview & Browser Support](https://docs.docmd.io/04/content/live-preview/) --- title: "Live Preview & Browser Support" description: "Run docmd entirely in the browser without a server using the new Live architecture." --- ::: button "Open Live Editor" https://live.docmd.io color:#007bff `docmd` features a modular architecture that separates file system operations from core processing logic. This allows the documentation engine to run **entirely in the browser** (client-side), opening up possibilities for live editors, CMS previews, and zero-latency feedback loops. ## The Live Editor `docmd` comes with a built-in "Live Editor" that demonstrates this capability. It provides a split-pane interface where you can write Markdown on the left and see the rendered documentation on the right - instantly, without a server round-trip. ### Running the Editor Locally To launch the live editor on your machine: ```bash docmd live ``` This command will: 1. Bundle the core logic into `dist/docmd-live.js`. 2. Copy necessary assets (CSS, templates). 3. Start a local static server opening the editor. ### Building for Deployment If you want to host the Live Editor itself on a static hosting provider (so your team can write docs in the browser), you can generate the assets without starting the local server: ```bash docmd live --build-only ``` This creates a `dist/` directory containing: * `index.html`: The editor entry point. * `docmd-live.js`: The bundled engine. * `assets/`: Themes and styles. You can simply upload this `dist/` folder to any static host. ## Embedding docmd in Your Site You can use the browser-compatible bundle to add Markdown preview capabilities to your own applications. ### 1. Include the Script and Assets You need to serve the `docmd-live.js` bundle and the `assets/` folder (which contains themes and styles). ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <link rel="stylesheet" href="/assets/css/docmd-theme-sky.css"> <script src="/docmd-live.js"></script> ``` ### 2. Use the API The bundle exposes a global `docmd` object. You can use the `compile` function to transform Markdown into a full HTML page string. ```javascript const markdown = "# Hello World\n\nThis is **live** documentation."; const config = { siteTitle: 'My Live Doc', theme: { name: 'sky', defaultMode: 'light' } }; // Compile returns the full HTML string including <head>, <body>, etc. const html = docmd.compile(markdown, config, { // Optional: Help the renderer resolve relative paths relativePathToRoot: './' }); // Inject into an iframe or DOM element document.getElementById('preview-frame').srcdoc = html; ``` ## Important Resources - Check out the [Browser API Guide](/advanced/browser-api/). - [Node API](/advanced/node-api/) for embedded documentation. --- ## [docmd : No-Style Page Example](https://docs.docmd.io/04/content/no-style-example/) --- title: "docmd : No-Style Page Example" description: "An example of a page using the no-style feature" noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; margin: 0; padding: 0; line-height: 1.6; } .container { max-width: 800px; margin: 0 auto; padding: 40px 20px; } .header { text-align: centre; margin-bottom: 40px; } .header h1 { font-size: 3rem; margin-bottom: 10px; color: #4a6cf7; } .header p { font-size: 1.2rem; color: #666; } .content { background-color: #f8f9fa; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); } .button { display: inline-block; padding: 12px 24px; background-color: #4a6cf7; color: white; text-decoration: none; border-radius: 4px; font-weight: 600; margin-top: 20px; } .button:hover { background-color: #3a5ce4; } [data-theme="dark"] { color-scheme: dark; } [data-theme="dark"] body { background-color: #121212; color: #e0e0e0; } [data-theme="dark"] .content { background-color: #1e1e1e; box-shadow: 0 2px 10px rgba(0,0,0,0.2); } [data-theme="dark"] .header p { color: #aaa; } </style> bodyClass: "no-style-example" --- <div class="container"> <div class="header"> <h1>No-Style Page Example</h1> <p>This page demonstrates the no-style feature with a custom layout</p> </div> <div class="content"> <h2>What is this page?</h2> <p> This is an example page that uses the <code>noStyle: true</code> frontmatter option to create a completely custom page layout. Unlike regular documentation pages, this page doesn't use the standard docmd layout with sidebar navigation and table of contents. </p> <h2>How does it work?</h2> <p> The <code>noStyle</code> option tells docmd to use a special template that only includes the components you explicitly request via the <code>components</code> object in frontmatter. This gives you complete control over the page structure. </p> <h2>Features enabled on this page:</h2> <ul> <li><strong>meta</strong>: Meta tags, title, and description for SEO</li> <li><strong>favicon</strong>: The site favicon</li> <li><strong>css</strong>: Basic CSS for markdown content</li> <li><strong>theme</strong>: Theme support for light/dark mode</li> <li><strong>scripts</strong>: JavaScript for functionality</li> </ul> <h2>Custom styling</h2> <p> This page includes custom CSS in the <code>customHead</code> frontmatter field. This allows you to define page-specific styles without affecting the rest of your site. </p> <a href="/content/no-style-pages/" class="button">Get Back to No-Style Pages Documentation</a> </div> </div> --- ## [No-Style Pages](https://docs.docmd.io/04/content/no-style-pages/) --- title: "No-Style Pages" description: "Create landing pages and custom layouts by disabling the default docmd theme." --- Sometimes you need a page that doesn't look like documentation - for example, a Marketing Landing Page, a Login screen, or a completely custom showcase. `docmd` allows you to disable the standard layout (Sidebar, Header, Footer) on a per-page basis using **Frontmatter**. ## Enabling No-Style Add `noStyle: true` to your page's frontmatter. ```yaml --- title: "Welcome" noStyle: true components: meta: true # Keep SEO meta tags favicon: true # Keep the site favicon scripts: false # Disable docmd's main JS (optional) --- <!-- Write raw HTML or Markdown below --> <div class="hero-section"> <h1>My Product</h1> <p>The future of something amazing.</p> </div> ``` ## Controlling Components When `noStyle` is active, `docmd` gives you a blank canvas. You can selectively re-enable specific parts of the system using the `components` object: | Component | Default (in noStyle) | Description | | :--- | :--- | :--- | | `meta` | `false` | Injects `<title>`, `<meta name="description">`, and SEO tags. | | `favicon` | `false` | Injects the favicon link. | | `css` | `false` | Injects `docmd-main.css` (useful if you want to use grid/typography but not layout). | | `theme` | `false` | Injects the active theme CSS (e.g., Sky, Retro). | | `scripts` | `false` | Injects `docmd-main.js` (needed for toggle buttons, copy code, etc). | ## Example: Marketing Landing Page ```yaml --- title: "Home" noStyle: true components: meta: true favicon: true css: true customHead: | <style> .hero { text-align: centre; padding: 100px 20px; } .hero h1 { font-size: 3rem; margin-bottom: 20px; } </style> --- <div class="hero"> <h1>Build Faster.</h1> <p>The ultimate developer tool.</p> ::: button "Get Started" /docs/intro color:blue </div> ``` --- ## [Advanced Syntax](https://docs.docmd.io/04/content/syntax/advanced/) --- title: "Advanced Syntax" description: "Beyond the basic syntax, docmd supports a variety of advanced Markdown features to help you create richer documentation." --- ## GFM (GitHub Flavored Markdown) docmd supports GitHub Flavored Markdown extensions including: ### Task Lists Create interactive checklists: ```markdown - [x] Completed task - [ ] Incomplete task - [ ] Another item ``` - [x] Completed task - [ ] Incomplete task - [ ] Another item ### Autolinked References URL and email addresses are automatically linked: ```markdown Visit https://docmd.io for more information. Contact support@example.com for help. ``` ### Emojis Use emoji shortcodes: ```markdown I :heart: docmd! :rocket: :smile: ``` > I :heart: docmd! :rocket: :smile: ## Custom Attributes (IDs and Classes) You can add custom IDs and CSS classes to headers, images, and links using curly braces `{}`. ### Custom IDs ```markdown ## My Header {#custom-id} ``` ### Custom Classes You can assign classes to elements. **Note:** You must define these classes in your own [Custom CSS](/theming/custom-css-js) file. ```markdown ## Styled Header {.text-centre .text-red} ``` ### Links and Buttons ```markdown [Download Now](/download){.docmd-button} ``` ## Footnotes You can add footnotes to your content for references or additional information[^1]. ```markdown Here's a statement that needs citation[^1]. [^1]: This is the footnote content. ``` Multiple footnotes can be used throughout your document[^2], and the definitions can be collected at the bottom. [^1]: This is the first footnote reference. [^2]: This is the second footnote with more information. ## Definition Lists Some Markdown parsers support definition lists: ```markdown Term : Definition for the term. : Another definition for the same term. Another Term : Definition of another term. ``` Term : Definition for the term. : Another definition for the same term. Another Term : Definition of another term. ## Abbreviations You can define abbreviations in your Markdown (depending on plugin support): ```markdown *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium HTML is defined by the W3C standards. ``` *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium HTML is defined by the W3C standards. ## Container Extensions Beyond standard Markdown, docmd provides custom containers for enhanced formatting. These are detailed in the [Custom Containers](/content/custom-containers/) guide, and include: ::: callout info Use containers for callouts, cards, and steps to structure your documentation. ::: --- ## [Code Blocks](https://docs.docmd.io/04/content/syntax/code/) --- title: "Code Blocks" description: "How to display code with syntax highlighting, line numbers, and copy buttons." --- `docmd` includes `highlight.js` for automatic syntax highlighting. ## Fenced Code Blocks Wrap your code in triple backticks (` ``` `) and specify the language. ````markdown ```javascript function hello() { console.log("Hello World"); } ``` ```` **Renders as:** ```javascript function hello() { console.log("Hello World"); } ``` ## Copy Button If `copyCode: true` is enabled in your config (default), a copy button will automatically appear on hover in the top-right corner of every code block. ## Supported Languages Common languages include: `javascript`, `typescript`, `html`, `css`, `bash`, `json`, `python`, `java`, `cpp`, `sql`, `yaml`, `markdown`. If you do not specify a language, it will be rendered as a plain text. --- ## [Images & Lightbox](https://docs.docmd.io/04/content/syntax/images/) --- title: "Images & Lightbox" description: "Adding images, galleries, and enabling lightbox zoom effects." --- ## Basic Images Use standard Markdown syntax to embed images. We recommend storing images in your `assets/images/` folder. ```markdown ![Alt Text](../../assets/images/screenshot.png "Optional Title") ``` ## Image Styling You can add classes to images using the attribute syntax `{ .class }` after the image. ### Sizing ```markdown ![Small](../../assets/icon.png){ .size-small } ![Medium](../../assets/preview.png){ .size-medium } ![Large](../../assets/banner.png){ .size-large } ``` ### Alignment ```markdown ![Centred](../../assets/img.png){ .align-centre } ![Right](../../assets/img.png){ .align-right } ``` ### Shadows & Borders ```markdown ![Styled](../../assets/img.png){ .with-shadow .with-border } ``` ![preview with styling](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium} ### Responsive Images All images in docmd are responsive by default, automatically scaling to fit their container. ## Image Captions Add captions to your images using the figure syntax: ```markdown <figure> <img src="/path/to/image.jpg" alt="Description of image"> <figcaption>This is the caption for the image</figcaption> </figure> ``` ## Image Galleries and Lightbox docmd includes built-in lightbox functionality for image galleries. When users click on an image in a gallery, it opens in a full-screen lightbox view. ## Image Galleries You can group multiple images into a responsive grid using the `image-gallery` class, use `figcaption` for image captioning. This requires raw HTML wrapping. ```html <div class="image-gallery"> <figure> <img src="../../assets/img1.jpg" alt="View 1"> <figcaption>Dashboard View</figcaption> </figure> <figure> <img src="../../assets/img2.jpg" alt="View 2"> <figcaption>Settings View</figcaption> </figure> </div> ``` <div class="image-gallery"> <figure> <img src="/assets/images/docmd-preview.png" alt="Feature 1"> <figcaption>Feature One</figcaption> </figure> <figure> <img src="/assets/images/docmd-preview.png" alt="Feature 2"> <figcaption>Feature Two</figcaption> </figure> </div> ## Lightbox (Zoom) If `mainScripts` is enabled (default), clicking any image in a gallery or any image with the `.lightbox` class will open a full-screen zoom view. ```markdown ![Click to Zoom](../../assets/diagram.png){ .lightbox } ``` ## Image Optimisation Best Practices For optimal performance: 1. **Use appropriate formats**: - JPEG for photographs - PNG for images with transparency - SVG for icons and logos - WebP for better compression (with fallbacks) 2. **Optimise file sizes**: - Compress images before adding them to your documentation - Consider using tools like ImageOptim, TinyPNG, or Squoosh 3. **Provide responsive images**: - Use the HTML `<picture>` element for advanced responsive image scenarios 4. **Specify dimensions**: - Always include width and height attributes to prevent layout shifts --- ## [Markdown Syntax](https://docs.docmd.io/04/content/syntax/) --- title: "Markdown Syntax" description: "Basic formatting guide for docmd: Headings, lists, bold, italic, and more." --- `docmd` uses standard Markdown syntax. This guide covers the essentials for formatting text. ## Text Formatting | Style | Syntax | Example | | :--- | :--- | :--- | | **Bold** | `**text**` or `__text__` | **Bold Text** | | *Italic* | `*text*` or `_text_` | *Italic Text* | | ~~Strikethrough~~ | `~~text~~` | ~~Deleted Text~~ | | `Code` | `` `text` `` | `Inline Code` | ## Common Elements You can use all standard Markdown elements: ### Headings ```markdown # Heading 1 ## Heading 2 ### Heading 3 ... ###### Heading 6 ``` ### Paragraphs Just type text. Separate paragraphs with a blank line. ### Lists * **Unordered:** ```markdown * Item 1 * Item 2 * Nested Item 2a * Nested Item 2b + Item 3 (using +) - Item 4 (using -) ``` * **Ordered:** ```markdown 1. First item 2. Second item 3. Third item 1. Nested ordered item ``` ### Links ```markdown [Link Text](https://www.example.com) [Link with Title](https://www.example.com "Link Title") [Relative Link to another page](../section/other-page/) ``` ::: callout info For internal links to other documentation pages, use relative paths to the `.md` files. `docmd` will convert these to the correct HTML paths during the build. ::: ### Images ::: callout info See [Images & Media](images.md) for more advanced setup. ::: ```markdown ![Alt text for image](/path/to/your/image.jpg "Optional Image Title") ``` ::: callout tip Place images in your `docs/` directory (e.g., `docs/images/`) or a similar assets folder that gets copied to your `site/` output. ::: ### Blockquotes ```markdown > This is a blockquote. > It can span multiple lines. ``` ### Horizontal Rules ```markdown --- *** ___ ``` ### Inline Code ::: callout info See [Code Blocks](code.md) for codeblocks and more advanced setup. ::: ```markdown Use `backticks` for inline code like `variableName`. ``` ### Tables (GFM Style) You can create tables using GitHub Flavored Markdown syntax: ```bash | Header 1 | Header 2 | Header 3 | | :------- | :------: | -------: | | Align L | Centre | Align R | | Cell 1 | Cell 2 | Cell 3 | | Cell 4 | Cell 5 | Cell 6 | ``` | Header 1 | Header 2 | Header 3 | | :------- | :------: | -------: | | Align L | Centre | Align R | | Cell 1 | Cell 2 | Cell 3 | | Cell 4 | Cell 5 | Cell 6 | ## HTML Because `markdown-it` is configured with `html: true`, you can embed raw HTML directly in your Markdown files. However, use this sparingly, as it can make your content less portable and harder to maintain. ```html <div style="color: blue;"> This is a blue div rendered directly from HTML. </div> ``` ::: callout tip For most formatting needs, standard Markdown and `docmd`'s [Custom Containers](../containers/) should suffice. ::: --- ## [Linking & Referencing](https://docs.docmd.io/04/content/syntax/linking/) --- title: "Linking & Referencing" description: "A guide to internal cross-linking, external links, and asset referencing." --- Learn how to connect your pages and link to external resources. ## Internal Page Links To link to another page in your documentation, use the **relative path** to the markdown file. ::: callout info Smart Rewriting `docmd` automatically converts `.md` extensions to valid HTML links during the build. This ensures links work in your code editor (VS Code) AND on the website. ::: **Examples:** | Goal | Syntax | | :--- | :--- | | Link to a file in the same folder | `[Read Guide](guide.md)` | | Link to a file in a subfolder | `[Read Config](configuration/index.md)` | | Link back to parent | `[Go Back](../index.md)` | ## Anchors (Section Linking) You can link to specific headers on a page using the `#slug`. * **Same Page:** `[Jump to Top](#linking--referencing)` * **Other Page:** `[See Installation](../getting-started/installation.md#global-installation)` ## External Links Standard URL syntax works for external sites. ```markdown [Visit Google](https://google.com) ``` **Protocol Links:** * `[Email Support](mailto:help@docmd.io)` * `[Call Us](tel:+123456789)` ## Linking to Assets To allow users to download files (like PDFs) or view raw assets, place them in your `assets/` folder. **Important:** When linking to files in `assets/`, `docmd` will **NOT** strip the extension. ```markdown [Download PDF](../../assets/manual.pdf) [View Raw Config](../../assets/examples/config.js) ``` --- ## [Contributing](https://docs.docmd.io/04/contributing/) --- title: "Contributing" description: "Learn how you can contribute to the development, design, and documentation of docmd." --- First off, thank you for considering contributing to `docmd`! It's people like you that make the open-source community an amazing place to learn, inspire, and create. We welcome contributions of all kinds, from fixing typos to engineering entirely new plugins. ## Ways to Contribute <div class="docmd-container clear-float"> <div class="image-gallery" style="grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));"> ::: card 🐛 Bug Reports Find something that isn't working right? Open an issue on GitHub. Please include your OS, Node version, and steps to reproduce. ::: ::: card ✨ Feature Requests Have an idea to make docmd better? Open an issue and let's discuss it before you start writing code! ::: ::: card 📝 Documentation This very website is built with docmd! You can contribute by fixing typos, improving recipes, or adding clearer examples. ::: ::: card 💻 Code Contributions Want to get your hands dirty? We happily accept Pull Requests for core engine improvements, UI polish, and new features. ::: </div> </div> ## Development Setup `docmd` is built as a **Monorepo** using `pnpm`. Developing it locally requires a specific workflow to ensure all the internal packages (core, UI, themes, plugins) talk to each other correctly. ::: steps 1. **Prerequisites** Ensure you have Node.js (v18+) and [pnpm](https://pnpm.io/installation) installed on your machine. ```bash npm install -g pnpm ``` 2. **Fork and Clone** Fork the repository on GitHub, then clone your fork locally: ```bash git clone https://github.com/YOUR_USERNAME/docmd.git cd docmd ``` 3. **Install Dependencies** Use `pnpm` to install all dependencies and link the monorepo workspaces together. ```bash pnpm install ``` 4. **Running the Dev Server** We use this documentation site (located in the `docs/` folder) as our primary testing ground. To start the development server and watch for changes in both the documentation *and* the core engine: ```bash # Windows (PowerShell) $env:DOCMD_DEV="true"; pnpm run dev # macOS / Linux DOCMD_DEV=true pnpm run dev ``` *Note: Setting `DOCMD_DEV=true` tells the watcher to monitor the internal templates, UI scripts, and engine logic, automatically rebuilding the site when you edit source files.* ::: ## Testing Your Changes Before submitting a Pull Request, you **must** ensure your changes haven't broken the core engine. `docmd` includes a brutal integration testing suite that verifies HTML generation, path resolutions, and SPA configurations. To run the test suite: ```bash pnpm test ``` If the test passes and outputs `✨ ALL SYSTEMS GO`, your code is safe to commit! ## Pull Request Guidelines 1. **Create a Branch:** Always branch off of `main` for your work (e.g., `feat/new-search-ui` or `fix/broken-link`). 2. **Write Clean Code:** Follow the existing coding style. If you are creating a new file in the `packages/` directory, ensure it includes the standard docmd copyright header at the top. 3. **Commit Messages:** We prefer [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) (e.g., `feat: add new button container` or `fix: resolve sidebar scroll issue`). 4. **Open a PR:** Push your branch to your fork and open a Pull Request against our `main` branch. Provide a clear summary of your changes and reference any related issues. ### Copyright Header All source files in `packages/` must include the standard copyright header. If you create a new file, please copy the header from an existing file. ```html /*! * -------------------------------------------------------------------- * docmd : the minimalist, zero-config documentation generator. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @license MIT * @copyright Copyright (c) 2025 docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` ## Code of Conduct Please note that this project operates with a standard Contributor Code of Conduct. By participating in this project you agree to abide by its terms, ensuring a welcoming and respectful environment for everyone. --- ## [Deployment (Deploy Your Website)](https://docs.docmd.io/04/deployment/) --- title: "Deployment (Deploy Your Website)" description: "Learn how to deploy your docmd-generated static site to modern hosting platforms like GitHub Pages, Vercel, and Netlify." --- Because `docmd` generates a pure, standard static site, you can host your documentation literally anywhere that serves HTML files. When you run the build command, `docmd` processes all your Markdown and places the final, production-ready website into your output directory (default: `site/`). ```bash docmd build ``` The contents of this `site/` folder are all you need. Below are guides for deploying to the most popular modern hosting platforms. ::: tabs == tab "GitHub Pages" The most reliable and automated way to deploy to GitHub Pages is using a **GitHub Actions** workflow. This ensures your site rebuilds automatically every time you push changes to your repository. **1. Create the Workflow File** Create a file in your repository at `.github/workflows/deploy-docs.yml` and add the following content: ```yaml name: Deploy docmd to GitHub Pages on: push: branches: ["main"] # Change this if your default branch is 'master' workflow_dispatch: # Allows manual triggers permissions: contents: read pages: write id-token: write jobs: build-and-deploy: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: '22' # docmd requires Node 18+ cache: 'npm' - name: Install docmd run: npm install -g @docmd/core - name: Build site run: docmd build - name: Setup Pages uses: actions/configure-pages@v5 - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: path: ./site # Your configured outputDir - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ``` **2. Configure Repository Settings** Go to your repository settings on GitHub. Navigate to **Pages**, and under "Build and deployment", change the Source to **GitHub Actions**. The next time you push to your `main` branch, your docs will automatically build and publish! == tab "Vercel" Vercel is an excellent platform for hosting static sites with zero configuration. 1. Push your `docmd` project to a Git repository (GitHub, GitLab, Bitbucket). 2. Log in to Vercel and click **Add New > Project**. 3. Import your repository. 4. Vercel usually detects Node.js projects automatically, but ensure the following settings are applied: * **Framework Preset:** `Other` * **Build Command:** `npm install -g @docmd/core && docmd build` * **Output Directory:** `site` 5. Click **Deploy**. == tab "Netlify" Netlify provides a seamless deployment experience for static site generators. 1. Push your `docmd` project to a Git repository. 2. Log in to Netlify and click **Add new site > Import an existing project**. 3. Connect your Git provider and select your repository. 4. Configure the build settings: * **Base directory:** *(Leave empty unless your docs are in a subfolder)* * **Build command:** `npm install -g @docmd/core && docmd build` * **Publish directory:** `site` 5. Click **Deploy site**. == tab "Traditional Web Server" If you are hosting your documentation on a traditional web server (like Apache, Nginx, or an AWS S3 bucket), deployment is as simple as moving files. 1. Run `docmd build` locally or in your CI/CD pipeline. 2. Copy the entire contents of the generated `site/` folder to your web server's public directory (e.g., `/var/www/html/docs`). ::: callout tip SPA Routing `docmd`'s Single Page Application (SPA) router is built to gracefully degrade. You **do not** need to configure complex URL rewrite rules on your server (like you would for React or Vue apps). If a user accesses a URL directly, the static HTML file is served by the server, and the SPA takes over from there. ::: ::: ## Path Configuration (Subdirectories) If you are not hosting your documentation at the root of a domain (e.g., you are hosting it at `https://mycompany.com/docs/` instead of `https://docs.mycompany.com/`), you must ensure your `docmd.config.js` reflects this so assets and relative links resolve correctly. While `docmd` uses highly resilient relative pathing out of the box, always ensure your `siteUrl` is set accurately in your config if you are using plugins like `sitemap` or `seo` that require absolute URLs. --- ## [Basic Usage](https://docs.docmd.io/04/getting-started/basic-usage/) --- title: "Basic Usage" description: "A quick-start guide to initialising a project, writing content, and building your site." --- Once you have `docmd` installed, creating a beautiful documentation site takes only a few minutes. This guide walks you through the standard workflow. ## 1. Initialise the Project Create a new folder for your documentation and navigate into it using your terminal. ```bash mkdir my-docs cd my-docs ``` Run the initialisation command: ```bash docmd init ``` `docmd` will scaffold a ready-to-use project. Your directory will now look like this: ```text my-docs/ ├── assets/ # Place custom images, CSS, and JS here ├── docs/ # Your Markdown files live here │ └── index.md # The homepage of your documentation ├── docmd.config.js # The main configuration file └── package.json # Contains helpful NPM scripts ``` ## 2. Start the Development Server You don't need to build the site blindly. `docmd` includes a blazing-fast development server that updates your browser the moment you save a file. Run the dev command: ```bash docmd dev ``` Open your browser to `http://localhost:3000`. You will see your newly generated documentation site. Keep this server running in your terminal while you work. ## 3. Write Your Content Open the `docs/` folder in your favourite code editor (like VS Code). `docmd` uses standard Markdown. Any `.md` file you create inside the `docs/` folder will automatically be converted into a web page. Try opening `docs/index.md` and changing the `# Welcome` text. When you save the file, your browser will instantly refresh to show the change. ::: callout tip Organising Content You can create subfolders inside `docs/` (e.g., `docs/api/endpoints.md`). `docmd` will automatically mirror this folder structure when generating your website's URLs. ::: ## 4. Configure the Sidebar By default, `docmd` doesn't guess what your navigation should look like. You define it explicitly to maintain perfect control over your users' experience. Open `docmd.config.js` and locate the `navigation` array. You can add new links, create dropdown categories, and assign SVG icons here. ```javascript navigation:[ { title: 'Home', path: '/', icon: 'home' }, { title: 'Guides', icon: 'book', collapsible: true, children:[ { title: 'Quick Start', path: '/quick-start' }, { title: 'Advanced', path: '/advanced' } ] } ] ``` ## 5. Build for Production When you are ready to share your documentation with the world, stop the development server (press `Ctrl + C` in your terminal) and run the build command: ```bash docmd build ``` `docmd` will process all your Markdown, generate an offline search index, minify your assets, and output a highly optimised static website into a new folder called `site/`. You can now upload the contents of that `site/` folder to any web host (GitHub Pages, Netlify, Vercel, or a traditional server). See our [Deployment Guide](/deployment) for specific instructions. --- ## [Installation](https://docs.docmd.io/04/getting-started/installation/) --- title: "Installation" description: "How to install docmd globally or locally using npm, yarn, or pnpm." --- `docmd` is a Node.js package. It requires **Node.js v18.0.0 or higher**. ## Global Installation (Recommended) For most users, installing `docmd` globally provides the best experience. It gives you access to the `docmd` command anywhere in your terminal. ```bash npm install -g @docmd/core ``` **Verification:** Run the following to check if the installation was successful: ```bash docmd --version ``` ## Local Installation If you prefer to keep dependencies scoped to a specific project (useful for CI/CD pipelines or teams), install it as a dev dependency. ```bash # npm npm install -D @docmd/core # pnpm pnpm add -D @docmd/core # yarn yarn add -D @docmd/core ``` **Running commands locally:** When installed locally, you cannot run `docmd` directly. Instead, use your package manager's runner: ```bash npx @docmd/core dev # or pnpm docmd dev ``` ## CDN Installation (Browser Only) ::: callout warning Developer Use Only This method is **not** for building documentation sites. It is for developers who want to embed the `docmd` parsing engine inside another web application (like a CMS or Live Preview tool). ::: If you are building a React/Vue/Vanilla JS app and want to render `docmd` syntax on the fly without a backend, use the browser build: ```html <!-- 1. Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 2. Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` See the [Browser API](/advanced/browser-api) guide for implementation details. ## Setup Troubleshooting ::: callout warning Permission Errors If you see `EACCES` errors on macOS/Linux during global installation, it means you don't have permission to write to global directories. **Fix:** Run `sudo npm install -g @docmd/core`. ::: ::: callout info Windows Powershell If you receive an error about "running scripts is disabled on this system", run this command in PowerShell as Administrator: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [docmd: The Minimalist Docs Generator](https://docs.docmd.io/04/) --- title: "docmd: The Minimalist Docs Generator" description: "Generate beautiful, lightweight, and blazing-fast documentation sites directly from your Markdown files. Zero clutter, just content." --- ```text _ _ _| |___ ___ _____ _| | | . | . | _| | . | |___|___|___|_|_|_|___| ``` **Generate beautiful, lightweight documentation sites directly from your Markdown files. Zero clutter, just content.** `docmd` bridges the gap between simple static site generators and heavy, framework-driven applications. It processes standard Markdown into highly optimised static HTML, while delivering a buttery-smooth Single Page Application (SPA) experience for your users. ::: button "Get Started" /getting-started/installation ::: button "View on GitHub" external:https://github.com/docmd-io/docmd color:#333 ## Quick Start You can have a beautiful documentation site running locally in under a minute. Requires [Node.js](https://nodejs.org/) installed on your machine. ```bash # 1. Install docmd globally npm install -g @docmd/core # 2. Initialise a new project in your current directory docmd init # 3. Start the local development server docmd dev ``` Open `http://localhost:3000` in your browser. Any changes you make to the files in the `docs/` folder will instantly update on your screen. ## Why choose docmd? We believe writing documentation should be as frictionless as possible. You shouldn't need to configure complex JavaScript frameworks just to publish text. <div class="image-gallery" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));"> ::: card Seamless SPA Navigation We generate static HTML for ultimate SEO and fast initial loads, but once the page is open, `docmd` intercepts navigation to swap content instantly without ever reloading the browser. ::: ::: card Zero Configuration Run `docmd init` and start writing. Our sensible defaults mean you don't have to touch a configuration file unless you want to customise your branding or layout. ::: ::: card Smart Offline Search Built-in full-text search with fuzzy matching and keyword highlighting. It runs entirely in the browser using a generated index, meaning it works perfectly even on air-gapped networks. ::: ::: card Isomorphic Engine `docmd` isn't just a CLI. The exact same rendering engine can run natively inside a web browser, allowing you to embed live documentation previews directly into your own web apps. ::: </div> ## Rich Content Out of the Box Write naturally. `docmd` extends standard Markdown with intuitive, nestable components to help you structure complex information beautifully. ::: tabs == tab "Containers" Easily highlight information using Callouts. ::: callout tip Pro Tip You can nest containers inside each other infinitely. Try putting a button inside a card inside a tab! ::: ::: button "Get Started with docmd" /getting-started/installation == tab "Diagrams" Native support for **Mermaid.js**. Just create a code block with the `mermaid` language tag, and it automatically renders and adapts to your user's Light/Dark mode preference. ```mermaid graph TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> E[Fix the issue] E --> B C --> F[Deploy] F --> G[End] ``` == tab "Code" Automatic syntax highlighting powered by `highlight.js`, complete with one-click copy buttons and themes tailored for optimal contrast. ```javascript function hello() { console.log("Hello World"); } ``` ::: Ready to dive in? Check out the [Basic Usage](/getting-started/basic-usage) guide or explore how to [Configure](/configuration/) your site. --- ## [Analytics Integration Plugin](https://docs.docmd.io/04/plugins/analytics/) --- title: "Analytics Integration Plugin" description: "Integrate web analytics services like Google Analytics into your docmd site to track visitor traffic." --- `docmd` allows you to easily integrate popular web analytics services into your documentation site using the built-in analytics plugin. This helps you understand your audience, track page views, and gather insights into how your documentation is being used. ## Enabling Analytics Plugin You enable analytics by adding the analytics plugin and its configuration to the `plugins` object in your config file. **Example:** ```javascript module.exports = { // ... plugins: { // Analytics plugin configuration analytics: { // For Google Analytics 4 (GA4) googleV4: { measurementId: 'G-XXXXXXXXXX' // Your GA4 Measurement ID }, // For Google Universal Analytics (Legacy) // googleUA: { // trackingId: 'UA-XXXXXXXXX-Y' // Your Universal Analytics Tracking ID // } }, // ... other plugins }, // ... }; ``` Choose the analytics service and version you want to use by configuring the appropriate section. ## Available Analytics Options ### Google Analytics 4 (GA4) * **Configuration Key:** `googleV4` * **Description:** Integrates the latest version of Google Analytics, GA4. This is the recommended version for new Google Analytics setups. * **Options:** * `measurementId` (String, Required): Your Google Analytics 4 Measurement ID, which typically looks like `G-XXXXXXXXXX`. * **Action:** Injects the standard Google Analytics 4 `gtag.js` tracking snippet into your pages. ### Google Universal Analytics (Legacy) * **Configuration Key:** `googleUA` * **Description:** Integrates the older version of Google Analytics, known as Universal Analytics (UA). Note that Google has sunset Universal Analytics as of July 2023. * **Options:** * `trackingId` (String, Required): Your Google Universal Analytics Tracking ID, which typically looks like `UA-XXXXXXXXX-Y`. * **Action:** Injects the standard Google Universal Analytics `analytics.js` tracking snippet into your pages. ## Important Considerations * **Choose One Google Analytics Version:** If using Google Analytics, configure *either* `googleUA` *or* `googleV4`, but not both for the same property, to avoid incorrect data collection. * **Privacy and Consent:** * Be mindful of user privacy when implementing analytics. * Clearly disclose your use of analytics (and any cookies set by them) in your site's privacy policy or a cookie consent banner if required by regulations in your target regions (e.g., GDPR, CCPA). * Consider features like IP anonymization if your analytics provider offers them and it's appropriate for your privacy stance. * **Testing:** After enabling the analytics plugin and deploying your site, verify that data is being collected correctly in your analytics provider's dashboard. Use browser developer tools (Network tab) to check if the tracking script is loading. ## Future Analytics Support `docmd` may add support for other privacy-focused or popular analytics providers in the future, such as: * Plausible Analytics * Fathom Analytics * Simple Analytics Check the latest `docmd` documentation or GitHub repository for updates on supported analytics integrations. --- ## [Building Plugins](https://docs.docmd.io/04/plugins/building-plugins/) --- title: "Building Plugins" description: "A guide for developers on how to create and share custom docmd plugins." --- Plugins are the primary way to extend `docmd`. They allow you to hook into the Markdown parser, inject HTML into the layout, and run logic after the build completes. ## Anatomy of a Plugin A plugin is simply a JavaScript object (or a function returning an object) that exports specific hook functions. You can define plugins inline in your `docmd.config.js` or create them as separate NPM packages. ### Available Hooks | Hook | Description | | :--- | :--- | | `markdownSetup(md)` | Access the `markdown-it` instance to add rules or plugins. | | `injectHead(config)` | Return HTML string to inject into `<head>`. | | `injectBody(config)` | Return HTML string to inject at the end of `<body>`. | | `getAssets()` | Return a list of CSS/JS files to copy and inject. | | `onPostBuild(context)` | Run logic after the HTML files are generated (e.g., sitemaps). | ## Creating a Local Plugin You can create a plugin file in your project, for example `my-plugin.js`: ```javascript // my-plugin.js module.exports = { // 1. Extend Markdown markdownSetup: (md) => { // Example: Add a custom container or rule // md.use(require('markdown-it-emoji')); }, // 2. Inject Styles/Scripts injectHead: (config) => { return `<meta name="custom-plugin" content="active">`; }, // 3. Post-Build Action onPostBuild: async ({ config, pages, outputDir, log }) => { log('Plugin: Build finished! Processed ' + pages.length + ' pages.'); } }; ``` To use it, require it in your `docmd.config.js`: ```javascript // docmd.config.js module.exports = { // ... plugins: { './my-plugin.js': {} // Key is path, Value is options object } }; ``` ## Plugin API Reference ### `getAssets()` Used to inject client-side scripts or CSS files. ```javascript getAssets: () => { return [ { src: path.join(__dirname, 'client-script.js'), // Source file dest: 'assets/js/plugin.js', // Destination in site/ type: 'js', // 'js' or 'css' location: 'body' // 'head' or 'body' } ]; } ``` ### `onPostBuild({ config, pages, outputDir, log })` * `config`: The full project configuration object. * `pages`: Array of processed page objects `{ outputPath, frontmatter, htmlContent, searchData }`. * `outputDir`: Absolute path to the build output folder. * `log`: Helper function to print messages to the CLI console. ## Publishing a Plugin To share your plugin with the community: 1. Name your package `docmd-plugin-<name>` (recommended). 2. Export the plugin object as the default export. 3. Publish to NPM. Users can then install it via `npm install docmd-plugin-name` and add it to their config: ```javascript plugins: { 'docmd-plugin-name': { /* options */ } } ``` --- ## [LLM Support (llms.txt) Plugin](https://docs.docmd.io/04/plugins/llms/) --- title: "LLM Support (llms.txt) Plugin" description: "Generate context files for Large Language Models (AI) to better understand your documentation." --- The `llms` plugin generates a standardised `/llms.txt` file at the root of your site. This file is becoming a standard for helping AI agents (like ChatGPT, Claude, or Cursor) discover and read your documentation context efficiently. ## Installation This plugin is included in `@docmd/core` but must be enabled in your config. ## Configuration Add `llms` to your `docmd.config.js`: ```javascript module.exports = { siteUrl: 'https://mysite.com', // REQUIRED plugins: { llms: {} // Enable with default settings } }; ``` ### Options Currently, the plugin uses your existing `siteTitle`, `description`, and page frontmatter to generate the file. ### Excluding Pages To prevent a specific page from appearing in the AI context file, add this to the frontmatter: ```yaml --- title: "Internal Draft" llms: false --- ``` ## Output Example The generated `llms.txt` will look like this: ```md # My Project Documentation > Generated by docmd This is the main description of my project. ## Documentation Files - [Installation](https://mysite.com/install) How to install the CLI. - [Configuration](https://mysite.com/config) Reference for config.js options. ``` --- ## [Mermaid Diagrams Plugin](https://docs.docmd.io/04/plugins/mermaid/) --- title: "Mermaid Diagrams Plugin" description: "Create beautiful diagrams and flowcharts using Mermaid syntax in your docmd documentation." --- Mermaid is a JavaScript-based diagramming and charting tool that uses Markdown-inspired text definitions to create and modify diagrams dynamically. docmd has built-in support for Mermaid diagrams with automatic light/dark theme switching. ::: callout tip All Mermaid diagrams automatically adapt to your site's light/dark theme! ::: ## Flowchart Flowcharts are used to represent workflows or processes. They show the steps as boxes of various kinds, and their order by connecting them with arrows. **Code:** ````markdown ```mermaid graph TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> E[Fix the issue] E --> B C --> F[Deploy] F --> G[End] ``` ```` **Rendered Preview:** ```mermaid graph TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> E[Fix the issue] E --> B C --> F[Deploy] F --> G[End] ``` ## Sequence Diagram Sequence diagrams show how processes operate with one another and in what order. They capture the interaction between objects in the context of a collaboration. **Code:** ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server participant Database User->>Browser: Enter URL Browser->>Server: HTTP Request Server->>Database: Query Data Database-->>Server: Return Results Server-->>Browser: HTTP Response Browser-->>User: Display Page ``` ```` **Rendered Preview:** ```mermaid sequenceDiagram participant User participant Browser participant Server participant Database User->>Browser: Enter URL Browser->>Server: HTTP Request Server->>Database: Query Data Database-->>Server: Return Results Server-->>Browser: HTTP Response Browser-->>User: Display Page ``` ## Pie Chart Pie charts are circular statistical graphics divided into slices to illustrate numerical proportions. **Code:** ````markdown ```mermaid pie title Browser Usage Statistics "Chrome" : 64.5 "Safari" : 18.2 "Firefox" : 8.5 "Edge" : 4.8 "Other" : 4.0 ``` ```` **Rendered Preview:** ```mermaid pie title Browser Usage Statistics "Chrome" : 64.5 "Safari" : 18.2 "Firefox" : 8.5 "Edge" : 4.8 "Other" : 4.0 ``` ## Git Graph Git graphs visualize Git branching and merging operations, making it easier to understand version control workflows. **Code:** ````markdown ```mermaid gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop commit branch feature checkout feature commit checkout main merge feature commit ``` ```` **Rendered Preview:** ```mermaid gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop commit branch feature checkout feature commit checkout main merge feature commit ``` ## XY Chart XY charts display data as a series of points on a coordinate plane, useful for showing correlations and trends. **Code:** ````markdown ```mermaid xychart-beta title "Sales Revenue by Quarter" x-axis [Q1, Q2, Q3, Q4] y-axis "Revenue (in $1000)" 0 --> 100 bar [50, 60, 70, 85] line [45, 55, 75, 80] ``` ```` **Rendered Preview:** ```mermaid xychart-beta title "Sales Revenue by Quarter" x-axis [Q1, Q2, Q3, Q4] y-axis "Revenue (in $1000)" 0 --> 100 bar [50, 60, 70, 85] line [45, 55, 75, 80] ``` ## Best Practices When using Mermaid diagrams in your documentation: 1. **Keep it Simple**: Start with simple diagrams and add complexity only when needed 2. **Use Clear Labels**: Make sure all nodes and connections are clearly labeled 3. **Consider Your Audience**: Adjust the level of detail based on who will read the documentation 4. **Test Both Themes**: Always check how your diagrams look in both light and dark modes 5. **Add Context**: Use callouts or text around diagrams to explain what they represent ::: callout info Visit the [Official Mermaid Documentation](https://mermaid.js.org/) for more types of Mermaid Diagrams and, detailed syntax and options. ::: --- ## [Search Plugin](https://docs.docmd.io/04/plugins/search/) --- title: "Search Plugin" description: "Configure the offline-capable, full-text search engine." --- `docmd` includes a privacy-focused, offline-capable search engine powered by `MiniSearch`. It indexes your content at build time, meaning no external services (like Algolia) are required. ## Configuration The search plugin is enabled by default. You can configure it via the `optionsMenu` in the layout config, or the `plugins` object. ### Enabling/Disabling To toggle the search button in the UI: ```javascript // docmd.config.js module.exports = { layout: { optionsMenu: { components: { search: true, // Set to false to hide the search icon } } } } ``` ### Excluding Pages To prevent specific pages (like drafts or utility pages) from appearing in search results, add `noindex: true` to the frontmatter: ```yaml --- title: "Private Draft" noindex: true --- ``` ## How it Works 1. **Build Time:** The plugin scans all generated HTML, strips tags, and extracts headings/text into `site/search-index.json`. 2. **Runtime:** When a user opens your site, the lightweight index is loaded. 3. **Privacy:** All search logic happens locally in the user's browser. No keystrokes are sent to any server. ## Keyboard Shortcuts * `Cmd + K` (Mac) or `Ctrl + K` (Windows): Open Search * `Arrow Up/Down`: Navigate results * `Enter`: Select result * `Esc`: Close modal ## Comparison vs. Algolia Many documentation generators (like Docusaurus) rely on **Algolia DocSearch**. While Algolia is powerful, it introduces friction: | Feature | docmd Search | Algolia / External | | :--- | :--- | :--- | | **Setup** | **Zero Config** (Automatic) | Complex (API Keys, CI/CD crawling) | | **Privacy** | **100% Private** (Client-side) | Data sent to 3rd party servers | | **Offline** | **Yes** | No | | **Cost** | **Free** | Free tier limits or Paid | | **Speed** | **Instant** (In-memory) | Fast (Network latency dependent) | `docmd` creates a frictionless experience: you write the markdown, we handle the discovery. --- ## [SEO & Meta Tags Plugin](https://docs.docmd.io/04/plugins/seo/) --- title: "SEO & Meta Tags Plugin" description: "Configure Search Engine Optimisation (SEO) meta tags to improve your docmd site's discoverability." --- The `seo` plugin automatically generates important meta tags in the `<head>` of your HTML pages. This helps search engines and social media platforms understand, index, and display your content more effectively. ## Enabling the Plugin Add the `seo` plugin to the `plugins` object in your config file: ```javascript module.exports = { // ... plugins: { seo: { defaultDescription: 'Discover insightful articles and guides on Project X. Your go-to resource for learning and development.', openGraph: { // siteName: 'Project X Documentation', // Optional, defaults to config.siteTitle defaultImage: '/assets/images/default-og-image.png', // Absolute path from site root }, twitter: { cardType: 'summary_large_image', // e.g., 'summary', 'summary_large_image' // siteUsername: '@ProjectX_Docs', // Your site's Twitter handle // creatorUsername: '@YourHandle' // Default author handle (override in frontmatter) } }, // ... other plugins }, // ... }; ``` ## Configuration Options The options in the config file serve as site-wide defaults. For the best results, you should provide specific metadata for each page using frontmatter. ## Frontmatter for SEO To control SEO on a per-page basis, add a nested `seo` object to your page's frontmatter. This keeps all SEO-related settings organised and prevents conflicts with other frontmatter keys. ```yaml --- title: "Advanced Widget Configuration" description: "A detailed guide on configuring advanced settings for the Super Widget." seo: description: "A more specific SEO description for search engines, overriding the main description if needed." image: "/assets/images/widgets/super-widget-social.jpg" ogType: "article" twitterCard: "summary_large_image" twitterCreator: "@widgetMaster" keywords: ["widget", "configuration", "advanced", "performance"] permalink: "https://example.com/docs/widgets/advanced-configuration" noindex: false --- ``` ::: callout info Backward Compatibility For backward compatibility, the plugin will still recognise top-level SEO fields like `image`, `ogType`, etc. However, the nested `seo:` structure is the recommended approach. ::: ### Supported Frontmatter Fields All fields should be placed inside the `seo:` object. * `description` (String): Overrides the main page description for SEO meta tags. * `image` or `ogImage` (String): Path to an image for `og:image` and `twitter:image`. * `ogType` (String): Overrides the default Open Graph type (e.g., `article`, `website`). * `twitterCard` (String): Overrides the default Twitter card type for this page. * `twitterCreator` (String): The Twitter @username of the page's author. * `keywords` (Array of Strings or String): Keywords for the `<meta name="keywords">` tag. * `permalink` or `canonicalUrl` (String): The canonical URL for the page. * `noindex` (Boolean): If `true`, adds `<meta name="robots" content="noindex">` to discourage search engines from indexing this page. ## Structured Data (LD+JSON) The SEO plugin can generate [Structured Data](https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data) (LD+JSON), which can enable rich search results. This feature is enabled per-page in your frontmatter. ### Enabling Structured Data To generate a default LD+JSON block, add `ldJson: true` inside your `seo` frontmatter object. ```yaml --- title: "My Article" description: "An article about something important." seo: ldJson: true --- ``` This generates a basic `Article` schema using your page's metadata. ### Customising Structured Data For more control, provide an object to `ldJson`. This object will be merged with the default data, allowing you to add or override any properties. **Example: Customising schema type and adding an author** ```yaml --- title: "Advanced Widget Configuration" description: "A detailed guide on configuring advanced settings for the Super Widget." seo: image: "/assets/images/widgets/super-widget-social.jpg" ldJson: "@type": "TechArticle" author: "@type": "Person" name: "Jane Doe" url: "https://example.com/authors/jane-doe" datePublished: "2024-01-15" review: "@type": "Review" reviewRating: "@type": "Rating" ratingValue: "5" bestRating: "5" author: "@type": "Person" name: "John Smith" --- ``` In this example, the schema type is changed to `TechArticle`, and detailed `author`, `datePublished`, and `review` information is added, giving search engines a much richer understanding of your content. --- ## [Sitemap Plugin](https://docs.docmd.io/04/plugins/sitemap/) --- title: "Sitemap Plugin" description: "Automatically generate a sitemap.xml for your docmd site to improve search engine discoverability." --- The `sitemap` plugin automatically generates a `sitemap.xml` file for your documentation site. This helps search engines discover, crawl, and index your content more effectively, which can improve your site's visibility in search results. ## Enabling the Plugin Add the `sitemap` plugin to the `plugins` object in your config file: ```javascript module.exports = { // ... plugins: { sitemap: { defaultChangefreq: 'weekly', defaultPriority: 0.8 }, // ... other plugins }, // ... }; ``` ## Configuration Options All options for the `sitemap` plugin are optional. If an option is not provided, the plugin will use sensible defaults. * `defaultChangefreq` (String): * Specifies how frequently the content is likely to change * Possible values: `'always'`, `'hourly'`, `'daily'`, `'weekly'`, `'monthly'`, `'yearly'`, `'never'` * Default: `'weekly'` * `defaultPriority` (Number): * Indicates the relative importance of a page in your site * Value between 0.0 and 1.0 * Default: `0.8` ## How It Works The sitemap plugin automatically: 1. Scans all generated HTML pages during the build process 2. Creates a `sitemap.xml` file in the root of your site output directory 3. Includes all pages with their URLs, last modification dates, and configured priorities The plugin uses your `siteUrl` property from the config file to create absolute URLs, which is required for a valid sitemap. Make sure you have a `siteUrl` defined: ```javascript module.exports = { siteUrl: 'https://yourdomain.com', // No trailing slash // ... other config }; ``` ## Overriding Per-Page Settings with Frontmatter You can override the default sitemap settings for individual pages by adding specific frontmatter properties: ```yaml --- title: "Important Page" description: "This is a very important page that changes frequently" sitemap: changefreq: 'daily' priority: 1.0 --- ``` ## Excluding Pages from the Sitemap If you want to exclude specific pages from the sitemap, you can add the following to your frontmatter: ```yaml --- title: "Private Page" description: "This page should not appear in search engines" sitemap: false --- ``` ## Verifying Your Sitemap After building your site, check the generated sitemap at `your-site/sitemap.xml`. You can also submit the sitemap URL to search engines like Google Search Console or Bing Webmaster Tools to help them discover and index your content more efficiently. --- ## [Extending docmd with Plugins](https://docs.docmd.io/04/plugins/usage/) --- title: "Extending docmd with Plugins" description: "Extend docmd's functionality with built-in integrations." --- Plugins allow you to add complex features to your documentation site - like analytics tracking or AI context generation - without bloating the core engine. All core plugins are bundled with `@docmd/core`. You simply enable them in your `docmd.config.js` file. ## Configuration Plugins are configured inside the `plugins` object. An empty object `{}` usually enables the plugin with its default settings. To disable a plugin, either remove it or set it to `false`. ```javascript module.exports = { // ... plugins: { // Generates Meta Tags and Open Graph data seo: { defaultDescription: 'My documentation site', openGraph: { defaultImage: '/assets/og-image.png' } }, // Injects Google Analytics analytics: { googleV4: { measurementId: 'G-XXXXXXXXXX' } }, // Generates sitemap.xml sitemap: { defaultChangefreq: 'weekly' }, // Enables Mermaid.js diagrams mermaid: {}, // Offline search (Can also be toggled in layout.optionsMenu) search: {}, // Generates an llms.txt file for AI agents llms: {} } }; ``` ## How Plugins Work Plugins in `docmd` hook into various parts of the build process: * They can add meta tags and scripts to the page head * They can inject content or scripts at the beginning or end of the page body * They can generate additional files in the output directory * They can modify the HTML output of pages All plugins are designed to be configurable through your config file, giving you control over their behaviour. Explore the sidebar to see the specific configuration options available for each plugin. --- ## [Recipe: Adding Custom Fonts](https://docs.docmd.io/04/recipes/custom-fonts/) --- title: "Recipe: Adding Custom Fonts" description: "Personalize your documentation by importing Google Fonts." --- `docmd` uses CSS variables to manage typography. Changing your site's font is as easy as creating a custom stylesheet. ## 1. Create a CSS File Create a file in your project (e.g., `assets/css/fonts.css`). Go to [Google Fonts](https://fonts.google.com), find the font you want (like *Inter* or *Fira Code*), and use the `@import` method. Then, assign that font to the docmd root variables. ```css /* assets/css/fonts.css */ /* Import the fonts */ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fira+Code&display=swap'); :root { /* Override the default sans-serif font */ --font-family-sans: "Inter", -apple-system, BlinkMacSystemFont, sans-serif; /* Override the monospace (code block) font */ --font-family-mono: "Fira Code", monospace; } ``` ## 2. Register the Stylesheet Open your `docmd.config.js` and add the path to your new CSS file in the `theme.customCss` array. ```javascript module.exports = { // ... theme: { name: 'sky', defaultMode: 'light', customCss:[ '/assets/css/fonts.css' // Path is relative to the generated site/ root ] } } ``` Restart your `docmd dev` server. Your entire site will now use your custom typography! --- ## [Recipe: Adding a Custom Favicon](https://docs.docmd.io/04/recipes/favicon/) --- title: "Recipe: Adding a Custom Favicon" description: "How to add a custom favicon to your documentation site." --- A favicon is the small icon that appears in the browser tab next to your page title. `docmd` makes it easy to add your own. ## 1. Prepare your image You can use `.ico`, `.png`, or `.svg` files. For the best compatibility, an `.ico` file is recommended. ## 2. Add to Assets Place your image file in your project's assets directory. ```bash # Example structure my-project/ ├── assets/ │ └── my-icon.ico <-- Your file here ├── docs/ └── docmd.config.js ``` ## 3. Update Configuration Open `docmd.config.js` and update the `favicon` property with the path relative to the output root. ```javascript module.exports = { // ... // Points to site/assets/my-icon.ico favicon: '/assets/my-icon.ico', // ... }; ``` ## 4. Build Run `docmd build` (or `docmd dev`). `docmd` will automatically copy your asset file to the site build and link it in the `<head>` of every page. --- ## [Recipe: Creating a Landing Page](https://docs.docmd.io/04/recipes/landing-page/) --- title: "Recipe: Creating a Landing Page" description: "How to build a custom landing page using noStyle." --- Sometimes you want your `index.html` (the home page) to look completely different from your documentation - like a product marketing page. `docmd` makes this easy with **No-Style Pages**. ## The Concept By adding `noStyle: true` to your frontmatter, `docmd` strips away the sidebar, header, and default CSS, giving you a blank canvas while still keeping helpful meta tags. ## Implementation Create or edit `docs/index.md`: ```html --- title: "My Product" description: " The best product ever." noStyle: true components: meta: true # Keep SEO tags favicon: true # Keep favicon scripts: false # Disable default docmd scripts customHead: | <style> body { font-family: sans-serif; margin: 0; } .hero { background: #111; color: #fff; padding: 100px 20px; text-align: centre; } .btn { background: #3b82f6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; } </style> --- <div class="hero"> <h1>Welcome to My Product</h1> <p>The ultimate solution for X, Y, and Z.</p> <br> <a href="/getting-started/" class="btn">Read the Docs →</a> </div> <div class="features"> <!-- Your custom HTML features grid here --> </div> ``` This page will be built as `index.html` but will look exactly like your custom HTML, serving as a perfect entry point to your documentation. --- ## [Recipe: Documentation Writing Guide](https://docs.docmd.io/04/recipes/writing-guide/) --- title: "Recipe: Documentation Writing Guide" description: "Best practices for writing clear, scannable, and effective documentation with docmd." --- Great documentation isn't just about correct information; it's about how that information is structured. This guide covers the best practices for using `docmd` features to help your readers. ## Scannability is Everything Users rarely read documentation line-by-line. They scan for answers. * **Use Descriptive Headings:** Instead of "Setup," use "Installing the CLI via NPM." * **Keep Paragraphs Short:** Break up large walls of text into 2-3 sentence chunks. * **Use Bold Text:** Highlight key terms, file paths, or commands so they pop while scanning. ## Choosing the Right Container `docmd` provides several containers. Using them correctly improves the user's mental model. ### Callouts vs. Cards * **Use Callouts** for "interruptions." Use `tip` for helpful shortcuts, `warning` for things that might break, and `danger` for critical errors. * **Use Cards** for "grouping." Cards are great for feature lists on a homepage or summarizing a large section. ### Steps for Tutorials Whenever you have more than two actions the user must perform in order, use the `::: steps` container. It provides a visual timeline that feels much more encouraging than a plain numbered list. ## Linking Best Practices Since `docmd` generates a Single Page Application, navigating between pages is instant. * **Use Relative Paths:** Always link using `./file.md` or `../folder/file.md`. This ensures your links work in your code editor (VS Code), on your web server, and even in offline mode. * **Self-Describing Links:** Avoid "Click here." Instead, use "[Read the Installation Guide](/getting-started/installation)." ## Organising Code Blocks * **Specify Languages:** Always add the language tag (e.g., ` ```javascript `) to enable syntax highlighting. * **Copy Buttons:** Remember that `docmd` automatically adds a copy button to every code block, so you don't need to ask users to "copy and paste" manually. --- ## [Assets Management](https://docs.docmd.io/04/theming/assets-management/) --- title: "Assets Management" description: "Learn how to manage and customise your assets (CSS, JavaScript, images) in your docmd site." --- Managing your custom assets (CSS, JavaScript, images) is an important part of customising your documentation site. `docmd` provides flexible ways to include and manage these assets. ## Project Structure When you initialise a new project with `docmd init`, it creates the following structure: ``` your-project/ ├── assets/ # User assets directory │ ├── css/ # Custom CSS files │ ├── js/ # Custom JavaScript files │ └── images/ # Custom images ├── docs/ # Markdown content ├── docmd.config.js └── ... ``` This structure makes it easy to organise and manage your custom assets. ## How Assets Are Handled There are two main ways to manage assets in your docmd site: ### 1. Root-Level Assets Directory (Recommended) The simplest and recommended approach is to use the `assets/` directory in your project root: **How it works:** - During the build process, docmd automatically copies everything from your root `assets/` directory to the output `site/assets/` directory - Your custom assets take precedence over docmd's built-in assets with the same name - This approach is ideal for GitHub Pages deployments and other hosting scenarios **Example workflow:** 1. Create or modify files in your project's `assets/` directory: ``` assets/css/custom-styles.css assets/js/interactive-features.js assets/images/logo.png ``` 2. Reference these files in your config file: ```javascript module.exports = { // ... theme: { // ... customCss: [ '/assets/css/custom-styles.css', ], }, customJs: [ '/assets/js/interactive-features.js', ], // ... }; ``` 3. Use images in your Markdown content: ```markdown ![Logo](/assets/images/logo.png) ``` 4. Build your site: ```bash docmd build ``` ### 2. Customising Default Assets If you want to modify docmd's default assets: 1. First, build your site normally to generate all assets: ```bash docmd build ``` 2. Modify the generated files in the `site/assets` directory as needed. 3. When rebuilding, use the `--preserve` flag to keep your customised files: ```bash docmd build --preserve ``` 4. If you want to update to the latest docmd assets (for example, after updating the package), run without the preserve flag: ```bash docmd build ``` This approach allows you to: - Get the latest assets by default when you update the package - Preserve your customizations when needed with `--preserve` - See which files are being preserved during the build process The preservation behaviour works with both `build` and `dev` commands: ```bash # Preserve custom assets during development docmd dev --preserve ``` ## Asset Precedence When multiple assets with the same name exist, docmd follows this precedence order: 1. **User assets** from the root `assets/` directory (highest priority) 2. **Preserved assets** from previous builds (if `--preserve` is enabled, which is the default) 3. **Built-in assets** from the docmd package (lowest priority) This ensures your custom assets always take precedence over default ones. ## GitHub Pages Deployment When deploying to GitHub Pages, your assets structure is preserved. If you're using a custom domain or GitHub Pages URL, make sure your asset paths are correctly configured. For more information on deployment, see the [Deployment](/deployment/) documentation. ## Related Topics - [Custom CSS & JS](/theming/custom-css-js/) - Learn how to configure custom CSS and JavaScript - [Theming](/theming/) - Explore other theming options for your documentation site --- ## [Available Themes](https://docs.docmd.io/04/theming/available-themes/) --- title: "Available Themes" description: "An overview of the built-in themes provided by docmd." --- `docmd` allows you to choose from a selection of built-in themes to quickly change the overall look and feel of your documentation site. You can specify the theme in your config file using the `theme.name` property. ```javascript module.exports = { // ... theme: { name: 'theme-name', // Options: 'default', 'sky', 'ruby', 'retro' defaultMode: 'light', // or 'dark' to set as landing mode // ... }, // ... }; ``` ## Try the Themes Click a button below to instantly switch the theme of this website: <div class="theme-picker" style="display: flex; gap: 10px; margin: 20px 0;"> <button onclick="switchDocTheme('default')" class="docmd-button" style="color:#fff;background: #4f4f4f;">Default</button> <button onclick="switchDocTheme('sky')" class="docmd-button" style="color:#fff;background: #0097ff;">Sky</button> <button onclick="switchDocTheme('ruby')" class="docmd-button" style="color:#fff;background: #b30000;">Ruby</button> <button onclick="switchDocTheme('retro')" class="docmd-button" style="color:#fff;background: #0a0a0a; border: 1px solid #0f0;">Retro</button> </div> ## 1. `default` Theme * **`theme.name: 'default'`** * **Description:** The foundation of all docmd themes. This is not a separate theme but the base styling that's always included regardless of which theme you select. It provides: * Basic layout structure with sidebar and content area * Essential typography and spacing * Core styling for documentation elements like code blocks, tables, and custom containers * Light and dark mode foundation * **When to use:** When you want a minimalist, clean interface without additional styling layers. This is the most lightweight option. ## 2. `sky` Theme * **`theme.name: 'sky'`** (This is the default if `theme.name` is not specified) * **Description:** A modern theme inspired by popular documentation platforms, with a fresh and airy design. It features: * A clean, minimalist interface with subtle shadows and rounded corners * Custom typography with improved readability * Refined colour palette for both light and dark modes * Enhanced callout and container styles * Premium documentation feel with careful attention to spacing and contrast * **When to use:** When you want a premium, polished look for your documentation site. ## 3. `ruby` Theme * **`theme.name: 'ruby'`** * **Description:** An elegant, vibrant theme inspired by the precious gemstone. It features: * Rich, jewel-toned colour palette centred around ruby reds and complementary colours * Sophisticated typography with serif headings and sans-serif body text * Distinctive card and callout designs with gem-like faceted styling * Subtle gradients and depth effects that evoke the brilliance of gemstones * Luxurious dark mode with deep, rich backgrounds and vibrant accent colours * **When to use:** When you want your documentation to have a distinctive, premium feel with rich colours and elegant typography. ## 4. `retro` Theme * **`theme.name: 'retro'`** * **Description:** A nostalgic theme inspired by 1980s-90s computing aesthetics. It features: * Terminal-style black backgrounds with phosphor green text in dark mode * Light mode with dark green text on light gray backgrounds * Monospace typography (Fira Code) for authentic retro feel * Neon accent colours (cyan, pink, amber) with glow effects * Animated scanlines and CRT flicker effects * Terminal-style code blocks with `[TERMINAL]` labels * Retro-styled containers with pixel-art inspired elements * Blinking cursor effects on links and active elements * **When to use:** Perfect for developer tools, gaming documentation, tech blogs with vintage computing focus, or anyone wanting a unique, eye-catching retro aesthetic. ## How Themes Work Each theme consists of CSS files located within `docmd`'s internal assets. When you select a theme name, `docmd` links the corresponding stylesheet in your site's HTML: - `default` theme uses the base CSS with no additional theme stylesheet - `sky` theme loads `docmd-theme-sky.css` with its custom styling on top of the default CSS - `ruby` theme loads `docmd-theme-ruby.css` with its custom styling on top of the default CSS - `retro` theme loads `docmd-theme-retro.css` with its custom styling on top of the default CSS You can further customise any chosen theme using the `theme.customCss` option in your config file to add your own overrides or additional styles. See [Custom CSS & JS](/theming/custom-css-js/) for details. --- ## [Custom Styles & Scripts](https://docs.docmd.io/04/theming/custom-css-js/) --- title: "Custom Styles & Scripts" description: "Learn how to add your own custom CSS and JavaScript to your docmd site for advanced customisation." --- While `docmd` themes provide a solid foundation, you can further tailor the appearance and behaviour of your site by injecting custom CSS and JavaScript files. This is configured in your config file. ## Custom CSS You can add one or more custom CSS files using the `theme.customCss` array in your config file. ```javascript module.exports = { // ... theme: { name: 'default', // ... customCss: [ '/assets/css/my-branding.css', // Path relative to your site's root '/css/another-stylesheet.css' ], }, // ... }; ``` **How it works:** * Each string in the `customCss` array should be an absolute path from the root of your generated `site/` directory (e.g., if your file is `site/assets/css/my-branding.css`, the path is `/assets/css/my-branding.css`). * These `<link rel="stylesheet">` tags will be added to the `<head>` of every page *after* the main theme CSS and `highlight.js` CSS. This allows your custom styles to override the default theme styles. > **Note:** For information on how to manage your custom asset files (CSS, JS, images), see the [Assets Management](/theming/assets-management/) documentation. **Use Cases for Custom CSS:** * **Overriding CSS Variables:** The `default` theme uses CSS variables extensively. You can redefine these in your custom CSS. ```css /* my-branding.css */ :root { /* Light mode overrides */ --primary-color: #D65A31; /* Example: Change primary colour */ --font-family-sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; --text-color: #222; } body[data-theme="dark"] { /* Dark mode overrides */ --primary-color: #E87A5A; --bg-color: #121212; --text-color: #ddd; } ``` * **Styling Custom Components:** Add styles for specific elements or components unique to your documentation. * **Fine-tuning Layout:** Make minor adjustments to spacing, sizing, or layout elements. ## Custom JavaScript You can add one or more custom JavaScript files using the top-level `customJs` array in your config file. ```javascript module.exports = { // ... customJs: [ '/assets/js/my-interactive-script.js', // Path relative to your site's root '/js/third-party-integration.js' ], // ... }; ``` **How it works:** * Each string in the `customJs` array should be an absolute path from the root of your generated `site/` directory. * These `<script src="..."></script>` tags will be added just before the closing `</body>` tag on every page. This ensures the DOM is loaded before your scripts run and is generally better for page performance. **Use Cases for Custom JS:** * Adding interactive elements (e.g., custom modals, tabs not provided by `docmd`). * Integrating third-party services or widgets. * Performing custom DOM manipulations after the page loads. * Adding simple analytics or tracking snippets if not using a built-in plugin. By using `customCss` and `customJs`, you have significant flexibility to extend and personalize your `docmd` site beyond the standard theming options. --- ## [Customisation & Variables](https://docs.docmd.io/04/theming/customisation/) --- title: "Customisation & Variables" description: "Master the look of your docs by overriding CSS variables and targeting component classes." --- `docmd` uses a "CSS Variable First" architecture. Instead of writing complex CSS rules, you can change the look of your entire site by redefining a few core variables in your `customCss`. ## Variables Reference ### Core Colours | Variable | Usage | | :--- | :--- | | `--bg-color` | The main page background. | | `--text-color` | Standard paragraph text colour. | | `--text-heading` | Contrast colour for H1, H2, etc. | | `--link-color` | Colour for hyperlinks and active states. | | `--border-color` | Standard divider and border colour. | ### Visual Polish | Variable | Usage | | :--- | :--- | | `--ui-element-size` | Height and width for utility buttons (32px). | | `--ui-radius` | Corner rounding for buttons and cards (6px). | | `--sidebar-width` | Width of the navigation column (260px). | ## CSS Class Reference For advanced styling, you can target these classes in your `customCss`: | Class | Target Element | | :--- | :--- | | `.page-header` | The sticky top bar. | | `.sidebar-nav` | The navigation tree container. | | `.nav-category-label`| Non-clickable menu headers. | | `.main-content` | The wrapper for your Markdown content. | | `.docmd-heading` | Container for H2-H4 (includes permalink anchor). | | `.heading-anchor` | The permalink chain icon. | | `.footer-complete` | The advanced multi-column footer. | ## Plugin Component Styling Plugins inject their own classes for targeting: * **Search:** `.docmd-search-modal`, `.search-result-item`. * **Containers:** `.callout`, `.card`, `.docmd-tabs`, `.steps`. ## Adding Custom CSS 1. Create a file in your project: `assets/css/brand.css`. 2. Add your overrides: ```css :root { --link-color: #ff5733; } ``` 3. Register it in `docmd.config.js`: ```javascript theme: { customCss: ['assets/css/brand.css'] } ``` --- ## [Icons](https://docs.docmd.io/04/theming/icons/) --- title: "Icons" description: "How to use and customise Lucide icons in your documentation." --- `docmd` comes with built-in support for the [Lucide](https://lucide.dev/) icon library. Icons can be used in your navigation sidebar, buttons, and custom components to provide visual cues and improve scannability. ## Navigation Icons Assign an icon to any navigation item in your `docmd.config.js`. Use the kebab-case name of any icon found on the Lucide website. ```javascript navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Setup', path: '/setup', icon: 'settings' } ] ``` ## Button Icons You can also use icons inside your button labels by including the raw HTML or using standard Lucide naming if supported by your theme. ```markdown ::: button "Download" /download icon:download ``` ## CSS Styling All icons are rendered as inline SVGs with the class `.lucide-icon`. You can globally change their size or stroke weight in your `customCss`: ```css .lucide-icon { stroke-width: 1.5px; /* Thinner icons for a modern look */ width: 1.2rem; height: 1.2rem; } /* Target a specific icon */ .icon-rocket { color: #ff5733; } ``` ## Icon Reference We support the entire Lucide library. You can browse the thousands of available icons here: ::: button "Browse Lucide Icons" external:https://lucide.dev/icons --- ## [Light & Dark Mode](https://docs.docmd.io/04/theming/light-dark-mode/) --- title: "Light & Dark Mode" description: "How to configure and manage light and dark themes in your docmd documentation." --- `docmd` provides built-in support for light and dark colour schemes to enhance readability and user experience. Users can choose their preferred viewing mode, which improves accessibility and reduces eye strain in different lighting conditions. ## Setting the Default Theme You can set the default theme for your site in the config file: ```javascript module.exports = { // ... other config ... theme: { name: 'default', // or 'sky', 'ruby', 'retro' defaultMode: 'dark', // Can be 'light' or 'dark' enableModeToggle: true, // Enable the toggle button in the UI positionMode: 'bottom', // 'top' or 'bottom' - where to show the toggle }, // ... }; ``` * `defaultMode: 'light'`: The site will initially render with the light colour scheme. * `defaultMode: 'dark'`: The site will initially render with the dark colour scheme. * `enableModeToggle: true`: Shows a toggle button for users to switch modes. * `positionMode: 'bottom'`: Places the toggle button at the bottom of the sidebar (default). * `positionMode: 'top'`: Places the toggle button in the page header (top right). If `defaultMode` is not specified, it defaults to `'light'`. ## How It Works The theme is controlled by a `data-theme` attribute on the `<body>` tag of your HTML pages: * `<body data-theme="light">` for light mode. * `<body data-theme="dark">` for dark mode. For the `sky` theme, the values would be `sky-light` and `sky-dark`. CSS variables in the theme files define colours, backgrounds, fonts, etc., for both modes: ```css /* Example from main.css */ :root { --bg-color: #ffffff; --text-color: #333333; /* ... other light theme variables ... */ } body[data-theme="dark"] { --bg-color: #1a1a1a; --text-color: #e0e0e0; /* ... other dark theme variables ... */ } body { background-color: var(--bg-color); color: var(--text-color); } ``` ## User Preference Toggle When `enableModeToggle` is set to `true`, a toggle button appears that allows users to switch between light and dark modes. The position of this button is controlled by the `positionMode` setting: ```javascript theme: { defaultMode: 'light', enableModeToggle: true, // Shows the toggle button positionMode: 'bottom', // 'bottom' (sidebar) or 'top' (header) }, ``` ### Toggle Button Positions - **`positionMode: 'bottom'`** (default): The toggle button appears at the bottom of the sidebar - **`positionMode: 'top'`**: The toggle button appears in the page header (top right corner) The toggle button uses Lucide icons (`sun` and `moon`) to indicate the current mode and what will happen when clicked. ### User Preference Persistence When a user selects a theme, their preference is saved in their browser's `localStorage` so it persists across sessions and page loads. The implementation uses the following logic: 1. Check if the user has a saved preference in `localStorage` 2. If not, use the `defaultMode` from the configuration 3. When the user clicks the toggle button, update both the display and the stored preference ## Syntax Highlighting Themes `docmd` also includes separate stylesheets for code block syntax highlighting that are compatible with light and dark modes: * `highlight-light.css` for light mode * `highlight-dark.css` for dark mode The correct syntax highlighting theme is loaded automatically based on the current theme mode. When the user toggles the mode, the appropriate syntax highlighting theme is also switched dynamically. ## Customising Theme Colours You can customise the colours for both light and dark modes by adding custom CSS to your project. See [Custom CSS & JS](/theming/custom-css-js/) for more information. ```css /* Example of overriding theme colours in your custom CSS */ :root { --link-color: #0077cc; /* Custom link colour for light mode */ } body[data-theme="dark"] { --link-color: #4da6ff; /* Custom link colour for dark mode */ } ``` --- ## [Browser API (Client-Side)](https://docs.docmd.io/05/advanced/browser-api/) --- title: "Browser API (Client-Side)" description: "How to use the docmd engine directly in the browser to render documentation dynamically without a server." --- `docmd` features an **isomorphic core**. This means the exact same engine that builds your static site in Node.js can also run entirely inside a web browser. This is powerful for: * Building **CMS Previews** (Type markdown, see result instantly). * Creating **Playgrounds** (Like [CodePen](https://codepen.io) for docs). * Embedding documentation rendering into existing React/Vue/Angular apps. ## Installation via CDN You don't need to install Node.js. You can simply include the scripts and styles from a CDN like `unpkg` or `jsdelivr`. ```html <!-- 1. Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Optional: Theme --> <link rel="stylesheet" href="https://unpkg.com/@docmd/themes/src/docmd-theme-sky.css"> <!-- 2. The Engine Bundle --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ## Usage Once the script loads, it exposes a global `docmd` object. ### `docmd.compile(markdown, config)` Compiles Markdown text into a complete HTML document string. **Parameters:** * `markdown` (String): The raw Markdown content. * `config` (Object): Configuration overrides (same structure as `docmd.config.js`). **Returns:** * `String`: The full HTML string. ### Example: Live Preview Iframe The safest way to render the output is inside an `<iframe>` using the `srcdoc` attribute. This ensures styles don't bleed into your main application. ```html <!DOCTYPE html> <html> <body> <textarea id="editor"># Hello World</textarea> <iframe id="preview" style="width: 100%; height: 500px; border: 1px solid #ccc;"></iframe> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> <script> const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); function update() { const html = docmd.compile(editor.value, { siteTitle: 'My Preview', theme: { name: 'sky', appearance: 'light' }, layout: { spa: false, header: { enabled: false } } }); preview.srcdoc = html; } editor.addEventListener('input', update); update(); </script> </body> </html> ``` ::: callout tip Because `docmd` is isomorphic, an AI agent can build its own documentation "sandbox" directly in the browser during a development session to verify its understanding of your documentation structure without needing to install the CLI. ::: ## Advanced: Raw Content (No-Style) If you only want the HTML content *without* the `docmd` sidebar, header, or footer (for example, to inject into a `div` on your own site), use the `noStyle` frontmatter option in your input. ```javascript const markdown = `--- noStyle: true components: css: true --- # Just Content This will render without the sidebar layout.`; const html = docmd.compile(markdown, { /* config */ }); ``` ## Limitations The Browser API has a few limitations compared to the Node.js CLI: 1. **No File System Access**: It cannot scan folders to auto-generate navigation. You must provide the `navigation` array explicitly in the config object. 2. **Plugins**: Some Node.js-specific plugins (like Sitemap generation) will not run. --- ## [Client-Side Events](https://docs.docmd.io/05/advanced/client-side-events/) --- title: Client-Side Events description: Hook into the docmd SPA router for custom interactive features. --- `docmd` uses a lightweight Single Page Application (SPA) router for instant page transitions. Because the page does not fully reload, standard `DOMContentLoaded` scripts might not trigger on subsequent page navigations. To solve this, `docmd` dispatches a custom event called `docmd:page-mounted` whenever a new page renders. ## The `docmd:page-mounted` Event Listen for this event in your custom JavaScript files to re-initialise libraries or trigger custom logic. ### Usage Create a custom script (e.g., `assets/js/my-plugin.js`) and add it to your `docmd.config.js` under `customJs`. ```javascript document.addEventListener('docmd:page-mounted', (e) => { console.log('New page loaded:', e.detail.url); // Re-initialise your libraries here // Example: MathJax.typeset(); }); ``` ### Event Detail The event object contains a `detail` property with the following data: | Property | Type | Description | | :--- | :--- | :--- | | `url` | `string` | The full URL of the page that just loaded. | | `initial` | `boolean` | `true` if this is the first initial load, `undefined` on navigation. | ::: callout tip When building AI-powered Search or Chat widgets for `docmd`, always bind their initialisation to `docmd:page-mounted`. This ensures the AI features remain active and aware of the current page context as the user navigates. ::: ## Example: Integrating MathJax Standard integration won't work with SPA navigation. Use the event listener: ```javascript // assets/js/math-support.js (function() { function renderMath() { if (window.MathJax) { window.MathJax.typesetPromise(); } } document.addEventListener('DOMContentLoaded', renderMath); document.addEventListener('docmd:page-mounted', renderMath); })(); ``` --- ## [Developer Guide](https://docs.docmd.io/05/advanced/developer-guide/) --- title: "Developer Guide" description: "Advanced debugging, testing, and contribution tools for developers working directly on the docmd monorepo." --- If you are a contributor who has forked the `docmd` monorepo, understanding the internal testing and debugging infrastructure is important. While `contributing.md` outlines how to get the project running, this guide details **how** to safely develop and test your changes inside the monorepo architecture. ## The Universal Failsafe (`failsafe.js`) Before any release, or when verifying major architectural changes, we rely on the Universal Failsafe. ```bash pnpm test ``` *(This triggers `node scripts/failsafe.js`)* ### What does it do? `failsafe.js` is an aggressive integration testing script. Instead of relying on mocked unit tests, it: 1. Creates a raw, temporary OS directory. 2. Installs the local monorepo packages. 3. Scaffolds dummy Markdown files featuring deep nesting, complex containers, and edge cases. 4. Generates both Legacy and Modern `docmd.config.js` schemas. 5. Executes `docmd build` across these configurations and generates explicit HTML assertions. 6. **Plugin Installer Testing**: It simulates `docmd add search` and `docmd remove search` on a raw environment to prove regex configuration injection and scaffold fallback schemas never break. 7. Compiles and executes the Isomorphic `docmd live` editor runtime inside a sandbox Node instance. **Rule of Thumb:** If you modify core parsers, builders, or installers, run `pnpm test`. If it passes, your code is structurally sound for production releases. ## The Playground Workspace (`_playground`) Developing plugins or tweaking the core engine requires a live environment. We provide a dedicated `packages/_playground` directory specifically for this purpose. ```bash pnpm run dev ``` *(This triggers the Dev Server bound solely to the Playground workspace)* Any changes you make to the core engine, the theme packages, or the UI layout templates will instantly hot-reload in the playground's browser tab. ## Testing the CLI (Add / Remove) When working on CLI features like `docmd add` or `docmd remove`, you shouldn't test them globally, nor should you pollute the root `package.json` with arbitrary plugin additions. We provide dedicated root workspace aliases to proxy CLI commands securely into your playground workspace directory: ```bash pnpm run playground:add search pnpm run playground:remove search ``` **Why use this?** - It runs your *local*, uncompiled code directly from `packages/core/bin/docmd.js`. - It executes the filesystem modifications strictly inside the isolated `packages/_playground` directory maintaining its pristine state. - It guarantees you aren't accidentally tracking plugin additions in your root git tree. ## Arbitrary Executions If you ever need to test an arbitrary CLI command exclusively inside your playground context without `cd`'ing in and out, utilize the pnpm filter bridging syntax natively: ```bash pnpm --filter @docmd/playground exec docmd [command] ``` --- ## [Programmatic Node API](https://docs.docmd.io/05/advanced/node-api/) --- title: "Programmatic Node API" description: "Integrate docmd's build engine directly into your custom Node.js scripts and automation pipelines." --- # Programmatic Node API For advanced workflows, you can import and use the `docmd` build engine directly within your own Node.js scripts. This is ideal for custom CI/CD pipelines, automated documentation generation from source code, or wrapping `docmd` in another tool. ## Installation ```bash npm install @docmd/core ``` ## Core Functions ### `build(configPath, options)` The primary build function used by the CLI. ```javascript const { build } = require('@docmd/core'); async function run() { await build('./docmd.config.js', { isDev: false, // Set to true for watch mode logic offline: false, // Set to true to optimise for file:// access zeroConfig: false // Set to true to bypass config file detection }); } ``` ### `buildLive(options)` Generates the browser-based **Live Editor** bundle. ```javascript const { buildLive } = require('@docmd/core'); async function run() { await buildLive({ serve: false, // true starts a local server; false generates static files port: 3000 // Custom port if serve is true }); } ``` ## Example: Custom Build Pipeline You can combine `docmd` with other tools (like `fs-extra`) to create complex build artifacts. ```javascript const { build } = require('@docmd/core'); const fs = require('fs-extra'); async function deployDocs() { try { // 1. Pre-build logic (e.g. generating markdown from code) await generateMarkdownFromJSDoc('./src', './docs/api'); // 2. Run docmd build await build('./docmd.config.js', { offline: true }); // 3. Post-build logic (e.g. moving files to a server folder) await fs.move('./site', '/var/www/html/docs'); console.log('Documentation successfully deployed!'); } catch (err) { console.error('Build Pipeline Failed:', err); } } ``` ::: callout tip The Programmatic API allows AI agents to act as **Documentation Engineers**. An agent can trigger a `docmd build` after modifying content, verify that the `llms-full.txt` was generated correctly, and then handle the deployment - all without human intervention. ::: --- ## [CLI Commands](https://docs.docmd.io/05/cli-commands/) --- title: "CLI Commands" description: "The complete command-line reference for docmd. Create, build, and deploy your documentation with ease." --- The `docmd` CLI is designed to be minimalist and intuitive. It handles everything from your initial project scaffolding to production-ready builds. ## `docmd init` Scaffolds a new documentation project in the current directory. ```bash docmd init ``` **What it does:** * Creates a `docs/` folder with an `index.md`. * Generates a `docmd.config.js` file with recommended defaults. * Sets up a `package.json` with build scripts. * It does not overwrite your existing `docs/` or configuration files. ## `docmd dev` Starts a local development server with **Instant Hot Reloading**. ```bash docmd dev [options] ``` **Options:** * `-z, --zero-config`: **Magic Mode**. If you don't have a config file, `docmd` will automatically detect your project structure and build your site. * `-p, --port <number>`: Specify a manual port (Default: `3000`). * `-c, --config <path>`: Use a non-standard config file path. ## `docmd build` Generates a production-ready static website to the `site/` folder. ```bash docmd build [options] ``` **Options:** * `--offline`: **File Protocol Friendly**. Rewrites all internal links to end in `.html`. This allow you to browse the site directly from a hard drive (e.g. `file:///Users/me/docs/site/index.html`) without a web server. * `-z, --zero-config`: Build for production using the auto-detection engine. * `-c, --config <path>`: Specify the config file to use. ## `docmd migrate` Upgrades an old configuration file to the modern schema. ```bash docmd migrate ``` It re-maps your legacy keys into the new `layout`, `footer`, and `optionsMenu` objects and saves a backup as `docmd.config.legacy.js`. ## `docmd live` Launches the **Isomorphic Live Editor**. ```bash docmd live ``` This starts a browser-based environment where you can write Markdown on the left and see the rendered `docmd` UI on the right in real-time. Use `--build-only` to generate a shareable static version of the editor. ## `docmd stop` Kills all running background development servers. ```bash docmd stop ``` **What it does:** * Scans active processes for docmd dev or docmd live instances. * Gracefully terminates all background servers. * Automatically identifies servers even if they were started on automated, non-standard ports. * Designed to find orphaned processes in complex workspace structures. ::: callout tip The `docmd` CLI provides structured stdout and clear error logging, making it highly compatible with **Agentic Workflows**. If you are using an AI agent (like me) to manage your site, we can easily parse the logs from `docmd dev` to identify and fix path errors or configuration mismatches. ::: --- ## [Comparing Documentation Tools](https://docs.docmd.io/05/comparison/) --- title: "Comparing Documentation Tools" description: "See how docmd stacks up against Docusaurus, MkDocs, Mintlify, and other documentation generators." --- `docmd` was engineered to fill a specific gap: the space between "too simple" (basic Markdown parsers) and "too heavy" (full React/framework applications). ## Feature Matrix | Feature | docmd | Docusaurus | MkDocs | Mintlify | | :--- | :--- | :--- | :--- | :--- | | **Language** | **Node.js** | React.js | Python | Proprietary | | **Navigation** | **Instant SPA** | React SPA | Page Reloads | Hosted SPA | | **Output** | **Static HTML** | React Hydration | Static HTML | Hosted | | **JS Payload** | **Tiny (< 20kb)** | Heavy (> 200kb) | Minimal | Medium | | **Versioning** | **Easy (Config + Auto)** | Complex (FS) | Plugin (Mike) | Native | | **i18n Support** | **In Pipeline** | Native | Theme-based | Beta | | **Search** | **Built-in (Offline)** | Algolia (Cloud) | Built-in (Lunr) | Built-in (Cloud) | | **PWA** | **Built-in (Plugin)** | Plugin | None | Hosted | | **AI Context** | **Built-in (llms.txt)** | Plugin | None | Proprietary | | **Setup** | **Instant (-z)** | ~15 mins | ~10 mins | ~5 mins | | **Cost** | **Free OSS** | Free OSS | Free OSS | Freemium | ## The docmd Advantage ### 1. AI-Centric Architecture Unlike traditional generators, `docmd` understands that humans aren't the only ones reading your docs. With the **LLM Plugin**, your site automatically generates `llms.txt` and `llms-full.txt` files. These provide instantly ingestible context for AI agents (like GitHub Copilot, ChatGPT, or custom RAG pipelines), making your project significantly easier for AI to support. ### 2. Native PWA Logic While other tools require complex Service Worker configurations, `docmd` offers a **one-line PWA plugin**. This turns your documentation into an installable mobile/desktop app with intelligent offline caching and background auto-updates out of the box. ### 3. Balanced Speed (SPA + Static) We generate pure static HTML for perfect SEO and initial load speed. However, once loaded, our lightweight SPA router handles all further navigations. This gives you the speed of a React app with the simplicity and SEO of a static site. ## When to choose something else * **Choose Docusaurus if:** You need highly interactive, custom React components embedded directly inside your Markdown (MDX), or have extreme multi-language requirements. * **Choose MkDocs if:** Your team is strictly Python-based and you want to use the existing Python plugin ecosystem (though you'll miss out on SPA features). --- ## [General Configuration](https://docs.docmd.io/05/configuration/general/) --- title: "General Configuration" description: "Master the docmd.config.js schema. Configure branding, layout architecture, and core engine features." --- The `docmd.config.js` file is the central brain of your documentation. It defines how your content is structured, how it looks, and how both humans and AI interact with it. ## The Configuration File We recommend using the `defineConfig` helper. It provides full IDE autocomplete and type-checking, making it much easier to discover available settings. ```javascript const { defineConfig } = require('@docmd/core'); module.exports = defineConfig({ title: 'My Project', url: 'https://docs.myproject.com', // ... settings }); ``` ## Core Settings (V3 Schema) `docmd` v0.5.0 introduces a streamlined V3 schema. While legacy keys are still supported, we recommend transitioning to these modern labels: | Key | Description | Default | | :--- | :--- | :--- | | `title` | The name of your documentation site. | `Documentation` | | `url` | Production base URL. **Important for SEO and Sitemap.** | `null` | | `src` | Directory containing your Markdown files. | `docs` | | `out` | Directory for the compiled static site. | `site` | | `base` | The base path if hosting in a subfolder (e.g., `/docs/`). | `/` | ## Branding Customise how your brand appears in the header and browser tabs. ```javascript logo: { light: 'assets/logo-dark.png', // Logo for light mode dark: 'assets/logo-light.png', // Logo for dark mode href: '/', // Click destination alt: 'Company Logo' // Accessibility text }, favicon: 'assets/favicon.ico', ``` ## Layout Architecture `docmd` follows a component-based layout system. You can toggle and configure different parts of the UI via the `layout` object. | Section | Key | Default | Description | | :--- | :--- | :--- | :--- | | **Global** | `spa` | `true` | Enables/Disables Single Page Application navigation. | | **Header** | `header` | `{ enabled: true }` | Toggles the top navigation bar. | | **Sidebar**| `sidebar`| `{ enabled: true, collapsible: true }` | Controls the navigation tree behaviour. | | **Footer** | `footer` | `{ style: 'minimal' }` | Supports `'minimal'` or `'complete'` styles. | ### The Options Menu The Options Menu consolidates utility buttons like **Search**, **Theme Switching**, and **Sponsorship links**. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, themeSwitch: true, sponsor: 'https://github.com/sponsors/your-profile' } } } ``` ::: callout info If `optionsMenu.position` is set to `header` or `menubar` but the target container is disabled or null, it automatically falls back to `sidebar-top`. ::: ## Engine Features Fine-tune how `docmd` processes your files. ```javascript minify: true, // Minifies production HTML, CSS, and JS autoTitleFromH1: true, // Automatically use the first # Heading if Frontmatter title is missing copyCode: true, // Adds a 'Copy' button to all code blocks pageNavigation: true, // Adds 'Next' and 'Previous' links at the bottom of pages ``` ## Legacy Support If you are upgrading from an older version of `docmd`, the following keys are automatically mapped to the V3 schema: * `siteTitle` → `title` * `siteUrl` / `baseUrl` → `url` * `srcDir` / `source` → `src` * `outDir` / `outputDir` → `out` ::: callout tip Use `docmd migrate` to automatically upgrade your configuration file to the newest schema while keeping a backup of your old settings. ::: --- ## [Layout & UI Slots](https://docs.docmd.io/05/configuration/layout-slots/) --- title: "Layout & UI Slots" description: "Master the structure of docmd by controlling headers, sidebars, and functional slots." --- A standard `docmd` page is divided into six primary zones: 1. **Menubar**: A full-width top navigation bar. (Added in 0.5.2) 2. **Header**: Secondary bar containing title and utility buttons. 3. **Sidebar**: Left-hand navigation tree. 4. **Content Area**: Primary Markdown rendering zone. 5. **Table of Contents (TOC)**: Right-hand heading navigation. 6. **Footer**: Bottom area for copyright and links. ### Item Properties The menubar is configured within the `layout` section of your `docmd.config.js`. ```javascript module.exports = { layout: { menubar: { enabled: true, position: 'top', // 'top' or 'header' left: [ { type: 'title', text: 'Brand', url: '/', icon: 'home' }, { text: 'Docs', url: '/docs' }, { type: 'dropdown', text: 'Resources', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Changelog', url: '/changelog' } ] } ], right: [ { text: 'Twitter', url: 'https://twitter.com/docmd', icon: 'twitter' } ] } } }; ``` For a deeper explore menubar layouts, see the [Menubar Configuration](./menubar) page. ## The Header Slot The header is enabled by default. Control it site-wide in your config: ```javascript // docmd.config.js layout: { header: { enabled: true // Set to false to hide the entire top bar } } ``` ### Hiding Page Title in Header Hiding the title from the sticky header on specific pages is handled via frontmatter: ```yaml --- title: "Advanced Guide" hideTitle: true --- ``` ## Multi-Functional Options Menu The `optionsMenu` bundles **Search**, **Theme Toggle**, and **Sponsor** buttons. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' (Added in 0.5.2) components: { search: true, themeSwitch: true, sponsor: 'https://github.com/sponsors/yourname' } } } ``` ::: callout info "Automatic Container Fallback" If the chosen position targets a disabled or missing container (e.g., `'header'` when header is disabled), `docmd` will automatically default to rendering the options menu in `sidebar-top`. ::: ## Sidebar & Footer Controls ### Sidebar ```javascript layout: { sidebar: { collapsible: true, // Adds the toggle icon defaultCollapsed: false, // Initial state position: 'left' } } ``` ### Footer `docmd` offers **minimal** and **complete** layouts. ```javascript footer: { style: 'complete', description: 'The ultimate docs tool.', hideBranding: false, // Set true to hide "Built with docmd" columns: [ { title: 'Links', links: [{ text: 'GitHub', url: '...' }] } ] } ``` ::: callout tip "AI-Ready Branding 🤖" When designing custom layouts using slots, always ensure the **Search** component is accessible in your `optionsMenu`. AI agents frequently look for the search bar as their primary interaction anchor when exploring your interface to find relevant technical information. ::: --- ## [Menubar](https://docs.docmd.io/05/configuration/menubar/) --- title: "Menubar" description: "How to structure and position your menubar, add links, drop-down menus and icons." --- The `menubar` is a top-level navigation component that can be placed either at the very top of the page (fixed) or within the main content area (above the page header). ## Configuration The menubar is configured within the `layout` section of your `docmd.config.js`. ```javascript module.exports = { layout: { menubar: { enabled: true, position: 'top', // 'top' or 'header' left: [ { type: 'title', text: 'Brand', url: '/', icon: 'home' }, { text: 'Docs', url: '/docs' }, { type: 'dropdown', text: 'Resources', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Changelog', url: '/changelog' } ] } ], right: [ { text: 'Twitter', url: 'https://twitter.com/docmd', icon: 'twitter' } ] } } }; ``` ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | `false` | Whether to show the menubar. | | `position` | `string` | `'top'` | Positioning: `'top'` (fixed at absolute top) or `'header'` (above page title in main area). | | `left` | `array` | `[]` | Navigation items for the left section. | | `right` | `array` | `[]` | Navigation items for the right section. | ## Item Types Each item in `left` or `right` can have the following properties: ### Standard Link - `text`: The display text. - `url`: The destination URL. - `icon`: (Optional) Lucide icon name. - `external`: (Optional) Whether to open in a new tab. ### Title Set `type: 'title'` to style the item as a brand/logo link. ### Dropdown Set `type: 'dropdown'` and provide an `items` array of links. ## Options Menu Integration You can integrate the search bar and theme toggle into the menubar by setting `optionsMenu.position` to `'menubar'`. ```javascript module.exports = { layout: { optionsMenu: { position: 'menubar' } } }; ``` When positioned in the menubar, the options menu will appear on the **right region** of the menubar. ::: callout info If the `menubar` is disabled or not configured, the options menu automatically falls back to `sidebar-top`. ::: ## Customisation You can customise the menubar's appearance using CSS variables in your `customCss`: ```css :root { --menubar-height: 52px; --menubar-bg: #1a1b1e; --menubar-border: #2c2e33; --menubar-text: #c1c2c5; } ``` --- ## [Navigation Configuration](https://docs.docmd.io/05/configuration/navigation/) --- title: "Navigation Configuration" description: "How to structure your sidebar, categorize links, and assign icons for both humans and AI models." --- `docmd` provides explicit control over your site's structure. By defining your `navigation` in `docmd.config.js`, you create a logical hierarchy that optimises the Single Page Application (SPA) experience and provides a clear context map for AI models. ## The Navigation Array Each object in the array defines a **Link** or a **Category Group**. ```javascript module.exports = { navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Installation', path: '/getting-started/installation', icon: 'download' } ] } ``` ## Available Properties | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **`title`** | `String` | Yes | The display text. Also used as metadata for search and AI. | | **`path`** | `String` | No | Destination URL. Must start with `/` for local markdown. | | **`icon`** | `String` | No | name of a [Lucide Icon](https://lucide.dev/icons) (e.g. `rocket`). | | **`children`** | `Array` | No | Nested items to create a dropdown or group. | | **`collapsible`**| `Boolean` | No | If `true`, the group can be expanded/collapsed. | | **`external`** | `Boolean` | No | If `true`, the link opens in a new tab. | ## Organising Groups You can nest navigation items infinitely. There are two primary ways to organise groups: ### 1. Clickable Group (Folder with Index) If the parent has a `path`, clicking the label navigates to that page and expands the children. ```javascript { title: 'Cloud Setup', path: '/cloud/overview', children: [ { title: 'AWS', path: '/cloud/aws' }, { title: 'GCP', path: '/cloud/gcp' } ] } ``` ### 2. Static Label (Category Wrapper) If you **omit the `path`**, the item becomes a static category header. This is the best way to group related technical sections. ```javascript { title: 'Content & Formatting', icon: 'layout', children: [ { title: 'Syntax Guide', path: '/content/syntax' }, { title: 'Containers', path: '/content/containers' } ] } ``` ## Icons Integration `docmd` comes pre-bundled with the entire **Lucide** icon library. Simply use the icon name in kebab-case. Common examples: `home`, `rocket`, `settings`, `github`, `terminal`, `brain-circuit`. ::: callout tip When defining navigation, use descriptive `title` keys even if the page content starts with a header. Clear navigation titles allow LLMs (using `llms-full.txt`) to understand the relationships between different parts of your project even without reading the full file. ::: --- ## [Redirects & 404](https://docs.docmd.io/05/configuration/redirects/) --- title: "Redirects & 404" description: "Configure instant metadata-based redirects and custom branded 404 error pages for static deployments." --- In a static environment, there is no server-side logic (like `.htaccess` or Nginx rules) to handle routing. `docmd` solves this by generating native HTML failsafes that handle redirection and error states automatically. ## Server-less Redirects You can forward traffic from old URLs to new destinations by defining a mapping in the `redirects` object. ```javascript module.exports = defineConfig({ redirects: { '/setup': '/getting-started/installation', // Redirect /setup to new path '/v1/api': '/api-reference' // Forward legacy API links } }); ``` ### Technical Implementation When you define a redirect, `docmd` creates a directory and an `index.html` at the old path containing a `<meta http-equiv="refresh">` tag. This ensures: 1. **Humans** are redirected instantly after the page loads. 2. **Search Engines** recognise the canonical link to the new content. 3. **Analytics** are preserved across the transition. ## Branded 404 Pages When a user accesses a non-existent URL, most static hosts (Netlify, Vercel, GitHub Pages) look for a `404.html` file in the root. `docmd` automatically generates this file, ensuring that it inherits your theme, sidebar, and Single Page Application (SPA) functionality. ### Customising the Error Content You can customise the 404 messaging in your configuration: ```javascript module.exports = defineConfig({ notFound: { title: '404: Lost in the Docs', content: "We couldn't find the page you're looking for. Use the sidebar to find your way back." } }); ``` ::: callout tip Local development server (`docmd dev`) will automatically serve this custom 404 page whenever a file is missing. ::: --- ## [Versioning](https://docs.docmd.io/05/configuration/versioning/) --- title: "Versioning" description: "Enable multi-version documentation with seamless switching, sticky path preservation, and isolated build directories." --- `docmd` features a native Versioning Engine that allows you to manage and serve multiple versions of your project simultaneously (e.g., `v1.0`, `v2.0`). It automatically handles the URL routing, sidebar updates, and version switching logic. ## Directory Organisation To enable versioning, you must organise your documentation into versioned source folders. The most common pattern is keeping the latest version in `docs` and older versions in folders prefixed with `docs-`. ```text my-project/ ├── docs/ # Version 2 (Main) ├── docs-v1/ # Version 1 (Legacy) ├── docmd.config.js ``` ## Configuration Define your versions in the `versions` object. ```javascript module.exports = defineConfig({ versions: { current: 'v2', // The version ID built to the root (/) position: 'sidebar-top', // Switcher location: 'sidebar-top' or 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Latest)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## Core Features ### 1. Root SEO (The "Current" Version) The version specified in `current` is built directly to your output directory root (e.g., `mysite.com/`). This ensures your primary SEO traffic always lands on your most up-to-date information. ### 2. Isolated Sub-directories Other versions are automatically built into subfolders matching their `id`. * `v2 (Current)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. Sticky Switching (Path Preservation) `docmd` smartly preserves the relative path when a user switches versions. If a user is reading `mysite.com/getting-started` and switches to **v1**, they are automatically taken to `mysite.com/v1/getting-started` instead of being dumped back at the home page. ### 4. Per-Version Assets Each version inherits your global `assets/` folder, but `docmd` ensures they are isolated in the build process, preventing styles from older versions from leaking into newer ones. ## Best Practices 1. **Semantic IDs**: Use short, URL-friendly IDs like `v1`, `v2`, or `beta`. These IDs appear directly in your URLs. 2. **Navigation Parity**: While you can have different navigation for different versions, keeping your folder structure consistent makes "Sticky Switching" much more effective for your users. 3. **One Config to Rule Them All**: You do not need separate configuration files for each version. `docmd` iterates through your `versions.all` array during a single `docmd build` command. --- ## [Buttons](https://docs.docmd.io/05/content/containers/buttons/) --- title: "Buttons" description: "Inject call-to-action buttons for internal routing or external resources. No closing tag required." --- Buttons are used to create prominent links. Unlike most `docmd` containers, the `button` is **self-closing**. You define it on a single line and do not use a closing `:::` tag. ## Syntax ```markdown ::: button "Label" Path [Option] ``` ### Options | Property | Value | Description | | :--- | :--- | :--- | | **Path** | `/path` | Relative URL to a page in your docs. | | **Path** | `external:URL` | Opens the link in a new tab with `target="_blank"`. | | **Colour** | `color:#hex` | Custom background colour (e.g. `color:#4f46e5`). | ## Examples ### 1. Internal Link Use relative paths to link between pages. ```markdown ::: button "Back to Installation" /getting-started/installation ``` ::: button "Back to Installation" /getting-started/installation ### 2. External Link Prepend `external:` to ensure the link opens in a new tab. ```markdown ::: button "View on GitHub" external:https://github.com/docmd-io/docmd ``` ::: button "View on GitHub" external:https://github.com/docmd-io/docmd ### 3. Styled Branding You can use standard CSS colours or Hex codes to match your brand. ```markdown ::: button "Critical Action" /delete-account color:red ::: button "Success" /confirm color:#228B22 ``` ::: button "Critical Action" ./#delete-account color:crimson ::: button "Success" ./#confirm color:#228B22 ## Troubleshooting: Accidental Over-closing Because buttons are self-closing, adding a second `:::` line will actually **close the parent container** (like a Card or a Tab) that the button is sitting inside. **Incorrect (Will break layout):** ```markdown ::: card ::: button "Click" /path ::: ::: ``` **Correct:** ```markdown ::: card ::: button "Click" /path ::: ``` --- ## [Callouts](https://docs.docmd.io/05/content/containers/callouts/) --- title: "Callouts" description: "Highlight critical information using semantic blocks. Supports Tip, Warning, Danger, and Info types." --- Callouts are used to highlight information that requires the user's immediate attention. `docmd` provides five semantic types, each with its own visual styling and icon. ## Syntax ```markdown ::: callout type "Optional Title" Your content here. ::: ``` | Type | Default Title | Best Used For | | :--- | :--- | :--- | | `info` | Info | General help or background context. | | `tip` | Tip | Best practices, shortcuts, or "Pro-tips". | | `warning` | Warning | Actions that might cause minor issues if ignored. | | `danger` | Danger | Critical warnings, data loss, or significant errors. | | `success` | Success | Confirmation of a completed action. | ## Examples ### 1. Simple Note ```markdown ::: callout info This is a standard informational note. ::: ``` ::: callout info This is a standard informational note. ::: ### 2. Custom Title ```markdown ::: callout warning "Action Required" Please back up your configuration before proceeding with the upgrade. ::: ``` ::: callout warning "Action Required" Please back up your configuration before proceeding with the upgrade. ::: ### 3. Rich Content (Nesting) Callouts can contain any Markdown content, including code blocks and buttons. ````markdown ::: callout tip "Try this Shortcut" Use the CLI to instantly verify your build: ```bash docmd dev --preserve ``` ::: button "Learn More" /cli-commands ::: ```` ::: callout tip "Try this Shortcut" Use the CLI to instantly verify your build: ```bash docmd dev --preserve ``` ::: button "Learn More" /cli-commands ::: ::: callout tip For LLMs, callouts act as high-priority anchors. Use a `::: callout danger` block to explicitly document breaking changes or "Gotchas" - AI models are specially tuned to prioritise these blocks in their reasoning. ::: --- ## [Cards](https://docs.docmd.io/05/content/containers/cards/) --- title: "Cards" description: "Organise information into framed, visually distinct blocks. Ideal for landing pages and feature grids." --- Cards are the primary structural component in `docmd`. They group related content into a bordered box with optional titles, providing clear visual hierarchy. ## Syntax ```markdown ::: card "Optional Title" This is the card body. ::: ``` ## Examples ### 1. Feature Highlight ```markdown ::: card "Fast Build Times" `docmd` uses an asynchronous processing engine that can build hundreds of pages in under a second. ::: ``` ::: card "Fast Build Times" `docmd` uses an asynchronous processing engine that can build hundreds of pages in under a second. ::: ### 2. Complex Content Cards can contain any other Markdown elements, including code blocks and buttons. ````markdown ::: card "Quick Install" Get the library via your favourite package manager: ```bash npm install @docmd/core ``` ::: button "Installation Guide" /getting-started/installation ::: ```` ::: card "Quick Install" Get the library via your favourite package manager: ```bash npm install @docmd/core ``` ::: button "Installation Guide" /getting-started/installation ::: ## Creating Grids While `docmd` is purely Markdown-driven, you can easily create responsive multi-column layouts using standard HTML wrappers around your cards. ```markdown <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;"> ::: card "Left Column" Content for the left side. ::: ::: card "Right Column" Content for the right side. ::: </div> ``` ::: callout tip Cards act as **Topic Clusters**. When an LLM parses the `llms-full.txt` context, items wrapped in a `card` are treated as a single cohesive unit of information. Use cards to isolate unrelated technical concepts on the same page. ::: --- ## [Changelogs](https://docs.docmd.io/05/content/containers/changelogs/) --- title: "Changelogs" description: "Create beautiful, timeline-based version history pages." --- The `changelog` container formats version history into a clean, vertical timeline. It is specifically designed to parse date/version headers and body content separately. ## Syntax Use `==` to separate entries. The text on the `==` line becomes the timeline badge (left side), and the content below becomes the body (right side). ```markdown ::: changelog == Version 2.0 Description of version 2.0. == Version 1.0 Description of version 1.0. ::: ``` ::: callout tip Maintaining a clean changelog helps AI agents understand the evolution of your project. An AI can quickly scan a `::: changelog` structure to determine which features were added in a specific version, allowing it to provide more accurate context to users asking about "what's new". ::: ## Example ```markdown ::: changelog == v2.0.0 (2026) ### Major Overhaul We rewrote the core engine for better performance. * Added SPA Router * Added Plugin System == v1.5.0 (2025) ### Maintenance Bug fixes and performance improvements. ::: callout info This was the last version to support Node 14. ::: == v1.0.0 (2024) Initial Release. ::: ``` ::: changelog == v2.0.0 (2026) ### Major Overhaul We rewrote the core engine for better performance. * Added SPA Router * Added Plugin System == v1.5.0 (2025) ### Maintenance Bug fixes and performance improvements. ::: callout info This was the last version to support Node 14. ::: == v1.0.0 (2024) Initial Release. ::: --- ## [Collapsible](https://docs.docmd.io/05/content/containers/collapsible/) --- title: "Collapsible" description: "Create toggleable accordion sections for FAQs and advanced details." --- The `collapsible` container creates an accordion-style toggle. It is perfect for FAQs, spoilers, or hiding complex configuration options that aren't relevant to every reader. ## Syntax ```markdown ::: collapsible [open] Title Text Content goes here. ::: ``` * **`open`**: (Optional) If present, the section defaults to expanded. * **`"Title"`**: The text shown on the clickable bar. Defaults to "Click to expand". ::: callout tip Even when collapsed in the UI, the content inside a `collapsible` is fully indexed by the `docmd` search engine and included in the `llms-full.txt` payload. This means AI can answer questions using hidden details while the interface remains clean for humans. ::: ## Examples ### Default (Closed) Useful for FAQs or spoilers. ```markdown ::: collapsible "How do I reset my password?" Go to **Settings > Account** and click "Reset Password". ::: ``` ::: collapsible "How do I reset my password?" Go to **Settings > Account** and click "Reset Password". ::: ### Default (Open) Useful for sections that should be visible but optional to hide. ```markdown ::: collapsible open "Prerequisites" 1. Node.js v18+ 2. A text editor ::: ``` ::: collapsible open "Prerequisites" 1. Node.js v18+ 2. A text editor ::: ### Nested Content ````markdown ::: collapsible "View JSON Response" ```json { "status": "success", "data": { "id": 123 } } ``` ::: ```` ::: collapsible "View JSON Response" ```json { "status": "success", "data": { "id": 123 } } ``` ::: --- ## [Custom Containers](https://docs.docmd.io/05/content/containers/) --- title: "Custom Containers" description: "A directory of the interactive UI components available in docmd. Cards, Tabs, Callouts, and more." --- Standard Markdown handles basic text well, but professional documentation often requires richer structure. `docmd` extends Markdown with a set of "Containers" that render into beautiful, responsive UI components. ## The Syntax Guide All containers follow a consistent block syntax. ```markdown ::: type "Optional Title" This is the content of the container. It can include **Markdown**, images, and even other containers. ::: ``` | Component | Keyword | Usage | | :--- | :--- | :--- | | **[Callouts](./callouts)** | `callout` | Semantic highlights (tips, warnings) | | **[Cards](./cards)** | `card` | Framed content blocks (perfect for grids) | | **[Tabs](./tabs)** | `tabs` | Switchable content panes | | **[Steps](./steps)** | `steps` | Visual numbered timelines | | **[Buttons](./buttons)** | `button` | Styled CTA links | | **[Collapsible](./collapsible)**| `collapsible` | Hidden content toggles (Accordions) | | **[Changelogs](./changelogs)** | `changelog` | Version and update tracking | ## Why Use Containers? Containers aren't just for humans. They provide high-level semantic signals to the `docmd` engine and LLMs: 1. **AI Context**: Highlighting a block as a `callout tip` tells AI models that this specific information is a recommendation. 2. **Layout Control**: Combining `cards` with standard CSS allows you to build complex landing pages entirely in Markdown. 3. **Clean Source**: No HTML or Class-soup is required in your markdown files. ## Nesting Components One of `docmd`'s most powerful features is **Infinite Nesting**. You can place any container inside another, allowing you to build very complex documentation elements purely with simple Markdown syntax. ```markdown ::: card "Pro Guide" ::: callout warning Reading this out of order may be confusing. ::: ::: button "Let's Begin" /start ::: ``` [Read the Nesting Guide →](./nested-containers) --- ## [Nested Containers](https://docs.docmd.io/05/content/containers/nested-containers/) --- title: "Nested Containers" description: "Master docmd's recursive parser. Learn how to combine cards, tabs, and callouts to build complex, interactive page layouts." --- One of `docmd`’s most powerful features is its recursive parsing engine. You can nest components inside each other infinitely to create professional, interactive layouts that would otherwise require complex HTML templates. ## The One Golden Rule While nesting is infinite, remember the **Self-Closing Button Rule**: ::: callout warning Because `::: button` is self-closing, do **not** add a closing `:::` line after it. Doing so will accidentally close the parent container that contains the button. ::: ## Example: Interactive Landing Page Block You can combine a **Card** for the frame, **Tabs** for technical choices, and **Callouts** for highlighting. ````markdown ::: card "Developer Quickstart" Choose your preferred environment to begin: ::: tabs == tab "NPM" ```bash npm install -g @docmd/core ``` ::: callout success Installation usually takes less than 10 seconds. ::: == tab "Manual" Download the binary from GitHub and add it to your PATH. ::: button "GitHub Downloads" external:https://github.com/docmd-io/docmd ::: ::: ```` ## Example: Documenting a Sequential Hack Nesting **Tabs** inside **Steps** is a great way to show multi-platform instructions. ```markdown ::: steps 1. **Select Platform** Choose your operating system below. ::: tabs == tab "macOS" Run the Homebrew command. == tab "Linux" Use the generic install script. ::: 2. **Verify Setup** Check the installation version. ::: ``` ::: steps 1. **Select Platform** Choose your operating system below. ::: tabs == tab "macOS" Run the Homebrew command. == tab "Linux" Use the generic install script. ::: 2. **Verify Setup** Check the installation version. ::: ## Nesting Constraints While the engine is reliable, follow these best practices for the best experience: * **Tabs in Tabs**: Not recommended. It creates "Context Loops" that are difficult for users to navigate on mobile. * **Steps in Tabs**: High syntax conflict. Use standard ordered lists (`1.`) inside tabs instead of the `::: steps` container. * **Indentation**: `docmd` does **not** require indentation for nested blocks, but adding 2 or 4 spaces makes your Markdown much easier for both humans and LLMs to read. * **Performance**: Deep nesting (over 6 levels) is supported but may impact initial build times on extremely large documentation sites. ::: callout tip Nesting helps segment knowledge. When an LLM reads the `llms-full.txt` stream, a nested `callout` inside a `card` tells the model that the tip is specifically scoped to that card's topic, improving the precision of its generation. ::: --- ## [Steps](https://docs.docmd.io/05/content/containers/steps/) --- title: "Steps" description: "Transform standard numbered lists into high-impact visual timelines of instructions." --- The `steps` container is designed specifically for "How-to" guides and tutorials. It takes a standard Markdown ordered list and converts it into a clean, numbered vertical timeline. ## Syntax Simply wrap your ordered list in a `::: steps` container. ```markdown ::: steps 1. **Preparation** Ensure you have Node.js installed on your machine. 2. **Execution** Run the `init` command. 3. **Completion** Your site is ready! ::: ``` ## Detailed Example: Deployment ```markdown ::: steps 1. **Build the Project** Generate the production-ready static files. ```bash docmd build ``` 2. **Verify Output** Inspect the `site/` directory to ensure all files were generated. 3. **Deploy to Host** Upload the contents of `site/` to your hosting provider. ::: ``` ::: steps 1. **Build the Project** Generate the production-ready static files. ```bash docmd build ``` 2. **Verify Output** Inspect the `site/` directory to ensure all files were generated. 3. **Deploy to Host** Upload the contents of `site/` to your hosting provider. ::: ## Advanced Usage ### Nesting Containers in Steps You can nest any other component (like a **Callout**) inside a step to provide extra context without breaking the numbering sequence. ```markdown ::: steps 1. **Configure Environment** Create a `.env` file in your root directory. ::: callout tip You can use the template provided in `.env.example`. ::: 2. **Restart Server** Apply the new environment settings. ::: ``` ::: callout tip The `steps` container is a strong signal to LLMs that a specific **Workflow** is being documented. When using `steps`, ensure each list item starts with a **Bolded Title**. This allows AI models to quickly parse the sequence of operations in the `llms-full.txt` context. ::: --- ## [Tabs](https://docs.docmd.io/05/content/containers/tabs/) --- title: "Tabs" description: "Organise alternative or dense information into switchable panes. Perfect for multi-language code snippets." --- Tabs are the best way to present related but mutually exclusive information (like "npm vs yarn" or "Windows vs macOS" instructions) in a compact, interactive format. ## Syntax The `tabs` container uses a special sub-delimiter: `== tab "Label"`. ```markdown ::: tabs == tab "Tab Label 1" Content for the first tab. == tab "Tab Label 2" Content for the second tab. ::: ``` ## Detailed Example: Package Managers ````markdown ::: tabs == tab "NPM" ```bash npm install @docmd/core ``` == tab "Yarn" ```bash yarn add @docmd/core ``` == tab "PNPM" ```bash pnpm add @docmd/core ``` ::: ```` ::: tabs == tab "NPM" ```bash npm install @docmd/core ``` == tab "Yarn" ```bash yarn add @docmd/core ``` == tab "PNPM" ```bash pnpm add @docmd/core ``` ::: ## Advanced Features ### Lazy Rendering `docmd` implements **Conditional Lazy Rendering**. If a tab contains heavy assets like a **Mermaid.js** diagram or large images, they are only initialised once the user clicks that specific tab. This ensures your initial page load remains blazingly fast. ### Sticky Tab State The `docmd` SPA router remembers the active tab's index when navigating between similar pages. This creates a cohesive experience for users switching between pages that share the same tab setup. ## Technical Constraints | Constraint | Note | | :--- | :--- | | **No Tabs-in-Tabs** | To prevent UX loops, tabs cannot be nested inside other tabs. | | **Steps-in-Tabs** | High-conflict syntax: If you need steps inside a tab, use a standard ordered list (`1. Step One`). | | **Max Tabs** | Recommended maximum of 6 tabs for mobile responsiveness. | ::: callout tip When using tabs for code snippets, always include the language in the tab label (e.g., `== tab "JavaScript"`). This allows LLMs to instantly identify the relevant block in the unified `llms-full.txt` stream. ::: --- ## [Frontmatter Reference](https://docs.docmd.io/05/content/frontmatter/) --- title: "Frontmatter Reference" description: "The complete guide to page-level metadata and configuration in docmd." --- Frontmatter allows you to override global settings on a per-page basis. It must be written in YAML format at the very top of your Markdown file. ## Core Metadata | Key | Type | Description | | :--- | :--- | :--- | | `title` | `String` | **Required.** Sets the HTML `<title>` and the primary page header. | | `description` | `String` | Sets the meta description for SEO and search results. | | `keywords` | `Array` | A list of keywords for the `<meta name="keywords">` tag. | ## Visibility & Control (v0.5.1+) | Key | Type | Description | | :--- | :--- | :--- | | `noindex` | `Boolean` | Excludes the page from the search results. | | `llms` | `Boolean` | Set to `false` to exclude this page from the `llms.txt` / `llms-full.txt` files. | | `hideTitle` | `Boolean` | If `true`, the title is hidden from the sticky header (use this if you have a custom H1). | | `bodyClass` | `String` | Adds a custom CSS class to the `<body>` tag of this page. | ## Page Layout & Components | Key | Type | Description | | :--- | :--- | :--- | | `layout` | `String` | Set to `full` to hide the Table of Contents and use the primary width. | | `toc` | `Boolean` | Set to `false` to disable the Table of Contents entirely. | | `noStyle`| `Boolean` | Removes the entire docmd UI (Sidebar, Header, Footer) for custom landing pages. | ### `noStyle` Component Control When `noStyle: true` is enabled, you must explicitly opt-in to components you want to keep: ```yaml --- noStyle: true components: meta: true # Injects SEO tags favicon: true # Injects favicon css: true # Injects docmd-main.css theme: true # Injects theme colours/overrides highlight: true # Injects syntax highlighting scripts: true # Injects docmd-main.js (for SPA/Search) layout: true # Injects the content-area wrapper sidebar: true # Injects the navigation sidebar footer: true # Injects the footer branding: true # Injects the "Built with docmd" badge --- ``` ## Plugin Overrides ### SEO Plugin (`seo`) * `description`: Page-specific social description. * `image`: Social share image URL. * `aiBots`: Set to `false` to block AI crawlers from this specific page. * `canonicalUrl`: Sets a custom canonical link. --- ## [Live Preview & Browser Support](https://docs.docmd.io/05/content/live-preview/) --- title: "Live Preview & Browser Support" description: "Run docmd entirely in the browser without a server using the new Live architecture." --- `docmd` features a modular architecture that separates file system operations from core processing logic. This allows the documentation engine to run **entirely in the browser**, enabling live editors and CMS previews without a server. ::: button "Open Live Editor" https://live.docmd.io ## The Live Editor The built-in Live Editor provides a split-pane interface where you can write Markdown on the left and see the rendered documentation on the right instantly. ### Running Locally Launch the editor on your machine: ```bash docmd live ``` ### Static Deployment Generate a standalone version for hosting (e.g., on Vercel or GitHub Pages): ```bash docmd live --build-only ``` This creates a `dist/` directory containing the `index.html` and `docmd-live.js` engine. ## Embedding docmd in Your Site Use the browser-compatible bundle to add Markdown preview capabilities to your own applications. ### 1. Include Script and Assets ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <link rel="stylesheet" href="/assets/css/docmd-theme-sky.css"> <script src="/docmd-live.js"></script> ``` ### 2. Using the API The global `docmd` object exposes the `compile` function. ```javascript const html = docmd.compile(markdown, { siteTitle: 'My Live Doc', theme: { name: 'sky' } }); document.getElementById('preview-frame').srcdoc = html; ``` ::: callout tip "AI Feedback Loops 🤖" By using the Live Editor architecture, you can build **AI-Agent sandboxes**. Instead of the AI saving files to disk, it can "post" its suggested edits to a live-compilation buffer, allowing you to preview AI-suggested documentation changes in real-time before approving the commit. ::: --- ## [docmd : No-Style Page Example](https://docs.docmd.io/05/content/no-style-example/) --- title: "docmd : No-Style Page Example" description: "An example of a page using the no-style feature" noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; margin: 0; padding: 0; line-height: 1.6; } .container { max-width: 800px; margin: 0 auto; padding: 40px 20px; } .header { text-align: centre; margin-bottom: 40px; } .header h1 { font-size: 3rem; margin-bottom: 10px; color: #4a6cf7; } .header p { font-size: 1.2rem; color: #666; } .content { background-color: #f8f9fa; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); } .button { display: inline-block; padding: 12px 24px; background-color: #4a6cf7; color: white; text-decoration: none; border-radius: 4px; font-weight: 600; margin-top: 20px; } .button:hover { background-color: #3a5ce4; } [data-theme="dark"] { color-scheme: dark; } [data-theme="dark"] body { background-color: #121212; color: #e0e0e0; } [data-theme="dark"] .content { background-color: #1e1e1e; box-shadow: 0 2px 10px rgba(0,0,0,0.2); } [data-theme="dark"] .header p { color: #aaa; } </style> bodyClass: "no-style-example" --- <div class="container"> <div class="header"> <h1>No-Style Page Example</h1> <p>This page demonstrates the no-style feature with a custom layout</p> </div> <div class="content"> <h2>What is this page?</h2> <p> This is an example page that uses the <code>noStyle: true</code> frontmatter option to create a completely custom page layout. Unlike regular documentation pages, this page doesn't use the standard docmd layout with sidebar navigation and table of contents. </p> <h2>How does it work?</h2> <p> The <code>noStyle</code> option tells docmd to use a special template that only includes the components you explicitly request via the <code>components</code> object in frontmatter. This gives you complete control over the page structure. </p> <h2>Features enabled on this page:</h2> <ul> <li><strong>meta</strong>: Meta tags, title, and description for SEO</li> <li><strong>favicon</strong>: The site favicon</li> <li><strong>css</strong>: Basic CSS for markdown content</li> <li><strong>theme</strong>: Theme support for light/dark mode</li> <li><strong>scripts</strong>: JavaScript for functionality</li> </ul> <h2>Custom styling</h2> <p> This page includes custom CSS in the <code>customHead</code> frontmatter field. This allows you to define page-specific styles without affecting the rest of your site. </p> <a href="/content/no-style-pages/" class="button">Get Back to No-Style Pages Documentation</a> </div> </div> --- ## [No-Style Pages](https://docs.docmd.io/05/content/no-style-pages/) --- title: "No-Style Pages" description: "Create landing pages and custom layouts by disabling the default docmd theme." --- Sometimes you need a page that looks completely different, like a Marketing Landing Page, a Login screen, or a custom showcase. `docmd` allows you to disable the standard layout (Sidebar, Header, Footer) on a per-page basis using **Frontmatter**. ## Enabling No-Style Add `noStyle: true` to your page's frontmatter. ```yaml --- title: "Welcome" noStyle: true components: meta: true # Keep SEO meta tags favicon: true # Keep site favicon css: true # Injects basic docmd-main.css --- <!-- Write raw HTML or Markdown below --> <div class="hero-section"> <h1>My Product</h1> <p>The future of documentation.</p> </div> ``` ## Controlling Components When `noStyle` is active, you have a blank canvas. Selectively re-enable specific parts of the system: | Component | Description | | :--- | :--- | | `meta` | Injects `<title>`, SEO tags, and OpenGraph data. | | `favicon` | Injects the site favicon. | | `css` | Injects `docmd-main.css` (useful for grid/typography). | | `theme` | Injects the active theme colours/overrides. | | `scripts` | Injects `docmd-main.js` (needed for buttons/SPA). | ## Example: Marketing Landing Page ```yaml --- title: "Home" noStyle: true components: meta: true css: true customHead: | <style> .hero { text-align: centre; padding: 100px 20px; } </style> --- <div class="hero"> <h1>Build Faster.</h1> ::: button "Get Started" /docs/intro color:blue </div> ``` ::: callout tip "AI-Managed Landing Pages 🤖" Because `noStyle` pages can accept raw HTML while still being parsed by `docmd`, they are perfect for **AI-generated layouts**. You can prompt an AI: *"Create a landing page for my project using noStyle: true and provide the raw HTML section."* The AI can perfectly integrate with the rest of your build pipeline. ::: --- ## [Advanced Syntax](https://docs.docmd.io/05/content/syntax/advanced/) --- title: "Advanced Syntax" description: "Master docmd's extended Markdown features: Task lists, custom attributes, footnotes, and more." --- Beyond standard Markdown, `docmd` supports several GitHub Flavored Markdown (GFM) extensions and custom attribute syntaxes to give you total control over your content. ## GFM Extensions ### Task Lists Create interactive or static checklists: ```markdown - [x] Completed task - [ ] Incomplete task ``` - [x] Completed task - [ ] Incomplete task ### Autolinks URL and email addresses are automatically linked without extra syntax: `https://docmd.io` ### Emojis Use standard emoji shortcodes like `:rocket:` or `:smile:`. > I :heart: docmd! :rocket: :smile: ## Custom Attributes (IDs and Classes) You can assign custom IDs and CSS classes directly to headers, images, and links using the `{}` syntax. ### Custom IDs Useful for deep-linking to specific sections. ```markdown ## My Header {#custom-id} ``` ### Custom Classes Assign classes to elements to apply [Custom CSS](/theming/custom-css-js). ```markdown ## Styled Header {.text-centre .text-red} ``` ### Direct Button Links Turn any link into a styled button. ```markdown [Download Now](/download){.docmd-button} ``` ## Footnotes & References Add footnotes for citations or technical deep-dives[^1]. Definitions are automatically moved to the bottom of the page. ```markdown Here is a statement needing a citation[^1]. [^1]: This is the footnote content. ``` ## Abbreviations & Definitions ### Definition Lists ```markdown Term : Definition for the term. ``` Term : Definition for the term. ### Abbreviations Define abbreviations globally within a page. Hovering over the word will show the full name. ```markdown *[HTML]: Hyper Text Markup Language HTML is defined by the W3C. ``` *[HTML]: Hyper Text Markup Language HTML is defined by the W3C. ::: callout tip Using **Definitions** and **Abbreviations** provides high-quality semantic context to AI agents. When an AI processes your `llms-full.txt`, these explicit definitions help it resolve technical acronyms correctly without guessing, leading to more accurate code generation. ::: --- ## [Code Blocks](https://docs.docmd.io/05/content/syntax/code/) --- title: "Code Blocks" description: "Document your code with automatic syntax highlighting, line numbers, and copy buttons." --- `docmd` includes `highlight.js` for automatic syntax highlighting. ## Fenced Code Blocks Wrap your code in triple backticks and specify the language for the best results. ````markdown ```javascript function hello() { console.log("Hello World"); } ``` ```` **Renders as:** ```javascript function hello() { console.log("Hello World"); } ``` ::: callout tip Copy Button If `copyCode: true` is enabled in your config (default), a copy button will automatically appear in the top-right corner of every code block when the user hovers. ::: ## AI Context Strategy When documenting code for LLMs: 1. **Always specify the language**: This helps AI models parse the block correctly in the `llms-full.txt` payload. 2. **Add comments**: Explaining complex logic within the code block helps the AI reason about your implementation during context retrieval. ## Supported Languages `docmd` supports hundreds of languages including: `javascript`, `typescript`, `html`, `css`, `bash`, `json`, `python`, `rust`, `go`, `markdown`, and `yaml`. --- ## [Images & Lightbox](https://docs.docmd.io/05/content/syntax/images/) --- title: "Images & Lightbox" description: "Adding images, styling galleries, and enabling lightbox zoom effects." --- Use standard Markdown syntax. We recommend storing images in your `assets/images/` directory. ```markdown ![Alt Text](/assets/images/screenshot.png "Optional Title") ``` ## Image Styling (v0.5.1+) Add specific classes using the `{ .class }` syntax. ### Sizing ```markdown ![Small](/assets/icon.png){ .size-small } ![Medium](/assets/preview.png){ .size-medium } ![Large](/assets/banner.png){ .size-large } ``` ### Alignment & Effects ```markdown ![Centred](/assets/img.png){ .align-centre } ![Right](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![preview with styling](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium} ## Captions & Galleries ### Figure Captions Use standard HTML for precise captioning: ```html <figure> <img src="/path/to/image.jpg" alt="Description"> <figcaption>This is the caption</figcaption> </figure> ``` ### Image Galleries Group multiple images into a responsive grid. ```html <div class="image-gallery"> <figure> <img src="/assets/img1.jpg" alt="View 1"> <figcaption>Dashboard</figcaption> </figure> <figure> <img src="/assets/img2.jpg" alt="View 2"> <figcaption>Settings</figcaption> </figure> </div> ``` ## Lightbox (Zoom) If `mainScripts` is enabled (default), any image inside a gallery or any image with the `.lightbox` class will open a full-screen zoom view on click. ```markdown ![Click to Zoom](/assets/diagram.png){ .lightbox } ``` ::: callout tip Always provide descriptive **Alt-Text**. While modern AI agents can "see" images, descriptive text in the markdown source acts as a direct hint for the model's reasoning engine, especially when images contain complex diagrams or architectural flows. ::: --- ## [Markdown Syntax](https://docs.docmd.io/05/content/syntax/) --- title: "Markdown Syntax" description: "Master the basic formatting of docmd: Headings, lists, bold, italic, and more." --- `docmd` uses standard Markdown syntax. This guide covers the essentials for formatting text. ## Text Formatting | Style | Syntax | Example | | :--- | :--- | :--- | | **Bold** | `**text**` | **Bold Text** | | *Italic* | `*text*` | *Italic Text* | | ~~Strikethrough~~ | `~~text~~` | ~~Deleted Text~~ | | `Code` | `` `text` `` | `Inline Code` | ## Technical Elements ### Headings ```markdown # Heading 1 ## Heading 2 ### Heading 3 ``` ::: callout tip AI models (and search engines) rely heavily on a proper heading hierarchy. Always avoid skipping levels (e.g., jumping from `#` to `###`) to ensure the `llms.txt` and search index can accurately map your documentation's context. ::: ### Links ```markdown [Link Text](https://www.example.com) [Relative Link](../section/other-page/) ``` ### Lists * **Unordered:** Use `*` or `-`. * **Ordered:** Use `1.`, `2.`, etc. ### Blocks > This is a blockquote. ## Tables | Header 1 | Header 2 | | :--- | :--- | | Left Align | Centre Align | ## Advanced HTML Because `docmd` is built with `html: true`, you can embed raw HTML directly in your Markdown files for custom styling needs. ```html <div style="color: blue;"> This is a blue div. </div> ``` --- ## [Linking & Referencing](https://docs.docmd.io/05/content/syntax/linking/) --- title: "Linking & Referencing" description: "Master internal cross-linking, external links, and asset referencing." --- To link to another page, use the **relative path** to the `.md` file. ::: callout info "Extension Rewriting" `docmd` automatically converts `.md` extensions to valid HTML links during the build. This ensures links work in your IDE (VS Code) and on the deployed website. ::: | Goal | Syntax | | :--- | :--- | | Same Folder | `[Read Guide](guide.md)` | | Subfolder | `[Read Config](configuration/index.md)` | | Parent Folder | `[Go Back](../index.md)` | ## Anchors (Section Linking) Link to specific headers using the `#slug`. * **Same Page:** `[Jump to Top](#linking--referencing)` * **Cross Page:** `[See Installation](../getting-started/installation.md#global-installation)` ## External & Protocol Links Standard URL syntax works for external sites and protocols. * **HTTPS:** `[Visit Google](https://google.com)` * **Email:** `[Email Support](mailto:help@docmd.io)` * **Phone:** `[Call Us](tel:+123456789)` ## Linking to Assets To allow users to download files, place them in your `assets/` folder. `docmd` will **not** strip the extension for files inside this directory. ```markdown [Download PDF](/assets/manual.pdf) [View Raw Config](/assets/examples/config.js) ``` ::: callout tip "AI Navigation Tip" When cross-linking pages, using descriptive link text (like `[Read about PWA configuration](../plugins/pwa.md)`) instead of `[Click here](../plugins/pwa.md)` helps AI models understand the relationship between different technical topics during contextual analysis. ::: --- ## [Contributing](https://docs.docmd.io/05/contributing/) --- title: "Contributing" description: "Learn how you can contribute to the development, design, and documentation of docmd." --- Thank you for contributing to `docmd`! We appreciate your help in making this tool faster, smarter, and more reliable. ## 🛠️ Development Setup `docmd` is a Monorepo managed with [pnpm](https://pnpm.io/). ### 1. Prerequisites - **Node.js**: v20+ - **pnpm**: v10+ ### 2. Setup Clone the repository and install all workspace dependencies: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install ``` ### 3. Running the Dev Server We use workspace filtering to ensure the local CLI is used during development. Start the documentation site and watch for changes in the core engine automatically: ```bash pnpm run dev ``` ### 4. Developer Mode By default, the dev server watches content. To watch internal source code (templates, core engine, plugins), set the environment variable: ```bash # Mac/Linux DOCMD_DEV=true pnpm run dev # Windows (PowerShell) $env:DOCMD_DEV="true"; pnpm run dev ``` ## 🧪 Testing & Quality Before submitting, ensure your changes haven't introduced regressions. 1. **Integration Suite:** Run our universal failsafe to test core engine features, versioning, and redirects: ```bash pnpm test ``` 2. **Conventional Commits:** We follow [Conventional Commits](https://www.conventionalcommits.org/). Use prefixes like `feat:`, `fix:`, or `docs:`. 3. **Copyright Header:** All new files in `packages/` must include the standard project copyright header. Please copy the header from any existing file in the `src/` directory. ## 🚀 Pull Request Workflow 1. **Branch:** Create a branch from `main`. 2. **Code:** Make your changes. 3. **Verify:** Run `pnpm test` and ensure it outputs `✨ ALL SYSTEMS GO`. 4. **Push & Open:** Open a Pull Request against the `main` branch. ### Copyright Header All source files in `packages/` must include the standard copyright header. If you create a new file, please copy the header from an existing file. ```html /*! * -------------------------------------------------------------------- * docmd : the minimalist, zero-config documentation generator. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @license MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` ## Code of Conduct Please note that this project operates with a standard Contributor Code of Conduct. By participating in this project you agree to abide by its terms, ensuring a welcoming and respectful environment for everyone. --- ## [Deployment (Deploy Your Website)](https://docs.docmd.io/05/deployment/) --- title: "Deployment (Deploy Your Website)" description: "Learn how to deploy your docmd-generated static site to modern hosting platforms like GitHub Pages, Vercel, and Netlify." --- Because `docmd` generates a pure static site, you can host your documentation literally anywhere that serves HTML. Run the build command and serve the output directory (default: `site/`). ```bash docmd build ``` ::: tabs == tab "GitHub Pages" The most reliable way is using a **GitHub Action**. This ensures your site rebuilds automatically every time you push. **Create `.github/workflows/deploy-docs.yml`** ```yaml name: Deploy docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: build-and-deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22', cache: 'npm' } - run: npm install -g @docmd/core - run: docmd build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. Connect your GitHub repository. 2. Under Build Settings: * **Build Command:** `npm install -g @docmd/core && docmd build` * **Output Directory:** `site` 3. Click **Deploy**. == tab "Traditional Server" 1. Run `docmd build`. 2. Copy the contents of `site/` to your public directory (e.g., `/var/www/html/docs`). ::: callout tip "SPA Routing" `docmd`'s Single Page Application (SPA) router handles direct URL access gracefully. You **do not** need complex rewrite rules (like `index.html` redirects) on your server. ::: ::: ## Site URL Configuration Always ensure your `siteUrl` is set accurately in `docmd.config.js` if you are using plugins like `sitemap` or `seo` that require absolute URLs. ::: callout tip "AI-Ready Deployments 🤖" When deploying to staging or production, run `docmd build` with the `llms` plugin active. This ensures that even your staging environments provide AI-consumable context via `/llms.txt`, allowing your testing agents to verify your documentation accuracy before going live. ::: --- ## [Basic Usage](https://docs.docmd.io/05/getting-started/basic-usage/) --- title: "Basic Usage" description: "Learn how to initialise a project, organise your markdown files, and build your documentation site." --- Getting started with `docmd` is designed to be instantaneous. This guide explains the core workflow from initialisation to final production build. ## 1. Initialise Your Project To start a new documentation project, create an empty directory and run the `init` command. ```bash mkdir my-guide && cd my-guide docmd init ``` ### The Project Structure After initialisation, your project will follow this clean, intuitive structure: | Folder / File | Purpose | | :--- | :--- | | `docs/` | **Source Folder.** Put all your `.md` files here. | | `assets/` | Static files (images, custom CSS, JS). | | `docmd.config.js` | Your site's brain. Branding, navigation, and plugins. | | `site/` | **Output Folder.** Generated after you run `docmd build`. | ## 2. Launching the Preview You can see your changes in real-time without building the site. Launch the development server: ```bash docmd dev ``` * **URL**: `http://localhost:3000` * **Hot Reload**: Every time you save a `.md` or `.config.js` file, the browser updates instantly. ## 3. Organising Content Every markdown file inside the `docs/` folder becomes a URL. Subfolders are respected automatically. * `docs/index.md` → `/` (Home) * `docs/api.md` → `/api` * `docs/guides/setup.md` → `/guides/setup` > [!TIP] > Use standard Markdown syntax. `docmd` will automatically extract the first `H1` header of your file to use as the page title if not specified in the frontmatter. ## 4. Configuring Navigation `docmd` gives you absolute control over the sidebar. Edit the `navigation` array in `docmd.config.js` to structure your site. ```javascript navigation:[ { title: 'Introduction', path: '/', icon: 'home' }, { title: 'Advanced', icon: 'settings', collapsible: true, // Allow users to collapse this section children:[ { title: 'Configuration', path: '/configuration' }, { title: 'Plugins', path: '/plugins' } ] } ] ``` ## 5. Building for Production When you are ready to deploy, run the build command: ```bash docmd build ``` This generates a highly optimised Single Page Application (SPA) inside the `site/` directory. It is completely static so you can host it on GitHub Pages, Vercel, Netlify, or even a local USB drive. ### Verification Step To verify your production build locally, you can use any static server or run: ```bash docmd dev --preserve ``` ::: callout tip The `--preserve` flag prevents the dev server from overwriting your production `site/` folder with dev-mode assets. ::: --- ## [Installation](https://docs.docmd.io/05/getting-started/installation/) --- title: "Installation" description: "How to install docmd globally or locally using npm, yarn, or pnpm." --- `docmd` is a Node.js package. It requires **Node.js v18.x or higher** installed on your machine. There are several ways you can deploy `docmd` sites. You can run it on-the-fly without installing, or add it permanently to your long term projects. ## Option 1: Zero-Config (Try it instantly) Run `docmd` inside any folder containing markdown files. It will automatically read your files, extract their headers and build a nested navigation sidebar. No configuration or formal setup required. ```bash npx @docmd/core dev -z # Start local dev serve npx @docmd/core build -z # Generate production static site ``` ::: callout warning Zero-Config (`-z`) is currently in `beta`. It is fantastic for quick previews, but for production sites, we recommend initialising a standard configuration file for maximum control. ::: ### Option 2: Project Installation (Recommended) For permanent projects, install `docmd` as dependency to lock your versions. ```bash # 1. Install locally npm install @docmd/core # 2. Initialise your configuration npx @docmd/core init # 3. Start developing npx @docmd/core dev ``` ### Option 3: Global Installation Install once and use the `docmd` command anywhere on your machine. ```bash npm install -g @docmd/core docmd dev # Start the local dev server docmd build # Generate the production static site ``` ## CDN Installation (Browser Only) ::: callout warning Developer Use Only This method is **not** for building documentation sites. It is for developers who want to embed the `docmd` parsing engine inside another web application (like a CMS or Live Preview tool). ::: If you are building a React/Vue/Vanilla JS app and want to render `docmd` syntax on the fly without a backend, use the browser build: ```html <!-- 1. Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 2. Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` See the [Browser API](/advanced/browser-api) guide for implementation details. ## Setup Troubleshooting ::: callout warning Permission Errors If you see `EACCES` errors on macOS/Linux during global installation, it means you don't have permission to write to global directories. **Fix:** Run `sudo npm install -g @docmd/core`. ::: ::: callout info Windows Powershell If you receive an error about "running scripts is disabled on this system", run this command in PowerShell as Administrator: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [Zero-Config Mode](https://docs.docmd.io/05/getting-started/zero-config/) --- title: "Zero-Config Mode" description: "Run docmd without any configuration file. Perfect for quick previews and rapid prototyping." --- `docmd` features a high-intelligence auto-detection engine. This allows you to generate professional documentation for any project without writing a single line of configuration. ## Usage Simply add the `-z` or `--zero-config` flag to your command. ```bash # Start dev server docmd dev -z # Build static site docmd build -z ``` ## How It Works When running in Zero-Config mode, `docmd` performs the following steps: 1. **Smart Directory Detection**: It scans your project for one of these documentation folders: `docs/`, `src/docs/`, `documentation/`, or `content/`. If none are found, `docmd` will gracefully exit with a helpful message. 2. **Automatic Index Fallback**: If no `index.md` or `README.md` is found in your documentation folder, `docmd` automatically designates the first file it finds as the temporary record for your root domain. No more 404s on fresh projects! 3. **Automatic Titling**: It reads your `package.json`. If found, it automatically sets your site `title` and `description` to match your npm package metadata. 4. **Recursive Routing**: It scans all folders and Markdown files to build a nested navigation sidebar. 5. **Sensible Defaults**: It applies the `default` theme with system-aware light/dark mode and enables the `search` plugin. ## Safety & Performance Zero-Config is engineered for safety and predictability: * **Context Awareness**: By limiting execution to specific folders, `docmd` avoids accidentally indexing your entire project root (which might contain thousands of unrelated files like logs or build artifacts). * **Recursion Limit**: The engine ignores `node_modules` and hidden folders (like `.git`) and restricts depth to prevent infinite loops. * **Bail-out Logic**: If no candidate directory is found, or if the directory contains no Markdown files, `docmd` will immediately stop and provide a clean CLI warning rather than hanging. ::: callout tip Zero-config is excellent for **AI Agents**. Because the structure is predictable and derived from the filesystem, an AI can easily predict where files will be located and update documentation without needing to parse complex configuration schemas. ::: --- ## [docmd: The Minimalist Docs Generator](https://docs.docmd.io/05/) --- title: "docmd: The Minimalist Docs Generator" description: "Generate beautiful, lightweight, and blazing-fast documentation sites directly from your Markdown files. Zero clutter, just content." --- ```text _ _ _| |___ ___ _____ _| | | . | . | _| | . | |___|___|___|_|_|_|___| ``` **Generate beautiful, lightweight documentation sites directly from your Markdown files. Zero clutter, just content.** `docmd` bridges the gap between simple static site generators and heavy, framework-driven applications. It processes standard Markdown into highly optimised static HTML, while delivering a buttery-smooth Single Page Application (SPA) experience for your users. ::: button "Quick Start" /getting-started/installation ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#333 ::: button "Explore Features" /getting-started/basic-usage color:#333 ## Quick Start **Requires [Node.js](https://nodejs.org/) installed on your machine.** Deploy a beautiful, searchable documentation site in seconds. No framework knowledge required. **1. Install `docmd` as dependency in your project to lock your versions.** ```bash npm install @docmd/core # Install locally (Recommended) npx @docmd/core init # Initialise your configuration npx @docmd/core dev # Start developing ``` **2. Install Globally** ```bash npm install -g @docmd/core # Enables docmd to run anywhere on your local machine ``` **3. You can run `docmd` on-the-fly without installing it or setting up any config.** ```bash npx @docmd/core dev -z # Start local dev server instantly ``` Open `http://localhost:3000` in your browser. Any changes you make to the files in the `docs/` folder will instantly update on your screen. ## Why choose docmd? We believe writing documentation should be as frictionless as possible. You shouldn't need to configure complex JavaScript frameworks just to publish text. We also believe that modern tools should be built for **both humans and machines**. That's why `docmd` is arguably the most AI-friendly static documentation generator on the market, ready to be immediately digested by the newest wave of LLMs directly out of the box. <div class="image-gallery" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));"> ::: card AI-Native Optimisation `docmd` transforms your documentation into a structured API for LLMs, allowing them to ingest your entire project context perfectly in single-shot prompts. ::: ::: card Zero Config & Auto-Routing Run `docmd dev -z` in your project. We automatically scan for a expected documentation folders, extract H1 headers as page titles, and build a nested, collapsible navigation tree instantly. No `config.js` needed to start. ::: ::: card SPA Performance We serve static HTML for maximum SEO and speed. Once loaded, `docmd` transitions between pages as a high-performance Single Page Application, no full browser reloads, just instant content swaps. ::: ::: card Smart Offline Search Built-in full-text search with fuzzy matching and section-deep linking. The entire search index runs in-browser, meaning it works 100% offline and in air-gapped environments. ::: ::: card Modern & Responsive Responsive by design. Includes a beautiful default theme with native Light/Dark mode, sticky versioning, and mobile-optimised sidebars out of the box. ::: ::: card Isomorphic Rendering The same engine that builds your static site can run natively in the browser. Embed live documentation previews or interactive editors directly into your own web applications. ::: </div> ## Rich Content Out of the Box `docmd` supports standard Markdown and extends it with intuitive components for professional structure. ::: tabs == tab "Interactive Components" Highlight critical information with Callouts and native Buttons. ::: callout tip Performance Tip Nest containers inside each other to create complex, usable layouts without touching HTML or CSS. ::: ::: button "Read about Containers" /content/containers/callouts == tab "Native Diagrams" Create professional diagrams using **Mermaid.js** syntax directly in your markdown. ```mermaid graph LR MD[Markdown] --> Build[docmd Build] Build --> Static[Static HTML] Build --> LLM[llms-full.txt] ``` == tab "Code Precision" Automatic syntax highlighting with `highlight.js`, including one-click copy buttons and multi-language support. ```javascript // docmd.config.js export default defineConfig({ title: 'My Project', layout: { spa: true } }); ``` ::: Ready to build? [Install docmd](/getting-started/installation) or see [Zero-Config Mode](/getting-started/zero-config) in action. --- ## [Analytics Integration](https://docs.docmd.io/05/plugins/analytics/) --- title: "Analytics Integration" description: "Integrate Google Analytics or other tracking services into your docmd site." --- `docmd` provides a built-in plugin for web analytics. This allows you to understand your audience and track page views with ease. ## Enabling Analytics Add the `analytics` plugin to your `plugins` object in `docmd.config.js`. ```javascript module.exports = { plugins: { analytics: { // For Google Analytics 4 (Recommended) googleV4: { measurementId: 'G-XXXXXXXXXX' }, // For Google Universal Analytics (Legacy) googleUA: { trackingId: 'UA-XXXXXXXXX-Y' } } } }; ``` ## Configuration Options ### Google Analytics 4 (GA4) * **Key**: `googleV4` * **Requirement**: `measurementId` (String). * **Behaviour**: Injects the `gtag.js` snippet into every page. ### Universal Analytics (UA) * **Key**: `googleUA` * **Requirement**: `trackingId` (String). * **Behaviour**: Injects the legacy `analytics.js` script. ## Important Considerations * **SPA Tracking**: The `docmd` analytics plugin is SPA-aware. It automatically sends a "Page View" event on every `docmd:page-mounted` trigger, ensuring your metrics are accurate despite the client-side routing. * **Privacy**: Be mindful of local regulations (GDPR/CCPA). You can use [Custom JS](/advanced/client-side-events) to implement custom consent banners. ::: callout tip "AI Bot Tracking 🤖" While standard analytics track human visitors, `docmd` sites also generate high traffic from AI crawlers. Use server-side logs or advanced privacy-first analytics (like Plausible or Fathom) if you want to distinguish between human readers and AI-agent context retrieval sessions. ::: --- ## [Building Plugins](https://docs.docmd.io/05/plugins/building-plugins/) --- title: "Building Plugins" description: "A guide for developers on how to create and share custom docmd plugins." --- Plugins are the primary way to extend `docmd`. They allow you to hook into the Markdown parser, inject HTML into the layout, and execute logic after builds. ## Anatomy of a Plugin A plugin is a JavaScript object exporting specific hook functions. | Hook | Purpose | | :--- | :--- | | `markdownSetup(md)` | Access the `markdown-it` instance for custom rules. | | `injectHead(config)` | Injects HTML into the `<head>`. | | `injectBody(config)` | Injects HTML at the bottom of the `<body>`. | | `getAssets()` | Returns a list of CSS/JS files to copy/inject. | | `onPostBuild(ctx)` | Executes logic after all HTML is generated. | ## Creating a Local Plugin You can create a plugin file in your project, for example `my-plugin.js`: ```javascript // my-plugin.js module.exports = { // 1. Extend Markdown markdownSetup: (md) => { // Example: Add a custom container or rule // md.use(require('markdown-it-emoji')); }, // 2. Inject Styles/Scripts injectHead: (config) => { return `<meta name="custom-plugin" content="active">`; }, // 3. Post-Build Action onPostBuild: async ({ config, pages, outputDir, log }) => { log('Plugin: Build finished! Processed ' + pages.length + ' pages.'); } }; ``` To use it, require it in your `docmd.config.js`: ```javascript // docmd.config.js module.exports = { // ... plugins: { './my-plugin.js': {} // Key is path, Value is options object } }; ``` ## Plugin API Reference ### `getAssets()` Used to inject client-side scripts or CSS files. ```javascript getAssets: () => { return [ { src: path.join(__dirname, 'client-script.js'), // Source file dest: 'assets/js/plugin.js', // Destination in site/ type: 'js', // 'js' or 'css' location: 'body' // 'head' or 'body' } ]; } ``` ### `onPostBuild({ config, pages, outputDir, log })` * `config`: The full project configuration object. * `pages`: Array of processed page objects `{ outputPath, frontmatter, htmlContent, searchData }`. * `outputDir`: Absolute path to the build output folder. * `log`: Helper function to print messages to the CLI console. ## Publishing a Plugin To share your plugin with the community: 1. Name your package `docmd-plugin-<name>` (recommended). 2. Export the plugin object as the default export. 3. Publish to NPM. Users can then install it via `npm install docmd-plugin-name` and add it to their config: ```javascript plugins: { 'docmd-plugin-name': { /* options */ } } ``` ::: callout tip "AI-Generated Plugins 🤖" The `docmd` plugin API is designed to be **LLM-Optimal**. Because the hooks are simple, stateless, and use standard JavaScript objects, an AI Agent can perfectly generate a complete plugin (e.g., for custom Markdown containers or third-party integrations) from a single prompt with minimal errors. ::: --- ## [Plugin Installer](https://docs.docmd.io/05/plugins/installer/) --- title: "Plugin Installer" description: "How to use the docmd plugin installer to easily add and configure plugins." --- The `docmd` plugin installer is a built-in cross-platform utility that fully automates downloading npm packages and injecting their configurations directly into your `docmd.config.js`. ## Adding Official Plugins To add an official docmd plugin, you can simply run its short name: ```bash docmd add analytics ``` ### What happens under the hood? 1. **Package Manager Detection:** The installer scans your project to detect if you use `npm`, `pnpm`, `yarn`, or `bun`. 2. **Registry Lookup:** It translates `analytics` to `@docmd/plugin-analytics` via the official registry. 3. **Silent Installation:** It silently runs the respective install command (e.g. `pnpm add @docmd/plugin-analytics`) without polluting your terminal. 4. **Configuration Injection:** It surgically parses your `docmd.config.js` and injects `'analytics': {}` into your `plugins` object natively. ## Removing Plugins To safely uninstall a plugin and remove its configuration from your active environment: ```bash docmd remove analytics ``` This will cleanly uninstall the dependency using your active package manager and elegantly strip the active configuration bounds from your `docmd.config.js` without breaking your formatting or code schema. ## Third-Party (Community) Plugins The installer also serves as a generic package installer. If you provide a plugin name that is *not* in the official docmd registry, it elegantly falls back to installing that literal module: ```bash docmd add docmd-custom-theme-plugin ``` 1. The installer downloads `docmd-custom-theme-plugin` natively. 2. It assumes an empty configuration standard and injects `'docmd-custom-theme-plugin': {}` securely into your active configuration file. ## Advanced Usage ### Verbose Logging By default, the installer runs completely silently to keep your terminal perfectly clean. If you are experiencing network issues or want to see the underlying package manager logs, run with the `--verbose` (or `-v`) flag: ```bash docmd add search --verbose ``` This will print the full NPM/Yarn/PNPM/Bun streaming output and detailed Node.js stack traces if an error occurs. --- ## [AI Support (llms.txt)](https://docs.docmd.io/05/plugins/llms/) --- title: "AI Support (llms.txt)" description: "Turn your documentation into a first-class API for Large Language Models using the native llms.txt and llms-full.txt generation." --- `docmd` is built for a world where both humans and machines consume documentation. The `llms` plugin automatically transforms your site into a structured, high-context data stream that allows AI agents and Large Language Models (LLMs) to understand your project with nearly 100% precision. ## Enabling AI Support The plugin is bundled with `@docmd/core` and can be activated with a single line: ```javascript // docmd.config.js module.exports = { url: 'https://docs.myproject.com', // Required for absolute link generation plugins: { llms: {} } }; ``` ## What it Generates When enabled, `docmd` generates two specialized files at the root of your production output: ### 1. `llms.txt` (The Index) A standardised, minimalist Markdown file that map out your site's hierarchy. AI tools like **Cursor**, **ChatGPT Search**, and **Perplexity** can use this to crawl your site's structure efficiently without downloading heavy HTML. ### 2. `llms-full.txt` (The Context Payload) This is a `docmd`-specific innovation. It concatenates the raw, high-fidelity content of your **entire** documentation project into one single massive text file. * **Zero Noise**: Strips CSS, JS, and UI clutter. * **High Context**: Preserves headings, code blocks, and relationships. * **Total Awareness**: Users can upload this single file to ChatGPT or Claude to give the model immediate, deep knowledge of your entire library in one prompt. ## Managing AI Context You can control what parts of your site are visible to AI models using frontmatter. ### Excluding a Page If a page contains sensitive information or internal notes you don't want AI models to learn: ```yaml --- title: "Internal Dev Secrets" llms: false --- ``` ::: callout tip By hosting an `llms-full.txt` file, you are essentially providing an **Open API for AI Models**. This makes your project the preferred choice for developers working with AI assistance, as they can reliably get accurate answers without your docs "hallucinating" or being outdated by the model's training cutoff. ::: --- ## [Mermaid Diagrams](https://docs.docmd.io/05/plugins/mermaid/) --- title: "Mermaid Diagrams" description: "Native support for Mermaid.js. Create flowcharts, sequence diagrams, and pie charts directly in your Markdown files." --- `docmd` includes native, zero-config support for [Mermaid.js](https://mermaid.js.org/). You can create professional diagrams using simple text-based syntax without leaving your Markdown file. ## Why use Mermaid in docmd? * **Zero Scripting**: No need to include external scripts. `docmd` detects the usage and injects the rendering engine automatically. * **Theme Aware**: Diagrams automatically shift colours between **Light** and **Dark** modes to match your site's theme. * **Lazy Loading**: For optimum page speed, diagrams are only initialised once they enter the viewport. ## Examples ### Flowchart Flowcharts are used to represent workflows or processes. They show the steps as boxes of various kinds, and their order by connecting them with arrows. ````markdown ```mermaid graph TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> E[Fix the issue] E --> B C --> F[Deploy] ``` ```` ```mermaid graph TD A[Start] --> B{Is it working?} B -->|Yes| C[Great!] B -->|No| D[Debug] D --> E[Fix the issue] E --> B C --> F[Deploy] ``` ### Sequence Diagram Sequence diagrams show how processes operate with one another and in what order. They capture the interaction between objects in the context of a collaboration. ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server participant Database User->>Browser: Enter URL Browser->>Server: HTTP Request Server->>Database: Query Data Database-->>Server: Return Results Server-->>Browser: HTTP Response Browser-->>User: Display Page ``` ```` ```mermaid sequenceDiagram participant User participant Browser participant Server participant Database User->>Browser: Enter URL Browser->>Server: HTTP Request Server->>Database: Query Data Database-->>Server: Return Results Server-->>Browser: HTTP Response Browser-->>User: Display Page ``` ## Pie Chart Pie charts are circular statistical graphics divided into slices to illustrate numerical proportions. ````markdown ```mermaid pie title Browser Usage Statistics "Chrome" : 64.5 "Safari" : 18.2 "Firefox" : 8.5 "Edge" : 4.8 "Other" : 4.0 ``` ```` ```mermaid pie title Browser Usage Statistics "Chrome" : 64.5 "Safari" : 18.2 "Firefox" : 8.5 "Edge" : 4.8 "Other" : 4.0 ``` ## Git Graph Git graphs visualize Git branching and merging operations, making it easier to understand version control workflows. ````markdown ```mermaid gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop commit branch feature checkout feature commit checkout main merge feature commit ``` ```` ```mermaid gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop commit branch feature checkout feature commit checkout main merge feature commit ``` ## XY Chart XY charts display data as a series of points on a coordinate plane, useful for showing correlations and trends. **Code:** ````markdown ```mermaid xychart-beta title "Sales Revenue by Quarter" x-axis [Q1, Q2, Q3, Q4] y-axis "Revenue (in $1000)" 0 --> 100 bar [50, 60, 70, 85] line [45, 55, 75, 80] ``` ```` ```mermaid xychart-beta title "Sales Revenue by Quarter" x-axis [Q1, Q2, Q3, Q4] y-axis "Revenue (in $1000)" 0 --> 100 bar [50, 60, 70, 85] line [45, 55, 75, 80] ``` ::: callout tip Mermaid diagrams are highly readable by LLMs. When an AI model reads your `llms-full.txt`, it can "see" the logic flow of your diagrams as text, making it much better at explaining complex architectural relationships in your project. ::: --- ## [PWA Plugin](https://docs.docmd.io/05/plugins/pwa/) --- title: "PWA Plugin" description: "Turn your documentation into a blazingly fast installable App using the zero-config PWA plugin." --- # PWA Plugin The `@docmd/plugin-pwa` allows you to instantly turn your documentation site into a **Progressive Web App (PWA)** with a single line of configuration. Once enabled, it handles everything: the Web Manifest, PWA meta tag injection, an intelligent Service Worker, and automatic offline caching. ## Installation This plugin ships bundled with `@docmd/core` and does not require a separate install. ## Enabling the Plugin Add `pwa` under the `plugins` object in `docmd.config.js`: ```javascript // docmd.config.js module.exports = { plugins: { pwa: {} // That's it. The plugin is now active! } } ``` ## What it Generates When `docmd build` runs with `pwa` active, three things are automatically generated and injected into your output: | File / Injection | Description | | :--- | :--- | | `manifest.webmanifest` | Declares your site as an installable app with name, theme colours, and icons | | `service-worker.js` | Intercepts network requests, caches assets, and powers offline support | | `<meta>` tag injection | Injects `mobile-web-app-capable`, `apple-mobile-web-app-capable`, and `theme-color` into every page's `<head>` | ## How Caching Works The Service Worker uses a **network-first with cache fallback** strategy: 1. **On page load**, it attempts to fetch from the network first. If the network responds successfully, the freshest version is stored and returned. 2. **On subsequent visits**, if a cached version exists, it is returned instantly from the cache while the network is simultaneously checked in the background and the cache is updated silently. 3. **Offline**: If the network is unreachable and a cached version exists, the cached version is returned easily. ## Automatic Cache Busting Every `docmd build` generates a new Service Worker with a unique `CACHE_NAME` timestamp fingerprint (e.g., `docmd-cache-1741267200000`). When the browser fetches the new worker, it automatically activates it and the old cache is purged immediately via the Service Worker's `activate` lifecycle. > **No manual cache clearing is needed.** Redeploying your site is all it takes. ## Background Auto-Updates The plugin registers a silent polling interval that checks the server for a new Service Worker every **5 minutes** while the user has your site open in their browser tab. If a new Site Worker is found (i.e. you have redeployed), it is staged and installed during activation on the next navigation. ## Disabling or Removing the Plugin ### Temporarily Disable ```javascript pwa: { enabled: false } ``` ### Fully Remove Simply delete the `pwa` block from your `plugins`. The next time you run `docmd build`, a new manifest is not generated. When users visit the site, docmd's client-side bootstrap (`docmd-main.js`) checks for the presence of `<link rel="manifest">`. If it's missing but a Service Worker is registered, it automatically **unregisters all existing ghost workers** and clears the cached shell - requiring no user action. > [!NOTE] > The `manifest.webmanifest` and `service-worker.js` files from a previous build persist on disk until you clear your output directory (`site/` by default) with `docmd build` or `rm -rf site`. This is a filesystem artifact, not an active PWA. ## Configuration Reference All fields are optional. The defaults are designed for zero-config use. ```javascript module.exports = { plugins: { pwa: { // --- Icon Configuration --- // Priority: pwa.logo > config.logo > config.favicon > (no icons) logo: 'assets/images/app-icon.png', // Path relative to your src folder // Or for full manual control: icons: [ { src: '/assets/images/icon-192.png', sizes: '192x192', type: 'image/png' }, { src: '/assets/images/icon-512.png', sizes: '512x512', type: 'image/png' } ], // --- Manifest Colours --- themeColor: '#1e293b', // Browser chrome / top bar accent bgColor: '#ffffff', // Splash screen background during install // --- Disable the plugin entirely --- enabled: false } } } ``` ### Icon Resolution Priority docmd resolves your PWA icon from the following cascade: 1. `pwa.icons` - Manual array, used as-is 2. `pwa.logo` - Single image path, used for both 192x192 and 512x512 entries 3. `config.logo` - Your global site logo 4. `config.favicon` - Your global favicon 5. *(No icons declared in manifest)* - If none of the above are set ## Testing Locally Browsers restrict Service Workers to `https://` or `localhost`. Use: ```bash docmd dev ``` Open Chrome DevTools → **Application** → **Manifest** and **Service Workers** to view the activated registration in real-time. Safari → **Develop** → **Service Workers** panel works equally well. --- ## [Search Plugin](https://docs.docmd.io/05/plugins/search/) --- title: "Search Plugin" description: "Configure docmd's zero-config, privacy-focused offline search engine with section-deep linking." --- Every `docmd` project includes a powerful, full-text search engine built-in. Unlike traditional search tools that require external indexing services or server-side databases, `docmd` search runs **entirely in the user's browser**. ## How it Works 1. **Build Phase**: `docmd` analyses your markdown and generates a compressed `search-index.json`. 2. **Section Awareness**: We don't just index pages; we index **headers**. If a keyword appears in a specific `###` section, the search result will link the user directly to that section using its permalink. 3. **Local Execution**: When a user types, the matching happens instantly in memory using `MiniSearch`. It works perfectly in air-gapped environments or on slow connections. ## Configuration The search plugin is **active by default**. You can customise its presence via the `layout` object. ```javascript // docmd.config.js module.exports = { layout: { optionsMenu: { components: { search: true // Set to false to remove the search button } } } } ``` ## Advanced Usage ### Excluding Content To prevent a specific page from being indexed (e.g., utility pages), add `noindex` to the frontmatter: ```yaml --- title: "Private Info" noindex: true --- ``` ### Keyboard Shortcuts We've optimised the search experience with native feeling shortcuts: * `Cmd + K` (Mac) or `Ctrl + K` (Windows) to open. * `ESC` to close. * `Arrow Keys` and `Enter` to navigate. ## Privacy First Because the search happens entirely on the client, no data - not even keystrokes - is ever sent to a server. This makes `docmd` the Gold Standard for documentation search in privacy-sensitive industries (Healthcare, Finance, Security). ## Comparison Many documentation generators (like Docusaurus) rely on **Algolia DocSearch**. While Algolia is powerful, it introduces friction: | Feature | docmd Search | Algolia / External | | :--- | :--- | :--- | | **Setup** | **Zero Config** (Automatic) | Complex (API Keys, CI/CD crawling) | | **Privacy** | **100% Private** (Client-side) | Data sent to 3rd party servers | | **Offline** | **Yes** | No | | **Cost** | **Free** | Free tier limits or Paid | | **Speed** | **Instant** (In-memory) | Fast (Network latency dependent) | --- ## [SEO & Meta Tags](https://docs.docmd.io/05/plugins/seo/) --- title: "SEO & Meta Tags" description: "Automatic SEO optimisation, Open Graph integration, and AI Scraper control for your docmd site." --- The `seo` plugin ensures your documentation is discoverable by search engines and looks professional when shared on social media. It handles technical meta-tag injection automatically. ## Quick Setup ```javascript // docmd.config.js module.exports = { plugins: { seo: { defaultDescription: 'The official documentation for Project X.', openGraph: { defaultImage: '/assets/og-hero.jpg' // Shown on Twitter/LinkedIn }, aiBots: { block: true // Automatically block common AI scrapers (GPTBot, etc) } } } } ``` ## Automatic Features ### 1. Smart Excerpts If you forget to provide a `description` in your file's frontmatter, the SEO plugin automatically constructs a **150-character fallback description** from the beginning of your content. This ensures you never have "empty" snippets in Google search results. ### 2. AI Scraper Control With `aiBots.block: true`, `docmd` injects `noindex` tags targetting 12+ major AI crawler agents (including `GPTBot`, `ClaudeBot`, and `Google-Extended`). This is the easiest way to keep your documentation out of bulk training datasets while remaining visible to humans. ## Per-Page Overrides For maximum SEO precision, use the `seo` object in your Markdown frontmatter. ```yaml --- title: "Advanced Setup Guide" seo: description: "Learn how to configure our enterprise-grade security clusters in minutes." image: "/assets/guides/setup-social.png" noindex: false keywords: ["security", "cluster", "enterprise"] --- ``` ## Structured Data (LD+JSON) `docmd` can automatically generate [Article Schema](https://developers.google.com/search/docs/appearance/structured-data/article) to help Search Engines display rich snippets. ```yaml --- title: "How to Build a docmd Plugin" seo: ldJson: true --- ``` ::: callout tip A well-configured SEO plugin helps AI-powered search engines (like SearchGPT or Perplexity) summarize your site accurately. By providing clear descriptions and blocked bots, you control exactly how AI models perceive and source your content online. ::: --- ## [Sitemap Plugin](https://docs.docmd.io/05/plugins/sitemap/) --- title: "Sitemap Plugin" description: "Automatically generate sitemap.xml to improve search engine discoverability." --- The `sitemap` plugin generates a standard `sitemap.xml` file during the build process. This ensures your content is indexed correctly by Google and other crawlers. ## Enabling the Plugin ```javascript // docmd.config.js module.exports = { siteUrl: 'https://mydocs.com', // Required for absolute URLs plugins: { sitemap: { defaultChangefreq: 'weekly', // Default: weekly defaultPriority: 0.8 // Default: 0.8 } } }; ``` ## Frontmatter Overrides You can control sitemap behaviour on a per-page basis. * **Exclude Page:** `sitemap: false` * **Custom Settings**: ```yaml --- sitemap: changefreq: 'daily' priority: 1.0 --- ``` ## How It Works 1. **Scanning**: The plugin scans every HTML file generated during the build. 2. **Absolute Mapping**: It uses your `siteUrl` to generate the final URLs. Ensure this is defined without a trailing slash. 3. **Generation**: It writes `sitemap.xml` to the root of your output directory. ::: callout tip "AI Discoverability 🤖" While traditional search engines use sitemaps, **AI Agents** and **Knowledge Crawlers** use them to prioritise which pages to ingest into their training or RAG sets first. A well-configured sitemap ensures your most important sections (like "Guides") are processed before minor utility pages. ::: --- ## [Using Plugins](https://docs.docmd.io/05/plugins/usage/) --- title: "Using Plugins" description: "How to enable and configure docmd's powerful plugin ecosystem." --- `docmd` features a modular architecture. While the core engine handles Markdown conversion and routing, specialized features are implemented via plugins. ## Enabling Core Plugins Most official plugins ship bundled with `@docmd/core` and simply need to be enabled in your `docmd.config.js`. ```javascript // docmd.config.js module.exports = { plugins: { // 1. Search (Built-in offline search) search: {}, // 2. SEO (Meta tags & canonical URLs) seo: { aiBots: false }, // 3. PWA (Mobile App support) pwa: { themeColor: '#0097ff' }, // 4. LLM (AI Context generation) llms: { fullContext: true }, // 5. Mermaid (Native Diagrams) mermaid: {} } } ``` ## Plugin Lifecycle Plugins hook into different stages of the build process: * **`onPreBuild`**: Modifies the file list or adds files before compilation. * **`onPostBuild`**: Generates secondary artifacts (like `sitemap.xml` or `service-worker.js`). * **`generateMetaTags`**: Injects custom HTML into the `<head>` of every page. * **`generateScripts`**: Injects JavaScript before the closing `</body>` tag. ## External Plugins To use a plugin from npm, install it and require it in your config. ```bash npm install @docmd/plugin-analytics ``` ```javascript // docmd.config.js const Analytics = require('@docmd/plugin-analytics'); module.exports = { plugins: { analytics: { googleV4: { measurementId: 'G-XXXX' } } } } ``` ::: callout tip Our plugin architecture is designed to be **transparent**. Every meta-tag and script injected by a plugin is clearly defined and traceable. This allows AI models to understand exactly how your site's functionality is being extended without guessing. ::: --- ## [Recipe: Optimising for AI Agents](https://docs.docmd.io/05/recipes/ai-optimisation/) --- title: "Recipe: Optimising for AI Agents" description: "How to structure your docmd site to be perfectly ingestible by LLMs and AI Agents." --- `docmd` is uniquely positioned as an "AI-Ready" documentation engine. By following these best practices, you ensure that AI models (like ChatGPT, Claude, and GitHub Copilot) can understand and support your project with high accuracy. ## 1. Enable the LLM Plugin The first step is enabling the native LLM plugin. This generates structured context files that AI agents crave. ```javascript // docmd.config.js module.exports = { plugins: { llms: { fullContext: true // Generates llms-full.txt (highly recommended) } } } ``` ## 2. Semantic Heading Hierarchy AI models use headings to build a mental map of your documentation. * **Don't skip levels**: Always go H1 → H2 → H3. * **Be Descriptive**: Instead of "Setup," use "Installing CLI via NPM." * **One H1 Per Page**: Ensure your frontmatter `title` is descriptive, as `docmd` uses it as the primary H1. ## 3. Code Block Metadata When providing code examples, always specify the language. This helps the LLM parser apply the correct syntax rules during context retrieval. ````markdown ```typescript // Good: Language is specified const docmd = new Engine(); ``` ```` ## 4. Using the `llms-full.txt` Pipeline The `llms-full.txt` file is a concatenated version of your entire documentation. * **Prompting Tip**: Tell your AI: *"Use the structure in /llms.txt and the full content in /llms-full.txt to answer my questions about this project."* * **Customisation**: Use `llms: false` in frontmatter to exclude private or internal-only pages from this public AI context file. ## 5. Descriptive Image Alt-Text While AI is getting better at vision, text is still the most reliable way to provide context. descriptive `alt` text in your images ensures that even if the AI doesn't "see" the image, it understands its purpose in the build. --- ## [Recipe: Adding Custom Fonts](https://docs.docmd.io/05/recipes/custom-fonts/) --- title: "Recipe: Adding Custom Fonts" description: "Personalize your documentation by importing Google Fonts." --- `docmd` uses CSS variables to manage typography. Changing your site's font is as easy as creating a custom stylesheet. ## 1. Create a CSS File Create a file in your project (e.g., `assets/css/fonts.css`). Go to [Google Fonts](https://fonts.google.com), find the font you want (like *Inter* or *Fira Code*), and use the `@import` method. Then, assign that font to the docmd root variables. ```css /* assets/css/fonts.css */ /* Import the fonts */ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fira+Code&display=swap'); :root { /* Override the default sans-serif font */ --font-family-sans: "Inter", -apple-system, BlinkMacSystemFont, sans-serif; /* Override the monospace (code block) font */ --font-family-mono: "Fira Code", monospace; } ``` ## 2. Register the Stylesheet Open your `docmd.config.js` and add the path to your new CSS file in the `theme.customCss` array. ```javascript module.exports = { // ... theme: { name: 'sky', appearance: 'light', customCss:[ '/assets/css/fonts.css' // Path is relative to the generated site/ root ] } } ``` Restart your `docmd dev` server. Your entire site will now use your custom typography! --- ## [Recipe: Adding a Custom Favicon](https://docs.docmd.io/05/recipes/favicon/) --- title: "Recipe: Adding a Custom Favicon" description: "How to add a custom favicon to your documentation site." --- A favicon is the small icon that appears in the browser tab next to your page title. `docmd` makes it easy to add your own. ## 1. Prepare your image You can use `.ico`, `.png`, or `.svg` files. For the best compatibility, an `.ico` file is recommended. ## 2. Add to Assets Place your image file in your project's assets directory. ```bash # Example structure my-project/ ├── assets/ │ └── my-icon.ico <-- Your file here ├── docs/ └── docmd.config.js ``` ## 3. Update Configuration Open `docmd.config.js` and update the `favicon` property with the path relative to the output root. ```javascript module.exports = { // ... // Points to site/assets/my-icon.ico favicon: '/assets/my-icon.ico', // ... }; ``` ## 4. Build Run `docmd build` (or `docmd dev`). `docmd` will automatically copy your asset file to the site build and link it in the `<head>` of every page. --- ## [Recipe: Creating a Landing Page](https://docs.docmd.io/05/recipes/landing-page/) --- title: "Recipe: Creating a Landing Page" description: "How to build a custom landing page using noStyle." --- Sometimes you want your `index.html` (the home page) to look completely different from your documentation - like a product marketing page. `docmd` makes this easy with **No-Style Pages**. ## The Concept By adding `noStyle: true` to your frontmatter, `docmd` strips away the sidebar, header, and default CSS, giving you a blank canvas while still keeping helpful meta tags. ## Implementation Create or edit `docs/index.md`: ```html --- title: "My Product" description: " The best product ever." noStyle: true components: meta: true # Keep SEO tags favicon: true # Keep favicon scripts: false # Disable default docmd scripts customHead: | <style> body { font-family: sans-serif; margin: 0; } .hero { background: #111; color: #fff; padding: 100px 20px; text-align: centre; } .btn { background: #3b82f6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; } </style> --- <div class="hero"> <h1>Welcome to My Product</h1> <p>The ultimate solution for X, Y, and Z.</p> <br> <a href="/getting-started/" class="btn">Read the Docs →</a> </div> <div class="features"> <!-- Your custom HTML features grid here --> </div> ``` This page will be built as `index.html` but will look exactly like your custom HTML, serving as a perfect entry point to your documentation. --- ## [Recipe: Documentation Writing Guide](https://docs.docmd.io/05/recipes/writing-guide/) --- title: "Recipe: Documentation Writing Guide" description: "Best practices for writing clear, scannable, and effective documentation with docmd." --- Great documentation isn't just about correct information; it's about how that information is structured. This guide covers the best practices for using `docmd` features to help your readers. ## Scannability is Everything Users rarely read documentation line-by-line. They scan for answers. * **Use Descriptive Headings:** Instead of "Setup," use "Installing the CLI via NPM." * **Keep Paragraphs Short:** Break up large walls of text into 2-3 sentence chunks. * **Use Bold Text:** Highlight key terms, file paths, or commands so they pop while scanning. ## Choosing the Right Container `docmd` provides several containers. Using them correctly improves the user's mental model. ### Callouts vs. Cards * **Use Callouts** for "interruptions." Use `tip` for helpful shortcuts, `warning` for things that might break, and `danger` for critical errors. * **Use Cards** for "grouping." Cards are great for feature lists on a homepage or summarizing a large section. ### Steps for Tutorials Whenever you have more than two actions the user must perform in order, use the `::: steps` container. It provides a visual timeline that feels much more encouraging than a plain numbered list. ## Linking Best Practices Since `docmd` generates a Single Page Application, navigating between pages is instant. * **Use Relative Paths:** Always link using `./file.md` or `../folder/file.md`. This ensures your links work in your code editor (VS Code), on your web server, and even in offline mode. * **Self-Describing Links:** Avoid "Click here." Instead, use "[Read the Installation Guide](/getting-started/installation)." ## Organising Code Blocks * **Specify Languages:** Always add the language tag (e.g., ` ```javascript `) to enable syntax highlighting. * **Copy Buttons:** Remember that `docmd` automatically adds a copy button to every code block, so you don't need to ask users to "copy and paste" manually. --- ## [Release Note for docmd 0.5.0](https://docs.docmd.io/05/release-notes/0-5-0/) --- title: "Release Note for docmd 0.5.0" description: "PWA & AI First docmd 0.5.0 Release Notes" --- v0.5.0 marks a massive evolution for docmd. We are introducing **Enterprise-Grade Versioning**, a magical **Zero-Config Mode**, and a modernized configuration schema, all while maintaining our promise of zero bloat. This release transforms docmd from a simple documentation generator into a reliable platform capable of handling complex, multi-versioned projects with ease. ## ✨ Highlights ### 1. Documentation Versioning Support You asked, we delivered. You can now maintain multiple versions of your documentation (e.g., `v1.0`, `v2.0`) simultaneously. docmd handles the routing, asset separation, and UI automatically. * **Sticky Switching:** Changing versions keeps you on the same page (e.g., switching v1 -> v2 while on `/installation` takes you to `/v2/installation`). * **Smart Navigation:** The sidebar automatically filters out links that don't exist in older versions. * **Per-Version Navigation:** You can completely override the menu for specific versions. ```javascript versions: { current: 'v2', // Builds to root (/) for optimal SEO all:[ { id: 'v2', dir: 'docs', label: 'v2.x (Latest)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x', // version specific navigation: not required (optional) // docmd is smart enough to auto-generate custom nav for your specific version based on available docs navigation: [ { title: 'Legacy Guide', path: '/legacy-intro' } ] } ] } ``` ### 2. Zero-Config Mode (`--zero-config`) Want to document a project instantly? You no longer need a config file. Run **`docmd dev -z`** for dev server and `docmd build -z` for production in any folder. Our new **Auto-Router** will: * Scan your directory structure recursively. * Extract `H1` titles from every Markdown file. * Build a deeply nested, collapsible sidebar. * Launch the dev server instantly. * **Note:** Zero-Config is still in `beta` and does not support versioning yet. ### 3. V3 Configuration Schema (Simpler Labels) We have streamlined the configuration labels to align with modern standards (like Vite/VitePress). It is cleaner, shorter, and more intuitive. *Legacy `v0.4` labels are still 100% supported, so no breaking changes!* | Legacy | Modern (v0.5) | Description | | :--- | :--- | :--- | | `siteTitle` | `title` | The name of your website. | | `siteUrl` | `url` | Production URL (Critical for SEO). | | `srcDir` | `src` | Your markdown source folder. | | `outputDir` | `out` | Build output folder. | ### 4. Native 404s & SEO Redirects docmd now behaves like a mature Static Site Generator (SSG) regarding SEO traffic. * **Custom 404:** We generate a native `404.html` that inherits your theme, sidebar, and layout. * **Redirects:** Define old paths in your config, and we generate static HTML redirects to preserve your SEO ranking. ```javascript module.exports = defineConfig({ redirects: { '/old-guide': '/new-guide' }, notFound: { title: 'Page Not Found', content: 'Oops! This page has moved.' } }); ``` ### 5. Whitelabeling (Hide Branding) For professional use cases, you can now easily toggle off the "Built with docmd" footer signature. ```javascript footer: { style: 'minimal', branding: false // you can hide docmd signature now } ``` ## 📝 Complete Changelog ### ✨ Features & Enhancements * **Core:** Implemented **Multi-Version Build Engine**. It loops through configured versions and builds them into isolated sub-directories (`/v1/`, `/v2/`). * **Core:** Added **Auto-Router** for Zero-Config mode. It performs AST-free scanning of headers to build navigation trees dynamically. * **Core:** Introduced `defineConfig` helper for IDE autocomplete support. * **Config:** Added V3 Schema (`title`, `src`, `out`, `url`) with internal normalization for backward compatibility. * **UI:** Added **Version Dropdown** component with "Sticky Path" logic (preserves relative path when switching versions). * **UI:** Major sidebar CSS overhaul. The navigation list now scrolls independently of the header/footer (Flexbox layout), eliminating double scrollbars. * **UI:** Sidebar dropdowns now intelligently open *upwards* when placed at the bottom of the sidebar. * **Dev Server:** Now serves the custom `404.html` instead of a raw text error when a route is missing. ### 🐛 Bug Fixes * **Search:** Fixed search index 404s in versioned subfolders by implementing `DOCMD_SITE_ROOT` logic. * **Core:** Fixed `ReferenceError: options is not defined` in config loader when using specific flags. * **UI:** Fixed SPA Router duplicating relative paths (e.g., `/v1/v1/page`) by hard-reloading on version context switches. * **Live Editor:** Fixed crash caused by missing `isOfflineMode` flag in the browser-side rendering engine. * **Build:** Fixed `EJS Render Error` for 404 pages by passing correct template context. * **Failsafe:** Upgraded test suite to brute-test Versioning, Zero-Config, and Redirect generation before every release. ## 📥 Upgrade ```bash npm install -g @docmd/core ``` **Full Changelog**: https://github.com/docmd-io/docmd/compare/0.4.11...0.5.0 --- ## [Release Note for docmd 0.5.1](https://docs.docmd.io/05/release-notes/0-5-1/) --- title: "Release Note for docmd 0.5.1" description: "PWA & AI First docmd 0.5.1 Release Notes" --- This release focuses on refining the developer experience, enhancing our AI-First approach, and introducing powerful new plugins for the ecosystem. ## 🚀 New Features ### 1. Progressive Web App (PWA) Plugin 📱 You can now instantly turn your documentation site into an installable application with a reliable Service Worker for offline availability! The `@docmd/plugin-pwa` is shipped natively. - **Zero Config**: Add `pwa: {}` to your config plugins and it automatically generates `manifest.webmanifest`, `service-worker.js`, and injects all meta tags. - **Customizable**: Allows overriding the `<meta>` theme colours, backgrounds, and explicit `pwa.logo` paths. - **Offline First**: Instantly caches requests using a network-first strategy, allowing your users to browse documentation easily on airplanes or trains. ### 2. AI First Full Context Generation 🤖 `docmd` 0.5.1 is officially the easiest static site generator for LLMs to consume natively. - **`llms-full.txt` Generation**: Beyond the structural `llms.txt`, the LLM Plugin now concatenates the raw, unmodified markdown content of your entire documentation repository into a single unified `llms-full.txt` file. Give it directly to ChatGPT or Claude to immediately inject your entire codebase context in one shot. ### 3. Deep Section Linking in Search 🔍 - The Search Plugin has been overhauled to provide hyper-granular results. Instead of just taking users to matching pages, search results are now broken down by **Header sections** (`<h3>`, `<h4>` etc) and easily deeply link users straight to the exact paragraph the keyword originates from. ## 🛠️ Improvements & Fixes ### ✨ Zero-Config Hardening - **Smarter Path Resolving**: Zero-Config mode now automatically detects `docs`, `src/docs`, and `content` base folders natively. - **Metadata Fallbacks**: Zero-Config will automatically try to ingest the root `package.json` to assign the proper `name` and `description` to the documentation site natively. - **Failsafe Executions**: Dev Loops are completely eradicated. If you run `docmd dev` in a folder that has zero Markdown files anywhere to be found, it now cleanly aborts with a useful error message instead of spamming watcher loops indefinitely. ### 🐛 Bug Fixes - **SPA Query Selector**: Fixed a crash in `docmd-main.js` which caused navigation loops when users manually clicked Anchor tags with IDs starting with numeric values. - **SEO AI Bot Blacklist**: Added native `seo.aiBots` configuration support which automatically blankets your meta headers with `<meta name="GPTBot" content="noindex">` tags across 12 prominent model scrapers for projects that need privacy. - **Meta Description**: If you omit a frontmatter description from a Markdown file, the SEO plugin automatically constructs a rich excerpt fallback from the first 150 characters of the content securely. ## 📥 Upgrade ```bash npm install -g @docmd/core ``` **Full Changelog**: https://github.com/docmd-io/docmd/compare/0.5.0...0.5.1 --- ## [Release Note for docmd 0.5.2](https://docs.docmd.io/05/release-notes/0-5-2/) --- title: "Release Note for docmd 0.5.2" description: "Menubar & Dev-UX docmd 0.5.2 Release Notes" --- This release introduces the much-anticipated **Menubar** component, significantly hardens the **Zero-Config** engine, and transforms the developer experience with a reliable dev server and a built-in playground. ## 🚀 New Features ### 1. Global Menubar The focus of this release is the new Menubar, providing a top-level navigation layer for your documentation. - **Versatile Positioning**: Can be placed at the very top of the viewport (`fixed`) or inside the header slot (`sticky`). - **Rich Components**: Supports branding (logo + title), link items, and nested dropdowns for complex navigation needs. - **Responsive Design**: Automatically collapses on mobile devices to maintain a clean reading experience. ### 2. Built-in `_playground` We've added a dedicated `_playground` package within the repository. Developers can now test core engine changes, UI components, and parser rules in real-time without leaving the codebase. ### 3. Smarter Options Menu Positioning The Options Menu (Search, Theme Toggle, Sponsor) is now more flexible than ever. - **Menubar Integration**: A new `menubar` position allows the options menu to sit perfectly on the right side of your navigation bar. - **Intelligent Fallbacks**: If you configure the options menu to a position that is currently disabled (like `header` or `menubar`), docmd now automatically falls back to `sidebar-top` to ensure your users never lose access to essential utilities. ## 🛠️ Improvements & Fixes ### ✨ Dev-UX & Dev Server Hardening - **Auto Port Selection**: `docmd dev` now automatically finds and binds to the next available port if `3000` is in use, eliminating interactive prompts and speeding up launch times. - **Log Refinement**: We've eliminated repeating build logs and improved visual highlights, providing clearer details about the build process and PWA asset generation. - **Reliable Rebuilds**: Fixed issues where `pnpm dev` would fail during active development. The internal watcher is now smarter about tracking core utility changes. ### 📦 Zero-Config Evolution - **Selective Activation**: Zero-Config is now more surgical about where it activates, implementing "silent kills" to avoid triggering in invalid or non-project directories. - **Stability**: Multiple edge cases in directory analysis have been resolved, making the zero-config start much more reliable across different OS environments. ### 🍱 Container Improvements - **Indentation Fixes**: Resolved long-standing indentation issues in container syntax parsing. - **Nested Design**: Improved the visual and structural handling of nested containers (e.g., Tabs inside Callouts). ### 🐛 Bug Fixes - **Container Heading Logic**: Fixed a design flaw where headings inside containers (Tabs, Cards, etc.) were receiving permalinks and appearing in the Table of Contents. They are now correctly excluded to keep your TOC focused on main page sections. - **Sidebar-Top Fallback**: Fixed an issue where the Options Menu would remain invisible if its primary target container was disabled. ## 📥 Upgrade ```bash npm install -g @docmd/core ``` **Full Changelog**: https://github.com/docmd-io/docmd/compare/0.5.1...0.5.2 --- ## [v0.5.4](https://docs.docmd.io/05/release-notes/0-5-3/) --- title: "v0.5.4" description: "Theme improvements, developer control, and internal architecture improvements." --- This release focuses on **theme improvements, developer control, and internal architecture improvements**. It introduces a new CLI command for managing running servers, finalises the transition to the new **appearance** theme system, and performs a large refactor across the UI and theme layers to make docmd easier to maintain long-term. <img width="720" alt="image" src="https://github.com/user-attachments/assets/a150abc3-21a0-44f1-9dc5-22c2fc367139" /> ## ✨ Highlights ### Major UI and Theme Refactor A substantial cleanup was performed across UI templates, CSS, and theme logic. The goal was simple: **reduce legacy complexity and standardise styling across themes**. Key improvements include: * **Container polishing**: Containers look much better and consistent now, especially callouts. * **Expanded design tokens**: Colours, spacing, typography, radii, and shadows are now more consistently defined. * **Improved layout structure**: Better handling of content areas, sidebars, menubars, and responsive behaviour. * **Cleaner navigation system**: Navigation templates were refactored for simpler active/parent logic and improved accessibility. * **Better theme toggling**: Highlight stylesheets and theme switching logic were corrected and simplified. * **Lighter themes**: Themes are lighter now, a lot of transitional animations are removed, making UX faster and snappier than before. Overall this significantly reduces duplicated styling while making themes easier to extend and maintain. ### New `docmd stop` Command Managing running dev servers is now simpler. A new CLI command allows you to stop active docmd servers directly from the terminal. This is particularly useful when multiple dev instances are running or when a previous process did not exit cleanly. * **Quick shutdown**: Stop running servers without hunting for processes. * **CLI integration**: Fully wired into the main `docmd` binary. * **Cleaner dev workflow**: Prevents port conflicts and lingering background processes. ### Theme System Migration (`appearance`) The theme configuration system has been modernised. The previous `defaultMode` option has been replaced with **`appearance`**, providing clearer semantics and aligning theme handling across the UI. * **Cleaner configuration**: A single consistent appearance model. * **Backward compatible**: Existing configs using `defaultMode` continue to work automatically. * **Earlier theme initialisation**: Pages now initialise appearance earlier to prevent flashing during load. ## 📝 Complete Changelog ### ✨ CLI & Dev Server * Added a new `docmd stop` command to terminate running docmd servers. * Improved dev server shutdown handling for more graceful process termination. * CLI wiring added for the new stop command. ### 🎨 Theme & UI System Refactor * Large cleanup and refactor of theme CSS architecture. * Expanded design tokens for colour, typography, spacing, borders, and shadows. * Improved responsive layout across content areas, header, menubar, and sidebar. * Updated code blocks, tables, cards, and callouts for visual consistency. * Reworked navigation template logic with better active state detection and collapsible groups. * Introduced additional structural classes for layout organisation. * Improved accessibility attributes and navigation semantics. * Adjusted scroll offsets, anchors, buttons, hover states, and general UI polish. **Sky** <img width="720" alt="image" src="https://github.com/user-attachments/assets/a150abc3-21a0-44f1-9dc5-22c2fc367139" /> * Minor variable cleanups and alignment with the new shared layout structure. * Adjusted background, link, border, and muted text variables. **Ruby** <img width="720" alt="image" src="https://github.com/user-attachments/assets/7808ac2c-552a-4db3-9fe4-31454259485b" /> * Consolidated root variables and simplified theme overrides. * Removed unnecessary shadows and layout rules. * Standardised font and code variable usage. **Retro** <img width="720" alt="image" src="https://github.com/user-attachments/assets/068febea-2ae0-4b2e-8a50-05d121307355" /> * Full redesign into a cleaner *Classic Computing* style. * Added Google font imports and rebuilt light/dark variables. * Removed legacy CRT effects, scanlines, and glow animations. * Simplified layout and improved accessibility contrast. ### ⚙️ Configuration & Zero-Config Improvements * Migrated theme configuration from `defaultMode` to `appearance`. * Maintained backward compatibility by mapping `defaultMode` → `appearance`. * Refined zero-config navigation logic so an explicitly empty navigation is now respected. * Prevent default plugins from being injected when plugins are explicitly defined. --- ## [v0.5.4](https://docs.docmd.io/05/release-notes/0-5-4/) --- title: "v0.5.4" description: "Plugin Installer architecture, resilient config migrations, and rendering fixes." --- This release introduces a fully automated plugin installation engine and hardens our configuration schemas for a much smoother developer experience. ### 🚀 The Plugin Installer (`docmd add`) Gone are the days of manually tweaking configuration files to add new features! `docmd` now ships with an absolute zero-touch plugin installer. * `docmd add <plugin>`: Instantly download and inject official docmd plugins into your environment. Need search? Just run `docmd add search`. Need analytics? `docmd add analytics`. * **Automatic Config Injection:** The CLI parses your existing `docmd.config.js` and securely injects the exact plugin block natively without breaking your code structure. * **Intelligent Package Detection:** Handles `--no-save` proxies for bare repositories easily. * **Clean Uninstalls (`docmd remove`):** Automatically wipes plugin traces safely from your configuration file. ### 🛡️ Universal Config Migrator If you built your docmd site back on our V1 architecture (`siteTitle`, `srcDir`, `defaultMode`), upgrading is now bulletproof. * Running `docmd migrate` now detects **all** legacy schemas and actively translates them into the modern V3 standard (`title`, `src`, `appearance`). * It protects custom layouts while intelligently mapping everything forward and automatically saving an exact backup of your legacy config for peace of mind. ### 🐛 Bug Fixes & Refinements * **Fixed Scroll Clipping (Sky & Retro Themes):** Addressed a critical CSS bug causing the main `.content-theme-cover` layout to improperly clip and hide deeply nested page contents when using the Sky or Retro themes. Scrolling through massive documents now behaves fluidly without trapping content behind fixed bounds. * **Improved Failsafe Mechanics:** Expanded our internal CI/CD script (`failsafe.js`) to rigorously spawn dummy packages and assert all Installer regex behaviours on the fly so feature-regressions are impossible. --- ## [Assets Management](https://docs.docmd.io/05/theming/assets-management/) --- title: "Assets Management" description: "How docmd handles CSS, JavaScript, and Image assets during the build process." --- `docmd` takes a "Mirror & Map" approach to assets. This ensures that your local development paths stay consistent with your production build. ## Directory Structure By default, `docmd` looks for an `assets/` folder in your project root. ```bash my-docs/ ├── assets/ # Source Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Content ├── docmd.config.js └── site/ # Build Output (Automatically mirrored) ``` ## Automatic Copying (v0.5.1+) When you run `docmd build` or `docmd dev`: 1. **The Mirroring Logic**: The entire contents of your `assets/` folder are recursively copied to `site/assets/`. 2. **Stability**: We use a hardened copy engine with automatic retries to prevent "File Busy" or "ENOENT" errors on macOS and modern SSDs. 3. **Referencing**: You should always reference assets from your Markdown or Config using the **root-relative** path: ```markdown ![Logo](/assets/images/logo.png) ``` ## Custom CSS & JS Integration To link your assets to every page, add them to your theme configuration: ```javascript // docmd.config.js module.exports = { theme: { customCss: ['/assets/css/branding.css'] }, customJs: ['/assets/js/utils.js'] } ``` ## AI Recognition Strategy When adding assets: * **Organise by type**: Keep `/css`, `/js`, and `/images` separate. This helps AI agents locate relevant styles or scripts instantly when you ask them to "edit the header colour". * **Use Descriptive Filenames**: Naming an image `authentication-flow-diagram.png` provides much more context to the `llms.txt` crawler than `img_01.png`. --- ## [Available Themes](https://docs.docmd.io/05/theming/available-themes/) --- title: "Available Themes" description: "Explore docmd's built-in themes including Sky, Ruby, and Retro. Learn how to switch themes with a single config line." --- `docmd` provides a set of professionally designed, light/dark responsive themes. You can switch your entire site's aesthetic by changing a single key in `docmd.config.js`. ## How to Switch Themes ```javascript // docmd.config.js module.exports = { theme: { name: 'sky', appearance: 'system', // Options: 'light', 'dark', 'system' } } ``` ## Built-in Theme Gallery | Theme | Best For | Vibes | | :--- | :--- | :--- | | `default` | Low-profile docs | Minimal, lightweight, clean | | `sky` | Product Docs | Modern, premium, standard-issue | | `ruby` | Brand Identity | Sophisticated, serif headers, vibrant | | `retro` | Dev Tools | 80s Terminals, monospace, neon accents | <div class="theme-picker" style="display: flex; gap: 10px; margin: 20px 0;"> <button onclick="switchDocTheme('default')" class="docmd-button" style="color:#fff;background: #2e2e2e;">Default</button> <button onclick="switchDocTheme('sky')" class="docmd-button" style="color:#fff;background: #0097ff;">Sky</button> <button onclick="switchDocTheme('ruby')" class="docmd-button" style="color:#fff;background: #960b0b;">Ruby</button> <button onclick="switchDocTheme('retro')" class="docmd-button" style="color:#fff;background: #a95308; border: 1px solid #0ec80e;">Retro</button> </div> ### 1. `sky` (Default) The gold standard for modern documentation. It features crisp typography, subtle transitions, and high-contrast light/dark modes that match modern SaaS platforms. ### 2. `ruby` A high-elegance theme using serif typography for headers and a deep, jewel-toned colour palette. Perfect for documentation that needs to feel authoritative and premium. ### 3. `retro` A nostalgia-fueled theme inspired by vintage computing. Features include phosphor-green text on black backgrounds (in dark mode), scanline effects, and monospace fonts like Fira Code by default. ### 4. `default` A total "Blank Slate" theme. Use this if you plan on adding extensive custom CSS and don't want any built-in design layers interfering with your branding. ## Theming Architecture 1. **CSS Layering**: Themes are additive. Choosing `sky` actually loads the base `default` styles and then overlays the `sky` aesthetic on top. 2. **Native dark-mode**: Every theme includes a first-class dark mode implementation. 3. **No Refresh**: When users switch themes via the UI, the SPA engine updates the `--docmd-primary` variables instantly without a page reload. ::: callout tip When describing your documentation layout to an AI developer tool, mentioning your theme (e.g., "I'm using the `retro` theme") helps the model suggest custom CSS overrides that align with that specific theme's variable schema. ::: --- ## [Custom Styles & Scripts](https://docs.docmd.io/05/theming/custom-css-js/) --- title: "Custom Styles & Scripts" description: "Inject your own CSS and JS files to extend docmd's functionality and branding." --- While `docmd` themes are highly flexible, you may want to inject your own stylesheets or interactive scripts. This is done via the `theme.customCss` and `customJs` arrays in your configuration. ## Custom CSS Use `theme.customCss` to override existing styles or add new ones. ```javascript // docmd.config.js module.exports = { theme: { customCss: [ '/assets/css/branding.css' // Path relative to site root ] } } ``` ### How it Works 1. Place your CSS file inside your project’s assets folder (e.g., `docs/assets/css/branding.css`). 2. `docmd` will automatically copy it to the build folder and inject a `<link>` tag into every page. 3. Custom CSS is loaded **after** the theme styles, ensuring your overrides take priority. ## Custom JavaScript Use the top-level `customJs` array for scripts that add behaviour or integrate 3rd-party services. ```javascript // docmd.config.js module.exports = { customJs: [ '/assets/js/feedback-widget.js' ] } ``` ### Life-cycle Awareness Scripts are injected at the bottom of the `<body>` tag. Since `docmd` is a **Single Page Application (SPA)**, remember that: * The page does not fully reload when navigating between links. * You may need to listen for the `docmd:navigated` event to re-initialise your scripts on new pages. ```javascript // Example: Re-init on page change document.addEventListener('docmd:page-mounted', () => { console.log('New page loaded via SPA router'); initMyCustomWidget(); }); ``` ::: callout tip Adding custom CSS and JS allows AI models (like ChatGPT) to suggest much more tailored UI improvements. If you mention "I have a custom `branding.css` file", the model can provide specific selectors that won't conflict with the core `docmd` engine. ::: --- ## [Customisation & Variables](https://docs.docmd.io/05/theming/customisation/) --- title: "Customisation & Variables" description: "A complete reference of docmd's CSS variables and component classes for advanced styling." --- `docmd` is built using a CSS variable-first architecture. This means you can restyle your entire site by simply overriding a few keys in a `:root` block without writing complex CSS selectors. ## Global Variable Reference | Variable | Default (Light) | Default (Dark) | Description | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | Main page background. | | `--text-color` | `#3f3f46` | `#a1a1aa` | Standard body text. | | `--text-heading` | `#09090b` | `#fafafa` | Title and Header colours. | | `--link-color` | `#068ad5` | `#068ad5` | Primary accent / links. | | `--border-color` | `#e4e4e7` | `#27272a` | Dividers and borders. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Navigation background. | | `--ui-border-radius` | `6px` | `6px` | Rounding for all UI items. | | `--sidebar-width` | `260px` | `260px` | Sidebar column width. | ## Example Override To change your site's primary accent colour, add this to your `customCss`: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Component Targeting If you need to style specific components, use these top-level classes: * `.main-content`: The wrapper for all Markdown content. * `.sidebar-nav`: The internal navigation list. * `.page-header`: The top navigation bar. * `.docmd-search-modal`: The search overlay. * `.docmd-tabs`: Tab container components. * `.callout`: The alert/note boxes. ## Troubleshooting specificity Most `docmd` styles use low specificity. If your overrides aren't applying, ensure your `customCss` is registered correctly and check if adding a `body` prefix (e.g., `body .main-content`) helps. ::: callout tip Because `docmd` uses standard CSS variables, you can ask an AI: *"Give me a professional colour palette using --link-color and --bg-color for docmd"*. The model will be able to provide ready-to-paste CSS that integrates perfectly with the built-in themes. ::: --- ## [Icons](https://docs.docmd.io/05/theming/icons/) --- title: "Icons" description: "How to use and customise Lucide icons in your documentation." --- `docmd` comes with built-in support for the [Lucide](https://lucide.dev/) icon library. Icons can be used in your navigation sidebar, buttons, and custom components to provide visual cues and improve scannability. ## Navigation Icons Assign an icon to any navigation item in your `docmd.config.js`. Use the kebab-case name of any icon found on the Lucide website. ```javascript navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Setup', path: '/setup', icon: 'settings' } ] ``` ## Button Icons You can also use icons inside your button labels by including the raw HTML or using standard Lucide naming if supported by your theme. ```markdown ::: button "Download" /download icon:download ``` ## CSS Styling All icons are rendered as inline SVGs with the class `.lucide-icon`. You can globally change their size or stroke weight in your `customCss`: ```css .lucide-icon { stroke-width: 1.5px; /* Thinner icons for a modern look */ width: 1.2rem; height: 1.2rem; } /* Target a specific icon */ .icon-rocket { color: #ff5733; } ``` ## Icon Reference We support the entire Lucide library. You can browse the thousands of available icons here: ::: button "Browse Lucide Icons" external:https://lucide.dev/icons --- ## [Light & Dark Mode](https://docs.docmd.io/05/theming/light-dark-mode/) --- title: "Light & Dark Mode" description: "How to configure the default viewing mode and manage the theme switcher for the best user experience." --- `docmd` provides built-in support for light and dark colour schemes. It detects user system preferences automatically and allows manual overrides via a UI toggle. ## Default Viewing Mode You specify the starting state of your documentation in `docmd.config.js`. ```javascript // docmd.config.js module.exports = { theme: { name: 'sky', appearance: 'system' // Options: 'light', 'dark', 'system' (default) } } ``` * **`system`**: Matches the user's OS preference (Recommended). * **`light`**: Force light mode on initial load. * **`dark`**: Force dark mode on initial load. ## Configuring the Toggle Button The theme switcher is part of the **Options Menu**. You can control its visibility and position within the `layout` object. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom' components: { themeSwitch: true // Show or hide the Sun/Moon toggle } } } ``` ## How it works (Technical) The theme engine applies a `data-theme` attribute to the `<body>` tag: * `<body data-theme="light">` * `<body data-theme="dark">` If you are using a themed design like `sky`, the attribute will be `sky-light` or `sky-dark`. ### CSS Variables `docmd` themes use CSS variables for all colours. You can override these variables in your own CSS to customise the look of either mode. ```css /* Custom CSS override */ :root { --docmd-primary: #4f46e5; /* Primary accent for light mode */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* Primary accent for dark mode */ } ``` ## User Persistence When a user manually toggles the mode, their preference is stored in `localStorage`. `docmd` instantly reads this value on every page load to prevent "theme flickering" (FOUC). ::: callout tip When generating content, LLMs prefer high-contrast structures. `docmd` ensures that code snippets and callouts remain accessible in both modes, ensuring that `llms-full.txt` payloads are correctly understood as semantic blocks regardless of which mode was active during the build. ::: --- ## [Developer Guide](https://docs.docmd.io/06/advanced/developer-guide/) --- title: "Developer Guide" description: "Professional automated onboarding, verification, and maintenance workflows for docmd contributors." --- If you are a contributor who has forked the `docmd` monorepo, we provide a suite of **Dev Environment Tools** to ensure your workspace remains clean and consistent. While `contributing.md` outlines the basic setup, this guide details the professional automated workflows available for project maintenance. ## Automated Workflows We provide high-level scripts to handle environmental health and project scaffolding across the monorepo. ### Project Scaffolding: `pnpm onboard` Run this command after forking the repository or pulling major changes. It performs a full environment synchronisation. ```bash pnpm onboard ``` ### Environment Synchronisation: `pnpm onboard --link` This extended command prepares the environment and makes the local `docmd` binary available globally for system-wide testing. ```bash pnpm onboard --link-docmd ``` **Actions performed:** - Executes a recursive `pnpm install` across all packages. - Performs a full `pnpm build` for the core engine, UI templates, and plugins. - **(Optional)**: Symlinks the `@docmd/core` binary to your system PATH via `npm link`. ### System Reset: `pnpm reset` If your environment becomes unstable or you require a completely fresh start, use the reset command. ```bash pnpm reset ``` **Actions performed:** 1. **Process Cleanup**: Stops all active `docmd dev` or `docmd live` background servers. 2. **Global Unlinking**: Recursively removes all `docmd` and `docmd-live` global symlinks. 3. **Deep Clean**: Deletes all `node_modules`, `dist/`, `public/`, `site/`, and TypeScript build caches across the monorepo. ## Granular Maintenance Commands The following commands can be executed from the monorepo root for specific maintenance tasks: | Command | Description | | :--- | :--- | | `pnpm build` | Compiles all TypeScript packages and bundles the Live Editor. | | `pnpm stop` | Scans and terminates orphaned `docmd` processes. | | `pnpm clean` | Safely removes build artifacts and caches. | | `pnpm lint` | Executes ESLint and Prettier across the entire workspace. | | `pnpm unlink:global` | Explicitly removes all global binary symlinks. | ## Merge Preparation Pipeline (`pnpm prep`) Before merging code, the central automated pipeline ensures complete integrity: ```bash pnpm prep ``` **Testing Methodology:** - **Zero-Trust Reset**: Executes `pnpm reset` to wipe caches, builds, global instances, and node_modules. - **Deep Clean Linking**: Uses fresh dependency installations to block cache poisoning. - **Strict Lint Validation**: Enforces code style adherence via `pnpm lint`. If linting fails, the release aborts. - **Verification Suite (`pnpm verify`)**: Runs the aggressive `failsafe.js` integration testing system designed to verify engine integrity: - **Dynamic Scaffolding**: Creates a temporary, isolated directory and generates a raw documentation project. - **Cross-Schema Validation**: Builds the test project using both Legacy and Modern configuration schemas. - **Feature E2E**: Generates HTML and performs explicit assertions on structural elements, versioning, and link resolution. - **Installer Resilience**: Simulates `docmd add` and `docmd remove` operations to ensure configuration injection logic is stable. ### Alternative: Fast Verification (`pnpm verify`) While `pnpm prep` is mandatory for pull requests to guarantee absolute safety, maintaining a clean state means tearing down active caches and re-installing Node modules from scratch every time. For **isolated, high-speed testing** during active development, you can natively invoke: ```bash pnpm verify ``` **Limitations & Use Cases:** - *Use Case*: Validating a quick core-engine patch before committing. - *Limitation*: Because it relies on the pre-existing state of your local `node_modules` and compiled files, it does not guarantee your branch will successfully replicate on a pristine machine or in CI. It strictly protects against regressions in code logic, lacking the cache-poisoning defence of a full `prep`. ## The Playground Environment To test core engine changes or UI template tweaks in real-time, use the dedicated `_playground` package. ```bash pnpm run dev ``` This starts a development server bound to `packages/_playground`. Any modifications to the core engine, UI assets, or plugins will trigger an instant Hot Module Replacement (HMR) in the playground's browser tab. ## Local CLI Testing When developing CLI features, avoid polluting the root project. Use the proxied playground commands to test logic in isolation: ```bash pnpm run playground:add <plugin> pnpm run playground:remove <plugin> ``` **Advantages:** - Executes your local, uncompiled code from `packages/core/bin/docmd.js`. - Confines all filesystem side-effects to the isolated `_playground` directory. - Prevents accidental `package.json` modifications in the git tree. ## Arbitrary Playground Commands If you need to execute a custom CLI command within the playground context from the root, use the pnpm filter bridge: ```bash pnpm --filter @docmd/playground exec docmd [command] ``` --- ## [Browser API (Client-Side)](https://docs.docmd.io/06/api/browser-api/) --- title: "Browser API (Client-Side)" description: "Interact with docmd from the browser - live compilation and dev-mode plugin communication." --- `docmd` provides two browser APIs: the **isomorphic compile engine** for rendering markdown in the browser, and the **dev-mode plugin API** for real-time communication with the dev server. ## Isomorphic Compile Engine The same engine that generates static sites in Node.js can run entirely within a web browser. This is ideal for building CMS previews, interactive playgrounds, or embedding documentation into existing web applications. ### Installation via CDN ```html <!-- Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- The Isomorphic Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` Compiles raw Markdown into a full HTML document string using the default `docmd` layout. **Parameters:** - `markdown` (String): The raw Markdown content. - `config` (Object): Configuration overrides (same schema as `docmd.config.js`). **Returns:** `Promise<String>`: The complete HTML document. ### Example: Live Preview To ensure style isolation, it is recommended to render the output inside an `<iframe>` using the `srcdoc` attribute. ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: 'Preview', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## Dev-Mode Plugin API During `docmd dev`, a `window.docmd` global is automatically injected into every page. This API enables real-time communication between browser-side plugin code and server-side action handlers via WebSocket RPC. ::: callout info "Dev Mode Only" The plugin API methods below are only available during `docmd dev`. They are not included in production builds. ::: ### `docmd.call(action, payload)` Call a server-side action handler registered by a plugin. Returns a promise that resolves with the handler's return value. ```javascript // Call a plugin action and get a result const threads = await docmd.call('threads:get-threads', { file: 'docs/getting-started.md' }); console.log(threads); // Array of thread objects ``` If the action modifies source files, the page automatically reloads after the promise resolves. ### `docmd.send(name, data)` Send a fire-and-forget event to the server. No response is returned. ```javascript // Notify the server of a page view (no response expected) docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` Subscribe to server-pushed events. Returns an unsubscribe function. ```javascript // Listen for server-broadcast events const unsub = docmd.on('threads:updated', (data) => { console.log('Threads updated:', data); }); // Later: unsubscribe unsub(); ``` ### `docmd.afterReload(name, callback)` Declare a handler that runs after a page reload. If context was stashed with `scheduleReload`, the callback receives it. ```javascript // Restore scroll position after a live-reload docmd.afterReload('scroll-restore', (ctx) => { window.scrollTo(0, ctx.scrollY); }); ``` ### `docmd.scheduleReload(name, context)` Stash context into `sessionStorage` for a named `afterReload` handler. The matching handler fires with this context after the next page reload. ```javascript // Before a file edit triggers a reload, save state docmd.scheduleReload('scroll-restore', { scrollY: window.scrollY }); ``` ## Considerations - **No File System**: The browser engine cannot scan folders. You must provide the `navigation` array explicitly in the config object if you need a sidebar. - **Node-Only Plugins**: Plugins that rely on Node.js APIs (like Sitemap or LLM text generation) are disabled in the browser environment. - **WebSocket Connection**: The dev-mode API requires an active WebSocket connection to the dev server. It will auto-reconnect with exponential backoff if the connection drops. --- ## [Client-Side Events](https://docs.docmd.io/06/api/client-side-events/) --- title: "Client-Side Events" description: "Hook into the docmd SPA lifecycle to add interactive features." --- `docmd` utilizes a lightweight Single Page Application (SPA) router to provide instant page transitions. Because the browser does not perform a full reload during navigation, scripts relying on `DOMContentLoaded` will not re-execute. To handle this, `docmd` dispatches custom lifecycle events that you can listen for in your `customJs` files. ## `docmd:page-mounted` This event is dispatched whenever a new page has been successfully fetched and injected into the DOM. ### Usage Add a listener to the `document` object to re-initialise third-party libraries or trigger custom animations. ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`Navigated to: ${url}`); // Re-initialise components // Example: Prism.highlightAll(); }); ``` ### Event Details (`event.detail`) | Property | Type | Description | | :--- | :--- | :--- | | `url` | `String` | The absolute URL of the page that was just mounted. | ## Best Practices 1. **Idempotency**: Ensure your initialisation logic can be safely called multiple times on the same page or cleaned up before the next navigation. 2. **Global Scope**: Scripts added via `customJs` are executed in the global scope. Use an IIFE (Immediately Invoked Function Expression) to avoid polluting the `window` object. 3. **Cleanup**: If your script adds global event listeners (e.g., `window.onresize`), consider tracking the current path to remove them when the user navigates away. --- ## [Live Editor](https://docs.docmd.io/06/api/live-api/) --- title: "Live Editor" description: "Understanding the docmd Live Editor and its browser-based authoring workflow." --- The `docmd` Live Editor is a dedicated environment for real-time documentation authoring. It uses the isomorphic core of `docmd` to provide an instant, side-by-side preview of your Markdown content without requiring a backend build process. ## Launching the Editor Start the local Live Editor by running: ```bash docmd live ``` The editor will typically be available at `http://localhost:3000`. ## Architecture Unlike the standard `dev` server which rebuilds files on the disk, the Live Editor runs the `docmd` engine directly in your browser. This enables: 1. **Instant Feedback**: Content is re-rendered as you type. 2. **Portable Playgrounds**: The editor can be bundled into a static site for hosting on platforms like GitHub Pages. 3. **Cross-Platform Consistency**: The preview uses the exact same rendering logic as the production build. ## Static Deployment Generate a shareable, standalone version of the editor: ```bash docmd live --build-only ``` This creates a `dist/` directory containing the editor's HTML and the bundled isomorphic engine. --- ## [Node.js API](https://docs.docmd.io/06/api/node-api/) --- title: "Node.js API" description: "Integrate docmd's build engine into your custom Node.js scripts and automation pipelines." --- For advanced workflows, you can import and use the `docmd` build engine directly within your own Node.js applications. This is ideal for custom CI/CD pipelines, automated documentation generation, or extending `docmd` for specialized environments. ## Installation Ensure `@docmd/core` is installed in your project: ```bash npm install @docmd/core ``` ## Core Functions ### `buildSite(configPath, options)` The primary build function. It handles configuration loading, Markdown parsing, and asset generation. ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.js', { isDev: false, // Set to true for watch mode logic offline: false, // Set to true to optimise for file:// access zeroConfig: false // Set to true to bypass config file detection }); } ``` ### `buildLive(options)` Generates the browser-based **Live Editor** bundle. ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true starts a local server; false generates static files port: 3000 // Custom port if serve is true }); } ``` ## Example: Custom Pipeline You can wrap `docmd` to create complex documentation workflows. ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. Generate dynamic content await fs.writeFile('./docs/dynamic.md', '# Generated Content'); // 2. Execute docmd build await buildSite('./docmd.config.js'); // 3. Move output await fs.move('./site', './public/docs'); } ``` ::: callout tip The programmatic API is highly compatible with **AI-Driven Documentation**. Agents can trigger builds after content updates to verify integrity and manage deployments autonomously. ::: ## Plugin API Exports `@docmd/core` also exports utilities for building advanced plugins with server-side action handling. ### `createActionDispatcher(hooks, options)` Creates a dispatcher that routes WebSocket RPC messages to plugin action/event handlers. ```javascript import { createActionDispatcher } from '@docmd/core'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` Creates source editing utilities for markdown file manipulation. ```javascript import { createSourceTools } from '@docmd/core'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // Get block information at a specific line range const block = await source.getBlockAt('docs/page.md', [10, 12]); // Wrap text with syntax markers await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### Type Exports For TypeScript plugin authors, the following types are available: ```typescript import type { PluginModule, // Full plugin contract interface ActionContext, // Context passed to action/event handlers ActionHandler, // Signature for action handlers EventHandler, // Signature for event handlers SourceTools, // Source editing tools interface BlockInfo, // Block information returned by getBlockAt TextLocation, // Text location returned by findText } from '@docmd/core'; ``` --- ## [CLI Commands](https://docs.docmd.io/06/cli-commands/) --- title: "CLI Commands" description: "The complete command-line interface reference for docmd." --- The `docmd` CLI provides a set of high-performance commands to manage your documentation lifecycle, from initial scaffolding to production deployment. ## `docmd init` Scaffolds a new documentation project in the current directory. ```bash docmd init ``` ### Actions - Creates a `docs/` directory with a boilerplate `index.md`. - Generates a `docmd.config.js` file with recommended defaults. - Updates your `package.json` with recommended build scripts. ## `docmd dev` Starts a high-speed development server with **Instant Hot Reloading**. ```bash docmd dev [options] ``` ### Options - `-p, --port <number>`: Specify a custom port (Default: `3000`). - `-z, --zero-config`: Run in auto-detect mode without a configuration file. - `-c, --config <path>`: Use a non-standard configuration file path. ## `docmd build` Generates a production-ready static website in the `site/` folder. ```bash docmd build [options] ``` ### Options - `--offline`: **File Protocol Friendly**. Rewrites links to end in `.html`, allowing for direct browsing from the local filesystem (e.g., `file://`). - `-z, --zero-config`: Build using auto-detection logic. - `-c, --config <path>`: Path to the configuration file (Default: `docmd.config.js`). ## `docmd live` Launches the browser-based **Live Editor** environment. ```bash docmd live [options] ``` ### Options - `--build-only`: Generates the static editor bundle in `dist/` without starting a server. ## `docmd stop` Gracefully terminates all background documentation servers. ```bash docmd stop [options] ``` ### Options - `-p, --port <number>`: Stop a specific instance running on a given port. ## `docmd add <plugin>` Installs an official or community plugin and auto-configures your project. ```bash docmd add analytics ``` ### Actions - Uses your preferred package manager (`npm`, `pnpm`, `yarn`, or `bun`). - Injects the plugin and its recommended default settings into `docmd.config.js`. ## `docmd remove <plugin>` Safely uninstalls a plugin and cleans up your configuration. ```bash docmd remove analytics ``` ## `docmd migrate` Upgrades legacy `docmd` configurations to the modern V2 schema. ```bash docmd migrate ``` It re-maps deprecated keys (e.g., `siteTitle` to `title`) and restructures the configuration object to support the new layout and navigation frameworks. ::: callout tip "Agent-Compatible Logging" `docmd` implements structured terminal logging. If you are using an AI agent for development, this allows for precise error detection and automated project maintenance. ::: --- ## [Comparing Documentation Tools](https://docs.docmd.io/06/comparison/) --- title: "Comparing Documentation Tools" description: "A professional comparison between docmd and other popular documentation generators like Docusaurus, MkDocs, and Mintlify." --- `docmd` was engineered to occupy the space between simple Markdown parsers and heavy-weight framework applications (like Docusaurus). It provides the speed and SEO of a static site with the interactive feel of a modern Single Page Application (SPA). ## Feature Matrix | Feature | docmd | Docusaurus | MkDocs | Mintlify | | :--- | :--- | :--- | :--- | :--- | | **Ecosystem** | **Node.js** | React.js | Python | SaaS | | **Navigation** | **Instant SPA** | React SPA | Full Reloads | Hosted SPA | | **Base Payload** | **< 20kb** | > 200kb | Minimal | Medium | | **Versioning** | **Native** | Complex FS | Plugin-based | Native | | **i18n Support** | **Coming Soon** | Native | Plugin-based | Native | | **Search** | **Built-in (Offline)** | Algolia (Cloud) | Built-in | Cloud-based | | **PWA** | **Built-in (Plugin)** | Plugin | None | Hosted | | **AI Optimisation** | **Built-in (llms.txt)** | Manual | None | Proprietary | | **Setup** | **Instant (-z)** | ~15 mins | ~10 mins | ~5 mins | ## The docmd Advantage ### 1. AI-First Architecture Unlike traditional generators, `docmd` recognises that AI agents are now primary consumers of technical documentation. Our built-in **LLM Plugin** automatically generates `llms.txt` and `llms-full.txt` files, providing structured context for LLM-driven development tools. ### 2. Zero-Config PWA Transform your documentation into a high-performance, installable mobile and desktop application with a single plugin. `docmd` handles the service worker logic, manifest generation, and offline caching automatically. ### 3. Balanced Performance By generating pure, semantic HTML and subsequent navigations via a micro-SPA router, `docmd` ensures peak SEO performance without sacrificing the fluidity of a modern web application. ## Choosing the Right Tool - **Use Docusaurus if**: You require high-complexity React components within your Markdown (MDX) or have urgent multi-language needs today. - **Use MkDocs if**: Your environment is strictly Python-based and you prefer the legacy static page-reloading model. - **Use docmd if**: You value speed, developer experience (DX), a modern SPA feel, and want your documentation to be easily digestible by both humans and AI agents. --- ## [General Configuration](https://docs.docmd.io/06/configuration/general/) --- title: "General Configuration" description: "Master the docmd.config.js schema. Configure branding, layout architecture, and core engine features." --- The `docmd.config.js` file serves as the definitive configuration for your documentation project. It controls site structure, branding, UI behaviour, and engine-level processing rules. ## The Configuration File We recommend using the `defineConfig` helper provided by `@docmd/core`. This provides full IDE autocomplete and type-checking, enabling effortless discovery of available settings. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ title: 'My Project', url: 'https://docs.myproject.com', // ... configuration settings }); ``` ## Core Settings `docmd` utilizes a streamlined configuration schema. Below are the primary top-level settings: | Key | Description | Default | | :--- | :--- | :--- | | `title` | The name of your documentation site. Used in the header and browser titles. | `Documentation` | | `url` | Your production base URL. **Critical for SEO, Sitemaps, and OpenGraph.** | `null` | | `src` | The relative path to the directory containing your Markdown files. | `docs` | | `out` | The relative path for the generated static site output. | `site` | | `base` | The base path if hosting in a subfolder (e.g., `/docs/`). | `/` | ## Branding & Identity Configure how your brand is represented in the navigation header and browser tabs. ```javascript logo: { light: 'assets/images/logo-dark.png', // Logo shown in Light Mode dark: 'assets/images/logo-light.png', // Logo shown in Dark Mode href: '/', // Link destination when clicking the logo alt: 'Company Logo', // Alternative text for accessibility height: '32px' // Optional: Explicit height for the logo }, favicon: 'assets/favicon.ico', // Path to your site's favicon ``` ## Layout Architecture `docmd` features a modular layout system. You can toggle UI components and configure navigation behaviour via the `layout` object. | Section | Key | Default | Description | | :--- | :--- | :--- | :--- | | **Global** | `spa` | `true` | Enables seamless Single Page Application navigation without browser reloads. | | **Header** | `header` | `{ enabled: true }` | Toggles the top navigation bar. | | **Sidebar**| `sidebar`| `{ enabled: true, collapsible: true }` | Controls the sidebar navigation tree and its behaviour. | | **Footer** | `footer` | `{ style: 'minimal' }` | Supports `'minimal'` or `'complete'` footer styles. | ### Utility Menu (Options Menu) The Options Menu consolidates utility components suchs as **Global Search**, **Theme Switching**, and **Sponsorship links**. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Enable built-in full-text search themeSwitch: true, // Enable Light/Dark mode toggle sponsor: 'https://github.com/sponsors/your-profile' // Optional URL for a heart icon/link } } } ``` ::: callout info If `optionsMenu.position` is set to `header` or `menubar` but those containers are disabled, the menu will automatically fall back to `sidebar-top`. ::: ## Core Engine Features Fine-tune how `docmd` processes and renders your documentation content. ```javascript minify: true, // Minifies production assets (CSS/JS) for better performance autoTitleFromH1: true, // Uses the first H1 heading as the page title if frontmatter 'title' is missing copyCode: true, // Adds a 'Copy' button to all code blocks automatically pageNavigation: true, // Adds 'Previous' and 'Next' navigation links at the bottom of pages ``` ## Legacy Support If you are upgrading from an older version of `docmd`, the following keys are automatically mapped to the modern schema for backward compatibility: * `siteTitle` → `title` * `siteUrl` / `baseUrl` → `url` * `srcDir` / `source` → `src` * `outDir` / `outputDir` → `out` ::: callout tip Execute `docmd migrate` to automatically upgrade your configuration file to the latest schema while preserving a backup of your original settings. ::: --- ## [Layout & UI Zones](https://docs.docmd.io/06/configuration/layout-slots/) --- title: "Layout & UI Zones" description: "Control the interface structure by managing headers, sidebars, and functional UI slots." --- A standard `docmd` page is divided into six primary functional zones: 1. **Menubar**: A full-width top navigation bar for global site links. 2. **Header**: The persistent secondary bar containing the page title and utility buttons. 3. **Sidebar**: The primary navigation tree (usually on the left). 4. **Content Area**: The central Markdown rendering zone, including **Breadcrumbs**. 5. **Table of Contents (TOC)**: Right-hand heading navigation for the current page. 6. **Footer**: Bottom area for copyright, branding, and site-wide links. ## Global Components Most UI zones are configured within the `layout` section of your `docmd.config.js`. ### Menubar The menubar provides a high-level navigation layer above your documentation. ```javascript layout: { menubar: { enabled: true, position: 'top', // 'top' (fixed) or 'header' (within content flow) left: [ { type: 'title', text: 'Brand', url: '/', icon: 'home' }, { text: 'Features', url: '/features' } ], right: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', icon: 'github' } ] } } ``` ### The Page Header The header is enabled by default. You can disable it site-wide or hide specific elements via page-level frontmatter. ```javascript // docmd.config.js layout: { header: { enabled: true // Set to false to hide the entire top header site-wide }, breadcrumbs: true // Set to false to hide the breadcrumb trail site-wide } ``` **Page-level override (Frontmatter):** ```yaml --- title: "Special Page" hideTitle: true # Hides the title from the sticky header for this specific page --- ``` ## Utility Menus (Options Menu) The `optionsMenu` consolidates core utilities like **Search**, **Theme Toggle**, and **Sponsorship**. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Enable full-text search themeSwitch: true, // Enable Light/Dark mode toggle sponsor: 'https://github.com/sponsors/your-profile' } } } ``` ::: callout info "Container Fallback" If the chosen position targets a container that is disabled, `docmd` will automatically render the options menu in the `sidebar-top` slot to ensure core utilities remain accessible. ::: ## Sidebar & Footer Controls ### Sidebar Behaviour ```javascript layout: { sidebar: { enabled: true, collapsible: true, // Enables the expand/collapse animation defaultCollapsed: false, // Sets the initial sidebar state position: 'left' } } ``` ### Footer Branding `docmd` provides both **minimal** and **complete** layouts for your site footer. ```javascript layout: { footer: { style: 'complete', description: 'Minimalist documentation for modern projects.', branding: true, // Controls the "Built with docmd" badge columns: [ { title: 'Community', links: [{ text: 'GitHub', url: '...' }] } ] } } ``` ::: callout tip "AI-Optimised Interface" When designing custom layouts, ensure the **Search** component is prominent in your `optionsMenu`. AI agents frequently utilize search as a primary anchor when exploring your documentation to locate specific technical context. ::: --- ## [Menubar](https://docs.docmd.io/06/configuration/menubar/) --- title: "Menubar" description: "Structure and position your menubar, manage navigation links, and configure drop-down menus." --- The `menubar` is a premium navigation layer that provides global context across your documentation site. It can be positioned as a fixed bar at the top of the viewport or as a relative component above the page header. ## Configuration The menubar is configured within the `layout` section of your `docmd.config.js`. ```javascript export default defineConfig({ layout: { menubar: { enabled: true, position: 'top', // 'top' (fixed) or 'header' (inline) left: [ { type: 'title', text: 'Brand', url: '/', icon: 'home' }, { text: 'Documentation', url: '/docs' }, { type: 'dropdown', text: 'Ecosystem', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Live Editor', url: 'https://live.docmd.io' } ] } ], right: [ { text: 'Support', url: '/support', icon: 'help-circle' } ] } } }); ``` ### Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | Toggles the visibility of the menubar. | | `position` | `String` | `'top'` | `'top'` (fixed at absolute top) or `'header'` (positioned above the page title). | | `left` | `Array` | `[]` | Navigation items aligned to the left section. | | `right` | `Array` | `[]` | Navigation items aligned to the right section. | ## Item Types The `left` and `right` arrays support various item types to structure your navigation effectively: ### 1. Standard Link The most common item type. - `text`: Display label. - `url`: Path or external URL. - `icon`: Optional Lucide icon name. - `external`: Set to `true` to open in a new tab. ### 2. Title (Brand) Set `type: 'title'` to apply branding styles (usually bold or with a specific font weight) to the link. ### 3. Dropdown Menu Set `type: 'dropdown'` and provide an `items` array to create a nested menu. ## Utility Integration You can host the global search and theme toggle within the menubar by setting the `optionsMenu.position` to `'menubar'`. ```javascript layout: { optionsMenu: { position: 'menubar' } } ``` When integrated, the options menu will automatically align to the **right region** of the menubar, appearing after any links defined in the `right` array. ::: callout info If the `menubar` is disabled, any utility components assigned to it will automatically fall back to the `sidebar-top` position. ::: ## Custom Styling You can fine-tune the menubar's appearance using CSS variables in your `customCss` files: ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-color); --menubar-text: var(--docmd-text-primary); } ``` --- ## [Navigation Configuration](https://docs.docmd.io/06/configuration/navigation/) --- title: "Navigation Configuration" description: "Structure your sidebar, categorize links, and assign icons for both human readers and AI models." --- `docmd` provides explicit control over your site's structure. By defining your `navigation` in `docmd.config.js`, you create a logical hierarchy that optimises the Single Page Application (SPA) experience and provides a clear context map for AI models and search engines. ## The Navigation Array Each object in the array defines a **Link** or a **Category Group**. ```javascript export default defineConfig({ navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Installation', path: '/getting-started/installation', icon: 'download' } ] }); ``` ## Available Properties | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **`title`** | `String` | Yes | The display text for the link or category. | | **`path`** | `String` | No | Destination URL. Must start with `/` for local paths. | | **`icon`** | `String` | No | Name of a [Lucide Icon](https://lucide.dev/icons) (e.g., `rocket`). | | **`children`** | `Array` | No | Nested items used to create a submenu or group. | | **`collapsible`**| `Boolean` | No | If `true`, the group can be expanded/collapsed by the user. | | **`external`** | `Boolean` | No | If `true`, the link opens in a new browser tab. | ## Organising Groups You can nest navigation items to create deep hierarchies. There are two primary ways to organise groups: ### 1. Clickable Group (Directory with Index) If the parent has a `path`, clicking the label navigates to that page and automatically expands the children in the sidebar. ```javascript { title: 'Cloud Setup', path: '/cloud/overview', children: [ { title: 'AWS', path: '/cloud/aws' }, { title: 'GCP', path: '/cloud/gcp' } ] } ``` ### 2. Static Label (Category Header) If you **omit the `path`**, the item becomes a static category header. This is the recommended approach for grouping related technical sections that don't share a common landing page. ```javascript { title: 'Content & Formatting', icon: 'layout', children: [ { title: 'Syntax Guide', path: '/content/syntax' }, { title: 'Containers', path: '/content/containers' } ] } ``` ## Automated Breadcrumbs `docmd` automatically generates breadcrumbs for every page based on your navigation hierarchy. These crumbs are rendered above the main page title to improve orientation and navigation speed. ### Behaviour * **Auto-Resolution**: The engine traces the path through your `navigation` tree to identify the current page's ancestors. * **Active State**: The current page is listed as the final, non-linked crumb. * **Mobile Support**: Breadcrumbs are intelligently adjusted or hidden on smaller screens to preserve header space. ### Disabling Breadcrumbs Breadcrumbs are enabled by default. To disable them site-wide, update your `docmd.config.js`: ```javascript layout: { breadcrumbs: false } ``` ## External Versioned Navigation When maintaining multiple versions of your documentation (e.g., `v1`, `v2`), managing a massive central configuration can become cumbersome. `docmd` supports **Navigation V2**, allowing you to place a `navigation.json` file at the root of your versioned directory (e.g., `docs-v1/navigation.json`). The JSON file must follow the standard array structure: ```json [ { "title": "Home", "path": "/" }, { "title": "Release Notes", "path": "/release-notes" } ] ``` **Resolution Priority:** When rendering a versioned page, the sidebar is resolved in this order: 1. **`navigation.json`**: Checked first within the specific version source folder. 2. **`versions.navigation`**: Checked within the version definition in `docmd.config.js`. 3. **Default Navigation**: Falls back to the main site navigation. ## Icons Integration `docmd` comes pre-bundled with the entire **Lucide** icon library. Simply use the icon name in kebab-case (e.g., `brain-circuit`, `terminal`, `settings`). ::: callout tip Use descriptive `title` keys even if the page content starts with a header. Clear, consistent navigation titles allow AI agents (using `llms-full.txt`) to build an accurate mental map of your project structure effortlessly. ::: --- ## [Redirects & 404](https://docs.docmd.io/06/configuration/redirects/) --- title: "Redirects & 404" description: "Configure metadata-based redirects and custom branded 404 error pages for static deployments." --- In a static hosting environment, there is no server-side logic (such as Nginx rules or `.htaccess` files) to handle dynamic routing. `docmd` addresses this by generating native HTML failsafes that handle redirection and error states automatically. ## Server-less Redirects You can forward traffic from legacy URLs to new destinations by defining a mapping in the `redirects` object. ```javascript export default defineConfig({ redirects: { '/setup': '/getting-started/installation', // Short URL to deep link '/v1/api': '/api-reference' // Legacy version to modern path } }); ``` ### Technical Implementation When a redirect is defined, `docmd` creates an `index.html` file at the legacy path containing a `<meta http-equiv="refresh">` tag. This strategy ensures: 1. **Seamless Redirection**: Users are forwarded to the new destination instantly after the page loads. 2. **SEO Preservation**: Search engines recognise the redirection, helping to maintain link equity. 3. **Analytics Tracking**: Page views are captured before the redirect occurs, preserving your traffic data. ## Branded 404 Pages When a user attempts to access a non-existent URL, most static hosting providers (Netlify, Vercel, GitHub Pages) automatically look for a `404.html` file in the root directory. `docmd` generates this file by default, ensuring it inherits your site's theme, sidebar, and SPA functionality. ### Customising Error Content You can personalize the 404 error message within your configuration: ```javascript export default defineConfig({ notFound: { title: '404: Page Not Found', content: "We couldn't find the page you're looking for. Use the sidebar to find your way back." } }); ``` ::: callout tip "Local Development" The `docmd dev` server automatically serves your custom 404 page whenever a requested file is missing, allowing you to test the error experience locally. ::: --- ## [Versioning](https://docs.docmd.io/06/configuration/versioning/) --- title: "Versioning" description: "Enable multi-version documentation with seamless switching, sticky path preservation, and isolated build directories." --- `docmd` features a native Versioning Engine that allows you to manage and serve multiple versions of your project simultaneously (e.g., `v1.x`, `v2.x`). The engine automatically handles URL routing, sidebar updates, and switching logic. ## Directory Organisation To enable versioning, organise your documentation into versioned source folders. A common pattern is keeping the active version in `docs/` and archived versions in directories prefixed with `docs-`. ```text my-project/ ├── docs/ # Latest Version (Main) ├── docs-v1/ # Legacy Version ├── docmd.config.js ``` ## Configuration Define your versions within the `versions` object: ```javascript export default defineConfig({ versions: { current: 'v2', // The version ID built to the root (/) position: 'sidebar-top', // Switcher location: 'sidebar-top' or 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Latest)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## Core Features ### 1. Root SEO (The "Current" Version) The version designated as `current` is generated directly at your output root (e.g., `mysite.com/`). This ensures your primary search traffic always lands on your most up-to-date documentation. ### 2. Isolated Sub-directories Non-current versions are automatically built into subfolders matching their `id`. * `v2 (Current)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. Sticky Switching (Path Preservation) `docmd` preserves the relative path when a user switches versions. If a user is reading `mysite.com/getting-started` and switches to **v1**, they are automatically redirected to `mysite.com/v1/getting-started` (if the page exists) rather than being returned to the home page. ### 4. Asset Isolation Each version inherits your global `assets/` directory, but `docmd` ensures they are isolated during the build process to prevent style leakage or version conflicts. ## Best Practices 1. **Semantic IDs**: Use concise, URL-friendly IDs like `v1`, `v2`, or `beta`. 2. **Navigation Parity**: Maintain consistent folder structures across versions to maximise the effectiveness of "Sticky Switching." 3. **Unified Configuration**: You do not need separate config files for each version; `docmd` processes all versions in a single pass. --- ## [Buttons](https://docs.docmd.io/06/content/containers/buttons/) --- title: "Buttons" description: "Inject call-to-action buttons for internal routing or external resources with a minimalist syntax." --- Buttons are high-impact UI elements used for prominent navigation. Unlike block containers, the `button` is **self-closing** - it is defined on a single line and does not require a closing `:::` tag. ## Syntax ```markdown ::: button "Label" Path [Options] ``` ### Options Reference | Property | Format | Description | | :--- | :--- | :--- | | **Path** | `/path/` | Relative project URL (resolves automatically for SPA navigation). | | **External** | `external:URL`| Opens the target URL in a new browser tab (`target="_blank"`). | | **Colour** | `color:VALUE` | Applies a background colour (supports CSS names or Hex codes). | ## Usage Examples ### 1. Internal Navigation Use relative paths to ensure seamless, zero-reload transitions within the `docmd` SPA. ```markdown ::: button "Install docmd" /getting-started/installation ``` ::: button "Install docmd" /getting-started/installation ### 2. External Resource Link Prepend `external:` to the URL to secure safe external linking. ```markdown ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ``` ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ### 3. Semantic & Brand Styling Match buttons to your brand identity or semantic priority using colour overrides. ```markdown ::: button "Danger Action" /delete color:crimson ::: button "Success Confirmation" /success color:#228B22 ``` ::: button "Danger Action" ./#delete color:crimson ::: button "Success Confirmation" ./#success color:#228B22 ## Critical Note: Self-Closing Logic Because buttons are self-closing, adding a terminal `:::` line will terminate the **parent container** (e.g., a Card or Tab) that the button resides in, potentially breaking your layout. **Incorrect Sequence:** ```markdown ::: card "Setup" ::: button "Begin" /setup ::: <-- Error: This closes the Card prematurely. ::: ``` **Correct Sequence:** ```markdown ::: card "Setup" ::: button "Begin" /setup ::: <-- Correct: This closes the Card. ``` --- ## [Callouts](https://docs.docmd.io/06/content/containers/callouts/) --- title: "Callouts" description: "Highlight critical warnings, pro-tips, and background context using semantic visual blocks." --- Callouts are used to isolate information that requires the reader's immediate attention. `docmd` provides five semantic types, each featuring distinct visual styling and themed iconography. ## Syntax Reference ```markdown ::: callout type "Optional Title" The technical content or warning goes here. ::: ``` ### Supported Semantic Types | Type | Intent | Visual Signal | | :--- | :--- | :--- | | `info` | **General Data** | Contextual background or helpful non-critical info. | | `tip` | **Optimisation** | Performance shortcuts or "Pro-tips". | | `warning`| **Cautionary** | Potential issues or deprecated features to monitor. | | `danger` | **Critical** | Risk of data loss, breaking changes, or system failure. | | `success`| **Verification** | Confirmation of successful configuration or build. | ## Implementation Gallery ### 1. Minimalist Informational Note ```markdown ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ``` ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ### 2. High-Priority Alert with Custom Title ```markdown ::: callout warning "Breaking Change Target" As of `v0.7.0`, the internal WebSocket RPC system will be officially deprecated. ::: ``` ::: callout warning "Breaking Change Target" As of `v0.7.0`, the internal WebSocket RPC system will be officially deprecated. ::: ### 3. Rich Content Composition Callouts support the full spectrum of Markdown, allowing you to embed buttons and code blocks within the alert. ````markdown ::: callout tip "Optimised Local Testing" Use the preserve flag to maintain build files during dev sessions: ```bash docmd dev --preserve ``` ::: button "CLI Flag Reference" /cli-commands ::: ```` ::: callout tip "Optimised Local Testing" Use the preserve flag to maintain build files during dev sessions: ```bash docmd dev --preserve ``` ::: button "CLI Flag Reference" ./#cli-commands ::: ::: callout tip "Prioritised Logic for AI" For LLMs, callouts act as **High-Priority Anchors**. By utilizing `::: callout danger` to document breaking changes or system constraints, you provide a clear signal that the AI model must prioritise this information above surrounding text during its reasoning and generation process. ::: --- ## [Cards](https://docs.docmd.io/06/content/containers/cards/) --- title: "Cards" description: "Organise information into framed, visually distinct containers. Perfect for feature grids and landing pages." --- Cards are the primary structural building blocks in `docmd`. They encapsulate related content into a distinct, bordered frame with optional headers, providing a clear visual hierarchy for your documentation. ## Syntax Reference ```markdown ::: card "Optional Header Title" This is the primary content area of the card. ::: ``` ## Practical Implementation Examples ### 1. Feature Showcasing Use cards to highlight key technical advantages or module capabilities. ```markdown ::: card "Asynchronous Generation" The `docmd` core engine utilizes a non-blocking I/O pipeline, enabling the generation of thousands of pages in milliseconds. ::: ``` ::: card "Asynchronous Generation" The `docmd` core engine utilizes a non-blocking I/O pipeline, enabling the generation of thousands of pages in milliseconds. ::: ### 2. Multi-Component Integration Cards can house any standard Markdown elements, including syntax-highlighted code and call-to-action buttons. ````markdown ::: card "Instant Localisation" Prepare your documentation for a global audience using our built-in i18n support. ```bash docmd add i18n ``` ::: button "L10n Strategy Guide" /configuration/localisation ::: ```` ::: card "Instant Localisation" Prepare your documentation for a global audience using our built-in i18n support. ```bash docmd add i18n ``` ::: button "L10n Strategy Guide" ./#localisation ::: ## Multi-Column Layouts (Grids) You can use the native `grids` container to organise your cards into clean, responsive multi-column layouts without ever touching HTML. ```markdown ::: grids ::: grid ::: card "Primary Node" Configuration for the master instance. ::: ::: ::: grid ::: card "Secondary Node" Configuration for redundant slave instances. ::: ::: ::: ``` ::: callout tip "Semantic Clustering for AI" In the `llms-full.txt` stream, content wrapped in a `card` is treated by AI agents as a **Cohesive Topic Cluster**. Utilizing cards to segment unrelated technical concepts on the same page prevents context leakage and ensures that LLM-generated summaries remain logically isolated and accurate. ::: --- ## [Changelogs](https://docs.docmd.io/06/content/containers/changelogs/) --- title: "Changelogs" description: "Generate structured, timeline-based version history and release notes." --- The `changelog` container provides a specialized layout for documenting project evolution. It automatically parses date or version headers into a vertical timeline, ensuring historical updates are easily scannable. ## Syntax Utilize the specialized `==` delimiter to define entries. The text on the `==` line is rendered as a timeline badge on the left, while the following content populates the adjacent chronological slot. ```markdown ::: changelog == v2.0.0 Description of the major feature release. == v1.5.0 Description of maintenance updates and security patches. ::: ``` ## Detailed Example: Release History Changelogs support rich Markdown within each entry, including lists, callouts, and code blocks. ```markdown ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ``` ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ::: callout tip "Historical Context for AI" Changelogs provide a temporal map for AI agents. When an LLM parses the `llms-full.txt` context, the `::: changelog` structure allows it to accurately identify when specific features, breaking changes, or security fixes were introduced, leading to higher accuracy in its development recommendations. ::: --- ## [Collapsible Sections](https://docs.docmd.io/06/content/containers/collapsible/) --- title: "Collapsible Sections" description: "Embed interactive accordion-style toggles for FAQs, deep-dive content, and spoilers." --- The `collapsible` container creates an interactive, toggleable section (accordion). This pattern is ideal for FAQs, detailed technical configuration, or any secondary information that should be accessible without cluttering the primary documentation flow. ## Syntax ```markdown ::: collapsible [open] "Title Text" Main content goes here. ::: ``` ### Options Reference - **`open`**: (Optional) If specified, the section initialises in an expanded state. - **`"Title"`**: The text rendered on the interactive toggle bar. Defaults to "Click to expand" if omitted. ## Detailed Implementation Examples ### Standard Usage (Initial State: Closed) Primarily used for FAQs or reducing the visual density of technical pages. ```markdown ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ``` ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ### Opt-In Visibility (Initial State: Open) Ideal for sections that should be visible by default but allow the user to minimise them for a cleaner view. ```markdown ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ``` ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ### Nested Technical Data Collapsibles can contain complex Markdown elements, including syntax-highlighted code blocks. ````markdown ::: collapsible "Analyse Sample JSON Response" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "Analyse Sample JSON Response" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ::: callout tip While content inside a `collapsible` may be hidden from the human user, it remains fully visible to the `docmd` search index and is included in the unified `llms-full.txt` stream. This ensures AI agents can provide comprehensive answers based on hidden technical details while the human-facing interface remains clean and prioritised. ::: --- ## [URL Embeds](https://docs.docmd.io/06/content/containers/embed/) --- title: URL Embeds description: How to safely embed dynamic components, videos, and social media directly into your documents. --- `docmd` ships natively with the highly-optimised `embed-lite` parser ecosystem. This allows you to aggressively map raw external URLs strictly onto the page, transforming them beautifully into completely secure, zero-latency UI components instantly! ## Supported Platforms The integrated engine natively exposes structured formatters targeting the following networks identically: * **Video Ecosystem:** YouTube (including native 9:16 Shorts support), Vimeo, Dailymotion, TikTok * **Social Connections:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **Code & Prototyping:** GitHub Gists, CodePen, Figma, Google Maps * **Music Services:** Spotify, SoundCloud ## Usage Syntax You simply use the `::: embed` container followed by any destination URL. All three enclosing formats are equivalent: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### Standard Result Example The rendering engine strictly parses that URL in the background, checking the validation matrix, and structurally injects native HTML nodes directly onto your page output gracefully: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## Fallback Safety Don't worry about generating broken screens. If the internal parser scans an unverified or strictly unavailable domain configuration mapping, `docmd` gracefully falls back to generating a simple, solid `<a>` hyperlink button mapping explicitly out to the target: ```md ::: embed "https://unsupported-example.com/status/123" ``` *(Proceeds to generate exactly what you would see below)* ::: embed "https://unsupported-example.com/status/123" --- ## [Grids](https://docs.docmd.io/06/content/containers/grids/) --- title: "Grids" description: "Organise layout easily with auto-adjusting responsive columns using native markdown containers." --- Grids provide a native, markdown-driven layout system in `docmd`. Instead of writing manual HTML wrappers, you can use the `grids` container to structure elements side-by-side. Columns automatically adjust their widths to fill available space and logically stack into vertical rows on smaller screens (mobile devices). ## Syntax Reference ```markdown ::: grids ::: grid #### Component A Content for the left side. ::: ::: grid #### Component B Content for the right side. ::: ::: ``` ## Practical Implementation Examples ### 1. Feature Showcasing Side-by-Side Use grids to highlight key capabilities next to each other, like combining structural cards with informational blocks. ```markdown ::: grids ::: grid ::: card "Speed :rocket:" Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability :zap:" Designed for massive monorepos and extensive project structures. ::: ::: ::: ``` ::: grids ::: grid ::: card "Speed :rocket:" Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability :zap:" Designed for massive monorepos and extensive project structures. ::: ::: ::: ### 2. Layout Balancing Grids will automatically calculate the optimal width per column (up to 4 items per row on ultra-wide screens) based on the content available and easily group rows on narrow viewports. ::: callout tip "Semantic Layouts" Using the `grids` container keeps your documentation structure purely written in Markdown, resulting in cleaner source files and ensuring LLMs interpret your structural relationships flawlessly! ::: --- ## [Hero Sections](https://docs.docmd.io/06/content/containers/hero/) --- title: "Hero Sections" description: "Build high-impact landing page headers and marketing highlights purely in Markdown." --- The `hero` container is designed for creates professional, visually-striking "landing page" headers. It handles complex CSS requirements like **Split Layouts**, **Glow Effects**, and **Sliders** while maintaining a minimalist authoring experience. ## Basic Syntax By default, the `hero` centres its content, making it perfect for banners and simple headlines. ```markdown ::: hero # Build Faster. The minimalist, zero-config documentation generator. ::: button "Get Started" /intro color:blue ::: ``` ## Advanced Layouts The `hero` container supports specialized flags to control its structural behaviour. | Flag | Effect | | :--- | :--- | | `layout:split` | Divides the hero into a Text area (left) and a Media area (right). Stacks vertically on mobile. | | `layout:slider` | Transforms the hero into a horizontal slider with scroll-snap behaviour. | | `glow:true` | Injects a subtle, radial gradient glow in the background. | ### The Split Layout (`== side`) Use the `== side` separator to define what content goes in the primary text area and what goes in the secondary "side" area (typically an image or a video embed). ```markdown ::: hero layout:split glow:true # docmd 2.0 Isomorphic execution. AI-optimised. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 Isomorphic execution. AI-optimised. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### The Slider Layout (`== slide`) Create an interactive hero slider by using the `== slide` separator between different content nodes. ```markdown ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ``` ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ## Responsive Behaviour The `hero` container is fully responsive by default: - On **Desktop**, `layout:split` displays side-by-side. - On **Mobile**, it automatically transitions to a centred, vertical stack to ensure optimal readability. ## Best Practices 1. **Glow Effects**: Use `glow:true` sparingly on dark mode sites for a premium "neon" feel. 2. **Media Types**: The "side" content of a split layout is perfect for the `::: embed` component, high-quality PNGs, or raw `<video>` tags. 3. **CTA Placement**: Always place `::: button` elements within the primary "Hero Copy" section (before the `== side` separator) to ensure they are the first thing users see on mobile. --- ## [Custom Interactive Containers](https://docs.docmd.io/06/content/containers/) --- title: "Custom Interactive Containers" description: "A comprehensive directory of the interactive UI building blocks available in docmd." --- Standard Markdown excels at basic text formatting, but professional technical documentation requires rich structural components to effectively communicate complex logic. `docmd` extends Markdown with a suite of **isomorphic containers** that render into responsive, high-fidelity UI elements. ## Block Syntax Reference All containers utilize a consistent block syntax, ensuring a predictable authoring experience across your entire project. ```markdown ::: type "Optional Header Title" This is the primary content area. It supports **Markdown**, imagery, and deep component nesting. ::: ``` | Component | Keyword | Primary Use Case | | :--- | :--- | :--- | | **[Callouts](./callouts)** | `callout` | Semantic highlights for tips, warnings, and alerts. | | **[Cards](./cards)** | `card` | Framed structural blocks for feature grids and layout control. | | **[Grids](./grids)** | `grids` | Auto-adjusting multi-column structural groups. | | **[Tabs](./tabs)** | `tabs` | Interactive switchable panes for alternative platform instructions. | | **[Steps](./steps)** | `steps` | Visual numbered timelines for "How-to" guides and tutorials. | | **[Buttons](./buttons)** | `button` | Self-closing, prominent call-to-action navigation links. | | **[Collapsibles](./collapsible)**| `collapsible`| Interactive accordion toggles for FAQs and deep-dive technical data. | | **[Changelogs](./changelogs)** | `changelog` | Structured, timeline-based version history and release notes. | | **[Hero](./hero)** | `hero` | High-impact landing page sections with layout and slider support. | ## The Strategic Importance of Containers Containers facilitate more than visual polish; they provide high-fidelity **Semantic Signals** to the `docmd` engine and downstream AI agents: 1. **AI Context Mapping**: Marking a block as a `callout warning` explicitly tells LLMs to prioritise that information during its reasoning and generation phases. 2. **Structural Integrity**: Combining `cards` with standard CSS allows for the creation of sophisticated landing pages without ever leaving the Markdown environment. 3. **Source Maintainability**: Eliminates "HTML Bloat" in your documentation source, keeping your `.md` files clean and machine-readable. ## Recursive Composition `docmd` supports **Infinite Nesting Depth**. You can compose any container within another to build complex, interactive documentation nodes purely with minimalist Markdown syntax. ```markdown ::: card "Architecture Overview" ::: callout info This module utilizes an asynchronous I/O pipeline. ::: ::: button "Deep Explore Core Engine" /advanced/developer-guide ::: ``` [Master the Nesting Guide →](./nested-containers) --- ## [Nested Containers](https://docs.docmd.io/06/content/containers/nested-containers/) --- title: "Nested Containers" description: "Use docmd's recursive parser to combine cards, tabs, and callouts into high-fidelity page layouts." --- One of `docmd`’s most powerful technical capabilities is its **Recursive Parsing Engine**. You can nest components within each other infinitely to synthesize complex, interactive documentation blocks that would otherwise require deep HTML knowledge or custom templates. ## The Architectural Rule While nesting is mathematically infinite, always adhere to the **Self-Closing Component Rule**: ::: callout warning "Self-Closing Buttons" Because the `::: button` component is self-closing (single line), never add a terminal `:::` line after it. Doing so will inadvertently close the **parent container** housing the button, resulting in a fractured layout. ::: ## Technical Composition Examples ### 1. Interactive Resource Block Combine a **Card** for structural framing, **Tabs** for environment-specific instructions, and **Callouts** for highlighting critical information. ````markdown ::: card "Monorepo Quickstart" Choose your preferred initialisation path: ::: tabs == tab "Automated" ```bash pnpm onboard ``` ::: callout success This script handles all package installation and build tasks automatically. ::: == tab "Manual" Manually fetch and link the core engine. ::: button "Go to Developer Guide" /advanced/developer-guide ::: ::: ```` ### 2. Multi-Platform Tutorials Nesting **Tabs** inside **Steps** is a professional pattern for providing platform-specific instructions within a standard tutorial sequence. ```markdown ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the Presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ``` ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the Presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ## Design Constraints To maintain both performance and mobile responsiveness, observe the following constraints: * **Recursive Tabs**: Nesting tabs within other tabs is technically supported but strongly discouraged. It creates navigation "loops" that are visually confusing on smaller viewports. * **Sequential Conflict**: If you require numbered steps within a tab, utilize a standard ordered list (`1. Step Content`) rather than the `::: steps` container to avoid layout conflicts. * **Legibility**: While `docmd` does not strictly require indentation for nested blocks, using a 2 or 4-space indentation significantly improves the human-readability of the Markdown source. ::: callout tip "Knowledge Segmentation for AI" Nesting provides clear **Semantic Boundaries**. When an AI agent parses the `llms-full.txt` stream, a `callout` nested within a `card` explicitly tells the model that the tip is scoped to that card's specific topic, preventing context leakage and improving technical accuracy in generated responses. ::: --- ## [Steps](https://docs.docmd.io/06/content/containers/steps/) --- title: "Steps" description: "Convert standard ordered lists into high-impact visual timelines and tutorials." --- The `steps` container is designed specifically for "How-to" guides and technical tutorials. It transforms a standard Markdown ordered list into a polished, numbered vertical timeline with automatic spacing and visual emphasis. ## Syntax Wrap any standard ordered list in a `::: steps` block. ```markdown ::: steps 1. **Initialise Project** Run the `docmd init` command to scaffold your directory. 2. **Author Content** Write your documentation using standard Markdown files. 3. **Build & Deploy** Generate static assets using `docmd build`. ::: ``` ## Detailed Implementation The `steps` component supports rich Markdown content within each item, including code blocks, images, and nested containers. ```markdown ::: steps 1. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash docmd build ``` 2. **Verify Asset Integrity** Inspect the `site/` directory to ensure all assets were correctly compiled. 3. **Deploy to Infrastructure** Synchronise the `site/` directory with your primary hosting provider (e.g., S3, Cloudflare Pages, or Vercel). ::: ``` ::: steps 1. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash docmd build ``` 2. **Verify Asset Integrity** Inspect the `site/` directory to ensure all assets were correctly compiled. 3. **Deploy to Infrastructure** Synchronise the `site/` directory with your primary hosting provider (e.g., S3, Cloudflare Pages, or Vercel). ::: ## Advanced Nesting You can nest other documentation components (such as **Callouts** or **Buttons**) inside a step without interrupting the chronological flow of the sequence. ```markdown ::: steps 1. **Configure Environment** Define your project-specific variables in `docmd.config.js`. ::: callout tip Use `defineConfig` to enable IDE autocompletion for configuration keys. ::: 2. **Validate Schema** Run `docmd verify` to ensure your configuration is structurally sound. ::: ``` ::: callout tip "Workflow Optimisation" Modern AI models interpret the `steps` container as a high-fidelity signal for **Sequential Workflows**. To maximise AI accuracy in the `llms-full.txt` context, always start your list items with a **Bolded Title**. This allows agents to reliably parse the objective of each step before processing the implementation details. ::: --- ## [Tabs](https://docs.docmd.io/06/content/containers/tabs/) --- title: "Tabs" description: "Organise dense, alternative, or multi-language information into switchable interactive panes." --- Tabs are the optimal UI pattern for presenting mutually exclusive or related data sets (e.g., "Install via NPM vs. Yarn" or "macOS vs. Windows" instructions) within a compact, interactive format. ## Syntax Reference The `tabs` container utilizes the specialized sub-delimiter `== tab "Label"`. Each label defines a distinct pane that users can toggle between. ```markdown ::: tabs == tab "Label 1" Content for the first tab. == tab "Label 2" Content for the second tab. ::: ``` ## Implementation Gallery ### 1. Package Management Tabs are most commonly used to show installation instructions for different package managers in a single view. ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. Multi-Language Code Snippets Keep your logic clean by separating different programming languages or environments. ::: tabs == tab "TypeScript" ```typescript import { build } from '@docmd/core'; await build('./docmd.config.js'); ``` == tab "JavaScript" ```javascript const { build } = require('@docmd/core'); build('./docmd.config.js'); ``` ::: ## Core Capabilities ### Isomorphic Lazy Rendering `docmd` implements **Conditional Resource Laziness**. If a tab contains computationally expensive elements (e.g., **Mermaid.js** diagrams or high-resolution images), these assets are only initialised and rendered once the user activates that specific tab. This ensures rapid initial page loads. ### State Persistence The default SPA router tracks the active tab's index across similar documentation pages. If a user selects "pnpm" on one page and navigates to another page with a matching tab structure, the "pnpm" tab will remain active automatically. ## Technical Constraints | Constraint | Note | | :--- | :--- | | **Nesting Depth** | To preserve layout integrity, tabs cannot be nested inside other tab components. | | **Interactive Conflict**| High-conflict syntax: To nest Steps inside a Tab, use a standard ordered list (`1. Step One`) instead of the `::: steps` container. | | **Responsive Limit** | It is recommended to limit tab counts to 6 per block to ensure mobile device compatibility. | ::: callout tip "AI Context Mapping" When utilizing tabs for code snippets, always include the target language directly in the tab label (e.g., `== tab "TypeScript"`). This allows LLMs to instantly identify and extract the technically relevant section from the `llms-full.txt` context stream. ::: --- ## [Frontmatter Reference](https://docs.docmd.io/06/content/frontmatter/) --- title: "Frontmatter Reference" description: "The complete guide to page-level metadata and configuration in docmd." --- Frontmatter allows you to override global settings on a per-page basis. It must be written in YAML format at the very top of your Markdown file. ## Core Metadata | Key | Type | Description | | :--- | :--- | :--- | | `title` | `String` | **Required.** Sets the HTML `<title>` and the primary section header. | | `description` | `String` | Sets the meta description for SEO and search results. | | `keywords` | `Array` | A list of keywords for the `<meta name="keywords">` tag. | ## Visibility & Indexing | Key | Type | Description | | :--- | :--- | :--- | | `noindex` | `Boolean` | Excludes the page from the internal search index. | | `llms` | `Boolean` | Set to `false` to exclude this page from the AI context files (`llms.txt`). | | `hideTitle` | `Boolean` | Hides the title from the sticky header (useful if using a custom H1). | | `bodyClass` | `String` | Adds a custom CSS class to the `<body>` tag of this page. | ## Layout Control | Key | Type | Description | | :--- | :--- | :--- | | `layout` | `String` | Set to `full` to use the primary content width and hide the TOC sidebar. | | `toc` | `Boolean` | Set to `false` to disable the Table of Contents entirely. | | `noStyle` | `Boolean` | Disables the entire `docmd` UI (Sidebar, Header, Footer) for custom pages. | ### `noStyle` Component Control When `noStyle: true` is active, you must explicitly opt-in to the components you wish to retain: ```yaml --- noStyle: true components: meta: true # Injects SEO metadata favicon: true # Injects site favicon css: true # Injects docmd-main.css theme: true # Injects theme-specific styling highlight: true # Injects syntax highlighting scripts: true # Injects the SPA router logic sidebar: true # Injects the navigation sidebar footer: true # Injects the site footer --- ``` ## Plugin Overrides ### SEO (`seo`) * `image`: Custom social share image URL for the page. * `aiBots`: Set to `false` to block specifically AI crawlers from this page. * `canonicalUrl`: Sets a custom canonical link for SEO. --- ## [Live Preview](https://docs.docmd.io/06/content/live-preview/) --- title: "Live Preview" description: "Run docmd entirely in the browser without a backend server using the Live architecture." --- `docmd` features a modular architecture that separates filesystem operations from core processing logic. This enables the documentation engine to run **entirely within the browser**, facilitating live editors and CMS previews without the need for a Node.js backend. ::: button "Open Live Editor" https://live.docmd.io ## The Live Editor The built-in Live Editor provides a high-performance, split-pane interface. Author your Markdown in the left pane and observe the rendered output navigate and synchronise in real-time on the right. ### Local Execution To launch the Live Editor locally within your project: ```bash docmd live ``` ### Static Distribution Generate a standalone, static version of the editor for hosting on platforms like Vercel or GitHub Pages: ```bash docmd live --build-only ``` This generates a `dist/` directory containing the `index.html` entry point and the bundled `docmd-live.js` isomorphic engine. ## Embedding docmd You can integrate the browser-compatible bundle into your own applications to provide internal Markdown rendering or preview capabilities. ### 1. Resource Integration Include the required CSS and JavaScript bundles from your assets or a CDN: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. Isomorphic API The global `docmd` object provides the `compile` method for instantaneous rendering. ```javascript const html = await docmd.compile(markdown, { siteTitle: 'Dynamic Preview', theme: { appearance: 'dark' } }); // Inject into an iframe for style isolation document.getElementById('preview-frame').srcdoc = html; ``` ::: callout tip "AI Feedback Loops" The Live architecture is ideal for building **AI-Agent Sandboxes**. Instead of providing an agent with filesystem write access, you can pipe its suggested documentation changes to a live-compilation buffer. This allows you to visually verify AI suggestions in a "ghost" environment before committing changes to your repository. ::: --- ## [docmd : Bespoke No-Style Page Demo](https://docs.docmd.io/06/content/no-style-example/) --- title: "docmd : Bespoke No-Style Page Demo" description: "A functional demonstration of the noStyle architectural feature." noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: centre; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-color); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>Bespoke Page Architecture</h1> <p>Demonstrating the absolute layout control enabled via <code>noStyle: true</code>.</p> </div> <div class="demo-card"> <h2>Logical Foundation</h2> <p> This demonstration utilizes the <code>noStyle: true</code> frontmatter directive to bypass the global documentation layout (Sidebar, Header, and TOC). This provides a "Zero-Friction" canvas for creating marketing landing pages or custom product dashboards. </p> <h3>Enabled System Components</h3> <p>When in No-Style mode, you explicitly opt-in to the documentation engine's core features:</p> <ul> <li><strong>SEO Meta Engine</strong>: Structured tags and social graph data are retained.</li> <li><strong>Project Branding</strong>: Global favicon injection remains active.</li> <li><strong>Foundational Typography</strong>: The processed <code>docmd-main.css</code> provides base styling.</li> <li><strong>Theme Synchronisation</strong>: Light/Dark mode state is fully preserved.</li> <li><strong>Interactive Capabilities</strong>: The SPA router and component logic remain available.</li> </ul> <h3>Technical Implementation</h3> <p> The layout for this page is authored using standard HTML wrappers and scoped CSS defined within the <code>customHead</code> frontmatter field. This ensures zero CSS leakage to the rest of the documentation site. </p> <a href="/content/no-style-pages/" class="demo-button">Analyse the Implementation Guide →</a> </div> </div> --- ## [No-Style Pages](https://docs.docmd.io/06/content/no-style-pages/) --- title: "No-Style Pages" description: "Create custom landing pages and unique layouts by disabling the default docmd theme." --- `docmd` allows you to bypass the standard documentation layout (Sidebar, Header, and Footer) on a per-page basis. This is ideal for creating product landing pages, custom dashboards, or marketing splash screens while maintaining access to the documentation engine's components. ## Enabling No-Style Mode To disable the global UI, add `noStyle: true` to the page's frontmatter. ```yaml --- title: "Product Showcase" noStyle: true components: meta: true # Retain SEO and OpenGraph tags favicon: true # Retain site favicon css: true # Inject docmd-main.css for typography --- <!-- Raw HTML or specialized Markdown goes here --> <div class="hero"> <h1>Next-Gen Documentation</h1> <p>Minimalist. Isomorphic. AI-Ready.</p> </div> ::: callout info "Infinite Nesting Support" Even with `noStyle: true`, all standard `docmd` containers like `::: card`, `::: tabs`, and `::: hero` are fully supported and can be nested at any depth. ::: ``` ## Component Opt-In When `noStyle` is active, you start with a blank canvas. Selectively re-enable core system components as needed: | Component | Description | | :--- | :--- | | `meta` | Injects `<title>`, SEO meta tags, and structured OpenGraph data. | | `favicon` | Injects the project-wide favicon. | | `css` | Injects `docmd-main.css`. Highly recommended for foundational grid and typography. | | `menubar` | Injects the site's top menubar. | | `theme` | Injects the active theme's CSS variables and appearance overrides. | | `scripts` | Injects interactive component logic (requires `mainScripts: true`). | | `spa` | Enables the single-page application router (requires `scripts: true`). | ## Composable Landing Pages The primary power of `noStyle` is that it allows you to use the entire suite of `docmd` components as high-fidelity "widgets" on a blank canvas. You aren't limited to raw HTML; you can build complex, structural designs purely in Markdown. ### Building a Modern Entry Point ```yaml --- title: "Welcome" noStyle: true components: meta: true css: true menubar: true # Use the site's top navigation scripts: true # Enable interactive components mainScripts: true --- ::: hero layout:split glow:true # Build Documentation that Wows. The zero-config engine for modern engineering teams. ::: button "Get Started" /introduction color:blue ::: button "GitHub" github:docmd-io/docmd color:gray == side ::: embed [https://www.youtube.com/watch?v=dQw4w9WgXcQ] ::: ::: ::: grids ::: card "Zero Configuration" Just write markdown. No complex React logic or build scripts. ::: ::: card "AI Optimised" Structure-aware parsing for the LLM era. ::: ::: card "Blazing Fast" Static generation with isomorphic SPA navigation. ::: ::: ``` ::: callout tip "AI-Generated Layouts" Because `noStyle` pages support raw HTML alongside `docmd` containers, they are perfectly suited for **AI-driven UI design**. You can prompt an AI: *"Design a modern hero section using Tailwind-like utility classes and docmd buttons, wrapped in a noStyle: true container."* The AI can iterate on the design within your static site pipeline with zero additional configuration. ::: --- ## [Advanced Markdown Syntax](https://docs.docmd.io/06/content/syntax/advanced/) --- title: "Advanced Markdown Syntax" description: "Use docmd's extended feature set: Custom attributes, GFM extensions, and semantic definitions." --- Beyond standard Markdown, `docmd` supports several high-fidelity extensions derived from GitHub Flavored Markdown (GFM) and custom attribute plugins. These tools provide total control over your document's structure and styling. ## GFM Extensions ### Task Lists Create interactive or read-only checklists for roadmap tracking. ```markdown - [x] Engine Optimisation Complete - [ ] Plugin API Finalization ``` - [x] Engine Optimisation Complete - [ ] Plugin API Finalization ### Automatic Link Resolution Standard URLs and email addresses are automatically identified and linked without additional markup: `https://docmd.io` ### Shortcode Emojis `docmd` supports standard shortcodes to inject visual personality into your documentation. > We :heart: high-performance documentation! :rocket: :smile: ## Custom Element Attributes Assign unique IDs and CSS classes directly to headers, images, and links using the curly-brace `{}` syntax. This is the primary method for applying [Custom CSS Styles](/theming/custom-css-js). ### Unique Semantic IDs Useful for deep-linking directly to technical subsections. ```markdown ## Performance Benchmarks {#benchmarks-2026} ``` ### Functional CSS Classes Apply styling utilities to specific elements. ```markdown ## Center-Aligned Section {.text-centre .text-blue} ``` ### Actionable Button Links Transform any standard markdown link into a styled call-to-action button. ```markdown [Download Latest Release](/download){.docmd-button} ``` ## Citations & Definitions ### Footnote References Add citations or technical deep-dives[^1] that are automatically collected and rendered at the bottom of the page. ```markdown Architectural decisions are documented in the RFC[^1]. [^1]: RFC-42: Isomorphic Rendering Pipeline. ``` ### Definition Lists Perfect for API parameter descriptions and glossaries. ```markdown PropName : The unique identifier for the configuration key. ``` PropName : The unique identifier for the configuration key. ### Technical Abbreviations Define abbreviations globally within a page. Hovering over the term reveals its full definition. ```markdown *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ``` *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ::: callout tip "Contextual Precision for AI" Utilizing **Definitions** and **Abbreviations** provides high-quality technical signals to AI agents. When an AI processes your `llms-full.txt` context, these explicit definitions prevent lexical ambiguity, ensuring the model generates logically correct explanations for your project's specific terminology. ::: --- ## [Code Blocks](https://docs.docmd.io/06/content/syntax/code/) --- title: "Code Blocks" description: "Document technical implementations with high-fidelity syntax highlighting and interactive copy buttons." --- `docmd` utilizes the ultra-fast `lite-hl` engine to provide automatic, context-aware syntax highlighting across hundreds of programming languages and configuration formats. ## Syntax Highlighting Author your technical examples using standard Markdown fenced code blocks. Always specify the language identifier to ensure the highlight engine applies the correct lexical rules. ````markdown ```javascript function initialise() { console.log("docmd engine active."); } ``` ```` **Rendered Result:** ```javascript function initialise() { console.log("docmd engine active."); } ``` ::: callout tip "One-Click Portability" When `copyCode: true` is enabled in your configuration (default), a subtle copy button automatically appears in the top-right corner of every code block on hover, allowing users to instantly transfer snippets to their IDE. ::: ## Strategy for AI Context When documenting code for consumption by LLMs and AI Agents, adhere to these technical best practices: 1. **Strict Language Labeling**: Explicitly labeling blocks as `typescript`, `bash`, or `json` ensures the AI parser accurately interprets the block's grammar within the `llms-full.txt` stream. 2. **Embedded Intent**: Use inline comments within your code blocks to explain the *why* behind complex logic. This provides the AI with critical reasoning context that simple text outside the block might lack. ## Language Support Reference `docmd` provides out-of-the-box support for the most common technical ecosystems, including: * **Logic**: `javascript`, `typescript`, `python`, `rust`, `go`, `ruby`, `csharp`. * **Web**: `html`, `css`, `markdown`. * **Data & Shell**: `json`, `yaml`, `bash`, `powershell`, `dockerfile`. * **Documentation**: `mermaid`, `changelog`. --- ## [Images & Visual Media](https://docs.docmd.io/06/content/syntax/images/) --- title: "Images & Visual Media" description: "Master media management: Responsive images, styling attributes, and automated Lightbox effects." --- `docmd` utilizes standard Markdown syntax for media integration. We recommend centralizing your media assets in the `assets/images/` directory within your project source. ```markdown ![Technical Diagram](/assets/images/architecture.png "Optional Tooltip Title") ``` ## Technical Styling Reference Assign specialized CSS classes and attributes directly to your images using the `{ .class }` attribute syntax. ### Dynamic Resizing ```markdown ![Small Scale](/assets/icon.png){ .size-small } ![Standard View](/assets/preview.png){ .size-medium } ![Full Scale](/assets/banner.png){ .size-large } ``` ### Alignment & Layout ```markdown ![Centred Focus](/assets/img.png){ .align-centre } ![Floating Right](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![Advanced Styling Example](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-centre} ## Structured Media Elements ### Figure Captions For precise, accessible media captioning, use standard HTML5 `<figure>` elements. ```html <figure> <img src="/assets/diagram.png" alt="Cloud Infrastructure Diagram"> <figcaption>Figure 1.1: Core System Infrastructure Architecture.</figcaption> </figure> ``` ### Image Galleries Organise multiple assets into a responsive, balanced grid using the `image-gallery` class. ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="User Dashboard View"> <figcaption>Live Performance Monitor</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="Configuration Panel View"> <figcaption>Project Global Settings</figcaption> </figure> </div> ``` ## Interactive Lightbox Zoom If the `mainScripts` component is active (default), `docmd` automatically applies a full-screen zoom effect to any image contained within a gallery or any image tagged with the `.lightbox` class. ```markdown ![Deep Texture Analysis](/assets/sample.png){ .lightbox } ``` ::: callout tip "AI Context & Accessibility" Always provide comprehensive **Alt-Text** for visual media. While advanced AI models possess vision capabilities, descriptive text within the Markdown source provides a direct, high-fidelity signal for the model's reasoning engine - enhancing architectural analysis and feature comprehension in the `llms-full.txt` stream. ::: --- ## [Markdown Syntax Foundation](https://docs.docmd.io/06/content/syntax/) --- title: "Markdown Syntax Foundation" description: "Master the fundamental formatting rules of docmd: Headings, typographic styles, and technical blocks." --- `docmd` adheres to standard **GitHub Flavored Markdown (GFM)** specifications. This guide establishes the baseline standards for authoring core content across your documentation site. ## Typographic Styling | Attribute | Markdown Syntax | Visual Outcome | | :--- | :--- | :--- | | **Emphasis** | `**Text**` | **Bold technical terms** | | **Italic** | `*Text*` | *Stylized variables* | | **Strikethrough** | `~~Text~~` | ~~Deprecated logic~~ | | **Inline Logic** | `` `code` `` | `engine.initialise()` | ## Structural Elements ### Semantic Header Hierarchy ```markdown # Level 1 (Automatic via Frontmatter) ## Level 2 (Major Section) ### Level 3 (Feature Detail) ``` ::: callout tip "Logical Integrity for AI" Advanced AI models and search internalizers rely on a strict heading hierarchy to build an accurate mental model of your project. By avoiding "Heading Skipping" (e.g., jumping from H2 directly to H4), you ensure the `llms-full.txt` context stream remains chronologically and logically sound. ::: ### Navigation & Reference Utilize standard link syntax for both internal documentation nodes and global resources. ```markdown [Global Resource](https://docmd.io) [Internal Module](../api/node-api.md) ``` ### Enumeration & Listing * **Unordered Segments**: Utilize `*` or `-` for scannable bullet points. * **Sequential Logic**: Utilize `1.`, `2.`, etc., for ordered instructions. (For tutorials, consider the high-impact **[Steps Container](../containers/steps)**). ## Technical Block Elements ### Blockquotes The standard `>` syntax is ideal for highlighting outside quotes or background context. > The docmd engine redefines the boundaries between static site generation and dynamic application delivery. ### Data Schemas (Tables) | Attribute | Data Type | Default | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## Embedded HTML Support As `docmd` is built with raw HTML parsing enabled, you can inject complex layouts or unique styling directly within your Markdown files for specialized UI requirements. ```html <div style="padding: 2rem; border: 1px solid var(--border-color); border-radius: 12px; text-align: centre;"> Bespoke UI elements live here. </div> ``` --- ## [Linking & Referencing](https://docs.docmd.io/06/content/syntax/linking/) --- title: "Linking & Referencing" description: "Master internal cross-linking, external resources, and reliable asset referencing." --- `docmd` provides a reliable, filesystem-aware linking system. By using relative paths to your source `.md` files, you ensure that links remain functional within your IDE (e.g., VS Code) and are automatically rewritten for production deployment. ::: callout info "Extension Neutrality" During the build process, the engine automatically resolves `.md` extensions to their relative HTML counterparts. This guarantees that internal documentation links never break, regardless of whether you are browsing local source or the compiled production site. ::: ## Internal Link Resolution | Targeting Strategy | Markdown Syntax | | :--- | :--- | | **Sibling Page** | `[System Overview](overview.md)` | | **Subdirectory** | `[API Reference](api/node-api.md)` | | **Parent Directory**| `[Back to Home](../index.md)` | ## Section Anchors (Deep Linking) Navigate directly to specific headings using standard URL slugs. * **Intra-page Anchor**: `[Jump to Roadmap](#project-roadmap)` * **Cross-page Anchor**: `[Review CLI Flags](../cli-commands.md#available-flags)` ## Protocols & External Resources The engine respects standard browser protocols for global resources. * **Global HTTPS**: `[docmd Homepage](https://docmd.io)` * **Mail Protocol**: `[Support Channel](mailto:help@docmd.io)` * **Asset Protocol**: `[Download CLI Binary](/assets/bin/docmd-mac.zip)` ## Static Asset Referencing To provide downloads or reference raw source files, place them within the `assets/` directory of your project. The `docmd` builder ensures these files are moved to the production root without path modifications. ```markdown [Download Documentation PDF](/assets/pdf/handbook.pdf) [View Raw Global Config](/assets/config/docmd.config.js) ``` ::: callout tip "Semantic Linkage for AI" When cross-linking technical modules, prioritise **Descriptive Anchors** (e.g., `[Optimise PWA caching](../plugins/pwa.md)`) over generic text (e.g., `[Read more](../plugins/pwa.md)`). Detailed link labels provide AI agents with a high-fidelity map of the semantic relationships between different documentation nodes in the `llms-full.txt` context. ::: --- ## [Contributing](https://docs.docmd.io/06/contributing/) --- title: "Contributing" description: "Guidelines and setup instructions for contributing to docmd." --- Thank you for your interest in contributing to `docmd`! We appreciate all contributions, from bug fixes and documentation improvements to new features and design suggestions. ## Development Environment `docmd` is a monorepo managed with [pnpm](https://pnpm.io/). ### Prerequisites - **Node.js**: v22.x or later (LTS recommended) - **pnpm**: v10.x or later ### Project Setup Clone the repository and run the automated onboarding tool to install dependencies and perform an initial build: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm onboard ``` To link the local `docmd` command globally for testing in other projects: ```bash pnpm onboard --link ``` ### Local Development Run the documentation site while watching for changes in the core engine: ```bash pnpm run dev ``` To watch internal source files (engine, templates, and plugins), set the `DOCMD_DEV` environment variable: ```bash DOCMD_DEV=true pnpm run dev ``` ## Quality Standards Ensure your code complies with the native codebase style guides enforced by our ESLint settings. For minor formatting issues, you can automatically fix them utilizing: ```bash pnpm lint:fix ``` Before submitting a Pull Request, please verify your entire branch compiles flawlessly against the continuous integration Gauntlet by preparing the final release image: ```bash pnpm prep ``` *(This rigorously chains `pnpm reset`, dependency installation, lint checks, E2E tests, and deep security audits in a fresh slate.)* ### Commit Guidelines We use [Conventional Commits](https://www.conventionalcommits.org/). Please prefix your commit messages with: - `feat:` (New features) - `fix:` (Bug fixes) - `docs:` (Documentation changes) - `refactor:` (Code changes that neither fix bugs nor add features) ### Source Headers All new files within the `packages/` directory MUST include the standard project copyright header to maintain consistency and compliance. ```javascript /** * -------------------------------------------------------------------- * docmd : the minimalist, zero-config documentation generator. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @license MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` ## GitHub Workflow 1. **Fork and Branch**: Create a feature branch from the latest `main`. 2. **Verify**: Ensure `pnpm verify` returns `🛡️ docmd is ready for production!`. 3. **Pull Request**: Open a PR with a clear description of the problem solved or the feature added. --- ## [Deployment](https://docs.docmd.io/06/deployment/) --- title: "Deployment" description: "Host your docmd documentation on platforms like GitHub Pages, Vercel, Netlify, and Cloudflare Pages." --- Because `docmd` generates a high-performance static website, it can be hosted on any environment that serves HTML. Simply run the build command and deploy the output directory (Default: `site/`). ```bash docmd build ``` ## Hosting Providers ::: tabs == tab "GitHub Pages" The recommended method is using **GitHub Actions** to automate your deployments on every push. **Create `.github/workflows/deploy.yml`:** ```yaml name: Deploy docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22' } - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. Connect your repository to Vercel. 2. In the project **Build Settings**: - **Framework Preset**: `Other` - **Build Command**: `npx @docmd/core build` - **Output Directory**: `site` 3. Deploy. Vercel automatically detects the static output and serves it globally. == tab "Netlify" 1. Import your project from GitHub/GitLab/Bitbucket. 2. Configure your build settings: - **Build command**: `npx @docmd/core build` - **Publish directory**: `site` 3. Click **Deploy site**. Netlify's CDN will handle the routing and asset delivery. == tab "Cloudflare Pages" 1. Create a new project in the Cloudflare Dashboard under **Pages**. 2. Connect your git provider and select your repository. 3. Configure the build settings: - **Framework preset**: `None` - **Build command**: `npx @docmd/core build` - **Build output directory**: `site` 4. Save and Deploy. == tab "Firebase" 1. Install the Firebase CLI: `npm install -g firebase-tools`. 2. Build your site: `npx @docmd/core build`. 3. Run `firebase init hosting` and select your project. 4. Set the public directory to `site`. 5. Configure as a single-page app: `Yes` (this handles the 404 behaviour). 6. Deploy using `firebase deploy`. == tab "Static Server" For traditional web servers (NGINX, Apache, IIS): 1. Generate the site: `npx @docmd/core build`. 2. Upload the contents of the `site/` folder to your server via SFTP, SCP, or your preferred CI/CD tool. 3. Ensure your server is configured to serve `index.html` for directories (the default for most). == tab "Docker" For self-hosting within a containerized environment, you can use a simple Nginx-based Dockerfile: ```dockerfile # Build Stage FROM node:22-alpine AS builder WORKDIR /app COPY . . RUN npx @docmd/core build # Serve Stage FROM nginx:alpine COPY --from=builder /app/site /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` ::: ## SPA Routing Considerations `docmd` implements a micro-SPA router that handles internal navigation smoothly. Unlike React-based SPAs, every page in `docmd` is generated as its own `index.html` file on the filesystem. This means: - **No Rewrite Rules**: You don't need to configure `index.html` rewrites on your server for most platforms. - **Deep Linking**: Direct access to URLs like `/guide/setup` works out of the box because the server finds `/guide/setup/index.html`. ## Production Checklist 1. **Site URL**: Ensure the `url` property is set in your `docmd.config.js`. This is critical for generating correct canonical tags, sitemaps, and social preview images. 2. **Redirects**: If you are migrating from another tool, use the `redirects` config to maintain your SEO rankings. 3. **Analytics**: Enable the `analytics` plugin to track user engagement and search queries. 4. **AI Ingress**: Enable the `llms` plugin to generate `llms.txt`. This allows AI agents to ingest your documentation more efficiently, providing better answers to your users. ::: callout tip "Custom 404 Pages" `docmd` automatically generates a `404.html` in your output directory. Most hosting providers (GitHub Pages, Netlify, Vercel) will automatically use this file when a user hits a missing route. ::: --- ## [Basic Usage](https://docs.docmd.io/06/getting-started/basic-usage/) --- title: "Basic Usage" description: "Learn how to initialise a project, organise your Markdown files, and build your documentation site." --- Getting started with `docmd` is designed to be instantaneous. This guide walks you through the core workflow, from initial setup to the final production build. ## 1. Project Initialisation To start a new documentation project, create a directory and execute the `init` command. ```bash mkdir my-docs && cd my-docs npx @docmd/core init ``` ### Project Structure After initialisation, your project will follow a clean and predictable structure: | File / Directory | Description | | :--- | :--- | | `docs/` | **Source Directory.** Place all your `.md` files here. | | `assets/` | Static assets (images, custom CSS, or client-side JavaScript). | | `docmd.config.js` | **Configuration File.** Define branding, navigation, and plugins. | | `site/` | **Output Directory.** Contains the generated static site after running `build`. | ## 2. Real-Time Development You can preview your changes instantly without manual rebuilding. Start the development server with: ```bash npx @docmd/core dev ``` * **Access**: `http://localhost:3000` * **Live Reload**: Changes to `.md` files or `docmd.config.js` are reflected instantly in the browser via Hot Module Replacement. ## 3. Content Organisation `docmd` maps the file structure of your `docs/` folder directly to URLs. Subdirectories are handled automatically. * `docs/index.md` → `/` (Home) * `docs/api.md` → `/api` * `docs/guides/setup.md` → `/guides/setup` ::: callout tip "Use standard Markdown" Use standard Markdown. If a page title is not defined in the frontmatter, `docmd` will automatically extract the first `H1` header as the title. ::: ## 4. Customising Navigation The sidebar navigation is controlled via the `navigation` array in `docmd.config.js`. This allows you to define a logical hierarchy for your content. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ navigation: [ { title: 'Introduction', path: '/', icon: 'home' }, { title: 'Advanced', icon: 'settings', collapsible: true, children: [ { title: 'Configuration', path: '/configuration' }, { title: 'Plugins', path: '/plugins' } ] } ] }); ``` ## 5. Production Build When you are ready to deploy, generate a production-ready static site: ```bash npx @docmd/core build ``` This command produces a highly optimised Single Page Application (SPA) in the `site/` directory. The output is entirely static and can be hosted on platforms like GitHub Pages, Vercel, Netlify, or even served from a local file system. ### Verification To verify your production build locally, you can use any static file server (e.g., `npx serve site`) to ensure all links and assets are functioning correctly before deployment. --- ## [Installation](https://docs.docmd.io/06/getting-started/installation/) --- title: "Installation" description: "Instructions for installing docmd globally, locally, or using it on-the-fly with npx." --- `docmd` is a Node.js-based documentation generator. It requires **Node.js (v18.x or higher)** to be installed on your system. There are several ways to deploy and use `docmd`. You can execute it instantly without installation, or integrate it permanently into your development workflow. ## Option 1: Instant Execution (Zero-Config) You can run `docmd` inside any directory containing Markdown files. It automatically scans your files, extracts headings for page titles, and generates a nested navigation structure. No configuration or formal setup is required. ```bash # Start a local development server on http://localhost:3000 npx @docmd/core dev -z # Generate a production-ready static site in the /site directory npx @docmd/core build -z ``` ::: callout warning "Beta Feature" Zero-Config mode (`-z`) is currently in beta. While it is excellent for rapid prototyping and internal documentation, we recommend initialising a project configuration (`docmd.config.js`) for production-grade sites to ensure maximum stability and control. ::: ## Option 2: Local Project Installation (Recommended) For long-term projects, we recommend installing `docmd` as a development dependency. This ensures version consistency across your team and CI/CD environments. ```bash # 1. Install docmd as a development dependency npm install -D @docmd/core # 2. Initialise your project configuration npx @docmd/core init # 3. Start the development server npx @docmd/core dev ``` ## Option 3: Global Installation If you prefer to have the `docmd` CLI available globally across your system: ```bash # Install globally npm install -g @docmd/core # Use the 'docmd' command anywhere docmd dev # Start development server docmd build # Build static site ``` ## Developer Integration (Browser-Only) ::: callout info "Library Use Only" This method is intended for developers who wish to embed the `docmd` parsing and rendering engine inside another web application, such as a CMS, a Live Preview tool, or a custom dashboard. It is **not** the standard way to build standalone documentation sites. ::: To render `docmd` syntax dynamically in a web application without a Node.js backend, include the following assets: ```html <!-- 1. Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 2. Processing Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` Refer to the [Browser API](../api/browser-api.md) guide for integration details. ## Troubleshooting ::: callout warning "Permission Denied (EACCES)" If you encounter `EACCES` errors on macOS or Linux during global installation, it indicates insufficient permissions for global directories. **Resolution:** Use `sudo npm install -g @docmd/core` or, preferably, use a Node version manager like `nvm` to manage global packages without root access. ::: ::: callout info "PowerShell Script Execution" On Windows, if you receive an error stating that "running scripts is disabled on this system," execute the following command in PowerShell as an Administrator: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [Zero-Config Mode](https://docs.docmd.io/06/getting-started/zero-config/) --- title: "Zero-Config Mode" description: "Execute docmd without a configuration file. Ideal for rapid prototyping and instant documentation previews." --- `docmd` features an intelligent auto-detection engine that allows you to generate professional documentation for any project without writing a single line of configuration. This "Zero-Config" mode derives structure and metadata directly from your filesystem and project files. ## Usage To activate Zero-Config mode, simply append the `-z` or `--zero-config` flag to your command. ```bash # Start the development server instantly npx @docmd/core dev -z # Generate a production-ready static site npx @docmd/core build -z ``` ## How It Works When executing in Zero-Config mode, `docmd` performs the following automated steps: 1. **Directory Detection**: The engine scans your project root for common documentation folders, including: `docs/`, `src/docs/`, `documentation/`, and `content/`. If multiple candidates exist, it prioritises them in that order. 2. **Smart Indexing**: If no `index.md` or `README.md` is found at the root of the source directory, `docmd` automatically designates the first discovered Markdown file as the home page. 3. **Metadata Extraction**: If a `package.json` exists in your project, `docmd` extracts the `name` and `description` to automatically set the site title and branding. 4. **Automatic Routing**: The engine recursively scans all subdirectories and Markdown files to build a nested, collapsible navigation sidebar instantly. 5. **Optimised Defaults**: It applies the premium `default` theme with system-aware Light/Dark mode and enables core features like built-in search. ## Safety & Performance Zero-Config mode is engineered for speed and predictability: * **Scoped Execution**: By targeting specific directories, `docmd` avoids unnecessary indexing of unrelated project files, build artifacts, or large logs. * **Intelligent Exclusion**: The engine automatically ignores `node_modules`, hidden system folders (e.g., `.git`), and typical output directories (`dist/`, `build/`, `site/`). * **Bail-out Protection**: If no valid documentation directory or content is found, `docmd` will provide a clear warning and exit gracefully rather than hanging or generating empty files. ::: callout tip "AI-Friendly Architecture" Zero-Config mode is highly recommended for **AI-driven development**. Because the documentation structure is strictly derived from the filesystem, AI agents can easily predict file locations and update content without needing to manage complex configuration schemas. ::: --- ## [Documentation for docmd: The Minimalist Docs Generator](https://docs.docmd.io/06/) --- title: "Documentation for docmd: The Minimalist Docs Generator" description: "Generate beautiful, lightweight, and blazing-fast documentation sites directly from your Markdown files. Zero clutter, just content." --- ```text _ _ _| |___ ___ _____ _| | | . | . | _| | . | |___|___|___|_|_|_|___| ``` **Generate professional, high-performance documentation sites directly from Markdown. Zero clutter, just content.** `docmd` bridges the gap between simple static site generators and heavy, framework-driven documentation tools. It transforms standard Markdown into highly optimised static HTML while delivering a seamless Single Page Application (SPA) experience. ::: button "Get Started" /getting-started/installation ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#333 ::: button "Explore Features" /getting-started/basic-usage color:#333 ## Quick Start **Requires [Node.js](https://nodejs.org/) (v18 or higher) installed.** Deploy a beautiful, searchable documentation site in seconds. No framework knowledge or complex setup required. **1. Install `docmd` as a development dependency** ```bash npm install -D @docmd/core # Recommended: Install locally npx @docmd/core init # Initialise your project configuration npx @docmd/core dev # Start the development server ``` **2. Global Installation (Optional)** ```bash npm install -g @docmd/core # Run docmd from anywhere on your system ``` **3. Instant Zero-Config Execution** ```bash # Start a dev server instantly without any local configuration npx @docmd/core dev -z ``` Once running, open `http://localhost:3000` in your browser. Changes to your files in the `docs/` folder will reflect instantly via Hot Module Replacement (HMR). ## Why choose docmd? Writing documentation should be frictionless. You shouldn't have to manage complex JavaScript frameworks or deep configuration trees just to publish technical text. `docmd` is built for **both humans and AI**, serving as the most LLM-friendly static site generator available. <div class="image-gallery" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));"> ::: card "AI-Native Optimisation" `docmd` generates a structured context for LLMs (`llms.txt` and `llms-full.txt`), allowing AI models to ingest your entire project context perfectly in a single request. ::: ::: card "Zero Config & Auto-Routing" Executing `docmd dev -z` automatically scans for documentation directories, extracts headings as page titles, and builds a nested, collapsible navigation tree instantly. ::: ::: card "SPA Performance" We serve pre-rendered HTML for maximum SEO and initial load speed. Once loaded, `docmd` transitions between pages as a high-performance SPA, ensuring instant content swaps without full browser reloads. ::: ::: card "Smart Offline Search" Features built-in full-text search with fuzzy matching and deep linking. The search index runs entirely in-browser, making it fully functional in offline or air-gapped environments. ::: ::: card "Modern & Responsive" Designed for all devices. Includes premium themes with native Light/Dark appearance modes, sticky versioning, and mobile-optimised sidebars out of the box. ::: ::: card "Isomorphic Rendering" The same engine used for static builds can run natively in the browser. Embed live documentation previews or interactive editors directly into your own web applications. ::: </div> ## Rich Content Out of the Box `docmd` extends standard Markdown with intuitive components designed for professional documentation structures. ::: tabs == tab "Interactive Components" Highlight critical information with Callouts and native Buttons. ::: callout tip Performance Tip Nest containers inside each other to create complex layouts without touching HTML or CSS. ::: ::: button "Read about Containers" /content/containers/callouts == tab "Native Diagrams" Create professional architectural diagrams using **Mermaid.js** syntax directly in your Markdown files. ```mermaid graph LR MD[Markdown] --> Build[docmd Build] Build --> Static[Static HTML] Build --> LLM[llms-full.txt] ``` == tab "Code Precision" Automatic syntax highlighting via our custom `lite-hl` engine, including one-click copy buttons and multi-language support. ```javascript // docmd.config.js import { defineConfig } from '@docmd/core'; export default defineConfig({ title: 'My Project', layout: { spa: true } }); ``` ::: Ready to build? [Install docmd](./getting-started/installation.md) or see [Zero-Config Mode](./getting-started/zero-config.md) in action. --- ## [Analytics Plugin](https://docs.docmd.io/06/plugins/analytics/) --- title: "Analytics Plugin" description: "Integrate Google Analytics 4 or Legacy Universal Analytics and track user interactions automatically." --- The `@docmd/plugin-analytics` plugin allows you to easily integrate Google Analytics into your documentation. It supports the modern Google Analytics 4 (GA4) standard, legacy Universal Analytics (UA), and includes native event tracking for interaction-heavy documentation sites. ## Configuration Enable analytics by adding your tracking credentials to the `plugins` section of `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { analytics: { // 1. Google Analytics 4 (Recommended) googleV4: { measurementId: 'G-XXXXXXX' }, // 2. Legacy Universal Analytics googleUA: { trackingId: 'UA-XXXXXXX-X' }, // 3. Behavioral Tracking Settings autoEvents: true, // Track clicks, downloads, and TOC interactions trackSearch: true // Track search keywords used by readers } } }); ``` ## Tracked Events When `autoEvents` is enabled, the plugin automatically captures the following user interactions and sends them to your analytics provider: * **External Links**: Track when users depart for external resources. * **File Downloads**: Automatically log clicks on links with the `download` attribute or common file extensions (`.pdf`, `.zip`, `.tar`, etc.). * **Table of Contents (TOC)**: Monitor which sections are most engaging by tracking clicks in the right-hand navigation. * **Heading Anchors**: Log when users click on "permalinks" (heading anchors) to share specific sections. * **Search Queries**: When `trackSearch` is active, keywords are captured (with a 1-second debounce) to help you understand what your users are looking for. ## Technical Details The plugin injects the necessary tracking scripts into the `<head>` of every page. Event listeners are attached to the `<body>` using efficient event delegation to ensure zero impact on page load performance or Single Page Application (SPA) transitions. ::: callout info "Privacy & GDPR" By default, this plugin does not anonymize IP addresses as that is now handled natively by GA4. If you require advanced cookie consent management, you can manually inject your consent manager scripts using the `customCss` or a custom plugin hook. ::: --- ## [Building Plugins](https://docs.docmd.io/06/plugins/building-plugins/) --- title: "Building Plugins" description: "A comprehensive guide to extending docmd with custom logic and interactive features." --- Plugins are the primary extension mechanism for `docmd`. They allow you to inject custom HTML, modify the Markdown parsing logic, and automate post-build tasks. This guide outlines the plugin API and best practices for creating shareable components. ## Plugin API Reference A `docmd` plugin is a standard JavaScript object (or a module that exports one as default) that implements one or more of the following asynchronous hooks. | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the `markdown-it` instance. Synchronous. | | `generateMetaTags(config, page, root)` | Inject `<meta>` or `<link>` tags into the `<head>`. | | `generateScripts(config, opts)` | Return an object containing `headScriptsHtml` and `bodyScriptsHtml`. | | `getAssets(opts)` | Define external files or CDN scripts to be injected. | | `onPostBuild(ctx)` | Run logic after the generation of all HTML files. | | `actions` | An object of named action handlers for WebSocket RPC calls from the browser. | | `events` | An object of named event handlers for fire-and-forget messages from the browser. | ## Creating a Local Plugin Creating a plugin is as simple as defining a JavaScript file. For example, `my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { // 1. Extend the Markdown Parser markdownSetup: (md, options) => { // Example: Add a rule or use a markdown-it plugin }, // 2. Inject Page Metadata generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, // 3. Post-Build Automation onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`Custom Plugin: Verified ${pages.length} pages.`); // Example: Generate a custom manifest or notification } }; ``` To enable your plugin, reference its **full package name** in your `docmd.config.js`: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { 'my-awesome-plugin': { // Your custom options go here } } }); ``` > **Note:** Shorthand names (e.g. `math`, `search`) are reserved exclusively for official `@docmd/plugin-*` packages. Third-party plugins must always be referenced by their full npm package name. ### Plugin Resolution The `docmd` engine resolves plugin names as follows: - **Official shorthands** (`math`, `search`, `seo`, etc.) automatically expand to `@docmd/plugin-<name>`. Since the `@docmd` npm scope is owned by the project, only official packages can exist under it. - **Third-party plugins** must use their full package name (e.g. `my-awesome-plugin`, `@myorg/docmd-extras`). There is no alias or shorthand system for external plugins - this prevents confusion and eliminates supply-chain attack vectors entirely. ### Scoping Plugins (`noStyle`) By default, plugins inject their CSS/JS universally. However, developers can explicitly prevent their plugin from rendering on `noStyle` pages (like minimal landing templates) by exporting a `noStyle` boolean: ```javascript export default { noStyle: false, // Prevents generateMetaTags and generateScripts from running on noStyle pages generateScripts: () => { ... } } ``` Users can also override this behaviour through their configuration (`plugins: { math: { noStyle: false } }`) or dynamically via Markdown frontmatter (`plugins: { math: true }`). ## Deep Dive: Asset Injection The `getAssets()` hook allows your plugin to bundle client-side logic securely. ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', // External CDN script type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), // Local source dest: 'assets/js/plugin-init.js', // Destination in build/ type: 'js', location: 'body' } ]; } ``` ## WebSocket RPC Actions Starting in `0.6.8`, plugins can register **action handlers** and **event handlers** that run on the dev server and are callable from the browser via the `window.docmd` API. ```javascript // my-live-plugin.js export default { // Server-side action - browser calls via docmd.call() actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, // Server-side event - browser sends via docmd.send() events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`Page viewed: ${data.path}`); } } }; ``` The `ctx` (ActionContext) object provides: | Method | Description | | :--- | :--- | | `ctx.readFile(path)` | Read a file relative to the project root. | | `ctx.writeFile(path, content)` | Write a file (triggers rebuild + reload). | | `ctx.readFileLines(path)` | Read a file as an array of lines. | | `ctx.broadcast(event, data)` | Push an event to all connected browsers. | | `ctx.source` | Source editing tools for block-level markdown manipulation. | | `ctx.projectRoot` | Absolute path to the project root. | | `ctx.config` | Current docmd site configuration. | All file operations are sandboxed to the project root - path traversal attempts are rejected automatically. ::: callout info "Dev Mode Only 🛡️" The WebSocket RPC system is only active during `docmd dev`. Production builds do not include the API client or any server-side action handling. ::: ## Best Practices 1. **Async/Await**: Always use `async` functions for `onPostBuild` and action handlers to prevent blocking the build engine during I/O operations. 2. **Statelessness**: Avoid maintaining state within the plugin object, as `docmd` may re-initialise plugins during development "Hot Reloads." 3. **Naming Convention**: For community plugins, prefix your package name with `docmd-plugin-` (e.g., `docmd-plugin-analytics`). 4. **Action Namespacing**: Prefix your action names with your plugin name (e.g., `my-plugin:save-note`) to avoid collisions. 5. **Logging**: Use the provided `log()` helper in `onPostBuild` to ensure your messages respect the user's `--verbose` settings. ::: callout tip "AI-Ready Design 🤖" The `docmd` plugin API is designed to be **LLM-Optimal**. Because the hooks use standard JavaScript objects and types without hidden complex class hierarchies, AI agents can generate bug-free custom plugins for you with minimal instruction. ::: --- ## [LLM Context Plugin](https://docs.docmd.io/06/plugins/llms/) --- title: "LLM Context Plugin" description: "Optimised your documentation for AI Consumption with automated llms.txt and llms-full.txt generation." --- The `@docmd/plugin-llms` plugin ensures your documentation is perfectly optimised for Large Language Models (LLMs) and AI Agents. It follows the growing industry standard of providing a high-level summary and a comprehensive context file that AI tools can ingest to understand your project with minimal hallucination. ## Configuration The LLM plugin is enabled by default. To function correctly, you must provide a `siteUrl` in your `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ siteUrl: 'https://docs.example.com', plugins: { llms: {} // Enabled by default } ### Excluding a Page If a page contains sensitive information or internal notes you don't want AI models to learn: ```yaml --- title: "Internal Dev Secrets" llms: false --- ``` ::: callout tip By hosting an `llms-full.txt` file, you are essentially providing an **Open API for AI Models**. This makes your project the preferred choice for developers working with AI assistance, as they can reliably get accurate answers without your docs "hallucinating" or being outdated by the model's training cutoff. ::: --- ## [Math Plugin](https://docs.docmd.io/06/plugins/math/) --- title: "Math Plugin" description: "Native KaTeX/LaTeX mathematics integration for docmd." --- The **Math plugin** adds native LaTeX and KaTeX support to your docmd sites. It utilizes `markdown-it-texmath` as securely integrated with the `katex` computation engine to render both inline and block-level mathematical equations smoothly without requiring complex client-side javascript libraries. ## Setup ```bash docmd add math ``` ```javascript plugins: { math: {} } ``` ## How It Works 1. Enable the plugin via your `docmd.config.js`. 2. Wrap your standard LaTeX mathematics in `$` (inline) or `$$` (block) indicators. 3. The server intelligently processes these math rules during the static-site build exactly as raw static HTML tags. 4. Minimal injected CSS automatically scopes these classes directly, yielding immediate visualization the moment the user views the page! ## Usage ### Inline Mathematics You can inject standard equations flawlessly within a paragraph utilizing single dollar signs `$`: ```markdown Here is an inline equation: $E = mc^2$ ``` Here is an inline equation: $E = mc^2$ ### Block Mathematics For wider mathematical proofs or distinct formulations, use double dollar signs `$$` for block level formatting: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid Diagrams](https://docs.docmd.io/06/plugins/mermaid/) --- title: "Mermaid Diagrams" description: "Create professional architectural diagrams, flowcharts, and sequence diagrams directly in your Markdown files using Mermaid.js syntax." --- The `@docmd/plugin-mermaid` plugin integrates the powerful [Mermaid.js](https://mermaid.js.org/) engine into your documentation pipeline. It allows you to transform plain-text descriptions into high-fidelity, interactive diagrams without ever leaving your Markdown environment. ## Key Features - **Zero Scripting**: No need to manually include external scripts or CDN links. `docmd` detects the usage and injects the rendering engine only where needed. - **Theme Awareness**: Diagrams automatically adapt their colour schemes to match your site's **Light** or **Dark** mode transitions. - **Isomorphic Lazy Loading**: For optimum performance, diagrams are initialised and rendered only as they enter the user's viewport. - **Technical Readability**: Diagrams remain pure text in your source, making them easily version-controlled and readable by AI agents. ## Configuration To enable diagram support, add the `mermaid` plugin to your `docmd.config.js`: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { mermaid: {} // Enabled with zero-config } }); ``` ## Implementation Gallery To render a diagram, place your Mermaid syntax within a fenced code block with the `mermaid` language identifier. ### 1. Sequence Diagrams Ideal for illustrating interactions between multiple system components. ::: tabs == tab "Preview" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` == tab "Markdown Source" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` ```` ::: ### 2. Analytical Charts Visualize data using built-in chart types like Pie Charts or Bar Charts. ::: tabs == tab "Preview" ```mermaid pie title Project Composition "Documentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI Components" : 10 ``` == tab "Markdown Source" ````markdown ```mermaid pie title Project Composition "Documentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI Components" : 10 ``` ```` ::: ### 3. Git Workflows Visualize branching and merging strategies for your developer guides. ::: tabs == tab "Preview" ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` == tab "Markdown Source" ````markdown ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` ```` ::: ## Technical Implementation The Mermaid plugin operates by intercepting `mermaid` code blocks during the parsing phase and wrapping them in a specialized `<div class="mermaid">` container. 1. **Detection**: The engine scans the rendered HTML for the presence of mermaid containers. 2. **Asset Injection**: If containers are found, `docmd` injects a lightweight `init-mermaid.js` module. 3. **Rendering**: The Mermaid library is fetched asynchronously and renders the diagrams client-side, ensuring that your initial HTML payload remains small and fast. ::: callout tip "Diagrams for AI Agents" While diagrams are visually helpful for humans, they are technically transparent to AI. Because the source is pure text, models like GPT-4 or Claude can "see" your system architecture or logic flows through the `llms-full.txt` stream. This allows the AI to explain complex architectural relationships based on your diagrams. ::: --- ## [PWA & Offline Support](https://docs.docmd.io/06/plugins/pwa/) --- title: "PWA & Offline Support" description: "Transform your documentation into a progressive web application with offline caching and mobile-first features." --- The `@docmd/plugin-pwa` plugin enables Progressive Web App (PWA) features for your documentation site. It adds a web manifest for mobile installation and registers a service worker to handle intelligent offline caching, ensuring your technical manuals remain accessible even in low-connectivity environments. ## Configuration The PWA plugin can be customised to match your branding within the `plugins` section of `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { pwa: { enabled: true, // Enabled by default if the plugin is loaded themeColor: '#1e293b', // The primary colour of the mobile UI bgColor: '#ffffff', // Background colour for the splash screen logo: '/assets/logo.png' // Fallback for app icons if not explicitly defined } } }); ``` ## Core Features ### 1. Offline Caching The plugin automatically generates a `service-worker.js` file that implements a "Stale-While-Revalidate" caching strategy. When a user visits a page, the service worker: * Returns the cached version instantly for maximum speed. * Fetches the latest version from the network in the background. * Updates the cache for the next visit. ### 2. Mobile Installation By generating a `manifest.webmanifest` and injecting the required `<meta>` tags, the plugin allows users to "Add to Home Screen" on iOS and Android. Your documentation will behave like a standalone application, with its own splash screen and window frame. ### 3. Smart Asset Resolution The plugin attempts to generate app icons automatically by looking for your project's `logo` or `favicon`. For more control, you can provide an explicit `icons` array: ```javascript pwa: { icons: [ { src: '/icons/icon-192x192.png', sizes: '192x192', type: 'image/png' }, { src: '/icons/icon-512x512.png', sizes: '512x512', type: 'image/png' } ] } ``` ## Technical Implementation The service worker is designed to be compatible with Single Page Application (SPA) routing. It includes specific fail-safe logic for Safari's strict security policies regarding redirected streams, ensuring stability across all modern browsers. ::: callout tip "Dev Mode" Service workers are typically disabled or bypassed in local development (`docmd dev`) to prevent aggressive caching from interfering with your edits. To test the PWA functionality, perform a production build with `docmd build` and serve the output directory using a static host. ::: ### Fully Remove Simply delete the `pwa` block from your `plugins`. The next time you run `docmd build`, a new manifest is not generated. When users visit the site, docmd's client-side bootstrap (`docmd-main.js`) checks for the presence of `<link rel="manifest">`. If it's missing but a Service Worker is registered, it automatically **unregisters all existing ghost workers** and clears the cached shell - requiring no user action. ::: callout warning The `manifest.webmanifest` and `service-worker.js` files from a previous build persist on disk until you clear your output directory (`site/` by default) with `docmd build` or `rm -rf site`. This is a filesystem artifact, not an active PWA. ::: ## Configuration Reference All fields are optional. The defaults are designed for zero-config use. ```javascript export default { plugins: { pwa: { // --- Icon Configuration --- // Priority: pwa.logo > config.logo > config.favicon > (no icons) logo: 'assets/images/app-icon.png', // Path relative to your src folder // Or for full manual control: icons: [ { src: '/assets/images/icon-192.png', sizes: '192x192', type: 'image/png' }, { src: '/assets/images/icon-512.png', sizes: '512x512', type: 'image/png' } ], // --- Manifest Colours --- themeColor: '#1e293b', // Browser chrome / top bar accent bgColor: '#ffffff', // Splash screen background during install // --- Disable the plugin entirely --- enabled: false } } } ``` ### Icon Resolution Priority docmd resolves your PWA icon from the following cascade: 1. `pwa.icons` - Manual array, used as-is 2. `pwa.logo` - Single image path, used for both 192x192 and 512x512 entries 3. `config.logo` - Your global site logo 4. `config.favicon` - Your global favicon 5. *(No icons declared in manifest)* - If none of the above are set ## Testing Locally Browsers restrict Service Workers to `https://` or `localhost`. Use: ```bash docmd dev ``` Open Chrome DevTools → **Application** → **Manifest** and **Service Workers** to view the activated registration in real-time. Safari → **Develop** → **Service Workers** panel works equally well. --- ## [Search Plugin](https://docs.docmd.io/06/plugins/search/) --- title: "Search Plugin" description: "Enable high-speed, offline-first full-text search for your documentation using MiniSearch." --- The `@docmd/plugin-search` plugin provides a powerful, client-side search experience for your documentation. It uses [MiniSearch](https://github.com/lucaong/minisearch) to build a lightweight index during the build process, allowing users to find technical information instantly without a server-side database. ## Configuration Search is enabled by default in most `docmd` templates. You can control its visibility and placement via the `layout` configuration. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ layout: { optionsMenu: { position: 'header', // 'header', 'sidebar-top', 'sidebar-bottom', or 'menubar' components: { search: true // Set to false to disable the search plugin entirely } } } }); ``` ## How It Works ### 1. Indexing (Build-time) During the `docmd build` process, the search plugin iterates through every page on your site. It extracts the title, headings, and plain-text prose, then compiles this data into a compressed `search-index.json` file. * **Deep Linking**: The indexer automatically registers every heading (`#`, `##`, etc.) as a searchable target. * **Relevancy Boosting**: Titles are given the highest weight, followed by headings, then page content. ### 2. Retrieval (Client-side) When a user opens the search modal (usually via `/` or `Ctrl+K`), the `search-index.json` is fetched by the browser. Searches are performed locally using fuzzy matching (allowing for small typos) and instant prefix matching. ## Customising Search Behaviour While the search plugin is designed for zero-config simplicity, you can exclude specific pages from the index by using the `noindex` flag in their frontmatter: ```yaml --- title: "Internal Specification" noindex: true # This page will not appear in search results or sitemaps --- ``` ## Technical Implementation The plugin injects a minimalist search modal into the `<body>` of your site. It is designed to be fully accessible (ARIA compliant) and supports keyboard navigation for a native app-like experience. ::: callout tip "Search Analytics" If you have the [Analytics Plugin](./analytics) enabled, search keywords used by your readers are automatically captured and sent to your analytics provider, giving you insights into what information is missing or hardest to find. ::: Because the search happens entirely on the client, no data - not even keystrokes - is ever sent to a server. This makes `docmd` the Gold Standard for documentation search in privacy-sensitive industries (Healthcare, Finance, Security). ## Comparison Many documentation generators (like Docusaurus) rely on **Algolia DocSearch**. While Algolia is powerful, it introduces friction: | Feature | docmd Search | Algolia / External | | :--- | :--- | :--- | | **Setup** | **Zero Config** (Automatic) | Complex (API Keys, CI/CD crawling) | | **Privacy** | **100% Private** (Client-side) | Data sent to 3rd party servers | | **Offline** | **Yes** | No | | **Cost** | **Free** | Free tier limits or Paid | | **Speed** | **Instant** (In-memory) | Fast (Network latency dependent) | --- ## [SEO Plugin](https://docs.docmd.io/06/plugins/seo/) --- title: "SEO Plugin" description: "Optimise your documentation for search engines and control AI crawler access with native meta tag generation." --- The `@docmd/plugin-seo` plugin is responsible for generating high-quality metadata for every page. It ensures your documentation is not only discoverable by human readers on search engines but also correctly interpreted by AI models and social media platforms. ## Global Configuration Configure site-wide SEO defaults in your `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { seo: { defaultDescription: 'Comprehensive documentation for the docmd ecosystem.', aiBots: false, // Set to false to block common AI crawlers (GPTBot, etc.) openGraph: { defaultImage: '/assets/og-image.png' }, twitter: { siteUsername: '@docmd_io', cardType: 'summary_large_image' } } } }); ``` ## Page-Level Overrides You can fine-tune SEO settings for individual pages using frontmatter. Page-level settings always take precedence over global defaults. ```yaml --- title: "Advanced Configuration" description: "Learn how to master docmd's internal engine." noindex: true # Hide this specific page from all search engines seo: keywords: ["docmd", "javascript", "ssg"] ogType: "article" canonicalUrl: "https://mysite.com/canonical-path" aiBots: true # Override global block to allow AI access to this page --- ``` ## Core Features ### 1. Smart Description Fallback If a description is not provided in the frontmatter or global config, the plugin automatically extracts the first 150 characters of the page's prose to use as the `<meta name="description">`, ensuring every page has basic metadata for search snippets. ### 2. AI Bot Governance By setting `aiBots: false`, the plugin injects `noindex` instructions specifically for major AI crawlers (including `GPTBot`, `Claude-Web`, and `Google-Extended`). This allows you to differentiate between traditional search engine indexing and LLM training sessions. ### 3. Canonical Resolution The plugin automatically generates `<link rel="canonical">` tags based on your `siteUrl`. It intelligently handles directory indexes, converting `guide/index.html` to a clean `/guide/` canonical URL to prevent duplicate content issues. ### 4. Rich Social Previews Native support for Open Graph and Twitter Cards ensures that links to your documentation look professional when shared on platforms like X (Twitter), LinkedIn, and Discord. ::: callout tip "Search Discovery" For the best SEO results, ensure your `siteUrl` is defined in the root of your configuration. Without a base URL, the plugin cannot generate absolute canonical links or Open Graph image paths. ::: ## Structured Data (LD+JSON) `docmd` can automatically generate [Article Schema](https://developers.google.com/search/docs/appearance/structured-data/article) to help Search Engines display rich snippets. ```yaml --- title: "How to Build a docmd Plugin" seo: ldJson: true --- ``` ::: callout tip "Structured Data" A well-configured SEO plugin helps AI-powered search engines (like SearchGPT or Perplexity) summarize your site accurately. By providing clear descriptions and blocked bots, you control exactly how AI models perceive and source your content online. ::: --- ## [Sitemap Plugin](https://docs.docmd.io/06/plugins/sitemap/) --- title: "Sitemap Plugin" description: "Automatically generate a standard-compliant sitemap.xml for better search engine discovery." --- The `@docmd/plugin-sitemap` plugin automatically generates a `sitemap.xml` file at the root of your build directory. This file provides search engines like Google and Bing with a comprehensive map of your site's architecture, ensuring that all pages - including deep links within versioned documentation - are crawled and indexed. ## Configuration Enable sitemap generation by providing your `siteUrl` in the root configuration. You can customise the crawl weight of various sections within the `plugins` object. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ siteUrl: 'https://docs.example.com', // Required for sitemap generation plugins: { sitemap: { defaultChangefreq: 'weekly', // 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never' defaultPriority: 0.8, // Default weight for standard pages rootPriority: 1.0 // Weight for the homepage (index.md) } } }); ``` ## Page-Level Controls You can override sitemap behaviour for specific pages using frontmatter. ```yaml --- title: "Archive Page" priority: 0.3 # Lower weight for legacy content changefreq: "monthly" # Hint to crawlers that this page rarely changes lastmod: "2024-03-15" # Explicitly set the last modification date sitemap: false # Exclude this specific page from the sitemap.xml --- ``` ## Core Features ### 1. Automatic URL Construction The plugin intelligently resolves page paths to their canonical public URLs. It handles directory indexes automatically, ensuring that `guide/index.html` is listed as `https://yoursite.com/guide/` to maintain clean URL structures. ### 2. Versioned Discovery If your project uses [Versioning](../configuration/versioning), the sitemap plugin automatically includes all pages from all versions (e.g., `/v1/getting-started`, `/v2/getting-started`), allowing search engines to discover your archived documentation without manual configuration. ### 3. Smart Exclusions Pages marked with `noindex: true` or `sitemap: false` in their frontmatter are automatically excluded from the generated `sitemap.xml`, giving you granular control over what is presented to search engines. ::: callout tip "Validation" After building your site, you can typically find the sitemap at `your-output-dir/sitemap.xml`. Most search engine consoles allow you to submit this file directly to accelerate indexing. ::: --- ## [Threads Plugin](https://docs.docmd.io/06/plugins/threads/) --- title: "Threads Plugin" description: "Add inline discussion threads to your documentation - stored directly in your markdown files." --- The **Threads plugin** brings collaborative inline comments to your documentation. Select any text on the page, leave a comment, start a discussion - all stored directly in your markdown source files with zero database needed. Original Author: [@svallory](https://github.com/svallory) ::: callout info "Alpha Release" This plugin is in alpha. The API and storage format are stable, but the UI is under active development. ::: ## Setup ```bash docmd add threads ``` ```javascript plugins: { threads: {} } ``` ### Configuration Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | When `true`, threads stay grouped at the bottom of the page. When `false` (default), threads are positioned inline next to their highlighted text. | ```javascript // Keep threads at bottom of page instead of inline plugins: { threads: { sidebar: true } } ``` ## How It Works 1. **Select text** on any documentation page during `docmd dev` 2. A **comment popover** appears - write your comment and submit 3. The selected text gets **highlighted** with a thread marker 4. Threads are stored as `::: threads` blocks at the bottom of the markdown file 5. **No database** - your markdown files are the source of truth ## Preview Here's what threads look like on a live page. Text with discussions gets <span class="threads-preview-highlight">highlighted like this</span> and thread cards appear below. <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 2d ago</div> <div class="threads-preview-body">This section could use a diagram to explain the architecture. What do you think?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · 1d ago</div> <div class="threads-preview-body">Good idea - I'll add a Mermaid flowchart. Does <code>sequenceDiagram</code> work here?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 12h ago</div> <div class="threads-preview-body">Perfect. A simple flowchart would be ideal.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> And here's a <span class="threads-preview-highlight-blue">second highlight with a different colour</span> - threads cycle through a palette of colours automatically. <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · 3d ago</div> <div class="threads-preview-body">Should we mention backward compatibility here?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> Resolved threads appear dimmed: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 5d ago  <span class="threads-preview-resolved-badge">✓ Resolved</span></div> <div class="threads-preview-body">Fixed the typo in the config example.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> A floating **discussion button** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span> appears in the bottom-right corner showing the count of open threads. Click it to jump to the first thread on the page. ## Storage Format Threads are embedded in your markdown using docmd's container syntax: ```markdown # My Documentation Page Some content with ==highlighted text=={t-a1b2c3d4} that has a thread. ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" This text needs clarification. ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 Updated it - does this work? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` The `==text=={threadId}` syntax links highlighted text in the document body to a specific thread. ## Features | Feature | Description | | :--- | :--- | | **Text Selection** | Select any text to start a new thread | | **Replies** | Nested reply chains within each thread | | **Reactions** | Emoji reactions on individual comments | | **Edit / Delete** | Modify or remove your comments | | **Resolve** | Mark threads as resolved with author + timestamp | | **Author Profiles** | Git-based author detection with Gravatar support | | **Highlight Markers** | Visual indicators on the page showing where threads are anchored | | **Floating Button** | Quick-access FAB with open thread count | | **Scroll Preservation** | Page stays in place after adding comments | ## Actions API The threads plugin exposes the following actions via the WebSocket RPC system. These can be called from browser plugins using `docmd.call()`: | Action | Description | | :--- | :--- | | `threads:get-threads` | Parse and return all threads from a file | | `threads:add-thread` | Create a new thread with its first comment | | `threads:add-comment` | Add a comment to an existing thread | | `threads:edit-comment` | Edit an existing comment's body | | `threads:delete-comment` | Remove a comment from a thread | | `threads:delete-thread` | Remove an entire thread and cleanup highlights | | `threads:resolve-thread` | Toggle resolved/unresolved status | | `threads:toggle-reaction` | Toggle an emoji reaction on a comment | | `threads:get-authors` | Read the author profile map | | `threads:upsert-author` | Create or update an author profile | ## Author Profiles Author information is stored in `<docsRoot>/.threads/authors.json`: ```json { "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } } ``` During development, the plugin automatically detects your git username and email for author identification. ::: callout tip "Version Control Friendly" Since threads are stored in your markdown files, they are automatically version-controlled with git. Review comments in PRs, track discussion history, and collaborate through your existing workflow. ::: --- ## [Using Plugins](https://docs.docmd.io/06/plugins/usage/) --- title: "Using Plugins" description: "Install, configure, and manage docmd plugins - from required defaults to optional add-ons." --- `docmd` features a modular plugin architecture. Required plugins ship with the core and need no installation. Optional plugins can be installed with a single CLI command. ## Installing Plugins Use the `docmd` CLI to install and remove plugins: ```bash # Install a plugin docmd add <plugin-name> # Remove a plugin docmd remove <plugin-name> ``` The installer automatically detects your package manager (npm, pnpm, yarn, or bun), resolves short names to full package names, and injects the plugin config into your `docmd.config.js`. Use `--verbose` for full installer output: ```bash docmd add <plugin-name> --verbose ``` ## Required Plugins These plugins are bundled with `@docmd/core` - no installation needed. Enable them in your `docmd.config.js`: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { search: {}, // Offline full-text search seo: { aiBots: false }, // Meta tags, Open Graph, AI bot controls sitemap: {}, // Automatic sitemap.xml generation analytics: {}, // Google Analytics v4 pwa: { themeColor: '#0097ff' }, // Progressive Web App support llms: {}, // LLM context generation (llms.txt) mermaid: {} // Native interactive diagrams } }); ``` ## Optional Plugins Optional plugins require installation before enabling. | Plugin | Install Command | Description | | :--- | :--- | :--- | | [Threads](threads.md) | `docmd add threads` | Inline discussion comments stored in your markdown | | [Math](math.md) | `docmd add math` | Native KaTeX and LaTeX mathematics integration | ## Plugin Scopes and `noStyle` Overrides Plugins inject CSS and behaviour by default globally across all pages. However, you can explicitly configure them to bypass specific pages or entirely disable their execution on unstyled landing templates (`noStyle: true`). ### Global Config Extent You can instruct any plugin to automatically skip injecting into `noStyle` pages via your `docmd.config.js`: ```javascript plugins: { math: { noStyle: false // math css/js will no longer load on minimalistic landing pages } } ``` ### Page Local Scope (Frontmatter) Regardless of your global config (or what the plugin developer set by default), you can definitively enable or disable any plugin uniquely per-document via markdown frontmatter. ```markdown --- noStyle: true plugins: math: true threads: false --- # Only Math renders here, Threads are completely blocked ``` ## Plugin Lifecycle Plugins hook into different stages of the build and development process: | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the Markdown parser with custom rules or containers | | `generateMetaTags(config, page, root)` | Inject `<meta>` and `<link>` tags into the `<head>` | | `generateScripts(config, opts)` | Inject scripts into `<head>` or `</body>` | | `getAssets(opts)` | Define external files or CDN scripts to inject | | `onPostBuild(ctx)` | Run logic after all HTML files are generated | | `actions` | Server-side handlers callable from the browser via WebSocket RPC | | `events` | Fire-and-forget handlers for browser-pushed events | ::: callout tip "AI-Transparent Architecture 🤖" The plugin architecture is designed to be **deterministic**. Every meta-tag and script injected by a plugin is traceable, allowing AI agents (and human developers) to understand exactly how the site behaves without hidden side effects. ::: --- ## [Recipe: Optimising for AI Agents](https://docs.docmd.io/06/recipes/ai-optimisation/) --- title: "Recipe: Optimising for AI Agents" description: "Engineer your documentation for maximum ingestibility by LLMs and AI Agents." --- `docmd` is architected as an "AI-First" documentation engine. By adhering to these structural best practices, you ensure that LLMs (such as ChatGPT, Claude, and GitHub Copilot) can parse your project's logic and architecture with surgical precision. ## 1. Enable the LLM Plugin The baseline for AI optimisation is the native `llms` plugin. It generates structured context files specifically designed for model ingestion. ```javascript // docmd.config.js export default { plugins: { llms: { fullContext: true // Generates the comprehensive llms-full.txt } } } ``` ## 2. Semantic Heading Integrity AI models utilize H-tags to build a hierarchical map of internal technical relationships. * **Logical Descent**: Never skip heading levels (always go H1 → H2 → H3). * **Technical Density**: Use descriptive headings. Instead of "Auth," use "Implementing OAuth2 Password Grants." * **The H1 Singular**: Ensure your Markdown frontmatter `title` is descriptive; `docmd` utilizes this as the primary semantic entry point. ## 3. Lexical Code Metadata Always explicitly specify the language identifier for fenced code blocks. This allows the AI's internal tokenizer to apply the correct grammar rules during context retrieval. ````markdown ```typescript // Optimised entry point const docmd = new Engine(); ``` ```` ## 4. Using the Context Pipeline The `llms-full.txt` file is a high-fidelity, concatenated stream of your entire static site. * **Prompt Engineering**: Direct your AI: *"Use the semantic structure in /llms.txt and the comprehensive technical content in /llms-full.txt to analyse this codebase."* * **Context Control**: Use `llms: false` in specific page frontmatter to exclude sensitive or internal-only documentation from the public AI context stream. ## 5. High-Fidelity Alt-Text While vision-capable models (Multimodal LLMs) are advancing, descriptive text remains the most reliable signal for reasoning engines. Comprehensive `alt` text for diagrams and screenshots ensures that the agent understands the visual logic even during text-only processing phases. --- ## [Recipe: Integrating Custom Fonts](https://docs.docmd.io/06/recipes/custom-fonts/) --- title: "Recipe: Integrating Custom Fonts" description: "Personalize your site's typography via Google Fonts and CSS variable overrides." --- `docmd` utilizes a reliable CSS variable system to manage design tokens. Personalizing your site's typography involves importing external font assets and overriding the core root variables. ## 1. Define Your Typography Manifest Establish a custom CSS file within your project (e.g., `assets/css/typography.css`). Identify your target font family on [Google Fonts](https://fonts.google.com) and utilize the `@import` directive to fetch the assets. Then, map these fonts to the `docmd` Typography tokens. ```css /* assets/css/typography.css */ /* 1. Import font assets */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&family=JetBrains+Mono&display=swap'); :root { /* 2. Override the primary Sans-Serif stack */ --font-family-sans: "Outfit", -apple-system, system-ui, sans-serif; /* 3. Override the Monospace (Code Block) stack */ --font-family-mono: "JetBrains Mono", monospace; } ``` ## 2. Register the Stylesheet Inject your custom manifest into the build pipeline via the `docmd.config.js` file. ```javascript export default { // ... theme: { name: 'sky', appearance: 'dark', customCss: [ '/assets/css/typography.css' // Path is absolute relative to the site/ directory ] } } ``` ## 3. Verify Changes Execute `docmd dev` to preview the typographical changes. The engine will automatically bundle the custom CSS and apply the variable overrides across all documentation nodes. --- ## [Recipe: Implementing Custom Favicons](https://docs.docmd.io/06/recipes/favicon/) --- title: "Recipe: Implementing Custom Favicons" description: "Establish project-wide branding by adding a custom favicon to your build." --- The favicon is a critical branding element rendered within the browser tab. `docmd` provides a centralized configuration key to automate the injection and resolution of these assets. ## 1. Format Preparation While `docmd` supports `.png` and `.svg` sources, utilize an `.ico` bundle for maximum legacy browser compatibility. Ensure your asset is at least 32x32px. ## 2. Asset Staging Place your processed image within the `assets/` directory of your project source. ```bash # Recommended Directory Mapping my-project/ ├── assets/ │ └── brand-favicon.ico <-- Source asset ├── docs/ └── docmd.config.js ``` ## 3. Configuration Binding Define the `favicon` property within your `docmd.config.js`. The path should reflect the location relative to the final `site/` output root. ```javascript export default { // ... // Maps to site/assets/brand-favicon.ico favicon: '/assets/brand-favicon.ico', // ... }; ``` ## 4. Final Build & Verification Execute `docmd build`. The engine will automatically: 1. Copy the asset to the production build directory. 2. Inject high-priority `<link rel="icon">` tags into the `<head>` of every generated HTML page. --- ## [Recipe: Designing Custom Landing Pages](https://docs.docmd.io/06/recipes/landing-page/) --- title: "Recipe: Designing Custom Landing Pages" description: "Master the noStyle mode to create high-impact marketing pages and product entries." --- While `docmd` excels at structured technical documentation, you can easily bypass the default UI logic to create bespoke landing pages, product showcases, or marketing splash screens using **No-Style Pages**. ## The Architectural Concept By activating `noStyle: true` in a page's frontmatter, the engine strips away the standard Sidebar, Header, and default CSS framework. This provides a "Blank Canvas" while maintaining access to the documentation engine's SEO meta tags and Markdown parsing capabilities. ## Implementation Workflow Create or refine your project's root entry point at `docs/index.md`. ```html --- title: "Next-Gen Documentation" description: "The minimalist, isomorphic, AI-ready engine for modern developers." noStyle: true components: meta: true # Retain structured SEO and OpenGraph tags favicon: true # Retain project branding scripts: false # Opt-out of the default SPA router for this page customHead: | <style> body { font-family: 'Inter', sans-serif; margin: 0; background: #000; color: #fff; } .hero { height: 80vh; display: flex; flex-direction: column; align-items: centre; justify-content: centre; } .btn { background: #3b82f6; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; } </style> --- <div class="hero"> <h1>Architecture Meets Documentation.</h1> <p>Isomorphic execution. AI-optimised context. Zero-reload navigation.</p> <br> <a href="/getting-started/" class="btn">Launch Documentation →</a> </div> <div class="feature-grid"> <!-- Inject custom landing page HTML or specialized Markdown Cards here --> </div> ``` ## Technical Outcomes When the project is compiled via `docmd build`, the root `index.html` will render as a bespoke landing page. This page serves as a high-fidelity entry point that easily directs users into the standardised documentation environment. --- ## [Recipe: Technical Writing Standards](https://docs.docmd.io/06/recipes/writing-guide/) --- title: "Recipe: Technical Writing Standards" description: "Best practices for authoring clear, scannable, and AI-optimised documentation." --- High-quality documentation is defined by its architectural clarity and scannability. This guide outlines the professional standards for utilizing `docmd` features to optimise the user and machine experience. ## Scannability & Semantic Density Technical users rarely read documentation linearly; they scan for specific solutions. * **Descriptive Semantic Headings**: Avoid generic titles. Use "Initialising the Production Pipeline" instead of "Startup." * **Concise Paragraphs**: Encapsulate single concepts into 2-3 sentence blocks to prevent cognitive overload. * **Lexical Emphasis**: Utilize **Bold Text** for key technical terms, file paths, and terminal commands to ensure they remain distinct during rapid scanning. ## Strategy for Interactive Containers `docmd` provides specialized UI blocks. Use them intentionally to reinforce your document's mental model. ### Callouts vs. Cards * **Callouts (Alerts)**: Use for "Out-of-band" information. `tip` for performance shortcuts, `warning` for cautionary logic, and `danger` for critical breaking changes. * **Cards (Structural Blocks)**: Use for "In-band" content clustering. Cards are ideal for feature summaries on a landing page or grouping related configuration keys. ### Sequential Workflows When documenting a multi-step procedure, always utilize the `::: steps` container. This provides a high-impact visual timeline that is significantly more legible than a standard numbered list for both humans and AI agents. ## High-Fidelity Linking `docmd`’s SPA router enables instant, zero-reload navigation. Maintain this experience through reliable referencing: * **Filesystem-Aware Paths**: Always utilize relative paths to your source `.md` files (e.g., `../core/engine.md`). This ensures link integrity across IDEs, local dev servers, and production builds. * **Descriptive Anchors**: Avoid "Read more." Utilize high-fidelity descriptors like "[Analyse the Browser API Reference](/api/browser-api)." ## Code Block Professionalism * **Explicit Language Labeling**: Always specify the language identifier (e.g., ` ```typescript `). This enables both accurate syntax highlighting and reliable AI parsing. * **Automated Portability**: `docmd` automatically attaches interactive copy buttons to every code block; prioritise concise, ready-to-execute snippets to maximise developer utility. --- ## [Release notes for docmd 0.6.0 release](https://docs.docmd.io/06/release-notes/0-6-0/) --- title: "Release notes for docmd 0.6.0 release" description: "Monorepo TypeScript & ESM migration, docmd Dev Environment Tools suite, and CI/CD automation." --- This landmark release marks a complete architectural overhaul of the `docmd` monorepo, transitioning the entire engine to TypeScript and ESM while launching a premium suite of automated developer tools. ## ✨ Highlights ### 🛡️ The docmd Dev Environment Tools We've transformed the contributor workflow into a professional, automated experience. No more manual `npm install` blocks or confusing build sequences. * **`pnpm onboard`**: A single command to set up a fresh fork. It silently handles dependency installation and monorepo builds. Use `--link-docmd` to instantly add `docmd` to your system path. * **`pnpm verify`**: Our new production-grade verification suite. It runs a branded E2E failsafe process, ensuring every parser rule, theme asset, and plugin lifecycle is 100% sound before release. * **`pnpm reset`**: A total environmental purge. Safely stops background servers, unlinks global binaries, and wipes all build caches for a truly fresh start. ### 🏗️ TypeScript & ESM Native The core engine has "grown up." We've migrated the entire monorepo from JavaScript (CJS) to TypeScript (ESM) to ensure long-term stability and developer agility. * **Type-Safe Core**: Internal APIs (Parser, Builder, Plugin System) now feature full type definitions, making contributions safer and eliminating "undefined" runtime errors. * **Modern Modules (ESM)**: Dropped legacy CommonJS in favour of native ECMAScript Modules, resulting in faster execution and better compatibility with the modern JS ecosystem. * **Plugin Ecosystem Upgrade**: We didn't stop at the core! All official plugins (`plugin-mermaid`, `plugin-pwa`, `plugin-search`, `plugin-seo`, `plugin-sitemap`, `plugin-analytics`, `plugin-installer`, `plugin-llms`) have been rewritten in fully typed ESM. Frontend assets are now independently bundled with `esbuild`. * **Version-Specific Navigation**: You can now override the global `navigation` for specific versions, allowing you to tailor the sidebar for legacy documentation versions. ## 📝 Complete Changelog ### 🤖 CI/CD Guardrails * **Automated Verification**: Introduced GitHub Actions that automatically run `pnpm verify` on every **Push** and **Pull Request** to the `main` branch. * **Release Automation**: Modernized the NPM publish workflow to use the new branded verification suite as a final release gatekeeper. ### 🐛 Refinements & Fixes * **Branded CLI**: All developer commands now feature the blue `docmd` branding and consistent dimmed status feedback. * **Playground Bridges**: Added `playground:add` and `playground:remove` workspace aliases to allow testing CLI features safely inside an isolated playground context. * **Optimised Failsafe**: The verification suite now automatically handles monorepo builds and supports a `--skip-setup` flag for lightning-fast CI execution. --- ## [Release notes for docmd 0.6.1 release](https://docs.docmd.io/06/release-notes/0-6-1/) --- title: "Release notes for docmd 0.6.1 release" description: "Hotfix release resolving NPM publishing failures and an installer runtime error." --- This is a hotfix release addressing pipeline publication issues and a critical runtime error in the plugin installer introduced in `0.6.0`. ## 🐛 Bug Fixes ### 🚀 CI/CD NPM Publisher * **Monorepo Workspaces**: Fixed a major bug in the `docmd Release to NPM` GitHub Actions workflow where `npm publish` interpreted package paths as GitHub remote repositories. * **Fail-Safe Publishing**: Completely overhauled the publisher to robustly handle partial updates (e.g. ignoring `EPRIVATE` packages and safely skipping already-published packages) without failing the release pipeline. ### 🔌 Plugin Installer (Runtime) * **Missing Registry**: Resolved a critical `MODULE_NOT_FOUND` error that crashed `docmd build` on user sites. The `registry/plugins.json` database was inadvertently excluded from the published NPM tarball, causing imports to fail in production. * **Explicit Whitelisting**: Added the `registry` folder to the `"files"` array in `@docmd/plugin-installer`'s `package.json`, ensuring the registry data is properly bundled in all future NPM releases. --- ## [Release notes for docmd 0.6.2 release](https://docs.docmd.io/06/release-notes/0-6-2/) --- title: "Release notes for docmd 0.6.2 release" description: "Smart Version Switcher, Navigation V2 (navigation.json), Breadcrumbs, Analytics V2, and core security fixes." --- The `docmd` 0.6.2 release focuses on refining the navigation architecture for complex, versioned documentation sites while providing deep insights through enhanced analytics and improving site-wide user experience with automated breadcrumbs. ## ✨ Highlights ### Smart Version Switcher Say goodbye to 404s when switching versions. The version switcher now intelligently checks if the current page exists in the target version. If an exact match isn't found, it gracefully falls back to the root of that version instead of showing a "Not Found" page. ### Navigation Architecture V2 (`navigation.json`) Manage large, versioned documentation sites with ease. You can now place a `navigation.json` file directly inside your versioned documentation folders (e.g., `docs-05/navigation.json`). This eliminates the need for massive, duplicated navigation arrays in your main `docmd.config.js`. ### Automated Breadcrumbs Every documentation page now features automated breadcrumbs located right above the title. This improves user orientation within deeply nested hierarchies and provides better context for both human readers and AI models. Breadcrumbs are enabled by default and can be toggled via `config.layout.breadcrumbs`. ### Analytics V2 (Auto-Event Tagging) The Analytics plugin has been significantly upgraded to support auto-event tagging. It now automatically tracks: * **External Link Clicks**: Understand where your users go after reading your docs. * **Downloads**: Automatically track clicks on PDFs, ZIPs, and other binary assets. * **Search Keywords**: Track what users are looking for with debounced keyword logging (can be disabled via `trackSearch: false`). * **Navigation Interactions**: Track Table of Contents (TOC) clicks and permalink (heading anchor) usage. ## 📝 Complete Changelog ### 🛠️ Core Generator * **V2 Nav Resolution**: Added support for the `navigation.json` resolution pattern. * **Breadcrumb Logic**: Implemented automated crumb trail calculation based on navigation active-state. * **Stable Version Switching**: updated `docmd-main.js` with `fetch(HEAD)` validation for version links. ### 🛡️ Security & Stability * **Dependency Fix**: Patched a high-priority vulnerability in the `flatted` library related to unbounded recursion DoS in the `parse()` revive phase. * **PWA Safety**: Added an explicit Service Worker unregistration safety net to prevent ghost caches for users who remove the PWA plugin. ### 🔌 Plugins * **Analytics V2**: New `autoEvents` option (enabled by default) for event tracking without manual code injection. --- ## [Release notes for docmd 0.6.3 release](https://docs.docmd.io/06/release-notes/0-6-3/) --- title: "Release notes for docmd 0.6.3 release" description: "Contextual Heading IDs, improved Table of Contents accuracy, and deep-link disambiguation." --- The `docmd` 0.6.3 release introduces major refinements to the project's structural integrity, a important patch to the hot-reload Dev Server and a complete overhaul of our internal build and linting verification pipeline. ## ✨ Highlights ### Contextual Heading IDs (Nested Permalinks) Duplicate headers (like "Options" or "Examples") appearing multiple times across different sections of a single page are now automatically disambiguated. IDs are now "Nested" based on their parent hierarchy. For example, a `### Options` header under a `## docmd dev` section will now correctly generate the ID `#docmd-dev-options` instead of a generic `#options`. This ensures: - **Unique Deep Links**: Every section on a page now has a truly unique permalink. - **Accurate TOC**: The Table of Contents now points to the correct section position. - **Enhanced Search**: The search engine can now link users to the exact sub-section they are looking for. ### Collision Safety In the rare case where identical headers appear within the same section, `docmd` now implements an automated numbering suffix (e.g., `#options-1`, `#options-2`), preventing ID collisions and ensuring valid HTML across your entire site. ## 📝 Complete Changelog ### 🛠️ Core Parser - **Smart ID Generation**: Updated the `headingIdPlugin` to track heading levels and parent IDs. - **TOC Integrity**: Improved ID extraction logic to ensure nested IDs are accurately reflected in the sidebar and navigation. - **Search Optimisation**: Refined the metadata generation for headings, providing higher-quality search handles to the MiniSearch engine. ### 🏗️ Internal Tooling & Developer Experience - **Strict Linting Automation**: Activated and strictly integrated ESLint logic directly into the CI verification workflows natively across the entire monorepo (`@docmd-monorepo`). - **Release Preparation Pipeline**: Introduced the new `pnpm prep` CLI tool utilizing seamless end-to-end sandbox reset, installation, compilation, linting, intensive test executions, and security audits into one single cohesive pre-flight deployment sequence! - **Resolved Auditing Traps**: Forced `pnpm.overrides` against `flatted` legacy trees to extinguish false-positive high-risk security blockages during deployment cycles. ### 🐛 Bug Fixes - **Dev Server**: Fixed an issue where the `docmd dev` command would fail to broadcast hot-reload signals due to a `WebSocket is not defined` error in the Node environment. --- ## [Release notes for docmd 0.6.4 release](https://docs.docmd.io/06/release-notes/0-6-4/) --- title: "Release notes for docmd 0.6.4 release" description: "Reliable Emoji Parsing, Auto-Adjusting Grids Container, and Dependency Security." --- The `docmd` 0.6.4 release introduces major refinements to the project's structural integrity with native support for grids, bulletproof container title parsing including emojis, and security upgrades for dependencies. ## ✨ Highlights ### Reliable Title Emojis Inline markdown elements, specifically emojis (e.g., `:rocket:`), are now perfectly parsed within the double quotes of container titles! This supports `card`, `callout`, `collapsible`, `tabs`, and `button` components transparently. The improved parser strictly ignores stray characters outside string headers, ensuring max stability. ### Auto-Adjusting Grids Container Added new `::: grids` and `::: grid` layout wrappers. They form an inherently responsive grid structure that automatically partitions available width (up to typical 4-column limits) while stacking gracefully on narrow mobile displays. No HTML or manual CSS required! ## 📝 Complete Changelog ### 🛠️ Core Parser - **Strict Emoji Parsing**: Updated the `parseQuotedTitle` helper to safely extract strings and ignore trailing unquoted inputs. - **Grids Component**: Introduced the `grids` structural container. ### 🐛 Bug Fixes - **Checklist Styling**: Resolved an issue where bullet points would still mistakenly render alongside checkboxes in standard markdown task lists. Task items now utilize a reliable flexbox layout to isolate the checkbox properly. - **Dependency Security**: Executed a comprehensive workspace audit to upgrade transitive dependencies (including patching known vulnerabilities in `picomatch` and `brace-expansion`). ## Migration Guide No breaking changes. You can upgrade safely without altering any of your existing markdown content. --- ## [Release notes for docmd 0.6.5 release](https://docs.docmd.io/06/release-notes/0-6-5/) --- title: "Release notes for docmd 0.6.5 release" description: "Zero-Latency URL Embeds Engine, Massive Ecosystem Integrations, and Sandbox Hardening." --- The `docmd` 0.6.5 release is an explosive visual deployment introducing official native support for **13+ leading media and developer ecosystem platforms**, easily bridging rich components directly into docmd output using zero-latency compilation powered by `embed-lite@0.1.4`. ## ✨ Highlights ### Zero-Latency Built-in Embeds We've integrated an entirely agnostic embedding bridge natively directly inside the core Markdown parser! You can now map dynamic video, audio, code snippets, and social media blocks onto the page purely by typing its exact URL dynamically: ```md ::: embed https://www.youtube.com/watch?v=dQw4w9WgXcQ ``` The internal engine rigidly intercepts the syntax, automatically validates the ecosystem, and completely formats the resulting player into our secure CSS-bounded UI frameworks - with absolutely out-of-the-box native Responsive Support! ### Core Platforms Fully Supported: * **Video:** YouTube (standard and native 9:16 Shorts), Vimeo, Dailymotion, TikTok * **Social Connectivity:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn (Intelligently intercepts messy `ugcPost` links!) * **Developers & Designers:** GitHub Gists, CodePen, Figma, Google Maps * **Audio Renders:** Spotify, SoundCloud ## 📝 Complete Changelog ### 🛠️ Core UI Integrations - **TikTok V2 Architecture**: Completely sidestepped TikTok's external un-reliable `embed.js` blockquotes (which commonly die against ad-blockers and geographic firewalls) by natively routing docmd components into TikTok's secure, unblockable `/embed/v2` data pipeline! - **GitHub Gists Sandbox Typographic Execution**: Eradicated the raw skeleton fonts usually generated by default Gist injections. `docmd 0.6.5` elegantly forces `data-URIs` payloads to flawlessly inherit our strict premium typographic suite (`-apple-system, Roboto, sans-serif`) with deeply smoothed `.gist` boundary borders directly natively into legacy outputs. - **Embedded Ratio Constraints**: Connected explicit internal flags (e.g. `data-short="true"`) to accurately squash vertical ratios onto `9:16` bounding boxes (ideal for YouTube Shorts) completely dynamically while automatically managing `16:9` ratios for Google Maps and standard iFrames natively using internal CSS layouts. - **Dependencies Bump**: System components heavily locked aggressively against `embed-lite@0.1.4`. ## Migration Guide No breaking changes. You can upgrade safely without altering any of your existing markdown content! --- ## [Release notes for docmd 0.6.6 release](https://docs.docmd.io/06/release-notes/0-6-6/) --- title: "Release notes for docmd 0.6.6 release" description: "The Great Shedding - removing massive dependencies in favour of ultra-light, zero-config in-house packages." --- The `docmd` 0.6.6 release is a massive architectural deployment fundamentally overhauling the core engine to prioritise raw compilation speed and minimal installation footprint by stripping out the heaviest dependencies in the open-source ecosystem in favour of bespoke, ultra-fast custom architectures. ## ✨ Highlights ### The Great Dependency Shedding Instead of relying on heavy legacy packages with cascading "waterfall" dependencies, `docmd` now utilizes native solutions and our own newly published `lite-*` libraries. This collapses the internal engine constraints from ~30 cascading external packages down to exactly **1** (`yaml`), dropping ~2.5MB of weight and making compilation up to **8.1x faster**! ### Core Packages Eliminated: | Legacy Package | New Engine | Waterfall Reduction | Performance Gain | Approx Weight Shed | |------------------|-------------|---------------------|-------------------|--------------------| | **`highlight.js`**| `lite-hl` | No waterfall deps | **~8.1x faster** | **~2MB** | | **`ejs`** | `lite-template`| 7 packages removed | **~3.2x faster** | **~50KB** | | **`gray-matter`** | `lite-matter` | 9 packages removed | Highly optimised | **~100KB** | | **`chokidar`** | `native fs` | 14+ packages removed| Native speed | **~200KB** | | **`commander`** | `util.parseArgs`| No 3rd party deps | Zero overhead | **~60KB** | ## 📝 Complete Changelog ### 🛠️ Core Engine Patches - **Zero-Config Root Index Fix**: Resolved the pervasive 404 bug at the domain root. If an `index.md` is missing, the auto-router now successfully dictates the designated fallback homepage directly to the generator engine natively. - **Native EJS Content Pages**: `.ejs` files are now recognised as first-class content pages natively by the auto-router. They process frontmatter dynamically and render alongside standard Markdown files easily. - **Recursive Frontmatter Stripping**: When utilizing `<%- await include(...) %>` inside complex nested components, `docmd` natively strips YAML frontmatter blocks from the sub-templates before rendering them, guaranteeing clean markdown compilation. ### 📦 The `lite-*` Public Releases - **lite-template@0.1.2**: Evolved into a genuinely standalone async alternative to EJS, natively resolving `include()` from the disk (or virtually via `includer` memory hooks). - **lite-hl@0.1.2**: Re-mapped to guarantee pixel-perfect legacy `highlight.js` CSS theme compatibility. Upgraded to support 60+ complex shell commands (`grep`, `find`, `awk`) and dynamic `$VARIABLES`. - **lite-matter@0.1.1**: Officially released as a reliable standalone metadata extraction library capable of natively parsing YAML structures instantly without arbitrary parsing bottlenecks. - **TypeScript & ESM Support**: All `lite` packages have strict `exports` map resolution introduced to guarantee flawlessly typed ESM module ingestion across modern IDE architectures natively. ## Migration Guide No breaking changes. You can upgrade safely without altering any of your existing markdown content! --- ## [Release notes for docmd 0.6.7 release](https://docs.docmd.io/06/release-notes/0-6-7/) --- title: "Release notes for docmd 0.6.7 release" description: "Live Build Engine Optimisation and Absolute Path Correction." --- The `docmd` 0.6.7 release brings a massive upgrade to our landing-page capabilities with the introduction of the new Hero 2.0 component, alongside important stability patches for our build infrastructure and container parsing logic. ## ✨ Highlights ### 🚀 Landing Page Revolution & Hero We've significantly empowered **No-Style Pages** (docmd's answer to landing pages). You can now selectively re-enable the core `menubar` and `scripts` while maintaining a blank canvas, allowing you to build high-fidelity entry points that feel deeply integrated with your documentation. To make building those pages effortless, we are introducing the **Hero Container**. Designed for high-impact visual storytelling, this component automatically renders stunning, responsive hero sections. It supports advanced features like `layout:split` for side-by-side media, `layout:slider` for interactive carousels, and `glow:true` for premium visual effects. ### 🍱 Enhanced Embed Ergonomics We've updated the `::: embed` syntax to be more flexible, now supporting optional brackets or quotes around the URL (e.g., `::: embed [url]` or `::: embed "url"`), improving structural consistency and developer ergonomics. ## 📝 Complete Changelog ### 🛠️ Core UI & Build Patches - **Hero Integration**: Added the powerful new `::: hero` markdown component with split and slider layout generation. - **Container Depth Tracking Fix**: Resolved a critical parsing bug where single-line containers (like `::: button` and `::: embed`) would corrupt the depth tracking of parent containers, breaking complex nested layouts. - **Markdown Rendering on No-Style Pages**: Fixed a regression where `noStyle: true` bypassed the markdown engine, ensuring core components like buttons and callouts work as expected on custom pages. - **Enhanced Component Opt-in**: Added `menubar: true` and `spa: true` toggles for `noStyle` pages, giving developers granular control over the landing page environment. - **Live Build Source Fallback**: Implemented an automated asset discovery resolver that gracefully falls back to looking for build components in the `dist/` folder when the package is installed as a pure NPM dependency. ## Migration Guide No breaking changes. You can upgrade safely without altering any of your existing markdown content! --- ## [Release notes for docmd 0.6.8 release](https://docs.docmd.io/06/release-notes/0-6-8/) --- title: "Release notes for docmd 0.6.8 release" description: "Plugin API expansion with WebSocket RPC, source editing tools, and the new threads plugin." --- The `docmd` 0.6.8 release is a foundational leap for the plugin ecosystem. It introduces a **WebSocket RPC protocol** that enables real-time browser-to-server communication, powerful **source editing tools** for manipulating markdown files from the browser, and a brand-new **Threads plugin** for inline discussion comments - all without adding any new runtime dependencies. ## ✨ Highlights ### 🔌 WebSocket RPC - Live Plugin Communication The dev server's existing WebSocket connection (used for live-reload) has been upgraded with a **JSON-based RPC protocol**. Plugins can now register server-side action handlers that the browser can call in real-time. This opens the door to live-editing features, collaborative workflows, and interactive documentation tools. A new `window.docmd` browser API is automatically injected during development, providing: - `docmd.call(action, payload)` - RPC calls with response - `docmd.send(name, data)` - Fire-and-forget events - `docmd.on(name, callback)` - Subscribe to server-pushed events - `docmd.afterReload()` / `docmd.scheduleReload()` - State persistence across live reloads ### 🧰 Source Editing Tools A new `source-tools` utility provides block-level markdown manipulation from plugin code. It can locate text within blocks, wrap content with syntax markers, insert/replace/remove blocks - all with frontmatter-aware line tracking and path traversal protection. ### 🧵 Threads Plugin (Alpha) Introducing `@docmd/plugin-threads` - inline discussion threads stored directly in your markdown files. Select text, leave comments, reply, react with emoji, and resolve threads. No database needed - comments are the source of truth in the `.md` files. ### 📤 Parser Export The `createDepthTrackingContainer` function is now exported from `@docmd/parser`, allowing external plugins to register custom `::: container` syntax with proper nesting support. ## 📝 Complete Changelog ### 🔌 Plugin API - **WebSocket RPC Protocol**: JSON-based message handling alongside the existing `reload` string protocol for full backward compatibility. - **Action Dispatcher**: Routes incoming RPC calls to registered plugin action handlers with a sandboxed `ActionContext`. - **Plugin Hooks Expansion**: Plugins can now export `actions` and `events` objects alongside existing build-time hooks. - **Type Definitions**: New `PluginModule` interface documents the full plugin contract (`types.ts`). - **Browser API Client**: `docmd-api.js` injected automatically during dev mode with reconnect and retry logic. ### 🧰 Core Improvements - **Plugin Loader Hardening**: Refactored the core module resolver with reliable `try/catch` fallbacks to gracefully warn against malformed plugins without crashing the build or throwing. - **Source Tools**: New `getBlockAt`, `findText`, `wrapText`, `insertAfter`, `replaceBlock`, `removeBlock` utilities for markdown source manipulation. - **RPC DOM Mapping**: Injected `data-source-file` automatically into the UI `<body>` layout container, enabling browser-to-server file tracking during interaction loops. - **Bundlephobia Compatibility**: Explicitly defined the `"browser": false` boundary on `@docmd/core` to prevent legacy external compilers from incorrectly trying to browserify server-side engine APIs. - **Codebase Standardisation**: Comprehensive alignment of license boundaries, boilerplate headers, trailing whitespaces, and metadata schemas across all plugins, legacy setups, and failsafe scripts. - **Git Dev Info**: Dev server detects git user info and injects it for plugin author identification (lazy-loaded). - **Path Security**: All file operations are sandboxed via `safePath()` validation against the project root. - **Native File Watcher**: Preserved the chokidar-free `fs.watch` implementation introduced in 0.6.6. ### 🧵 New Plugin: Threads - Text selection and highlight-based thread anchoring (`==text=={threadId}` syntax). - Full CRUD: create threads, add/edit/delete comments, reply chains, emoji reactions. - Thread resolution with author tracking and timestamps. - Author profiles stored in `.threads/authors.json` with Gravatar support. - Lit-based Web Components for the client-side UI. ### 📤 Parser - **Exported `createDepthTrackingContainer`**: Available via `import { createDepthTrackingContainer } from '@docmd/parser'` for plugin authors building custom container syntax. - Added comprehensive JSDoc documentation to the container API. ### 🧹 Bug Fixes & Refactors - **TypeScript Overhauls**: Vast strict-null enforcement, non-implicit global declarations, and DOM explicit-typing integrations finalized inside `@docmd/plugin-mermaid` and `@docmd/plugin-search` clients. - **CSS Layout Issues**: Fixed iframe aspect-ratios, Hero component bounds, and plugin-threads text area sizing. Realigned responsive padding breakpoints. - **Legacy Header Cleanups**: Stripped conflicting or malformed document headers from ecosystem forks and standardised `docmd.io` branding definitions consistently across active `packages/*`. ## Migration Guide No breaking changes. The WebSocket RPC protocol is additive - existing live-reload behaviour is fully preserved. The new `docmd-api.js` replaces the inline reload script with an enhanced version that handles both reload and RPC. --- ## [Release notes for docmd 0.6.9 release](https://docs.docmd.io/06/release-notes/0-6-9/) --- title: "Release notes for docmd 0.6.9 release" description: "Core architectural stability, reliable plugin dynamic resolution, and the official KaTeX math plugin." --- The `docmd` 0.6.9 release focuses on significant core stability updates, hardening the plugin resolution architecture, and the introduction of a highly requested mathematical plugin using server-side rendered LaTeX. ## ✨ Highlights ### 🧮 Math Plugin (KaTeX) Introducing `@docmd/plugin-math` - an official extension providing native parsed `LaTeX` and `KaTeX` support easily decoupled into docmd. Writing `$E = mc^2$` or block arrays `$$` automatically hooks into reliable server-side build steps producing purely static visual nodes. No client-side Javascript compilation is required! ### 🏗️ Plugin Security Hardening The plugin resolution architecture has been completely rewritten. Shorthand names (e.g. `math`, `search`) are now **strictly reserved** for official `@docmd/plugin-*` packages. Third-party plugins must be referenced by their full package name - there is no fallback cascade to community or bare npm names. This eliminates supply-chain attack vectors via namespace squatting entirely. ### 🧹 Layout & UI Stability This release contains sweeping fixes protecting custom UI definitions matching `#101`. `noStyle` structurally broken layout grids have been resolved restoring total CSS conformity across customised landing pages heavily featuring `.menubar` blocks. Navigational headers explicitly linked toward raw `.md` domains are also safely purged enforcing clean-urls matching the generated HTML structure! ## 📝 Complete Changelog ### 🧰 Core Improvements - **Plugin Security Hardening**: Rewrote `core/src/utils/plugin-loader` - shorthand names now resolve exclusively to official `@docmd/plugin-*` scope. Third-party plugins require full package names with no fallback cascade. - **Expanded Asset Parsing (#100)**: Rewrote `core/src/engine/assets.ts` to natively verify and append nested `config.src/assets` definitions concurrently alongside root `CWD/assets` supporting local documentation directories explicitly. - **UX Menu Linking**: Menubar now uses absolute base paths instead of relative paths, fixing broken URLs on versioned pages where menubar links incorrectly resolved to version-scoped paths (e.g. `/05/nostyle` instead of `/nostyle`). ### 🧵 Bug Fixes & Refactors - **miniSearch Fatal Crashes (#8)**: Fixed a runtime structural array duplication resulting in a failed indexing routine. Added `seenIds` tracking inside `plugins/search/src/index.ts` intercepting overlapping layout blocks silently. - **Menubar Flex Structural Collapse (#101)**: Found and deleted orphaned closing elements inside `menubar.ejs`. Options menus (`theme`, `search`) correctly load into `menubar-right` aligned grids completely separate from iterated loop structures bridging un-styled overrides easily. - **SPA Sidebar URL Nesting**: Fixed an issue where SPA navigation caused sidebar hrefs to nest incorrectly (e.g. `/nostyle/nostyle/`). The SPA router now resolves fetched sidebar hrefs to absolute paths before syncing them into the current DOM. - **Removed Implicit `.md` Stripping**: The config normalizer no longer silently strips `.md` extensions from navigation and menubar URLs. Users should use clean URLs in their config as documented - this prevents hidden routing conflicts with SPA navigation. - **TypeScript Strictness**: Added `"types": ["node"]` to monorepo base `tsconfig.json` and replaced `import.meta.dirname` with `fileURLToPath` for universal type compatibility across all packages. ## Migration Guide No breaking changes for users of official plugins. If you were relying on shorthand names for third-party plugins, update your `docmd.config.js` to use the full package name instead. --- ## [Assets Management](https://docs.docmd.io/06/theming/assets-management/) --- title: "Assets Management" description: "How docmd handles CSS, JavaScript, and Image assets during the build process." --- `docmd` takes a "Mirror & Map" approach to assets. This ensures that your local development paths stay consistent with your production build. ## Directory Structure By default, `docmd` looks for an `assets/` folder in your project root. ```bash my-docs/ ├── assets/ # Source Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Content ├── docmd.config.js └── site/ # Build Output (Automatically mirrored) ``` ## Automatic Copying (v0.5.1+) When you run `docmd build` or `docmd dev`: 1. **The Mirroring Logic**: The entire contents of your `assets/` folder are recursively copied to `site/assets/`. 2. **Stability**: We use a hardened copy engine with automatic retries to prevent "File Busy" or "ENOENT" errors on macOS and modern SSDs. 3. **Referencing**: You should always reference assets from your Markdown or Config using the **root-relative** path: ```markdown ![Logo](/assets/images/logo.png) ``` ## Custom CSS & JS Integration To link your assets to every page, add them to your theme configuration: ```javascript // docmd.config.js export default { theme: { customCss: ['/assets/css/branding.css'] }, customJs: ['/assets/js/utils.js'] } ``` ## AI Recognition Strategy When adding assets: * **Organise by type**: Keep `/css`, `/js`, and `/images` separate. This helps AI agents locate relevant styles or scripts instantly when you ask them to "edit the header colour". * **Use Descriptive Filenames**: Naming an image `authentication-flow-diagram.png` provides much more context to the `llms.txt` crawler than `img_01.png`. --- ## [Available Themes](https://docs.docmd.io/06/theming/available-themes/) --- title: "Available Themes" description: "Explore docmd's built-in themes including Sky, Ruby, and Retro. Learn how to switch themes with a single config line." --- `docmd` provides a set of professionally designed, light/dark responsive themes. You can switch your entire site's aesthetic by changing a single key in `docmd.config.js`. ## How to Switch Themes ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system', // Options: 'light', 'dark', 'system' } } ``` ## Built-in Theme Gallery | Theme | Best For | Vibes | | :--- | :--- | :--- | | `default` | Low-profile docs | Minimal, lightweight, clean | | `sky` | Product Docs | Modern, premium, standard-issue | | `ruby` | Brand Identity | Sophisticated, serif headers, vibrant | | `retro` | Dev Tools | 80s Terminals, monospace, neon accents | <div class="theme-picker" style="display: flex; gap: 10px; margin: 20px 0;"> <button onclick="switchDocTheme('default')" class="docmd-button" style="color:#fff;background: #2e2e2e;">Default</button> <button onclick="switchDocTheme('sky')" class="docmd-button" style="color:#fff;background: #0097ff;">Sky</button> <button onclick="switchDocTheme('ruby')" class="docmd-button" style="color:#fff;background: #960b0b;">Ruby</button> <button onclick="switchDocTheme('retro')" class="docmd-button" style="color:#fff;background: #a95308; border: 1px solid #0ec80e;">Retro</button> </div> ### 1. `sky` (Default) The gold standard for modern documentation. It features crisp typography, subtle transitions, and high-contrast light/dark modes that match modern SaaS platforms. ### 2. `ruby` A high-elegance theme using serif typography for headers and a deep, jewel-toned colour palette. Perfect for documentation that needs to feel authoritative and premium. ### 3. `retro` A nostalgia-fueled theme inspired by vintage computing. Features include phosphor-green text on black backgrounds (in dark mode), scanline effects, and monospace fonts like Fira Code by default. ### 4. `default` A total "Blank Slate" theme. Use this if you plan on adding extensive custom CSS and don't want any built-in design layers interfering with your branding. ## Theming Architecture 1. **CSS Layering**: Themes are additive. Choosing `sky` actually loads the base `default` styles and then overlays the `sky` aesthetic on top. 2. **Native dark-mode**: Every theme includes a first-class dark mode implementation. 3. **No Refresh**: When users switch themes via the UI, the SPA engine updates the `--docmd-primary` variables instantly without a page reload. ::: callout tip When describing your documentation layout to an AI developer tool, mentioning your theme (e.g., "I'm using the `retro` theme") helps the model suggest custom CSS overrides that align with that specific theme's variable schema. ::: --- ## [Custom Styles & Scripts](https://docs.docmd.io/06/theming/custom-css-js/) --- title: "Custom Styles & Scripts" description: "Inject your own CSS and JS files to extend docmd's functionality and branding." --- While `docmd` themes are highly flexible, you may want to inject your own stylesheets or interactive scripts. This is done via the `theme.customCss` and `customJs` arrays in your configuration. ## Custom CSS Use `theme.customCss` to override existing styles or add new ones. ```javascript // docmd.config.js export default { theme: { customCss: [ '/assets/css/branding.css' // Path relative to site root ] } } ``` ### How it Works 1. Place your CSS file inside your project’s assets folder (e.g., `docs/assets/css/branding.css`). 2. `docmd` will automatically copy it to the build folder and inject a `<link>` tag into every page. 3. Custom CSS is loaded **after** the theme styles, ensuring your overrides take priority. ## Custom JavaScript Use the top-level `customJs` array for scripts that add behaviour or integrate 3rd-party services. ```javascript // docmd.config.js export default { customJs: [ '/assets/js/feedback-widget.js' ] } ``` ### Life-cycle Awareness Scripts are injected at the bottom of the `<body>` tag. Since `docmd` is a **Single Page Application (SPA)**, remember that: * The page does not fully reload when navigating between links. * You may need to listen for the `docmd:navigated` event to re-initialise your scripts on new pages. ```javascript // Example: Re-init on page change document.addEventListener('docmd:page-mounted', () => { console.log('New page loaded via SPA router'); initMyCustomWidget(); }); ``` ::: callout tip Adding custom CSS and JS allows AI models (like ChatGPT) to suggest much more tailored UI improvements. If you mention "I have a custom `branding.css` file", the model can provide specific selectors that won't conflict with the core `docmd` engine. ::: --- ## [Customisation & Variables](https://docs.docmd.io/06/theming/customisation/) --- title: "Customisation & Variables" description: "A complete reference of docmd's CSS variables and component classes for advanced styling." --- `docmd` is built using a CSS variable-first architecture. This means you can restyle your entire site by simply overriding a few keys in a `:root` block without writing complex CSS selectors. ## Global Variable Reference | Variable | Default (Light) | Default (Dark) | Description | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | Main page background. | | `--text-color` | `#3f3f46` | `#a1a1aa` | Standard body text. | | `--text-heading` | `#09090b` | `#fafafa` | Title and Header colours. | | `--link-color` | `#068ad5` | `#068ad5` | Primary accent / links. | | `--border-color` | `#e4e4e7` | `#27272a` | Dividers and borders. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Navigation background. | | `--ui-border-radius` | `6px` | `6px` | Rounding for all UI items. | | `--sidebar-width` | `260px` | `260px` | Sidebar column width. | ## Example Override To change your site's primary accent colour, add this to your `customCss`: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Component Targeting If you need to style specific components, use these top-level classes: * `.main-content`: The wrapper for all Markdown content. * `.sidebar-nav`: The internal navigation list. * `.page-header`: The top navigation bar. * `.docmd-search-modal`: The search overlay. * `.docmd-tabs`: Tab container components. * `.callout`: The alert/note boxes. ## Troubleshooting specificity Most `docmd` styles use low specificity. If your overrides aren't applying, ensure your `customCss` is registered correctly and check if adding a `body` prefix (e.g., `body .main-content`) helps. ::: callout tip Because `docmd` uses standard CSS variables, you can ask an AI: *"Give me a professional colour palette using --link-color and --bg-color for docmd"*. The model will be able to provide ready-to-paste CSS that integrates perfectly with the built-in themes. ::: --- ## [Icons](https://docs.docmd.io/06/theming/icons/) --- title: "Icons" description: "How to use and customise Lucide icons in your documentation." --- `docmd` comes with built-in support for the [Lucide](https://lucide.dev/) icon library. Icons can be used in your navigation sidebar, buttons, and custom components to provide visual cues and improve scannability. ## Navigation Icons Assign an icon to any navigation item in your `docmd.config.js`. Use the kebab-case name of any icon found on the Lucide website. ```javascript navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Setup', path: '/setup', icon: 'settings' } ] ``` ## Button Icons You can also use icons inside your button labels by including the raw HTML or using standard Lucide naming if supported by your theme. ```markdown ::: button "Download" /download icon:download ``` ## CSS Styling All icons are rendered as inline SVGs with the class `.lucide-icon`. You can globally change their size or stroke weight in your `customCss`: ```css .lucide-icon { stroke-width: 1.5px; /* Thinner icons for a modern look */ width: 1.2rem; height: 1.2rem; } /* Target a specific icon */ .icon-rocket { color: #ff5733; } ``` ## Icon Reference We support the entire Lucide library. You can browse the thousands of available icons here: ::: button "Browse Lucide Icons" external:https://lucide.dev/icons --- ## [Light & Dark Mode](https://docs.docmd.io/06/theming/light-dark-mode/) --- title: "Light & Dark Mode" description: "How to configure the default viewing mode and manage the theme switcher for the best user experience." --- `docmd` provides built-in support for light and dark colour schemes. It detects user system preferences automatically and allows manual overrides via a UI toggle. ## Default Viewing Mode You specify the starting state of your documentation in `docmd.config.js`. ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system' // Options: 'light', 'dark', 'system' (default) } } ``` * **`system`**: Matches the user's OS preference (Recommended). * **`light`**: Force light mode on initial load. * **`dark`**: Force dark mode on initial load. ## Configuring the Toggle Button The theme switcher is part of the **Options Menu**. You can control its visibility and position within the `layout` object. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom' components: { themeSwitch: true // Show or hide the Sun/Moon toggle } } } ``` ## How it works (Technical) The theme engine applies a `data-theme` attribute to the `<body>` tag: * `<body data-theme="light">` * `<body data-theme="dark">` If you are using a themed design like `sky`, the attribute will be `sky-light` or `sky-dark`. ### CSS Variables `docmd` themes use CSS variables for all colours. You can override these variables in your own CSS to customise the look of either mode. ```css /* Custom CSS override */ :root { --docmd-primary: #4f46e5; /* Primary accent for light mode */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* Primary accent for dark mode */ } ``` ## User Persistence When a user manually toggles the mode, their preference is stored in `localStorage`. `docmd` instantly reads this value on every page load to prevent "theme flickering" (FOUC). ::: callout tip When generating content, LLMs prefer high-contrast structures. `docmd` ensures that code snippets and callouts remain accessible in both modes, ensuring that `llms-full.txt` payloads are correctly understood as semantic blocks regardless of which mode was active during the build. ::: --- ## [Browser API (Client-Side)](https://docs.docmd.io/07/api/browser-api/) --- title: "Browser API (Client-Side)" description: "Interact with docmd from the browser - live compilation and dev-mode plugin communication." --- `docmd` provides two browser APIs: the **isomorphic compile engine** for rendering markdown in the browser, and the **dev-mode plugin API** for real-time communication with the dev server. ## Isomorphic Compile Engine The same engine that generates static sites in Node.js can run entirely within a web browser. This is ideal for building CMS previews, interactive playgrounds, or embedding documentation into existing web applications. ### Installation via CDN ```html <!-- Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- The Isomorphic Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` Compiles raw Markdown into a full HTML document string using the default `docmd` layout. **Parameters:** - `markdown` (String): The raw Markdown content. - `config` (Object): Configuration overrides (same schema as `docmd.config.js`). **Returns:** `Promise<String>`: The complete HTML document. ### Example: Live Preview To ensure style isolation, it is recommended to render the output inside an `<iframe>` using the `srcdoc` attribute. ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: 'Preview', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## Dev-Mode Plugin API During `docmd dev`, a `window.docmd` global is automatically injected into every page. This API enables real-time communication between browser-side plugin code and server-side action handlers via WebSocket RPC. ::: callout info "Dev Mode Only" The plugin API methods below are only available during `docmd dev`. They are not included in production builds. ::: ### `docmd.call(action, payload)` Call a server-side action handler registered by a plugin. Returns a promise that resolves with the handler's return value. ```javascript // Call a plugin action and get a result const threads = await docmd.call('threads:get-threads', { file: 'docs/getting-started.md' }); console.log(threads); // Array of thread objects ``` If the action modifies source files, the page automatically reloads after the promise resolves. ### `docmd.send(name, data)` Send a fire-and-forget event to the server. No response is returned. ```javascript // Notify the server of a page view (no response expected) docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` Subscribe to server-pushed events. Returns an unsubscribe function. ```javascript // Listen for server-broadcast events const unsub = docmd.on('threads:updated', (data) => { console.log('Threads updated:', data); }); // Later: unsubscribe unsub(); ``` ### `docmd.afterReload(name, callback)` Declare a handler that runs after a page reload. If context was stashed with `scheduleReload`, the callback receives it. ```javascript // Restore scroll position after a live-reload docmd.afterReload('scroll-restore', (ctx) => { window.scrollTo(0, ctx.scrollY); }); ``` ### `docmd.scheduleReload(name, context)` Stash context into `sessionStorage` for a named `afterReload` handler. The matching handler fires with this context after the next page reload. ```javascript // Before a file edit triggers a reload, save state docmd.scheduleReload('scroll-restore', { scrollY: window.scrollY }); ``` ## Considerations - **No File System**: The browser engine cannot scan folders. You must provide the `navigation` array explicitly in the config object if you need a sidebar. - **Node-Only Plugins**: Plugins that rely on Node.js APIs (like Sitemap or LLM text generation) are disabled in the browser environment. - **WebSocket Connection**: The dev-mode API requires an active WebSocket connection to the dev server. It will auto-reconnect with exponential backoff if the connection drops. --- ## [CLI Commands](https://docs.docmd.io/07/api/cli-commands/) --- title: "CLI Commands" description: "Command-line reference for docmd - all available commands and options." --- ## Commands Overview | Command | Description | |:--------|:------------| | [`docmd init`](#docmd-init) | Scaffold a new documentation project | | [`docmd dev`](#docmd-dev) | Start the development server with hot reload | | [`docmd build`](#docmd-build) | Generate a production static site | | [`docmd live`](#docmd-live) | Launch the browser-based Live Editor | | [`docmd stop`](#docmd-stop) | Kill running dev servers | | [`docmd deploy`](#docmd-deploy) | Generate deployment configs (Docker, Nginx, Caddy) | | [`docmd migrate`](#docmd-migrate) | Upgrade legacy configs to V2 schema | | [`docmd add <plugin>`](#docmd-add-plugin) | Install and configure a plugin | | [`docmd remove <plugin>`](#docmd-remove-plugin) | Remove a plugin and its config | ## Global Options | Option | Alias | Description | |:-------|:------|:------------| | `--config <path>` | `-c` | Path to config file (default: `docmd.config.js`) | | `--verbose` | `-V` | Show detailed build logs | | `--version` | `-v` | Output the installed version | | `--help` | `-h` | Display help menu | | `--cwd <path>` | - | Override working directory (for monorepos) | ## `docmd init` Scaffold a new documentation project in the current directory. ```bash docmd init ``` Creates: - `docs/index.md` - boilerplate home page - `docmd.config.js` - recommended defaults - Updated `package.json` with build scripts ## `docmd dev` Start a development server with instant hot reload. ```bash docmd dev [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--port <number>` | `-p` | Server port (default: `3000`) | | `--config <path>` | `-c` | Path to config file | ## `docmd build` Generate a production-ready static site in `site/`. ```bash docmd build [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--offline` | - | Rewrite links to `.html` for `file://` browsing | | `--config <path>` | `-c` | Path to config file | ## `docmd live` Launch the browser-based Live Editor. ```bash docmd live [options] ``` | Option | Description | |:-------|:------------| | `--build-only` | Generate the editor bundle without starting the server | ## `docmd stop` Kill running docmd dev servers. ```bash docmd stop [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--port <number>` | `-p` | Stop only the server on this port | | `--force` | `-f` | Also kill `serve` processes on ports 3000, 3001, 8080, 8081 | ## `docmd deploy` Generate deployment configuration files. ```bash docmd deploy [options] ``` | Option | Description | |:-------|:------------| | `--docker` | Generate a `Dockerfile` | | `--nginx` | Generate `nginx.conf` | | `--caddy` | Generate `Caddyfile` | | `--force` | Overwrite existing deployment files | ## `docmd migrate` Upgrade legacy docmd V1 configs to the V2 schema. ```bash docmd migrate ``` Automatically re-maps deprecated keys (e.g., `siteTitle` → `title`) and restructures the config object. ## `docmd add <plugin>` Install and configure an official or community plugin. ```bash docmd add <plugin-name> ``` | Example | Description | |:--------|:------------| | `docmd add analytics` | Install `@docmd/plugin-analytics` | | `docmd add search` | Install `@docmd/plugin-search` | The CLI detects your package manager (npm, pnpm, yarn, or bun) and injects recommended defaults into `docmd.config.js`. ## `docmd remove <plugin>` Safely uninstall a plugin and clean up its config. ```bash docmd remove <plugin-name> ``` Removes: - The npm package - Plugin configuration from `docmd.config.js` ::: callout tip "Agent-Compatible Logging :robot:" `docmd` uses structured terminal logging. AI agents can parse output precisely for error detection and automated maintenance. ::: --- ## [Client-Side Events](https://docs.docmd.io/07/api/client-side-events/) --- title: "Client-Side Events" description: "Hook into the docmd SPA lifecycle to add interactive features." --- `docmd` utilises a lightweight Single Page Application (SPA) router to provide instant page transitions. Because the browser does not perform a full reload during navigation, scripts relying on `DOMContentLoaded` will not re-execute. To handle this, `docmd` dispatches custom lifecycle events that you can listen for in your `customJs` files. ## `docmd:page-mounted` This event is dispatched whenever a new page has been successfully fetched and injected into the DOM. ### Usage Add a listener to the `document` object to re-initialise third-party libraries or trigger custom animations. ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`Navigated to: ${url}`); // Re-initialise components // Example: Prism.highlightAll(); }); ``` ### Event Details (`event.detail`) | Property | Type | Description | | :--- | :--- | :--- | | `url` | `String` | The absolute URL of the page that was just mounted. | ## Best Practices 1. **Idempotency**: Ensure your initialisation logic can be safely called multiple times on the same page or cleaned up before the next navigation. 2. **Global Scope**: Scripts added via `customJs` are executed in the global scope. Use an IIFE (Immediately Invoked Function Expression) to avoid polluting the `window` object. 3. **Cleanup**: If your script adds global event listeners (e.g., `window.onresize`), consider tracking the current path to remove them when the user navigates away. --- ## [Live Editor](https://docs.docmd.io/07/api/live-api/) --- title: "Live Editor" description: "Understanding the docmd Live Editor and its browser-based authoring workflow." --- The `docmd` Live Editor is a dedicated environment for real-time documentation authoring. It uses the isomorphic core of `docmd` to provide an instant, side-by-side preview of your Markdown content without requiring a backend build process. ## Launching the Editor Start the local Live Editor by running: ```bash docmd live ``` The editor will typically be available at `http://localhost:3000`. ## Architecture Unlike the standard `dev` server which rebuilds files on the disk, the Live Editor runs the `docmd` engine directly in your browser. This enables: 1. **Instant Feedback**: Content is re-rendered as you type. 2. **Portable Playgrounds**: The editor can be bundled into a static site for hosting on platforms like GitHub Pages. 3. **Cross-Platform Consistency**: The preview uses the exact same rendering logic as the production build. ## Static Deployment Generate a shareable, standalone version of the editor: ```bash docmd live --build-only ``` This creates a `dist/` directory containing the editor's HTML and the bundled isomorphic engine. --- ## [Node.js API](https://docs.docmd.io/07/api/node-api/) --- title: "Node.js API" description: "Integrate docmd's build engine into your custom Node.js scripts and automation pipelines." --- For advanced workflows, you can import and use the `docmd` build engine directly within your own Node.js applications. This is ideal for custom CI/CD pipelines, automated documentation generation, or extending `docmd` for specialised environments. ## Installation Ensure `@docmd/core` is installed in your project: ```bash npm install @docmd/core ``` ## Core Functions ### `buildSite(configPath, options)` The primary build function. It handles configuration loading, Markdown parsing, and asset generation. ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.js', { isDev: false, // Set to true for watch mode logic offline: false, // Set to true to optimise for file:// access zeroConfig: false // Set to true to bypass config file detection }); } ``` ### `buildLive(options)` Generates the browser-based **Live Editor** bundle. ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true starts a local server; false generates static files port: 3000 // Custom port if serve is true }); } ``` ## Example: Custom Pipeline You can wrap `docmd` to create complex documentation workflows. ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. Generate dynamic content await fs.writeFile('./docs/dynamic.md', '# Generated Content'); // 2. Execute docmd build await buildSite('./docmd.config.js'); // 3. Move output await fs.move('./site', './public/docs'); } ``` ::: callout tip The programmatic API is highly compatible with **AI-Driven Documentation**. Agents can trigger builds after content updates to verify integrity and manage deployments autonomously. ::: ## Plugin API (`@docmd/api`) The `@docmd/api` package is the dedicated home for the plugin system. It provides hook registration, WebSocket RPC dispatch, source editing tools, and **centralised URL utilities**. ```bash npm install @docmd/api ``` ### URL Utilities Plugins should use these centralised utilities instead of rolling their own URL logic. #### `outputPathToSlug(outputPath)` Convert a build engine output path to a clean directory-style slug. ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` Convert to a root-relative pathname. ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` Build a full canonical URL. ```javascript import { outputPathToCanonical } from '@docmd/api'; outputPathToCanonical('guide/index.html', 'https://example.com'); // → 'https://example.com/guide/' ``` #### `sanitizeUrl(url)` Collapse double slashes (except after protocol). ```javascript import { sanitizeUrl } from '@docmd/api'; sanitizeUrl('https://example.com//path/'); // → 'https://example.com/path/' sanitizeUrl('/foo//bar/'); // → '/foo/bar/' ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` Build an absolute URL with locale and version prefixes. ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` Normalise user-written hrefs to clean URLs. Handles `.md` stripping, trailing slashes, `external:` and `raw:` prefixes. ```javascript import { resolveHref } from '@docmd/api'; resolveHref('overview.md'); // → { href: 'overview/', isExternal: false, isRaw: false } resolveHref('external:https://github.com/docmd-io/docmd'); // → { href: 'https://github.com/docmd-io/docmd', isExternal: true, isRaw: false } resolveHref('raw:docs/readme.md'); // → { href: 'docs/readme.md', isExternal: false, isRaw: true } ``` ### Pre-computed Page URLs Every page object includes pre-computed URL data. Plugins can read these directly - zero computation needed. ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); // "guide/" console.log(page.urls.canonical); // "https://example.com/guide/" console.log(page.urls.pathname); // "/guide/" } } ``` | Property | Type | Description | |:---------|:-----|:------------| | `slug` | `string` | Clean directory-style slug (e.g., `guide/` or `/`) | | `canonical` | `string` | Full canonical URL (only if `config.url` is set) | | `pathname` | `string` | Root-relative path (e.g., `/guide/`) | > **Backward Compatibility:** All exports from `@docmd/api` are also re-exported from `@docmd/core`, so existing code continues to work without changes. New projects are encouraged to import directly from `@docmd/api`. ### `createActionDispatcher(hooks, options)` Creates a dispatcher that routes WebSocket RPC messages to plugin action/event handlers. ```javascript import { createActionDispatcher } from '@docmd/api'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` Creates source editing utilities for markdown file manipulation. ```javascript import { createSourceTools } from '@docmd/api'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // Get block information at a specific line range const block = await source.getBlockAt('docs/page.md', [10, 12]); // Wrap text with syntax markers await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### `loadPlugins(config, options)` Loads, validates, and registers all plugins declared in the config. Returns the populated hooks registry. ```javascript import { loadPlugins, hooks } from '@docmd/api'; const registeredHooks = await loadPlugins(config, { resolvePaths: [__dirname] // Help resolve plugins in pnpm workspaces }); ``` ### Type Exports For TypeScript plugin authors, the following types are available: ```typescript import type { PluginModule, // Full plugin contract interface PluginDescriptor, // Plugin metadata (name, version, capabilities) PluginHooks, // Shape of the hook registry PageContext, // Context passed to build hooks (sourcePath, html, etc) Capability, // Hook category declaration (init, body, actions, etc) ActionContext, // Context passed to action/event handlers ActionHandler, // Signature for action handlers EventHandler, // Signature for event handlers SourceTools, // Source editing tools interface BlockInfo, // Block information returned by getBlockAt TextLocation, // Text location returned by findText } from '@docmd/api'; ``` --- ## [Comparison](https://docs.docmd.io/07/comparison/) --- title: "Comparison" description: "How docmd stacks up against Docusaurus, VitePress, MkDocs, Starlight, and Mintlify - real numbers, real features." --- You picked a documentation tool before. You'll pick one again. Here's what actually matters - and where docmd stands. ## Start writing in 3 seconds, not 30 minutes ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` Done. Your docs are live. No config files, no project scaffolding, no dependency maze. == tab "Docusaurus" ```bash npx create-docusaurus@latest my-site classic cd my-site npm install npm start ``` Four commands, a generated project with ~250MB in `node_modules`, and a `docusaurus.config.js` you'll need to edit before anything useful happens. == tab "VitePress" ```bash npx vitepress init ``` Asks you 5 questions, generates a config file, then you run `vitepress dev`. Clean - but still requires scaffolding. == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new my-site && cd my-site mkdocs serve ``` Python ecosystem. You'll need `pip`, a virtual environment, and a `mkdocs.yml` before the first page renders. ::: ## The payload gap is real Your readers shouldn't download a React app just to read a paragraph. Here's what the browser actually receives on a 50-page site: | Generator | Total initial load | JS payload | CSS payload | |:----------|:------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "Why this matters" Every 100 KB of JavaScript costs ~50ms of parse time on a mid-range phone. docmd's 12 KB JS means your docs load instantly, even on 3G. Docusaurus ships 16× more JavaScript for the same content. ::: ## Build speed Building the same 50-page site on an M1 MacBook Air: | Generator | Cold build | Hot rebuild (dev) | |:----------|:----------:|:-----------------:| | **docmd** | **~1.2s** | **~80ms** | | VitePress | ~2.5s | ~150ms | | MkDocs Material | ~3.0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd rebuilds are fast enough that the page refreshes before you switch windows. ## i18n that actually works This is where most tools fall apart. You add 6 languages, translate 3 pages in Hindi, and suddenly your users hit 404s on every untranslated page. | Capability | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | Per-page fallback to default locale | ✅ | ❌ (404) | ❌ (404) | ✅ | | Localised "not translated" warning | ✅ | ❌ | ❌ | ✅ | | Auto-disable missing locales in switcher | ✅ | ❌ | ❌ | ❌ | | Instant page-existence check (no network) | ✅ | ❌ | ❌ | ❌ | | Versioning + i18n combined | ✅ | ❌ | ❌ | ❌ | | Zero-config (no custom React/Vue) | ✅ | Partial | ❌ | ✅ | ::: callout warning "What happens in VitePress and Docusaurus" If a reader switches to Hindi and that page isn't translated, they get a **404 error**. The only workaround is server-side redirects or writing a custom React/Vue component. docmd handles this at build time - unavailable locales show an "N/A" badge, and untranslated pages fall back silently with a localised warning callout. ::: ## Multi-project Organisations maintaining multiple tools under one domain need separate docs for each - different versions, different navigation, different release cycles. Most generators force you to either maintain separate sites or hack around plugin systems. | Capability | docmd | Docusaurus | VitePress | MkDocs | Starlight | |:-----------|:-----:|:----------:|:---------:|:------:|:---------:| | Native multi-project support | ✅ | Plugin | ❌ | Plugin | ❌ | | Single config line per project | ✅ | ❌ | ❌ | ❌ | ❌ | | Independent versioning per project | ✅ | ✅ | ❌ | ❌ | ❌ | | Independent i18n per project | ✅ | ❌ | ❌ | ❌ | ❌ | | Shared assets across projects | ✅ | ❌ | ❌ | ❌ | ❌ | | Single `site/` output (no proxy needed) | ✅ | ❌ | ❌ | ❌ | ❌ | | Zero-config detection | ✅ | ❌ | ❌ | ❌ | ❌ | ::: callout info "How docmd does it" ```javascript // That's the entire root config. module.exports = defineConfig({ projects: [ { prefix: '/', src: 'main-docs' }, { prefix: '/sdk', src: 'sdk-docs' } ] }); ``` Each project folder has its own `docmd.config.js` with independent configuration. One `docmd build` produces a single deployable directory - no reverse proxy, no nginx, no separate CI pipelines. ::: Docusaurus achieves something similar with multi-instance plugins, but requires complex configuration - each instance needs separate plugin entries, sidebar files, and manual route configuration. MkDocs requires the third-party `mkdocs-monorepo-plugin`. VitePress, Starlight, and Mintlify have no native multi-project support. ## Full feature matrix | Feature | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **Zero-config start** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Config required** | None | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **Multi-project** | ✅ | Plugin | ❌ | Plugin | ❌ | ❌ | | **SPA navigation** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **Native versioning** | ✅ | ✅ | ❌ | Plugin | ❌ | ✅ | | **Native i18n** | ✅ | ✅ | Manual | Plugin | ✅ | ✅ | | **Built-in search** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | Cloud | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Inline discussions** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA support** | ✅ | Community | ❌ | ❌ | ❌ | ❌ | | **Self-hosted** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **Deploy config generator** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## Configuration overhead Lines of config required for a site with versioning, i18n, search, and sitemap: | Generator | Config lines | Files required | |:----------|:------------:|:--------------:| | **docmd** | **~15 lines** | 1 (`docmd.config.js`) | | MkDocs Material | ~50 lines | 1 + plugins | | VitePress | ~80 lines | 1 + theme dir | | Docusaurus | ~120 lines | 3+ config files | ## Quality assurance docmd ships with a brute test suite that validates **25 distinct scenarios** across **85 assertions** - covering every feature in isolation and in combination. Every release must pass all 85 assertions and 13 internal failsafe checks before shipping. ::: callout tip "Run the tests yourself" ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: No other documentation generator in this class publishes a comparable end-to-end feature test suite as part of its source. --- ## [Layout & UI Zones](https://docs.docmd.io/07/configuration/layout-ui/) --- title: "Layout & UI Zones" description: "Control the interface structure by managing headers, sidebars, and functional UI slots." --- A standard `docmd` page is divided into six primary functional zones: 1. **Menubar**: A full-width top navigation bar for global site links. 2. **Header**: The persistent secondary bar containing the page title and utility buttons. 3. **Sidebar**: The primary navigation tree (usually on the left). 4. **Content Area**: The central Markdown rendering zone, including **Breadcrumbs**. 5. **Table of Contents (TOC)**: Right-hand heading navigation for the current page. 6. **Footer**: Bottom area for copyright, branding, and site-wide links. ## Global Component Configuration `docmd` features a modular layout system. Most UI zones are configured within the `layout` section of your `docmd.config.js`. ### Menubar The menubar provides a high-level navigation layer above your documentation. It supports brand titles, regular links, and nested dropdowns. * **Location**: Fixed at the `top` or inline within the `header`. * **Documentation**: See [Menubar Configuration](menubar.md) for full item schemas and styling. ### The Page Header The header contains the page title, breadcrumbs, and usually the utility menus. * **Controls**: Enable/disable the header or breadcrumbs site-wide via `layout.header` and `layout.breadcrumbs`. * **Overriding**: Use `hideTitle: true` in your [Page Frontmatter](../content/frontmatter.md) to hide the title area on specific pages. ### Utility Menus (Options Menu) The `optionsMenu` consolidates core utilities like **Global Search**, **Theme Toggle**, and **Sponsorship links**. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Enable full-text search themeSwitch: true, // Enable Light/Dark mode toggle sponsor: 'https://github.com/sponsors/your-profile' } } } ``` ::: callout info "Automatic Fallback" If the chosen position targets a container that is disabled, `docmd` will automatically render the options menu in the `sidebar-top` slot to ensure core utilities remain accessible. ::: ### Sidebar & Navigation The sidebar is the primary navigation tree for your site. Its structure is defined either in your config or via external JSON files. * **Behaviour**: Supports animations, collapsible groups, and automatic path preservation. * **Documentation**: See [Navigation Configuration](navigation.md) for structuring your sidebar tree. ### Footer `docmd` provides both **minimal** and **complete** layouts for your site footer. ```javascript layout: { footer: { style: 'complete', // Options: 'minimal' or 'complete' description: 'Documentation built with docmd.', branding: true, // Controls the "Built with docmd" badge columns: [ { title: 'Community', links: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd' } ] } ] } } ``` ::: callout tip "Interface Hierarchy" For the best user experience, keep your **Menubar** for global external links and your **Sidebar** for logical documentation structure. AI agents frequently utilise this hierarchy to understand the relationship between different documentation modules. ::: --- ## [Localisation](https://docs.docmd.io/07/configuration/localisation/) --- title: "Localisation" description: "Serve documentation in multiple languages with locale-first routing, translated navigation, and automatic fallback." --- Add multi-language support to your documentation site. docmd serves each locale at its own URL prefix, translates system UI strings, and falls back gracefully when a translation is missing. ## Add languages to your config ```js // docmd.config.js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }, { id: 'zh', label: '中文' } ] } } ``` The `default` locale renders at the site root (`/`). All other locales render at `/{id}/`. You choose the IDs, labels, and which locale is the default - there are no hardcoded assumptions. If you want Hindi as the default, set `default: 'hi'` and Hindi renders at `/` whilst English renders at `/en/`. | Key | Type | Description | |:----|:-----|:------------| | `default` | `string` | Locale ID that renders at `/`. Defaults to the first locale if omitted. | | `locales` | `array` | List of locale objects. Each must have an `id`. | | `position` | `string` | Where the language switcher appears. `options-menu` (default), `sidebar-top`, or `sidebar-bottom`. | | `stringMode` | `boolean` | When `true`, generates locale pages from a single source using `data-i18n` attribute replacement. Default `false`. | | `inPlace` | `boolean` | When `true` (with client-side script), swaps strings without URL navigation. For SPAs/dashboards only. Default `false`. | Each locale object accepts: | Key | Type | Default | Description | |:----|:-----|:--------|:------------| | `id` | `string` | - | Any identifier you choose (e.g. `en`, `hi`, `fr-ca`). Used as the folder name and URL prefix. Required. | | `label` | `string` | Same as `id` | Display name shown in the language switcher. | | `dir` | `string` | `ltr` | Text direction. Set to `rtl` for Arabic, Hebrew, etc. | | `translations` | `object` | `{}` | Custom UI string overrides (see [Custom UI strings](ui-strings.md)). | ## URL structure The default locale has no URL prefix. Non-default locales are nested under `/{id}/`. When combined with [versioning](../versioning.md), the URL is `/{locale}/{version}/page`. ``` / ← default locale, current version /getting-started ← default locale page /05/ ← default locale, old version /hi/ ← non-default locale, current version /hi/getting-started ← non-default locale page /hi/05/ ← non-default locale, old version ``` The language switcher preserves your current page and version when you switch locales. The version switcher preserves your current locale. ## Missing locale directories If a locale is declared in `locales` but its source directory does not exist (e.g. no `docs/hi/` folder), docmd automatically **disables** that locale in the language switcher. The locale still appears in the dropdown - with an "N/A" badge and greyed-out styling - but clicking it does nothing. This prevents 404 errors when you list planned languages before their content is ready. ## Position the language switcher Control where the language switcher appears using the `position` option: ```js i18n: { position: 'options-menu', // default // ... } ``` | Position | Behaviour | |:---------|:----------| | `options-menu` | Compact globe icon alongside theme toggle and search. Default. | | `sidebar-top` | Full dropdown with label at the top of the sidebar. | | `sidebar-bottom` | Full dropdown with label at the bottom of the sidebar. | ## String Mode (noStyle pages only) Standard i18n uses separate directories per locale (`docs/en/`, `docs/hi/`), each with its own markdown files. **String Mode** is a simpler alternative designed specifically for [noStyle pages](../../content/no-style-pages.md) - pages that use raw HTML instead of markdown. ```js // docmd.config.js export default { i18n: { default: 'en', stringMode: true, locales: [ { id: 'en', label: 'English' }, { id: 'zh', label: '中文' } ] } } ``` With `stringMode: true`: 1. Source files stay in the root `docs/` directory (no locale subdirectories) 2. The default locale builds at `/` as normal 3. For each non-default locale, docmd clones the rendered HTML and applies **server-side string replacement** using JSON files from `assets/i18n/{locale}.json` 4. Output goes to `/{locale}/` - e.g. `/zh/index.html` - with full SEO (hreflang tags, correct `lang` attribute) 5. If a translation file is missing, the page renders with the default language text For full details on the `data-i18n` attribute syntax and JSON file format, see [noStyle string replacement](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: callout warning "String Mode does not translate markdown content" String replacement works by finding `data-i18n` attributes in the rendered HTML. Standard markdown content (`## Heading`, paragraphs, lists) renders to plain HTML tags without these attributes - so there is nothing for the replacer to find. - **Documentation sites** → use directory mode (the default). Each locale has its own markdown files with fully translated prose. - **Landing pages, marketing sites, dashboards** → use string mode. These are noStyle pages with custom HTML where you control every tag and can add `data-i18n` attributes. If your site has both - for example, a noStyle landing page plus documentation - use directory mode for the docs and add `data-i18n` attributes to your noStyle page. String mode will translate the noStyle HTML while directory mode handles the documentation content. ::: ## Next steps - [Translated content](translated-content.md) - directory structure, writing translations, navigation - [UI strings & SEO](ui-strings.md) - customising system text, hreflang tags - [noStyle string replacement](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle) - `data-i18n` attribute syntax and JSON format for noStyle pages --- ## [Translated Content](https://docs.docmd.io/07/configuration/localisation/translated-content/) --- title: "Translated Content" description: "Organise translations in locale subdirectories with per-file fallback and per-locale navigation." --- ## Directory structure Every locale - including the default - lives in its own subdirectory inside the source directory. The folder name matches the locale `id` from your config. ``` docs/ ├── en/ ← default locale content │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← second locale │ ├── index.md ← translated homepage │ ├── navigation.json ← translated navigation labels │ └── getting-started/ │ └── installation.md ← translated page └── zh/ ← third locale └── index.md ← only the homepage translated ``` The source directory is a clean container - it holds only locale folders. No content files sit at the root level when i18n is enabled. ::: callout info "Folder names are your choice" The folder names come directly from the `id` values in your config. If your config says `{ id: 'fr-ca' }`, your folder is `docs/fr-ca/`. If Hindi is your default locale (`default: 'hi'`), then `docs/hi/` is the canonical content directory. ::: ## Per-file fallback You don't need to translate every page. docmd scans the **default locale's directory** as the canonical list of pages. For every other locale, it checks whether a translated version of each page exists: - If `docs/hi/getting-started/installation.md` exists → serves the Hindi translation - If it doesn't exist → serves the default locale's version of that page When a page falls back, docmd can display a translated callout informing viewers that the page is shown in the default language. This message is customisable via your [UI strings](ui-strings.md) configuration. ## Locale-exclusive pages A non-default locale can also have pages that don't exist in the default locale. These are rendered only for that locale - they don't appear in other locales. ## Translate the navigation Each locale directory can have its own `navigation.json`. `docmd` uses a cascading priority system (Level 1-3) to resolve the sidebar. For details on the resolution hierarchy and visual examples, see [Navigation Resolution Priority](../navigation.md#navigation-resolution-priority). A locale's `navigation.json` uses the same format: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "Partial navigation" You only need to create a locale `navigation.json` when you want translated labels. If it's missing, the default locale's navigation is used - pages still render, just with untranslated labels. ::: ## Versioning and i18n together When both versioning and i18n are configured, the source structure is: ``` docs/ ← current version (container) en/ ← current version, default locale hi/ ← current version, translated locale docs-v1/ ← old version index.md ← old version content (no locale structure) navigation.json ``` Old versions that predate i18n work automatically - docmd reads them directly when no locale subdirectories are present. Only the default locale renders the old version. To add translations to an old version, create a locale subdirectory inside it: ``` docs-v1/ hi/ ← Hindi translation for v1 index.md navigation.json ``` The output URLs nest locale first, then version: ``` / ← default locale, current version /hi/ ← translated locale, current version /v1/ ← default locale, old version /hi/v1/ ← translated locale, old version ``` --- ## [UI Strings & SEO](https://docs.docmd.io/07/configuration/localisation/ui-strings/) --- title: "UI Strings & SEO" description: "Customise system UI text per locale and understand automatic SEO tags for multi-language sites." --- ## Built-in language support docmd and its official plugins (Search, Threads, etc.) ship with built-in translations for common languages. When you configure a supported locale, all system text - search placeholders, navigation labels, theme toggles - is automatically translated. For unsupported languages or custom phrasing, the system falls back to English. You can override any string per locale. ## Custom UI strings Use the `translations` property on any locale to override system text: ```js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'ar', label: 'العربية', dir: 'rtl', translations: { onThisPage: 'في هذه الصفحة', previous: 'السابق', next: 'التالي', search: 'بحث', toggleTheme: 'تبديل المظهر', editThisPage: 'تعديل هذه الصفحة', selectLanguage: 'اختر اللغة', selectVersion: 'اختر الإصدار', fallbackMessage: 'هذه الصفحة غير متاحة بعد باللغة {active}. عرض اللغة الافتراضية ({default}).' } } ] } } ``` The merge order is: **system translations → plugin translations → your config translations**. Your config always wins. ## Available keys | Key | Default (English) | |:----|:-------------------| | `skipToContent` | Skip to main content | | `toggleSidebar` | Toggle Sidebar | | `previous` | Previous | | `next` | Next | | `onThisPage` | On This Page | | `search` | Search | | `toggleTheme` | Toggle theme | | `selectLanguage` | Select Language | | `selectVersion` | Select Version | | `editThisPage` | Edit this page | | `builtWith` | Built with | | `copyCode` | Copy code | | `copiedToClipboard` | Copied! | | `mainNavigation` | Main Navigation | | `fallbackMessage` | This page is not yet available in {active}. Showing default language ({default}). | The `fallbackMessage` key supports `{active}` and `{default}` placeholders, replaced with locale labels at build time. ## SEO and hreflang docmd automatically generates `<link rel="alternate" hreflang="...">` tags for every page across all locales. The default locale also receives the `x-default` hreflang value. ```html <!-- Generated automatically on every page --> <link rel="alternate" hreflang="en" href="/"> <link rel="alternate" hreflang="x-default" href="/"> <link rel="alternate" hreflang="hi" href="/hi/"> <link rel="alternate" hreflang="zh" href="/zh/"> ``` No configuration is required - these tags are injected into every page when i18n is enabled. ::: callout info "noStyle Pages" The UI strings system described above applies to themed layout pages (server-side). For noStyle pages that use custom HTML, see the [client-side string replacement](../../content/no-style-pages/#string-replacement-i18n-for-nostyle) system which uses `data-i18n` attributes and JSON files in `assets/i18n/`. ::: --- ## [Menubar](https://docs.docmd.io/07/configuration/menubar/) --- title: "Menubar" description: "Structure and position your menubar, manage navigation links, and configure drop-down menus." --- The `menubar` is a premium navigation layer that provides global context across your documentation site. It can be positioned as a fixed bar at the top of the viewport or as a relative component above the page header. ## Configuration The menubar is configured within the `layout` section of your `docmd.config.js`. ```javascript export default defineConfig({ layout: { menubar: { enabled: true, position: 'top', // 'top' (fixed) or 'header' (inline) left: [ { type: 'title', text: 'Brand', url: '/', icon: 'home' }, { text: 'Documentation', url: '/docs' }, { type: 'dropdown', text: 'Ecosystem', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Live Editor', url: 'https://live.docmd.io' } ] } ], right: [ { text: 'Support', url: '/support', icon: 'help-circle' } ] } } }); ``` ### Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | Toggles the visibility of the menubar. | | `position` | `String` | `'top'` | `'top'` (fixed at absolute top) or `'header'` (positioned above the page title). | | `left` | `Array` | `[]` | Navigation items aligned to the left section. | | `right` | `Array` | `[]` | Navigation items aligned to the right section. | ## Item Types The `left` and `right` arrays support various item types to structure your navigation effectively: ### 1. Standard Link The most common item type. - `text`: Display label. - `url`: Path or external URL. - `icon`: Optional Lucide icon name. - `external`: Set to `true` to open in a new tab. ### 2. Title (Brand) Set `type: 'title'` to apply branding styles (usually bold or with a specific font weight) to the link. ### 3. Dropdown Menu Set `type: 'dropdown'` and provide an `items` array to create a nested menu. ## Utility Integration You can host the global search and theme toggle within the menubar by setting the `optionsMenu.position` to `'menubar'`. ```javascript layout: { optionsMenu: { position: 'menubar' } } ``` When integrated, the options menu will automatically align to the **right region** of the menubar, appearing after any links defined in the `right` array. ::: callout info If the `menubar` is disabled, any utility components assigned to it will automatically fall back to the `sidebar-top` position. ::: ## Custom Styling You can fine-tune the menubar's appearance using CSS variables in your `customCss` files: ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-colour); --menubar-text: var(--docmd-text-primary); } ``` --- ## [Multi-Project Configuration](https://docs.docmd.io/07/configuration/multi-project/) --- title: "Multi-Project Configuration" description: "Build multiple independent documentation sites from a single docmd instance. Shared assets, independent versioning, one deployment." --- Build and deploy multiple documentation projects from a single repository. Each project maintains its own configuration, versioning, and navigation while sharing a common theme and asset pipeline. ## Overview Multi-project mode is designed for organisations that maintain multiple tools, libraries, or products under one domain. Instead of running separate docmd instances behind a reverse proxy, a single `docmd build` produces a unified `site/` directory. ``` docs.example.com/ → Main documentation docs.example.com/sdk/ → SDK reference docs.example.com/cli/ → CLI documentation ``` ## Setup ### 1. Directory Structure Organise your repository with one directory per project: ``` my-docs/ ├── assets/ ← shared assets (all projects) ├── main-docs/ │ ├── docmd.config.js ← project config │ └── v01/ ← versioned content │ └── en/ ├── sdk-docs/ │ ├── docmd.config.js ← project config │ └── docs/ ← unversioned content ├── docmd.config.js ← root multi-project config └── package.json ``` ### 2. Root Configuration The root `docmd.config.js` contains **only** the `projects` array: ```javascript module.exports = defineConfig({ projects: [ { prefix: '/', src: 'main-docs' }, { prefix: '/sdk', src: 'sdk-docs' } ] }); ``` | Key | Description | | :-- | :---------- | | `prefix` | URL prefix for this project. Use `'/'` for the root project. | | `src` | Directory containing this project's `docmd.config.js` and content. | ::: callout warning Every multi-project configuration **must** include a root project with `prefix: '/'`. ::: ### 3. Project Configurations Each project directory has its own `docmd.config.js` with full independent configuration. Do **not** include `src` or `out` keys - the parent config provides those automatically. Each project can have completely independent: - **i18n** - different locales, different default languages - **Versioning** - different version numbers and structures - **Plugins** - enable only what each project needs - **Navigation** - custom sidebar for each project ## Assets ### Shared Assets Place shared resources (logos, favicons, global CSS) in the root `assets/` directory. These are copied into every project's output automatically. ### Project-Specific Assets Each project can have its own `assets/` directory. Project assets take priority over shared assets when filenames overlap. ``` my-docs/ ├── assets/ │ └── images/ │ └── logo.png ← used by all projects ├── sdk-docs/ │ └── assets/ │ └── images/ │ └── logo.png ← overrides shared logo for SDK only ``` ## Development Start the multi-project dev server: ```bash docmd dev ``` The server builds all projects and serves them from a single port: ``` ┌─ DEV SERVER │ │ Local http://127.0.0.1:3000 │ Network http://192.168.1.5:3000 │ │ Project http://127.0.0.1:3000/ │ Project http://127.0.0.1:3000/sdk └────────────────────────────────────────────────────────── ``` File changes in any project trigger a targeted rebuild with live reload. Only the affected project rebuilds - other projects remain untouched for fast iteration. Shared asset changes rebuild all projects. ## Building & Deployment ```bash docmd build ``` Output is a single static directory: ``` site/ ├── index.html ← main-docs root ├── sdk/ │ └── index.html ← sdk-docs root ├── assets/ ← merged assets ├── 404.html └── sitemap.xml ``` Deploy to any static hosting (GitHub Pages, Netlify, Vercel, Cloudflare Pages) with no additional configuration. No nginx or proxy rules needed. ## Rules & Constraints 1. **Root project required** - one project must have `prefix: '/'` 2. **No duplicate prefixes** - each project needs a unique URL prefix 3. **No `src`/`out` in children** - the parent config provides these 4. **Independent everything** - each project has its own title, versions, i18n, plugins, and navigation 5. **Root config is minimal** - only `projects` should be in the root `docmd.config.js` ## Example The official docmd documentation uses multi-project to serve the main docs and semantic search docs from one domain: ```javascript // Root docmd.config.js module.exports = defineConfig({ projects: [ { prefix: '/', src: 'docmd-main' }, { prefix: '/search', src: 'docmd-search' } ] }); ``` Check the [documentation repo](external:https://github.com/docmd-io/docs). This produces: - `docs.docmd.io/` - main docmd documentation (versioned, multilingual) - `docs.docmd.io/search/` - docmd search documentation (independent versioning) Each project has its own: - `docmd.config.js` with different title, URL, and plugins - Version structure (main has v0.5-v0.7, search has its own versioning) - Navigation and sidebar configuration --- ## [Navigation Configuration](https://docs.docmd.io/07/configuration/navigation/) --- title: "Navigation Configuration" description: "Structure your sidebar, categorise links, and assign icons for human readers and LLMs." --- `docmd` provides explicit control over your site's structure. By defining your `navigation` in `docmd.config.js`, you create a logical hierarchy that optimises the Single Page Application (SPA) experience and provides a clear context map for AI models and search engines. ## The Navigation Array <img width="260" class="with-border" src="/assets/previews/navigation-hierarchy.webp"> Each object in the array defines a **Link** or a **Category Group**. ```javascript export default defineConfig({ navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Installation', path: '/getting-started/installation', icon: 'download' } ] }); ``` ## Available Properties | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **`title`** | `String` | Yes | The display text for the link or category. | | **`path`** | `String` | No | Destination URL. Must start with `/` for local paths. | | **`icon`** | `String` | No | Name of a [Lucide Icon](external:https://lucide.dev/icons) (e.g., `rocket`). | | **`children`** | `Array` | No | Nested items used to create a submenu or group. | | **`collapsible`**| `Boolean` | No | If `true`, the group can be expanded/collapsed by the user. | | **`external`** | `Boolean` | No | If `true`, the link opens in a new browser tab. | ## Organising Groups You can nest navigation items to create deep hierarchies. There are two primary ways to organise groups: ### 1. Clickable Group (Directory with Index) If the parent has a `path`, clicking the label navigates to that page and automatically expands the children in the sidebar. ```javascript { title: 'Cloud Setup', path: '/cloud/overview', children: [ { title: 'AWS', path: '/cloud/aws' }, { title: 'GCP', path: '/cloud/gcp' } ] } ``` ### 2. Static Label (Category Header) If you **omit the `path`**, the item becomes a static category header. This is the recommended approach for grouping related technical sections that don't share a common landing page. ```javascript { title: 'Content & Formatting', icon: 'layout', children: [ { title: 'Syntax Guide', path: '/content/syntax' }, { title: 'Containers', path: '/content/containers' } ] } ``` ## Automated Breadcrumbs <img width="500" class="with-border" src="/assets/previews/navigation-breadcrumb.webp"> `docmd` automatically generates breadcrumbs for every page based on your navigation hierarchy. These crumbs are rendered above the main page title to improve orientation and navigation speed. ### Behaviour * **Auto-Resolution**: The engine traces the path through your `navigation` tree to identify the current page's ancestors. * **Active State**: The current page is listed as the final, non-linked crumb. * **Mobile Support**: Breadcrumbs are intelligently adjusted or hidden on smaller screens to preserve header space. ### Disabling Breadcrumbs Breadcrumbs are enabled by default. To disable them site-wide, update your `docmd.config.js`: ```javascript layout: { breadcrumbs: false } ``` ## Navigation Resolution Priority `docmd` provides a flexible cascading resolution system. This allows you to maintain a central navigation config while overriding specific parts for different languages or versions. The resolution follows a "closest file wins" logic based on folder nesting. The hierarchy is as follows (from highest priority to lowest): ```text my-project/ ├── docmd.config.js [Level 3: Global Config] - Lowest Priority ├── docs-v1/ │ ├── navigation.json [Level 2: Version Navigation] - Medium Priority │ └── zh/ │ └── navigation.json [Level 1: Language Navigation] - Highest Priority ``` 1. **Level 1: Language-Specific** (`docs-v1/zh/navigation.json`): Overrides everything for the specific locale and version. 2. **Level 2: Version-Specific** (`docs-v1/navigation.json`): Overrides the global config for all languages in this version. 3. **Level 3: Global Configuration** (`config.navigation`): The final fallback defined in your root config file. ### Smart Broken-Link Filtering Even when falling back to a parent configuration (Level 2 or 3), `docmd` automatically filters out sidebar items that link to files not present in the current version's source folder. This guarantees no broken links when users select an older version. ### JSON Structure Each `navigation.json` must follow the standard array structure: ```json [ { "title": "Home", "path": "/" }, { "title": "Release Notes", "path": "/release-notes" } ] ``` ## Icons Integration `docmd` comes pre-bundled with the entire **Lucide** icon library. Simply use the icon name in kebab-case (e.g., `brain-circuit`, `terminal`, `settings`). ::: callout tip Use descriptive `title` keys even if the page content starts with a header. Clear, consistent navigation titles allow AI agents (using `llms-full.txt`) to build an accurate mental map of your project structure effortlessly. ::: --- ## [General Configuration](https://docs.docmd.io/07/configuration/overview/) --- title: "General Configuration" description: "Configure docmd.config.js schema, branding, layout, and engine features." --- The `docmd.config.js` file serves as the definitive configuration for your documentation project. It controls site structure, branding, UI behaviour, and engine-level processing rules. ## The Configuration File We recommend using the `defineConfig` helper provided by `@docmd/core`. This provides full IDE autocomplete and type-checking, enabling effortless discovery of available settings. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ title: 'My Project', url: 'https://docs.myproject.com', // ... configuration settings }); ``` ## Core Settings `docmd` utilises a simple configuration schema. Below are the primary top-level settings: | Key | Description | Default | | :--- | :--- | :--- | | `title` | The name of your documentation site. Used in the header and browser titles. | `Documentation` | | `url` | Your production base URL. Critical for SEO, Sitemaps, and OpenGraph. | `null` | | `src` | The relative path to the directory containing your Markdown files. | `docs` | | `out` | The relative path for the generated static site output. | `site` | | `base` | The base path if hosting in a subfolder (e.g., `/docs/`). | `/` | | `i18n` | Configuration for [multi-language support](localisation/index.md). | `null` | | `plugins` | Configuration for any standard or custom [plugins](../plugins/usage.md). | `{}` | ## Branding & Identity Configure how your brand is represented in the navigation header and browser tabs. ```javascript logo: { light: 'assets/images/logo-dark.png', // Logo shown in Light Mode dark: 'assets/images/logo-light.png', // Logo shown in Dark Mode href: '/', // Link destination when clicking the logo alt: 'Company Logo', // Alternative text for accessibility height: '32px' // Optional: Explicit height for the logo }, favicon: 'assets/favicon.ico', // Path to your site's favicon ``` ## Site Layout & UI `docmd` features a modular layout system. You can toggle UI components like the **Sidebar**, **Header**, **Menubar**, and **Global Search** via the `layout` object. For a full breakdown of functional zones and configuration options, see [Layout & UI Zones](layout-ui.md). ## Core Engine Features Fine-tune how `docmd` processes and renders your documentation content. ```javascript minify: true, // Minifies production assets (CSS/JS) for better performance autoTitleFromH1: true, // Uses the first H1 heading as the page title if frontmatter 'title' is missing copyCode: true, // Adds a 'Copy' button to all code blocks automatically pageNavigation: true, // Adds 'Previous' and 'Next' navigation links at the bottom of pages ``` ## Legacy Support If you are upgrading from an older version of `docmd`, the following keys are automatically mapped to the modern schema for backward compatibility: * `siteTitle` → `title` * `siteUrl` / `baseUrl` → `url` * `srcDir` / `source` → `src` * `outDir` / `outputDir` → `out` ::: callout tip Execute `docmd migrate` to automatically upgrade your configuration file to the latest schema while preserving a backup of your original settings. ::: ::: callout warning "Deprecated: editLink" The standalone `editLink` configuration option has been deprecated in favour of the [Git plugin](../plugins/git.md). The Git plugin provides the same edit link functionality plus additional features like last-updated timestamps and commit history tooltips. See the [migration guide](../plugins/git.md#migration-from-editlink) for details. ::: --- ## [Redirects & 404](https://docs.docmd.io/07/configuration/redirects/) --- title: "Redirects & 404" description: "Configure metadata-based redirects and custom branded 404 error pages for static deployments." --- In a static hosting environment, there is no server-side logic (such as Nginx rules or `.htaccess` files) to handle dynamic routing. `docmd` addresses this by generating native HTML failsafes that handle redirection and error states automatically. ## Server-less Redirects You can forward traffic from legacy URLs to new destinations by defining a mapping in the `redirects` object. ```javascript export default defineConfig({ redirects: { '/setup': '/getting-started/installation', // Short URL to deep link '/v1/api': '/api-reference' // Legacy version to modern path } }); ``` ### Technical Implementation When a redirect is defined, `docmd` creates an `index.html` file at the legacy path containing a `<meta http-equiv="refresh">` tag. This strategy ensures: 1. **Seamless Redirection**: Users are forwarded to the new destination instantly after the page loads. 2. **SEO Preservation**: Search engines recognise the redirection, helping to maintain link equity. 3. **Analytics Tracking**: Page views are captured before the redirect occurs, preserving your traffic data. ## Branded 404 Pages When a user attempts to access a non-existent URL, most static hosting providers (Netlify, Vercel, GitHub Pages) automatically look for a `404.html` file in the root directory. `docmd` generates this file by default, ensuring it inherits your site's theme, sidebar, and SPA functionality. ### Customising Error Content You can personalise the 404 error message within your configuration: ```javascript export default defineConfig({ notFound: { title: '404: Page Not Found', content: "We couldn't find the page you're looking for. Use the sidebar to find your way back." } }); ``` ::: callout tip "Local Development" The `docmd dev` server automatically serves your custom 404 page whenever a requested file is missing, allowing you to test the error experience locally. ::: --- ## [Versioning](https://docs.docmd.io/07/configuration/versioning/) --- title: "Versioning" description: "Enable multi-version documentation with seamless switching, sticky path preservation, and isolated build directories." --- `docmd` features a native Versioning Engine that allows you to manage and serve multiple versions of your project simultaneously (e.g., `v1.x`, `v2.x`). The engine automatically handles URL routing, sidebar updates, and switching logic. ## Directory Organisation To enable versioning, organise your documentation into versioned source folders. A common pattern is keeping the active version in `docs/` and archived versions in directories prefixed with `docs-`. ```text my-project/ ├── docs/ # Latest Version (Main) ├── docs-v1/ # Legacy Version ├── docmd.config.js ``` ## Configuration Define your versions within the `versions` object: ```javascript export default defineConfig({ versions: { current: 'v2', // The version ID built to the root (/) position: 'sidebar-top', // Switcher location: 'sidebar-top' or 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Latest)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## Core Features ### 1. Root SEO (The "Current" Version) The version designated as `current` is generated directly at your output root (e.g., `mysite.com/`). This ensures your primary search traffic always lands on your most up-to-date documentation. ### 2. Isolated Sub-directories Non-current versions are automatically built into subfolders matching their `id`. * `v2 (Current)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. Sticky Switching (Path Preservation) `docmd` preserves the relative path when a user switches versions. If a user is reading `mysite.com/getting-started` and switches to **v1**, they are automatically redirected to `mysite.com/v1/getting-started` (if the page exists) rather than being returned to the home page. ### 4. Asset Isolation Each version inherits your global `assets/` directory, but `docmd` ensures they are isolated during the build process to prevent style leakage or version conflicts. ### 5. Versioned Navigation Each version can maintain its own independent navigation structure. `docmd` uses a cascading priority system to resolve the sidebar, allowing you to use a centralised config or per-version/per-language `navigation.json` files. For details on the resolution hierarchy and visual examples, see [Navigation Resolution Priority](navigation.md#navigation-resolution-priority). ## Best Practices 1. **Semantic IDs**: Use concise, URL-friendly IDs like `v1`, `v2`, or `beta`. 2. **Navigation Parity**: Maintain consistent folder structures across versions to maximise the effectiveness of "Sticky Switching." 3. **Unified Configuration**: You do not need separate config files for each version; `docmd` processes all versions in a single pass. --- ## [Buttons](https://docs.docmd.io/07/content/containers/buttons/) --- title: "Buttons" description: "Inject call-to-action buttons for internal routing or external resources with a single-line syntax." --- Buttons are high-impact UI elements used for prominent navigation. Unlike block containers, the `button` is **self-closing** - it is defined on a single line and does not require a closing `:::` tag. ## Syntax ```markdown ::: button "Label" Path [Options] ``` ### Options Reference | Property | Format | Description | | :--- | :--- | :--- | | **Path** | `/path/` | Relative project URL (resolves automatically for SPA navigation). | | **External** | `external:URL`| Opens the target URL in a new browser tab (`target="_blank"`). | | **Colour** | `color:VALUE` | Applies a background colour (supports CSS names or Hex codes). | | **Icon** | `icon:NAME` | Adds a [Lucide](external:https://lucide.dev/icons) icon before the button label. | ## Usage Examples ### 1. Internal Navigation Use relative paths to ensure seamless, zero-reload transitions within the `docmd` SPA. ```markdown ::: button "Install docmd" /getting-started/installation ``` ::: button "Install docmd" /getting-started/installation ### 2. External Resource Link Prepend `external:` to the URL to secure safe external linking. ```markdown ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ``` ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ### 3. Semantic & Brand Styling Match buttons to your brand identity or semantic priority using colour overrides. ```markdown ::: button "Danger Action" /delete color:crimson ::: button "Success Confirmation" /success color:#228B22 ``` ::: button "Danger Action" ./#delete color:crimson ::: button "Success Confirmation" ./#success color:#228B22 ### 4. Buttons with Icons Add a Lucide icon to enhance visual clarity. ```markdown ::: button "Get Started" /getting-started/installation icon:arrow-right ::: button "View Source" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "Get Started" /getting-started/installation icon:arrow-right ::: button "View Source" external:https://github.com/docmd-io/docmd icon:github ## Critical Note: Self-Closing Logic Because buttons are self-closing, adding a terminal `:::` line will terminate the **parent container** (e.g., a Card or Tab) that the button resides in, potentially breaking your layout. **Incorrect Sequence:** ```markdown ::: card "Setup" ::: button "Begin" /setup ::: <-- Error: This closes the Card prematurely. ::: ``` **Correct Sequence:** ```markdown ::: card "Setup" ::: button "Begin" /setup ::: <-- Correct: This closes the Card. ``` --- ## [Callouts](https://docs.docmd.io/07/content/containers/callouts/) --- title: "Callouts" description: "Highlight critical warnings, pro-tips, and background context using semantic visual blocks." --- Callouts are used to isolate information that requires the reader's immediate attention. `docmd` provides five semantic types, each featuring distinct visual styling and themed iconography. ::: callout info "Migration-Friendly Aliases" If you're migrating from **VitePress** or **Docusaurus**, you can use their native syntax directly: - `:::tip`, `:::warning`, `:::danger`, `:::info` (VitePress) - `:::note`, `:::caution` (Docusaurus) These aliases render identically to their `docmd` equivalents. Spaceless syntax like `:::callout` also works. ::: ## Syntax Reference ```markdown ::: callout type "Optional Title" The technical content or warning goes here. ::: ``` Add an optional `icon:` parameter to override the default type icon with any [Lucide](external:https://lucide.dev/icons) icon: ```markdown ::: callout info "Custom Icon" icon:sparkles This callout uses a custom icon instead of the default info icon. ::: ``` ### Supported Semantic Types | Type | Intent | Visual Signal | | :--- | :--- | :--- | | `info` | **General Data** | Contextual background or helpful non-critical info. | | `tip` | **Optimisation** | Performance shortcuts or "Pro-tips". | | `warning`| **Cautionary** | Potential issues or deprecated features to monitor. | | `danger` | **Critical** | Risk of data loss, breaking changes, or system failure. | | `success`| **Verification** | Confirmation of successful configuration or build. | ## Implementation Gallery ### 1. Minimalist Informational Note ```markdown ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ``` ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ### 2. High-Priority Alert with Custom Title ```markdown ::: callout warning "Breaking Change Target" As of `v0.7.0`, the internal WebSocket RPC system will be officially deprecated. ::: ``` ::: callout warning "Breaking Change Target" As of `v0.7.0`, the internal WebSocket RPC system will be officially deprecated. ::: ### 3. Rich Content Composition Callouts support the full spectrum of Markdown, allowing you to embed buttons and code blocks within the alert. ````markdown ::: callout tip "Optimised Local Testing" icon:command Use the preserve flag to maintain build files during dev sessions: ```bash docmd dev --preserve ``` ::: button "CLI Flag Reference" /cli-commands ::: ```` ::: callout info "Optimised Local Testing" icon:command Use the preserve flag to maintain build files during dev sessions: ```bash docmd dev --preserve ``` ::: button "CLI Flag Reference" ./#cli-commands ::: ::: callout tip "Prioritised Logic for AI" For LLMs, callouts act as **High-Priority Anchors**. By utilising `::: callout danger` to document breaking changes or system constraints, you provide a clear signal that the AI model must prioritise this information above surrounding text during its reasoning and generation process. ::: --- ## [Untitled](https://docs.docmd.io/07/content/containers/cards/) --- ## [Changelogs](https://docs.docmd.io/07/content/containers/changelogs/) --- title: "Changelogs" description: "Generate structured, timeline-based version history and release notes." --- The `changelog` container provides a specialised layout for documenting project evolution. It automatically parses date or version headers into a vertical timeline, ensuring historical updates are easily scannable. ## Syntax Utilise the specialised `==` delimiter to define entries. The text on the `==` line is rendered as a timeline badge on the left, while the following content populates the adjacent chronological slot. ```markdown ::: changelog == v2.0.0 Description of the major feature release. == v1.5.0 Description of maintenance updates and security patches. ::: ``` ## Detailed Example: Release History Changelogs support rich Markdown within each entry, including lists, callouts, and code blocks. ```markdown ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ``` ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ::: callout tip "Historical Context for AI" Changelogs provide a temporal map for AI agents. When an LLM parses the `llms-full.txt` context, the `::: changelog` structure allows it to accurately identify when specific features, breaking changes, or security fixes were introduced, leading to higher accuracy in its development recommendations. ::: --- ## [Collapsible Sections](https://docs.docmd.io/07/content/containers/collapsible/) --- title: "Collapsible Sections" description: "Embed interactive accordion-style toggles for FAQs, deep-dive content, and spoilers." --- The `collapsible` container creates an interactive, toggleable section (accordion). This pattern is ideal for FAQs, detailed technical configuration, or any secondary information that should be accessible without cluttering the primary documentation flow. ::: callout info "VitePress Alias" If you're migrating from **VitePress**, you can use `:::details` as an alias for `:::collapsible`. Spaceless syntax like `:::collapsible` also works. ::: ## Syntax ```markdown ::: collapsible [open] "Title Text" Main content goes here. ::: ``` ### Options Reference - **`open`**: (Optional) If specified, the section initialises in an expanded state. - **`"Title"`**: The text rendered on the interactive toggle bar. Defaults to "Click to expand" if omitted. - **`icon:NAME`**: (Optional) Adds a [Lucide](external:https://lucide.dev/icons) icon before the title text. ## Detailed Implementation Examples ### Standard Usage (Initial State: Closed) Primarily used for FAQs or reducing the visual density of technical pages. ```markdown ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ``` ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ### Opt-In Visibility (Initial State: Open) Ideal for sections that should be visible by default but allow the user to minimise them for a cleaner view. ```markdown ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ``` ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ### Nested Technical Data Collapsibles can contain complex Markdown elements, including syntax-highlighted code blocks. ````markdown ::: collapsible "Analyse Sample JSON Response" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "Analyse Sample JSON Response" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ::: callout tip While content inside a `collapsible` may be hidden from the human user, it remains fully visible to the `docmd` search index and is included in the unified `llms-full.txt` stream. This ensures AI agents can provide comprehensive answers based on hidden technical details while the human-facing interface remains clean and prioritised. ::: --- ## [URL Embeds](https://docs.docmd.io/07/content/containers/embed/) --- title: URL Embeds description: How to safely embed dynamic components, videos, and social media directly into your documents. --- `docmd` ships natively with the highly-optimised **[embed-lite](external:https://github.com/mgks/embed-lite)** parser ecosystem. This allows you to aggressively map raw external URLs strictly onto the page, transforming them beautifully into completely secure, zero-latency UI components instantly! ## Supported Platforms The integrated engine natively exposes structured formatters targeting the following networks identically: * **Video Ecosystem:** YouTube (including native 9:16 Shorts support), Vimeo, Dailymotion, TikTok * **Social Connections:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **Code & Prototyping:** GitHub Gists, CodePen, Figma, Google Maps * **Music Services:** Spotify, SoundCloud ## Usage Syntax You simply use the `::: embed` container followed by any destination URL. All three enclosing formats are equivalent: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### Standard Result Example The rendering engine strictly parses that URL in the background, checking the validation matrix, and structurally injects native HTML nodes directly onto your page output gracefully: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## Fallback Safety Don't worry about generating broken screens. If the internal parser scans an unverified or strictly unavailable domain configuration mapping, `docmd` gracefully falls back to generating a simple, solid `<a>` hyperlink button mapping explicitly out to the target: ```md ::: embed "https://docs.docmd.io/content/containers/embed/" ``` *(Proceeds to generate exactly what you would see below)* ::: embed "https://docs.docmd.io/content/containers/embed/" --- ## [Grids](https://docs.docmd.io/07/content/containers/grids/) --- title: "Grids" description: "Organise layout easily with auto-adjusting responsive columns using native markdown containers." --- Grids provide a native, markdown-driven layout system in `docmd`. Instead of writing manual HTML wrappers, you can use the `grids` container to structure elements side-by-side. Columns automatically adjust their widths to fill available space and logically stack into vertical rows on smaller screens (mobile devices). ## Syntax Reference ```markdown ::: grids ::: grid #### Component A Content for the left side. ::: ::: grid #### Component B Content for the right side. ::: ::: ``` ## Practical Implementation Examples ### 1. Feature Showcasing Side-by-Side Use grids to highlight key capabilities next to each other, like combining structural cards with informational blocks. ```markdown ::: grids ::: grid ::: card "Speed :rocket:" Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability :zap:" Designed for massive monorepos and extensive project structures. ::: ::: ::: ``` ::: grids ::: grid ::: card "Speed :rocket:" Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability :zap:" Designed for massive monorepos and extensive project structures. ::: ::: ::: ### 2. Layout Balancing Grids will automatically calculate the optimal width per column (up to 4 items per row on ultra-wide screens) based on the content available and easily group rows on narrow viewports. ::: callout tip "Semantic Layouts" Using the `grids` container keeps your documentation structure purely written in Markdown, resulting in cleaner source files and ensuring LLMs interpret your structural relationships flawlessly! ::: --- ## [Hero Sections](https://docs.docmd.io/07/content/containers/hero/) --- title: "Hero Sections" description: "Build high-impact landing page headers and marketing highlights purely in Markdown." --- The `hero` container creates professional, visually striking landing page headers. It handles complex CSS requirements like **Split Layouts**, **Glow Effects**, and **Sliders** while keeping the authoring experience clean. ## Basic Syntax By default, the `hero` centres its content, making it perfect for banners and simple headlines. ```markdown ::: hero # Build Faster. Markdown to production docs in one command. ::: button "Get Started" /intro color:blue ::: ``` ## Advanced Layouts The `hero` container supports specialised flags to control its structural behaviour. | Flag | Effect | | :--- | :--- | | `layout:split` | Divides the hero into a Text area (left) and a Media area (right). Stacks vertically on mobile. | | `layout:slider` | Transforms the hero into a horizontal slider with scroll-snap behaviour. | | `glow:true` | Injects a subtle, radial gradient glow in the background. | ### The Split Layout (`== side`) Use the `== side` separator to define what content goes in the primary text area and what goes in the secondary "side" area (typically an image or a video embed). ```markdown ::: hero layout:split glow:true # docmd 2.0 Isomorphic execution. AI-optimised. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 Isomorphic execution. AI-optimised. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### The Slider Layout (`== slide`) Create an interactive hero slider by using the `== slide` separator between different content nodes. ```markdown ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ``` ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ## Responsive Behaviour The `hero` container is fully responsive by default: - On **Desktop**, `layout:split` displays side-by-side. - On **Mobile**, it automatically transitions to a centred, vertical stack to ensure optimal readability. ## Best Practices 1. **Glow Effects**: Use `glow:true` sparingly on dark mode sites for a premium "neon" feel. 2. **Media Types**: The "side" content of a split layout is perfect for the `::: embed` component, high-quality PNGs, or raw `<video>` tags. 3. **CTA Placement**: Always place `::: button` elements within the primary "Hero Copy" section (before the `== side` separator) to ensure they are the first thing users see on mobile. --- ## [Custom Interactive Containers](https://docs.docmd.io/07/content/containers/) --- title: "Custom Interactive Containers" description: "A comprehensive directory of the interactive UI building blocks available in docmd." --- Standard Markdown excels at basic text formatting, but professional technical documentation requires rich structural components to effectively communicate complex logic. `docmd` extends Markdown with a suite of **isomorphic containers** that render into responsive, high-fidelity UI elements. ::: callout tip "Migrating from Other Documentation Engines?" `docmd` supports syntax aliases from **VitePress** and **Docusaurus** out of the box. Containers like `:::tip`, `:::warning`, `:::note`, `:::details`, and `:::caution` work without modification. Spaceless syntax (e.g., `:::tabs` instead of `::: tabs`) is also supported for all containers. ::: ## Block Syntax Reference All containers utilise a consistent block syntax, ensuring a predictable authoring experience across your entire project. ```markdown ::: type "Optional Header Title" This is the primary content area. It supports **Markdown**, imagery, and deep component nesting. ::: ``` | Component | Keyword | Primary Use Case | | :--- | :--- | :--- | | **[Callouts](callouts.md)** | `callout` | Semantic highlights for tips, warnings, and alerts. | | **[Cards](cards.md)** | `card` | Framed structural blocks for feature grids and layout control. | | **[Grids](grids.md)** | `grids` | Auto-adjusting multi-column structural groups. | | **[Tabs](tabs.md)** | `tabs` | Interactive switchable panes for alternative platform instructions. | | **[Steps](steps.md)** | `steps` | Visual numbered timelines for "How-to" guides and tutorials. | | **[Tags](tags.md)** | `tag` | Self-closing, coloured labels for version, statuses, or highlight. | | **[Buttons](buttons.md)** | `button` | Self-closing, prominent call-to-action navigation links. | | **[Collapsibles](collapsible.md)**| `collapsible`| Interactive accordion toggles for FAQs and deep-dive technical data. | | **[Changelogs](changelogs.md)** | `changelog` | Structured, timeline-based version history and release notes. | | **[Hero](hero.md)** | `hero` | High-impact landing page sections with layout and slider support. | ## The Strategic Importance of Containers Containers facilitate more than visual polish; they provide high-fidelity **Semantic Signals** to the `docmd` engine and downstream AI agents: 1. **AI Context Mapping**: Marking a block as a `callout warning` explicitly tells LLMs to prioritise that information during its reasoning and generation phases. 2. **Structural Integrity**: Combining `cards` with standard CSS allows for the creation of sophisticated landing pages without ever leaving the Markdown environment. 3. **Source Maintainability**: Eliminates "HTML Bloat" in your documentation source, keeping your `.md` files clean and machine-readable. ## Recursive Composition `docmd` supports **Infinite Nesting Depth**. You can compose any container within another to build complex, interactive documentation nodes purely in Markdown. ```markdown ::: card "Architecture Overview" ::: callout info This module utilises an asynchronous I/O pipeline. ::: ::: button "Deep Explore Core Engine" /advanced/developer-guide ::: ``` [Master the Nesting Guide](nested-containers.md) --- ## [Nested Containers](https://docs.docmd.io/07/content/containers/nested-containers/) --- title: "Nested Containers" description: "Use docmd's recursive parser to combine cards, tabs, and callouts into high-fidelity page layouts." --- One of `docmd`’s most powerful technical capabilities is its **Recursive Parsing Engine**. You can nest components within each other infinitely to synthesise complex, interactive documentation blocks that would otherwise require deep HTML knowledge or custom templates. ## The Architectural Rule While nesting is mathematically infinite, always adhere to the **Self-Closing Component Rule**: ::: callout warning "Self-Closing Buttons" Because the `::: button` component is self-closing (single line), never add a terminal `:::` line after it. Doing so will inadvertently close the **parent container** housing the button, resulting in a fractured layout. ::: ## Technical Composition Examples ### 1. Interactive Resource Block Combine a **Card** for structural framing, **Tabs** for environment-specific instructions, and **Callouts** for highlighting critical information. ````markdown ::: card "Monorepo Quickstart" Choose your preferred initialisation path: ::: tabs == tab "Automated" ```bash pnpm onboard ``` ::: callout success This script handles all package installation and build tasks automatically. ::: == tab "Manual" Manually fetch and link the core engine. ::: button "Go to Developer Guide" /advanced/developer-guide ::: ::: ```` ### 2. Multi-Platform Tutorials Nesting **Tabs** inside **Steps** is a professional pattern for providing platform-specific instructions within a standard tutorial sequence. ```markdown ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the Presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ``` ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the Presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ## Design Constraints To maintain both performance and mobile responsiveness, observe the following constraints: * **Recursive Tabs**: Nesting tabs within other tabs is technically supported but strongly discouraged. It creates navigation "loops" that are visually confusing on smaller viewports. * **Sequential Conflict**: If you require numbered steps within a tab, utilise a standard ordered list (`1. Step Content`) rather than the `::: steps` container to avoid layout conflicts. * **Legibility**: While `docmd` does not strictly require indentation for nested blocks, using a 2 or 4-space indentation significantly improves the human-readability of the Markdown source. ::: callout tip "Knowledge Segmentation for AI" Nesting provides clear **Semantic Boundaries**. When an AI agent parses the `llms-full.txt` stream, a `callout` nested within a `card` explicitly tells the model that the tip is scoped to that card's specific topic, preventing context leakage and improving technical accuracy in generated responses. ::: --- ## [Steps](https://docs.docmd.io/07/content/containers/steps/) --- title: "Steps" description: "Convert standard ordered lists into high-impact visual timelines and tutorials." --- The `steps` container is designed specifically for "How-to" guides and technical tutorials. It transforms a standard Markdown ordered list into a polished, numbered vertical timeline with automatic spacing and visual emphasis. ::: callout info "Spaceless Syntax" Both `::: steps` and `:::steps` (spaceless) are supported. Use whichever style you prefer. ::: ## Syntax Wrap any standard ordered list in a `::: steps` block. ```markdown ::: steps 1. **Initialise Project** Run the `docmd init` command to scaffold your directory. 2. **Author Content** Write your documentation using standard Markdown files. 3. **Build & Deploy** Generate static assets using `docmd build`. ::: ``` ## Detailed Implementation The `steps` component supports rich Markdown content within each item, including code blocks, images, and nested containers. ```markdown ::: steps 1. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash docmd build ``` 2. **Verify Asset Integrity** Inspect the `site/` directory to ensure all assets were correctly compiled. 3. **Deploy to Infrastructure** Synchronise the `site/` directory with your primary hosting provider (e.g., S3, Cloudflare Pages, or Vercel). ::: ``` ::: steps 1. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash docmd build ``` 2. **Verify Asset Integrity** Inspect the `site/` directory to ensure all assets were correctly compiled. 3. **Deploy to Infrastructure** Synchronise the `site/` directory with your primary hosting provider (e.g., S3, Cloudflare Pages, or Vercel). ::: ## Advanced Nesting You can nest other documentation components (such as **Callouts** or **Buttons**) inside a step without interrupting the chronological flow of the sequence. ```markdown ::: steps 1. **Configure Environment** Define your project-specific variables in `docmd.config.js`. ::: callout tip Use `defineConfig` to enable IDE autocompletion for configuration keys. ::: 2. **Validate Schema** Run `docmd verify` to ensure your configuration is structurally sound. ::: ``` ::: callout tip "Workflow Optimisation" Modern AI models interpret the `steps` container as a high-fidelity signal for **Sequential Workflows**. To maximise AI accuracy in the `llms-full.txt` context, always start your list items with a **Bolded Title**. This allows agents to reliably parse the objective of each step before processing the implementation details. ::: --- ## [Tabs](https://docs.docmd.io/07/content/containers/tabs/) --- title: "Tabs" description: "Organise dense, alternative, or multi-language information into switchable interactive panes." --- Tabs are the optimal UI pattern for presenting mutually exclusive or related data sets (e.g., "Install via NPM vs. Yarn" or "macOS vs. Windows" instructions) within a compact, interactive format. ::: callout info "Spaceless Syntax" Both `::: tabs` and `:::tabs` (spaceless) are supported. Use whichever style you prefer. ::: ## Syntax Reference The `tabs` container utilises the specialised sub-delimiter `== tab "Label"`. You can optionally add an icon using the `icon:name` syntax. ```markdown ::: tabs == tab "Label 1" icon:rocket Content for the first tab. == tab "Label 2" icon:settings Content for the second tab. ::: ``` ## Implementation Gallery ### 1. Package Management Tabs are most commonly used to show installation instructions for different package managers in a single view. ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. Multi-Language Code Snippets Keep your logic clean by separating different programming languages or environments. ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.js'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.js'); ``` ::: ## Core Capabilities ### Isomorphic Lazy Rendering `docmd` implements **Conditional Resource Laziness**. If a tab contains computationally expensive elements (e.g., **Mermaid.js** diagrams or high-resolution images), these assets are only initialised and rendered once the user activates that specific tab. This ensures rapid initial page loads. ### State Persistence The default SPA router tracks the active tab's index across similar documentation pages. If a user selects "pnpm" on one page and navigates to another page with a matching tab structure, the "pnpm" tab will remain active automatically. ## Technical Constraints | Constraint | Note | | :--- | :--- | | **Nesting Depth** | To preserve layout integrity, tabs cannot be nested inside other tab components. | | **Interactive Conflict**| High-conflict syntax: To nest Steps inside a Tab, use a standard ordered list (`1. Step One`) instead of the `::: steps` container. | | **Responsive Limit** | It is recommended to limit tab counts to 6 per block to ensure mobile device compatibility. | ::: callout tip "AI Context Mapping" When utilising tabs for code snippets, always include the target language directly in the tab label (e.g., `== tab "TypeScript"`). This allows LLMs to instantly identify and extract the technically relevant section from the `llms-full.txt` context stream. ::: --- ## [Tags](https://docs.docmd.io/07/content/containers/tags/) --- title: "Tags" description: "Use the tag container to label versions, statuses, or highlight short text snippets easily inline." --- The `tag` container is a self-closing component used to insert small, pill-shaped badges directly into your text. Unlike block containers, tags do not inherit massive sizing from parent elements like headings, they retain their tight, clean proportions no matter where they are placed. ## Basic Usage To create a basic tag, simply provide the text you want to display: ::: tabs == tab "Preview" This feature was added in ::: tag "v0.7.4" color:blue and works perfectly. == tab "Markdown Source" ```markdown This feature was added in ::: tag "v0.7.4" and works perfectly. ``` ::: ## Customising Colours You can override the default tag styling by providing any valid CSS colour string (e.g., `#ff0000`, `blue`, or `hsl(...)`) using the `color:` attribute. `docmd` will automatically calculate a beautiful tinted background with perfectly contrasted text and borders! ::: tabs == tab "Preview" ::: tag "Deprecated" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stable" color:#22c55e == tab "Markdown Source" ````markdown ::: tag "Deprecated" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stable" color:#22c55e ```` ::: ## Adding Icons Just like buttons and callouts, you can easily attach an icon from the `docmd` icon library using the `icon:` attribute. ::: tabs == tab "Preview" ::: tag "Verified" icon:check-circle color:#10b981 == tab "Markdown Source" ````markdown ::: tag "Verified" icon:check-circle color:#10b981 ```` ::: ## Linking Tags If you need your tag to act as a hyperlink (for instance, linking a version tag directly to its release notes), you can use the `link:` attribute. External links are automatically detected and opened in a new tab. ::: tabs == tab "Preview" Check out the latest ::: tag "Release Notes" icon:external-link link:/release-notes/0-7-4 == tab "Markdown Source" ````markdown Check out the latest ::: tag "Release Notes" icon:external-link link:/release-notes/0-7-4 ```` ::: ## Using Tags in Headings Because tags are true inline elements, they look gorgeous when used to label major headings. They will automatically align to the baseline without inheriting the heading's massive font-size. ::: tabs == tab "Preview" # Search Filtering ::: tag "New" color:#8b5cf6 == tab "Markdown Source" ````bash # Search Filtering ::: tag "New" color:#8b5cf6 ```` ::: --- ## [Frontmatter Reference](https://docs.docmd.io/07/content/frontmatter/) --- title: "Frontmatter Reference" description: "The complete guide to page-level metadata and configuration in docmd." --- Frontmatter allows you to override global settings on a per-page basis. It must be written in YAML format at the very top of your Markdown file. ## Core Metadata | Key | Type | Description | | :--- | :--- | :--- | | `title` | `String` | **Required.** Sets the HTML `<title>` and the primary section header. | | `description` | `String` | Sets the meta description for SEO and search results. | | `keywords` | `Array` | A list of keywords for the `<meta name="keywords">` tag. | ::: callout warning "Title is important" While not strictly required, the `title` field is strongly recommended. Without it, docmd falls back to the first `# H1` heading or the filename - which can produce less ideal `<title>` tags and search results. ::: ## Visibility & Indexing | Key | Type | Description | | :--- | :--- | :--- | | `noindex` | `Boolean` | Excludes the page from the internal search index. | | `llms` | `Boolean` | Set to `false` to exclude this page from the AI context files (`llms.txt`). | | `hideTitle` | `Boolean` | Hides the title from the sticky header (useful if using a custom H1). | | `bodyClass` | `String` | Adds a custom CSS class to the `<body>` tag of this page. | ## Layout Control | Key | Type | Description | | :--- | :--- | :--- | | `layout` | `String` | Set to `full` to use the primary content width and hide the TOC sidebar. | | `toc` | `Boolean` | Set to `false` to disable the Table of Contents entirely. | | `noStyle` | `Boolean` | Disables the entire `docmd` UI (Sidebar, Header, Footer) for custom pages. | | `titleAppend` | `Boolean` | Set to `false` to prevent appending the site title to the html `<title>`, OpenGraph (`og:title`), and Twitter metadata tags. Default: `true`. | ### `noStyle` Component Control When `noStyle: true` is active, you must explicitly opt-in to the components you wish to retain: ```yaml --- noStyle: true components: meta: true # Injects SEO metadata favicon: true # Injects site favicon css: true # Injects docmd-main.css theme: true # Injects theme-specific styling highlight: true # Injects syntax highlighting scripts: true # Injects the SPA router logic sidebar: true # Injects the navigation sidebar footer: true # Injects the site footer --- ``` ## Plugin Overrides ### SEO (`seo`) * `image`: Custom social share image URL for the page. * `aiBots`: Set to `false` to block specifically AI crawlers from this page. * `canonicalUrl`: Sets a custom canonical link for SEO. --- ## [Live Preview](https://docs.docmd.io/07/content/live-preview/) --- title: "Live Preview" description: "Run docmd entirely in the browser without a backend server using the Live architecture." --- `docmd` features a modular architecture that separates filesystem operations from core processing logic. This enables the documentation engine to run **entirely within the browser**, facilitating live editors and CMS previews without the need for a Node.js backend. ::: button "Open Live Editor" external:https://live.docmd.io ## The Live Editor The built-in Live Editor provides a high-performance, split-pane interface. Author your Markdown in the left pane and observe the rendered output navigate and synchronise in real-time on the right. ### Local Execution To launch the Live Editor locally within your project: ```bash docmd live ``` ### Static Distribution Generate a standalone, static version of the editor for hosting on platforms like Vercel or GitHub Pages: ```bash docmd live --build-only ``` This generates a `dist/` directory containing the `index.html` entry point and the bundled `docmd-live.js` isomorphic engine. ## Embedding docmd You can integrate the browser-compatible bundle into your own applications to provide internal Markdown rendering or preview capabilities. ### 1. Resource Integration Include the required CSS and JavaScript bundles from your assets or a CDN: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. Isomorphic API The global `docmd` object provides the `compile` method for instantaneous rendering. ```javascript const html = await docmd.compile(markdown, { siteTitle: 'Dynamic Preview', theme: { appearance: 'dark' } }); // Inject into an iframe for style isolation document.getElementById('preview-frame').srcdoc = html; ``` ::: callout tip "AI Feedback Loops" The Live architecture is ideal for building **AI-Agent Sandboxes**. Instead of providing an agent with filesystem write access, you can pipe its suggested documentation changes to a live-compilation buffer. This allows you to visually verify AI suggestions in a "ghost" environment before committing changes to your repository. ::: --- ## [docmd : Bespoke No-Style Page Demo](https://docs.docmd.io/07/content/no-style-example/) --- title: "docmd : Bespoke No-Style Page Demo" description: "A functional demonstration of the noStyle architectural feature." noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: centre; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-colour); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>Bespoke Page Architecture</h1> <p>Demonstrating the absolute layout control enabled via <code>noStyle: true</code>.</p> </div> <div class="demo-card"> <h2>Logical Foundation</h2> <p> This demonstration utilises the <code>noStyle: true</code> frontmatter directive to bypass the global documentation layout (Sidebar, Header, and TOC). This provides a "Zero-Friction" canvas for creating marketing landing pages or custom product dashboards. </p> <h3>Enabled System Components</h3> <p>When in No-Style mode, you explicitly opt-in to the documentation engine's core features:</p> <ul> <li><strong>SEO Meta Engine</strong>: Structured tags and social graph data are retained.</li> <li><strong>Project Branding</strong>: Global favicon injection remains active.</li> <li><strong>Foundational Typography</strong>: The processed <code>docmd-main.css</code> provides base styling.</li> <li><strong>Theme Synchronisation</strong>: Light/Dark mode state is fully preserved.</li> <li><strong>Interactive Capabilities</strong>: The SPA router and component logic remain available.</li> </ul> <h3>Technical Implementation</h3> <p> The layout for this page is authored using standard HTML wrappers and scoped CSS defined within the <code>customHead</code> frontmatter field. This ensures zero CSS leakage to the rest of the documentation site. </p> <a href="/content/no-style-pages/" class="demo-button">Analyse the Implementation Guide →</a> </div> </div> --- ## [No-Style Pages](https://docs.docmd.io/07/content/no-style-pages/) --- title: "No-Style Pages" description: "Create custom landing pages and unique layouts by disabling the default docmd theme." --- `docmd` allows you to bypass the standard documentation layout (Sidebar, Header, and Footer) on a per-page basis. This is ideal for creating product landing pages, custom dashboards, or marketing splash screens while maintaining access to the documentation engine's components. ## Enabling No-Style Mode To disable the global UI, add `noStyle: true` to the page's frontmatter. ```yaml --- title: "Product Showcase" noStyle: true components: meta: true # Retain SEO and OpenGraph tags favicon: true # Retain site favicon css: true # Inject docmd-main.css for typography --- <!-- Raw HTML or specialised Markdown goes here --> <div class="hero"> <h1>Next-Gen Documentation</h1> <p>Zero-config. Isomorphic. AI-Ready.</p> </div> ::: callout info "Infinite Nesting Support" Even with `noStyle: true`, all standard `docmd` containers like `::: card`, `::: tabs`, and `::: hero` are fully supported and can be nested at any depth. ::: ``` ## Component Opt-In When `noStyle` is active, you start with a blank canvas. Selectively re-enable core system components as needed: | Component | Description | | :--- | :--- | | `meta` | Injects `<title>`, SEO meta tags, and structured OpenGraph data. | | `favicon` | Injects the project-wide favicon. | | `css` | Injects `docmd-main.css`. Highly recommended for foundational grid and typography. | | `menubar` | Injects the site's top menubar. | | `theme` | Injects the active theme's CSS variables and appearance overrides. | | `scripts` | Injects interactive component logic (requires `mainScripts: true`). | | `spa` | Enables the single-page application router (requires `scripts: true`). | ## Composable Landing Pages The primary power of `noStyle` is that it allows you to use the entire suite of `docmd` components as high-fidelity "widgets" on a blank canvas. You aren't limited to raw HTML; you can build complex, structural designs purely in Markdown. ### Building a Modern Entry Point ```yaml --- title: "Welcome" noStyle: true components: meta: true css: true menubar: true # Use the site's top navigation scripts: true # Enable interactive components mainScripts: true --- ::: hero layout:split glow:true # Build Documentation that Wows. The zero-config engine for modern engineering teams. ::: button "Get Started" /introduction color:blue ::: button "GitHub" github:docmd-io/docmd color:gray == side ::: embed [https://www.youtube.com/watch?v=dQw4w9WgXcQ] ::: ::: ::: grids ::: card "Zero Configuration" Just write markdown. No complex React logic or build scripts. ::: ::: card "AI Optimised" Structure-aware parsing for the LLM era. ::: ::: card "Fast Without the Framework Tax" Static generation with isomorphic SPA navigation. ::: ::: ``` ::: callout tip "AI-Generated Layouts" Because `noStyle` pages support raw HTML alongside `docmd` containers, they are perfectly suited for **AI-driven UI design**. You can prompt an AI: *"Design a modern hero section using Tailwind-like utility classes and docmd buttons, wrapped in a noStyle: true container."* The AI can iterate on the design within your static site pipeline with zero additional configuration. ::: ## String Replacement (i18n for noStyle) When your site has [i18n configured](../configuration/localisation/index.md), themed documentation pages get full server-side translations automatically - each locale has its own markdown files in separate directories. But noStyle pages use custom HTML, not markdown, so that approach doesn't apply. Instead, docmd provides **string replacement** - translating your HTML via `data-i18n` attributes and JSON translation files. ::: callout info "Why this only works for noStyle pages" String replacement finds elements with `data-i18n` attributes in the rendered HTML and swaps their text content. Standard markdown content renders to plain `<p>`, `<h2>`, `<li>` tags - there are no `data-i18n` attributes for the replacer to find. For translating documentation written in markdown, use [directory mode](../configuration/localisation/translated-content.md) - separate markdown files per locale. ::: ### How It Works There are two modes for string replacement: - **Server-side (recommended)**: With [`stringMode: true`](../configuration/localisation/index.md#string-mode-nostyle-pages-only) in your i18n config, docmd resolves `data-i18n` attributes **at build time** and generates fully translated HTML in `/{locale}/` directories. Each locale gets its own URL - fully indexable by search engines. - **Client-side**: The `docmd-i18n-strings.js` script loads translations at runtime via XHR. This is injected automatically on noStyle pages when i18n is configured. Useful for in-place switching without page reload (e.g. SPAs, dashboards). Both modes use the same `data-i18n` attribute syntax and JSON file format. 1. Place JSON translation files inside `assets/i18n/` - one per locale: ``` assets/ i18n/ en.json hi.json zh.json ``` 2. Each JSON file is a flat key-value map: ```json { "hero.title": "Markdown → Production Docs", "hero.subtitle": "The zero-config documentation engine.", "nav.docs": "Documentation", "nav.editor": "Live Editor", "cta.getStarted": "Get Started", "cta.install": "npm i @docmd/core" } ``` 3. Use `data-i18n` attributes on your HTML elements: ```html <h1 data-i18n="hero.title">Markdown → Production Docs</h1> <p data-i18n="hero.subtitle">The zero-config documentation engine.</p> <a data-i18n="nav.docs" href="/docs">Documentation</a> ``` The default-language text is written directly in the HTML (acts as the fallback). When a non-default locale is active, the script loads the matching JSON and replaces the text. ### Attribute Translation To translate element attributes like `placeholder`, `title`, or `aria-label`, use `data-i18n-{attr}`: ```html <input data-i18n-placeholder="search.placeholder" placeholder="Search..."> <button data-i18n-aria-label="nav.menuLabel" aria-label="Open menu">☰</button> <a data-i18n-title="nav.tooltip" title="Go to docs">Docs</a> ``` ### HTML Content For keys that contain HTML markup, use `data-i18n-html` instead of `data-i18n`: ```html <p data-i18n-html="hero.desc">Static HTML for SEO. <br>SPA for speed.</p> ``` ### Switching Locales The i18n strings module exposes a global API at `window.DOCMD_I18N_STRINGS`: ```js // Switch to Hindi DOCMD_I18N_STRINGS.switchLocale('hi'); // Get current locale console.log(DOCMD_I18N_STRINGS.locale); // 'en' // Get all configured locales console.log(DOCMD_I18N_STRINGS.locales); // [{ id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }] ``` You can build a custom language switcher using this API: ```html <select onchange="DOCMD_I18N_STRINGS.switchLocale(this.value)"> <option value="en">English</option> <option value="hi">हिन्दी</option> </select> ``` ### Events Listen for the `docmd:i18n-applied` event to run custom logic after strings are applied: ```js document.addEventListener('docmd:i18n-applied', function(e) { console.log('Locale:', e.detail.locale); console.log('Strings:', e.detail.strings); }); ``` ::: callout info "Automatic Detection" The script detects the active locale from the URL path prefix (e.g. `/hi/` → Hindi). For the default locale (rendered at `/`), it checks `localStorage` for a previously saved preference. The `switchLocale()` function handles URL navigation automatically. ::: ### In-Place Mode For single-page sites (like landing pages), you don't want locale switching to navigate to a different URL. Set `inPlace: true` in your i18n config to swap strings without any URL redirect: ```js // docmd.config.js i18n: { defaultLocale: "en", locales: [ { id: "en", label: "English" }, { id: "zh", label: "中文" } ], inPlace: true } ``` With `inPlace: true`, calling `switchLocale()` reloads the JSON for the new locale and replaces all `data-i18n` strings on the current page - no navigation occurs. --- ## [Advanced Markdown Syntax](https://docs.docmd.io/07/content/syntax/advanced/) --- title: "Advanced Markdown Syntax" description: "Use docmd's extended feature set: Custom attributes, GFM extensions, and semantic definitions." --- Beyond standard Markdown, `docmd` supports several high-fidelity extensions derived from GitHub Flavored Markdown (GFM) and custom attribute plugins. These tools provide total control over your document's structure and styling. ## GFM Extensions ### Task Lists Create interactive or read-only checklists for roadmap tracking. ```markdown - [x] Engine Optimisation Complete - [ ] Plugin API Finalisation ``` - [x] Engine Optimisation Complete - [ ] Plugin API Finalisation ### Automatic Link Resolution Standard URLs and email addresses are automatically identified and linked without additional markup: `https://docmd.io` ### Shortcode Emojis `docmd` supports standard shortcodes to inject visual personality into your documentation. > We :heart: high-performance documentation! :rocket: :smile: ## Custom Element Attributes Assign unique IDs and CSS classes directly to headers, images, and links using the curly-brace `{}` syntax. This is the primary method for applying [Custom CSS Styles](../../theming/custom-css-js.md). ### Unique Semantic IDs Useful for deep-linking directly to technical subsections. ```markdown ## Performance Benchmarks {#benchmarks-2026} ``` ### Functional CSS Classes Apply styling utilities to specific elements. ```markdown ## Centre-Aligned Section {.text-centre .text-blue} ``` ### Actionable Button Links Transform any standard markdown link into a styled call-to-action button. ```markdown [Download Latest Release](#download){.docmd-button} ``` ## Citations & Definitions ### Footnote References Add citations or technical deep-dives[^1] that are automatically collected and rendered at the bottom of the page. ```markdown Architectural decisions are documented in the RFC[^1]. [^1]: RFC-42: Isomorphic Rendering Pipeline. ``` ### Definition Lists Perfect for API parameter descriptions and glossaries. ```markdown PropName : The unique identifier for the configuration key. ``` PropName : The unique identifier for the configuration key. ### Technical Abbreviations Define abbreviations globally within a page. Hovering over the term reveals its full definition. ```markdown *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ``` *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ::: callout tip "Contextual Precision for AI" Utilising **Definitions** and **Abbreviations** provides high-quality technical signals to AI agents. When an AI processes your `llms-full.txt` context, these explicit definitions prevent lexical ambiguity, ensuring the model generates logically correct explanations for your project's specific terminology. ::: --- ## [Code Blocks](https://docs.docmd.io/07/content/syntax/code/) --- title: "Code Blocks" description: "Document technical implementations with high-fidelity syntax highlighting and interactive copy buttons." --- `docmd` utilises the ultra-fast `lite-hl` engine to provide automatic, context-aware syntax highlighting across hundreds of programming languages and configuration formats. ## Syntax Highlighting Author your technical examples using standard Markdown fenced code blocks. Always specify the language identifier to ensure the highlight engine applies the correct lexical rules. ````markdown ```javascript function initialise() { console.log("docmd engine active."); } ``` ```` **Rendered Result:** ```javascript function initialise() { console.log("docmd engine active."); } ``` ## Block Titles You can provide a descriptive title (like a filename) for your code blocks by following the language identifier with a string in double quotes. This renders a premium header above the code block. ````markdown ```javascript "initialise.js" function initialise() { console.log("docmd engine active."); } ``` ```` **Rendered Result:** ```javascript "initialise.js" function initialise() { console.log("docmd engine active."); } ``` ::: callout tip "One-Click Portability" When `copyCode: true` is enabled in your configuration (default), a subtle copy button automatically appears in the top-right corner of every code block on hover, allowing users to instantly transfer snippets to their IDE. ::: ## Strategy for AI Context When documenting code for consumption by LLMs and AI Agents, adhere to these technical best practices: 1. **Strict Language Labeling**: Explicitly labeling blocks as `typescript`, `bash`, or `json` ensures the AI parser accurately interprets the block's grammar within the `llms-full.txt` stream. 2. **Embedded Intent**: Use inline comments within your code blocks to explain the *why* behind complex logic. This provides the AI with critical reasoning context that simple text outside the block might lack. ## Language Support Reference `docmd` provides out-of-the-box support for the most common technical ecosystems, including: * **Logic**: `javascript`, `typescript`, `python`, `rust`, `go`, `ruby`, `csharp`. * **Web**: `html`, `css`, `markdown`. * **Data & Shell**: `json`, `yaml`, `bash`, `powershell`, `dockerfile`. * **Documentation**: `mermaid`, `changelog`. --- ## [Images & Visual Media](https://docs.docmd.io/07/content/syntax/images/) --- title: "Images & Visual Media" description: "Master media management: Responsive images, styling attributes, and automated Lightbox effects." --- `docmd` utilises standard Markdown syntax for media integration. We recommend centralising your media assets in the `assets/images/` directory within your project source. ```markdown ![Technical Diagram](/assets/images/architecture.png "Optional Tooltip Title") ``` ## Technical Styling Reference Assign specialised CSS classes and attributes directly to your images using the `{ .class }` attribute syntax. ### Dynamic Resizing ```markdown ![Small Scale](/assets/icon.png){ .size-small } ![Standard View](/assets/preview.png){ .size-medium } ![Full Scale](/assets/banner.png){ .size-large } ``` ### Alignment & Layout ```markdown ![Centred Focus](/assets/img.png){ .align-centre } ![Floating Right](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![Advanced Styling Example](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-centre} ## Structured Media Elements ### Figure Captions For precise, accessible media captioning, use standard HTML5 `<figure>` elements. ```html <figure> <img src="/assets/diagram.png" alt="Cloud Infrastructure Diagram"> <figcaption>Figure 1.1: Core System Infrastructure Architecture.</figcaption> </figure> ``` ### Image Galleries Organise multiple assets into a responsive, balanced grid using the `image-gallery` class. ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="User Dashboard View"> <figcaption>Live Performance Monitor</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="Configuration Panel View"> <figcaption>Project Global Settings</figcaption> </figure> </div> ``` ## Interactive Lightbox Zoom If the `mainScripts` component is active (default), `docmd` automatically applies a full-screen zoom effect to any image contained within a gallery or any image tagged with the `.lightbox` class. ```markdown ![Deep Texture Analysis](/assets/sample.png){ .lightbox } ``` ::: callout tip "AI Context & Accessibility" Always provide comprehensive **Alt-Text** for visual media. While advanced AI models possess vision capabilities, descriptive text within the Markdown source provides a direct, high-fidelity signal for the model's reasoning engine - enhancing architectural analysis and feature comprehension in the `llms-full.txt` stream. ::: --- ## [Markdown Syntax Foundation](https://docs.docmd.io/07/content/syntax/) --- title: "Markdown Syntax Foundation" description: "Master the fundamental formatting rules of docmd: Headings, typographic styles, and technical blocks." --- `docmd` adheres to standard **GitHub Flavored Markdown (GFM)** specifications. This guide establishes the baseline standards for authoring core content across your documentation site. ## Typographic Styling | Attribute | Markdown Syntax | Visual Outcome | | :--- | :--- | :--- | | **Emphasis** | `**Text**` | **Bold technical terms** | | **Italic** | `*Text*` | *Stylized variables* | | **Strikethrough** | `~~Text~~` | ~~Deprecated logic~~ | | **Inline Logic** | `` `code` `` | `engine.initialise()` | ## Structural Elements ### Semantic Header Hierarchy ```markdown # Level 1 (Automatic via Frontmatter) ## Level 2 (Major Section) ### Level 3 (Feature Detail) ``` ::: callout tip "Logical Integrity for AI" Advanced AI models and search internalizers rely on a strict heading hierarchy to build an accurate mental model of your project. By avoiding "Heading Skipping" (e.g., jumping from H2 directly to H4), you ensure the `llms-full.txt` context stream remains chronologically and logically sound. ::: ### Navigation & Reference Utilise standard link syntax for both internal documentation nodes and global resources. ```markdown [Global Resource](https://docmd.io) [Internal Module](../api/node-api.md) ``` ### Enumeration & Listing * **Unordered Segments**: Utilise `*` or `-` for scannable bullet points. * **Sequential Logic**: Utilise `1.`, `2.`, etc., for ordered instructions. (For tutorials, consider the high-impact **[Steps Container](../containers/steps.md)**). ## Technical Block Elements ### Blockquotes The standard `>` syntax is ideal for highlighting outside quotes or background context. > The docmd engine redefines the boundaries between static site generation and dynamic application delivery. ### Data Schemas (Tables) | Attribute | Data Type | Default | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## Embedded HTML Support As `docmd` is built with raw HTML parsing enabled, you can inject complex layouts or unique styling directly within your Markdown files for specialised UI requirements. ```html <div style="padding: 2rem; border: 1px solid var(--border-colour); border-radius: 12px; text-align: centre;"> Bespoke UI elements live here. </div> ``` --- ## [Linking & Referencing](https://docs.docmd.io/07/content/syntax/linking/) --- title: "Linking & Referencing" description: "Master internal cross-linking, external resources, and reliable asset referencing with docmd's automatic URL normalisation." --- `docmd` provides a reliable, filesystem-aware linking system. Write links to your source `.md` files naturally - using any format you prefer - and the engine will automatically normalise them into clean, SEO-optimised URLs for production. ::: callout info "Write Naturally, Ship Perfectly" You do not need to follow any special linking conventions. Whether you write `overview.md`, `overview/`, or just `overview`, the build engine produces the same clean, trailing-slash URL. Every internal link is automatically normalised at build time so you can focus on content, not URL formatting. ::: ## How URL Normalisation Works During the build process, the engine applies a consistent set of rules to every internal link - in Markdown text, button containers, tags, and navigation configuration alike: | What You Write | What Gets Rendered | Why | | :--- | :--- | :--- | | `overview.md` | `overview/` | `.md` extension stripped, trailing `/` added | | `overview` | `overview/` | Trailing `/` added automatically | | `overview/` | `overview/` | Already correct - no change | | `api/commands.md` | `api/commands/` | Subdirectory link normalised | | `localisation/index.md` | `localisation/` | `index` stripped - folder is the canonical URL | | `../index.md` | `../` | Parent directory index resolved cleanly | | `overview.md#settings` | `overview/#settings` | Hash fragment preserved through normalisation | | `./guide.md` | `./guide/` | Relative prefix preserved | | `https://example.com` | `https://example.com` | External links pass through untouched | ::: callout tip "SEO Best Practice" All internal pages are served as directory-style URLs ending with a trailing slash (e.g., `/configuration/overview/`). This is the industry standard for static sites, prevents 301 redirect chains, and ensures consistent canonical URLs for search engine indexing. ::: ## Internal Link Resolution Link to other pages in your documentation using relative paths to the source `.md` files. The engine resolves them correctly regardless of directory depth. | Targeting Strategy | Markdown Syntax | | :--- | :--- | | **Sibling Page** | `[System Overview](overview.md)` | | **Subdirectory** | `[API Reference](api/node-api.md)` | | **Subdirectory Index** | `[Localisation](localisation/index.md)` | | **Parent Directory** | `[Back to Home](../index.md)` | ## Section Anchors (Deep Linking) Navigate directly to specific headings using standard URL hash fragments. * **Intra-page Anchor**: `[Jump to Roadmap](#project-roadmap)` * **Cross-page Anchor**: `[Review CLI Flags](../cli-commands.md#available-flags)` Hash fragments are preserved through the normalisation process. The link above renders as `../cli-commands/#available-flags` in production. ## Opening Links in a New Tab Use the `external:` prefix on any link to force it to open in a new tab. This works universally - in standard Markdown links, button containers, tags, and anywhere else you can write a URL. ```markdown <!-- Force any link to open in a new tab --> [Open in New Tab](external:./configuration/overview.md) <!-- External link to GitHub --> [GitHub](external:https://github.com/docmd-io/docmd) ``` By default, all links (including HTTP/HTTPS) open in the same window. Use the `external:` prefix only when you want a new tab. The `external:` prefix is **stripped** from the rendered URL - it is purely a build-time signal. ## Linking to Raw Files By default, the engine strips `.md` extensions and normalises paths. If you genuinely need to link to a raw `.md` file (for example, a downloadable source file), use the `raw:` prefix: ```markdown [View Raw Source](raw:docs/readme.md) ``` The `raw:` prefix bypasses all normalisation - the extension and path are preserved exactly as written. Like `external:`, the prefix itself is stripped from the rendered URL. ## Button Containers The `::: button` container supports the same linking conventions as standard Markdown links - including `external:` and `raw:` prefixes: ```markdown ::: button "Get Started" ./getting-started/quick-start.md icon:rocket ::: button "View on GitHub" https://github.com/docmd-io/docmd icon:github ::: button "Download Source" raw:docs/readme.md icon:download ``` ## Tag Links Tags with `link:` values also benefit from the unified normaliser: ```markdown ::: tag "v0.7.6" link:release-notes/0-7-6.md icon:tag color:#22c55e ::: tag "GitHub" link:https://github.com/docmd-io/docmd icon:github ::: tag "Open Externally" link:external:./configuration/overview.md icon:external-link ``` ## Navigation Configuration Paths defined in `navigation.json` and `docmd.config.js` are also normalised at build time. You can write them in any format: ```json "navigation.json" [ { "title": "Overview", "path": "configuration/overview" }, { "title": "Overview", "path": "configuration/overview.md" }, { "title": "Overview", "path": "configuration/overview/" } ] ``` All three entries above produce the same canonical URL: `/configuration/overview/`. For navigation items that should open in a new tab, use the `external` flag: ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "Index Pages in Navigation" When linking to a directory's index page, use the folder path rather than explicitly referencing `index.md`. Both work identically, but the folder path is cleaner: ```markdown <!-- Preferred --> [Localisation](localisation/) <!-- Also works (auto-normalised) --> [Localisation](localisation/index.md) ``` ::: ## Protocols & External Resources The engine respects standard browser protocols for external resources. These links are never modified. * **Global HTTPS**: `[docmd Homepage](https://docmd.io)` - opens in same tab (use `external:` prefix for new tab) * **Mail Protocol**: `[Support Channel](mailto:help@docmd.io)` - not opened in a new tab * **Asset Protocol**: `[Download CLI Binary](/assets/bin/docmd-mac.zip)` - not normalised ## Static Asset Referencing To provide downloads or reference raw source files, place them within the `assets/` directory of your project. The `docmd` builder ensures these files are moved to the production root without path modifications. ```markdown [Download Documentation PDF](/assets/pdf/handbook.pdf) [View Raw Global Config](/assets/config/docmd.config.js) ``` ::: callout tip "Semantic Linkage for AI" When cross-linking technical modules, prioritise **Descriptive Anchors** (e.g., `[Optimise PWA caching](../plugins/pwa.md)`) over generic text (e.g., `[Read more](../plugins/pwa.md)`). Detailed link labels provide AI agents with a high-fidelity map of the semantic relationships between different documentation nodes in the `llms-full.txt` context. ::: --- ## [Contributing](https://docs.docmd.io/07/contributing/) --- title: "Contributing" description: "Guidelines and setup instructions for contributing to docmd." --- Thank you for your interest in contributing to `docmd`. We appreciate bug fixes, documentation improvements, new features, and design suggestions. ## Development Environment `docmd` is a monorepo managed with [pnpm](https://pnpm.io/). ### Prerequisites - **Node.js**: v22.x or later (LTS recommended) - **pnpm**: v10.x or later ### Project Setup Clone the repository and run the initial setup to install dependencies and build the monorepo: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` To link the local `docmd` command globally for testing in other projects: ```bash pnpm verify --link ``` ### Local Development We provide a master proxy command to run any `docmd` command against our internal `_playground` directory. This makes development identical to the user CLI experience: ```bash pnpm docmd dev # Starts playground dev server (also: pnpm dev) pnpm docmd build # Builds playground documentation ``` To watch internal source files (engine, templates, and plugins) with hot-reload, set the `DOCMD_DEV` environment variable: ```bash DOCMD_DEV=true pnpm dev ``` ## Quality Standards ### Linting Ensure your code complies with our ESLint configuration. To automatically fix formatting issues, run: ```bash pnpm lint --fix ``` ### Verification Before submitting a Pull Request, you **MUST** ensure the entire monorepo passes our intensive verification pipeline. This simulates a fresh release environment, audits for security vulnerabilities, and verifies monorepo integrity: ```bash pnpm prep ``` *(This chains `pnpm reset`, dependency installation, lint checks, 7-pillar E2E tests, and the final release dry-run.)* ## GitHub Workflow 1. **Fork and Branch**: Create a feature branch from the latest `main`. 2. **Verify**: Ensure `pnpm prep` returns `🛡️ docmd is ready for production!`. 3. **Pull Request**: Open a PR with a clear description of the problem solved or the feature added. ### Commit Guidelines We use [Conventional Commits](https://www.conventionalcommits.org/). Please prefix your commit messages with: - `feat:` (New features) - `fix:` (Bug fixes) - `docs:` (Documentation changes) - `refactor:` (Internal refactorings) ### Source Headers All new files within the `packages/` directory MUST include the standard project copyright header: ```javascript /** * -------------------------------------------------------------------- * docmd : the zero-config documentation engine. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @licence MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` --- ## [Caddy](https://docs.docmd.io/07/deployment/caddy/) --- title: "Caddy" description: "Deploy docmd with a production-ready Caddyfile." --- [Caddy](https://caddyserver.com/) is a modern web server that handles HTTPS provisioning and certificate renewals automatically. ## Generate a Caddyfile ```bash docmd deploy --caddy ``` This generates a `Caddyfile` personalised to your project: - **Site address** is set to the hostname from your `url` config - Caddy will automatically provision an SSL certificate for it. Falls back to `:80` if no URL is configured. - **Root directory** uses your configured `out` directory (not hardcoded) - **SPA fallback** is only included when `layout.spa` is `true` in your config ### What Gets Generated ```caddy docs.example.com { root * ./site file_server # SPA Routing Fallback (only when layout.spa is true) try_files {path} {path}/ /index.html # Security Headers header { X-Content-Type-Options "nosniff" X-Frame-Options "SAMEORIGIN" -Server } # Custom 404 handle_errors { rewrite * /404.html file_server } # Cache Static Assets (6 months) @static { file path *.ico *.css *.js *.gif *.jpg *.jpeg *.png *.webp *.avif *.svg *.woff *.woff2 *.eot *.ttf *.otf } header @static Cache-Control "public, max-age=15552000, immutable" } ``` When you use a real domain as the site address (e.g., `docs.example.com` instead of `:80`), Caddy automatically provisions a free SSL certificate via Let's Encrypt - zero HTTPS configuration needed. ## Deployment Steps 1. Build your site: `docmd build` 2. Transfer your output folder and the generated `Caddyfile` to your server. 3. Run `caddy start` or `caddy run` in the directory containing your Caddyfile. ### Re-Generating Changed your site URL or output directory? Run `docmd deploy --caddy` again - the Caddyfile is regenerated to match your current `docmd.config.js`. --- ## [CI/CD Pipelines](https://docs.docmd.io/07/deployment/ci-cd/) --- title: "CI/CD Pipelines" description: "Automate documentation builds and deployments with CI/CD pipelines for GitHub Pages, Vercel, Netlify, and more." --- Use CI/CD workflows to automatically build and deploy your `docmd` site every time you push changes. Below are ready-to-use configurations for popular cloud platforms. ## Cloud Platforms ::: tabs == tab "GitHub Pages" The recommended method is using **GitHub Actions** to automate your deployments on every push. **Create `.github/workflows/deploy.yml`:** ```yaml name: Deploy docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22' } - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. Connect your repository to Vercel. 2. In the project **Build Settings**: - **Framework Preset**: `Other` - **Build Command**: `npx @docmd/core build` - **Output Directory**: `site` 3. Deploy. Vercel automatically detects the static output and serves it globally. == tab "Netlify" 1. Import your project from GitHub/GitLab/Bitbucket. 2. Configure your build settings: - **Build command**: `npx @docmd/core build` - **Publish directory**: `site` 3. Click **Deploy site**. Netlify's CDN will handle the routing and asset delivery. == tab "Cloudflare Pages" 1. Create a new project in the Cloudflare Dashboard under **Pages**. 2. Connect your git provider and select your repository. 3. Configure the build settings: - **Framework preset**: `None` - **Build command**: `npx @docmd/core build` - **Build output directory**: `site` 4. Save and Deploy. == tab "Firebase" 1. Install the Firebase CLI: `npm install -g firebase-tools`. 2. Build your site: `npx @docmd/core build`. 3. Run `firebase init hosting` and select your project. 4. Set the public directory to `site`. 5. Configure as a single-page app: `Yes` (this handles the 404 behaviour). 6. Deploy using `firebase deploy`. ::: ::: callout info "Why npx @docmd/core?" In CI/CD environments where `docmd` is not globally installed, use `npx @docmd/core` to run the scoped package directly. If your project has `@docmd/core` listed as a `devDependency`, simply using `docmd build` after `npm install` will also work. ::: ## Manual / Static Server For traditional web servers (Apache, IIS, etc): 1. Generate the site: `npx @docmd/core build`. 2. Upload the contents of the `site/` folder to your server via SFTP, SCP, or your preferred deployment tool. 3. Ensure your server is configured to serve `index.html` for directories (the default for most). --- ## [Docker](https://docs.docmd.io/07/deployment/docker/) --- title: "Docker" description: "Deploy docmd in a Docker container with a single command." --- `docmd` generates static HTML - perfect for lightweight, reproducible Docker containers. ## Generate a Dockerfile ```bash docmd deploy --docker ``` This creates a `Dockerfile` and `.dockerignore` in your project root, personalised to your configuration: - **Your output directory** is used in the `COPY` path (not a hardcoded `site/`) - **Your exact `@docmd/core` version** is pinned in the install step for reproducible builds - **Your config file** is passed to `docmd build` if you use a non-default name ### What Gets Generated The Dockerfile uses an optimised multi-stage build: 1. **Stage 1 - Build**: Installs dependencies with layer caching (`package.json` copied first), installs the pinned `@docmd/core` version, and runs `docmd build`. 2. **Stage 2 - Serve**: Copies the built output into a minimal `nginx:alpine` container. ```dockerfile # Stage 1: Build FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN if [ -f package.json ]; then npm install --ignore-scripts; fi COPY . . RUN npm install -g @docmd/core@0.7.2 RUN docmd build # Stage 2: Serve FROM nginx:alpine COPY --from=builder /app/site /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` ::: callout tip "Custom Nginx with Docker" If you generate an `nginx.conf` (via `docmd deploy --nginx`) before generating the Dockerfile, it will be detected and automatically configured inside the container. ::: ### The `.dockerignore` A `.dockerignore` is generated alongside the Dockerfile to keep the build context lean: ``` node_modules site dist .git .env *.md !docs/**/*.md ``` ## Build and Run ```bash docker build -t my-docs . docker run -p 8080:80 my-docs ``` Your documentation is now live at `http://localhost:8080`. ### Re-Generating Changed your config? Just run `docmd deploy --docker` again - the files are always regenerated to match your current `docmd.config.js`. --- ## [Deployment](https://docs.docmd.io/07/deployment/) --- title: "Deployment" description: "Deploy your docmd documentation to Docker, Nginx, Caddy, or any cloud platform with a single command." --- `docmd` generates a high-performance static website. Run the build command to generate the output directory: ```bash docmd build ``` The output is a self-contained `site/` folder (or whatever you've configured as `out` in your config) that can be hosted anywhere. ## One-Command Deployment ::: callout tip "New in v0.7.2" `docmd deploy` reads your `docmd.config.js` and generates deployment files personalised to your project - no generic templates. ::: Instead of manually writing Dockerfiles and server configs, let docmd generate them for you: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # Production nginx.conf docmd deploy --caddy # Production Caddyfile ``` ### What Gets Personalised The deploy command reads your configuration (or zero-config defaults) and injects: | Config Field | Used In | |:--|:--| | `title` | Comment headers in every generated file | | `out` | `COPY` paths in Dockerfile, `root` directives in Nginx/Caddy | | `url` | `server_name` in Nginx, site address in Caddy | | `layout.spa` | Controls whether SPA routing fallback is included | | Config file path | Dockerfile build step uses `--config` when non-default | No `docmd.config.js`? No problem - the command uses the same zero-config defaults as `docmd dev` and `docmd build`. ### Always In Sync Every run regenerates your deployment files to match your current config. Changed your site URL or output directory? Just re-run the deploy command - no need to manually track what changed. Use `--force` only if you intentionally want to suppress any future confirmation prompts. By default, files are silently regenerated. ### Supported Targets * [`docmd deploy --docker`](docker.md) - Optimised multi-stage Dockerfile with layer caching and version pinning. * [`docmd deploy --nginx`](nginx.md) - Security-hardened nginx.conf with GZIP and immutable asset caching. * [`docmd deploy --caddy`](caddy.md) - HTTPS-ready Caddyfile with automatic routing. Click each target above for detailed, service-specific documentation. *(Cloud deployment targets like `--vercel` and `--netlify` are planned for a future release.)* ## Cloud Hosting & CI/CD If you prefer managed hosting over self-hosted servers, deploy your output folder directly to GitHub Pages, Vercel, Netlify, or Cloudflare Pages. See the [CI/CD Deployment Guide](ci-cd.md) for automated workflows. ## SPA Routing `docmd` implements a micro-SPA router for smooth internal navigation. Every page is generated as its own `index.html` file, so: - **No rewrite rules needed** - direct URL access works because `/guide/setup` resolves to `/guide/setup/index.html`. - **Deep linking works** - out of the box, on every hosting platform. When `layout.spa` is set to `false` in your config, the deploy command omits SPA fallback routing from generated server configs. ## Production Checklist 1. **Site URL**: Set the `url` property in `docmd.config.js` - this drives canonical tags, sitemaps, social previews, and deployment file generation. 2. **Redirects**: Migrating from another tool? Use the `redirects` config to preserve SEO rankings. 3. **Analytics**: Enable the `analytics` plugin to track engagement and search queries. 4. **AI Context**: Enable the `llms` plugin to generate `llms.txt` for AI agent ingestion. ::: callout tip "Custom 404 Pages" `docmd` generates a `404.html` in your output directory. Most hosting providers automatically serve this for missing routes. ::: --- ## [NGINX](https://docs.docmd.io/07/deployment/nginx/) --- title: "NGINX" description: "Deploy docmd with a production-ready NGINX configuration." --- NGINX is one of the most reliable web servers available. Because `docmd` output is entirely static, NGINX can serve it with near-zero latency. ## Generate nginx.conf ```bash docmd deploy --nginx ``` This generates an `nginx.conf` personalised to your project: - **`server_name`** is set to the hostname extracted from your `url` config (falls back to `localhost` if not set) - **SPA fallback** (`try_files ... /index.html`) is only included when `layout.spa` is `true` in your config - **Security headers**, GZIP compression, and immutable asset caching are included by default ### What Gets Generated ```nginx server { listen 80; server_name docs.example.com; root /usr/share/nginx/html; index index.html; # Security server_tokens off; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; # GZIP Compression gzip on; gzip_vary on; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml; # SPA Routing Fallback (only when layout.spa is true) location / { try_files $uri $uri/ /index.html; } # Custom 404 error_page 404 /404.html; # Cache Static Assets (6 months, immutable) location ~* \.(?:ico|css|js|gif|jpe?g|png|webp|avif|woff2?|eot|ttf|otf|svg)$ { expires 6M; access_log off; add_header Cache-Control "public, immutable"; } } ``` ## Deployment Steps 1. Build your site: `docmd build` 2. Upload the contents of your output directory to your server's web root (e.g., `/var/www/html/` or `/usr/share/nginx/html/`). 3. Place the generated `nginx.conf` into your server's configuration (e.g., `/etc/nginx/conf.d/default.conf`). 4. Restart NGINX: `sudo systemctl restart nginx` ### Re-Generating Changed your site URL or switched off SPA mode? Just run `docmd deploy --nginx` again - the config file is regenerated to match your current `docmd.config.js`. --- ## [Installation](https://docs.docmd.io/07/getting-started/installation/) --- title: "Installation" description: "Install docmd globally, locally, or run it instantly with npx. Requires Node.js 18+." --- Choose the installation method that fits your workflow. ## Install as a project dependency (recommended) ::: tabs == tab "npm" icon:package ```bash npm install -D @docmd/core npx @docmd/core init ``` == tab "pnpm" icon:boxes ```bash pnpm add -D @docmd/core pnpm dlx @docmd/core init ``` == tab "yarn" icon:scroll ```bash yarn add -D @docmd/core yarn dlx @docmd/core init ``` == tab "Bun" icon:zap ```bash bun add -D @docmd/core bunx @docmd/core init ``` ::: This pins the version across your team and CI/CD pipeline. ::: callout tip "After local install" Once `@docmd/core` is a project dependency, use `docmd` (or `npm docmd`, `yarn docmd`, `bun docmd`) instead of `npx @docmd/core` for all commands. ::: ## Install globally ::: tabs == tab "npm" icon:package ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: ```bash # Use the 'docmd' command anywhere docmd dev docmd build ``` ## Browser-only integration ::: callout info "Library use only" This method embeds the docmd rendering engine into another web application. It is not the standard way to build documentation sites. ::: ```html <!-- Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Processing Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` See the [Browser API](../api/browser-api.md) guide for integration details. ## Troubleshooting ::: callout warning "Permission denied (EACCES)" If you encounter `EACCES` errors during global installation on macOS or Linux, switch to a Node version manager like [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm) instead of using `sudo`. ::: ::: callout info "PowerShell script execution (Windows)" If PowerShell blocks script execution, run as Administrator: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [Project Structure](https://docs.docmd.io/07/getting-started/project-structure/) --- title: "Project Structure" description: "Learn how docmd maps physical folders and Markdown files to dynamic URLs and clean navigation." --- The compiler uses your local filesystem as the source of truth. Folders become navigation sections. Markdown files become content pages. Your directory hierarchy translates directly into web URLs. ## 1. Standard Project Scaffold Scaffolding a default project establishes a minimal workspace layout. This structure keeps source content separated from assets and production builds. ```text my-docs/ ├── docs/ ← Source directory containing your Markdown (.md) pages │ └── index.md ← The landing page (resolves to /) ├── assets/ ← Static web assets loaded directly by the engine │ ├── css/ ← Custom stylesheets for customising page layout │ ├── js/ ← Custom scripts to extend browser-side logic │ └── images/ ← Brand logos, icons, and inline illustrations ├── docmd.config.json ← Central configuration script ├── package.json ← Node dependency manifest and scripts └── site/ ← Generated production build output folder ``` ::: callout info "Configuration File Resolution" icon:settings `docmd.config.json` (or `docmd.config.ts`) is the recommended, primary configuration format. The legacy `docmd.config.js` format remains supported but acts strictly as a fallback when `.json` or `.ts` configuration files are missing. ::: ## 2. Directory and URL Mapping The compiler maps files within your source folder directly to public URLs. There are no trailing `.html` extensions or complex routing rules. | Source File | Resolved URL Path | Purpose | | :--- | :--- | :--- | | `docs/index.md` | `/` | Home Landing Page | | `docs/api.md` | `/api` | Main API Reference | | `docs/guides/setup.md` | `/guides/setup` | Sub-section Technical Guide | ::: callout tip "Automatic Header Parsing" If a file lacks a `title` in its YAML frontmatter, the engine extracts the first `H1` tag (`# Heading`). This title represents the page in breadcrumb navigation and search. ::: ## 3. Workspace Monorepo Structure For complex layouts or large projects with multiple distinct products (such as a core platform, an SDK, and a CLI tool), `docmd` natively supports a **Workspace Monorepo** directory structure. This allows you to manage multiple independent documentation sites from a single root repository while maintaining unified branding. ```text my-docs-monorepo/ ├── docmd.config.json ← Root configuration (defines global settings) ├── assets/ ← Shared global assets (inherited by all projects) │ ├── css/ ← Shared global stylesheets │ └── images/ ← Shared logos and icons ├── package.json ← Root dependency manifest ├── main-site/ ← Root project directory │ ├── docmd.config.json ← Project-specific config overrides │ └── docs/ ← Content for main-site (resolves to /) │ └── index.md └── sdk-reference/ ← Secondary project directory ├── docmd.config.json ← Project-specific config overrides └── docs/ ← Content for sdk-reference (resolves to /sdk) └── index.md ``` ### Key Workspace Directory Patterns * **Global Configuration Cascading:** Any configuration defined in the root `docmd.config.json` (such as `theme` or `menubar`) acts as a fallback default. Individual projects can selectively override these defaults in their own local config files. * **Asset Sharing and Priority:** Shared logos, global custom styles, and common scripts are placed in the root `assets/` directory. Projects can also define their own local `assets/` directories; in the event of filename conflicts, project-specific assets always take precedence. * **Output Consolidation:** During the build process (`npx @docmd/core build`), the engine automatically merges all projects into a single consolidated production output directory (e.g. `./site/` and `./site/sdk/`), negating the need for complex reverse proxy setups or isolated build pipeline configuration. --- ## [Quick Start](https://docs.docmd.io/07/getting-started/quick-start/) --- title: "Quick Start" description: "Go from an empty folder to a running documentation site in under a minute." --- Run docmd inside any folder containing Markdown files. No config file, no setup, no framework knowledge required. ## Start a dev server ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: Opens `http://localhost:3000`. Your documentation is live. ## What happens automatically docmd scans your project and sets everything up: 1. **Directory detection** - looks for `docs/`, `src/docs/`, `documentation/`, or any `.md` files 2. **Navigation generation** - builds a nested sidebar from your folder structure 3. **Metadata extraction** - reads `package.json` for the site title if available 4. **Theme activation** - applies the default theme with system-aware light/dark mode 5. **Search indexing** - enables built-in full-text search No `docmd.config.js` is needed. Add one later when you need versioning, plugins, or custom navigation. ## Build for production ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: Outputs a static site to `./site/`, ready to deploy anywhere. --- ## [Context Preservation for AI-Friendly Documentation](https://docs.docmd.io/07/guides/ai-optimisation/context-preservation/) --- title: "Context Preservation for AI-Friendly Documentation" description: "How to ensure that AI models can understand and utilise the relationships between different parts of your documentation." --- ## Problem While human readers can easily click a hyperlink to learn more about a term, AI models often process documentation in isolated "chunks." When an AI encounters a hyperlink, it cannot "click" it to fetch more context. If critical information is hidden behind a link rather than explained in context, the AI may fail to provide accurate answers, leading to hallucinations. ## Why it matters AI models rely on the immediate surrounding text to determine the meaning and relevance of information. If your documentation is highly fragmented with poor context preservation, AI-driven search tools (like those powered by RAG) will struggle to provide high-quality responses. ## Approach Use **Inline Context Unrolling** to provide the minimum viable context alongside every major link. Additionally, use `docmd`'s specific features, such as the [LLMs Plugin](../../plugins/llms.md), to provide a unified, machine-readable view of your entire documentation set. ## Implementation ### 1. Descriptive Linking and Summaries Avoid generic link text. Instead, provide a brief, one-sentence summary of the linked concept before or after the link itself. - **❌ Poor (Context Lost)**: To configure the timeout, refer to the [General Configuration](../../configuration/overview.md). - **✅ Better (Context Preserved)**: You can configure the `timeoutMs` parameter within the [General Configuration](../../configuration/overview.md), which defines how long the engine waits before failing a network request. ### 2. Using Collapsible Sections for Detail [Collapsible Containers](../../content/containers/collapsible.md) are excellent for AI optimisation. The content remains part of the raw Markdown source (which the AI can read), but it is visually tucked away for human readers. ```markdown ### Database Connection Connect using the primary URI. ::: collapsible "What is the URI format?" The URI follows the standard PostgreSQL format: `postgresql://user:password@host:port/database`. ::: ``` ### 3. Enabling the LLMs Plugin Enable the [LLMs Plugin](../../plugins/llms.md) in your `docmd.config.js`. This plugin automatically generates a `llms-full.txt` file after every build, which concatenates your entire documentation set into a single, high-context file that can be easily consumed by Large Language Models. ## Trade-offs Inline context unrolling makes your documentation slightly more verbose and introduces minor redundancy. However, this redundancy is a small price to pay for ensuring that your documentation is "AI-ready" and capable of powering high-quality automated support and search experiences. --- ## [Creating Deterministic and Chunkable Documentation](https://docs.docmd.io/07/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "Creating Deterministic and Chunkable Documentation" description: "How to structure your documentation to optimise it for Retrieval-Augmented Generation (RAG) and AI ingestion." --- ## Problem When AI pipelines (such as RAG architectures) ingest documentation, they slice the Markdown source into smaller "chunks" (e.g., 500 tokens each). If a document consists of long, meandering paragraphs with unclear boundaries, the slicing algorithm may split the context mid-thought, destroying the utility of the chunk and leading to incomplete or incorrect AI responses. ## Why it matters If an AI retrieves a chunk containing a code block but misses the preceding paragraph explaining *when* to use that code, the generated answer will lack necessary conditionality. Structuring your documentation for chunkability ensures that each segment of text contains enough context to be useful on its own. ## Approach Structure your pages as a hierarchy of deterministic, atomic blocks. Use Markdown headers to clearly delineate concepts and ensure that related information (like a warning and the code it applies to) is kept physically close together in the source file. ## Implementation ### 1. Atomic Header Sections Ensure that every `##` or `###` header encapsulates a single, atomic concept. A well-structured section should be able to stand alone as a useful chunk for an AI model. - **✅ Good**: A header "Authentication via OAuth" followed by a brief explanation and a code example. - **❌ Poor**: A massive "Getting Started" page with 15 different concepts and no sub-headers. ### 2. Tight Proximity for Critical Information Do not separate a critical warning from the code it applies to with long paragraphs. Use [Callouts](../../content/containers/callouts.md) to bind them together vertically. This increases the probability that they will remain in the same vector chunk during ingestion. ```markdown ::: callout warning "Destructive Action" Running this command will permanently delete all logs. ::: `docmd logs --clear` ``` ### 3. Automated Concatenation The [LLMs Plugin](../../plugins/llms.md) facilitates chunking by generating a `llms-full.txt` file. This file uses standard separators (`---`) between pages, helping ingestion pipelines recognise natural document boundaries while preserving the global context of your project. ## Trade-offs This approach favours a modular, segmented writing style over long, flowing narratives. While this may feel more repetitive to a human reader, it significantly improves the performance of AI-powered search and automated support agents that rely on your documentation. --- ## [Generating AI-Ready Documentation with docmd](https://docs.docmd.io/07/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "Generating AI-Ready Documentation with docmd" description: "How to use the llms.txt standard and docmd's built-in tools to provide optimised context for AI assistants." --- ## Problem Developers increasingly rely on AI coding assistants (like Cursor, GitHub Copilot, and ChatGPT) to read and interpret documentation on their behalf. If your documentation is only accessible via a web browser and is cluttered with navigation elements, trackers, and complex HTML, AI agents will consume excessive tokens on irrelevant data, quickly exhausting their context windows. ## Why it matters Providing a clean, token-optimised text version of your documentation is the modern equivalent of providing a high-quality REST API. It ensures that AI agents can quickly ingest your entire documentation set, resulting in more accurate code suggestions and better support for developers using your product. ## Approach Use `docmd`'s built-in **LLMs Plugin**. This plugin natively implements the emerging `llms.txt` standard, automatically generating token-optimised summaries and full-context files during every build process. ## Implementation The `llms` plugin is available in `docmd >= 0.7.0` and can be configured in your [Plugin Configuration](../../plugins/llms.md). ### 1. Configure the Site URL Ensure that the `url` property is correctly set in your `docmd.config.js`. This allows the plugin to generate absolute URLs for all pages in the `llms.txt` file. ```javascript // docmd.config.js export default { title: 'My Project Docs', url: 'https://docs.example.com', plugins: ['llms'] }; ``` ### 2. Output Files During the build process, `docmd` generates two key files in your site root: - **`llms.txt`**: A concise, structured Markdown summary of all your pages, including their titles, descriptions, and full URLs. - **`llms-full.txt`**: A comprehensive file containing the raw Markdown content of your entire site, concatenated with standard separators (`---`). This provides the ultimate "source of truth" for AI models. ### 3. Controlling Ingestion You can exclude specific pages from the AI-ready output by using the `llms` property in the [Page Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Internal Debugging Guide" llms: false --- ``` ## Trade-offs Generating `llms-full.txt` creates a large single file. For exceptionally large documentation sites, this file could exceed several megabytes. While this is ideal for modern LLMs with large context windows (like Gemini 1.5 Pro or Claude 3.5 Sonnet), it may be too large for smaller models. Ensure you organise your [Navigation](../../configuration/navigation.md) logically so that the AI can prioritise the most important sections. --- ## [Minimising AI Hallucinations via Documentation](https://docs.docmd.io/07/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "Minimising AI Hallucinations via Documentation" description: "How to write explicit, self-contained documentation that prevents AI models from inventing incorrect information." --- ## Problem AI models are predictive engines, not reasoning engines. If an API usage example is incomplete, uses ambiguous placeholders, or relies on implicit knowledge, the AI will often "hallucinate" - it will invent the missing pieces based on general patterns it learned during training. These inventions are frequently incorrect for your specific software, leading to developer frustration. ## Why it matters Hallucinated code destroys user trust. When a developer asks an AI for help and receives code that throws a syntax error or uses non-existent parameters, they often blame the software itself for being "buggy" or "poorly documented." Minimising hallucinations is critical for maintaining the professional reputation of your project. ## Approach Practice **Defensive Documentation**. This involves writing extremely explicit, fully instantiated code blocks that leave no room for ambiguity. Never assume that the reader (or the AI) knows the necessary imports, environment variables, or prerequisite configurations. ## Implementation ### 1. Fully-Qualified Code Blocks Always include the necessary imports or setup code in every snippet. This ensures that when an AI chunks your documentation, the code block remains a self-contained unit of truth. - **❌ Hallucination Risk**: ```javascript const config = loadConfig(); // Where does loadConfig come from? ``` - **✅ Hallucination Proof**: ```javascript import { loadConfig } from '@docmd/core'; const config = loadConfig(); ``` ### 2. Concrete Examples Over Placeholders Avoid using vague placeholders like `your-api-key` or `env-name`. Instead, provide concrete, valid examples or use comments to specify strict enum requirements. ```javascript // Valid environments: "development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. Inline Code Comments Place critical requirements *inside* the code block as comments, rather than only in the surrounding Markdown text. AI models weigh comments within code highly when generating similar snippets. ```javascript export default { // CRITICAL: The outputPath must be an absolute filesystem path. outputPath: '/var/www/html/docs' }; ``` ### 4. Categorised Warnings Use [Callouts](../../content/containers/callouts.md) to clearly mark deprecated features or breaking changes. AI models are more likely to respect a `::: callout warning` block than a simple sentence in a paragraph. ## Trade-offs Defensive documentation makes code blocks longer and more repetitive. Human readers may find seeing the same `import` statements in every snippet slightly tedious. However, the benefit of having "AI-proof" documentation that significantly reduces support tickets and user errors far outweighs the minor cost of verbosity. --- ## [Designing for Semantic Search and RAG](https://docs.docmd.io/07/guides/ai-optimisation/semantic-search-design/) --- title: "Designing for Semantic Search and RAG" description: "How to structure your documentation to optimise it for vector-based search and Retrieval-Augmented Generation." --- ## Problem Traditional keyword search (like [docmd's built-in search](../../plugins/search.md)) relies on exact text matches. If a user searches for "authentication," a basic keyword engine might fail to find a page titled "Integrating OAuth2" if that specific word doesn't appear frequently enough. Semantic search, which uses vector embeddings to understand the *meaning* of a query, solves this problem but requires specific documentation structures to be effective. ## Why it matters Modern developers expect intuitive, intent-based search experiences. If your documentation fails to surface relevant content because of minor terminology differences, users will quickly abandon your site and seek help elsewhere. Designing for semantic search ensures that your documentation remains discoverable even when users use varied terminology. ## Approach Structure your documentation to be easily consumed by Retrieval-Augmented Generation (RAG) pipelines. This involves creating "semantically dense" content where concepts are clearly defined, and pronouns are replaced with explicit entities to preserve context during the chunking and vectorization process. ## Implementation ### 1. Rich Frontmatter Metadata Use [Frontmatter](../../content/frontmatter.md) to provide explicit keywords and descriptions that might not be used naturally in the body text. This gives the search engine extra "hooks" into your content. ```yaml --- title: "Integrating OAuth2" description: "Learn how to implement secure user authentication and SSO." keywords: ["login", "authentication", "sso", "security", "identity"] --- ``` ### 2. The "Semantic Density" Strategy RAG systems slice documents into small chunks (vectors). The first paragraph of every section should contain the highest density of relevant nouns and verbs related to that topic. This ensures the primary "meaning" of the section is captured in the initial vector. - **✅ Good**: "This guide explains how to implement **OAuth2 Single Sign-On (SSO)** to provide secure **authentication** for your documentation site." - **❌ Poor**: "In this section, we'll talk about how it works and how you can set it up easily." ### 3. Avoiding Pronoun Ambiguity In a chunked database, a sentence like "It works with any provider" is useless if the preceding paragraph defining "It" was sliced into a different chunk. Be explicit. - **❌ Ambiguous**: "It is highly scalable." - **✅ Explicit**: "The **docmd Search Engine** is designed to be highly scalable." ## Trade-offs Writing for semantic density can sometimes feel slightly more formal or repetitive than traditional narrative writing. However, the resulting improvement in discoverability and the accuracy of AI-generated responses makes this a vital practice for modern, enterprise-grade documentation. --- ## [Structuring Documentation for AI Agents](https://docs.docmd.io/07/guides/ai-optimisation/structure-for-llms/) --- title: "Structuring Documentation for AI Agents" description: "How to move from visual formatting to semantic structuring to improve the accuracy of AI coding assistants." --- ## Problem Human readers rely on visual cues, sidebar navigation, and inferred context to understand documentation. AI agents and Large Language Models (LLMs), however, primarily consume raw text streams. When documentation lacks a rigorous semantic structure, these models struggle to map relationships between concepts, leading to poor reasoning and inaccurate coding suggestions. ## Why it matters If your documentation is not optimised for LLMs, developers using tools like GitHub Copilot, Cursor, or ChatGPT will receive more hallucinations when working with your software. This directly degrades the developer experience, as users often blame the product itself for the errors generated by their AI assistants. ## Approach Transition from a "visual-first" mindset to a **"semantic-first"** mindset. Use standard Markdown features - such as strict header hierarchies, explicit code block language tags, and descriptive alt text - to provide a clear, machine-readable roadmap of your content. `docmd` processes this structure into optimised outputs via the [LLMs Plugin](../../plugins/llms.md). ## Implementation ### 1. Strict Header Hierarchy Avoid skipping header levels for purely visual effects. A consistent hierarchy allows LLMs to understand the scope and relationship of different sections. - **`#` Title**: The primary subject of the page. - **`##` Major Concept**: An atomic, high-level topic. - **`###` Detail**: A specific sub-task or property of that concept. * **❌ Poor**: Using `###` immediately after `#` because you like the smaller font size. * **✅ Good**: `# Installation` followed by `## Prerequisites` and then `### System Requirements`. ### 2. Descriptive Metadata for Media Since LLMs cannot "see" images or diagrams, you must provide the architectural context in the alternative text or an adjacent paragraph. ```markdown ![System Architecture: The frontend React application communicates with the Node.js API via REST, which then queries a Redis cache and a PostgreSQL database.](../../static/img/architecture.png) ``` ### 3. Explicit Code Block Labeling Always specify the language for every fenced code block using [Syntax Highlighting](../../content/syntax/index.md). This allows LLMs to parse the code's Abstract Syntax Tree (AST) correctly. ```javascript // docmd.config.js export default { plugins: ['llms'] }; ``` ### 4. Semantic Containers Use [Callouts](../../content/containers/callouts.md) rather than generic blockquotes to provide intent. `docmd`'s semantic containers help AI models distinguish between core instructions and supplementary tips or warnings. ## Trade-offs Semantic rigor requires authors to be disciplined. You can no longer use Markdown features (like blockquotes or headers) as purely decorative elements. However, this discipline results in documentation that is significantly more accessible to both AI agents and human readers using assistive technologies. --- ## [Avoiding Anti-Patterns](https://docs.docmd.io/07/guides/content-ux/avoiding-anti-patterns/) --- title: "Avoiding Anti-Patterns" description: "How to identify and eliminate common documentation mistakes that degrade the user experience and increase content debt." --- ## Problem Over time, documentation repositories often accumulate "quick fixes" to content problems that inadvertently erode the user experience. These anti-patterns - such as vague link text or bloated code samples - become entrenched in the project, making the documentation harder to maintain and less useful for developers. ## Why it matters Anti-patterns contribute to "content debt." They degrade search engine rankings (SEO), reduce accessibility for users with disabilities, and significantly increase the cognitive load on readers who are simply trying to find a quick solution to a technical problem. High-quality documentation requires constant vigilance to keep it clean, concise, and professional. ## Approach Identify and ruthlessly eliminate common anti-patterns during the [Peer Review process](../workflows-teams/git-based-workflows.md). Use automated prose linters like Vale and manual reviews to ensure your content remains high-quality, accessible, and consistent across all pages. ## Implementation ### 1. Non-Descriptive Hyperlinks Avoid using generic text like "click here" or "read more" for links. This is harmful to SEO and makes the documentation inaccessible for screen reader users who often navigate by skipping between links. * **❌ Bad**: To configure your server, [click here](../../configuration/overview.md). * **✅ Good**: Review the [General Configuration](../../configuration/overview.md) to set up your production server. ### 2. The "Wall of Boilerplate" In code examples, including dozens of lines of standard imports and boilerplate configuration before the core logic distracts the reader from the actual point of the example. * **Solution**: Focus on the relevant code snippet. If boilerplate is necessary for context, use comments to indicate that standard imports are omitted for brevity, or use [Callouts](../../content/containers/callouts.md) to explain the required setup. ### 3. Using FAQs as "Dumping Grounds" "Frequently Asked Questions" (FAQ) pages often become a repository for information that was too difficult to integrate into the main guides. If a question is truly "frequently asked," it is a clear sign that your core documentation has failed to explain that concept effectively. * **Solution**: Instead of adding to an FAQ, refactor the relevant tutorial or conceptual guide to address the confusion directly where the user first encounters it. Use an [Important Callout](../../content/containers/callouts.md) if the information is critical for success. ## Trade-offs Eliminating FAQs requires writers to constantly refactor and improve existing documentation hierarchies as new support issues are discovered. While this adds more initial maintenance overhead than simply appending a bullet point to an FAQ list, it results in a significantly more cohesive, professional, and useful documentation site for your users. --- ## [Improving Readability](https://docs.docmd.io/07/guides/content-ux/improving-readability/) --- title: "Improving Readability" description: "How to use visual rhythm, information hierarchy, and docmd's structural tools to create highly readable documentation." --- ## Problem Technical documentation is often dense, jargon-heavy, and difficult to scan. When readers encounter "walls of text" without visual relief, they tend to skim over important details or miss critical safety warnings entirely. Dense formatting increases cognitive friction and leads to user frustration and potential errors. ## Why it matters Readability is not just an aesthetic choice - it is a functional requirement. If a developer misses a warning because it was buried in a long paragraph, the consequences can be severe. A clear information hierarchy ensures that users can find the information they need quickly, understand it accurately, and act upon it safely. ## Approach Establish a predictable visual rhythm by breaking up long sections of text and using [Thematic Containers](../../content/containers/index.md) to highlight critical information. By utilising `docmd`'s built-in structural tools, you can create a hierarchy that guides the reader's eye naturally toward the most important parts of the page. ## Implementation ### 1. The "Power of Brevity" Try to limit paragraphs to no more than three or four sentences. Shorter paragraphs are easier to digest on screens and provide natural "breathing room" for complex technical concepts. If a paragraph feels too long, consider breaking it into a list or using a sub-heading to re-categorise the information. ### 2. Categorising with Callouts Use [Callouts](../../content/containers/callouts.md) consistently to categorise information. This allows users who are skimming to instantly recognise the intent of a block based on its visual style: * **Info**: Background context or supplementary details that provide deeper understanding. * **Tip**: Best practices, shortcuts, and "pro-tips" for efficiency. * **Warning/Danger**: Critical actions that could lead to errors, data loss, or security vulnerabilities. ```markdown ::: callout warning "Production Safety" Never execute this command on a live database without verifying your backups first. ::: ``` ### 3. Sequential Instruction with Steps For tutorials and step-by-step guides, avoid narrative descriptions of actions. Instead, use the [Steps Container](../../content/containers/steps.md) to create a clear, numbered progression that is easy to follow. ```markdown ::: steps 1. **Initialise**: Run `npx @docmd/core init` in your project root. 2. **Configure**: Update your `docmd.config.js` with your site title and navigation. 3. **Build**: Run `npx @docmd/core build` to generate your production-ready static files. ::: ``` ## Trade-offs Using specialised containers like `::: steps` or `::: callout` requires contributors to learn `docmd`-specific Markdown extensions. While this adds a small learning curve, the significant improvement in information density, clarity, and professional presentation far outweighs the minimal effort of learning these powerful structural tags. --- ## [Navigation for Large Sites](https://docs.docmd.io/07/guides/content-ux/navigation-large-sites/) --- title: "Navigation for Large Sites" description: "How to organise complex documentation sets into an intuitive, scalable navigation structure using docmd's layout tools." --- ## Problem As a documentation site grows from a few dozen pages to hundreds or thousands, a simple sidebar often transforms into a confusing labyrinth of deeply nested folders. When users are forced to expand multiple levels of hierarchy just to find a specific reference, they lose context, become frustrated, and often abandon the documentation in favour of trial-and-error. ## Why it matters Navigation is the "map" of your product's capabilities. If navigation is difficult to use, users will rely exclusively on the search bar, which can lead to fragmented knowledge. A well-structured navigation system teaches the user the logic and taxonomy of your product as they browse, helping them become more proficient and self-sufficient over time. ## Approach Prioritise **Top-Level Context Switching** over deep nesting. Aim to keep your left sidebar limited to no more than two or three levels of depth. Use the horizontal [Menubar](../../configuration/menubar.md) to separate distinct documentation "domains" (e.g., Guides, API Reference, and Community), which allows each individual sidebar to remain focused, relevant, and manageable. ## Implementation ### 1. Domain-Based Separation In your `docmd.config.js`, use the [Menubar](../../configuration/menubar.md) to divide your content into high-level categories. This approach allows you to present a completely different sidebar for each domain, preventing a single navigation tree from becoming overwhelmed. ### 2. Flattening the Hierarchy Instead of splitting a single concept across many tiny Markdown pages, consolidate related information into comprehensive parent pages. Use clear [Heading Hierarchy](../../content/syntax/index.md) to allow users to navigate within the page using the auto-generated right-side Table of Contents (TOC). * **❌ Poor IA**: A folder named "Security" containing ten separate, one-paragraph files for different protocols. * **✅ Better IA**: A single, well-structured "Security Overview" page that covers all protocols, using headings to provide a clean TOC. ### 3. Using Collapsible Sections For large groups of related content that aren't accessed constantly, use the `collapsible` property in your [Navigation Configuration](../../configuration/navigation.md). This keeps the interface clean by hiding secondary information until it is explicitly requested by the user. ```json // navigation.json { "title": "API Reference", "collapsible": true, "collapsed": true, "children": [ { "title": "Authentication", "path": "api/auth" }, { "title": "Endpoints", "path": "api/endpoints" } ] } ``` ## Trade-offs Consolidating content into fewer, longer pages requires authors to be disciplined about structural clarity and heading use. If a page becomes too long without proper internal navigation (TOC), it can become its own "wall of text." However, the significant reduction in "click-fatigue" and the improved discovery of related content make a flatter, domain-based hierarchy far better for large documentation sets. --- ## [Scalable Technical Writing](https://docs.docmd.io/07/guides/content-ux/scalable-technical-writing/) --- title: "Scalable Technical Writing" description: "How to use Progressive Disclosure and structural containers to manage growing documentation complexity without overwhelming your users." --- ## Problem In the early stages of a product, documenting a feature might only take a few paragraphs. However, as the product evolves into an enterprise platform, those paragraphs can explode into a sea of edge cases, platform-specific variations (Docker, Kubernetes, Cloud), and complex configuration options. This results in "vertical bloat," where a single page becomes an unreadable wall of text that is difficult to navigate and maintain. ## Why it matters Vertical bloat destroys comprehension and increases cognitive load. When users are forced to scroll through pages of content that is irrelevant to their specific environment or use case, they become overwhelmed and often assume the product is more complex than it actually is. Scalable writing ensures that users only see the information they need at any given moment, maintaining a clear path to success. ## Approach Implement **Progressive Disclosure**. This technique involves presenting only the most critical information upfront (the "Happy Path") and hiding more complex, technical, or specific details behind interactive UI structures. `docmd` provides several built-in containers specifically designed to help you manage this complexity effectively and elegantly. ## Implementation ### 1. Handling Variations with Tabs Instead of listing instructions for multiple package managers, operating systems, or cloud providers sequentially, use the [Tabs Container](../../content/containers/tabs.md). This allows the user to select their specific environment, instantly hiding irrelevant commands and reducing visual noise. ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. Managing Edge Cases with Collapsibles If a troubleshooting step or a specific edge case only applies to a small percentage of users, do not let it interrupt the logical flow of your main tutorial. Use the [Collapsible Container](../../content/containers/collapsible.md) to bury these details while keeping them easily accessible when needed. ```markdown 1. Start the development server by running `npx @docmd/core dev`. ::: collapsible "Troubleshooting: Port already in use" If you receive an `EADDRINUSE` error, you can specify a custom port using the `--port` flag: `npx @docmd/core dev --port 4000`. ::: ``` ### 3. Progressive Detail with Callouts Use [Callouts](../../content/containers/callouts.md) to provide supplementary information that isn't required for the primary task but offers valuable context for advanced users. ## Trade-offs Hiding content inside tabs or collapsibles can occasionally make it harder for users to find information using the browser's native `Ctrl+F` search. However, `docmd`'s integrated [Search Engine](../../plugins/search.md) indexes all content within these containers, ensuring that users can still find exactly what they need through the site's primary search interface while enjoying a much cleaner reading experience. --- ## [Task vs. Concept](https://docs.docmd.io/07/guides/content-ux/task-vs-concept/) --- title: "Task vs. Concept" description: "How to apply the Diátaxis framework to separate 'How-To' guides from conceptual explanations for a more effective documentation structure." --- ## Problem A frequent mistake in technical writing is mixing the *Why* something works with the *How* to actually do it. A tutorial on "Configuring SSO," for example, can easily become bogged down with pages explaining the history of the SAML protocol, distracting the user from their immediate goal of getting the feature running. ## Why it matters User intent varies significantly depending on their current context. An engineer trying to fix a production issue at 2 AM is looking for specific, actionable steps, not architectural philosophy. Conversely, a technical leader evaluating your platform needs to understand the underlying logic before committing to an implementation. Separating these concerns ensures that both personas find the information they need without unnecessary friction. ## Approach Adopt the **Diátaxis framework**, which categorizes documentation into four distinct quadrants: Tutorials, How-to Guides, Explanation (Concepts), and Technical Reference. For this guide, we focus on the critical separation between **Task-oriented content** (actionable steps) and **Concept-oriented content** (deeper understanding). ## Implementation ### 1. The Task-Oriented Guide (How-To) Focus entirely on a specific, narrow objective. Strip out lengthy theoretical explanations and focus on the minimum steps required to achieve the goal. Use the [Steps Container](../../content/containers/steps.md) to provide a clear, unambiguous path forward. * **Title Example**: "How to Configure Webhooks" * **Structure**: * Prerequisites * Direct, actionable instructions * Verification steps (how to know it worked) ### 2. The Concept-Oriented Guide (Explanation) Focus on the "Big Picture," including architecture, design philosophy, and the "why" behind specific decisions. Avoid giving direct instructions or commands in these sections. * **Title Example**: "Understanding Webhook Delivery Architecture" * **Structure**: * High-level architecture diagrams * Retry logic and reliability philosophy * Security considerations ### 3. Effective Cross-Referencing Instead of merging the two types of content, use `docmd`'s linking tools to provide a bridge for users who need more context or are ready to implement. * **In a How-To guide**: "For a deeper explore our retry logic, see [Webhook Architecture](../../guides/performance-delivery/caching-strategies.md)." * **In a Conceptual guide**: "Ready to get started? Follow our [Webhook Configuration Guide](../../guides/integrations/alongside-other-tools.md)." ## Trade-offs Separating tasks and concepts increases the number of pages in your navigation and requires more rigorous cross-linking. However, this modular structure significantly improves the long-term maintainability, searchability, and overall professionalism of your documentation suite. --- ## [Customising Favicons and Metadata](https://docs.docmd.io/07/guides/customisation/custom-favicons-metadata/) --- title: "Customising Favicons and Metadata" description: "How to configure your site's visual identity in the browser and optimise social media previews." --- ## Problem A default documentation site often lacks a distinct visual identity in the browser (using a generic favicon) and provides poor previews when links are shared on social media or communication tools like Slack and Discord. This reduces brand recognition and click-through rates. ## Why it matters Your favicon is the primary visual anchor in a crowded browser window. High-quality OpenGraph and Twitter metadata ensure that your documentation looks professional and trustworthy when shared, providing context through titles, descriptions, and hero images. ## Approach `docmd` provides a built-in `favicon` property for easy icon configuration. For advanced SEO and social metadata, use the [SEO Plugin](../../plugins/seo.md), which automates the generation of meta tags based on your project configuration and page frontmatter. ## Implementation ### 1. Configuring the Favicon Place your favicon file (e.g., `favicon.svg` or `favicon.ico`) in your source directory and reference it in your `docmd.config.js`. `docmd` will automatically handle the relative pathing and cache-busting. ```javascript // docmd.config.js export default { title: 'My Project', favicon: '/favicon.svg' // Relative to source directory }; ``` ### 2. Global SEO Configuration Enable and configure the [SEO Plugin](../../plugins/seo.md) to set default social media previews for your entire site. ```javascript // docmd.config.js export default { url: 'https://docs.example.com', plugins: { seo: { defaultDescription: 'The ultimate guide to our amazing software.', openGraph: { defaultImage: '/static/og-banner.png' }, twitter: { siteUsername: '@myproject', cardType: 'summary_large_image' } } } }; ``` ### 3. Page-Specific Overrides You can override SEO settings for individual pages using the `seo` property in the [Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Major Release v2.0" description: "Everything you need to know about our new engine." seo: image: "/assets/v2-hero-banner.png" keywords: ["release", "v2", "update", "performance"] --- ``` ## Trade-offs While the `favicon` property is convenient, it only supports a single file. For complex multi-size favicon sets (Apple Touch Icons, Android manifests, etc.), you may need to use a custom plugin to inject additional `<link>` tags into the `<head>`. --- ## [Custom Fonts and Branding](https://docs.docmd.io/07/guides/customisation/custom-fonts-branding/) --- title: "Custom Fonts and Branding" description: "How to match your documentation's appearance to your corporate identity using CSS variables." --- ## Problem Ensuring that your documentation platform easily matches your corporate identity is critical for maintaining a professional appearance. The default font stack and colour palette are designed for general readability but may not reflect your specific brand personality. ## Why it matters Documentation is a key brand touchpoint. If your main product uses a specific typography (like "Outfit") and a distinct primary colour, your documentation should reflect those same choices. Consistency across all your web properties builds trust and provides a more cohesive user experience. ## Approach `docmd` uses a system of CSS custom properties (variables) that define the layout's visual tokens. You can easily override these variables in a custom stylesheet without needing to modify the core engine. ## Implementation ### 1. Create a Custom Stylesheet Create a file named `custom.css` in your source directory (or any subdirectory) and override the `:root` variables. ```css /* Import your brand font */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* Brand Typography */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* Brand Colours (Light Mode) */ --link-color: #8a2be2; /* Your primary brand colour */ --link-colour-hover: #7b1fa2; --bg-color: #fcfcfd; /* Subtle background tint */ } /* Dark Mode Overrides */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. Register the Stylesheet Add your custom CSS file to the `theme.customCss` array in your `docmd.config.js`. ```javascript // docmd.config.js export default { theme: { customCss: ['/custom.css'] } }; ``` ## Trade-offs Importing external fonts (like those from Google Fonts) adds a small amount of latency to the initial page load. To optimise performance, consider hosting your font files locally within your project and using `font-display: swap` to prevent "Flash of Unstyled Text" (FOUT) while the custom font is loading. --- ## [Designing Custom Landing Pages](https://docs.docmd.io/07/guides/customisation/custom-landing-pages/) --- title: "Designing Custom Landing Pages" description: "How to use docmd's hero and grid containers to create premium landing pages for your documentation." --- ## Problem By default, the `index.md` file in most documentation generators looks like a standard technical page. Creating a high-impact, marketing-grade landing page usually requires a separate web framework (like Next.js or Astro), which adds complexity to your documentation workflow. ## Why it matters Your documentation homepage is often the first interaction a developer has with your product. A generic Markdown-parsed page may fail to inspire confidence in your project's polish and professional quality. A custom landing page can better guide users to the most important sections while reinforcing your brand's visual identity. ## Approach `docmd` provides specialised [Hero](../../content/containers/hero.md) and [Grids](../../content/containers/grids.md) containers designed specifically for building premium landing pages. For total creative freedom, you can also use the `noStyle` frontmatter property to take complete control over a page's HTML and styling. ## Implementation ### 1. Using the Hero Container The `hero` container supports several layouts, including `split` (for side-by-side content) and `glow` (for a modern aesthetic). ```markdown ::: hero layout:split glow:true # Build Faster with docmd The zero-config documentation engine for modern developer teams. [Get Started](/docs/start) [View on GitHub](https://github.com/docmd-io/docmd) == side ![Dashboard Preview](../../static/img/hero-preview.png) ::: ``` ### 2. Organising Content with Grids Use [Grids and Cards](../../content/containers/grids.md) to create high-level navigation sections that help users find what they need quickly. ```markdown ::: grids ::: grid ::: card "Quick Start" icon:rocket Get up and running in less than 5 minutes. [Learn More](/docs/start.md) ::: ::: ::: grid ::: card "API Reference" icon:code Comprehensive documentation for all our endpoints. [Explore API](/api) ::: ::: ::: ``` ### 3. Full Customisation with noStyle If you need a completely custom design that ignores the standard documentation layout (no sidebar or header), use the `noStyle` property in the [Page Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Custom Dashboard" noStyle: true --- ``` When `noStyle: true` is set, `docmd` will render only the raw HTML/Markdown content you provide, allowing you to inject your own CSS and JavaScript for a pixel-perfect experience. ## Trade-offs Using `noStyle: true` means you forfeit the native navigation, search, and theme-switching features provided by `docmd`. You are responsible for ensuring that the custom page is mobile-responsive and accessible. For most use cases, combining the `hero` and `grid` containers within the standard layout provides the best balance of aesthetics and functionality. --- ## [Extending docmd with Custom Plugins](https://docs.docmd.io/07/guides/customisation/extending-custom-plugins/) --- title: "Extending docmd with Custom Plugins" description: "How to use docmd's lifecycle hooks to build custom functionality and extend the documentation engine." --- ## Problem Sometimes you have a highly specific requirement that isn't covered by built-in features or existing plugins. For example, you might need to fetch data from an internal API during the build process or perform complex transformations on the generated HTML that go beyond simple CSS. ## Why it matters Extensibility is what separates a static tool from a professional documentation framework. Without a clean way to inject custom logic, teams are often forced to maintain fragile shell scripts or post-processing wrappers that make the build process difficult to manage and debug. ## Approach `docmd` features a reliable, hook-based [Plugin API](../../plugins/building-plugins.md). You can write simple Node.js modules that intercept the documentation lifecycle at various stages - from initial configuration to final HTML generation - allowing you to arbitrarily modify content and behaviour. ## Implementation ### 1. Create a Local Plugin A plugin is a standard JavaScript module that exports a descriptor and several lifecycle hooks. ```javascript // plugins/version-injector.js export default { // Plugin Metadata plugin: { name: 'version-injector', version: '1.0.0', capabilities: ['build'] // Required to use 'build' hooks }, // State shared across hooks latestVersion: '0.0.0', // Runs once the configuration is resolved async onConfigResolved(config) { // Fetch data from an internal API const response = await fetch('https://api.internal.com/version'); this.latestVersion = await response.text(); console.log(`[Plugin] Fetched version: ${this.latestVersion}`); }, // Intercepts page context before template rendering async onBeforeRender(page) { if (!page.html) return; // Replace placeholders with dynamic data in both HTML and frontmatter page.html = page.html.replace(/\{\{VERSION\}\}/g, this.latestVersion); page.frontmatter.computedVersion = this.latestVersion; } }; ``` ### 2. Register the Plugin You can register your local plugin by importing it into your `docmd.config.js`. ```javascript // docmd.config.js import VersionInjector from './plugins/version-injector.js'; export default { title: 'My Project Docs', plugins: { // Register by providing the imported module 'version-injector': VersionInjector } }; ``` ## Trade-offs Custom plugins run in the Node.js environment during build time. While powerful, they can impact build performance if not optimised. Any logic in hooks like `onAfterParse` or `onPageReady` runs for *every* page in your site. Ensure your transformations are efficient (e.g., using optimised Regex) to keep build times fast. --- ## [Alongside Other Tools](https://docs.docmd.io/07/guides/integrations/alongside-other-tools/) --- title: "Alongside Other Tools" description: "Strategies for integrating docmd into a multi-tool documentation ecosystem to create a seamless user experience." --- ## Problem Large organisations rarely use a single tool for all their documentation needs. Your company might use Confluence for internal specifications, Stoplight for API design, and GitHub for code examples. Integrating these disparate sources into a unified user journey is a significant challenge, as users often find themselves jumping between disconnected portals with different styles and navigation. ## Why it matters A fragmented documentation experience ruins developer trust and increases cognitive load. If a user is forced to switch between completely different interfaces just to follow a single tutorial, they are more likely to lose context or abandon your product. Unifying your tools ensures a professional, cohesive experience that encourages exploration and learning. ## Approach Use `docmd` as your primary documentation hub or "Single Pane of Glass." By using the [Menubar](../../configuration/menubar.md) for unified navigation and [Embed Containers](../../content/containers/embed.md) for third-party content, you can create a seamless interface that hides the complexity of your multi-tool infrastructure. ## Implementation ### 1. Unified Global Navigation Use the `menubar` configuration to link your various documentation portals together. This ensures that users can always find their way back to the main guides, regardless of which subdomain they are currently on. ```javascript // docmd.config.js export default { layout: { menubar: { left: [ { text: 'Guides', url: '/' }, // docmd site { text: 'API Reference', url: 'https://api.example.com' }, // External tool { text: 'Community', url: 'https://forum.example.com', external: true } ] } } }; ``` ### 2. Seamless Embedding For tools that provide a web interface (like interactive API explorers or dashboard previews), use the `::: embed` container to display them directly within your `docmd` pages. This keeps users within your branded environment. ```markdown # Interactive API Explorer ::: embed "https://api.example.com/v1/explorer" ::: ``` For more information, see the [Embed Reference](../../content/containers/embed.md). ### 3. Content Aggregation For external content that must be searchable alongside your core documentation, consider a build step that fetches data from other sources and converts it into Markdown. This allows `docmd` to index all your information in a single, unified [Search Index](../../plugins/search.md). ## Trade-offs While embedding provides a unified look, it can occasionally introduce performance overhead or "scroll-nesting" issues on mobile devices. In addition, content within an iframe is not natively indexed by `docmd`'s search engine. If search parity is critical, prioritising [OpenAPI Generation](openapi-generation.md) or other Markdown-based ingestion methods is recommended. --- ## [Existing Markdown Repos](https://docs.docmd.io/07/guides/integrations/existing-markdown-repos/) --- title: "Existing Markdown Repos" description: "How to instantly generate a professional documentation site from your existing Markdown files with zero configuration." --- ## Problem You have an established repository with hundreds or thousands of raw Markdown files - perhaps a legacy wiki, an Obsidian vault, or a collection of technical notes. Manually converting frontmatter, fixing broken links, and restructuring files to fit a new engine is a difficult task that often prevents teams from modernising their documentation. ## Why it matters Your content should remain portable and tool-agnostic. A high-quality documentation engine should adapt to your existing files, not force your files to adapt to the engine. Avoiding vendor lock-in ensures that your intellectual property remains standard, readable, and future-proof. ## Approach `docmd` adheres to strict CommonMark specifications and is designed to be **zero-config** by default. You can point the `docmd` CLI at any directory containing Markdown files, and it will intelligently bootstrap a full-featured documentation site without modifying a single line of your source content. ## Implementation ### 1. Instant Bootstrapping Navigate to your existing Markdown folder and run the development server. `docmd` will scan your directory structure and build a functional site in memory instantly. ```bash cd my-existing-docs/ npx @docmd/core dev ``` ### 2. Automatic Navigation (Auto-Router) If no `navigation.json` or `docmd.config.js` is found, `docmd` triggers its [Auto-Router](../../configuration/navigation.md#automatic-sidebar-generation). It recursively maps your folder structure, prettifies directory names (e.g., `getting-started` becomes `Getting Started`), and generates a logical sidebar taxonomy automatically. ### 3. Intelligent Title Inference You don't need to add `title` frontmatter to every file. `docmd` uses a cascading resolution strategy to determine page titles: 1. **Frontmatter**: Checks for a `title` or `h1` key. 2. **First Heading**: Extracts the first `# Heading` found in the file content. 3. **Filename**: Prettifies the filename as a fallback (e.g., `install-guide.md` becomes `Install Guide`). ### 4. Resilient Syntax Handling `docmd` is built to be resilient. If your existing files contain proprietary syntax or legacy shortcodes from other engines, they are safely rendered as raw text or skipped, ensuring that your build never fails due to content you haven't yet migrated. ## Trade-offs Automatic sidebars are typically sorted alphabetically by filename. While naming files like `01-intro.md` and `02-setup.md` works well, more descriptive filenames may appear in an unintuitive order. For production-ready sites, we recommend transitioning to a manual [Navigation Configuration](../../configuration/navigation.md) to gain full control over the user journey. --- ## [GitHub Actions CI/CD](https://docs.docmd.io/07/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "How to automate your documentation builds and deployments using GitHub Actions and docmd for a high-velocity documentation workflow." --- ## Problem Building and deploying documentation manually from a local machine is prone to errors, environment inconsistencies (e.g., differing Node.js versions), and security risks. It also creates a bottleneck, as deployments depend on a single individual's availability and local setup. ## Why it matters Continuous Deployment (CD) ensures that your documentation is always in sync with your software. When a technical update is merged, it should reach your users within minutes, not days. Automation guarantees that every build happens in a clean, reproducible environment, maintaining high standards of quality and reliability. ## Approach Use GitHub Actions to run the `docmd` build pipeline on every push or Pull Request. The resulting static assets can then be automatically deployed to hosting providers like GitHub Pages, Cloudflare Pages, or containerised environments using Docker. ## Implementation ### 1. Standard GitHub Pages Workflow Create `.github/workflows/docs.yml` to automate the build and deployment process. ```yaml name: Deploy Docs on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # Build the site into the 'site/' directory - run: npx @docmd/core build - name: Upload Artifact uses: actions/upload-pages-artifact@v3 with: path: site/ - name: Deploy to GitHub Pages uses: actions/deploy-pages@v4 ``` ### 2. Containerised Deployment (Docker) If you host your own documentation, use the [Deploy Command](../../deployment/index.md) to generate a production-ready `Dockerfile` and server configurations. ```bash # Generate Docker and Nginx configs locally npx @docmd/core deploy --docker --nginx ``` You can then update your GitHub Action to build and push this Docker image to a registry (like Docker Hub or GitHub Container Registry) whenever you release a new version. ### 3. Pull Request Previews Enhance your workflow by generating ephemeral preview environments for every Pull Request. This allows reviewers to see the rendered documentation before it is merged into the main branch. See the [Previewing Changes Guide](../workflows-teams/previewing-changes.md) for more details. ## Trade-offs Automated CI/CD requires initial setup time and management of secrets (e.g., API tokens). However, the long-term benefits of a "hands-off" deployment process - including reduced human error and faster update cycles - far outweigh the initial investment. For large sites, ensure your workflow only triggers when files in your documentation directory are changed to save on CI minutes. --- ## [OpenAPI Generation](https://docs.docmd.io/07/guides/integrations/openapi-generation/) --- title: "OpenAPI Generation" description: "How to integrate OpenAPI/Swagger schemas into your docmd workflow for automated and synchronised API reference documentation." --- ## Problem Manually maintaining REST API documentation is a major operational risk. The moment an engineer modifies an endpoint or updates a schema in the code, the documentation becomes obsolete. Keeping these in sync manually is tedious, error-prone, and frequently leads to integration failures for your API consumers. ## Why it matters Inaccurate API references are a primary cause of developer frustration and increased support tickets. Automation ensures that your documentation remains the "source of truth," reflecting the actual state of your API in real-time (or at every build). This allows engineers to focus on building features rather than manually updating documentation tables. ## Approach Implement an asynchronous build pipeline that converts your `openapi.json` or `swagger.yaml` schema into standard Markdown files. Because `docmd` excels at rendering Markdown with complex [Containers](../../content/containers/index.md), the resulting API reference feels integrated and visually consistent with the rest of your documentation. ## Implementation ### 1. Build Pipeline Integration You can use a tool like `widdershins` or a custom script to generate Markdown from your OpenAPI schema as a pre-build step in your CI/CD pipeline. ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. Optimising API Layouts API references are often content-dense, with large tables for parameters and nested schemas. Use [Frontmatter](../../content/frontmatter.md) to optimise the page layout for readability. ```markdown --- title: "REST API Reference" layout: "full" # Maximises horizontal space for dense tables --- ``` Setting `layout: "full"` removes the right-hand Table of Contents sidebar, providing more room for wide code blocks and response examples. ### 3. Enhancing with docmd Containers You can post-process the generated Markdown to inject `docmd` features like [Tabs](../../content/containers/tabs.md) for multi-language code samples or [Callouts](../../content/containers/callouts.md) for authentication warnings. ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## Trade-offs Machine-generated documentation is excellent for technical accuracy but often lacks the "human touch" required for effective learning. We recommend using OpenAPI generation for the **Technical Reference** (endpoints, parameters, schemas) while providing handwritten **Tutorials** and **Conceptual Guides** to explain the context and use cases for your API. --- ## [Caching Strategies](https://docs.docmd.io/07/guides/performance-delivery/caching-strategies/) --- title: "Caching Strategies" description: "How to optimise your documentation site's performance using immutable caching, Etag revalidation, and production-ready server configurations." --- ## Problem When a documentation site is served without proper cache-control headers, browsers will unnecessarily re-download images, CSS, and JavaScript bundles on every visit. This results in visual stuttering, increased bandwidth consumption, and a poor experience for returning users who expect the documentation to load instantaneously. ## Why it matters Effective caching is one of the most impactful ways to improve the "perceived performance" of your site. By ensuring that static assets are stored locally in the user's browser, you eliminate the latency of repeated network requests. This makes navigating your documentation feel fluid and reliable, even on unstable network connections. ## Approach Implement a two-tier caching strategy: **Immutable Caching** for static assets (CSS, JS, images) and **Etag Revalidation** for dynamic content (HTML, JSON). `docmd` facilitates this by generating production-ready configurations that handle cache-busting automatically through version hashes. ## Implementation ### 1. Production-Ready Server Configs The easiest way to implement optimal caching is by using the [Deploy Command](../../deployment/index.md) to generate your server configuration. ```bash # Generate an optimised Nginx configuration npx @docmd/core deploy --nginx ``` ### 2. Immutable Assets For assets that don't change frequently (like theme styles and core scripts), use long-term caching. `docmd` appends version hashes to these assets to ensure that users only download new versions when you update your documentation. ```nginx # Example Nginx rule for immutable assets location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML & Navigation Revalidation Your HTML files and `navigation.json` should always be checked for updates to ensure users see the latest content and structure immediately. Use the `no-cache` directive to force the browser to revalidate with the server using Etags. ```nginx # Example Nginx rule for HTML files location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## Trade-offs ### Stale Content vs. Performance Setting long cache times for assets is highly performant but requires a reliable "cache-busting" strategy. `docmd` handles this automatically for its core files, but if you manually add assets to your `static/` directory, you must ensure you update their references (e.g., by changing the filename or adding a query parameter) when the content changes. ### CDN Integration If you are using a CDN (like Cloudflare or AWS CloudFront), ensure that it is configured to honour your server's `Cache-Control` headers. Most modern CDNs provide "instant purge" capabilities, which we recommend triggering as part of your CI/CD pipeline whenever you deploy a new version of your documentation. --- ## [CDN & Edge Deployment](https://docs.docmd.io/07/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN & Edge Deployment" description: "How to minimise global latency by deploying your static documentation to a Content Delivery Network (CDN) or Edge Network." --- ## Problem Hosting your documentation on a single server in one geographic region (e.g., US-East) means that users in other parts of the world (e.g., Europe or Asia) will experience significant network latency. Every page load, image, and script must travel thousands of miles, making your documentation feel sluggish and unresponsive for a global audience. ## Why it matters High latency directly harms the developer experience. Even if your documentation is well-written and lightweight, the "Time to First Byte" (TTFB) is limited by the laws of physics. If your site feels slow, developers are more likely to lose focus or abandon your tool entirely in favour of one with faster, more accessible documentation. ## Approach The optimal solution is to deploy your site to an Edge CDN. Because `docmd` generates pure static assets (HTML, CSS, JS), it is perfectly suited for edge distribution. CDNs replicate your files across hundreds of globally distributed "Edge Nodes," serving your users from the data centre closest to them. ## Implementation ### 1. Choose a Platform `docmd` is natively compatible with all modern static hosting and edge platforms. We recommend the following for their global performance and ease of use: * **Cloudflare Pages**: Extremely fast global edge network with built-in DDoS protection. * **Vercel**: Optimised for performance with excellent developer workflow integration. * **Netlify**: Powerful automation features and a reliable global CDN. ### 2. Automate the Build Use a CI/CD pipeline to build and deploy your site automatically whenever you push changes. See the [GitHub Actions Guide](../../guides/integrations/github-actions-cicd.md) for detailed examples. ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # Build the site into the default 'site/' directory - run: npm install && npx @docmd/core build # Example: Deploying to Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: my-docs directory: site ``` ### 3. Verification Once deployed, you can verify your global performance using tools like PageSpeed Insights or global ping tests. You should see sub-100ms response times from almost any location worldwide. ## Trade-offs Global edge networks abstract away server management, which is a major advantage for documentation teams. However, debugging regional caching issues can occasionally be more complex than reviewing a single server log. Using platforms with reliable "instant cache invalidation" ensures that your users always see the latest version of your documentation immediately after a deployment. --- ## [Low-End Device Optimisation](https://docs.docmd.io/07/guides/performance-delivery/low-end-devices/) --- title: "Low-End Device Optimisation" description: "How to build high-performance, accessible documentation that works easily on low-powered hardware and slow network connections." --- ## Problem Modern documentation sites often rely on heavy JavaScript runtimes just to display static text. For users on older mobile phones, budget laptops, or slow 3G/4G connections, these sites can take several seconds to load. The device's processor struggles to parse large JS bundles, resulting in "input lag," stuttering animations, and a poor overall reading experience. ## Why it matters Technical documentation should be universally accessible. Forcing users in emerging markets or those on constrained hardware to download and execute a heavy framework just to read a tutorial creates an unnecessary barrier to learning. A lightweight site ensures your product information is available to everyone, regardless of their hardware or internet speed. ## Approach Adopt an **HTML-First** strategy. `docmd` is designed with a zero-framework architecture, ensuring that the primary content is rendered into standard HTML during the build process. This keeps the browser's main thread unblocked, ensuring smooth scrolling and snappy navigation even on budget devices. ## Implementation ### 1. Minimal Runtime Footprint By default, `docmd` does not use React, Vue, or any other heavy client-side framework for its core UI. This pre-rendered approach ensures that the initial "First Contentful Paint" happens almost immediately. To maintain this performance: * **Limit Custom Scripts**: Avoid adding large third-party libraries to your `customJs` configuration. * **Use Native Browser Features**: Rely on standard CSS and HTML5 elements which are highly optimised by all modern browsers. ### 2. Strategic Plugin Management While [Plugins](../../plugins/usage.md) add powerful features, they can introduce significant performance overhead. For example, the [Mermaid Plugin](../../plugins/mermaid.md) requires a large engine to render diagrams. If your users are primarily on low-end devices, consider using static images for diagrams instead of client-side rendering. ### 3. Responsive and Optimised Media Avoid serving oversized images to mobile users. Use modern formats like WebP and consider the `<picture>` tag for more granular control over responsive assets. ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="Feature Overview" loading="lazy"> </picture> ``` Using the `loading="lazy"` attribute ensures that images are only downloaded as they enter the user's viewport, saving bandwidth on slow connections. ### 4. Efficient Search Indexing `docmd` generates scoped search indices to keep the memory footprint low. However, for extremely large sites, the [Search Plugin](../../plugins/search.md) can still be memory-intensive. Encourage users on mobile to use the search bar only when necessary, or optimise your index as described in the [Local-First Search Guide](../search/local-first-search.md). ## Trade-offs Prioritising performance for low-end devices often means avoiding "heavy" interactive features like complex 3D visualizations or large client-side data processing. This is a deliberate design choice that values **inclusivity and speed** over visual complexity, ensuring your documentation remains a useful resource for the widest possible audience. --- ## [Reducing JS Payload](https://docs.docmd.io/07/guides/performance-delivery/reducing-javascript-payload/) --- title: "Reducing JS Payload" description: "How to maintain a high-performance documentation site by optimising your JavaScript dependencies and using docmd's zero-framework architecture." --- ## Problem Many modern documentation tools rely on heavy JavaScript frameworks (like React or Vue) just to render static text. These frameworks can add several hundred kilobytes to your initial page load, forcing the browser to download, parse, and execute large amounts of code before the site becomes fully interactive. This leads to slow loading times and "ghost clicks" on low-end devices. ## Why it matters A large JavaScript payload directly impacts "Time to Interactive" (TTI). In technical documentation, where users need answers quickly, any delay caused by heavy framework initialisation is a significant usability barrier. Keeping your payload small ensures that search, navigation, and theme switching are instantaneous from the moment the page appears. ## Approach `docmd` uses a **zero-framework** architecture for its core client-side logic. By utilising Vanilla JavaScript and native browser APIs instead of a heavy Virtual DOM, we keep the total JS payload for a standard site under **20KB**. This lightweight foundation ensures maximum performance across all devices and network conditions. ## Implementation ### 1. Use Native Browser APIs Avoid importing heavy libraries like jQuery or Lodash for simple tasks. Modern browsers have reliable native APIs that can handle almost any documentation-related requirement with zero overhead. ```javascript // docmd.config.js export default { // ✅ Use a small, purpose-built script instead of a heavy library customJs: ['/static/js/my-custom-logic.js'] }; ``` ### 2. Strategic Plugin Management While [Plugins](../../plugins/usage.md) add powerful features, some can significantly increase your JavaScript payload. For example, the [Mermaid Plugin](../../plugins/mermaid.md) requires a large client-side library to render diagrams. Only enable heavy plugins if they are essential to your content, and consider their impact on overall page weight. ### 3. Defer Non-Critical Scripts If you need to include third-party services like analytics or feedback widgets, ensure they are loaded asynchronously or deferred so they don't block the rendering of your documentation. ```html <!-- In your custom head injection --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. Optimise Assets Ensure that any custom JavaScript you provide is minified and compressed. `docmd` handles the minification of its core assets, but you are responsible for the optimisation of any files you add to your `static/` directory. ## Trade-offs Building complex interactive features with Vanilla JavaScript can require more manual effort than using a declarative framework. However, for documentation - where 95% of the content is static text and images - the performance gains of a zero-framework approach far outweigh the developer convenience of a heavy framework. --- ## [Sub-100ms Navigation](https://docs.docmd.io/07/guides/performance-delivery/sub-100ms-navigation/) --- title: "Sub-100ms Navigation" description: "How docmd's native SPA router and intent-based prefetching deliver instant page transitions for an optimal reading experience." --- ## Problem Traditional multi-page navigation, where every link click triggers a full browser reload, creates a disruptive "white flash" and breaks the reader's flow. The browser must discard the current state, request new HTML, and re-parse CSS and JavaScript - even if only the central content area has changed. ## Why it matters Documentation users frequently jump between different sections, such as tutorials, API references, and conceptual guides. If every transition takes a second or more, it creates cognitive friction and discourages thorough exploration. Instant navigation makes the documentation feel like a native application, significantly improving user satisfaction and engagement. ## Approach `docmd` utilizes a high-performance **Single Page Application (SPA) Router** built on top of pre-generated static files. This allows the browser to intercept link clicks, fetch only the necessary content in the background, and update the page dynamically without a full reload. This approach preserves the state of the sidebar, table of contents, and theme settings, resulting in near-instant transitions. ## Implementation The `docmd` SPA router is enabled by default and uses several advanced techniques to achieve sub-100ms navigation speeds: ### 1. Intent-Based Prefetching When a user hovers over a navigation link, `docmd` detects the intent to navigate and initiates a background fetch for the target page's content. By the time the user actually clicks the link, the data is often already available in the browser's cache, making the transition feel instantaneous. ### 2. Partial DOM Updates Instead of re-rendering the entire page, `docmd` intelligently updates only the necessary functional zones: * **Main Content**: The primary Markdown-rendered body. * **Table of Contents**: Refreshed to match the new page's headers. * **Navigation State**: Updates the active and expanded states in the sidebar. ### 3. Lifecycle Events for Custom Logic Because the browser doesn't perform a full reload, standard events like `DOMContentLoaded` only fire once. To execute custom JavaScript after every navigation - such as re-initialising a third-party widget or tracking page views - you should listen for the `docmd:page-mounted` event. ```javascript // Example: Re-initialising a custom component after navigation document.addEventListener('docmd:page-mounted', (event) => { const currentPath = event.detail.path; console.log(`Successfully navigated to: ${currentPath}`); // Custom logic here if (currentPath.includes('/api/')) { initApiConsole(); } }); ``` For more details, see the [Client-Side Events](../../api/client-side-events.md) documentation. ## Trade-offs ### Script Execution The SPA router automatically re-executes `<script>` tags found within the Markdown body of the new page. However, global scripts defined in your theme or layout only run once during the initial load. Always use the `docmd:page-mounted` event for logic that must execute on every page. ### SEO and Accessibility Despite the SPA-like behaviour, `docmd` still generates a complete, standalone `.html` file for every page. This ensures that search engine crawlers see the full content and that the site remains functional for users with JavaScript disabled, maintaining excellent SEO and accessibility standards. --- ## [Breaking Changes & Deprecations](https://docs.docmd.io/07/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "Breaking Changes & Deprecations" description: "How to communicate API changes and migration paths effectively using versioned documentation and contextual callouts." --- ## Problem When a product introduces a major version change, certain APIs, features, or configurations are inevitably deprecated or removed. Users browsing the latest documentation must be clearly warned if they are using outdated patterns, yet the documentation should remain focused on the modern implementation to avoid confusion. ## Why it matters Failure to explicitly surface breaking changes leads to developers wasting hours debugging code that the engine no longer supports. Contextual warnings and clear migration paths are essential for maintaining user trust, reducing support requests, and ensuring a smooth transition to the latest version of your software. ## Approach Combine `docmd`'s [Versioning Engine](../../configuration/versioning.md) with [Callout Containers](../../content/containers/callouts.md) to create a clear distinction between legacy and modern content. The strategy is to move full legacy documentation to an archived version while providing "migration anchors" in the current version that link back to the archived content. ## Implementation ### 1. Archiving Legacy Content When releasing a new major version (e.g., v2.0), move your existing documentation to an archived directory (e.g., `docs-v1/`). This ensures that the full context of the previous version is preserved for users who haven't migrated yet. ### 2. Contextual Migration Callouts In your latest documentation, use `warning` or `important` callouts at the top of pages where significant changes have occurred. This provides immediate value to users who are attempting to use legacy patterns. ```markdown # Configuration API ::: callout warning "Migration: Breaking Change in v2.0" The `siteTitle` property has been removed. It has been replaced by the global `title` property. * **Migrating from v1.x?** Please update your `docmd.config.js`. * **Need latest docs?** Refer to the [Configuration Guide](../../configuration/overview.md). ::: ``` ### 3. Maintaining AI Accuracy By strictly separating deprecated content from the active version, you significantly improve the accuracy of AI tools. `docmd`'s [LLMs Plugin](../../plugins/llms.md) generates context files based on the active version. Archiving legacy content prevents AI models from "hallucinating" and recommending outdated APIs to users who are looking for modern solutions. ## Trade-offs Actively managing migration callouts adds maintenance overhead. If left indefinitely, pages can become cluttered with old warnings. We recommend a policy of removing migration callouts once the legacy version reaches its End-of-Life (EOL) or after one full major release cycle to keep the documentation lean and focused. --- ## [Multi-Team Collaboration](https://docs.docmd.io/07/guides/scaling-architecture/multi-team-collaboration/) --- title: "Multi-Team Collaboration" description: "How to use decentralized navigation and global menubars to allow multiple teams to contribute to a unified documentation project without friction." --- ## Problem When multiple independent teams (e.g., Frontend, Backend, DevOps, and Product) contribute to a single documentation repository, organizational friction often occurs. Teams may accidentally overwrite global navigation settings, create conflicting styling paradigms, or break links across domain boundaries during concurrent updates. ## Why it matters Friction in the authoring experience leads to "documentation silos," where teams create independent, isolated wikis to avoid the complexity of a shared repository. This destroys the unified user experience of a single documentation portal and makes it significantly harder for users to find comprehensive information about the entire system. ## Approach Use `docmd`'s decentralized [Navigation Resolution](../../configuration/navigation.md#navigation-resolution-priority) system. This allows individual teams to have full autonomy over their specific domains using local `navigation.json` files, while a central team governs the global [Menubar](../../configuration/menubar.md) and visual design system. ## Implementation ### 1. Domain-Based Ownership Divide your documentation into top-level directories assigned to specific teams. Each team completely owns the content and internal structure of their assigned folder. ```text my-project/ ├── docs/ │ ├── frontend/ # Owned by the UI Team │ │ ├── navigation.json # Team-specific sidebar │ │ └── components.md │ ├── backend/ # Owned by the API Team │ │ ├── navigation.json │ │ └── database.md │ └── docmd.config.js # Owned by the Platform/Core Team ``` ### 2. Global Context Switching (The Menubar) The central platform team controls the [Menubar](../../configuration/menubar.md), which serves as the primary navigation layer to switch between different team domains. ```javascript // docmd.config.js export default { menubar: { enabled: true, items: [ { text: 'Frontend', url: '/frontend/components' }, { text: 'Backend', url: '/backend/database' }, { text: 'Infrastructure', url: '/devops/setup' } ] } }; ``` ### 3. Local Autonomy with navigation.json When a user is browsing content within the `/frontend/` directory, `docmd` automatically prioritises the `frontend/navigation.json` file. The sidebar updates dynamically to reflect only the frontend-specific hierarchy, preventing the navigation from becoming cluttered with unrelated information from other teams. ```json // docs/frontend/navigation.json [ { "title": "Design System", "path": "/frontend/design-system" }, { "title": "Component Library", "path": "/frontend/components" } ] ``` ## Trade-offs Decentralized navigation requires teams to be mindful of cross-domain links. While `docmd` handles relative links effectively, moving an entire team directory will break links in other teams' files. We recommend using root-relative paths (starting with `/`) for links between different team domains to ensure stability. --- ## [Managing Multi-Version Documentation](https://docs.docmd.io/07/guides/scaling-architecture/multi-version-documentation/) --- title: "Managing Multi-Version Documentation" description: "How to maintain multiple versions of your documentation (v1, v2, legacy) with a unified switcher and path preservation." --- ## Problem As software products evolve, enterprise users often remain on older LTS (Long Term Support) versions. Dropping documentation for v1 when v2 is released leaves those users stranded, while maintaining completely separate sites for each version leads to a fragmented user experience and SEO cannibalization. ## Why it matters Without a seamless way to switch versions, developers often mistakenly apply instructions from the latest documentation to legacy environments, leading to errors and increased support overhead. A unified versioning system ensures that users always know which context they are in and can easily jump between versions of the same page. ## Approach `docmd` features a native [Versioning Engine](../../configuration/versioning.md) that treats versions as first-class citizens. It isolates builds into version-prefixed directories, provides a "Sticky Switching" mechanism that preserves the current page path, and correctly scopes search results to the active version context. ## Implementation ### 1. Organise Source Directories Keep your latest documentation in a standard directory (e.g., `docs/`) and place legacy versions in sibling directories (e.g., `docs-v1/`). ```text my-project/ ├── docs/ # v2.x (Current) ├── docs-v1/ # v1.x (Legacy LTS) └── docmd.config.js ``` ### 2. Configure the Version Map Define your version structure in `docmd.config.js`. The `current` version is served at the root URL, while others are served at `/{id}/`. ```javascript // docmd.config.js export default { versions: { current: 'v2', // Served at / position: 'sidebar-top', // Switcher location all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Latest)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x (LTS)' } ] } }; ``` ### 3. Per-Version Navigation If the navigation structure differs between versions, you can place a `navigation.json` file inside each version's source directory. `docmd` will automatically detect and use it for that specific version. ```json // docs-v1/navigation.json [ { "title": "Legacy Setup", "path": "/legacy-setup" }, { "title": "Migration to v2", "path": "/migration" } ] ``` ### 4. Path Preservation (Sticky Switching) `docmd` automatically attempts to preserve the user's current path when they switch versions. If a user is at `/api/auth` on the `v2` site and switches to `v1`, the engine will attempt to route them to `/v1/api/auth`. If the page doesn't exist in the target version, it falls back to the version's homepage. ## Trade-offs Storing multiple versions in a single repository increases the repository size over time. For very large documentation sets, consider using CI/CD to pull in legacy documentation directories dynamically during the build process instead of committing them to the main branch. --- ## [Organising Large Repositories](https://docs.docmd.io/07/guides/scaling-architecture/organising-large-repositories/) --- title: "Organising Large Repositories" description: "How to maintain navigation clarity and usability in complex documentation structures using hub pages and hierarchical navigation." --- ## Problem As a documentation repository grows to hundreds of pages, displaying every topic in a single, massive sidebar makes the site unusable. Users suffer from "choice paralysis," where finding a specific module requires scrolling through dozens of irrelevant, expanded categories. ## Why it matters Navigation is a critical component of user experience. A cluttered interface diminishes the perceived quality of your product and makes it harder for developers to find the answers they need. If the navigation feels chaotic, users often assume the software itself is equally difficult to use. ## Approach Implement a hierarchical grouping strategy using `docmd`'s [Navigation Configuration](../../configuration/navigation.md). The core principle is to hide complexity until it is needed. Use collapsible groups and "Hub Pages" to maintain a clean sidebar, ensuring that users can focus on their current task without being overwhelmed. ## Implementation ### 1. Hierarchical Grouping Use the `collapsible` property in your `navigation.json` or config file to group related pages. This keeps the sidebar clean and allows users to expand only the sections they are interested in. ```json // docs/navigation.json [ { "title": "Advanced API", "icon": "braces", "collapsible": true, "children": [ { "title": "Authentication", "path": "/api/auth" }, { "title": "Webhooks", "path": "/api/webhooks" }, { "title": "Rate Limiting", "path": "/api/rate-limiting" } ] } ] ``` ### 2. Implementing Hub Pages Instead of exposing every individual page in the sidebar, create central "Hub Pages" that act as directories for specific sub-systems. Use [Grids and Cards](../../content/containers/grids.md) to provide a visual, high-level overview of the available content. ```markdown # Integrations Hub ::: grids ::: grid ::: card "Database Integrations" icon:database Connect your application to popular databases like Postgres and MongoDB. [View Database Guides](/integrations/databases) ::: ::: ::: grid ::: card "Payment Gateways" icon:credit-card Learn how to implement Stripe, PayPal, and more. [View Payment Guides](/integrations/payments) ::: ::: ::: ``` ### 3. Using Breadcrumbs `docmd` automatically generates [Breadcrumbs](../../content/syntax/advanced.md#breadcrumbs) for every page based on your folder structure and navigation hierarchy. By using Hub Pages, you can keep the sidebar focused while breadcrumbs provide the necessary context and an easy way for users to navigate back up the hierarchy. ## Trade-offs Using Hub Pages can add an extra "click" for users to reach deep content. However, this is usually preferable to a cluttered sidebar that makes discovery difficult. The trade-off is a cleaner, more professional interface that significantly improves the overall searchability and focus of your documentation. --- ## [Scalable Folder Structure](https://docs.docmd.io/07/guides/scaling-architecture/scalable-folder-structure/) --- title: "Scalable Folder Structure" description: "How to organise large-scale documentation projects using the Diátaxis framework and docmd's resolution system." --- ## Problem Small documentation sites often start with a flat `docs/` folder. However, as the project grows to include multiple modules, tutorials, APIs, and conceptual deep-dives, a disorganised folder structure becomes a significant maintenance burden. Files become difficult to locate, and the navigation sidebar becomes an overwhelming "wall of links." ## Why it matters A disorganised folder structure directly results in a confusing user experience, as `docmd`'s routing and default navigation are derived from your file system. For authors, a lack of clear structure leads to content duplication and inconsistent naming, making the documentation harder to manage as more contributors join the project. ## Approach We recommend adopting an information architecture framework like [Diátaxis](external:https://diataxis.fr/), which separates content into four distinct categories: Tutorials, How-To Guides, Reference, and Explanation. Mapping these categories strictly to your physical file system provides a clear roadmap for both readers and authors. ## Implementation ### 1. The Diátaxis Hierarchy Organise your source directory into semantic subfolders. This physical isolation makes it easier to manage large sets of files and ensures a clean URL structure. ```text my-project/ ├── docs/ │ ├── tutorials/ (Learning-oriented: step-by-step lessons) │ │ └── getting-started.md │ ├── guides/ (Task-oriented: solving specific problems) │ │ └── deployment.md │ ├── reference/ (Information-oriented: technical descriptions) │ │ └── api-spec.md │ ├── explanation/ (Understanding-oriented: theoretical background) │ │ └── architecture.md │ └── navigation.json (Main navigation definition) └── docmd.config.js ``` ### 2. Strategic Use of navigation.json Instead of defining a massive navigation tree in your global configuration, use `navigation.json` files within your source directories. `docmd` follows a [Resolution Priority](../../configuration/navigation#navigation-resolution-priority) system, allowing you to define distinct sidebar hierarchies for different sections of your site. ```json // docs/navigation.json [ { "title": "Tutorials", "icon": "book-open", "children": [ { "title": "Get Started", "path": "/tutorials/getting-started" } ] }, { "title": "Reference", "icon": "braces", "children": [ { "title": "API Specification", "path": "/reference/api-spec" } ] } ] ``` ### 3. File-Based Routing Remember that every Markdown file's location in the folder structure determines its final URL. For example, `docs/guides/auth.md` becomes `your-site.com/guides/auth`. Use this to your advantage to create intuitive, memorable URLs for your users. ## Trade-offs Strict organizational frameworks like Diátaxis require a clear understanding of content types. Technical writers may occasionally find it difficult to categorise a specific document (e.g., "Is this a guide or a tutorial?"). Establishing clear internal contribution guidelines is essential to maintain consistency as your team and documentation grow. --- ## [Scaling to 1000+ Pages](https://docs.docmd.io/07/guides/scaling-architecture/scaling/) --- title: "Scaling to 1000+ Pages" description: "How to maintain high performance and usability in massive documentation projects with docmd." --- ## Problem As a software product matures, its documentation naturally expands. When a project grows to hundreds or thousands of Markdown files, many documentation generators suffer from sluggish build times, slow development server hot-reloading, and navigation structures that overwhelm both maintainers and users. ## Why it matters If documentation generation takes minutes instead of seconds, authors are discouraged from making small corrections, leading to stale and inaccurate content. For users, a massive, unorganised sidebar menu makes finding information frustrating, leading to increased support tickets and a poor developer experience. ## Approach `docmd` is architected for speed and scalability. By utilising a high-performance parsing engine and a granular file-based build strategy, it can process thousands of pages in seconds. Its optimised SPA (Single Page Application) delivery ensures that navigating through a large site remains instantaneous for the end user. ## Implementation ### 1. Granular Project Structure Avoid placing all files in a single flat directory. Use a deeply nested folder structure that mirrors your product's architecture. This makes the project easier to maintain and allows `docmd` to efficiently track changes during development. ### 2. Optimised Search Indexing For large sites, the [Search Plugin](../../plugins/search) is essential. `docmd` generates a highly compressed search index that is loaded on demand. This ensures that even with thousands of pages, the initial page load remains fast while providing full-text search capabilities across the entire site. ### 3. Versioning and Archiving Use the [Versioning Engine](../../configuration/versioning) to separate legacy content from active documentation. By isolating older versions into their own build contexts, you reduce the number of pages that need to be re-processed during daily updates, significantly improving development velocity. ```javascript // docmd.config.js export default { versions: { current: 'v3', all: [ { id: 'v3', dir: 'docs/current', label: 'v3.x (Latest)' }, { id: 'v2', dir: 'docs/v2', label: 'v2.x (Legacy)' } ] } }; ``` ### 4. Component-Based Navigation Break down your navigation into logical segments using `navigation.json` files. This allows you to define distinct sidebar hierarchies for different sections of your site, preventing the main navigation from becoming cluttered. ## Trade-offs A large site naturally consumes more disk space and memory during the build process. To maintain sub-second build times at extreme scales (10,000+ pages), consider using a high-performance CI/CD environment with SSD storage and ample RAM to handle the parallel processing of files. --- ## [Fast & Accurate Search](https://docs.docmd.io/07/guides/search/fast-accurate-search/) --- title: "Fast & Accurate Search" description: "How docmd optimises search indexing for speed and accuracy, even in large-scale documentation projects." --- ## Problem As documentation grows to hundreds or thousands of pages, the compiled search index can become quite large. A monolithic index file can block the browser's main thread during download and parsing, delaying the "Time to Interactive" and causing the search interface to feel sluggish or unresponsive. ## Why it matters The primary goal of documentation search is "Time to Answer." If a user triggers the search modal and has to wait several seconds for the index to load, the utility of the search tool is lost. Fast, accurate search results are essential for providing a professional developer experience and helping users find information without friction. ## Approach `docmd` utilizes an optimised indexing strategy powered by a high-performance search library. It employs **Scoping**, **Incremental Loading**, and **Field Optimisation** to ensure that search results are delivered almost instantaneously, regardless of the size of the documentation site. ## Implementation ### 1. Scoped Search Indices `docmd` automatically generates separate search indices for every [Locale](../../configuration/localisation/index.md) and [Version](../../configuration/versioning.md). This ensures that a user only downloads the index relevant to their current context. For example, a user browsing the Chinese version of your documentation only downloads the Chinese search index, significantly reducing the payload size. ### 2. Intelligent Field Stripping The [Search Plugin](../../plugins/search.md) allows you to control exactly what content is indexed. By default, it prioritises headers and frontmatter metadata while stripping out common "stop words" and unnecessary code symbols that bloat the index without adding value. You can also exclude specific pages from the index using the `search` property in your [Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Internal Developer Guide" search: false # This page will not appear in search results --- ``` ### 3. Lazy Loading & Prefetching To keep the initial page load fast, `docmd` does not load the search index immediately. Instead, it is fetched lazily in the background or triggered the moment a user interacts with the search UI (e.g., by clicking the search bar or using the `Cmd+K` / `Ctrl+K` shortcut). ### 4. Result Ranking Results are ranked based on a weighted scoring system. Keywords found in the page `title` or `h1` headers are weighted significantly higher than those found in the body text. This ensures that the most relevant pages appear at the top of the results list. ## Trade-offs Excluding utility or internal pages from the search index makes them harder to discover. You should use the `search: false` property sparingly to ensure that valuable information remains findable. While lazy loading improves initial performance, users on extremely slow connections may experience a brief delay the first time they trigger a search. --- ## [Search Relevance & Structure](https://docs.docmd.io/07/guides/search/improving-search-relevance/) --- title: "Search Relevance & Structure" description: "How to structure your Markdown content to improve search relevance and help users find information faster." --- ## Problem Search engines prioritise content based on structure. If a high-quality guide uses generic headers like "Introduction" or "Step 1," the search engine may not assign enough weight to the core keywords buried within the paragraphs. This results in relevant pages being buried deep in search results, frustrating users who expect instant answers. ## Why it matters Users typically search for specific technical terms (e.g., "authentication token" or "deployment limit") rather than full sentences. If your documentation structure doesn't emphasise these terms, the search engine cannot confidently rank your content. High search relevance is the difference between a self-service documentation portal and a high volume of support tickets. ## Approach Structure your Markdown so the search indexer can automatically identify and prioritise core concepts. `docmd`'s search engine assigns higher weights to the page `title`, `description`, and `headers` compared to the body text. By optimising these structural elements, you significantly improve the discoverability of your content. ## Implementation ### 1. Optimise Frontmatter Metadata Use the [Frontmatter](../../content/frontmatter.md) block to provide explicit keywords and a descriptive summary. The [Search Plugin](../../plugins/search.md) indexes these fields to provide better results and more useful snippets in the search UI. ```yaml --- title: "AWS S3 Storage Configuration" description: "How to configure IAM roles and bucket permissions for AWS S3 integration." keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. Use Semantic Headers Avoid generic header names. Instead, include relevant keywords in your headers to provide context for both the user and the search engine. * **Low Relevance:** `## Step 1: Configuration` * **High Relevance:** `## Step 1: Configuring AWS IAM Roles` ### 3. Use Callouts for Key Information Using [Callout Containers](../../content/containers/callouts.md) for critical warnings or "Pro Tips" can also help search relevance. Content within callouts is often semantically isolated and can be weighted differently by the indexer to highlight important troubleshooting steps. ## Trade-offs Optimising for search relevance requires disciplined writing. As your product evolves, keywords in frontmatter can become outdated if not regularly reviewed. In addition, including too many keywords in headers (keyword stuffing) can make the documentation feel repetitive and less natural to read. Aim for a balance between SEO and readability. --- ## [Local-First Search Optimisation](https://docs.docmd.io/07/guides/search/local-first-search/) --- title: "Local-First Search Optimisation" description: "How to optimise your documentation content for docmd's high-performance, client-side search engine." --- ## Problem Local-first search engines run entirely in the browser, providing instant results without a server round-trip. However, this means they are constrained by the browser's memory and processing limits. If a search index is not properly optimised, it can consume excessive RAM, causing the browser tab to stutter or even crash, especially on mobile devices. ## Why it matters A seamless search experience is essential for developer productivity. If the search tool causes performance issues or consumes too much memory, users will avoid using it. Optimising your content for local-first search ensures that your documentation remains fast, responsive, and reliable across all devices and network conditions. ## Approach `docmd`'s [Search Plugin](../../plugins/search.md) uses a build-time extraction pipeline to create a highly optimised index. By pruning unnecessary data and focusing on high-value semantic fields, it ensures that the resulting index is both comprehensive and lightweight. ## Implementation ### 1. Build-Time Extraction During the build process, `docmd` processes your Markdown files to extract only the most relevant text for indexing. It automatically strips out: * HTML tags and structural boilerplate. * Markdown syntax characters that don't add semantic value. * Formatting-only elements that would otherwise bloat the index. This ensures that the indexer only receives clean, meaningful text, which significantly reduces the final index size. ### 2. Strategic Indexing with Frontmatter You can use [Frontmatter](../../content/frontmatter.md) to explicitly control how a page is indexed. For example, if a page contains large amounts of repetitive data (like raw JSON logs) that aren't useful for search, you can choose to index only the headers and metadata. ```yaml --- title: "API Log Reference" search: indexBody: false # Only index the title and headers --- ``` ### 3. Client-Side Memory Management `docmd` manages the search index lifecycle carefully in the browser. It uses an on-demand loading strategy, meaning the search engine is only initialised when the user first interacts with it. This keeps the initial page load footprint small and ensures that system resources are only used when needed. ## Trade-offs Aggressively pruning content from the search index (e.g., excluding large code blocks) can sometimes result in missing niche results. You must balance the need for a lightweight, fast index with the requirement for thorough search coverage. We recommend prioritising headers and conceptual descriptions, as these are the most common search targets for developers. --- ## [Git-Based Workflows](https://docs.docmd.io/07/guides/workflows-teams/git-based-workflows/) --- title: "Git-Based Workflows" description: "How to manage documentation contributions effectively using Git, Pull Requests, and automated CI/CD checks." --- ## Problem Allowing direct pushes to the main documentation branch often leads to broken links, inconsistent formatting, and unverified technical information. However, imposing too much friction - such as requiring separate CMS accounts - discourages community members and internal developers from contributing valuable updates. ## Why it matters Collaboration is the lifeblood of great documentation. If a developer finds a typo or an outdated example, they should be able to submit a fix in minutes. A Git-based workflow provides a familiar, transparent, and secure environment for contributions, ensuring that every change is reviewed and validated before it goes live. ## Approach Implement a "Pull Request" (PR) model supported by automated validation and preview environments. `docmd` is designed for this workflow, as it operates on standard Markdown files that are easy to diff, review, and merge using familiar Git tools. ## Implementation ### 1. Enable "Edit this Page" Links You can configure `docmd` to automatically generate "Edit this page" links in the footer or sidebar. This allows users to jump directly from a documentation page to the corresponding source file in your repository. ```javascript // docmd.config.js export default { editLink: { enabled: true, baseUrl: 'https://github.com/my-org/my-docs/edit/main/docs', text: 'Suggest an edit' } }; ``` For more details, see the [Edit Link Configuration](../../configuration/overview.md#editlink). ### 2. Contextual Reviews with Threads For complex updates that require detailed feedback, use the [Threads Plugin](../../plugins/usage.md). This allows authors and reviewers to leave inline comments directly within the Markdown content during the review phase, keeping discussions contextualised. ```markdown ::: thread "Reviewer Name" Should we include a code example for the new authentication flow here? ::: ``` ### 3. Automated Validation in CI Integrate `docmd` into your CI/CD pipeline (e.g., [GitHub Actions](../../guides/integrations/github-actions-cicd.md)) to validate every PR. At a minimum, your pipeline should run the build command to ensure no syntax errors or broken configurations are introduced. ```bash # In your CI pipeline npm install npx @docmd/core build ``` ## Trade-offs Strict Git workflows can occasionally slow down minor updates, such as fixing a critical typo or updating a service status notice. For high-velocity teams, we recommend designating "Documentation Owners" who have the authority to fast-track small changes while maintaining rigorous review standards for significant technical updates. --- ## [Maintaining Consistency](https://docs.docmd.io/07/guides/workflows-teams/maintaining-consistency/) --- title: "Maintaining Consistency" description: "How to ensure a unified voice and professional quality across large documentation teams using linting and standardised patterns." --- ## Problem In large teams, every technical writer has a different style and preference. Some might use bold text for emphasis, while others use italics. Some may prefer "Click the button," while others use "Select the option." Over time, your documentation can become a "patchwork quilt" of conflicting styles, making it harder for users to parse information quickly and reducing the professional trust of your product. ## Why it matters Consistency breeds familiarity. When users are learning complex APIs or workflows, they rely on consistent vocabulary and structural patterns to navigate the content effectively. A unified voice makes your documentation feel like a cohesive, high-quality product, which in turn builds confidence in the software itself. ## Approach Enforce consistency mechanically using [Standardised Containers](../../content/containers/index.md) and automated linting tools. By automating low-level style and syntax checks, you free up your human editors to focus on the high-level quality, accuracy, and clarity of the content. ## Implementation ### 1. Use Standardised docmd Patterns Encourage all contributors to use `docmd`'s built-in thematic containers instead of improvising with manual Markdown formatting. This ensures that every warning, tip, or note looks and behaves identically across the entire site. ```markdown <!-- ❌ Avoid: inconsistent and unstyled --> **Note:** Please restart the service. <!-- ✅ Use: consistent, accessible, and thematic --> ::: callout info Please restart the service. ::: ``` Using [Callouts](../../content/containers/callouts.md) ensures that your documentation maintains a professional appearance and meets accessibility standards without extra effort from the writer. ### 2. Implement Prose Linting Integrate tools like **Vale** or **Markdownlint** to enforce brand terminology, tone, and grammar. These tools can be configured to check for passive voice, biased language, or incorrect product spelling automatically. ```ini # .vale.ini example MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. Automated Enforcement in CI/CD Include consistency checks in your [GitHub Actions](../../guides/integrations/github-actions-cicd.md) or other CI/CD pipelines. This ensures that every Pull Request is automatically audited for style and structural consistency before it can be merged. ```bash # Example CI step for linting - name: Lint Documentation run: vale docs/ ``` ## Trade-offs Strict linting can sometimes discourage community contributors if they are met with multiple "style errors" for a simple typo fix. We recommend setting your linter's sensitivity to `warning` for external contributions and reserving `error` status for internal team updates to balance consistency with inclusivity. --- ## [Previewing Changes](https://docs.docmd.io/07/guides/workflows-teams/previewing-changes/) --- title: "Previewing Changes" description: "How to set up local and cloud-based preview environments to ensure your documentation renders perfectly before it goes live." --- ## Problem Writing Markdown without a live preview often leads to formatting errors, broken containers, and incorrect image paths that only become visible once the content is in production. This results in a frustrating experience for users and extra work for maintainers who must constantly push hotfixes for simple rendering issues. ## Why it matters High-quality documentation is essential for developer trust. A broken warning box or unrendered syntax looks unprofessional and can even mislead users about how your software works. Seeing the "real" documentation before it goes live is the most effective way to catch errors, improve readability, and ensure a seamless user experience. ## Approach Implement a multi-stage preview strategy: use `docmd`'s [Local Development](../../getting-started/quick-start.md#local-development) server for immediate feedback while writing, and use ephemeral cloud environments (like Vercel or Cloudflare Pages) for final reviews within your Pull Requests. ## Implementation ### 1. Instant Local Previews The fastest way to see your changes is by running the `docmd dev` server. It features Hot Module Replacement (HMR), which automatically refreshes your browser the moment you save a Markdown file. ```bash # Start the local development server npx @docmd/core dev ``` ### 2. Cloud-Based Preview Environments For collaborative reviews, configure your CI/CD platform to generate unique "Preview URLs" for every Pull Request. Since `docmd` outputs standard static files, it is compatible with all major hosting providers. * **Build Command**: `npx @docmd/core build` * **Output Directory**: `site` This allows reviewers to see exactly how the changes will look and behave in a production-like environment before they are merged into the main branch. ### 3. Collaborative Reviews with Threads Combine your cloud previews with the [Threads Plugin](../../plugins/usage.md). This allows team members to leave feedback directly on the rendered preview page, bridging the gap between the source Markdown and the final user experience. ## Trade-offs Building a full static site for every commit in a massive repository (thousands of pages) can be time-consuming and costly in terms of CI/CD resources. To optimise this, configure your CI pipeline to only trigger a documentation build when files within your source directory (e.g., `/docs`) have been modified. --- ## [Setting Up a Workflow](https://docs.docmd.io/07/guides/workflows-teams/setting-up-workflow/) --- title: "Setting Up a Workflow" description: "How to establish a high-velocity, multi-author documentation workflow using docmd and docs-as-code principles." --- ## Problem When teams lack a structured documentation workflow, updates are often delayed, forgotten, or shared as ad-hoc messages. Without a clear process, content becomes fragmented, formatting becomes inconsistent, and technical writers spend more time resolving merge conflicts than writing high-quality content. ## Why it matters Without a formal process, documentation quickly becomes outdated and loses its value. If updating documentation requires waiting on a slow software release cycle, your guides will perpetually remain out of sync with your actual product features, leading to user frustration and increased support volume. ## Approach Decouple documentation deployments from software release cycles while adopting the same reliable processes used in software engineering (Branches → Pull Requests → CI/CD Previews). `docmd`'s lightweight nature allows teams to treat "documentation as code" with minimal overhead, ensuring that your guides are as reliable and up-to-date as your software. ## Implementation ### 1. Repository Strategy Choose the strategy that best fits your organizational structure: * **Monorepo Strategy**: Keep a `/docs` folder within your main application repository. This is ideal for ensuring that documentation changes are merged in the same Pull Request as the code they describe, maintaining perfect synchronisation. * **Separate Repository Strategy**: Best for large organisations or open-source projects where a dedicated team manages the documentation independently of the main application's build pipeline. ### 2. Validation with CI/CD Integrate `docmd` into your CI/CD pipeline to ensure that every update is technically sound. At a minimum, your pipeline should run the build command to check for syntax errors and configuration issues. ```bash # Example validation step in GitHub Actions - name: Validate Documentation run: npm install && npx @docmd/core build ``` See the [GitHub Actions Guide](../../guides/integrations/github-actions-cicd.md) for detailed setup instructions. ### 3. Collaborative Review Process Establish a culture of peer review for all documentation updates. Use Pull Requests to discuss changes, verify formatting, and ensure technical accuracy. You can use the [Threads Plugin](../../plugins/usage.md) to facilitate detailed discussions directly on the rendered content. ## Trade-offs Adopting a "docs-as-code" workflow can create a barrier for non-technical contributors (e.g., Product Managers or Legal teams) who may find Git and Markdown intimidating. To mitigate this, consider using GitHub's built-in web editor for minor fixes or using the [Live Preview](../../content/live-preview.md) feature to provide a more visual and intuitive authoring experience. --- ## [Versioning Workflows](https://docs.docmd.io/07/guides/workflows-teams/versioning-release-workflows/) --- title: "Versioning Workflows" description: "How to synchronise documentation releases with software deployment using docmd's versioning engine and promotion strategies." --- ## Problem Synchronising software releases with corresponding documentation updates is a significant coordination challenge. Frequently, documentation is updated on the live site before the new code is deployed (confusing current users) or delayed several days after the release (frustrating early adopters). ## Why it matters Desynchronisation between software behaviour and its documentation is a major source of developer friction. For documentation to be effective, it must strictly map to the specific version of the software the user is currently running. Providing the correct context for every version ensures a smooth onboarding and troubleshooting experience. ## Approach Isolate active development documentation using `docmd`'s [Versioning Engine](../../configuration/versioning.md). This allows your team to draft content for upcoming features asynchronously in a separate directory (e.g., `docs-next/`), promoting it to the "Stable" or "Current" status only when the official software release occurs. ## Implementation ### 1. Structure Your Directories Maintain your stable documentation in the primary `docs/` folder and create a dedicated directory for the upcoming release. ```text project-root/ ├── docs/ # Current Stable (v1.x) ├── docs-v2/ # Upcoming Release (v2.0) └── docmd.config.js ``` ### 2. Configure Versions Register both versions in your configuration. You can label the upcoming version as "Beta" or "Next" to signal its status to users through the version switcher. ```javascript // docmd.config.js export default { versions: { current: 'v1.0', all: [ { id: 'v1.0', dir: 'docs', label: 'v1.x (Stable)' }, { id: 'v2.0', dir: 'docs-v2', label: 'v2.0 (Beta)' } ] } }; ``` ### 3. The Promotion Process When you are ready to release the new version officially: 1. **Update Config**: Change the `current` version ID in `docmd.config.js` to `v2.0`. 2. **Update Labels**: Remove the "(Beta)" tag from the `label` in the `all` array. 3. **Archive Old Docs**: Keep the `v1.0` entry in the `all` array so users on older versions can still access their relevant documentation. ## Trade-offs ### Maintenance Overhead Maintaining multiple versions of documentation requires discipline. If a critical typo or security warning is fixed in the stable version, ensure it is also applied to the upcoming version directory to prevent "regressions" in clarity. ### SEO and Search Multiple versions can occasionally lead to search results pointing to older documentation. Use the `seo` plugin and proper canonical tags to ensure that the "Current" version is always prioritised by search engines. See [Handling Breaking Changes](../scaling-architecture/breaking-changes-deprecations.md) for more on managing transitions. --- ## [docmd docs: deploy production-ready docs from Markdown](https://docs.docmd.io/07/) --- title: "docmd docs: deploy production-ready docs from Markdown" description: "Build production-ready documentation from Markdown in seconds. Zero setup, fast by default, SEO-friendly, and AI-ready." titleAppend: false --- ::: hero # docmd Markdown to production docs in one command. Static HTML for SEO. SPA for speed. AI-ready by default. ::: button "Get Started" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#333 icon:github ::: ## Start Get a production documentation site running in seconds - no boilerplate, no config files. ```bash npx @docmd/core dev ``` That's it. Write Markdown in a `docs/` folder and docmd builds a full documentation site with navigation, search, SEO, sitemap, and more - all out of the box. ## Core Capabilities Everything you need ships built-in. No plugins to install for the essentials. ::: grids ::: grid ::: card "Instant Setup" icon:rocket One command to go from Markdown files to a production documentation site. No config files required. ::: ::: ::: grid ::: card "AI Optimised" icon:brain-circuit Auto-generates `llms.txt` and `llms-full.txt` for LLM consumption. Your docs are AI-ready by default. ::: ::: ::: grid ::: card "Built-in Search" icon:search Client-side full-text search powered by MiniSearch. Works across versions and locales with zero setup. ::: ::: ::: grid ::: card "Live Previews" icon:monitor Embed docmd live, editable code sandboxes directly in your documentation pages. ::: ::: ::: grid ::: card "Theming Engine" icon:palette Switch between built-in themes or create your own. Supports light, dark, and system-preference modes. ::: ::: ::: grid ::: card "Native i18n" icon:globe First-class multi-language support with locale-first URLs, per-locale search, and translated UI strings. ::: ::: ::: ## Extending Markdown Go beyond static text. docmd provides rich container syntax directly in Markdown - callouts, tabs, cards, grids, hero sections, collapsible sections, and more. ::: button "Explore Containers" ./content/containers/index.md icon:blocks ::: grids ::: grid ::: card "Interactive Sandboxes" Embed live, editable preview windows naturally into your pages using the [Live Preview](./content/live-preview.md) API. ::: ::: ::: grid ::: card "Inline Collaboration" Select text in dev mode to open [Threads](./plugins/threads.md) and leave comments alongside your documentation team. ::: ::: ::: --- ## [Migrating from Docusaurus](https://docs.docmd.io/07/migration/docusaurus/) --- title: "Migrating from Docusaurus" description: "A comprehensive guide on moving your Docusaurus v2/v3 project to docmd." --- # Migrating from Docusaurus to docmd Docusaurus is a popular documentation framework built on React. `docmd` provides a fast, zero-config alternative that compiles significantly faster and doesn't require React components to render rich features. ## Step 1: Run the Migration Engine Run the following command at the root of your existing Docusaurus project (where your `docusaurus.config.js` or `docusaurus.config.ts` is located): ```bash npx @docmd/core migrate --docusaurus ``` ### What Happens Automatically 1. **Backup**: Your entire project (excluding `node_modules` and `.git`) is safely moved into a new `docusaurus-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for `docmd` to use. 3. **Config Generation**: A `docmd.config.js` is generated, extracting your site `title` from your Docusaurus configuration. ## Step 2: Test the Setup Once the command finishes, you can immediately preview your Markdown content in `docmd`: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration Docusaurus has complex programmatic configurations that `docmd` does not try to guess. You will need to map these manually. ### 1. Navigation Setup Docusaurus sidebars are often auto-generated or configured in `sidebars.js`. **Action required:** Create a `navigation.json` inside your new `docs/` directory to structure your `docmd` sidebar. See the [Navigation Guide](../configuration/navigation.md). ### 2. Replacing MDX Components Docusaurus relies heavily on MDX (`.mdx`) to render custom React components (like Tabs, Admonitions, or custom UI elements). `docmd` is purely Markdown-driven and does not use React. **Action required:** You must convert any custom `<MyReactComponent />` tags into standard Markdown or use `docmd`'s native [Containers](../content/containers/callouts.md). #### Example: Converting Admonitions **Docusaurus:** ```markdown :::tip My Tip This is a helpful tip. ::: ``` ::: callout success "Zero Changes Required" As of `docmd` 0.7.8, Docusaurus admonition syntax works **without any modification**. The following aliases are fully supported: - `:::note` → renders as `callout info` - `:::tip` → renders as `callout tip` - `:::info` → renders as `callout info` - `:::caution` → renders as `callout warning` - `:::danger` → renders as `callout danger` Spaceless syntax is also supported. Your existing Docusaurus admonitions will render correctly in `docmd` without changes. ::: **docmd native syntax** (optional, provides more features like custom icons): ```markdown ::: callout tip "My Tip" This is a helpful tip. ::: ``` #### Example: Converting Tabs **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> This is an apple. </TabItem> <TabItem value="orange" label="Orange"> This is an orange. </TabItem> </Tabs> ``` **docmd:** (Convert to the native `docmd` tabs container syntax) ```markdown ::: tabs == tab "Apple" This is an apple. == tab "Orange" This is an orange. ::: ``` ### 3. Localisation (i18n) If you used Docusaurus's `i18n` features, your translated files were likely in `i18n/locale/docusaurus-plugin-content-docs/current/`. **Action required:** Move these files into `docmd`'s directory structure (`docs/en/`, `docs/es/`, etc.) and configure the locales in `docmd.config.js`. See the [Localisation Guide](../configuration/localisation/index.md). ## Next Steps - Explore the [Layout & UI](../configuration/layout-ui.md) settings to match your Docusaurus theme. - Convert React-based hero headers into `docmd` [Hero Containers](../content/containers/hero.md). --- ## [Migrating from MkDocs](https://docs.docmd.io/07/migration/mkdocs/) --- title: "Migrating from MkDocs" description: "A comprehensive guide on moving your MkDocs (or Material for MkDocs) project to docmd." --- # Migrating from MkDocs to docmd MkDocs, particularly with the Material theme, is a popular Python-based documentation generator. `docmd` provides a similar Markdown-first experience, but relies on Node.js/Bun for incredibly fast builds and rich interactive features without the need for complex Python extensions. ## Step 1: Run the Migration Engine Run the following command at the root of your existing MkDocs project (where your `mkdocs.yml` is located): ```bash npx @docmd/core migrate --mkdocs ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `mkdocs-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for `docmd` to use. 3. **Config Generation**: A `docmd.config.js` is generated, extracting your site `site_name` from your `mkdocs.yml`. ## Step 2: Test the Setup Once the command finishes, preview your content in `docmd`: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration MkDocs uses `mkdocs.yml` to define site navigation and extensions. You'll need to translate this setup to `docmd`. ### 1. Navigation Setup In MkDocs, navigation is strictly defined in the `nav` key of `mkdocs.yml`. **Action required:** You must create a `navigation.json` inside your `docs/` folder. **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "Home", "path": "/" }, { "title": "Guide", "collapsible": true, "children": [ { "title": "Setup", "path": "/setup" }, { "title": "Usage", "path": "/usage" } ] } ] ``` ### 2. Replacing Python Markdown Extensions If you used "Material for MkDocs", you likely relied on Python Markdown extensions like PyMdown Extensions for tabs, admonitions, or task lists. **Action required:** Convert MkDocs-specific extension syntax to `docmd`'s native [Containers](../content/containers/callouts.md). #### Example: Converting Admonitions **MkDocs (PyMdown):** ```markdown !!! note "Optional Title" This is an admonition content block. ``` ::: callout warning "Manual Conversion Required" MkDocs uses `!!!` syntax for admonitions, which differs from the `:::` syntax used by `docmd`, VitePress, and Docusaurus. You will need to convert these manually or use a find-and-replace tool. **Mapping:** - `!!! note` → `::: callout info` or `:::note` - `!!! tip` → `::: callout tip` or `:::tip` - `!!! warning` → `::: callout warning` or `:::warning` - `!!! danger` → `::: callout danger` or `:::danger` - `!!! example` → `::: callout info` ::: **docmd:** ```markdown ::: callout info "Optional Title" This is an admonition content block. ::: ``` #### Example: Converting Tabs **MkDocs (SuperFences):** ```markdown === "Tab 1" Content for tab 1. === "Tab 2" Content for tab 2. ``` **docmd:** ```markdown ::: tabs == tab "Tab 1" Content for tab 1. == tab "Tab 2" Content for tab 2. ::: ``` ## Next Steps - `docmd` has native search. You do not need to configure a search plugin. - Explore the [Theming options](../theming/customisation.md) to customise your site's colours to match your old Material theme. --- ## [Migration Overview](https://docs.docmd.io/07/migration/overview/) --- title: "Migration Overview" description: "Learn how to easily migrate your existing documentation to docmd." --- # Migrating to docmd `docmd` provides a fully automated **migration engine** to help you transition from legacy or competing documentation platforms with a single command. The goal of the migration engine is to eliminate the tedious work of moving your markdown files and restructuring your project directory. ## How It Works The migration command will: 1. **Detect** your existing configuration file (e.g. `docusaurus.config.js`, `mkdocs.yml`). 2. **Extract** core metadata like your site's `title`. 3. **Backup** your existing files and directories safely into a `*-backup/` directory (e.g., `docusaurus-backup/`). 4. **Copy** your Markdown content into the standard `docmd` `docs/` directory. 5. **Generate** a fresh `docmd.config.js` tailored for your content. You can then run `npx @docmd/core dev` immediately to see your content rendered in the `docmd` engine. ## What is Migrated | Feature | Migrated Automatically? | | :--- | :--- | | **Markdown Files** | ✅ Yes, all `.md` and `.mdx` files are moved to `docs/` | | **Directory Structure** | ✅ Yes, your folder nesting is preserved | | **Site Title** | ✅ Yes, extracted from your config | | **Container Syntax** | ✅ Yes, VitePress/Docusaurus containers work without changes | | **Navigation / Sidebar** | ⚠️ **No**, requires manual mapping | | **Localisation (i18n)** | ⚠️ **No**, requires manual mapping | | **Versioning** | ⚠️ **No**, requires manual mapping | | **Custom React/Vue Components** | ❌ No, these must be replaced with `docmd` Containers | ::: callout success "Container Syntax Compatibility" As of `docmd` 0.7.8, container syntax from **VitePress** (`:::tip`, `:::warning`, `:::danger`, `:::info`, `:::details`) and **Docusaurus** (`:::note`, `:::caution`) works without modification. Your existing admonitions and collapsible sections will render correctly in `docmd`. **MkDocs** uses `!!!` syntax which requires manual conversion to `:::` format. ::: ## Why Navigation and i18n Aren't Automatically Migrated Every documentation platform handles navigation sidebars, translations, and multi-versioning differently. For example, Docusaurus uses complex JavaScript objects or autogenerated sidebars, while MkDocs relies on strictly indented YAML structures. Rather than risking an incorrect, broken migration by guessing complex configurations, `docmd` moves your content safely and asks you to configure navigation, localisation, and versioning natively using `docmd`'s simple JSON-based APIs. - **Navigation:** Learn how to create a `navigation.json` in the [Navigation Setup](../configuration/navigation.md). - **Localisation:** See the [Localisation Guide](../configuration/localisation/index.md) for setting up multi-language docs. - **Versioning:** Refer to the [Versioning Setup](../configuration/versioning.md). ## Supported Platforms Select your current platform for specific migration instructions: - [Migrating from Docusaurus](./docusaurus.md) - [Migrating from MkDocs](./mkdocs.md) - [Migrating from VitePress](./vitepress.md) - [Migrating from Astro Starlight](./starlight.md) --- ## [Migrating from Astro Starlight](https://docs.docmd.io/07/migration/starlight/) --- title: "Migrating from Astro Starlight" description: "A comprehensive guide on moving your Astro Starlight project to docmd." --- # Migrating from Astro Starlight to docmd Starlight is an excellent documentation theme built on the Astro framework. `docmd` provides a similar zero-JavaScript-by-default experience, but eliminates the need to configure a full web framework (Astro), dramatically reducing the learning curve for technical writers. ## Step 1: Run the Migration Engine Run the following command at the root of your existing Starlight project (where your `astro.config.mjs` is located): ```bash npx @docmd/core migrate --starlight ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `starlight-backup/` directory. 2. **Content Migration**: Starlight keeps documentation in `src/content/docs/`. The migration engine automatically extracts this specific directory and moves its contents to the root `docs/` folder for `docmd` to use. 3. **Config Generation**: A `docmd.config.js` is generated, extracting your site `title` from the Starlight integration inside `astro.config.mjs`. ## Step 2: Test the Setup Once the command finishes, preview your content in `docmd`: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration ### 1. Navigation Setup Starlight defines navigation in `astro.config.mjs` via the `sidebar` array. **Action required:** You must create a `navigation.json` inside your new `docs/` folder. **Starlight (`astro.config.mjs`):** ```js sidebar: [ { label: 'Guides', items: [ { label: 'Setup', link: '/guides/setup/' } ], }, ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. Replacing Astro Components (MDX/Markdoc) Starlight uses Astro components (`<Tabs>`, `<Card>`, etc.) embedded via MDX or Markdoc. Because `docmd` relies on pure Markdown syntax instead of UI components, these must be converted. **Action required:** Replace Astro components with `docmd` [Containers](../content/containers/callouts.md). #### Example: Converting Tabs **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### Example: Converting Asides (Admonitions) **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter Mapping Starlight has strict frontmatter typing via Astro content collections. `docmd` frontmatter is simpler. If you used `hero` or `banner` frontmatter properties in Starlight for landing pages, you will need to replace them with `docmd`'s [Hero Sections](../content/containers/hero.md) written directly in the Markdown body. ## Next Steps - Explore `docmd`'s built-in [Search plugin](../plugins/search.md) (Starlight uses Pagefind, while `docmd` ships with a highly optimised local search indexer natively). --- ## [Migrating from VitePress](https://docs.docmd.io/07/migration/vitepress/) --- title: "Migrating from VitePress" description: "A comprehensive guide on moving your VitePress project to docmd." --- # Migrating from VitePress to docmd VitePress is a fast Vue-powered SSG framework. Like VitePress, `docmd` is exceptionally fast, but it achieves this by shipping absolutely zero JavaScript framework logic to the client (no Vue hydration overhead). ## Step 1: Run the Migration Engine Run the following command at the root of your existing VitePress project: ```bash npx @docmd/core migrate --vitepress ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `vitepress-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for `docmd` to use. The `.vitepress` hidden configuration folder is completely stripped from the new `docs/` directory to prevent conflicts. 3. **Config Generation**: A `docmd.config.js` is generated, extracting your site `title` from your `.vitepress/config.js` or `.ts`. ## Step 2: Test the Setup Once the command finishes, preview your content in `docmd`: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration VitePress configures navigation in its config file and uses Vue components inside Markdown. You will need to translate these to `docmd`. ### 1. Navigation Setup VitePress uses an array of objects in `themeConfig.sidebar`. **Action required:** Create a `navigation.json` inside your `docs/` directory. **VitePress (`.vitepress/config.js`):** ```js themeConfig: { sidebar: [ { text: 'Guide', items: [ { text: 'Introduction', link: '/introduction' }, { text: 'Getting Started', link: '/getting-started' } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. Replacing Vue Components VitePress allows authors to embed Vue components directly in Markdown files (e.g., `<MyComponent />`). Because `docmd` does not run Vue on the client, you must remove these custom components or replace them with native Markdown. **Action required:** Replace Vue-specific UI components with `docmd` [Containers](../content/containers/callouts.md). #### Example: Admonitions (Custom Containers) VitePress uses a markdown-it custom block syntax that looks very similar to `docmd`. **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` ::: callout success "Zero Changes Required" As of `docmd` 0.7.8, VitePress container syntax works **without any modification**. The following aliases are fully supported: - `:::tip` → renders as `callout tip` - `:::warning` → renders as `callout warning` - `:::danger` → renders as `callout danger` - `:::info` → renders as `callout info` - `:::details` → renders as `collapsible` Spaceless syntax (e.g., `:::tip` instead of `::: tip`) is also supported. Your existing VitePress content will render correctly in `docmd` without changes. ::: ## Next Steps - Explore `docmd`'s [Build & Deploy](../deployment/index.md) guide since `docmd` does not rely on Vite's build pipeline. - Review the full list of [docmd Containers](../content/containers/index.md) for additional UI components. --- ## [Analytics Plugin](https://docs.docmd.io/07/plugins/analytics/) --- title: "Analytics Plugin" description: "Integrate Google Analytics 4 or legacy Universal Analytics and track user interactions automatically." --- The `@docmd/plugin-analytics` plugin allows you to easily integrate Google Analytics into your documentation. It supports the modern Google Analytics 4 (GA4) standard, legacy Universal Analytics (UA), and includes native event tracking for interaction-heavy documentation sites. ## Configuration Enable analytics by adding your tracking credentials to the `plugins` section of your `docmd.config.js`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `googleV4` | `object` | `null` | Google Analytics 4 configuration (requires `measurementId`). | | `googleUA` | `object` | `null` | Universal Analytics configuration (requires `trackingId`). | | `autoEvents` | `boolean` | `true` | Automatically track clicks, downloads, and TOC interactions. | | `trackSearch` | `boolean` | `true` | Track search keywords used by readers. | ### Usage ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { analytics: { googleV4: { measurementId: 'G-XXXXXXX' }, autoEvents: true, trackSearch: true } } }); ``` ## Tracked Events When `autoEvents` is enabled, the plugin automatically captures the following user interactions: - **External Links**: Track when users depart for external resources. - **File Downloads**: Log clicks on links with the `download` attribute or common file extensions. - **Table of Contents (TOC)**: Monitor section engagement by tracking clicks in the right-hand navigation. - **Heading Anchors**: Log when users click on "permalinks" to share specific sections. - **Search Queries**: Capture keywords used in the search bar (with a 1-second debounce). ::: callout info "Privacy & GDPR" By default, this plugin does not anonymise IP addresses as that is now handled natively by GA4. If you require advanced cookie consent management, you can manually inject scripts using a custom plugin hook. ::: --- ## [Building Plugins](https://docs.docmd.io/07/plugins/building-plugins/) --- title: "Building Plugins" description: "A comprehensive guide to extending docmd with custom logic, data injection, and interactive features." --- Plugins are the primary extension mechanism for `docmd`. They allow you to inject custom HTML, modify the Markdown parsing logic, inject build-time data before template rendering, and automate post-build tasks. This guide outlines the plugin API and best practices for creating shareable components. ## Plugin Descriptor Every plugin should export a `plugin` descriptor declaring its identity and capabilities. This enables the engine to validate, isolate, and enforce capability boundaries at load time. ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` > **Note:** The descriptor is currently optional (soft deprecation warning). It will be **required starting 0.8.0**. ## Core Capabilities The `capabilities` array dictates which hooks your plugin is allowed to use. | Capability | Allowed Hooks | Phase | | :--- | :--- | :--- | | `init` | `onConfigResolved` | Init | | `markdown` | `markdownSetup` | Setup | | `head` | `generateMetaTags`, `generateScripts` (head) | Render | | `body` | `generateScripts` (body) | Render | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeRender`, `onPageReady` | Build | | `post-build`| `onPostBuild` | Post-Build | | `dev` | `onDevServerReady` | Dev Server | | `assets` | `getAssets` | Output | | `actions` | `actions` | Interactive | | `events` | `events` | Interactive | | `translations`| `translations` | i18n | Legacy plugins without a descriptor get full access to all hooks, so nothing breaks during the transition. ## Plugin API Reference A `docmd` plugin is a standard JavaScript object (or a module that exports one as default) that implements one or more of the following hooks. | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the `markdown-it` instance. Synchronous. | | `generateMetaTags(config, page, root)` | Inject `<meta>` or `<link>` tags into the `<head>`. | | `generateScripts(config, opts)` | Return an object containing `headScriptsHtml` and `bodyScriptsHtml`. | | `getAssets(opts)` | Define external files or CDN scripts to be injected. | | `onPostBuild(ctx)` | Run logic after the generation of all HTML files. | | `translations(localeId)` | Return an object of translated strings for the given locale. | | `actions` | An object of named action handlers for WebSocket RPC calls from the browser. | | `events` | An object of named event handlers for fire-and-forget messages from the browser. | ## Creating a Local Plugin Creating a plugin is as simple as defining a JavaScript file. For example, `my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { // Plugin descriptor (recommended) plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, // 1. Extend the Markdown Parser markdownSetup: (md, options) => { // Example: Add a rule or use a markdown-it plugin }, // 2. Inject Page Metadata generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, // 3. Post-Build Automation onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`Custom Plugin: Verified ${pages.length} pages.`); // Example: Generate a custom manifest or notification } }; ``` To enable your plugin, reference its **full package name** in your `docmd.config.js`: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { 'my-awesome-plugin': { // Your custom options go here } } }); ``` > **Note:** Shorthand names (e.g. `math`, `search`) are reserved exclusively for official `@docmd/plugin-*` packages. Third-party plugins must always be referenced by their full npm package name. ### Plugin Resolution The `docmd` engine resolves plugin names as follows: - **Official shorthands** (`math`, `search`, `seo`, etc.) automatically expand to `@docmd/plugin-<name>`. Since the `@docmd` npm scope is owned by the project, only official packages can exist under it. - **Third-party plugins** must use their full package name (e.g. `my-awesome-plugin`, `@myorg/docmd-extras`). There is no alias or shorthand system for external plugins - this prevents confusion and eliminates supply-chain attack vectors entirely. ### Plugin Isolation Every hook invocation is wrapped in a try/catch boundary. A broken plugin cannot crash the build or interfere with other plugins. Errors are logged and collected into a summary at the end of the build. ### Scoping Plugins (`noStyle`) By default, plugins inject their CSS/JS universally. However, developers can explicitly prevent their plugin from rendering on `noStyle` pages (like minimal landing templates) by exporting a `noStyle` boolean: ```javascript export default { noStyle: false, // Prevents generateMetaTags and generateScripts from running on noStyle pages generateScripts: () => { ... } } ``` Users can also override this behaviour through their configuration (`plugins: { math: { noStyle: false } }`) or dynamically via Markdown frontmatter (`plugins: { math: true }`). ## Lifecycle Hooks Docmd provides deep integration hooks that allow plugins to manipulate configuration, raw sources, and page data throughout the build pipeline. | Hook | Description | Expected Return | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | Reads or modifies the active normalised `config` right after initialisation. | `void` or `Promise<void>` | | **`onDevServerReady(server, wss)`** | Exposes the raw Node.js `http.Server` and `WebSocketServer` during development mode (`docmd dev`). | `void` or `Promise<void>` | | **`onBeforeParse(src, frontmatter)`** | Pre-processes raw markdown string data immediately before it is passed to markdown-it for parsing. | `string` or `Promise<string>` | | **`onAfterParse(html, frontmatter)`** | Post-processes generated HTML representing the markdown body segment. | `string` or `Promise<string>` | | **`onBeforeRender(page)`** | Called before template rendering. Receives the full `PageContext`. Mutations to `frontmatter` and `html` are reflected in the rendered output. | `void` or `Promise<void>` | | **`onPageReady(page)`** | Accesses the fully assembled page metadata (`page.html`, `page.outputPath`, `page.frontmatter`) just before it is written to the destination file. | `void` or `Promise<void>` | ### `onBeforeRender` and `PageContext` The `onBeforeRender` hook is the right place for plugins that need to inject build-time data derived from the source file - reading file metadata, computing custom frontmatter fields, or loading data from external sources. ```typescript interface PageContext { sourcePath: string; // Absolute path to the .md source file. Always set. frontmatter: Record<string, any>; // Mutable - changes reflected in template output html: string; // Mutable - rendered markdown body localeId?: string; versionId?: string; relativePathToRoot?: string; } ``` ```javascript export default { plugin: { name: 'my-metadata-plugin', version: '1.0.0', capabilities: ['build'] }, onBeforeRender: async (page) => { // sourcePath is always available - no guessing or path construction needed const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } }; ``` ```javascript export default { plugin: { name: "my-advanced-plugin", version: "1.0.0", capabilities: ["init", "build", "dev"] }, onConfigResolved: (config) => { config.siteTitle = config.siteTitle + " (Modified)"; }, onBeforeParse: (src, frontmatter) => { return src.replace(/foo/gi, 'bar'); }, onBeforeRender: async (page) => { // Inject data before template rendering page.frontmatter.customField = 'value'; }, onPageReady: (page) => { // Append custom tracking script into the final HTML page.html = page.html.replace('</body>', '<script>/* tracker */</script></body>'); } } ``` ## Deep Dive: Asset Injection The `getAssets()` hook allows your plugin to bundle client-side logic securely. ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', // External CDN script type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), // Local source dest: 'assets/js/plugin-init.js', // Destination in build/ type: 'js', location: 'body' } ]; } ``` ## Translating Plugins (i18n) Plugins that render client-side UI should expose translatable strings via the `translations(localeId)` hook. The docmd engine will call this hook during the build process, merge the results with core system strings and user overrides, and pass them down. The standard pattern is to store a JSON file for each language in an `i18n/` directory inside your plugin: ```javascript // my-plugin.js import fs from 'fs'; import path from 'path'; export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['translations', 'body'] }, translations: (localeId) => { // 1. Try loading the specific locale try { const p = path.join(__dirname, 'i18n', `${localeId}.json`); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } // 2. Fall back to English try { const p = path.join(__dirname, 'i18n', 'en.json'); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } return {}; } } ``` You can then inject these strings via `generateScripts` (using `config._activeLocale.id` to determine the current language), or rely on the engine to merge them into a global registry. ## WebSocket RPC Actions Starting in `0.6.8`, plugins can register **action handlers** and **event handlers** that run on the dev server and are callable from the browser via the `window.docmd` API. ```javascript // my-live-plugin.js export default { plugin: { name: 'my-live-plugin', version: '1.0.0', capabilities: ['actions', 'events'] }, // Server-side action - browser calls via docmd.call() actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, // Server-side event - browser sends via docmd.send() events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`Page viewed: ${data.path}`); } } }; ``` The `ctx` (ActionContext) object provides: | Method | Description | | :--- | :--- | | `ctx.readFile(path)` | Read a file relative to the project root. | | `ctx.writeFile(path, content)` | Write a file (triggers rebuild + reload). | | `ctx.readFileLines(path)` | Read a file as an array of lines. | | `ctx.broadcast(event, data)` | Push an event to all connected browsers. | | `ctx.source` | Source editing tools for block-level markdown manipulation. | | `ctx.projectRoot` | Absolute path to the project root. | | `ctx.config` | Current docmd site configuration. | All file operations are sandboxed to the project root - path traversal attempts are rejected automatically. ::: callout info "Dev Mode Only 🛡️" The WebSocket RPC system is only active during `docmd dev`. Production builds do not include the API client or any server-side action handling. ::: ## Best Practices 1. **Declare Capabilities**: Always export a `plugin` descriptor with your declared capabilities. This enables the engine to enforce boundaries and will be required in `0.8.0`. 2. **Use `onBeforeRender` for data injection**: If your plugin reads the source file or computes frontmatter fields, use `onBeforeRender` - not `generateMetaTags`. The `sourcePath` is always available in `PageContext`. 3. **Async/Await**: Always use `async` functions for `onPostBuild`, `onBeforeRender`, and action handlers to prevent blocking the build engine during I/O operations. 4. **Statelessness**: Avoid maintaining state within the plugin object, as `docmd` may re-initialise plugins during development rebuilds. 5. **Naming Convention**: For community plugins, prefix your package name with `docmd-plugin-` (e.g., `docmd-plugin-analytics`). 6. **Action Namespacing**: Prefix your action names with your plugin name (e.g., `my-plugin:save-note`) to avoid collisions. 7. **Action Validation**: Always define and require an explicit payload schema in your actions. This ensures a secure plugin ecosystem where unknown payload properties are stripped or rejected. 8. **Logging**: Use the provided `log()` helper in `onPostBuild` to ensure your messages respect the user's `--verbose` settings. ::: callout tip "AI-Ready Design 🤖" The `docmd` plugin API is designed to be **LLM-Optimal**. Because the hooks use standard JavaScript objects and types without hidden complex class hierarchies, AI agents can generate bug-free custom plugins for you with minimal instruction. ::: --- ## [Git Plugin](https://docs.docmd.io/07/plugins/git/) --- title: "Git Plugin" description: "Repository-aware metadata, last-updated timestamps, and automated edit links derived from Git history." --- The `@docmd/plugin-git` plugin adds repository intelligence to your documentation. It automatically displays when each page was last modified, who contributed to it, and provides an optional "Edit this page" link - all extracted directly from your Git history at build-time. ## Configuration | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | Repository URL (e.g. `https://github.com/org/repo`). Required for edit links. | | `branch` | `string` | `'main'` | Branch name for edit links. | | `editLink` | `boolean` | `true` | Show "Edit this page" link when `repo` is set. | | `lastUpdated` | `boolean` | `true` | Show last updated timestamp. | | `commitHistory` | `boolean` | `true` | Show commit history tooltip on hover. | | `maxCommits` | `number` | `6` | Maximum commits to show in the tooltip. | | `dateFormat` | `string` | `'relative'` | Timestamp format: `relative` (default), `iso`, or `locale-aware`. | ### Usage ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { git: { repo: 'https://github.com/docmd-io/docs', branch: 'main', editLink: true, lastUpdated: true, commitHistory: true, maxCommits: 5 } } }); ``` ## Features - **Last Updated Timestamps**: Automatically shows when a page was last modified in the footer. - **Commit History Tooltip**: Hovering over the timestamp reveals a list of recent commits for that specific page. - **Automated Edit Links**: Provides a link to edit the source file on GitHub, GitLab, or Bitbucket. - **Performance-First**: Git history is queried once and cached at build-time, ensuring zero impact on site performance. ## Usage Once configured, the plugin works automatically. Timestamps and edit links appear in the page footer. ### Footer Example ::: callout info "Rendering Result" The footer of this page (and all others in this documentation) is rendered by the Git plugin. Scroll to the bottom to see it in action - hover over the **Last updated** date to see the commit history. ::: ## Per-Page Control Disable Git features for specific pages via frontmatter: ```markdown --- title: "Internal Notes" plugins: git: false --- ``` ## CI/CD Integration The Git plugin reads your repository history at build-time using local Git commands. Many CI/CD providers use "shallow clones" by default (fetching only the last commit), which will cause the plugin to only show the most recent change across all pages. To ensure accurate timestamps and history, you must configure your CI environment to perform a full fetch. ::: tabs == tab "GitHub Actions" Add `fetch-depth: 0` to your checkout step: ```yaml - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 ``` == tab "GitLab CI" Set the `GIT_DEPTH` variable to `0`: ```yaml variables: GIT_DEPTH: 0 ``` == tab "Netlify" Netlify fetches the full history by default. However, if you have issues, ensure your build command has access to the `.git` directory. No additional configuration is usually required. ::: ::: callout warning "Git Data Requirement" The `.git` directory must be present in the build environment for the plugin to function. If you are building inside a Docker container or a restricted CI environment, ensure the Git history is preserved and that the `git` binary is installed. ::: ## Localisation The plugin includes built-in translations for English, German, and Chinese. Custom strings can be provided through the [UI Localisation](../configuration/localisation/ui-strings.md) system. --- ## [LLM Context Plugin](https://docs.docmd.io/07/plugins/llms/) --- title: "LLM Context Plugin" description: "Optimise your documentation for AI consumption with automated llms.txt and llms-full.txt generation." --- The `@docmd/plugin-llms` plugin ensures your documentation is perfectly optimised for Large Language Models (LLMs) and AI Agents. It follows the growing industry standard of providing a high-level summary and a comprehensive context file that AI tools can ingest to understand your project with minimal hallucination. ## Configuration The LLM plugin is enabled by default. To function correctly, you must provide a `url` in your `docmd.config.js`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable the LLM context generation. | | `fullContext` | `boolean` | `true` | If true, generates a `llms-full.txt` file containing the content of all pages. | | `maxTokenLimit` | `number` | `null` | Optional limit on the total characters/tokens for context files. | ### Usage ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ url: 'https://docs.example.com', plugins: { llms: { fullContext: true } } }); ``` ## Usage Once configured, the plugin automatically generates `llms.txt` and `llms-full.txt` in your site root during every build. These files are linked in the page `<head>` for automatic discovery by AI tools. ### Excluding a Page If a page contains sensitive information or internal notes you don't want AI models to learn, use the `llms: false` flag in your frontmatter: ```markdown --- title: "Internal Dev Secrets" llms: false --- ``` ::: callout tip "Maximising AI Accuracy" For detailed best practices on structuring your markdown (semantic headings, alt-text, etc.), see our [Optimising for AI Agents](../guides/ai-optimisation/generating-ai-ready-docs.md) guide. ::: --- ## [Math Plugin](https://docs.docmd.io/07/plugins/math/) --- title: "Math Plugin" description: "Native KaTeX/LaTeX mathematics integration for docmd." --- The **Math plugin** adds native LaTeX and KaTeX support to your docmd sites. It utilises `markdown-it-texmath` as securely integrated with the `katex` computation engine to render both inline and block-level mathematical equations smoothly without requiring complex client-side javascript libraries. ## Setup ```bash docmd add math ``` ```javascript plugins: { math: {} } ``` ## How It Works 1. Enable the plugin via your `docmd.config.js`. 2. Wrap your standard LaTeX mathematics in `$` (inline) or `$$` (block) indicators. 3. The server intelligently processes these math rules during the static-site build exactly as raw static HTML tags. 4. Minimal injected CSS automatically scopes these classes directly, yielding immediate visualisation the moment the user views the page! ## Usage ### Inline Mathematics You can inject standard equations flawlessly within a paragraph utilising single dollar signs `$`: ```markdown Here is an inline equation: $E = mc^2$ ``` Here is an inline equation: $E = mc^2$ ### Block Mathematics For wider mathematical proofs or distinct formulations, use double dollar signs `$$` for block level formatting: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid Diagrams](https://docs.docmd.io/07/plugins/mermaid/) --- title: "Mermaid Diagrams" description: "Create professional architectural diagrams, flowcharts, and sequence diagrams directly in your Markdown files using Mermaid.js syntax." --- The `@docmd/plugin-mermaid` plugin integrates the powerful [Mermaid.js](external:https://mermaid.js.org/) engine into your documentation pipeline. It allows you to transform plain-text descriptions into high-fidelity, interactive diagrams with built-in support for themes, panning, and zooming. ## Configuration The Mermaid plugin is bundled with `@docmd/core` and enabled by default. No mandatory configuration is required. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable Mermaid diagram rendering globally. | ### Example ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { mermaid: {} // Enabled by default } }); ``` ## Features - **Theme Awareness**: Diagrams automatically adapt to **Light** or **Dark** mode transitions. - **Interactive Controls**: Built-in **Pan**, **Zoom**, and **Fullscreen** buttons for every diagram. - **Lazy Loading**: Diagrams are initialised only as they enter the user's viewport for optimum performance. - **Icon Support**: Deep integration with the **Lucide** icon pack (use `icon:name` syntax). ## Usage Embed diagrams using a fenced code block with the `mermaid` language identifier. ### Sequence Diagram Example ::: tabs == tab "Preview" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` == tab "Source" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` ```` ::: ### Architecture Example ```mermaid architecture-beta group api(icon:cloud)[API Service] service db(icon:database)[Database] in api service disk(icon:hard-drive)[Storage] in api db:L -- R:disk ``` ::: callout tip "AI Readability" Because Mermaid diagrams are defined as pure text in your Markdown, they are fully readable by AI agents. This allows LLMs to understand and explain your system architecture directly from your documentation source. ::: --- ## [OpenAPI Plugin](https://docs.docmd.io/07/plugins/openapi/) --- title: "OpenAPI Plugin" description: "Static API reference documentation rendered directly from OpenAPI 3.x specifications at build-time." --- The `@docmd/plugin-openapi` plugin converts OpenAPI 3.x specification files into structured, searchable API reference pages. It follows the Docmd "Zero-JS" philosophy - rendering every endpoint, parameter, and response into semantic HTML tables during the build process, ensuring maximum performance and SEO. ## Configuration The OpenAPI plugin is included by default in `@docmd/core`. You can configure global rendering options in your `docmd.config.js`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `info` | `boolean` | `true` | Display the API title, version, and description from the spec's `info` object. | | `download` | `boolean` | `false` | If true, adds a link to the header of the spec to download the raw JSON/YAML file. | | `summaryOnly` | `boolean` | `false` | If true, only renders the method, path, and summary. Useful for large API indexes. | | `allowRawHtml` | `boolean` | `false` | If true, prevents escaping of HTML tags in descriptions. | ### Example ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { openapi: { info: true, download: true, summaryOnly: false } } }); ``` ## Usage Embed an OpenAPI specification anywhere in your Markdown using a fenced code block with the `openapi` tag. The path is resolved relative to your project source. ````markdown ```openapi assets/openapi.json ``` ```` ### Rendering Result ```openapi assets/docmd-api.json ``` ## What Gets Rendered For each path and HTTP method in the spec, the plugin renders: - **Method badge** - colour-coded (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`) - **Path** - the full endpoint path with parameters highlighted - **Summary and description** - from the operation object - **Parameters table** - name, location (`path`, `query`, `header`, `cookie`), type, required flag, description - **Request body table** - schema properties with types and defaults - **Responses table** - status codes with descriptions and response schema types - **Deprecated notice** - operations marked `deprecated: true` are flagged inline ::: callout tip "Build-Time Rendering" All rendering happens at build time. The generated pages are fully static - no JavaScript is needed to display the API docs, which means fast page loads and full search indexation. This approach ensures zero-JS performance and SEO-friendliness. ::: ## Capability Support | Feature | Support | | :--- | :--- | | OpenAPI 3.x | ✓ (JSON & YAML*) | | Swagger 2.x | ✗ (Convert to 3.x first) | | `$ref` Resolution | ✓ (Internal schemas) | | `oneOf` / `anyOf` | ✓ (Shown as union types) | | `deprecated` flag | ✓ | *\*YAML support requires the `js-yaml` package to be installed in your project.* --- ## [PWA & Offline Support](https://docs.docmd.io/07/plugins/pwa/) --- title: "PWA & Offline Support" description: "Transform your documentation into a progressive web application with offline caching and mobile-first features." --- The `@docmd/plugin-pwa` plugin transforms your documentation into a Progressive Web App (PWA). It adds a web manifest for mobile installation and registers a service worker for intelligent offline caching, ensuring your technical manuals remain accessible even in low-connectivity environments. ## Configuration Customise your app branding within the `plugins` section of your `docmd.config.js`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable PWA manifest and service worker generation. | | `themeColor` | `string` | `'#1e293b'` | The primary colour of the mobile UI browser chrome. | | `bgColor` | `string` | `'#ffffff'` | Background colour for the splash screen during installation. | | `logo` | `string` | `null` | Path to the app icon (relative to project source). | ### Example ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { pwa: { themeColor: '#1e293b', bgColor: '#ffffff', logo: 'assets/app-icon.png' } } }); ``` ## Features - **Offline Caching**: Uses a "Stale-While-Revalidate" strategy to serve pages instantly from the cache while updating in the background. - **Mobile Installation**: Generates a `manifest.webmanifest` allowing users to "Add to Home Screen" on iOS and Android. - **Smart Asset Resolution**: Automatically generates app icons from your project logo or favicon if no explicit icon is provided. - **SPA Compatible**: Fully compatible with Single Page Application transitions and standard directory routing. ## Icon Resolution Priority The plugin resolves your PWA icons based on the following priority: 1. `pwa.icons` - Explicit array in config. 2. `pwa.logo` - Path relative to source. 3. `config.logo` - Global site logo. 4. `config.favicon` - Global favicon. ::: callout tip "Testing PWA Features" Service workers are bypassed in `docmd dev` to prevent caching issues during editing. To test PWA features, run `docmd build` and serve the `site/` directory using a static host. ::: --- ## [Search Plugin](https://docs.docmd.io/07/plugins/search/) --- title: "Search Plugin" description: "Enable high-speed, offline-first full-text search for your documentation using MiniSearch." --- The `@docmd/plugin-search` plugin provides a powerful, client-side search experience for your documentation. It uses [MiniSearch](external:https://github.com/lucaong/minisearch) to build a lightweight index during the build process, allowing users to find technical information instantly without a server-side database. ## Configuration Search is enabled by default in most `docmd` templates. You can control its visibility and placement via the `layout` configuration. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable the full-text search indexer. | | `placeholder` | `string` | `'Search...'` | Custom placeholder text for the search input. | | `maxResults` | `number` | `10` | Maximum number of results to display in the modal. | ### Usage ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ layout: { optionsMenu: { position: 'header', // 'header', 'sidebar-top', 'sidebar-bottom', or 'menubar' components: { search: true // Set to false to disable the search plugin entirely } } } }); ``` ## How It Works ### 1. Indexing (Build-time) During the `docmd build` process, the search plugin iterates through every page on your site. It extracts the title, headings, and plain-text prose, then compiles this data into a compressed `search-index.json` file. * **Deep Linking**: The indexer automatically registers every heading (`#`, `##`, etc.) as a searchable target. * **Relevancy Boosting**: Titles are given the highest weight, followed by headings, then page content. ### 2. Retrieval (Client-side) When a user opens the search modal (usually via `/` or `Ctrl+K`), the `search-index.json` is fetched by the browser. Searches are performed locally using fuzzy matching (allowing for small typos) and instant prefix matching. ## Customising Search Behaviour While the search plugin is designed for zero-config simplicity, you can exclude specific pages from the index by using the `noindex` flag in their frontmatter: ```yaml --- title: "Internal Specification" noindex: true # This page will not appear in search results or sitemaps --- ``` ## Technical Implementation The plugin injects a lightweight search modal into the `<body>` of your site. It is fully accessible (ARIA compliant) and supports keyboard navigation for a native app-like experience. ::: callout tip "Search Analytics" If you have the [Analytics Plugin](./analytics.md) enabled, search keywords used by your readers are automatically captured and sent to your analytics provider, giving you insights into what information is missing or hardest to find. ::: Because the search happens entirely on the client, no data - not even keystrokes - is ever sent to a server. This makes `docmd` the Gold Standard for documentation search in privacy-sensitive industries (Healthcare, Finance, Security). ## Comparison Many documentation generators (like Docusaurus) rely on **Algolia DocSearch**. While Algolia is powerful, it introduces friction: | Feature | docmd Search | Algolia / External | | :--- | :--- | :--- | | **Setup** | **Zero Config** (Automatic) | Complex (API Keys, CI/CD crawling) | | **Privacy** | **100% Private** (Client-side) | Data sent to 3rd party servers | | **Offline** | **Yes** | No | | **Cost** | **Free** | Free tier limits or Paid | | **Speed** | **Instant** (In-memory) | Fast (Network latency dependent) | --- ## [SEO Plugin](https://docs.docmd.io/07/plugins/seo/) --- title: "SEO Plugin" description: "Optimise your documentation for search engines and control AI crawler access with native meta tag generation." --- The `@docmd/plugin-seo` plugin generates high-quality metadata for every page. It ensures your documentation is not only discoverable by human readers on search engines but also correctly interpreted by AI models and social media platforms. ## Configuration Configure site-wide SEO defaults in your `docmd.config.js`. Page-level settings always take precedence over global defaults. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `defaultDescription` | `string` | `null` | Fallback description for pages without frontmatter descriptions. | | `aiBots` | `boolean` | `true` | Set to `false` to block common AI crawlers (GPTBot, Claude-Web, etc.). | | `openGraph` | `object` | `null` | Open Graph settings for social media (Facebook, LinkedIn). | | `twitter` | `object` | `null` | Twitter (X) Card settings including username and card type. | ### Example ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { seo: { defaultDescription: 'Comprehensive documentation for the docmd ecosystem.', aiBots: false, twitter: { siteUsername: '@docmd_io', cardType: 'summary_large_image' } } } }); ``` ## Features - **Smart Fallbacks**: Automatically extracts the first 150 characters of prose if no description is provided. - **AI Bot Governance**: Easily block or allow AI crawlers to differentiate between indexing and LLM training. - **Canonical Resolution**: Automatically generates `<link rel="canonical">` tags to prevent duplicate content issues. - **Rich Social Previews**: Native support for Open Graph and Twitter Cards for professional link sharing. - **Structured Data**: Supports LD+JSON Article Schema for rich search snippets. ## Page-Level Overrides Fine-tune settings for individual pages using frontmatter: ```markdown --- title: "Advanced Configuration" noindex: true # Hide from all search engines seo: keywords: ["docmd", "javascript", "ssg"] aiBots: true # Override global block for this page ldJson: true # Enable Article Schema --- ``` ::: callout tip "Search Discovery" For best results, ensure your `url` is defined in the root of your configuration. Without a base URL, the plugin cannot generate absolute canonical links or social image paths. ::: --- ## [Sitemap Plugin](https://docs.docmd.io/07/plugins/sitemap/) --- title: "Sitemap Plugin" description: "Automatically generate a standard-compliant sitemap.xml for better search engine discovery." --- The `@docmd/plugin-sitemap` plugin generates a `sitemap.xml` file at the root of your build directory. This provides search engines with a comprehensive map of your site's architecture, ensuring that all pages - including versioned documentation - are crawled and indexed. ## Configuration Enable sitemap generation by providing your `siteUrl` in the root configuration. You can customise the crawl weight within the `plugins` object. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable sitemap generation. | | `defaultChangefreq` | `string` | `'weekly'` | Hint to crawlers on how often pages change. | | `defaultPriority` | `number` | `0.8` | Default weight for standard pages (0.0 to 1.0). | | `rootPriority` | `number` | `1.0` | Weight for the homepage (`index.md`). | ### Example ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ url: 'https://docs.example.com', plugins: { sitemap: { defaultChangefreq: 'weekly', defaultPriority: 0.8 } } }); ``` ## Features - **Automatic URL Construction**: Intelligently resolves page paths to their canonical public URLs with clean directory structure. - **Versioned Discovery**: Automatically includes all pages from all versions (e.g. `/v1/`, `/v2/`) without manual configuration. - **Granular Exclusions**: Exclude specific pages from the sitemap using frontmatter. - **SEO Ready**: Follows standard XML sitemap protocols compatible with all major search engines. ## Page-Level Controls Override sitemap behaviour for specific pages using frontmatter: ```markdown --- title: "Archive Page" priority: 0.3 # Lower weight for legacy content changefreq: "monthly" # Hint to crawlers sitemap: false # Exclude this specific page --- ``` ::: callout tip "Validation" After building your site, you can find the sitemap at `site/sitemap.xml`. You can submit this URL directly to search engine consoles to accelerate indexing. ::: --- ## [Threads Plugin](https://docs.docmd.io/07/plugins/threads/) --- title: "Threads Plugin" description: "Add inline discussion threads to your documentation - stored directly in your markdown files." --- The **Threads plugin** brings collaborative inline comments to your documentation. Select any text on the page, leave a comment, start a discussion - all stored directly in your markdown source files with zero database needed. Original Author: [@svallory](external:https://github.com/svallory) ::: callout info "Alpha Release" This plugin is in alpha. The API and storage format are stable, but the UI is under active development. ::: ## Setup ```bash docmd add threads ``` ```javascript plugins: { threads: {} } ``` ### Configuration Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | When `true`, threads stay grouped at the bottom of the page. When `false` (default), threads are positioned inline next to their highlighted text. | ```javascript // Keep threads at bottom of page instead of inline plugins: { threads: { sidebar: true } } ``` ## How It Works 1. **Select text** on any documentation page during `docmd dev` 2. A **comment popover** appears - write your comment and submit 3. The selected text gets **highlighted** with a thread marker 4. Threads are stored as `::: threads` blocks at the bottom of the markdown file 5. **No database** - your markdown files are the source of truth ## Preview Here's what threads look like on a live page. Text with discussions gets <span class="threads-preview-highlight">highlighted like this</span> and thread cards appear below. <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 2d ago</div> <div class="threads-preview-body">This section could use a diagram to explain the architecture. What do you think?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · 1d ago</div> <div class="threads-preview-body">Good idea - I'll add a Mermaid flowchart. Does <code>sequenceDiagram</code> work here?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 12h ago</div> <div class="threads-preview-body">Perfect. A simple flowchart would be ideal.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> And here's a <span class="threads-preview-highlight-blue">second highlight with a different colour</span> - threads cycle through a palette of colours automatically. <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · 3d ago</div> <div class="threads-preview-body">Should we mention backward compatibility here?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> Resolved threads appear dimmed: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 5d ago  <span class="threads-preview-resolved-badge">✓ Resolved</span></div> <div class="threads-preview-body">Fixed the typo in the config example.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> A floating **discussion button** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span> appears in the bottom-right corner showing the count of open threads. Click it to jump to the first thread on the page. ## Storage Format Threads are embedded in your markdown using docmd's container syntax: ```markdown # My Documentation Page Some content with ==highlighted text=={t-a1b2c3d4} that has a thread. ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" This text needs clarification. ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 Updated it - does this work? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` The `==text=={threadId}` syntax links highlighted text in the document body to a specific thread. ## Features | Feature | Description | | :--- | :--- | | **Text Selection** | Select any text to start a new thread | | **Replies** | Nested reply chains within each thread | | **Reactions** | Emoji reactions on individual comments | | **Edit / Delete** | Modify or remove your comments | | **Resolve** | Mark threads as resolved with author + timestamp | | **Author Profiles** | Git-based author detection with Gravatar support | | **Highlight Markers** | Visual indicators on the page showing where threads are anchored | | **Floating Button** | Quick-access FAB with open thread count | | **Scroll Preservation** | Page stays in place after adding comments | ## Actions API The threads plugin exposes the following actions via the WebSocket RPC system. These can be called from browser plugins using `docmd.call()`: | Action | Description | | :--- | :--- | | `threads:get-threads` | Parse and return all threads from a file | | `threads:add-thread` | Create a new thread with its first comment | | `threads:add-comment` | Add a comment to an existing thread | | `threads:edit-comment` | Edit an existing comment's body | | `threads:delete-comment` | Remove a comment from a thread | | `threads:delete-thread` | Remove an entire thread and cleanup highlights | | `threads:resolve-thread` | Toggle resolved/unresolved status | | `threads:toggle-reaction` | Toggle an emoji reaction on a comment | | `threads:get-authors` | Read the author profile map | | `threads:upsert-author` | Create or update an author profile | ## Author Profiles Author information is stored in `<docsRoot>/.threads/authors.json`: ```json { "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } } ``` During development, the plugin automatically detects your git username and email for author identification. ::: callout tip "Version Control Friendly" Since threads are stored in your markdown files, they are automatically version-controlled with git. Review comments in PRs, track discussion history, and collaborate through your existing workflow. ::: --- ## [Using Plugins](https://docs.docmd.io/07/plugins/usage/) --- title: "Using Plugins" description: "Install, configure, and manage docmd plugins - from required defaults to optional add-ons." --- `docmd` features a modular plugin architecture. Required plugins ship with the core and need no installation. Optional plugins can be installed with a single CLI command. ## Installing Plugins Use the `docmd` CLI to install and remove plugins: ```bash # Install a plugin docmd add <plugin-name> # Remove a plugin docmd remove <plugin-name> ``` The installer automatically detects your package manager (npm, pnpm, yarn, or bun), resolves short names to full package names, and injects the plugin config into your `docmd.config.js`. Use `--verbose` (or `-V`) for full installer output: ```bash docmd add <plugin-name> -V ``` ## Required Plugins These plugins are bundled with `@docmd/core` - no installation needed. Enable them in your `docmd.config.js`: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { search: {}, // Offline full-text search seo: { aiBots: false }, // Meta tags, Open Graph, AI bot controls sitemap: {}, // Automatic sitemap.xml generation analytics: {}, // Google Analytics v4 llms: {}, // LLM context generation (llms.txt) mermaid: {}, // Native interactive diagrams git: {} // Last updated timestamps and commit history } }); ``` ::: callout tip "Git Plugin" The Git plugin automatically detects if your project is in a Git repository. If not, it gracefully disables itself. No configuration is needed for basic last-updated timestamps - just ensure your docs are in a Git repo. ::: ## Optional Plugins Optional plugins require installation before enabling. | Plugin | Install Command | Description | | :--- | :--- | :--- | | [PWA](pwa.md) | `docmd add pwa` | Progressive Web App support with offline caching | | [Threads](threads.md) | `docmd add threads` | Inline discussion comments stored in your markdown | | [Math](math.md) | `docmd add math` | Native KaTeX and LaTeX mathematics integration | ## Auto-Installation When you add an official plugin to your `docmd.config.js` that isn't installed, docmd automatically downloads and installs it on the next build. This works for all plugins in the [official registry](/plugins/usage). ```javascript // docmd.config.js plugins: { pwa: {} // Not installed? docmd will auto-install it } ``` The auto-installer: - Only works for official `@docmd/plugin-*` packages - Installs the exact version matching your `@docmd/core` version - Uses your project's package manager (npm, pnpm, yarn, or bun) - Shows progress in the terminal ::: callout warning "Third-Party Plugins" Auto-installation only works for official plugins in the registry. Third-party plugins must be installed manually using your package manager. ::: ## Plugin Scopes and `noStyle` Overrides Plugins inject CSS and behaviour by default globally across all pages. However, you can explicitly configure them to bypass specific pages or entirely disable their execution on unstyled landing templates (`noStyle: true`). ### Global Config Extent You can instruct any plugin to automatically skip injecting into `noStyle` pages via your `docmd.config.js`: ```javascript plugins: { math: { noStyle: false // math css/js will no longer load on no-style pages } } ``` ### Page Local Scope (Frontmatter) Regardless of your global config (or what the plugin developer set by default), you can definitively enable or disable any plugin uniquely per-document via markdown frontmatter. ```markdown --- noStyle: true plugins: math: true threads: false --- # Only Math renders here, Threads are completely blocked ``` ## Plugin Lifecycle Plugins hook into different stages of the build and development process: | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the Markdown parser with custom rules or containers | | `generateMetaTags(config, page, root)` | Inject `<meta>` and `<link>` tags into the `<head>` | | `generateScripts(config, opts)` | Inject scripts into `<head>` or `</body>` | | `getAssets(opts)` | Define external files or CDN scripts to inject | | `onPostBuild(ctx)` | Run logic after all HTML files are generated | | `translations(localeId)` | Return translated UI strings for a locale | | `actions` | Server-side handlers callable from the browser via WebSocket RPC | | `events` | Fire-and-forget handlers for browser-pushed events | ## Plugin Safety The plugin system provides built-in safety guarantees: - **Validation**: Plugins can declare a `plugin` descriptor with `name`, `version`, and `capabilities`. Invalid descriptors are rejected at load time. - **Isolation**: Every hook invocation is wrapped in a try/catch boundary. A broken plugin cannot crash the build or affect other plugins. - **Capability Enforcement**: Plugins that declare capabilities can only register for hooks they've explicitly declared. Undeclared hooks are skipped with a warning. See [Building Plugins](building-plugins.md) for the full API reference. ::: callout tip "AI-Transparent Architecture :robot:" The plugin architecture is designed to be **deterministic**. Every meta-tag and script injected by a plugin is traceable, allowing AI agents (and human developers) to understand exactly how the site behaves without hidden side effects. ::: --- ## [Release Notes - 0.7.0](https://docs.docmd.io/07/release-notes/0-7-0/) --- title: "Release Notes - 0.7.0" description: "First-class internationalisation, zero-config core plugins, and true zero-config defaults." --- The `docmd` 0.7.0 release is a major step forward - introducing native multi-language support (i18n) with a built-in translation system and true zero-config defaults where all core plugins are active out-of-the-box. ## ✨ Highlights ### 🌍 Internationalisation (i18n) docmd now has first-class i18n support. Configure multiple locales and docmd builds a complete, localised version of your site for every locale - with locale-first URLs (`/hi/`, `/zh/`), translated UI strings, and automatic language detection. Every locale lives in its own subdirectory - including the default language. This keeps your source directory clean and makes the structure easy to understand at a glance: ``` docs/ en/ ← default locale (renders at /) hi/ ← Hindi (renders at /hi/) zh/ ← Chinese (renders at /zh/) ``` The locale IDs, folder names, and default language are entirely your choice - `en`, `hi`, `fr`, `de`, or any identifier you prefer. ```js // docmd.config.js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }, { id: 'zh', label: '中文' }, ] } } ``` This includes **Per-Locale Search Indexes** spanning across your versions automatically, along with translated UI components for official plugins like Search and Threads! ### 🚀 Zero-Config Core Plugins In `0.7.0`, docmd embraces a true zero-config philosophy. All official core plugins (`search`, `seo`, `sitemap`, `pwa`, `analytics`, `llms`, `mermaid`) are now **auto-included by default**. You no longer need to declare them manually in your `plugins` array to use them. If you want to disable a core plugin, you can now simply mark it as `false`: ```js export default { plugins: { search: false // Disables the automatically included search plugin } } ``` ## 📝 Complete Changelog ### 🌍 i18n Architecture - **Clean locale directories**: Every locale (including the default) lives in its own subdirectory inside `src`. No more mixing locale folders alongside content folders. - **Locale-first URL generation**: Build loop now builds nested directories for each configured locale. - **Per-file fallback**: Non-default locales inherit pages from the default locale when a translation is missing, with an automatic warning callout. - **Per-locale navigation**: Each locale directory can have its own `navigation.json`, falling back to the default locale's navigation when absent. - **Versioning + i18n**: Old versions without locale directories are rendered in the default locale only. Add a locale subdirectory to any old version to enable translations for it. - **Translated UI strings**: Native translation system across all UI elements and templates. Handlers resolved against JSON locale files (`en.json`, `hi.json`, `zh.json`) - all template strings accessible via a fast `t('key')` helper. - **Plugin i18n API**: Plugins now support a new `translations(localeId)` hook alongside an `i18n/` directory convention for client-side strings. - **Global Search Locales**: The local MiniSearch index is now built per-locale, dynamically rendering version badges based on context, and gracefully providing localised search results. - **Zero-footprint fallback**: Sites with no `i18n` block build identically to pre-0.7.0 - no path or output changes overhead. - **String Mode (`stringMode: true`)**: A new i18n mode for noStyle pages - generate locale-specific HTML from a single source file. Add `data-i18n` attributes to your HTML, place translation files in `assets/i18n/{locale}.json`, and docmd clones the rendered output with **server-side string replacement** at build time. Produces fully translated, SEO-indexable pages at `/{locale}/` paths. Supports `data-i18n` (textContent), `data-i18n-html` (innerHTML), and `data-i18n-{attr}` (attribute values). Missing translation files gracefully fall back to the default language. Designed for noStyle/HTML pages only - markdown documentation should use directory mode. - **Client-side i18n for noStyle pages**: A lightweight `docmd-i18n-strings.js` module is auto-injected when i18n is configured. Provides a runtime `switchLocale()` API, `inPlace` mode for SPAs, and a `docmd:i18n-applied` event for custom language switchers. ### 🔌 Plugin System & Engine - **Core plugins auto-activation**: Zero-config defaults automatically provide the complete docmd suite without config overhead. - **Asset generation optimisations**: Restructured asset pipeline so that static CSS, JS, and global configurations are built exactly once to the root, regardless of how many locales or versions are active. ### 🎨 UI & Containers - **Container `icon:` parameter**: Callouts, cards, collapsible sections, and buttons now accept an `icon:` parameter to render a Lucide icon inline with the title. Icons are vertically centred and properly sized using flexbox alignment. ```md ::: card "Setup" icon:rocket ::: button "Get Started" /start icon:arrow-right ``` - **`titleAppend` frontmatter option**: Pages can now set `titleAppend: false` in frontmatter to suppress the automatic ` - Site Title` suffix in the `<title>` tag. Useful for homepages and landing pages. - **Pill-style version & language switchers**: The version dropdown and language switcher in the sidebar now render as compact pill buttons that sit side-by-side on the same line, saving vertical space. Shared CSS classes ensure consistent sizing across both components. - **Language switcher version awareness**: When browsing an old version that has no translations, non-default locales are visually disabled in the language switcher with an "N/A" badge, preventing broken navigation to non-existent pages. - **Translatable "(Latest)" badge**: The current version now displays an auto-generated, translatable "Latest" badge in the version dropdown. No longer hardcoded in the config label - uses the built-in translation system. - **Search result version badges**: Search results now display version badges as colour-coded pills aligned to the right of the result title. Each version gets a deterministic colour generated at build time for easy visual identification. - **Responsive language pill**: When both version and language pills are present, the language label auto-hides on standard sidebars and only shows the globe icon, expanding to show the label on wider screens. - **Dev server config hot-reload**: Changes to `docmd.config.js` now trigger a full rebuild during `docmd dev` without requiring a manual restart. File watcher correctly detects config file changes on all platforms. ## 🐛 Bug Fixes - **Versioning + i18n conflict**: Old version directories without locale subdirectories were being duplicated across all locales. Now correctly rendered for the default locale only - non-default locales skip versions that have no translations. - **Ghost locale pages in old versions**: Locale subdirectories inside old version directories (e.g. `docs-v1/hi/`) were rendered as regular content pages during the default locale pass, producing duplicate URLs. Fixed by filtering known locale directory names during the scan. - **Navigation warning false positive**: The "No navigation settings found" message was shown even when `navigation.json` existed inside locale or version directories. Now silent when navigation is available in any locale or version directory. - **Auto-nav scanning wrong directory**: When i18n is enabled, the auto-navigation builder was scanning the source root (which only contains locale directories), generating incorrect navigation from folder names. Now scans the default locale's directory instead. - **`<title>` tag missing site name**: Pages without an explicit title produced empty title tags. The template now auto-appends the site title with an em-dash separator (`Page - Site`), and the homepage shows just the site title. - **Language switcher URL duplication on old versions**: Switching language while browsing a non-current version produced URLs with the version prefix duplicated (e.g. `/zh/06/06/page`). Fixed by stripping the version prefix from the page path before rebuilding the locale URL. ## 🧪 Quality Assurance The 0.7.0 release passes a comprehensive brute test suite covering **25 distinct scenarios** with **85 individual assertions** - all green. Every major feature is tested both in isolation and in combination: ::: collapsible "View full test coverage" | # | Scenario | Assertions | |:--|:---------|:-----------| | 1 | Zero-config (no config file) | 5 | | 2 | Zero-config with nested directories | 4 | | 3 | i18n standalone (non-English default) | 5 | | 4 | Versioning standalone (no i18n) | 5 | | 5 | i18n + versioning combined | 6 | | 6 | Old version with partial translations | 4 | | 7 | Missing locale dir (graceful skip) | 3 | | 8 | Navigation resolution priority | 2 | | 9 | Frontmatter parsing | 3 | | 10 | Containers (callout, tabs, steps, hero) | 5 | | 11 | Code blocks (JS, Python) | 3 | | 12 | Custom CSS/JS injection | 3 | | 13 | Edit links | 3 | | 14 | No-style pages | 3 | | 15 | Search index generation | 3 | | 16 | Sitemap generation | 3 | | 17 | EJS content pages | 3 | | 18 | README.md as index fallback | 4 | | 19 | `.markdown` file extension | 3 | | 20 | Deep nested structure (4+ levels) | 2 | | 21 | Zero-config auto-nav accuracy | 3 | | 22 | Title tag auto-append | 2 | | 23 | Open Graph meta tags | 3 | | 24 | Redirects | 3 | | 25 | Per-page layout override | 3 | All 13 internal failsafe checks also pass. The brute test script is included in `scripts/brute-test.js` for anyone to run locally. ::: ## ⚠️ Breaking Changes - **Third-party plugin shorthand names are no longer resolved** - you must use the full package name if you are importing third-party plugins. (`search`, `threads`, etc., are reserved strictly for `@docmd/plugin-*`). - **`pnpm onboard` removed** - the `onboard` script has been merged into `pnpm prep`. Use `pnpm prep` for full environment setup and `pnpm prep --link` (or `pnpm verify --link`) to also link `docmd` globally. - **PWA Plugin is now an optional plugin and no longer auto-included**, if you want to add PWA to your docs, use `docmd add pwa` command. ## Migration Guide Upgrade by running `npm install docmd@latest`. Then: 1. **You may remove** core plugins from your `plugins` array if you were using them with default settings - they are now automatically enabled! 2. If you use third-party plugins by shorthand, update them to their full package name. See [Getting Started - Installation](../getting-started/installation) for a full walkthrough. --- ## [Release Notes - 0.7.1](https://docs.docmd.io/07/release-notes/0-7-1/) --- title: "Release Notes - 0.7.1" description: "Dedicated Plugin API package, plugin descriptors, isolation, and capability enforcement." --- The `docmd` 0.7.1 release introduces a major architectural improvement - the plugin system has been extracted into a dedicated `@docmd/api` package, bringing plugin descriptors, crash isolation, and capability enforcement to the ecosystem. ## ✨ Highlights ### 📦 `@docmd/api` - Dedicated Plugin Package The plugin API surface - hook registration, WebSocket RPC dispatch, and source editing tools - now lives in its own dedicated package: `@docmd/api`. ```bash npm install @docmd/api ``` This decouples the plugin ecosystem from the build engine, allowing plugin authors to depend on a lightweight API contract without pulling in the entire `@docmd/core` package. > **Backward Compatible:** All exports from `@docmd/api` are re-exported from `@docmd/core`. Existing code using `@docmd/core` imports continues to work without changes. ### 🛡️ Plugin Descriptors Plugins can now export a `plugin` descriptor declaring their identity and capabilities: ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` The engine validates descriptors at load time - invalid names, versions, or unknown capabilities are rejected immediately for official plugins, and emit warnings for third-party packages. > **Migration Note:** Descriptors are **optional** in 0.7.x. A soft deprecation warning is emitted for plugins without one. This will become a **hard requirement in 0.8.0**. ### 🔒 Plugin Isolation Every hook invocation is now wrapped in a try/catch boundary. A broken plugin cannot crash the build or interfere with other plugins. Errors are logged and collected into a summary displayed at the end of the build: ``` ⚠️ 2 plugin error(s) occurred (build completed) ``` ### 🔑 Capability Enforcement Plugins that declare capabilities can only register for hooks matching those declarations. If a plugin exports a hook it didn't declare, the engine skips it with a warning: ``` Plugin "analytics" exports markdownSetup but didn't declare "markdown" capability - skipped ``` | Capability | Allowed Hooks | Phase | | :--- | :--- | :--- | | `init` | `onConfigResolved` | Init | | `markdown` | `markdownSetup` | Setup | | `head` | `generateMetaTags`, `generateScripts` (head) | Render | | `body` | `generateScripts` (body) | Render | | `build` | `onBeforeParse`, `onAfterParse`, `onPageReady` | Build | | `post-build`| `onPostBuild` | Post-Build | | `dev` | `onDevServerReady` | Dev Server | | `assets` | `getAssets` | Output | | `actions` | `actions` | Interactive | | `events` | `events` | Interactive | | `translations`| `translations` | i18n | Legacy plugins without a descriptor continue to have full access to all hooks. ## 📝 Complete Changelog ### 📦 Architecture - **`@docmd/api` package**: Extracted `loadPlugins`, `createActionDispatcher`, `createSourceTools`, and all plugin/RPC types into `packages/api/`. - **`@docmd/core` re-exports**: All moved API symbols are re-exported from `@docmd/core/src/index.ts` for seamless backward compatibility. - **Dead code removal**: Deleted the original `plugin-loader.ts`, `action-dispatcher.ts`, `source-tools.ts`, and `types.ts` from `@docmd/core` after migration. ### 🔌 Plugin System - **Plugin Descriptor** (`plugin` export): Name, version, and capability declaration. - **Validation (§1)**: Strict enforcement for `@docmd/plugin-*` packages; soft warnings for third-party plugins. - **Isolation (§2)**: `safeCall()` wrappers around all synchronous hooks; async try/catch for `onPostBuild`. - **Capability Enforcement (§3)**: Hook registration gated by declared capabilities. - **Expanded Lifecycle Hooks (§4)**: Introduced `onConfigResolved`, `onDevServerReady`, `onBeforeParse`, `onAfterParse`, and `onPageReady` to handle complex site integration. - **Error Summary**: Plugin errors are collected and displayed as a count at the end of the build, without halting the process. ### 🐛 Bug Fixes - **404 page raw key display**: Fixed an issue where the 404 page could display `errorCode404` as literal text when translations failed to load. The error code is now hardcoded as `404`. - **i18n `stringMode` script leak**: Fixed `no-style.ejs` injecting the `docmd-i18n-strings.js` runtime when `stringMode` is active. The client-side locale runtime is now correctly suppressed in string mode. - **Plugin resolution in pnpm workspaces**: Fixed `loadPlugins` failing to locate `@docmd/plugin-*` packages when called from `@docmd/api` - the function now accepts `resolvePaths` from the caller to support pnpm's strict `node_modules` layout. ## ⚠️ Breaking Changes ### Plugin API Import Path (Recommended Migration) The canonical home for the plugin API is now `@docmd/api`. While `@docmd/core` re-exports everything for backward compatibility, **plugin authors are encouraged to update their imports**: ```diff -import { createActionDispatcher, createSourceTools } from '@docmd/core'; +import { createActionDispatcher, createSourceTools } from '@docmd/api'; ``` ```diff -import type { PluginModule, ActionContext, SourceTools } from '@docmd/core'; +import type { PluginModule, ActionContext, SourceTools, PluginDescriptor, Capability } from '@docmd/api'; ``` > **No action required for end users.** This only affects plugin developers who directly import API utilities. The `@docmd/core` re-exports will remain available indefinitely. ### Threads Plugin Peer Dependency The `@docmd/plugin-threads` package now peer-depends on `@docmd/api` instead of `@docmd/core`. If you install Threads manually (rather than via `docmd add threads`), ensure `@docmd/api` is available in your dependency tree. ## Migration Guide For **end users**: No changes required. `npm install docmd@latest` is sufficient. For **plugin authors**: 1. **Add a plugin descriptor** to your default export (optional now, required in 0.8.0): ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, // ... hooks }; ``` 2. **Update imports** from `@docmd/core` to `@docmd/api` for `createActionDispatcher`, `createSourceTools`, `loadPlugins`, and all type exports. 3. **Update peer dependencies** from `@docmd/core` to `@docmd/api` in your `package.json` if your plugin uses the RPC or source editing APIs. See [Building Plugins](../../plugins/building-plugins) for the full updated API reference. --- ## [Release Notes - 0.7.2](https://docs.docmd.io/07/release-notes/0-7-2/) --- title: "Release Notes - 0.7.2" description: "Introducing config-aware 'docmd deploy', production security headers, and the 7-pillar failsafe verification engine." --- The `docmd` 0.7.2 release introduces the **`docmd deploy`** command : a config-aware deployment scaffolder that reads your project and generates production-ready server configurations tailored to it. No other documentation tool does this. Docusaurus, VitePress, MkDocs - they all leave you to write your own Dockerfiles and server configs from scratch. `docmd` reads your `docmd.config.js` (or its zero-config defaults) and generates files that are ready to ship. ## ✨ `docmd deploy` : Config-Aware Deployment Run a single command and get production-ready deployment files personalised to your project: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # nginx.conf docmd deploy --caddy # Caddyfile ``` ### What Makes It Smart The deploy command **reads your configuration** before generating anything. It extracts: - **Project title** - stamped into every generated file as a header comment - **Output directory** (`out`) - used in `COPY` paths, `root` directives, and file server configs instead of hardcoded values - **Site URL** (`url`) - extracted hostname is injected as `server_name` (Nginx) or the Caddy site address - **SPA mode** (`layout.spa`) - only generates `try_files` SPA fallback routing when SPA mode is active - **Config file path** - if you use a non-default config name, the Dockerfile build step runs `docmd build --config your-config.js` If no `docmd.config.js` exists, the command still works - it falls back to the same zero-config defaults that `docmd dev` and `docmd build` use. ### Always In Sync Every run regenerates the deployment files to match your current configuration. Changed your `url` or `out` directory? Just run `docmd deploy --nginx` again. No `--force` flag needed for updates - your configs always reflect the latest state of your project. ### Generated File Quality - **Docker**: Multi-stage builds with `package.json` layer caching and exact `@docmd/core` version pinning for reproducible builds - **Nginx**: Security headers (`X-Content-Type-Options`, `X-Frame-Options`), GZIP compression, immutable asset caching - **Caddy**: Automatic HTTPS-ready addressing, security headers, SPA routing, static asset caching ## 🛡️ The 7-Pillar Failsafe Our internal verification engine has been refactored into **7 logical pillars of stability**. This includes a new **Dynamic Integrity Engine** that catches version mismatch regressions instantly across the entire monorepo. ## 🌍 Global Ecosystem Expansion Major localisation updates in this release: - **Native Language Support**: Built-in UI translations for **German, Spanish, Japanese, and French** added to the core engine - these locales work out-of-the-box for all UI components. - **Full German Translation**: The entire documentation suite is now available in German (`/de/`). ## 📝 Complete Changelog ### 🚀 Features & Enhancements - **New Command**: `docmd deploy` with `--docker`, `--nginx`, `--caddy` targets. - **Config-Aware Scaffolding**: Deploy command reads `docmd.config.js` (or zero-config defaults) and personalises generated files with project title, output directory, hostname, SPA mode, and config path. - **Always Fresh Configs**: Deployment files regenerate on every run to stay in sync with config changes. - **Docker Scaffolding**: Multi-stage Dockerfile with `package.json` layer caching and version-pinned `@docmd/core`. - **Web Server Scaffolding**: Hardened Nginx and Caddy templates with security headers, GZIP, and intelligent 404/SPA routing. - **Unified Config Labels**: All internal modules (SEO, sitemap, LLMS, PWA, deployer, generator) now use the modern config keys (`config.title`, `config.url`, `config.out`, `config.src`) instead of scattered legacy fallbacks. Defaults are defined once in `normalizeConfig` - the single source of truth. - **Failsafe**: Consolidated verification logic into a faster, more professional 7-stage pipeline. - **Versioning**: New integrity engine automatically flags outdated internal workspace references. - **SEO Plugin**: Fully respects the `titleAppend` frontmatter property for social media (OG/Twitter) metadata. - **Native Support**: Added built-in UI translations for **German, Spanish, Japanese, and French** to the core engine. - **Localisation**: Added comprehensive **German** translation and optimised **Chinese** translation for the documentation site. ### 🐛 Bug Fixes - **Deploy CLI**: Fixed argument parsing when running through `pnpm` proxy scripts with `--cwd`. - **Deploy UX**: Unknown arguments now show a helpful usage summary instead of a raw error with exit code 1. - **Caddy Config**: Corrected Cache-Control header syntax (quoted values) for Caddyfile compatibility. - **Bump Script**: Fixed a regex `lastIndex` bug in `scripts/bump.js` that caused inconsistent version replacements. - **CLI Safety**: Added proper async error handling to all deployment command entry points. - **Live Editor**: Fixed mobile overflow issues and template switching state tracking. ## Migration Guide For **end users**: No breaking changes. Update and try `docmd deploy` to generate deployment configs tailored to your project. For **plugin authors**: No changes required. --- ## [Release Notes - 0.7.3](https://docs.docmd.io/07/release-notes/0-7-3/) --- title: "Release Notes - 0.7.3" description: "Introducing code block titles, the multi-service migration engine, interactive Mermaid diagrams with Lucide icons, and first-class Bun ecosystem support." --- The `docmd` 0.7.3 release delivers significant new authoring capabilities, a production-grade migration engine for users switching from competing platforms, and a complete overhaul of the Mermaid diagram rendering pipeline. We have also unified the icon rendering logic across all interactive containers and introduced deeply contextual pagination logic. ## ✨ Highlights ### 🚀 Multi-Service Migration Engine We have replaced the legacy internal config migration tool with a full-featured **migration engine** that can move your entire documentation project from a competing platform to `docmd` in a single command. ### Supported Sources | Source | Command | Config Detected | |---|---|---| | **Docusaurus** | `npx @docmd/core migrate --docusaurus` | `docusaurus.config.js` / `.ts` | | **MkDocs** | `npx @docmd/core migrate --mkdocs` | `mkdocs.yml` | | **VitePress** | `npx @docmd/core migrate --vitepress` | `.vitepress/config.[js\|ts\|mjs]` | | **Astro Starlight** | `npx @docmd/core migrate --starlight` | `astro.config.mjs` / `.ts` | Each migration will: 1. Detect the source project's configuration file and extract the site title. 2. Safely move all existing files into a `<source>-backup/` directory. 3. Copy the documentation source files (`docs/`, `src/content/docs/`, etc.) into `docmd`'s standard `docs/` structure. 4. Generate a ready-to-use `docmd.config.js` with sensible defaults. ```bash cd my-docusaurus-site npx @docmd/core migrate --docusaurus npx @docmd/core dev ``` > **Note:** Because every documentation platform handles complex logic like sidebars, versioning, and internationalization (i18n) via proprietary code or APIs, `docmd` does not attempt to auto-translate these configurations to avoid breaking your build. The migration engine focuses purely on safely moving your Markdown content and assets, while leaving the setup of `navigation.json` and `localisation` to you via `docmd`'s simple native APIs. Read our new comprehensive [Migration Guides](/migration/overview) to see exactly what gets migrated and the easy steps required to map your previous tool's configuration to `docmd`. ### 📝 Code Block Titles You can now add a descriptive **filename or title** to any fenced code block by placing a quoted string after the language identifier. This renders a clean, Mintlify-style header bar above the code. ````markdown ```javascript "config.js" export default { title: "My Site" }; ``` ```` The title is rendered as a semantic label (not a heading), so it will never appear in the Table of Contents or interfere with your page structure. ### 📊 Interactive Mermaid Diagrams We have completely overhauled how `docmd` renders Mermaid diagrams, turning static SVGs into deeply interactive visual elements. - **Smart Scaling**: Diagrams are rendered at full Mermaid quality and then intelligently scaled to fit the content width using CSS transforms, preserving all label and edge positioning. - **Pan & Drag**: Click and drag to pan across large diagrams. - **Zoom Controls**: Dedicated zoom in/out buttons appear on hover for precise inspection. - **Fullscreen Mode**: A native fullscreen toggle allows users to expand complex charts for distraction-free viewing. - **Lucide Icon Integration**: The Lucide icon pack is registered directly into the Mermaid engine (`icon:icon-name`), enabling rich architecture diagrams with the same icons used in your sidebar and tabs. - **Dark Mode**: Diagrams and their containers now render correctly in dark mode with properly themed borders and backgrounds. ### ✨ Isomorphic Container Icons We have refactored the core parser to use a shared **Container Integrity Engine**. This ensures that all interactive elements - Callouts, Cards, Collapsibles, and now **Tabs** - support a unified `icon:name` syntax. ### Icons in Tabs You can now add any Lucide icon directly to your tab labels, providing immediate visual context to your users. This is particularly useful for differentiating between package managers, operating systems, or programming languages. ```markdown ::: tabs == tab "npm" icon:box npx @docmd/core dev == tab "Bun" icon:zap bunx docmd dev ::: ``` All icons are rendered as optimised inline SVGs, maintaining `docmd`'s commitment to zero-layout-shift and sub-100ms navigation performance. ### ⚡ First-Class Bun Support Following the rapid adoption of the Bun runtime, we have updated all core documentation and "Getting Started" guides to include native Bun examples. - **`bunx` support**: All one-off commands now include `bunx` alternatives alongside `npx`. - **Dependency management**: Installation guides now cover `bun add` workflows for project-level integration. - **Documentation Parity**: English, Chinese, and German guides have been synchronised to ensure a consistent experience regardless of your preferred runtime or language. ### 🧭 Contextual Pagination Navigation The Next and Previous page pagination links at the bottom of articles have received a major intelligence upgrade. Previously, these links defaulted to generating URLs for the primary locale and latest version, which disrupted the user experience when browsing translated docs or archived versions. The Core Engine now natively understands the `outputPrefix` context, ensuring that your readers stay perfectly within their current language and version silo as they navigate sequentially through your documentation. ### 🎨 Visual Refinements - **Softer Code Blocks**: All code blocks now feature softer `border-radius` corners and subtle box shadows for a more premium aesthetic. - **Dark Mode Code Borders**: Added a dedicated `--border-colour-codeblock` variable for dark mode, fixing invisible borders on code blocks and diagram containers. - **Mermaid Container Chrome**: Diagrams are now wrapped in a bordered, padded container with consistent styling across light and dark themes. ### 🛠️ Internal Refactoring This release includes a significant architectural cleanup of the `docmd/parser` package: - **Refactored Utility Layer**: Moved `parseTitleAndIcon` into a central `container-helper` utility. This eliminates logic duplication between the `tabs` and `common-containers` modules. - **Custom Fence Renderer**: Code block titles are implemented via a markdown-it fence renderer override, ensuring titles are never misinterpreted as content headings. - **Performance Optimisation**: The shared helper uses optimised regex patterns to reduce the overhead of parsing large documents with many interactive containers. ## 📝 Complete Changelog ### 🚀 Features & Enhancements - **Migration Engine**: New `docmd migrate` command supporting Docusaurus, MkDocs, VitePress, and Astro Starlight. - **Code Block Titles**: Added `language "title"` syntax for filename headers on fenced code blocks. - **Tabs Icons**: Added support for `icon:name` syntax in the `== tab` sub-delimiter. - **Shared Parser Logic**: Created a unified `container-helper` utility for parsing titles and icons across all containers. - **Mermaid Interactive Controls**: Diagrams now feature native pan, zoom, and fullscreen capabilities with smart transform-based scaling. - **Mermaid Icons**: Registered the Lucide icon pack within the Mermaid rendering engine. - **Context-Aware Pagination**: Next/Previous links now automatically respect the active locale and version silos. - **Bun Ecosystem**: Comprehensive update to all Getting Started and Installation guides to include Bun/bunx examples. - **Dark Mode Code Borders**: Added `--border-colour-codeblock` dark mode variable for proper border visibility. - **Visual Consistency**: Standardised icon sizes and alignment within tab navigation bars. ### 🐛 Bug Fixes - **Navigation Sync**: Fixed an inconsistency in the Chinese (`zh`) navigation where a legacy "Recipes" section was incorrectly visible. - **Code Block Title Rendering**: Fixed a critical bug where titles after the language identifier were being parsed as markdown headings instead of being captured as code block labels. - **Mermaid Scroll Hijacking**: Fixed an issue where mouse wheel scrolling was blocked when hovering over Mermaid diagrams. - **Mermaid Dark Mode**: Fixed invisible diagram container borders in dark mode. - **Parser Robustness**: Fixed an edge case where nested containers within tabs could occasionally fail to render if they contained specific Markdown-it fence markers. - **Locale Consistency**: Corrected several technical translation inaccuracies in the German `content-ux` guides. ## Migration Guide For **end users**: No changes required. `npm update @docmd/core` is sufficient. For **plugin authors**: If you were manually parsing tab headers, we recommend switching to the exported `parseTitleAndIcon` utility from `@docmd/parser` to maintain compatibility with future icon enhancements. For **users of other documentation platforms**: Run `npx @docmd/core migrate --help` to see all available migration sources and get started in seconds. --- ## [Release Notes - 0.7.4](https://docs.docmd.io/07/release-notes/0-7-4/) --- title: "Release Notes - 0.7.4" description: "Introducing context-aware version filtering for offline search, plus Mermaid icon rendering standardisation." --- The `docmd` 0.7.4 release introduces a powerful new feature to our offline search plugin: **Context-Aware Version Filtering**. It also includes a hotfix for Mermaid icon rendering and syntax standardisation. ## ✨ Highlights ### 🔍 Version Filtering in Search When building documentation with multiple versions, finding the right information can be challenging. The built-in search modal now natively understands version silos and automatically generates a dynamic filter bar. - **Smart Version Detection**: The search engine automatically extracts all available versions from your index and generates clickable filter tags. - **Colour-Coded Tags**: Each version tag is automatically assigned a unique, aesthetically pleasing colour from a predefined palette to help users visually distinguish between different documentation silos. - **Real-Time Toggling**: Users can click tags to instantly narrow down their search results to one or multiple specific versions, providing a much cleaner and more accurate search experience. ### 🏷️ Inline Tags Container We've introduced a brand new `tag` container! This is a self-closing, inline component designed for inserting pill-shaped badges directly into your text or headings. - **Fully Customisable**: Override default colours with any CSS colour string (`color:#ef4444`). - **Icon Support**: Attach any Lucide icon (`icon:check-circle`) directly to the tag. - **Hyperlinks**: Easily turn tags into links using the `link:` attribute. - **Heading-Safe**: Tags automatically align to the baseline without inheriting massive font sizes when used inside `<h1>` or `<h2>` elements. ## 🐛 Bug Fixes - **Mermaid Icon Registration**: Fixed an issue where the Lucide icon pack was not properly decoupled from the user-facing syntax in Mermaid flowcharts. - **Architecture Syntax Support**: We have officially migrated our documented Mermaid icon support to use Mermaid's native `architecture` and `architecture-beta` diagram types, which support inline Iconify nodes perfectly. ## 🛡️ Security - **Dependency Audit**: Addressed multiple security advisories by forcefully upgrading deeply nested sub-dependencies across the monorepo (`cross-spawn`, `dompurify`, `lodash-es`, `uuid`, and `mermaid`). The entire engine ecosystem is now 100% clean and vulnerability-free. ## ✨ Standardised Icon Syntax To abstract the underlying icon library (currently Lucide) from your diagrams, we have registered the pack generically as `icon`. This means that instead of explicitly tying your documentation to `lucide:`, you should now use `icon:`. This future-proofs your diagrams - if we ever expand or change the underlying icon library in `docmd`, your diagrams will automatically inherit the updates without any changes required on your end! **Example:** ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Database] in api service disk(icon:hard-drive)[Storage] in api db:L -- R:disk ``` ## Migration Guide For **end users**: Update to the latest patch with `npm update @docmd/core`. If you previously used `lucide:` in your Mermaid diagrams, please replace it with the new `icon:` prefix. --- ## [Release Notes - 0.7.5](https://docs.docmd.io/07/release-notes/0-7-5/) --- title: "Release Notes - 0.7.5" description: "Security patch and i18n optimisation: eliminates uuid vulnerability, adds language switcher failsafes, and introduces build-time page manifests for zero-latency locale switching." --- The `docmd` 0.7.5 release combines a security fix with significant i18n optimisations. It eliminates the upstream `uuid` vulnerability from the Mermaid plugin, adds multi-layer failsafes to the language switcher, and introduces a **build-time page manifest** that replaces all runtime network checks with instant local lookups. ## 🛡️ Security ### Mermaid Plugin - Dependency Tree Fix The `@docmd/plugin-mermaid` package previously declared `mermaid` as a production `dependency`. This caused the vulnerable transitive sub-dependency `uuid@<14.0.0` to be installed in every consumer's `node_modules`, even though the package never uses it at runtime. **Root Cause**: The mermaid library is loaded exclusively from a CDN at runtime in the browser. The npm `mermaid` package was only needed during development for TypeScript type-checking and the esbuild bundling step. It was incorrectly categorised as a production dependency. **Fix**: `mermaid` has been moved from `dependencies` to `devDependencies` in `@docmd/plugin-mermaid`. The published package now ships with **zero production dependencies**, so `mermaid` and its vulnerable `uuid` sub-dependency are never installed for end users. - `npm audit` / `pnpm audit` now reports **0 vulnerabilities** for projects using `@docmd/plugin-mermaid`. - No functional changes - the mermaid rendering pipeline is completely unaffected. ## 🌐 i18n - Language Switcher Failsafe Previously, if a locale was declared in `i18n.locales` but its source directory (e.g. `docs/hi/`) did not exist, the language switcher would still render it as clickable - leading to a **404** when selected. **Fix**: The engine now **pre-scans locale directories** at build time. Locales without a source directory are automatically disabled in the language switcher with an **N/A** badge, `aria-disabled` attribute, and non-clickable state. - **Build-time detection**: The engine checks which locale directories actually exist before any pages are rendered. - **Template-level disabling**: Unavailable locales appear greyed out with an "N/A" badge and `href="#"`. - **Client-side guard**: Clicking a disabled locale is a no-op - no navigation, no 404. - **Chained fallback**: If a locale is available but a specific page is missing, the engine falls back to the default locale's version of that page with a localised warning callout. ## ⚡ i18n - Build-Time Page Manifest Previously, the language switcher used `fetch(url, { method: 'HEAD' })` to verify whether a page existed in the target locale before navigating. This added latency, broke on some CDNs, and didn't work offline. **Fix**: The engine now generates a **page manifest** at build time - a tiny JS file (`docmd-i18n-manifest.js`) that maps every locale to its available page paths. The client-side switcher reads this manifest synchronously. - **Zero network requests**: Page existence is checked locally from the manifest - no HEAD fetches. - **Works offline**: The manifest is bundled with the site assets. - **CDN-agnostic**: No dependency on how the hosting provider handles HEAD requests. - **Graceful degradation**: If the manifest fails to load, the switcher falls back to HEAD fetches automatically. ::: callout info When i18n is enabled, each locale **must** have its own subdirectory under the source directory (e.g. `docs/en/`, `docs/hi/`). The default locale's directory is required as the fallback source for partially translated locales. ::: ## i18n Failsafe - How docmd Compares | Capability | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | Per-page fallback to default locale | ✅ | ❌ (404) | ❌ (404) | ✅ | | Localised "not translated" warning | ✅ | ❌ | ❌ | ✅ | | Auto-disable missing locales in switcher | ✅ | ❌ | ❌ | ❌ | | Client-side navigation guard | ✅ | ❌ | ❌ | ❌ | | Versioning + i18n combined | ✅ | ❌ | ❌ | ❌ | | Old version backward compat (no locale dirs) | ✅ | N/A | N/A | N/A | | RTL direction support | ✅ | ✅ | ✅ | ✅ | | Zero-config (no custom React/Vue) | ✅ | Partial | ❌ | ✅ | VitePress and Docusaurus both return **404 errors** when a page is missing in a non-default locale - requiring manual server-side redirects or custom components to handle gracefully. Starlight (Astro) provides per-page fallback with a translation notice, similar to docmd - but does not auto-disable missing locale directories or guard against client-side navigation to non-existent locales. ## Migration Guide For **end users**: Update to the latest patch with `npm update @docmd/plugin-mermaid` or `pnpm update @docmd/plugin-mermaid`. No configuration changes are required. --- ## [Release Notes - 0.7.6](https://docs.docmd.io/07/release-notes/0-7-6/) --- title: "Release Notes - 0.7.6" description: "Unified URL normalisation engine, universal external: and raw: link prefixes, SEO trailing-slash enforcement, SPA hash navigation fix, and silent plugin warnings in dev mode." --- The `docmd` 0.7.6 release introduces a **unified URL normalisation engine** that eliminates 301 redirects, enforces trailing-slash URLs for SEO, and brings consistent link handling across every surface. ## ✨ Highlights ### Unified URL Normalisation All URL handling now routes through a single `resolveHref()` function in `@docmd/parser`. Trailing-slash enforcement, `index.md` stripping, and double-slash prevention are applied consistently across Markdown links, button containers, navigation, and menubar. - **Eliminate 301 Redirects**: URLs like `/configuration/overview` resolve to `200` directly at `/configuration/overview/`. - **No Path Artefacts**: No `/index` remnants or `.md` extensions in any rendered link. - **Hreflang Accuracy**: Alternate tags now correctly strip locale prefixes from page paths. See the [Linking & Referencing](https://docs.docmd.io/content/syntax/linking/) guide for the full URL translation table. ### Universal `external:` and `raw:` Prefixes We've introduced two new magic prefixes to give you total control over link behaviour across all `docmd` components. - **`external:` - Force New Tab**: Add this to any link (Markdown, Buttons, Menubar) to force it to open in a new tab. - **`raw:` - Bypass Normalisation**: Use this when you need to link to a file (like `template.md`) without the engine stripping its extension. ```markdown [Open in new tab](external:./configuration/overview.md) ::: button "API Docs" external:./api/node-api.md [Download Template](raw:templates/starter.md) ``` **Behaviour change**: HTTP/HTTPS links no longer auto-open in a new tab. Use `external:` explicitly when you want that behaviour. ### Centralised URL API for Plugins A new URL utility layer in `@docmd/parser` is re-exported via `@docmd/api`. Plugins no longer need to parse `outputPath` manually - the engine pre-computes clean URLs for every page: ```typescript import { outputPathToSlug, sanitizeUrl } from '@docmd/api'; export async function onPostBuild({ pages }) { for (const page of pages) { page.urls.slug; // "guide/" page.urls.canonical; // "https://example.com/guide/" page.urls.pathname; // "/guide/" } } ``` See the [Plugin Development](https://docs.docmd.io/advanced/plugins/) guide for the full API reference. ## 🔧 Developer Experience ### Silent Plugin Warnings in Dev Mode Previously, a missing or misconfigured plugin would print a warning on **every file change** during `docmd dev`. These warnings are now **printed once** per dev session and suppressed on subsequent rebuilds to keep your terminal clean. ``` ↻ Change in docs/en/guide.md... ⚠️ Could not load plugin: @docmd/plugin-math Done. ``` ### SPA Hash Navigation Fixed In SPA mode, clicking a `#heading` anchor on the current page now scrolls smoothly to the target element. Browser back/forward through hash history (via `popstate`) also scrolls correctly. ```markdown [Jump to Configuration](#configuration) <!-- now working in SPA mode --> ``` ## 🚀 SEO Improvements - **Trailing Slashes**: All internal URLs rendered with trailing slashes to eliminate 301 redirect chains. - **Clean paths**: Canonical and hreflang `<link>` tags use correct normalised paths. - **Zero Artefacts**: No `.md` extensions or `/index` fragments in production HTML. ## Migration Guide Update with `npm update @docmd/core` or `pnpm update @docmd/core`. No configuration changes required. ::: callout info If you have custom server-side redirect rules that strip trailing slashes, remove them. The engine now produces the canonical trailing-slash format natively. ::: --- ## [Release Notes - 0.7.7](https://docs.docmd.io/07/release-notes/0-7-7/) --- title: "Release Notes - 0.7.7" description: "Introducing multi-project support, the Universal TUI Design System, and a premium, emoji-free terminal experience for professional documentation workflows." --- The `docmd` 0.7.7 release introduces **multi-project support** - the ability to orchestrate multiple independent documentation sites from a single repository. Alongside this architectural shift, we are debuting the **Universal TUI Design System**, a complete modernisation of our terminal interface that delivers a premium, high-signal developer experience through a new standalone styling package. ## ✨ Highlights ### Multi-Project Support You can now build and serve multiple independent documentation sites from a single `docmd` instance. A single root configuration allows you to define multiple projects, each with its own prefix, independent versioning, and isolated navigation, while sharing a unified theme and deployment pipeline. ```javascript // docmd.config.js (root) import { defineConfig } from '@docmd/api'; export default defineConfig({ projects: [ { prefix: '/', src: 'docmd-main' }, { prefix: '/search', src: 'docmd-search' } ] }); ``` Each project maintains its own directory structure and configuration, allowing you to manage complex documentation ecosystems (e.g., a core engine and its satellite tools) under a single domain without version conflicts. ### Universal TUI Design System We have completely rebuilt the `docmd` terminal interface to provide a professional, high-signal experience. Moving away from "playful" emojis, the new system uses refined box-drawing characters and a curated colour palette to deliver clear, actionable feedback. - **Improved Branding**: Centralised ASCII logo definition within the TUI system ensures a consistent brand presence across all CLI interactions. - **High-Signal Output**: Logs are now structured using a clean, tabular aesthetic that prioritises readability in both local development and CI/CD environments. - **Consistency**: Whether you are building a site, running a dev server, or using a migration tool, the terminal experience remains perfectly unified. ### Standalone `@docmd/tui` Package To support this new design system, we have decoupled terminal aesthetics from the core logic into a dedicated `@docmd/tui` package. This architectural shift eliminates circular dependencies and allows plugin authors to consume the same professional UI components as the core engine. By centralising our "Terminal User Interface" logic, we ensure that every piece of output - from core build logs to third-party plugin warnings - follows the same premium design language. ### Emoji-Free Professionalism In line with our commitment to a premium developer experience, 0.7.7 transitions to an **emoji-free standard**. We've replaced legacy emoji-based status markers with a sophisticated box-drawing aesthetic. This change ensures that `docmd` looks and feels like a production-grade tool, providing a cleaner interface that integrates easily into professional IDEs and terminal emulators. ### Intelligent Config Validation Configuration errors no longer leak Node.js stack traces. We've enhanced real-time configuration feedback using standardised TUI components to provide clean, human-readable error messages. The validator now detects multi-project root configurations and provides specific guidance for missing properties or typos. When a configuration error occurs, `docmd` now presents a clear "Error Report" with exact line references and suggested fixes, ensuring you spend less time debugging and more time writing. ### Multi-Project Dev Server The `docmd dev` command has been upgraded to support multi-project orchestration. It builds all projects and serves them from a single port, with intelligent file watching that triggers targeted rebuilds for the specific project being edited. ``` ──────────────────────────────────────── MULTI-PROJECT DEV SERVER Local: http://127.0.0.1:3000 Network: http://192.168.1.5:3000 Project: / → docmd-main/ Project: /search → docmd-search/ ──────────────────────────────────────── ``` ## 🛠️ Internal Refactoring This release includes significant architectural hardening to support the new TUI and multi-project capabilities: - **Dependency Architecture**: Optimised package dependencies to ensure a strictly directed acyclic flow, preventing circular imports between the engine and UI layers. - **Logger Refactoring**: Fully deprecated legacy logger utilities in favour of the centralised TUI system. - **Project Orchestration**: The multi-project handler lives in a standalone module that safely manages directory contexts (`chdir`) and merges independent outputs into a unified site structure without modifying the existing build pipeline. ## 📝 Complete Changelog ### Features & Enhancements - **Multi-Project Engine**: Support for `projects[]` in root configuration with shared assets and independent versioning. - **Universal TUI**: Rebuilt terminal interface using box-drawing characters and professional styling. - **Standalone TUI Package**: New `@docmd/tui` library for unified CLI aesthetics across the monorepo. - **Improved Branding**: Introduced a centralised ASCII logo for all CLI entry points. - **Config Validation**: Enhanced real-time feedback with human-readable error reports and no stack traces. - **Dependency Optimisation**: Strictly enforced acyclic dependency flow across all internal packages. ### Cleanups & Removals - **Emoji-Free Standard**: Removed all legacy emoji-based terminal output. - **Redundant Logs**: Eliminated ad-hoc `chalk` and `console.log` calls in favour of the TUI logger. - **Legacy Utilities**: Removed deprecated internal logger helpers. ## Migration Guide ### For Existing Projects **Existing single-project setups require no changes.** The engine continues to support the standard single-project workflow by default. ### Adopting Multi-Project Support To transition to a multi-project setup: 1. Move your existing documentation source into a subdirectory. 2. Create a root `docmd.config.js` and define your projects using the `projects` array. 3. Remove redundant `src` and `out` paths from child configurations, as the root orchestrator now manages these. We recommend migrating any custom `console.log` or `chalk` statements to the new `@docmd/tui` package to ensure your plugin's output matches the core `docmd` aesthetic. --- ## [Release Notes - 0.7.8](https://docs.docmd.io/07/release-notes/0-7-8/) --- title: "Release Notes - 0.7.8" description: "Introducing the Git plugin, a redesigned high-signal terminal interface with live progress tracking, parallel page processing for significantly faster builds, auto-installation for official plugins, and container syntax compatibility." --- The `docmd` 0.7.8 release introduces the **Git plugin** for repository-aware metadata, a completely **redesigned terminal interface** with live progress feedback, **parallel page processing** for dramatically faster builds, **automatic plugin installation** for official plugins, and **container syntax compatibility** for users migrating from other documentation engines. ## ✨ Highlights ### Build Engine - Parallel Processing The page rendering pipeline has been redesigned from sequential to **batched parallel processing**, delivering significant speedup on documentation sites of all sizes. **What changed:** - **Batched file I/O**: Files are now read 64 at a time and written 128 at a time via `Promise.all`, instead of one-by-one sequential reads - **Pipeline overlap**: File reading, markdown parsing, and HTML writing phases now overlap across batches - **Parallel writes**: All rendered HTML files are written to disk concurrently in batches instead of sequentially **Projected performance (simple pages):** | Scale | Before (0.7.7) | After (0.7.8) | Improvement | | :--- | :--- | :--- | :--- | | ~1,000 pages | ~22s | ~12s | **~45% faster** | | ~10,000 pages | ~4 min+ | ~1.5 min | **~60% faster** | | File read phase | Sequential | 64-file batches | **64x concurrency** | | File write phase | Sequential | 128-file batches | **128x concurrency** | | Progress feedback | None (silent) | Live progress bar | Real-time | The performance improvement scales with documentation size. Larger sites (1,000+ pages) with heavy I/O benefit the most from batched parallel processing. ### Terminal Interface - Unified TUI All terminal output has been redesigned into a **unified, high-signal design system** shared across every command. No more silent waits, inconsistent formatting, or cluttered multi-line output. **New TUI primitives:** | Feature | Description | | :--- | :--- | | **Progress bar** | `━━━━━━━━━━━━───────── 42/100 (42%)` - single-line, updates in-place | | **Spinner** | `⠋ ⠙ ⠹` - braille-dot animation during long operations | | **Timer** | Every build, rebuild, and project shows elapsed time | | **Sections** | Consistent `┌─ Section / └──` framing across all commands | **Unified output across all commands:** <img width="640" alt="image" src="https://github.com/user-attachments/assets/4d5a780b-73c1-4b6b-bd83-99837c09362f" /> **Commands unified:** - **`docmd build`** - section header with source/output/versions/locales, progress bar, timing - **`docmd dev`** - animated spinner during initial build and rebuilds, timing per-rebuild - **Multi-project builds** - per-project spinner animation, per-project timing, total summary - **`docmd live`** - consistent section framing matching all other commands ### Git Plugin The new **Git plugin** brings repository-aware metadata to your documentation pages, last-updated timestamps, commit history tooltips, and edit links, all derived directly from your Git history with zero configuration. ```javascript // Configure edit links plugins: { git: { repo: 'https://github.com/your-org/docs', branch: 'main' } } ``` **Features:** - **Last Updated Timestamps**: Shows when each page was last modified, using relative formatting for recent changes - **Commit History Tooltip**: Hover to see recent commits with author names and messages - **Edit Links**: Automatically constructs "Edit this page" links for GitHub, GitLab, and Bitbucket - **Graceful Degradation**: Automatically disables itself if the project is not in a Git repository The plugin replaces the legacy `editLink` configuration option with a more feature-rich alternative. See the [Git plugin documentation](https://docs.docmd.io/plugins/git/) for full details. ### Auto-Installation for Official Plugins Official plugins listed in your `docmd.config.js` are now automatically installed if missing. When you add a plugin to your config that isn't installed, docmd downloads it from npm on the next build. ```javascript // docmd.config.js plugins: { pwa: {}, // Not installed? docmd auto-installs it threads: {} // Same here } ``` **Security features:** - Only works for official `@docmd/plugin-*` packages in the registry - Installs the exact version matching your `@docmd/core` version - Uses your project's package manager (npm, pnpm, yarn, or bun) - Shows progress in the terminal ### Container Syntax Compatibility Users migrating from **VitePress**, **Docusaurus**, or similar documentation engines can now use familiar container syntax without modification. **VitePress-style containers now work:** ```markdown :::tip This renders as a tip callout. ::: :::warning This renders as a warning callout. ::: :::details Click to expand This renders as a collapsible section. ::: ``` **Docusaurus-style containers now work:** ```markdown :::note This renders as an info callout. ::: :::caution This renders as a warning callout. ::: ``` Additionally, **spaceless syntax** is now supported for all containers: ```markdown :::callout info Works the same as ::: callout info ::: :::tabs Works the same as ::: tabs ::: ``` This allows documentation to be migrated from other engines with minimal changes. ### Migration-Friendly Aliases | Alias | Maps To | Origin | | :--- | :--- | :--- | | `:::tip` | `callout tip` | VitePress | | `:::warning` | `callout warning` | VitePress | | `:::danger` | `callout danger` | VitePress | | `:::info` | `callout info` | VitePress | | `:::details` | `collapsible` | VitePress | | `:::note` | `callout info` | Docusaurus | | `:::caution` | `callout warning` | Docusaurus | These aliases work silently alongside the standard `docmd` syntax. Your existing documentation continues to work unchanged, whilst imported content from other engines renders correctly. ## Internal Improvements ### British English Standardisation Documentation has been updated to use British English spelling consistently throughout. This includes terminology like "optimised", "centralised", "localisation", and "colour" where appropriate. ### Code Quality - Replaced em-dashes with standard hyphens across documentation and code comments for improved readability - Standardised comment formatting in source files - Improved TypeScript type definitions for plugin APIs ## 📝 Complete Changelog ### Features - **Git Plugin (Core)**: New core plugin for last-updated timestamps, commit history, and edit links with graceful degradation - **Auto-Install**: Official plugins in config are automatically installed if missing - **Container Aliases**: VitePress and Docusaurus container syntax now works out of the box - **Spaceless Containers**: All containers now accept syntax with or without space after `:::` - **Parallel Processing**: Batched file I/O with 64-file read and 128-file write concurrency - **Unified TUI**: Progress bar, spinner, timer, and consistent section output across all commands ### Improvements - **Build Performance**: Up to ~60% faster builds on large sites through parallel I/O batching - **Live Progress**: Real-time progress bar during page processing - **Animated Spinners**: Visual feedback during builds, rebuilds, and multi-project processing - **Build Timing**: Every operation reports elapsed time - **Git Widget UI**: Tooltip uses CSS `:hover`/`:focus-within` for smooth, jitter-free display - **Code Block Styling**: `docmd-code-block-wrapper` now uses the universal `--shadow-sm` variable, matching all other container blocks - **Live Editor TUI**: Unified section framing and graceful shutdown - **Documentation**: British English spelling standardisation - **Code Style**: Consistent formatting across codebase - **Plugin Registry**: Added Git plugin to official registry ### Deprecations - **editLink Config**: The standalone `editLink` configuration option is deprecated in favour of the Git plugin ## Migration Guide ### Adopting the Git Plugin If you were using the `editLink` configuration, replace it with the `git` plugin. The new approach is smarter, it automatically detects your git repository root and computes the correct file path, so you no longer need to hardcode a directory in the URL. **Before (deprecated):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs' // ← hardcoded dir } }); ``` **After:** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', // ← just the repo, no path needed branch: 'main' } } }); ``` The plugin resolves the correct file path relative to the git root automatically. This means edit links work correctly in monorepos and multi-project setups without any manual path configuration. **Additional options:** | Option | Default | Description | | :--- | :--- | :--- | | `repo` | - | Repository URL (any provider) | | `branch` | `'main'` | Branch to link to | | `editPath` | `'edit'` | URL segment for edit page. Use `'-/edit'` for GitLab, `'src'` for Bitbucket | | `editLink` | `true` | Set `false` to disable the edit link | | `editLinkText` | i18n string | Custom label for the edit link | ### For Users Migrating from Other Engines If you are importing documentation from VitePress, Docusaurus, or similar engines: 1. Your existing `:::tip`, `:::warning`, `:::note` containers will render correctly 2. Spaceless syntax like `:::tabs` works alongside the standard `::: tabs` 3. No changes to your markdown files are required We recommend gradually transitioning to the standard `docmd` syntax (`::: callout tip`) for new content, as it provides more flexibility with titles and icons. --- ## [Release Notes - 0.7.9](https://docs.docmd.io/07/release-notes/0-7-9/) --- title: "Release Notes - 0.7.9" description: "OpenAPI plugin, Plugin API improvements with onBeforeRender hook and sourcePath, Git plugin commit history accuracy fix for multi-project builds, contributor avatars, and smart sticky footer." --- The `docmd` 0.7.9 release introduces **Incremental Rebuilds** for near-instant development, the **OpenAPI plugin**, and major performance optimizations via a **Parallel Plugin Architecture**. It also resolves critical config file leakage, fixes monorepo git history accuracy, adds contributor avatars, and implements a smart sticky footer. ## ✨ Highlights ### OpenAPI Plugin The new **OpenAPI plugin** renders API reference documentation directly from OpenAPI 3.x spec files inside Markdown pages - at build time, with no client-side JavaScript and no third-party UI libraries (no Swagger UI, no Redoc). Add a spec embed anywhere in your Markdown: ````markdown ```openapi ./api/openapi.json ``` ```` The plugin reads the spec at build time and outputs static HTML: colour-coded method badges, parameter tables, request/response schema tables, and status code descriptions. It supports both JSON and YAML specs, resolves internal `$ref` references, and handles `oneOf`/`anyOf` union types. **New in 0.7.9:** Added a `download: true` option to provide direct links to the raw spec file in the UI - perfect for AI models (like GPT-4 or Claude) to consume your API documentation programmatically. ```bash docmd add openapi ``` See the [OpenAPI plugin documentation](../plugins/openapi/) for full details. ### Incremental Rebuilds (Instant Dev Mode) The development server now features a **Targeted Rebuild** system. Previously, editing a single Markdown file triggered a full site rebuild. For sites with hundreds of pages, this could take 10+ seconds. In 0.7.9, `docmd dev` only re-renders the specific file you modified. Page reloads are now **instant (<1s)**, even for massive projects. The system correctly maintains all navigation, versioning, and asset context during these partial updates. ### Parallel Plugin Architecture (Multi-Threaded Performance) The build engine has been overhauled to support **parallel plugin execution**. Previously, plugin hooks like `onBeforeRender` ran sequentially for every page. For plugins that perform I/O or spawn child processes (like the Git plugin), this was a significant bottleneck. In 0.7.9, the engine now processes page rendering in concurrent batches. Combined with the new **Asynchronous Git Plugin**, which uses non-blocking `execFile` calls, build times for large sites with hundreds of pages are up to **3x faster**. **Key improvements:** - **Batched Rendering**: Phase 3 of the generator now runs in parallel batches of 64 pages. - **Async Hooks**: All plugin hooks can now be `async`, and the engine correctly awaits them in parallel. - **Git Plugin Overhaul**: Replaced synchronous `execSync` with asynchronous, non-blocking process spawning. ## 📝 Complete Changelog ### Bug Fixes - **Git Plugin - Per-file commit history in multi-project builds**: Module-level singleton state (`_gitRootPath`) was set once from whichever project docmd processed first, and reused for all subsequent projects. This caused pages in project 2+ to query git history against the wrong repository root, returning empty or mismatched results. The fix resolves the git root per file directory using a per-directory cache, so each file always queries its own repository context - safe for monorepos and multi-project setups. - **Git Plugin - SPA hydration**: The git widget was re-hydrating timestamps on `docmd.afterReload()` (dev-server only). In SPA mode, navigating between pages left timestamps un-formatted. Fixed to listen on `docmd:page-mounted` instead, which fires after every SPA page swap. ### Features - **OpenAPI Plugin (`@docmd/plugin-openapi`)**: Build-time OpenAPI 3.x spec renderer. Outputs static HTML endpoint docs from JSON or YAML spec files. No client-side dependencies. - **Plugin API - `onBeforeRender` hook**: New lifecycle hook called before template rendering. Receives full `PageContext` including `sourcePath`. Mutations to `frontmatter` and `html` are reflected in the rendered output. - **Plugin API - `PageContext` type**: Formally typed and exported from `@docmd/api`. Includes `sourcePath`, `frontmatter`, `html`, `localeId`, `versionId`, and `relativePathToRoot`. - **Git Plugin - Contributor Avatars**: Commit history tooltip now shows Gravatar images (MD5-hashed email, `?d=mp` fallback) instead of initials. - **Git Plugin - Configurable Date Formats**: New `dateFormat` option: `relative` (default), `iso`, or `locale-aware`. ```javascript plugins: { git: { dateFormat: 'locale-aware' } } ``` - **Parallel Build Pipeline**: The generator now parallelises the template rendering phase. Plugins can now perform expensive operations (like Git calls or OpenAPI parsing) concurrently across multiple CPU cores via child processes. - **Asynchronous Git Plugin**: The Git plugin is now fully asynchronous. It uses non-blocking child processes and path normalisation to ensure high performance and accuracy even in complex monorepo structures. - **Incremental Rebuild System**: The dev server now performs targeted partial builds. Editing a file re-renders only that file, reducing reload times from 10s+ to under 300ms for large sites. - **OpenAPI Plugin - Download Spec**: New `download` option provides a link to the raw JSON/YAML spec in the page header for AI accessibility. - **UI - Smart Sticky Footer**: Footer is now always pinned to the bottom of the viewport using flex layout, even on pages with minimal content. (Fixed). ### Internal - **Edit Link Path Resolution**: Computed from the git repository root, not `config.src` or `process.cwd()`. Correct in all project layouts. - **Config Loader - Hardening**: Implemented mandatory cleanup for orphaned temporary config files (`docmd.config-*.js`) and added `try-finally` safety to prevent leakage during syntax errors. --- ## [Assets Management](https://docs.docmd.io/07/theming/assets-management/) --- title: "Assets Management" description: "How docmd handles CSS, JavaScript, and Image assets during the build process." --- `docmd` takes a "Mirror & Map" approach to assets. This ensures that your local development paths stay consistent with your production build. ## Directory Structure By default, `docmd` looks for an `assets/` folder in your project root. ```bash my-docs/ ├── assets/ # Source Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Content ├── docmd.config.js └── site/ # Build Output (Automatically mirrored) ``` ## Automatic Copying When you run `docmd build` or `docmd dev`: 1. **The Mirroring Logic**: The entire contents of your `assets/` folder are recursively copied to `site/assets/`. 2. **Stability**: We use a hardened copy engine with automatic retries to prevent "File Busy" or "ENOENT" errors on macOS and modern SSDs. 3. **Referencing**: You should always reference assets from your Markdown or Config using the **root-relative** path: ```markdown ![Logo](/assets/images/logo.png) ``` ## Custom CSS & JS Integration To link your assets to every page, add them to your theme configuration: ```javascript // docmd.config.js export default { theme: { customCss: ['/assets/css/branding.css'] }, customJs: ['/assets/js/utils.js'] } ``` ::: callout info "AI Recognition Strategy :robot:" * **Organise by type**: Keep `/css`, `/js`, and `/images` separate. This helps AI agents locate relevant styles or scripts instantly when you ask them to "edit the header colour". * **Use Descriptive Filenames**: Naming an image `authentication-flow-diagram.png` provides much more context to the `llms.txt` crawler than `img_01.png`. ::: --- ## [Available Themes](https://docs.docmd.io/07/theming/available-themes/) --- title: "Available Themes" description: "Explore docmd's built-in themes including Sky, Ruby, and Retro. Learn how to switch themes with a single config line." --- `docmd` provides a set of professionally designed, light/dark responsive themes. You can switch your entire site's aesthetic by changing a single key in `docmd.config.js`. ## How to Switch Themes ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system', // Options: 'light', 'dark', 'system' } } ``` ## Built-in Theme Gallery | Theme | Best For | Vibes | | :--- | :--- | :--- | | `default` | Low-profile docs | Clean, lightweight, neutral | | `sky` | Product Docs | Modern, premium, standard-issue | | `ruby` | Brand Identity | Sophisticated, serif headers, vibrant | | `retro` | Dev Tools | 80s Terminals, monospace, neon accents | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` The very theme used for this documentation site. Use this if you plan on adding extensive custom CSS and don't want any built-in design layers interfering. ### 2. `sky` The gold standard for modern documentation. It features crisp typography, subtle transitions, and high-contrast light/dark modes that match modern SaaS platforms. ### 3. `ruby` A high-elegance theme using serif typography for headers and a deep, jewel-toned colour palette. Perfect for documentation that needs to feel authoritative and premium. ### 4. `retro` A nostalgia-fueled theme inspired by vintage computing. Features include phosphor-green text on black backgrounds (in dark mode), scanline effects, and monospace fonts like Fira Code by default. ## Theming Architecture 1. **CSS Layering**: Themes are additive. Choosing `sky` actually loads the base `default` styles and then overlays the `sky` aesthetic on top. 2. **Native dark-mode**: Every theme includes a first-class dark mode implementation. 3. **No Refresh**: When users switch themes via the UI, the SPA engine updates the `--docmd-primary` variables instantly without a page reload. ::: callout tip When describing your documentation layout to an AI developer tool, mentioning your theme (e.g., "I'm using the `retro` theme") helps the model suggest custom CSS overrides that align with that specific theme's variable schema. ::: --- ## [Custom Styles & Scripts](https://docs.docmd.io/07/theming/custom-css-js/) --- title: "Custom Styles & Scripts" description: "Inject your own CSS and JS files to extend docmd's functionality and branding." --- While `docmd` themes are highly flexible, you may want to inject your own stylesheets or interactive scripts. This is done via the `theme.customCss` and `customJs` arrays in your configuration. ## Custom CSS Use `theme.customCss` to override existing styles or add new ones. ```javascript // docmd.config.js export default { theme: { customCss: [ '/assets/css/branding.css' // Path relative to site root ] } } ``` ### How it Works 1. Place your CSS file inside your project’s assets folder (e.g., `docs/assets/css/branding.css`). 2. `docmd` will automatically copy it to the build folder and inject a `<link>` tag into every page. 3. Custom CSS is loaded **after** the theme styles, ensuring your overrides take priority. ## Custom JavaScript Use the top-level `customJs` array for scripts that add behaviour or integrate 3rd-party services. ```javascript // docmd.config.js export default { customJs: [ '/assets/js/feedback-widget.js' ] } ``` ### Life-cycle Awareness Scripts are injected at the bottom of the `<body>` tag. Since `docmd` is a **Single Page Application (SPA)**, remember that: * The page does not fully reload when navigating between links. * You may need to listen for custom lifecycle events to re-initialise your scripts on new pages. For the full event list and usage examples, see [Client-Side Events](../api/client-side-events.md). ::: callout tip Adding custom CSS and JS allows AI models (like ChatGPT) to suggest much more tailored UI improvements. If you mention "I have a custom `branding.css` file", the model can provide specific selectors that won't conflict with the core `docmd` engine. ::: --- ## [Customisation & Variables](https://docs.docmd.io/07/theming/customisation/) --- title: "Customisation & Variables" description: "A complete reference of docmd's CSS variables and component classes for advanced styling." --- `docmd` is built using a CSS variable-first architecture. This means you can restyle your entire site by simply overriding a few keys in a `:root` block without writing complex CSS selectors. ## Global Variable Reference | Variable | Default (Light) | Default (Dark) | Description | | :--- | :--- | :--- | :--- | | `--bg-colour` | `#ffffff` | `#09090b` | Main page background. | | `--text-colour` | `#3f3f46` | `#a1a1aa` | Standard body text. | | `--text-heading` | `#09090b` | `#fafafa` | Title and Header colours. | | `--link-colour` | `#068ad5` | `#068ad5` | Primary accent / links. | | `--border-colour` | `#e4e4e7` | `#27272a` | Dividers and borders. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Navigation background. | | `--ui-border-radius` | `6px` | `6px` | Rounding for all UI items. | | `--sidebar-width` | `260px` | `260px` | Sidebar column width. | ## Example Override To change your site's primary accent colour, add this to your `customCss`: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Component Targeting If you need to style specific components, use these top-level classes: * `.main-content`: The wrapper for all Markdown content. * `.sidebar-nav`: The internal navigation list. * `.page-header`: The top navigation bar. * `.docmd-search-modal`: The search overlay. * `.docmd-tabs`: Tab container components. * `.callout`: The alert/note boxes. ## Troubleshooting specificity Most `docmd` styles use low specificity. If your overrides aren't applying, ensure your `customCss` is registered correctly and check if adding a `body` prefix (e.g., `body .main-content`) helps. ::: callout tip Because `docmd` uses standard CSS variables, you can ask an AI: *"Give me a professional colour palette using --link-colour and --bg-colour for docmd"*. The model will be able to provide ready-to-paste CSS that integrates perfectly with the built-in themes. ::: --- ## [Icons](https://docs.docmd.io/07/theming/icons/) --- title: "Icons" description: "How to use and customise Lucide icons in your documentation." --- `docmd` comes with built-in support for the [Lucide](external:https://lucide.dev/) icon library. Icons can be used in your navigation sidebar, buttons, and custom components to provide visual cues and improve scannability. ## Navigation Icons Assign an icon to any navigation item in your `docmd.config.js`. Use the kebab-case name of any icon found on the Lucide website. ```javascript navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Setup', path: '/setup', icon: 'settings' } ] ``` ## Icons in Containers You can also use icons inside your buttons, tags, tabs, and other containers by including the raw HTML or using standard `icon:` prefix across docmd. ```markdown ::: button "Download" /download icon:download ``` ## CSS Styling All icons are rendered as inline SVGs with the class `.lucide-icon`. You can globally change their size or stroke weight in your `customCss`: ```css .lucide-icon { stroke-width: 1.5px; /* Thinner icons for a modern look */ width: 1.2rem; height: 1.2rem; } /* Target a specific icon */ .icon-rocket { color: #ff5733; } ``` ## Icon Reference We support the entire Lucide library. You can browse the thousands of available icons here: ::: button "Browse Lucide Icons" external:https://lucide.dev/icons icon:globe --- ## [Light & Dark Mode](https://docs.docmd.io/07/theming/light-dark-mode/) --- title: "Light & Dark Mode" description: "How to configure the default viewing mode and manage the theme switcher for the best user experience." --- `docmd` provides built-in support for light and dark colour schemes. It detects user system preferences automatically and allows manual overrides via a UI toggle. ## Default Viewing Mode You specify the starting state of your documentation in `docmd.config.js`. ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system' // Options: 'light', 'dark', 'system' (default) } } ``` * **`system`**: Matches the user's OS preference (Recommended). * **`light`**: Force light mode on initial load. * **`dark`**: Force dark mode on initial load. ## Configuring the Toggle Button The theme switcher is part of the **Options Menu**. You can control its visibility and position within the `layout` object. ```javascript layout: { optionsMenu: { position: 'header', // Options: 'header', 'sidebar-top', 'sidebar-bottom' components: { themeSwitch: true // Show or hide the Sun/Moon toggle } } } ``` ## How it works (Technical) The theme engine applies a `data-theme` attribute to the `<body>` tag: * `<body data-theme="light">` * `<body data-theme="dark">` If you are using a themed design like `sky`, the attribute will be `sky-light` or `sky-dark`. ### CSS Variables `docmd` themes use CSS variables for all colours. You can override these variables in your own CSS to customise the look of either mode. ```css /* Custom CSS override */ :root { --docmd-primary: #4f46e5; /* Primary accent for light mode */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* Primary accent for dark mode */ } ``` ## User Persistence When a user manually toggles the mode, their preference is stored in `localStorage`. `docmd` instantly reads this value on every page load to prevent "theme flickering" (FOUC). ::: callout tip When generating content, LLMs prefer high-contrast structures. `docmd` ensures that code snippets and callouts remain accessible in both modes, ensuring that `llms-full.txt` payloads are correctly understood as semantic blocks regardless of which mode was active during the build. ::: --- ## [Browser API (Client-Side)](https://docs.docmd.io/api/browser-api/) --- title: "Browser API (Client-Side)" description: "Interact with docmd from the browser - live compilation and dev-mode plugin communication." --- docmd provides two browser APIs: the **isomorphic compile engine** for rendering markdown in the browser, and the **dev-mode plugin API** for real-time communication with the dev server. ## Isomorphic Compile Engine The engine that generates static sites in Node.js can run entirely within a web browser. This is ideal for building CMS previews, interactive playgrounds, or embedding documentation. ### Installation via CDN ```html <!-- Core Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- The Isomorphic Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` Compiles raw Markdown into a full HTML document string using the default docmd layout. **Parameters:** - `markdown` (String): The raw Markdown content. - `config` (Object): Configuration overrides (same schema as `docmd.config.json`). **Returns:** `Promise<String>`: The complete HTML document. ### Example: Live Preview To ensure style isolation, render the output inside an `<iframe>` using the `srcdoc` attribute. ```javascript const editor = document.getElementById("editor"); const preview = document.getElementById("preview"); async function updatePreview() { const html = await docmd.compile(editor.value, { "title": "Preview", "theme": { "appearance": "light" } }); preview.srcdoc = html; } editor.addEventListener("input", updatePreview); ``` ## Dev-Mode Plugin API During `npx @docmd/core dev`, a `window.docmd` global is injected into every page automatically. This API enables real-time communication between browser-side plugin code and server-side action handlers via WebSocket RPC. ::: callout info "Dev Mode Only" icon:code The plugin API methods below are only available during `npx @docmd/core dev`. They are not included in production builds. ::: ### `docmd.call(action, payload)` Call a server-side action handler registered by a plugin. Returns a promise that resolves with the handler's return value. ```javascript const threads = await docmd.call("threads:get-threads", { "file": "docs/getting-started.md" }); console.log(threads); ``` If the action modifies source files, the page automatically reloads after the promise resolves. ### `docmd.send(name, data)` Send a fire-and-forget event to the server. No response is returned. ```javascript docmd.send("analytics:page-view", { "path": window.location.pathname }); ``` ### `docmd.on(name, callback)` Subscribe to server-pushed events. Returns an unsubscribe function. ```javascript const unsub = docmd.on("threads:updated", (data) => { console.log("Threads updated:", data); }); unsub(); ``` ### `docmd.afterReload(name, callback)` Declare a handler that runs after a page reload. If context was stashed with `scheduleReload`, the callback receives it. ```javascript // Restore scroll position after a live-reload docmd.afterReload('scroll-restore', (ctx) => { window.scrollTo(0, ctx.scrollY); }); ``` ### `docmd.scheduleReload(name, context)` Stash context into `sessionStorage` for a named `afterReload` handler. The matching handler fires with this context after the next page reload. ```javascript docmd.scheduleReload("scroll-restore", { "scrollY": window.scrollY }); ``` ## Considerations - **No File System**: The browser engine cannot scan folders. You must provide the `navigation` array explicitly in the config object if you need a sidebar. - **Node-Only Plugins**: Plugins that rely on Node.js APIs (like Sitemap or LLM text generation) are disabled in the browser environment. - **WebSocket Connection**: The dev-mode API requires an active WebSocket connection to the dev server. It auto-reconnects with exponential backoff if the connection drops. --- ## [CLI Commands](https://docs.docmd.io/api/cli-commands/) --- title: "CLI Commands" description: "Command-line reference for docmd - all available commands and options." --- ## Commands Overview | Command | Description | |:--------|:------------| | [`npx @docmd/core init`](#npx-docmdcore-init) | Scaffold a new documentation project | | [`npx @docmd/core dev`](#npx-docmdcore-dev) | Start the development server with hot reload | | [`npx @docmd/core build`](#npx-docmdcore-build) | Generate a production static site | | [`npx @docmd/core live`](#npx-docmdcore-live) | Launch the browser-based Live Editor | | [`npx @docmd/core stop`](#npx-docmdcore-stop) | Kill running dev servers | | [`npx @docmd/core deploy`](#npx-docmdcore-deploy) | Generate deployment configs | | [`npx @docmd/core migrate`](#npx-docmdcore-migrate) | Upgrade legacy configs or migrate from other tools | | [`npx @docmd/core add <plugin>`](#npx-docmdcore-add-plugin) | Install and configure a plugin | | [`npx @docmd/core remove <plugin>`](#npx-docmdcore-remove-plugin) | Remove a plugin and its config | ## Global Options | Option | Alias | Description | |:-------|:------|:------------| | `--config <path>` | `-c` | Path to config file (default: `docmd.config.json`) | | `--verbose` | `-V` | Show detailed build logs | | `--version` | `-v` | Output the installed version | | `--help` | `-h` | Display help menu | | `--cwd <path>` | - | Override working directory (for monorepos) | ## `npx @docmd/core init` Scaffold a new documentation project in the current directory. ```bash npx @docmd/core init ``` Creates: - `docs/index.md` - boilerplate home page - `docmd.config.json` - recommended defaults - Updated `package.json` with build scripts ## `npx @docmd/core dev` Start a development server with instant hot reload. ```bash npx @docmd/core dev [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--port <number>` | `-p` | Server port (default: `3000`) | | `--config <path>` | `-c` | Path to config file | ## `npx @docmd/core build` Generate a production-ready static site in `site/`. ```bash npx @docmd/core build [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--offline` | - | Rewrite links to `.html` for `file://` browsing | | `--config <path>` | `-c` | Path to config file | ## `npx @docmd/core live` Launch the browser-based Live Editor. ```bash npx @docmd/core live [options] ``` | Option | Description | |:-------|:------------| | `--build-only` | Generate the editor bundle without starting the server | ## `npx @docmd/core stop` Kill running dev servers. ```bash npx @docmd/core stop [options] ``` | Option | Alias | Description | |:-------|:------|:------------| | `--port <number>` | `-p` | Stop only the server on this port | | `--force` | `-f` | Also kill `serve` processes on ports 3000, 3001, 8080, 8081 | ## `npx @docmd/core deploy` Generate deployment configuration files. ```bash npx @docmd/core deploy [options] ``` | Option | Description | |:-------|:------------| | `--docker` | Generate a `Dockerfile` + `.dockerignore` | | `--nginx` | Generate `nginx.conf` | | `--caddy` | Generate `Caddyfile` | | `--github-pages` | Generate `.github/workflows/deploy.yml` | | `--vercel` | Generate `vercel.json` | | `--netlify` | Generate `netlify.toml` | | `--force` | Overwrite existing deployment files | ## `npx @docmd/core migrate` Migrate from another tool or upgrade configs. ```bash npx @docmd/core migrate ``` Automatically re-maps deprecated keys (e.g., `siteTitle` → `title`) and restructures the config object. ## `npx @docmd/core add <plugin>` Install and configure an official or community plugin. ```bash npx @docmd/core add <plugin-name> ``` | Example | Description | |:--------|:------------| | `npx @docmd/core add analytics` | Install `@docmd/plugin-analytics` | | `npx @docmd/core add search` | Install `@docmd/plugin-search` | The CLI detects your package manager (npm, pnpm, yarn, or bun) and injects recommended defaults into `docmd.config.json`. ## `npx @docmd/core remove <plugin>` Safely uninstall a plugin and clean up its config. ```bash npx @docmd/core remove <plugin-name> ``` Removes: - The npm package - Plugin configuration from `docmd.config.json` ::: callout tip "Agent-Compatible Logging" icon:sparkles docmd uses structured terminal logging. AI agents can parse output precisely for error detection and automated maintenance. ::: --- ## [Client-Side Events](https://docs.docmd.io/api/client-side-events/) --- title: "Client-Side Events" description: "Hook into the docmd SPA lifecycle to add interactive features." --- docmd uses a lightweight Single Page Application (SPA) router to provide instant page transitions. Because the browser does not perform a full reload during navigation, scripts relying on `DOMContentLoaded` will not re-execute. To handle this, docmd dispatches custom lifecycle events that you can listen for in your `customJs` files. ## `docmd:page-mounted` This event is dispatched whenever a new page has been successfully fetched and injected into the DOM. ### Usage Add a listener to the `document` object to re-initialise third-party libraries or trigger custom animations. ```javascript document.addEventListener("docmd:page-mounted", (event) => { const { url } = event.detail; console.log(`Navigated to: ${url}`); }); ``` ### Event Details (`event.detail`) | Property | Type | Description | | :--- | :--- | :--- | | `url` | `String` | The absolute URL of the page that was just mounted. | ## Best Practices 1. **Idempotency**: Ensure your initialisation logic can be safely called multiple times on the same page or cleaned up before the next navigation. 2. **Global Scope**: Scripts added via `customJs` execute in the global scope. Use an IIFE (Immediately Invoked Function Expression) to avoid polluting the `window` object. 3. **Cleanup**: If your script adds global event listeners (e.g., `window.onresize`), consider tracking the current path to remove them when the user navigates away. --- ## [Live Editor](https://docs.docmd.io/api/live-api/) --- title: "Live Editor" description: "Understanding the docmd Live Editor and its browser-based authoring workflow." --- The docmd Live Editor is a dedicated environment for real-time documentation authoring. It uses the isomorphic core to provide an instant, side-by-side preview of your Markdown content without requiring a backend build process. ## Launching the Editor Start the local Live Editor by running: ```bash npx @docmd/core live ``` The editor will typically be available at `http://localhost:3000`. ## Architecture Unlike the standard `dev` server which rebuilds files on the disk, the Live Editor runs the engine directly in your browser. This enables: 1. **Instant Feedback**: Content is re-rendered as you type. 2. **Portable Playgrounds**: The editor can be bundled into a static site for hosting on platforms like GitHub Pages. 3. **Cross-Platform Consistency**: The preview uses the exact same rendering logic as the production build. ## Static Deployment Generate a shareable, standalone version of the editor: ```bash npx @docmd/core live --build-only ``` This creates a `dist/` directory containing the editor's HTML and the bundled isomorphic engine. --- ## [MCP Server](https://docs.docmd.io/api/mcp-server/) --- title: "MCP Server" description: "Connect AI development agents to your documentation workspace using the Model Context Protocol." --- docmd includes a native Model Context Protocol (MCP) server, enabling AI development agents to interact with your documentation workspace programmatically over a secure, local connection. ## What is MCP? The [Model Context Protocol](external:https://modelcontextprotocol.io/) is an open standard for connecting AI models to external tools and data sources. It uses JSON-RPC 2.0 messages over a transport layer (stdio, HTTP). docmd implements the `stdio` transport — the agent spawns `docmd mcp` as a child process and communicates via stdin/stdout. ## Quick Start ```bash docmd mcp ``` This starts the MCP server over `stdio`. No network ports are opened — all communication happens through standard input/output streams. ### Claude Desktop Configuration Add to your Claude Desktop `claude_desktop_config.json`: ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/path/to/your/docs/project" } } } ``` ### Cursor / Windsurf Configuration Add to your editor's MCP settings: ```json { "command": "npx @docmd/core mcp", "transport": "stdio" } ``` ## Available Tools The MCP server exposes four tools that agents can call: | Tool | Description | | :--- | :--- | | **`search_docs`** | Full-text search across all documentation files. Returns matching lines with file paths and line numbers. | | **`read_doc`** | Read the raw markdown content of any documentation file by its relative path. | | **`validate_docs`** | Run link validation across all markdown files. Returns a list of broken links with file, line, and target. | | **`get_llms_context`** | Retrieve the complete `llms-full.txt` context — the unified content of the entire documentation site, optimised for LLM ingestion. | ### Tool Schemas #### `search_docs` ```json { "name": "search_docs", "inputSchema": { "type": "object", "properties": { "query": { "type": "string", "description": "The term or phrase to search for." } }, "required": ["query"] } } ``` #### `read_doc` ```json { "name": "read_doc", "inputSchema": { "type": "object", "properties": { "route": { "type": "string", "description": "Relative path to the markdown file (e.g. docs/getting-started.md)." } }, "required": ["route"] } } ``` #### `validate_docs` / `get_llms_context` No input parameters required. ## Protocol Details docmd implements the MCP specification (protocol version `2025-03-26`): - **Transport**: `stdio` — JSON-RPC 2.0 messages over stdin/stdout, one per line - **Diagnostics**: Logged to `stderr` (does not interfere with the JSON-RPC stream) - **Lifecycle**: `initialize` → `notifications/initialized` → tool calls - **Ping**: Responds to `ping` requests with `{}` (required for connection health checks) - **Capabilities**: Declares `tools`, `resources`, and `prompts` (tools are the primary interface) ## Privacy & Security - **Local only**: The server runs as a child process — no network exposure, no ports opened - **Sandboxed**: File operations are restricted to the project working directory - **No telemetry**: No data is sent anywhere — all processing happens on your machine ## Complementary Features The MCP server works alongside other AI-first features in docmd: - **`llms.txt` / `llms-full.txt`**: Generated at build time by the `llms` plugin. Any agent can fetch these from your deployed site without MCP. - **Copy Context widget**: Browser UI button that copies page content optimised for pasting into AI chat windows. - **SKILL.md**: Agent instruction manual auto-generated by `docmd init`. Points to the [docmd-skills](external:https://github.com/docmd-io/docmd-skills) knowledge base. ::: callout tip "When to use MCP vs llms.txt" Use **MCP** when an agent needs to search, read specific files, or validate links interactively during development. Use **llms-full.txt** when an agent needs the entire documentation context in a single fetch (e.g., for RAG or pre-prompting). ::: --- ## [Node.js API](https://docs.docmd.io/api/node-api/) --- title: "Node.js API" description: "Integrate docmd's build engine into your custom Node.js scripts and automation pipelines." --- You can import and use the docmd build engine directly within your Node.js applications. This is ideal for custom CI/CD pipelines, automated documentation generation, or extending docmd for specialised environments. ## Installation Ensure `@docmd/core` is installed in your project: ```bash npm install @docmd/core ``` ## Core Functions ### `buildSite(configPath, options)` The primary build function. It handles configuration loading, Markdown parsing, and asset generation. ```javascript import { buildSite } from "@docmd/core"; async function runBuild() { await buildSite("./docmd.config.json", { "isDev": false, offline: false, zeroConfig: false }); } ``` ### `buildLive(options)` Generates the browser-based **Live Editor** bundle. ```javascript import { buildLive } from "@docmd/core"; async function generateEditor() { await buildLive({ "serve": false, port: 3000 }); } ``` ## Workspace Management For managing workspaces programmatically, use the dedicated workspace functions. ### `isWorkspace(config)` Returns `true` if the provided configuration object follows the Workspace schema. ### `detectWorkspace(configPath)` Detects and loads a workspace configuration file. Returns a normalised `WorkspaceRootConfig` or `null`. ### `buildWorkspace(config, options)` Builds all projects within a workspace. Handles shared assets and project-specific prefixing. ### `devWorkspace(config, options)` Starts the workspace dev server. Watches all projects for changes and performs targeted rebuilds. ```javascript import { detectWorkspace, buildWorkspace } from "@docmd/core"; async function buildAll() { const config = await detectWorkspace("./docmd.config.json"); if (config) { await buildWorkspace(config, { quiet: false }); } } ``` ## Example: Custom Pipeline You can wrap docmd to create complex documentation workflows. ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. Generate dynamic content await fs.writeFile('./docs/dynamic.md', '# Generated Content'); // 2. Execute build await buildSite('./docmd.config.json'); // 3. Move output await fs.move('./site', './public/docs'); } ``` ::: callout tip The programmatic API is highly compatible with **AI-Driven Documentation**. Agents can trigger builds after content updates to verify integrity and manage deployments autonomously. ::: ## Plugin API (`@docmd/api`) The `@docmd/api` package is the dedicated home for the plugin system. It provides hook registration, WebSocket RPC dispatch, source editing tools, and **centralised URL utilities**. ```bash npm install @docmd/api ``` ### URL Utilities Plugins should use these centralised utilities instead of rolling their own URL logic. #### `outputPathToSlug(outputPath)` Convert a build engine output path to a clean directory-style slug. ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` Convert to a root-relative pathname. ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` Build a full canonical URL. ```javascript import { outputPathToCanonical } from "@docmd/api"; outputPathToCanonical("guide/index.html", "https://docs.example.com"); ``` #### `sanitizeUrl(url)` Collapse double slashes (except after protocol). ```javascript import { sanitizeUrl } from "@docmd/api"; sanitizeUrl("https://docs.example.com//guide"); // → "https://docs.example.com/guide" sanitizeUrl("/foo//bar"); // → "/foo/bar" ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` Build an absolute URL with locale and version prefixes. ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` Normalise user-written hrefs to clean URLs. Handles `.md` stripping, trailing slashes, `external:` and `raw:` prefixes. ```javascript import { resolveHref } from "@docmd/api"; resolveHref("overview.md"); // → "overview/" resolveHref("external:https://github.com"); // → "https://github.com" resolveHref("raw:docs/readme.md"); // → "docs/readme.md" ``` ### Pre-computed Page URLs Every page object includes pre-computed URL data. Plugins can read these directly with zero computation needed. ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); console.log(page.urls.canonical); console.log(page.urls.pathname); } } ``` | Property | Type | Description | |:---------|:-----|:------------| | `slug` | `string` | Clean directory-style slug (e.g., `guide/` or `/`) | | `canonical` | `string` | Full canonical URL (only if `config.url` is set) | | `pathname` | `string` | Root-relative path (e.g., `/guide/`) | > **Note:** All exports from `@docmd/api` are also available from `@docmd/core`. New projects should import directly from `@docmd/api`. ### `createActionDispatcher(hooks, options)` Creates a dispatcher that routes WebSocket RPC messages to plugin action/event handlers. ```javascript import { createActionDispatcher } from "@docmd/api"; const dispatcher = createActionDispatcher( { "actions": myPlugin.actions, "events": myPlugin.events }, { "projectRoot": "/path/to/project", config, broadcast } ); const { result, reload } = await dispatcher.handleCall("my-action", payload); ``` ### `createSourceTools({ projectRoot })` Creates source editing utilities for markdown file manipulation. ```javascript import { createSourceTools } from "@docmd/api"; const source = createSourceTools({ "projectRoot": "/path/to/project" }); const block = await source.getBlockAt("docs/page.md", [10, 12]); await source.wrapText("docs/page.md", [10, 12], "important", 0, "**", "**"); ``` ### `loadPlugins(config, options)` Loads, validates, and registers all plugins declared in the config. Returns the populated hooks registry. ```javascript import { loadPlugins, hooks } from "@docmd/api"; const registeredHooks = await loadPlugins(config, { "resolvePaths": [__dirname] }); ``` ### Engine Loader API The pluggable engine architecture allows programmatic resolution and instantiation of acceleration layers directly via `@docmd/api`. #### `loadEngine(engineName)` Resolves and initialises the requested build engine backend. If native architecture binaries are unavailable, it gracefully falls back to the high-performance JavaScript engine. ```javascript import { loadEngine } from "@docmd/api"; const engine = await loadEngine("rust"); const gitLogResult = await engine.runWorkerTask("git:log", { "paths": ["docs/guide.md"] }); ``` #### `registerEngine(engineName, engineInstance)` Allows custom tools or third-party integrators to register custom execution engines programmatically. ```javascript import { registerEngine } from "@docmd/api"; registerEngine("custom", myCustomEngineImpl); ``` ### Type Exports For TypeScript plugin authors, the following types are available: ```typescript import type { PluginModule, PluginDescriptor, PluginHooks, PageContext, BeforeBuildContext, PostBuildContext, Capability, ActionContext, ActionHandler, EventHandler, SourceTools, BlockInfo, TextLocation, Engine, } from '@docmd/api'; ``` --- ## [Comparison](https://docs.docmd.io/comparison/) --- title: "Comparison" description: "How docmd stacks up against Docusaurus, VitePress, MkDocs, Starlight, and Mintlify - real numbers, real features." --- You picked a documentation tool before. You'll pick one again. Here's what actually matters - and where docmd stands. ## Start writing in 3 seconds, not 30 minutes ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` Done. Your docs are live. No config files, no project scaffolding, no dependency maze. == tab "Docusaurus" ```bash npx create-docusaurus@latest my-site classic cd my-site npm install npm start ``` Four commands, a generated project with ~250MB in `node_modules`, and a `docusaurus.config.js` you'll need to edit before anything useful happens. == tab "VitePress" ```bash npx vitepress init ``` Asks you 5 questions, generates a config file, then you run `vitepress dev`. Clean - but still requires scaffolding. == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new my-site && cd my-site mkdocs serve ``` Python ecosystem. You'll need `pip`, a virtual environment, and a `mkdocs.yml` before the first page renders. ::: ## The payload gap is real Your readers shouldn't download a React app just to read a paragraph. Here's what the browser actually receives on a 50-page site: | Generator | Total initial load | JS payload | CSS payload | |:----------|:------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "Why this matters" icon:lightbulb Every 100 KB of JavaScript costs ~50ms of parse time on a mid-range phone. docmd's 12 KB JS means your docs load instantly, even on 3G. Docusaurus ships 16× more JavaScript for the same content. ::: ## Build speed Building the same 50-page site on an M1 MacBook Air: | Generator | Cold build | Hot rebuild (dev) | |:----------|:----------:|:-----------------:| | **docmd** | **~1.2s** | **~80ms** | | VitePress | ~2.5s | ~150ms | | MkDocs Material | ~3.0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd rebuilds are fast enough that the page refreshes before you switch windows. ## i18n that actually works This is where most tools fall apart. You add 6 languages, translate 3 pages in Hindi, and suddenly your users hit 404s on every untranslated page. | Capability | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | Per-page fallback to default locale | ✅ | ❌ (404) | ❌ (404) | ✅ | | Localised "not translated" warning | ✅ | ❌ | ❌ | ✅ | | Auto-disable missing locales in switcher | ✅ | ❌ | ❌ | ❌ | | Instant page-existence check (no network) | ✅ | ❌ | ❌ | ❌ | | Versioning + i18n combined | ✅ | ❌ | ❌ | ❌ | | Zero-config (no custom React/Vue) | ✅ | Partial | ❌ | ✅ | ::: callout warning "What happens in VitePress and Docusaurus" icon:info If a reader switches to Hindi and that page isn't translated, they get a **404 error**. The only workaround is server-side redirects or writing a custom React/Vue component. docmd handles this at build time - unavailable locales show an "N/A" badge, and untranslated pages fall back silently with a localised warning callout. ::: ## Workspace Organisations maintaining multiple tools under one domain need separate docs for each - different versions, different navigation, different release cycles. Most generators force you to either maintain separate sites or hack around plugin systems. | Capability | docmd | Docusaurus | VitePress | MkDocs | Starlight | |:-----------|:-----:|:----------:|:---------:|:------:|:---------:| | Native workspace support | ✅ | Plugin | ❌ | Plugin | ❌ | | Single config line per project | ✅ | ❌ | ❌ | ❌ | ❌ | | Independent versioning per project | ✅ | ✅ | ❌ | ❌ | ❌ | | Independent i18n per project | ✅ | ❌ | ❌ | ❌ | ❌ | | Shared assets across projects | ✅ | ❌ | ❌ | ❌ | ❌ | | Single `site/` output (no proxy needed) | ✅ | ❌ | ❌ | ❌ | ❌ | | Zero-config detection | ✅ | ❌ | ❌ | ❌ | ❌ | ::: callout info "How docmd does it" icon:info ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Docs" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK" } ] } } ``` Each project folder has its own `docmd.config.json` with independent configuration. One `npx @docmd/core build` produces a single deployable directory - no reverse proxy, no nginx, no separate CI pipelines. ::: Docusaurus achieves something similar with multi-instance plugins, but requires complex configuration - each instance needs separate plugin entries, sidebar files, and manual route configuration. MkDocs requires the third-party `mkdocs-monorepo-plugin`. VitePress, Starlight, and Mintlify have no native workspace support. ## Full feature matrix | Feature | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **Zero-config start** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Config required** | None | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **Workspace** | ✅ | Plugin | ❌ | Plugin | ❌ | ❌ | | **SPA navigation** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **Native versioning** | ✅ | ✅ | ❌ | Plugin | ❌ | ✅ | | **Native i18n** | ✅ | ✅ | Manual | Plugin | ✅ | ✅ | | **Built-in search** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | Cloud | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **MCP Server** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Agent Skills** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Docker Image** | ✅ | ❌ | ✅ | ❌ | ❌ | N/A | | **Inline discussions** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA support** | ✅ | Community | ❌ | ❌ | ❌ | ❌ | | **Self-hosted** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **Deploy config generator** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## Configuration overhead Lines of config required for a site with versioning, i18n, search, and sitemap: | Generator | Config lines | Files required | |:----------|:------------:|:--------------:| | **docmd** | **~15 lines** | 1 (`docmd.config.json`) | | MkDocs Material | ~50 lines | 1 + plugins | | VitePress | ~80 lines | 1 + theme dir | | Docusaurus | ~120 lines | 3+ config files | ## Quality assurance docmd ships with a brute test suite that validates **25 distinct scenarios** across **85 assertions** - covering every feature in isolation and in combination. Every release must pass all 85 assertions and 13 internal failsafe checks before shipping. ::: callout tip "Run the tests yourself" icon:lightbulb ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: No other documentation generator in this class publishes a comparable end-to-end feature test suite as part of its source. --- ## [Layout & UI Zones](https://docs.docmd.io/configuration/layout-ui/) --- title: "Layout & UI Zones" description: "Control the interface structure by managing headers, sidebars, and functional UI slots." --- A standard page contains six primary functional zones: 1. **Menubar**: A full-width top navigation bar for global site links. 2. **Header**: A persistent secondary bar. It contains the page title and utility buttons. 3. **Sidebar**: The primary navigation tree, usually on the left. 4. **Content Area**: The central Markdown rendering zone. Includes **Breadcrumbs**. 5. **Table of Contents (TOC)**: Right-hand heading navigation for the current page. 6. **Footer**: Bottom area for copyright, branding, and site-wide links. ## Global Component Configuration The engine uses a modular layout system. Configure most UI zones in the `layout` section of your `docmd.config.json`. ### Menubar The menubar provides a high-level navigation layer. It supports brand titles, regular links, and nested dropdowns. * **Location**: Fixed at the `top` or inline within the `header`. * **Documentation**: See [Menubar Configuration](menubar.md) for schemas and styling. ### The Page Header The header displays the page title, breadcrumbs, and utility menus. * **Controls**: Enable or disable the header globally via `layout.header`. Toggle breadcrumbs via `layout.breadcrumbs`. * **Overriding**: Use `hideTitle: true` in your [Page Frontmatter](../content/frontmatter.md) to hide the title area locally. ### Copy Widgets (AI Integration) To help developers and LLM agents working with your documentation, docmd includes integrated copy buttons in the breadcrumbs bar. These buttons allow copy-pasting the raw Markdown of the page, or the unified LLM context. Configure these buttons under the `theme.copyWidgets` settings block in your `docmd.config.json`: ```json { "theme": { "copyWidgets": { "enabled": true, "raw": true, "context": true } } } ``` * `enabled`: Set to `false` to disable the copy widgets bar completely. * `raw`: Set to `false` to hide the "Copy Markdown" button. * `context`: Set to `false` to hide the "Copy Context" button. ### Utility Menus (Options Menu) The `optionsMenu` groups core utilities like **Global Search**, **Theme Toggle**, and **Sponsorship links**. ```json { "layout": { "optionsMenu": { "position": "header", "components": { "search": true, "themeSwitch": true, "sponsor": "https://github.com/sponsors/mgks" } } } } ``` ::: callout info "Automatic Fallback" icon:sparkles If the chosen position targets a disabled container, the engine moves the options menu to `sidebar-top`. This ensures utilities remain accessible. ::: ### Sidebar & Navigation The sidebar is the primary navigation tree. Define its structure in your config or external JSON files. * **Behaviour**: Supports animations, collapsible groups, and automatic path preservation. * **Documentation**: See [Navigation Configuration](navigation.md). ### Footer The engine provides **minimal** and **complete** layouts for your site footer. ```json { "layout": { "footer": { "style": "complete", "description": "Documentation built with docmd.", "branding": true, "columns": [ { "title": "Community", "links": [ { "text": "GitHub", "url": "https://github.com/docmd-io/docmd" } ] } ] } } } ``` ::: callout tip "Interface Hierarchy" icon:lightbulb Keep your **Menubar** for global links. Use your **Sidebar** for logical documentation structure. AI agents rely on this hierarchy to understand the relationships between modules. ::: --- ## [Localisation](https://docs.docmd.io/configuration/localisation/) --- title: "Localisation" description: "Serve documentation in multiple languages with locale-first routing, translated navigation, and automatic fallback." --- Add multi-language support to your documentation site. docmd serves each locale at its own URL prefix, translates system UI strings, and falls back gracefully when a translation is missing. ## Add languages to your config ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "hi", "label": "हिन्दी" }, { "id": "zh", "label": "中文" } ] } } ``` The `default` locale renders at the site root (`/`). All other locales render at `/{id}/`. You choose the IDs, labels, and which locale is the default - there are no hardcoded assumptions. If you want Hindi as the default, set `default: 'hi'` and Hindi renders at `/` whilst English renders at `/en/`. | Key | Type | Description | |:----|:-----|:------------| | `default` | `string` | Locale ID that renders at `/`. Defaults to the first locale if omitted. | | `locales` | `array` | List of locale objects. Each must have an `id`. | | `position` | `string` | Where the language switcher appears. `options-menu` (default), `sidebar-top`, or `sidebar-bottom`. | | `stringMode` | `boolean` | When `true`, generates locale pages from a single source using `data-i18n` attribute replacement. Default `false`. | | `inPlace` | `boolean` | When `true` (with client-side script), swaps strings without URL navigation. For SPAs/dashboards only. Default `false`. | Each locale object accepts: | Key | Type | Default | Description | |:----|:-----|:--------|:------------| | `id` | `string` | - | Any identifier you choose (e.g. `en`, `hi`, `fr-ca`). Used as the folder name and URL prefix. Required. | | `label` | `string` | Same as `id` | Display name shown in the language switcher. | | `dir` | `string` | `ltr` | Text direction. Set to `rtl` for Arabic, Hebrew, etc. | | `translations` | `object` | `{}` | Custom UI string overrides (see [Custom UI strings](ui-strings.md)). | ## URL structure The default locale has no URL prefix. Non-default locales are nested under `/{id}/`. When combined with [versioning](../versioning.md), the URL is `/{locale}/{version}/page`. ``` / ← default locale, current version /getting-started ← default locale page /05/ ← default locale, old version /hi/ ← non-default locale, current version /hi/getting-started ← non-default locale page /hi/05/ ← non-default locale, old version ``` The language switcher preserves your current page and version when you switch locales. The version switcher preserves your current locale. ## Missing locale directories If a locale is declared in `locales` but its source directory does not exist (e.g. no `docs/hi/` folder), docmd automatically **disables** that locale in the language switcher. The locale still appears in the dropdown - with an "N/A" badge and greyed-out styling - but clicking it does nothing. This prevents 404 errors when you list planned languages before their content is ready. ## Position the language switcher <img width="500" class="with-border" src="/assets/previews/menu-i18n.webp"> Control where the language switcher appears using the `position` option: ```json { "i18n": { "position": "sidebar-top" } } ``` | Position | Behaviour | |:---------|:----------| | `options-menu` | Compact globe icon alongside theme toggle and search. Default. | | `sidebar-top` | Full dropdown with label at the top of the sidebar. | | `sidebar-bottom` | Full dropdown with label at the bottom of the sidebar. | ## String Mode (noStyle pages only) Standard i18n uses separate directories per locale (`docs/en/`, `docs/hi/`), each with its own markdown files. **String Mode** is a simpler alternative designed specifically for [noStyle pages](../../content/no-style-pages.md) - pages that use raw HTML instead of markdown. ```json "i18n": { "default": "en", "stringMode": true, "locales": [ { "id": "en", "label": "English" }, { "id": "zh", "label": "中文" } ] } ``` With `stringMode: true`: 1. Source files stay in the root `docs/` directory (no locale subdirectories) 2. The default locale builds at `/` as normal 3. For each non-default locale, docmd clones the rendered HTML and applies **server-side string replacement** using JSON files from `assets/i18n/{locale}.json` 4. Output goes to `/{locale}/` - e.g. `/zh/index.html` - with full SEO (hreflang tags, correct `lang` attribute) 5. If a translation file is missing, the page renders with the default language text For full details on the `data-i18n` attribute syntax and JSON file format, see [noStyle string replacement](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: callout warning "String Mode does not translate markdown content" icon:info String replacement works by finding `data-i18n` attributes in the rendered HTML. Standard markdown content (`## Heading`, paragraphs, lists) renders to plain HTML tags without these attributes - so there is nothing for the replacer to find. - **Documentation sites** → use directory mode (the default). Each locale has its own markdown files with fully translated prose. - **Landing pages, marketing sites, dashboards** → use string mode. These are noStyle pages with custom HTML where you control every tag and can add `data-i18n` attributes. If your site has both - for example, a noStyle landing page plus documentation - use directory mode for the docs and add `data-i18n` attributes to your noStyle page. String mode will translate the noStyle HTML while directory mode handles the documentation content. ::: ## Next steps - [Translated content](translated-content.md) - directory structure, writing translations, navigation - [UI strings & SEO](ui-strings.md) - customising system text, hreflang tags - [noStyle string replacement](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle) - `data-i18n` attribute syntax and JSON format for noStyle pages --- ## [Translated Content](https://docs.docmd.io/configuration/localisation/translated-content/) --- title: "Translated Content" description: "Organise translations in locale subdirectories with per-file fallback and per-locale navigation." --- ## Directory Structure Every locale lives in its own subdirectory inside the source directory. The folder name matches the locale `id` from your config. ```text docs/ ├── en/ ← default locale content │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← second locale │ ├── index.md ← translated homepage │ ├── navigation.json ← translated navigation labels │ └── getting-started/ │ └── installation.md ← translated page └── zh/ ← third locale └── index.md ← only the homepage translated ``` The source directory holds only locale folders. No content files sit at the root level when i18n is enabled. ::: callout info "Folder Names Are Your Choice" icon:info Folder names match the `id` values in your config. If your config sets `{ id: 'fr-ca' }`, your folder is `docs/fr-ca/`. ::: ## Per-file Fallback You do not need to translate every page. docmd scans the **default locale directory** as the canonical structure. For every other locale, it checks for a translated page: - If `docs/hi/getting-started/installation.md` exists → serves the Hindi translation. - If it does not exist → serves the default locale version. When a page falls back, docmd displays a translated callout. This informs viewers the page is shown in the default language. Customise this message via your [UI strings](ui-strings.md) configuration. ## Locale-Exclusive Pages A non-default locale can host pages that do not exist in the default locale. These render only for that specific locale. ## Translate the Navigation Each locale directory can include its own `navigation.json`. docmd uses a cascading priority system to resolve the sidebar. For details on the resolution hierarchy, see [Navigation Configuration](../navigation.md). A locale's `navigation.json` uses the standard format: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "Partial Navigation" icon:info Create a locale `navigation.json` only when you want translated labels. If missing, the default navigation is used. ::: ## Versioning and i18n When combining versioning and i18n, structure the source directories hierarchically: ```text docs/ ← current version en/ ← current version, default locale hi/ ← current version, translated locale docs-v1/ ← previous version en/ ← v1, default locale hi/ ← v1, translated locale ``` The output URLs nest locale first, then version: ```text / ← default locale, current version /hi/ ← translated locale, current version /v1/ ← default locale, previous version /hi/v1/ ← translated locale, previous version ``` --- ## [UI Strings & SEO](https://docs.docmd.io/configuration/localisation/ui-strings/) --- title: "UI Strings & SEO" description: "Customise system UI text per locale and understand automatic SEO tags for multi-language sites." --- ## Built-in Language Support docmd and its official plugins ship with built-in translations for common languages. When you configure a supported locale, the engine automatically translates system text like search placeholders, navigation labels, and theme toggles. For unsupported languages or custom phrasing, the system falls back to English. You can override any string per locale. ## Custom UI Strings Use the `translations` property on any locale to override system text: ```json "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "ar", "label": "العربية", "dir": "rtl", "translations": { "onThisPage": "في هذه الصفحة", "previous": "السابق", "next": "التالي", "search": "بحث", "toggleTheme": "تبديل المظهر", "editThisPage": "تعديل هذه الصفحة", "selectLanguage": "اختر اللغة", "selectVersion": "اختر الإصدار", "fallbackMessage": "هذه الصفحة غير متاحة بعد باللغة {active}. عرض اللغة الافتراضية ({default})." } } ] } ``` The merge order is: **system translations → plugin translations → your config translations**. Your config always wins. ## Available Keys Instead of hardcoding a list of available keys, you can review the complete set of supported languages and translation keys directly in the docmd source repository. **[View Translation Source on GitHub](external:https://github.com/docmd-io/docmd/tree/main/packages/ui/translations)** The `fallbackMessage` key supports `{active}` and `{default}` placeholders. The engine replaces these with locale labels at build time. ## SEO and Hreflang docmd automatically generates `<link rel="alternate" hreflang="...">` tags for every page across all locales. The default locale also receives the `x-default` hreflang value. ```html <!-- Generated automatically on every page --> <link rel="alternate" hreflang="en" href="/"> <link rel="alternate" hreflang="x-default" href="/"> <link rel="alternate" hreflang="hi" href="/hi/"> <link rel="alternate" hreflang="zh" href="/zh/"> ``` No configuration is required. The engine injects these tags into every page when i18n is enabled. ::: callout info "noStyle Pages" icon:info The UI strings system applies to themed layout pages. For noStyle pages using custom HTML, see [Client-Side String Replacement](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: --- ## [Menubar](https://docs.docmd.io/configuration/menubar/) --- title: "Menubar" description: "Structure and position your menubar, manage navigation links, and configure drop-down menus." --- The `menubar` is a premium navigation layer. It provides global context across your site. Position it as a fixed bar at the viewport top or relatively above the page header. ## Configuration Configure the menubar in the `layout` section of your `docmd.config.json`. ```json { "layout": { "menubar": { "enabled": true, "position": "top", "left": [ { "type": "title", "text": "Brand", "url": "/", "icon": "home" }, { "text": "Documentation", "url": "/docs" }, { "type": "dropdown", "text": "Ecosystem", "items": [ { "text": "GitHub", "url": "https://github.com/docmd-io/docmd" }, { "text": "Live Editor", "url": "https://live.docmd.io" } ] } ], "right": [ { "text": "Support", "url": "/support", "icon": "help-circle" } ] } } } ``` ### Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | Toggles menubar visibility. | | `position` | `String` | `'top'` | `'top'` (fixed at absolute top) or `'header'` (positioned above the page title). | | `left` | `Array` | `[]` | Left-aligned navigation items. | | `right` | `Array` | `[]` | Right-aligned navigation items. | ## Item Types The `left` and `right` arrays support various item types. ### 1. Standard Link The most common item type. - `text`: Display label. - `url`: Path or external URL. - `icon`: Optional Lucide icon name. - `external`: Set to `true` to open in a new tab. ### 2. Title (Brand) Set `type: 'title'` to apply branding styles (e.g. bold fonts). ### 3. Dropdown Menu Set `type: 'dropdown'` and provide an `items` array to create a nested menu. ## Utility Integration Host the global search and theme toggle in the menubar. Set `optionsMenu.position` to `'menubar'`. ```json { "layout": { "optionsMenu": { "position": "menubar" } } } ``` The options menu automatically aligns to the **right region**. It appears after any links defined in the `right` array. ::: callout info "Automatic Fallback" If the `menubar` is disabled, assigned utilities automatically fall back to the `sidebar-top` position. ::: ## Custom Styling Use CSS variables in your custom stylesheets to override the menubar appearance. See [Custom CSS & JS](../theming/custom-css-js.md) for details. ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-colour); --menubar-text: var(--docmd-text-primary); } ``` --- ## [Navigation Configuration](https://docs.docmd.io/configuration/navigation/) --- title: "Navigation Configuration" description: "Structure your sidebar, categorise links, and configure icons for readers and search engines." --- The compiler provides explicit control over your site navigation. A clear navigation hierarchy creates a logical reading sequence. This optimises the SPA experience and provides a clear context map for search indexing and AI models. ## 1. The Navigation Schema An array of link objects in your `docmd.config.json` file controls the sidebar. Each object is a direct link or a nested category group. <img width="260" class="with-border" src="/assets/previews/navigation-hierarchy.webp"> ```json { "navigation": [ { "title": "Overview", "path": "/", "icon": "home" }, { "title": "Quick Start", "path": "/getting-started/quick-start", "icon": "rocket" } ] } ``` ## 2. Supported Properties Every item supports these settings: | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | `title` | `String` | Yes | The text displayed in the sidebar menu. | | `path` | `String` | No | Target URL. Relative local paths must begin with a forward slash (`/`). | | `icon` | `String` | No | Name of any [Lucide Icon](external:https://lucide.dev/icons) in kebab-case format (e.g., `git-branch`). | | `children` | `Array` | No | An array of nested navigation items to establish a submenu. | | `collapsible`| `Boolean`| No | When `true`, the user can expand or collapse the category folder. | | `external` | `Boolean`| No | When `true`, opens the link in a new browser tab. | ## 3. Organising Section Groups Structure your sidebar using two primary grouping methods: ### Clicking Group (Direct Page + Child Folders) Specify a `path` along with `children` for a category header. Clicking the title loads the landing page and expands the child links. ```json { "title": "Cloud Services", "path": "/cloud/overview", "children": [ { "title": "AWS Setup", "path": "/cloud/aws" }, { "title": "GCP Setup", "path": "/cloud/gcp" } ] } ``` ### Static Label (Category Headers Only) Omit the `path` parameter. The header serves as a non-clickable title grouping related links. Use this to divide major technical categories without a single landing page. ```json { "title": "Formatting & Elements", "icon": "layout-grid", "children": [ { "title": "Syntax Guide", "path": "/content/syntax" }, { "title": "Rich Containers", "path": "/content/containers" } ] } ``` ## 4. Automated Breadcrumbs The engine automatically generates contextual breadcrumbs for every page. These display directly above the main page header to assist with rapid orientation. <img width="500" class="with-border" src="/assets/previews/navigation-breadcrumb.webp"> ### Key Behaviours * **Automatic Resolution**: The engine traces the active route through your navigation tree to construct the hierarchy. * **Active Indicator**: The current page is the final, unlinked breadcrumb item. * **Mobile Optimisation**: Breadcrumbs simplify or hide dynamically on small viewports to save screen space. ### Disabling Breadcrumbs Breadcrumbs are enabled by default. Update your site layout options to disable them globally: ```json { "layout": { "breadcrumbs": false } } ``` ## 5. Navigation Resolution Cascading The compiler uses a "closest file wins" cascading resolution system. This supports multiple versions or languages without bloating your global configuration. ```text my-project/ ├── docmd.config.json [Level 3: Global Config] - Default Fallback ├── docs-v1.0/ │ ├── navigation.json [Level 2: Version Navigation] - Overrides Global │ └── zh/ │ └── navigation.json [Level 1: Language Navigation] - Absolute Priority ``` 1. **Level 1: Language-Specific** (`navigation.json` inside a locale folder): Overrides all settings for this specific language and version. 2. **Level 2: Version-Specific** (`navigation.json` inside a version folder): Overrides global configuration for this version across all languages. 3. **Level 3: Global Configuration** (`config.navigation`): The base fallback definition in the central configuration file. ### Smart Broken-Link Prevention The engine automatically checks if targeted files exist during Level 2 or 3 navigation fallback. Missing files are filtered out of the sidebar dynamically. This eliminates broken links for older versions or missing translations. ## 6. Icon Integration The compiler includes the complete **Lucide Icon** system. Use the official Lucide name in kebab-case format (e.g., `settings`, `folder-open`, `book-marked-line`) to apply an icon. ::: callout tip "Optimising Sidebar Labels" icon:sparkles Keep sidebar titles clear and descriptive. A concise navigation structure allows AI agents to parse your site map easily from the compiled `llms.txt` feed. ::: --- ## [General Configuration](https://docs.docmd.io/configuration/overview/) --- title: "General Configuration" description: "Configure docmd.config.json to manage branding, custom schemas, routing, layout behaviour, and build engines." --- The `docmd.config.json` file is the central configuration for your workspace. It controls site styling, sidebar hierarchies, localisation details, and compiler options. ## 1. The Configuration Schema JSON is the standard configuration format. This allows high-performance serialisation across the engine's worker pools. However, `docmd.config.js` and `docmd.config.ts` remain fully supported if you need dynamic JavaScript logic. ```json { "title": "My Project", "url": "https://docs.myproject.com", "src": "docs", "out": "site", "base": "/" } ``` ## 2. Core Settings These top-level parameters configure the compiler's base inputs and destinations. | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `title` | `String` | `"Documentation"` | The formal name of your site. Appears in navigation headers and browser title tabs. | | `url` | `String` | `null` | Your canonical production URL. Critical for SEO validation, Sitemap indexing, and OpenGraph metadata. | | `src` | `String` | `"docs"` | Relative path to the folder containing your source Markdown (.md) files. | | `out` | `String` | `"site"` | Relative path where the compiler writes the optimised production static site. | | `base` | `String` | `"/"` | The root base path of your site (e.g., set to `/docs/` if hosting in a subfolder). | | `tmp` | `String` | `null` | Custom directory for temporary compile files and caching. Defaults to an isolated system temp folder. | | `i18n` | `Object` | `null` | Multi-language parameters. See the [Localisation Guide](localisation/translated-content.md). | | `plugins` | `Object` | `{}` | Key-value mapping to configure standard and custom plugins. See [Plugins Guide](../plugins/usage.md). | | `engine` | `String` | `"js"` | The active processing engine: `"js"` or `"rust"` (preview). | ## 3. Branding & Identity Manage how your brand appears in the header and browser tabs. ```json { "logo": { "light": "assets/images/logo-dark.png", "dark": "assets/images/logo-light.png", "href": "/", "alt": "Company Logo", "height": "32px" }, "favicon": "assets/favicon.ico" } ``` ## 4. UI Layout & Behaviour The engine provides a modular header and sidebar layout. Customise functional regions. Change component visibility like search and dark-mode toggles. Enable or disable breadcrumbs. ```json { "layout": { "spa": true, "header": { "enabled": true }, "sidebar": { "collapsible": true, "defaultCollapsed": false }, "optionsMenu": { "position": "header", "components": { "search": true, "themeSwitch": true } } } } ``` See the [Layout & UI Zones](layout-ui.md) guide for full visual customisation options. ## 5. Core Engine Features Fine-tune how the parser processes your content files. ```json { "minify": true, "autoTitleFromH1": true, "copyCode": true, "pageNavigation": true, "markdown": { "breaks": true } } ``` | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `minify` | `Boolean` | `true` | Compresses output HTML and JS structures for maximum speed. | | `autoTitleFromH1` | `Boolean` | `true` | Resolves missing page titles using the first H1 header in the file. | | `copyCode` | `Boolean` | `true` | Displays a "Copy Code" button on the top-right of syntax blocks. | | `pageNavigation` | `Boolean` | `true` | Generates a right-hand "On This Page" table of contents automatically. | | `markdown.breaks` | `Boolean` | `true` | Standardises line breaks. Set to `false` if you wrap markdown lines at 80 columns. | ::: callout warning "Standalone editLink Deprecated" icon:alert-triangle The standalone `editLink` configuration is deprecated. Use the core [Git plugin](../plugins/git.md) instead. It provides identical edit link functionality alongside commit timestamps and metadata logs. ::: --- ## [Redirects & 404](https://docs.docmd.io/configuration/redirects/) --- title: "Redirects & 404" description: "Configure metadata-based redirects and custom branded 404 error pages for static deployments." --- Static hosting environments lack server-side logic (like Nginx rules) for dynamic routing. docmd generates native HTML failsafes to handle redirection and error states automatically. ## Server-less Redirects Forward traffic from old URLs to new destinations by defining mappings in the `redirects` object. ```json { "redirects": { "/setup": "/getting-started/installation", "/v1/api": "/api-reference" } } ``` ### Technical Implementation When you define a redirect, the engine creates an `index.html` file at the old path containing a `<meta http-equiv="refresh">` tag. This strategy ensures: 1. **Seamless Redirection**: Users forward to the new destination instantly. 2. **SEO Preservation**: Search engines recognise the redirection to maintain link equity. 3. **Analytics Tracking**: Page views register before the redirect occurs. ## Branded 404 Pages When users request a missing URL, static hosts automatically load a root `404.html` file. docmd generates this file by default. It inherits your site's theme, sidebar, and SPA functionality perfectly. ### Customising Error Content Personalise the 404 error message in your configuration: ```json { "notFound": { "title": "404: Page Not Found", "content": "We couldn't find the page you're looking for. Use the sidebar to find your way back." } } ``` ::: callout tip "Local Development" icon:lightbulb The development server automatically serves your custom 404 page for missing files. Test the error experience locally. ::: --- ## [Versioning](https://docs.docmd.io/configuration/versioning/) --- title: "Versioning" description: "Enable multi-version documentation with seamless switching, sticky path preservation, and isolated build directories." --- docmd features a native Versioning Engine. Manage and serve multiple versions of your project simultaneously. The engine automatically handles URL routing, sidebar updates, and switching logic. ## Directory Organisation Organise your documentation into versioned source folders. A common pattern keeps the active version in `docs/` and archived versions in directories prefixed with `docs-`. ```text my-project/ ├── docs/ # Latest Version (Main) ├── docs-v1/ # Legacy Version ├── docmd.config.json ``` ## Configuration <img width="500" class="with-border" src="/assets/previews/menu-versioning.webp"> Define your versions within the `versions` object: ```json { "versions": { "current": "v2", "position": "sidebar-top", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (Latest)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x" } ] } } ``` ## Core Features ### 1. Root SEO (The "Current" Version) The `current` version generates directly at your output root (e.g., `mysite.com/`). This ensures search traffic always lands on your most up-to-date documentation. ### 2. Isolated Sub-directories Non-current versions build automatically into subfolders matching their `id`. * `v2 (Current)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. Sticky Switching (Path Preservation) docmd preserves the relative path when users switch versions. If a user reads `mysite.com/getting-started` and switches to **v1**, they automatically redirect to `mysite.com/v1/getting-started` (if the page exists). ### 4. Asset Isolation Each version inherits your global `assets/` directory. docmd isolates them during the build to prevent style leakage or conflicts. ### 5. Versioned Navigation Each version can maintain an independent navigation structure. docmd uses a cascading priority system to resolve the sidebar. See [Navigation Configuration](navigation.md) for details on the resolution hierarchy. ## Best Practices 1. **Semantic IDs**: Use concise, URL-friendly IDs like `v1`, `v2`, or `beta`. 2. **Navigation Parity**: Maintain consistent folder structures across versions to maximise "Sticky Switching". 3. **Unified Configuration**: Do not create separate config files for each version. docmd processes all versions in a single pass. --- ## [Workspaces](https://docs.docmd.io/configuration/workspaces/) --- title: "Workspaces" description: "Build multiple independent documentation projects from a single docmd instance, with global configuration cascading and a built-in Project Switcher." --- Workspaces let you build and deploy multiple documentation projects from one repository. Each project keeps its own configuration. Global settings defined at the workspace root cascade automatically into every project. ```text docs.example.com/ → Main documentation docs.example.com/sdk/ → SDK reference docs.example.com/cli/ → CLI documentation ``` ## Setup ### 1. Directory Structure One directory per project. Shared assets and global configuration live at the repository root. ```text my-docs/ ├── assets/ ← shared assets (all projects inherit these) ├── main-docs/ │ ├── docmd.config.json ← project config (overrides root defaults) │ └── docs/ ← project content ├── sdk-docs/ │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← workspace root config └── package.json ``` ### 2. Root Workspace Config The root `docmd.config.json` uses the `workspace` key. Any top-level keys (e.g. `theme`, `menubar`, `logo`) act as **global defaults** for every project. ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Docs" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK Reference" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg" }, "menubar": [ { "text": "GitHub", "url": "https://github.com/my-org/my-repo", "external": true } ] } ``` #### `workspace` Options | Key | Type | Description | | :-- | :--- | :---------- | | `projects` | `Array` | List of project entries. At least one must use `prefix: "/"`. | | `switcher` | `Object` | Controls the [Project Switcher](#project-switcher) visibility and position. | #### Project Entry Fields | Key | Type | Required | Description | | :-- | :--- | :------- | :---------- | | `prefix` | `String` | ✅ | URL prefix. Use `"/"` for the root project. | | `src` | `String` | ✅ | Directory path (relative to CWD) containing the project's content and optional `docmd.config.json`. | | `title` | `String` | - | Display name shown in the Project Switcher UI. | ### 3. Project-Level Config Each project directory can have its own `docmd.config.json`. Settings defined here **override** the workspace root defaults. ```json { "title": "SDK Reference", "src": "docs", "plugins": { "search": {}, "openapi": {} } } ``` If no local config file is found, the engine applies zero-config auto-routing using the workspace defaults. ### 4. Global Configuration Cascading Any key defined in the root workspace config automatically applies to every project. Project configs can selectively override any of these globals. | Layer | Precedence | | :---- | :--------- | | Root workspace config | Lowest (applied first as defaults) | | Project `docmd.config.json` | Higher (overrides root defaults) | | Project `navigation.json` | Highest (always wins for navigation) | **Example**: Define your global `theme` and `menubar` once at the root. Each project only needs to set `title`, `src`, and its own `plugins`. ::: callout info "Navigation Priority" icon:info A project-level `navigation.json` file **always takes precedence** over any `navigation` array defined in the workspace root config. If neither exists, docmd falls back to automatic directory scanning. ::: ## Project Switcher The Project Switcher renders a slim UI component for navigating between workspace projects. ### Configuration ```json { "workspace": { "switcher": { "enabled": true, "position": "sidebar-top" } } } ``` | Position | Description | | :------- | :---------- | | `sidebar-top` (default) | Pinned at the top of the sidebar, above navigation. | | `sidebar-bottom` | Pinned at the bottom of the sidebar. | | `options-menu` | Integrated into the header options menu alongside search and theme toggles. | The switcher only renders when two or more projects are defined. ## Assets ### Shared Assets Place logos, favicons, and global CSS in the root `assets/` directory. The engine copies these into every project's output automatically during both `dev` and `build`. ### Project-Specific Assets Each project can have its own `assets/` directory. Project assets take priority over shared assets when filenames conflict. ## Building & Development ### Dev Server ```bash npx @docmd/core dev ``` Builds all projects and serves them from a single port. File changes trigger **targeted, per-project** rebuilds - only the modified project re-renders, not the whole workspace. Root config changes trigger a full workspace rebuild. ### Production Build ```bash npx @docmd/core build ``` Outputs a single static directory. All projects merge into their respective subpaths. No reverse proxy or complex CI pipelines are required. ## Rules & Constraints 1. **Root Project Required**: Exactly one project must have `prefix: "/"`. 2. **Unique Prefixes**: Every project must use a unique URL prefix. 3. **`out` in Root Only**: Only the root workspace config controls the output directory. Child project configs must not define `out`. 4. **No Prefix Conflicts**: If a root project has a folder named `sdk/`, and another project uses `prefix: "/sdk"`, the engine emits a conflict warning. The prefixed project always wins. ## Migrating from Legacy Configurations The pre-0.8.3 `projects` array syntax and other legacy configuration keys are automatically normalised to the modern `workspace` schema for backward compatibility. While manual updates are strictly not required, you can automatically upgrade your configuration file to the modern schema using the CLI. ::: callout tip "Migrate with one command" icon:lightbulb Run `npx @docmd/core migrate --upgrade` to automatically rewrite your root configuration to the current schema. ::: --- ## [Zero-Config](https://docs.docmd.io/configuration/zero-config/) --- title: "Zero-Config" description: "Understand the heuristics engine of docmd that automatically structures your site without files." --- `docmd` features a smart heuristics engine designed to parse and structure your documentation automatically. You can start building, serving, and translating your documentation without writing a single line of configuration. ## How It Works When run without a `docmd.config.json` file, the engine automatically triggers **Zero-Config Mode**. It scans the workspace directory for content and applies the following heuristics: ### 1. Source Directory Detection The engine looks for documentation files in these candidate directories in order: 1. `docs/` 2. `src/docs/` 3. `documentation/` 4. `content/` 5. `.` (Root directory fallback) If one of the candidate directories is found and contains Markdown files, it is selected as the source. If no directory is found, but the project root has Markdown files, the root directory is used (automatically ignoring `node_modules`, `.git`, output folders like `site/`, `dist/`, and `out/`). If no documentation content is found at all, `docmd` initializes a fresh starter structure automatically. ### 2. Heuristics for Versions and Locales The folder structure is scanned to dynamically extract versioning and localization metadata: - **Versions**: Subdirectories matching `v[0-9]+` (e.g., `v1.0`, `v08`) are parsed as documentation versions. - **Locales**: Subdirectories with two-letter language codes (e.g., `en`, `de`, `zh`) are treated as localized variants. - **Structure Extraction**: The highest version is designated as the current release, and the first locale found (prioritizing `en` if present) is set as the default language. ### 3. Automatic Navigation Routing If there are no root-level versions or locales, the engine builds a navigation tree dynamically by analyzing the file structure: - Subdirectories are mapped to navigation groups. - Titles are generated dynamically from file basenames. E.g., `getting-started.md` is formatted as `Getting Started`. - Index files (`index.md`, `README.md`) are routed as the landing page of the current directory. ## Zero-Config Best Practices To get the most out of Zero-Config mode, follow these structure recommendations: - **Explicit file naming**: Use clear, hyphenated or camelCase file names. The autoloader converts them to readable titles. - **Folder-based sections**: Place related documents inside subfolders to automatically group them in the sidebar. - **Index fallback**: Always place an `index.md` or `README.md` at the root of your source folder to serve as the landing page. - **Clean output path**: If you are using the root folder `.` as your source, keep your built assets in the default `site/` folder which is automatically ignored. --- ## [Buttons](https://docs.docmd.io/content/containers/buttons/) --- title: "Buttons" description: "Inject clear, highly visible call-to-actions directly into your documentation." --- Buttons are interactive components designed for navigation and call-to-actions. They can point to internal documentation pages or external resources. ## Syntax Reference ```markdown ::: button "Label text" target_url [property:value...] ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Path** | `/path/` | Relative project URL. Resolves automatically for SPA navigation. | | **External** | `external:URL`| Opens the target URL in a new browser tab (`target="_blank"`). | | **Colour** | `color:VALUE` | Applies a background colour (supports CSS names or Hex codes). | | **Icon** | `icon:NAME` | Adds a [Lucide](external:https://lucide.dev/icons) icon before the label. | ## Examples ### Internal Navigation Use relative Markdown paths to ensure seamless transitions within the docmd SPA. ```markdown ::: button "Install docmd" ../../getting-started/installation.md ``` ::: button "Install docmd" ../../getting-started/installation.md ### External Resource Link Prepend `external:` to the URL to force the link to open in a new tab. ```markdown ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ``` ::: button "View GitHub Repository" external:https://github.com/docmd-io/docmd ### Styling & Icons Match buttons to your brand identity using colour overrides and Lucide icons to enhance visual clarity. ```markdown ::: button "Success Confirmation" ./#success color:#228B22 ::: button "Danger Action" ./#delete color:crimson icon:alert-circle ::: button "View Source" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "Success Confirmation" ./#success color:#228B22 ::: button "Danger Action" ./#delete color:crimson icon:alert-circle ::: button "View Source" external:https://github.com/docmd-io/docmd icon:github ## Critical Note: Self-Closing Logic Buttons are self-closing. Adding a terminal `:::` line immediately after a button will terminate the **parent container** (e.g., a Card or Tab), potentially breaking your layout. **Incorrect Sequence:** ```markdown ::: card "Setup" ::: button "Begin" ../../setup.md ::: <-- Error: This closes the Card prematurely. ::: ``` **Correct Sequence:** ```markdown ::: card "Setup" ::: button "Begin" ../../setup.md ::: <-- Correct: This closes the Card cleanly. ``` --- ## [Callouts](https://docs.docmd.io/content/containers/callouts/) --- title: "Callouts" description: "Highlight critical warnings, pro-tips, and background context using semantic visual blocks." --- Callouts isolate information that requires the reader's immediate attention. docmd provides five semantic types, each with distinct styling and iconography. ::: callout info "Migration-Friendly Aliases" If migrating from VitePress or Docusaurus, you can use their native syntax: - `:::tip`, `:::warning`, `:::danger`, `:::info` (VitePress) - `:::note`, `:::caution` (Docusaurus) These aliases render identically to their docmd equivalents. Spaceless syntax like `:::callout` also works. ::: ## Syntax Reference ```markdown ::: callout type "Title text" [property:value...] The content or warning goes here. ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Type** | `info` \| `tip` \| `warning` \| `danger` \| `success` | The semantic intent which defines default colours and iconography. | | **Title** | `"String"` | Optional. Overrides the default semantic label with a custom title. | | **Icon** | `icon:NAME` | Optional. Overrides the default icon with a custom [Lucide](external:https://lucide.dev/icons) icon. | ### Supported Types | Type | Visual Signal | | :--- | :--- | | `info` | Contextual background or helpful non-critical information. | | `tip` | Performance shortcuts or best practices. | | `warning` | Potential issues or deprecated features to monitor. | | `danger` | Risk of data loss, breaking changes, or critical failures. | | `success` | Confirmation of a successful configuration or build. | ## Examples ### Basic Callout A minimal callout without a title uses the type as its default label. ```markdown ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ``` ::: callout info Legacy configuration schemas remain supported but are no longer recommended. ::: ### Custom Title & Icon Override the default label and icon with a custom title and any Lucide icon name. ```markdown ::: callout warning "Breaking Change" icon:alert-triangle The internal WebSocket RPC system is officially deprecated. ::: ``` ::: callout warning "Breaking Change" icon:alert-triangle The internal WebSocket RPC system is officially deprecated. ::: ### Rich Content Composition Callouts support full Markdown. Embed code blocks and buttons directly within the alert. ````markdown ::: callout tip "Optimised Local Testing" icon:command Use the preserve flag to maintain build files during dev sessions: ```bash npx @docmd/core dev --preserve ``` ::: button "CLI Flag Reference" /cli-commands ::: ```` ::: callout tip "Optimised Local Testing" icon:command Use the preserve flag to maintain build files during dev sessions: ```bash npx @docmd/core dev --preserve ``` ::: button "CLI Flag Reference" ./#cli-commands ::: ::: callout tip "Prioritised Logic for AI" For LLMs, callouts act as **High-Priority Anchors**. Use `::: callout danger` to document breaking changes - this provides a clear signal that the AI model must prioritise that information. ::: --- ## [Cards](https://docs.docmd.io/content/containers/cards/) --- title: "Cards" description: "Organise information into framed, visually distinct containers. Perfect for feature grids and landing pages." --- Cards encapsulate related content into a distinct, bordered frame with an optional header, providing clear visual hierarchy for your documentation. ## Syntax Reference ```markdown ::: card "Title text" [property:value...] This is the primary content area of the card. ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Title** | `"String"` | Optional header title rendered at the top of the card. | | **Icon** | `icon:NAME` | Optional. Adds a [Lucide](external:https://lucide.dev/icons) icon next to the header title. | ## Examples ### Feature Highlight Use a card to frame a single technical capability with a clear title and icon. ```markdown ::: card "Asynchronous Generation" icon:zap The core engine uses a non-blocking I/O pipeline, generating thousands of pages in milliseconds. ::: ``` ::: card "Asynchronous Generation" icon:zap The core engine uses a non-blocking I/O pipeline, generating thousands of pages in milliseconds. ::: ### Rich Content Cards accept any standard Markdown, including code blocks and buttons. ````markdown ::: card "Instant Localisation" Prepare your documentation for a global audience using the built-in i18n support. ```bash docmd add i18n ``` ::: button "L10n Strategy Guide" /guides/localization ::: ```` ::: card "Instant Localisation" Prepare your documentation for a global audience using the built-in i18n support. ```bash docmd add i18n ``` ::: button "L10n Strategy Guide" ./#localization ::: ### Multi-Column Layout Wrap multiple cards inside a `grids` container for a responsive multi-column layout. ```markdown ::: grids ::: grid ::: card "Primary Node" Configuration for the master instance. ::: ::: ::: grid ::: card "Secondary Node" Configuration for redundant slave instances. ::: ::: ::: ``` ::: grids ::: grid ::: card "Primary Node" Configuration for the master instance. ::: ::: ::: grid ::: card "Secondary Node" Configuration for redundant slave instances. ::: ::: ::: ::: callout tip "Semantic Clustering for AI" icon:lightbulb In the `llms-full.txt` stream, content wrapped in a `card` is treated by AI agents as a **Cohesive Topic Cluster**. Utilising cards to segment unrelated concepts prevents context leakage and ensures LLM-generated summaries remain logically isolated. ::: --- ## [Changelogs](https://docs.docmd.io/content/containers/changelogs/) --- title: "Changelogs" description: "Generate structured, timeline-based version history and release notes." --- The `changelog` container provides a specialised layout for documenting project evolution. It parses version or date headers into a vertical timeline, ensuring historical updates are easily scannable. ## Syntax Reference ```markdown ::: changelog == Label Text Description of the entry goes here. ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Entry Marker** | `==` | The delimiter that defines a new timeline entry within the changelog. | | **Label** | `String` | The text (e.g., version number or date) that renders as a timeline badge on the left. | ## Examples ### Release History Changelogs support rich Markdown within each entry, including lists, callouts, and code blocks. ```markdown ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ``` ::: changelog == v2.0.0 (2026-03-15) ### Major System Overhaul The core engine has been rearchitected for isomorphic execution. * Implemented **SPA Router** for zero-reload navigation. * Introduced the **Isomorphic Plugin** system. ::: callout success This release offers a 40% improvement in initial build speed. ::: == v1.5.1 (2025-12-10) ### Security Patch * Resolved high-severity vulnerability in the internal parser. * Updated dependency `flatted` to `v3.3.2`. == v1.0.0 (2024-05-01) Initial public release. ::: ::: callout tip "Historical Context for AI" Changelogs provide a temporal map for AI agents. The `::: changelog` structure allows an LLM to accurately parse when specific features or security fixes were introduced in the `llms.txt` context stream. ::: --- ## [Collapsible Sections](https://docs.docmd.io/content/containers/collapsible/) --- title: "Collapsible Sections" description: "Embed interactive accordion-style toggles for FAQs, deep-dive content, and spoilers." --- The `collapsible` container creates an interactive, toggleable accordion. It is ideal for FAQs and detailed technical configuration, keeping secondary information accessible without cluttering the primary view. ::: callout info "VitePress Alias" If migrating from VitePress, use `:::details` as an alias for `:::collapsible`. Spaceless syntax like `:::collapsible` also works. ::: ## Syntax Reference ```markdown ::: collapsible [open] "Title text" [property:value...] Main content goes here. ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Open State** | `open` | Optional. If provided, the section initialises in an expanded state. | | **Title** | `"String"` | The text rendered on the toggle bar. Defaults to "Click to expand". | | **Icon** | `icon:NAME` | Optional. Adds a [Lucide](external:https://lucide.dev/icons) icon before the title text. | ## Examples ### Default State A collapsible section is closed by default. Ideal for FAQs and reducing visual density. ```markdown ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ``` ::: collapsible "How do I upgrade docmd?" Run `npm update -g @docmd/core` to fetch the latest stable engine. ::: ### Initially Open Use the `open` flag for sections that should be visible by default but allow users to minimise them. ```markdown ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ``` ::: collapsible open "Environment Prerequisites" 1. Node.js v18+ (LTS recommended) 2. PNPM package manager ::: ### Rich Content Collapsibles can contain any Markdown, including syntax-highlighted code blocks. ````markdown ::: collapsible "Sample JSON Response" ```json { "status": "success", "data": { "version": "0.8.2" } } ``` ::: ```` ::: collapsible "Sample JSON Response" ```json { "status": "success", "data": { "version": "0.8.2" } } ``` ::: ::: callout tip Content inside a `collapsible` is fully indexed by search and included in the `llms.txt` stream. AI agents can answer questions based on hidden technical details while keeping the human-facing interface clean. ::: --- ## [URL Embeds](https://docs.docmd.io/content/containers/embed/) --- title: URL Embeds description: Safely embed dynamic video, social, and interactive content directly into your documents. --- docmd ships natively with the highly-optimised **[embed-lite](external:https://github.com/mgks/embed-lite)** parser. It transforms external URLs into secure, zero-latency UI components automatically. ## Supported Platforms The engine natively supports structured formatters for the following networks: * **Video:** YouTube (including Shorts), Vimeo, Dailymotion, TikTok * **Social:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **Code & Prototyping:** GitHub Gists, CodePen, Figma, Google Maps * **Music:** Spotify, SoundCloud ## Syntax Reference ```markdown ::: embed "target_url" ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **URL** | `"String"` | The absolute URL of the external resource to embed (e.g., a YouTube video, Figma file, or GitHub Gist). | ## Examples ### Video Embed Paste any YouTube, Vimeo, or TikTok URL to render a native, responsive player. ```markdown ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ### Fallback Behaviour If the parser encounters an unsupported or invalid URL, docmd gracefully falls back to a hyperlink button rather than breaking the page. ```markdown ::: embed "https://docs.docmd.io/content/containers/embed/" ``` ::: embed "https://docs.docmd.io/content/containers/embed/" --- ## [Grids](https://docs.docmd.io/content/containers/grids/) --- title: "Grids" description: "Organise layout into auto-adjusting responsive columns without writing HTML." --- Grids provide a native, Markdown-driven layout system. Use the `grids` container to structure elements side-by-side. Columns automatically fill available space and stack vertically on smaller screens. ## Syntax Reference ```markdown ::: grids ::: grid Content for the first column. ::: ::: grid Content for the second column. ::: ::: ``` | Container | Description | | :--- | :--- | | **`::: grids`** | The parent container that initiates the responsive flexbox layout. | | **`::: grid`** | Each child `grid` block acts as an individual column. Add as many as needed. | ## Examples ### Side-by-Side Cards Combine `grids` with `cards` to display multiple features in a clean, responsive layout. ```markdown ::: grids ::: grid ::: card "Speed" icon:zap Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability" icon:layers Designed for massive monorepos and extensive project structures. ::: ::: ::: ``` ::: grids ::: grid ::: card "Speed" icon:zap Built on a non-blocking I/O pipeline for maximum performance. ::: ::: ::: grid ::: card "Scalability" icon:layers Designed for massive monorepos and extensive project structures. ::: ::: ::: ### Three-Column Layout Add a third `grid` block to create a three-column row. Columns automatically balance their widths. ```markdown ::: grids ::: grid ::: card "Search" icon:search Client-side full-text search powered by MiniSearch. ::: ::: ::: grid ::: card "i18n" icon:globe First-class locale routing and translated search indexes. ::: ::: ::: grid ::: card "Themes" icon:palette Built-in dark mode and full CSS variable customisation. ::: ::: ::: ``` ::: grids ::: grid ::: card "Search" icon:search Client-side full-text search powered by MiniSearch. ::: ::: ::: grid ::: card "i18n" icon:globe First-class locale routing and translated search indexes. ::: ::: ::: grid ::: card "Themes" icon:palette Built-in dark mode and full CSS variable customisation. ::: ::: ::: ::: callout tip "Semantic Layouts" The `grids` container keeps your structure purely in Markdown. This results in cleaner source files and ensures LLMs interpret structural relationships accurately. ::: --- ## [Hero Sections](https://docs.docmd.io/content/containers/hero/) --- title: "Hero Sections" description: "Build high-impact landing page headers and marketing highlights purely in Markdown." --- The `hero` container creates visually striking landing page headers. It handles complex layouts including splits, glow effects, and sliders without requiring custom HTML. ## Syntax Reference ```markdown ::: hero [property:value...] # Page Title A short supporting tagline. ::: button "Call to Action" /target-url ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Layout** | `layout:split` \| `layout:slider` | `split` divides the hero into a text area and a side media area. `slider` creates a horizontal scroll-snap carousel. | | **Glow** | `glow:true` | Injects a subtle radial gradient glow in the background. | | **Side Separator** | `== side` | Used with `layout:split`. Everything after this delimiter renders in the secondary (right-hand) area. | | **Slide Separator** | `== slide` | Used with `layout:slider`. Each `== slide` defines a new carousel panel. | ## Examples ### Split Layout Use the `== side` separator to divide content into a primary text area and a secondary media area. ```markdown ::: hero layout:split glow:true # docmd Isomorphic execution. AI-optimised. ::: button "Quickstart" ../../getting-started/quick-start.md color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd Isomorphic execution. AI-optimised. ::: button "Quickstart" ../../getting-started/quick-start.md color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### Slider Layout Use `== slide` separators to build an auto-advancing carousel of content panels. ```markdown ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ``` ::: hero layout:slider == slide # Isomorphic Core The engine renders everywhere. == slide # AI Optimisation Built for the LLM era. ::: ::: callout tip "Best Practices" Use `glow:true` sparingly on dark mode sites for a premium feel. Place `::: button` elements in the primary text section, before `== side`, to ensure they remain visible on mobile screens. ::: --- ## [Custom Interactive Containers](https://docs.docmd.io/content/containers/) --- title: "Custom Interactive Containers" description: "A comprehensive directory of the interactive UI building blocks available in docmd." --- Standard Markdown excels at basic text formatting, but professional technical documentation requires rich structural components to effectively communicate complex logic. `docmd` extends Markdown with a suite of **isomorphic containers** that render into responsive, high-fidelity UI elements. ::: callout tip "Migrating from Other Documentation Engines?" `docmd` supports syntax aliases from **VitePress** and **Docusaurus** out of the box. Containers like `:::tip`, `:::warning`, `:::note`, `:::details`, and `:::caution` work without modification. Spaceless syntax (e.g., `:::tabs` instead of `::: tabs`) is also supported for all containers. ::: ## Block Syntax Reference All containers utilise a consistent block syntax, ensuring a predictable authoring experience across your entire project. ```markdown ::: type "Optional Header Title" This is the primary content area. It supports **Markdown**, imagery, and deep component nesting. ::: ``` | Component | Keyword | Primary Use Case | | :--- | :--- | :--- | | **[Callouts](callouts.md)** | `callout` | Semantic highlights for tips, warnings, and alerts. | | **[Cards](cards.md)** | `card` | Framed structural blocks for feature grids and layout control. | | **[Grids](grids.md)** | `grids` | Auto-adjusting multi-column structural groups. | | **[Tabs](tabs.md)** | `tabs` | Interactive switchable panes for alternative platform instructions. | | **[Steps](steps.md)** | `steps` | Visual numbered timelines for how-to guides and tutorials. | | **[Collapsibles](collapsible.md)** | `collapsible` | Interactive accordion toggles for FAQs and deep-dive technical data. | | **[Buttons](buttons.md)** | `button` | Self-closing, prominent call-to-action navigation links. | | **[Tags](tags.md)** | `tag` | Self-closing, coloured labels for versions, statuses, or inline highlights. | | **[Hero](hero.md)** | `hero` | High-impact landing page sections with layout and slider support. | | **[URL Embeds](embed.md)** | `embed` | Secure, zero-latency embeds for video, social, and interactive content. | | **[Changelogs](changelogs.md)** | `changelog` | Structured, timeline-based version history and release notes. | | **[Nested Containers](nested-containers.md)** | - | Recursive composition patterns for complex, multi-component layouts. | ## The Strategic Importance of Containers Containers facilitate more than visual polish; they provide high-fidelity **Semantic Signals** to the `docmd` engine and downstream AI agents: 1. **AI Context Mapping**: Marking a block as a `callout warning` explicitly tells LLMs to prioritise that information during its reasoning and generation phases. 2. **Structural Integrity**: Combining `cards` with standard CSS allows for the creation of sophisticated landing pages without ever leaving the Markdown environment. 3. **Source Maintainability**: Eliminates "HTML Bloat" in your documentation source, keeping your `.md` files clean and machine-readable. ## Recursive Composition `docmd` supports **Infinite Nesting Depth**. You can compose any container within another to build complex, interactive documentation nodes purely in Markdown. ```markdown ::: card "Architecture Overview" ::: callout info This module utilises an asynchronous I/O pipeline. ::: ::: button "Deep Explore Core Engine" /advanced/developer-guide ::: ``` [Master the Nesting Guide](nested-containers.md) --- ## [Nested Containers](https://docs.docmd.io/content/containers/nested-containers/) --- title: "Nested Containers" description: "Use the recursive parser to combine cards, tabs, and callouts into high-fidelity page layouts." --- docmd uses a recursive parsing engine. You can nest components within each other to build complex, interactive documentation blocks without writing custom HTML. ::: callout warning "Self-Closing Buttons" The `::: button` component is self-closing (single line). Never add a terminal `:::` immediately after it - doing so closes the **parent container**, resulting in a broken layout. ::: ## Examples ### Interactive Resource Block Combine a **Card** for structural framing, **Tabs** for environment-specific instructions, and a **Callout** for critical information. ````markdown ::: card "Monorepo Quickstart" Choose your preferred initialisation path: ::: tabs == tab "Automated" ```bash pnpm onboard ``` ::: callout success This script handles all package installation and build tasks automatically. ::: == tab "Manual" Manually fetch and link the core engine. ::: button "Go to Developer Guide" ../../advanced/developer-guide.md ::: ::: ```` ### Platform-Specific Tutorial Steps Nesting **Tabs** inside **Steps** is a standard pattern for providing platform-specific instructions within a sequential tutorial. ```markdown ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ``` ::: steps 1. **Environment Setup** Configure your local operating system. ::: tabs == tab "macOS" Ensure Homebrew is installed and up-to-date. == tab "Linux" Verify the presence of `curl` and `bash`. ::: 2. **Core Verification** Execute the version check to confirm connectivity. ::: ## Design Constraints | Constraint | Note | | :--- | :--- | | **Recursive Tabs** | Nesting tabs within other tabs is technically supported but strongly discouraged - it creates confusing navigation on smaller viewports. | | **Sequential Conflict** | If you need numbered steps within a tab, use a standard ordered list rather than `::: steps` to avoid layout conflicts. | | **Indentation** | Indentation is not required by the parser, but 2 or 4-space indentation significantly improves source readability. | ::: callout tip "Knowledge Segmentation for AI" Nesting provides clear **Semantic Boundaries**. A `callout` nested within a `card` explicitly scopes that tip to the card's topic in the `llms.txt` stream, preventing context leakage across unrelated sections. ::: --- ## [Steps](https://docs.docmd.io/content/containers/steps/) --- title: "Steps" description: "Convert standard ordered lists into high-impact visual timelines and tutorials." --- The `steps` container transforms a standard Markdown ordered list into a numbered vertical timeline. It is designed for technical tutorials and sequential how-to guides. ::: callout info "Spaceless Syntax" Both `::: steps` and `:::steps` (spaceless) work natively. Use whichever style you prefer. ::: ## Syntax Reference ```markdown ::: steps 1. **Step Title** Step description goes here. 2. **Next Step** Continue the sequence. ::: ``` | Container | Description | | :--- | :--- | | **`::: steps`** | The parent container that transforms child ordered list items into a numbered timeline. | | **`1. `** | Any standard Markdown ordered list item acts as a chronological step. Bold the first line of each item to create a clear title. | ## Examples ### Basic Workflow A straightforward sequence for a common task. ```markdown ::: steps 1. **Initialise Project** Run `npx @docmd/core init` to scaffold your directory. 2. **Author Content** Write your documentation using standard Markdown files. 3. **Build & Deploy** Run `npx @docmd/core build` to generate your static site. ::: ``` ::: steps 1. **Initialise Project** Run `npx @docmd/core init` to scaffold your directory. 2. **Author Content** Write your documentation using standard Markdown files. 3. **Build & Deploy** Run `npx @docmd/core build` to generate your static site. ::: ### Steps with Rich Content Each step can contain code blocks, callouts, and other nested containers. ```markdown ::: steps 1. **Configure Environment** Define your project variables in `docmd.config.json`. ::: callout tip Use `defineConfig` to enable IDE autocompletion for all configuration keys. ::: 2. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash npx @docmd/core build ``` 3. **Deploy to Infrastructure** Synchronise the `site/` directory with S3, Cloudflare Pages, or Vercel. ::: ``` ::: steps 1. **Configure Environment** Define your project variables in `docmd.config.json`. ::: callout tip Use `defineConfig` to enable IDE autocompletion for all configuration keys. ::: 2. **Generate Production Build** Execute the build command to generate a highly optimised static site. ```bash npx @docmd/core build ``` 3. **Deploy to Infrastructure** Synchronise the `site/` directory with S3, Cloudflare Pages, or Vercel. ::: ::: callout tip "Workflow Optimisation" icon:lightbulb AI models interpret the `steps` container as a signal for **Sequential Workflows**. Always start each list item with a **bolded title** - this allows agents to reliably parse the objective of each step from the `llms.txt` context. ::: --- ## [Tabs](https://docs.docmd.io/content/containers/tabs/) --- title: "Tabs" description: "Organise dense, alternative, or multi-language information into switchable interactive panes." --- Tabs present mutually exclusive or related data sets - such as "pnpm vs npm" or "macOS vs Windows". They condense information into a compact, interactive format. ::: callout info "Spaceless Syntax" Both `::: tabs` and `:::tabs` (spaceless) work natively. Use whichever style you prefer. ::: ## Syntax Reference ```markdown ::: tabs == tab "Label" [property:value...] Content for this tab. == tab "Another Label" Content for the second tab. ::: ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Label** | `"String"` | The text displayed on the tab trigger button. | | **Icon** | `icon:NAME` | Optional. Adds a [Lucide](external:https://lucide.dev/icons) icon before the label text. | ## Examples ### Package Manager Instructions Show installation commands for multiple package managers in a single compact block. ````markdown ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ```` ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### Multi-Language Code Snippets Keep programming environments cleanly separated with tab icons for quick visual identification. ````markdown ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.json'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.json'); ``` ::: ```` ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.json'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.json'); ``` ::: ## Constraints | Constraint | Note | | :--- | :--- | | **Nesting Depth** | Tabs cannot nest inside other tab components. | | **Interactive Conflict** | Do not nest `::: steps` inside a tab. Use a standard ordered list instead. | | **Responsive Limit** | Limit tab counts to 6 per block for mobile compatibility. | | **State Persistence** | The active tab is tracked by the SPA router. Selecting "pnpm" on one page activates it on subsequent pages. | ::: callout tip "AI Context Mapping" Always include the target language or platform in the tab label (e.g., `== tab "TypeScript"`). This helps AI agents instantly identify the correct context stream without having to infer it from code content. ::: --- ## [Tags](https://docs.docmd.io/content/containers/tags/) --- title: "Tags" description: "Use the tag container to label versions, statuses, or highlight short text snippets inline." --- The `tag` container is a self-closing component that inserts small, pill-shaped badges inline. Tags retain their compact proportions everywhere - they do not inherit heading sizes or surrounding text styles. ## Syntax Reference ```markdown ::: tag "Label text" [property:value...] ``` | Parameter | Type | Description | | :--- | :--- | :--- | | **Label** | `"String"` | The text displayed inside the pill-shaped badge. | | **Colour** | `color:VALUE` | Applies a background colour (supports CSS names or Hex codes). Automatically calculates a contrasting text colour. | | **Icon** | `icon:NAME` | Adds a [Lucide](external:https://lucide.dev/icons) icon inside the badge. | | **Link** | `link:URL` | Makes the tag a clickable hyperlink. External URLs open in a new tab. | ## Examples ### Version Badge Use a coloured tag inline to mark when a feature was introduced. ```markdown This feature was added in ::: tag "v0.8.2" color:blue and works perfectly. ``` This feature was added in ::: tag "v0.8.2" color:blue and works perfectly. ### Status Labels Use tags for status indicators across a page. Colours are fully customisable. ```markdown ::: tag "Deprecated" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stable" color:#22c55e ::: tag "Verified" icon:check-circle color:#10b981 ``` ::: tag "Deprecated" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stable" color:#22c55e ::: tag "Verified" icon:check-circle color:#10b981 ### Linked Tag Add `link:` to make a tag act as a hyperlink, useful for cross-referencing release notes or external resources. ```markdown Check out the latest ::: tag "Release Notes" icon:external-link link:../../release-notes/0-8-2.md ``` Check out the latest ::: tag "Release Notes" icon:external-link link:../../release-notes/0-8-2.md --- ## [Frontmatter Reference](https://docs.docmd.io/content/frontmatter/) --- title: "Frontmatter Reference" description: "The complete guide to page-level metadata and configuration." --- Frontmatter overrides global settings for specific pages. Write it in YAML format at the top of your Markdown files. ## Core Metadata | Key | Type | Description | | :--- | :--- | :--- | | `title` | `String` | **Required.** Sets the HTML `<title>` and the primary section header. | | `description` | `String` | Sets the meta description for SEO and search results. | | `keywords` | `Array` | A list of keywords for the `<meta name="keywords">` tag. | ::: callout warning "Title is Important" icon:triangle-alert The `title` field is strongly recommended. Without it, the engine falls back to the first `# H1` heading or the filename. This can produce less ideal search results. ::: ## Visibility & Indexing | Key | Type | Description | | :--- | :--- | :--- | | `noindex` | `Boolean` | Excludes the page from the internal search index. | | `llms` | `Boolean` | Set to `false` to exclude this page from AI context files (`llms.txt`). | | `hideTitle` | `Boolean` | Hides the title from the sticky header. Useful for custom H1s. | | `bodyClass` | `String` | Adds a custom CSS class to the `<body>` tag. | ## Layout Control | Key | Type | Description | | :--- | :--- | :--- | | `layout` | `String` | Set to `full` to use maximum width and hide the TOC sidebar. | | `toc` | `Boolean` | Set to `false` to disable the Table of Contents entirely. | | `noStyle` | `Boolean` | Disables the entire UI (Sidebar, Header, Footer) for custom pages. | | `titleAppend` | `Boolean` | Set to `false` to prevent appending the site title to metadata tags. Default is `true`. | ### `noStyle` Component Control When `noStyle: true` is active, you must opt-in to the components you wish to retain. ```yaml --- noStyle: true components: meta: true # Injects SEO metadata favicon: true # Injects site favicon css: true # Injects docmd-main.css theme: true # Injects theme-specific styling highlight: true # Injects syntax highlighting scripts: true # Injects the SPA router logic sidebar: true # Injects the navigation sidebar footer: true # Injects the site footer --- ``` ## Plugin Overrides ### SEO (`seo`) * `image`: Custom social share image URL for the page. * `aiBots`: Set to `false` to block AI crawlers from this page. * `canonicalUrl`: Sets a custom canonical link for SEO. --- ## [Live Preview](https://docs.docmd.io/content/live-preview/) --- title: "Live Preview" description: "Run the engine entirely in the browser without a backend server using the Live architecture." --- The compiler features a modular architecture separating filesystem operations from core logic. This enables the engine to run entirely within the browser. It facilitates live editors and CMS previews without a Node.js backend. <img width="720" class="with-border" src="/assets/previews/live-editor-preview.webp"> ::: button "Open Live Editor" external:https://live.docmd.io ## The Live Editor The built-in Live Editor provides a high-performance, split-pane interface. Author your Markdown in the left pane. Watch the rendered output update and sync in real-time on the right. ### Local Execution Launch the Live Editor locally within your project: ```bash npx @docmd/core live ``` ### Static Distribution Generate a standalone, static version of the editor. Host it on platforms like Vercel or GitHub Pages: ```bash npx @docmd/core live --build-only ``` This generates a `dist/` directory. It contains the `index.html` entry point and the bundled `docmd-live.js` engine. ## Embedding @docmd/core Integrate the browser-compatible bundle into your applications. Provide internal Markdown rendering or preview capabilities. ### 1. Resource Integration Include the required CSS and JavaScript bundles from your assets or a CDN: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. Isomorphic API The global `docmd` object provides the `compile` method for instant rendering. ```javascript const html = await docmd.compile(markdown, { "title": "Dynamic Preview", "theme": { "appearance": "dark" } }); document.getElementById("preview-frame").srcdoc = html; ``` ::: callout tip "AI Feedback Loops" icon:sparkles The Live architecture is ideal for building **AI-Agent Sandboxes**. Pipe an agent's suggested changes to a live-compilation buffer. Visually verify AI suggestions before committing changes to your repository. ::: --- ## [docmd : Bespoke No-Style Page Demo](https://docs.docmd.io/content/no-style-example/) --- title: "docmd : Bespoke No-Style Page Demo" description: "A functional demonstration of the noStyle architectural feature." noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: centre; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-colour); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>Bespoke Page Architecture</h1> <p>Demonstrating the absolute layout control enabled via <code>noStyle: true</code>.</p> </div> <div class="demo-card"> <h2>Logical Foundation</h2> <p> This demonstration utilises the <code>noStyle: true</code> frontmatter directive to bypass the global documentation layout (Sidebar, Header, and TOC). This provides a "Zero-Friction" canvas for creating marketing landing pages or custom product dashboards. </p> <h3>Enabled System Components</h3> <p>When in No-Style mode, you explicitly opt-in to the documentation engine's core features:</p> <ul> <li><strong>SEO Meta Engine</strong>: Structured tags and social graph data are retained.</li> <li><strong>Project Branding</strong>: Global favicon injection remains active.</li> <li><strong>Foundational Typography</strong>: The processed <code>docmd-main.css</code> provides base styling.</li> <li><strong>Theme Synchronisation</strong>: Light/Dark mode state is fully preserved.</li> <li><strong>Interactive Capabilities</strong>: The SPA router and component logic remain available.</li> </ul> <h3>Technical Implementation</h3> <p> The layout for this page is authored using standard HTML wrappers and scoped CSS defined within the <code>customHead</code> frontmatter field. This ensures zero CSS leakage to the rest of the documentation site. </p> <a href="/content/no-style-pages/" class="demo-button">Analyse the Implementation Guide →</a> </div> </div> --- ## [No-Style Pages](https://docs.docmd.io/content/no-style-pages/) --- title: "No-Style Pages" description: "Create custom landing pages and unique layouts by disabling the default docmd theme." --- docmd allows you to bypass the standard documentation layout (Sidebar, Header, Footer) on a per-page basis. This is ideal for creating landing pages or custom dashboards while retaining access to the engine's components. ## Enabling No-Style Mode To disable the global UI, add `noStyle: true` to the page's frontmatter. ```yaml --- title: "Product Showcase" noStyle: true components: meta: true # Retain SEO and OpenGraph tags favicon: true # Retain site favicon css: true # Inject docmd-main.css for typography --- <!-- Raw HTML or specialised Markdown goes here --> <div class="hero"> <h1>Next-Gen Documentation</h1> <p>Zero-config. Isomorphic. AI-Ready.</p> </div> ::: callout info "Infinite Nesting Support" icon:info Even with `noStyle: true`, all standard docmd containers like `::: card`, `::: tabs`, and `::: hero` are fully supported and can be nested infinitely. ::: ``` ## Component Opt-In When `noStyle` is active, you start with a blank canvas. Selectively re-enable core system components as needed: | Component | Description | | :--- | :--- | | `meta` | Injects `<title>`, SEO meta tags, and structured OpenGraph data. | | `favicon` | Injects the project-wide favicon. | | `css` | Injects `docmd-main.css`. Highly recommended for foundational grid and typography. | | `menubar` | Injects the site's top menubar. | | `theme` | Injects the active theme's CSS variables and appearance overrides. | | `scripts` | Injects interactive component logic (requires `mainScripts: true`). | | `spa` | Enables the single-page application router (requires `scripts: true`). | ## Composable Landing Pages The primary power of `noStyle` is using docmd components as high-fidelity "widgets" on a blank canvas. You aren't limited to raw HTML; you can build complex structural designs purely in Markdown. ### Building a Modern Entry Point ```yaml --- title: "Welcome" noStyle: true components: meta: true css: true menubar: true # Use the site's top navigation scripts: true # Enable interactive components mainScripts: true --- ::: hero layout:split glow:true # Build Documentation that Wows. The zero-config engine for modern engineering teams. ::: button "Get Started" ../getting-started/quick-start.md color:blue ::: button "GitHub" github:docmd-io/docmd color:gray == side ::: embed "https://www.youtube.com/watch?v=dQw4w9WgXcQ" ::: ::: ::: grids ::: card "Zero Configuration" Just write markdown. No complex React logic or build scripts. ::: ::: card "AI Optimised" Structure-aware parsing for the LLM era. ::: ::: card "Fast Without the Framework Tax" Static generation with isomorphic SPA navigation. ::: ::: ``` ::: callout tip "AI-Generated Layouts" icon:lightbulb Because `noStyle` pages support raw HTML alongside docmd containers, they are perfectly suited for **AI-driven UI design**. Prompt an AI: *"Design a modern hero section using utility classes and docmd buttons, wrapped in a noStyle container."* The AI can iterate within your static site pipeline with zero configuration. ::: ## String Replacement (i18n for noStyle) When your site has [i18n configured](../configuration/localisation/index.md), themed documentation pages get full server-side translations automatically. However, `noStyle` pages use custom HTML. docmd provides **string replacement** to translate HTML via `data-i18n` attributes and JSON translation files. ::: callout info "Why this only works for noStyle pages" icon:info String replacement finds elements with `data-i18n` attributes and swaps their text content. Standard Markdown content renders to plain `<p>`, `<h2>`, `<li>` tags without these attributes. For standard Markdown, use [Directory Mode](../configuration/localisation/translated-content.md). ::: ### How It Works There are two modes for string replacement: - **Server-side (recommended)**: With `stringMode: true` in your i18n config, docmd resolves `data-i18n` attributes **at build time**. It generates fully translated HTML in `/{locale}/` directories for search engines. - **Client-side**: The `docmd-i18n-strings.js` script loads translations at runtime via XHR. This is useful for in-place switching without page reloads. Both modes use the same `data-i18n` attribute syntax and JSON file format. 1. Place JSON translation files inside `assets/i18n/` - one per locale: ```text assets/ i18n/ en.json hi.json zh.json ``` 2. Each JSON file is a flat key-value map: ```json { "hero.title": "Markdown → Production Docs", "hero.subtitle": "The zero-config documentation engine.", "nav.docs": "Documentation", "nav.editor": "Live Editor", "cta.getStarted": "Get Started", "cta.install": "npm i @docmd/core" } ``` 3. Use `data-i18n` attributes on your HTML elements: ```html <h1 data-i18n="hero.title">Markdown → Production Docs</h1> <p data-i18n="hero.subtitle">The zero-config documentation engine.</p> <a data-i18n="nav.docs" href="/docs">Documentation</a> ``` The default language text serves as the fallback. When a non-default locale is active, the engine replaces the text. ### Attribute Translation To translate attributes like `placeholder`, `title`, or `aria-label`, use `data-i18n-{attr}`: ```html <input data-i18n-placeholder="search.placeholder" placeholder="Search..."> <button data-i18n-aria-label="nav.menuLabel" aria-label="Open menu">☰</button> <a data-i18n-title="nav.tooltip" title="Go to docs">Docs</a> ``` ### HTML Content For keys containing HTML markup, use `data-i18n-html` instead of `data-i18n`: ```html <p data-i18n-html="hero.desc">Static HTML for SEO. <br>SPA for speed.</p> ``` ### Switching Locales The i18n strings module exposes a global API at `window.DOCMD_I18N_STRINGS`: ```javascript // Switch language DOCMD_I18N_STRINGS.switchLocale("hi"); // Get active language console.log(DOCMD_I18N_STRINGS.locale); // Get all languages console.log(DOCMD_I18N_STRINGS.locales); ``` You can build a custom language switcher using this API: ```html <select onchange="DOCMD_I18N_STRINGS.switchLocale(this.value)"> <option value="en">English</option> <option value="hi">हिन्दी</option> </select> ``` ### Events Listen for the `docmd:i18n-applied` event to run custom logic after strings are applied: ```javascript document.addEventListener("docmd:i18n-applied", function(e) { console.log("Locale:", e.detail.locale); console.log("Strings:", e.detail.strings); }); ``` ::: callout info "Automatic Detection" icon:info The script detects the active locale from the URL path prefix. For the default locale, it checks `localStorage` for a previously saved preference. The `switchLocale()` function handles URL navigation automatically. ::: ### In-Place Mode For single-page sites, set `inPlace: true` in your i18n config to swap strings without URL redirects: ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "zh", "label": "中文" } ], "inPlace": true } } ``` With `inPlace: true`, calling `switchLocale()` reloads the JSON for the new locale and replaces all `data-i18n` strings instantly. No navigation occurs. --- ## [Advanced Markdown Syntax](https://docs.docmd.io/content/syntax/advanced/) --- title: "Advanced Markdown Syntax" description: "Extended formatting features: task lists, custom element attributes, footnotes, and semantic definitions." --- Beyond standard Markdown, docmd supports high-fidelity extensions derived from GitHub Flavored Markdown (GFM) and custom attribute plugins. These tools provide fine-grained control over document structure and styling. ## Task Lists Create interactive or read-only checklists for roadmap tracking and release planning. ```markdown - [x] Engine optimisation complete - [ ] Plugin API finalisation - [ ] Documentation audit ``` - [x] Engine optimisation complete - [ ] Plugin API finalisation - [ ] Documentation audit ## Emojis Use standard shortcodes to add visual personality. Emoji codes render inline with surrounding text. ```markdown We :heart: high-performance documentation! :rocket: :sparkles: ``` We :heart: high-performance documentation! :rocket: :sparkles: ## Custom Element Attributes Assign unique IDs and CSS classes to headings, images, and links using the `{}` syntax. ### Custom IDs Useful for deep-linking directly to technical subsections. ```markdown ## Performance Benchmarks {#benchmarks-2026} ``` ### CSS Classes Apply styling utilities to specific elements without touching your CSS. ```markdown ## Centre-Aligned Section {.text-centre .text-blue} ``` ### Button-Style Links Transform any standard Markdown link into a styled call-to-action button. ```markdown [Download Latest Release](#download){.docmd-button} ``` ## Footnotes Add citations or technical deep-dives as footnotes. The engine automatically collects and renders them at the page bottom. ```markdown Architectural decisions are documented in the RFC.[^1] [^1]: RFC-42: Isomorphic Rendering Pipeline. ``` Architectural decisions are documented in the RFC.[^1] [^1]: RFC-42: Isomorphic Rendering Pipeline. ## Definition Lists Perfect for API parameter descriptions and glossaries. ```markdown PropName : The unique identifier for the configuration key. DefaultValue : The value used when no override is specified. ``` PropName : The unique identifier for the configuration key. DefaultValue : The value used when no override is specified. ## Abbreviations Define abbreviations globally within a page. Hovering over the term reveals its full definition. ```markdown *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ``` *[SPA]: Single Page Application The docmd router enables a seamless SPA experience. ::: callout tip "Contextual Precision for AI" Definitions and abbreviations provide high-quality technical signals to AI agents. Explicit semantic definitions prevent lexical ambiguity in the `llms.txt` context stream. ::: --- ## [Code Blocks](https://docs.docmd.io/content/syntax/code/) --- title: "Code Blocks" description: "Document technical implementations with syntax highlighting, file titles, and one-click copying." --- docmd uses the ultra-fast `lite-hl` engine for automatic, context-aware syntax highlighting. Specify the language identifier on every fenced block to ensure the correct lexical rules apply. ## Syntax Highlighting Always name the language after the opening fence. The highlighter applies grammar rules specific to that ecosystem. ````markdown ```typescript async function build(config: string): Promise<void> { await initialise(config); } ``` ```` ```typescript async function build(config: string): Promise<void> { await initialise(config); } ``` ## Block Titles Follow the language identifier with a quoted filename to render a labelled header above the block. This is useful for referencing configuration files and source paths directly. ````markdown ```json "docmd.config.json" { "title": "My Documentation", "src": "docs/" } ``` ```` ```json "docmd.config.json" { "title": "My Documentation", "src": "docs/" } ``` ## Language Support docmd supports common technical ecosystems out of the box: * **Logic:** `javascript`, `typescript`, `python`, `rust`, `go`, `ruby`, `csharp` * **Web:** `html`, `css`, `markdown` * **Data & Shell:** `json`, `yaml`, `bash`, `powershell`, `dockerfile` * **Documentation:** `mermaid`, `changelog` ## AI Context Strategy When documenting code for AI agents, follow these practices: 1. **Label every block explicitly** - use `typescript`, `bash`, `json` rather than relying on auto-detection. This ensures the parser applies the correct grammar for the `llms.txt` stream. 2. **Embed intent in comments** - inline comments explain complex logic and provide critical reasoning context directly inside the code. ::: callout tip "One-Click Portability" Set `copyCode: true` in your configuration to enable a subtle copy button. It appears on the top-right of every block on hover, allowing readers to copy snippets instantly. ::: --- ## [Images & Visual Media](https://docs.docmd.io/content/syntax/images/) --- title: "Images & Visual Media" description: "Embed responsive images, apply styling attributes, and enable interactive lightbox zoom." --- docmd uses standard Markdown syntax for images. Centralise your media assets in the `assets/images/` directory within your project source for clean, consistent references. ```markdown ![Alt text](/assets/images/architecture.png "Optional tooltip title") ``` ![Advanced Styling Example](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-centre} ## Sizing Apply a size class using the `{ }` attribute syntax. Three predefined sizes are available. ```markdown ![Small icon](/assets/icon.png){ .size-small } ![Standard view](/assets/preview.png){ .size-medium } ![Full width banner](/assets/banner.png){ .size-large } ``` ## Alignment & Decoration Combine alignment and decoration classes in a single attribute block. ```markdown ![Centred diagram](/assets/img.png){ .align-centre } ![Floating right with shadow](/assets/img.png){ .align-right .with-shadow .with-border } ``` ## Figure Captions Use the standard HTML5 `<figure>` element for precise, accessible image captioning. ```html <figure> <img src="/assets/diagram.png" alt="Cloud Infrastructure Diagram"> <figcaption>Figure 1.1: Core System Infrastructure Architecture.</figcaption> </figure> ``` ## Image Galleries Wrap multiple figures in a `div.image-gallery` to produce a responsive, balanced grid. ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="User Dashboard View"> <figcaption>Live Performance Monitor</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="Configuration Panel View"> <figcaption>Project Global Settings</figcaption> </figure> </div> ``` ## Lightbox Zoom When `mainScripts` is active, docmd automatically applies a full-screen zoom effect to any image tagged with the `.lightbox` class or placed inside a gallery. ```markdown ![Deep texture analysis](/assets/sample.png){ .lightbox } ``` ::: callout tip "AI Context & Accessibility" icon:sparkles Always provide descriptive **alt text** for every image. Meaningful alt text is a direct, high-fidelity signal for AI agents parsing the `llms.txt` stream and improves accessibility for screen reader users. ::: --- ## [Markdown Syntax Foundation](https://docs.docmd.io/content/syntax/) --- title: "Markdown Syntax Foundation" description: "The baseline formatting rules for all docmd content: typography, structure, lists, and tables." --- `docmd` adheres to standard **GitHub Flavored Markdown (GFM)** specifications. This page covers the core formatting primitives that apply across every page in your project. ## Typography | Style | Syntax | Renders As | | :--- | :--- | :--- | | **Bold** | `**text**` | **Strong emphasis** | | *Italic* | `*text*` | *Soft emphasis* | | ~~Strikethrough~~ | `~~text~~` | ~~Deprecated content~~ | | `Inline code` | `` `text` `` | `engine.initialise()` | ## Heading Hierarchy `docmd` derives the page `<h1>` automatically from the `title` field in your frontmatter. Begin your heading structure at `##`. ```markdown ## Level 2 - Major Section ### Level 3 - Feature Detail #### Level 4 - Sub-Detail ``` ::: callout tip "Logical Integrity for AI" AI models and search indexers rely on a strict heading hierarchy to build an accurate mental model of your project. Avoid skipping levels (e.g., jumping from `##` to `####`) to keep the `llms-full.txt` context stream logically sound. ::: ## Lists Use unordered lists for scannable bullet points and ordered lists for sequential steps. For numbered tutorials, consider the higher-impact [Steps container](../containers/steps.md). ```markdown * Unordered item * Another item 1. First step 2. Second step ``` ## Blockquotes The standard `>` syntax highlights external quotes or background context. ```markdown > The docmd engine redefines the boundaries between static site generation and dynamic application delivery. ``` > The docmd engine redefines the boundaries between static site generation and dynamic application delivery. ## Tables ```markdown | Parameter | Type | Default | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ``` | Parameter | Type | Default | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## Embedded HTML docmd has raw HTML parsing enabled. Inject custom layouts or unique styling directly within Markdown files for specialised UI requirements. ```html <div style="padding: 2rem; border: 1px solid var(--border-colour); border-radius: 12px; text-align: centre;"> Bespoke UI elements live here. </div> ``` --- ## [Linking & Referencing](https://docs.docmd.io/content/syntax/linking/) --- title: "Linking & Referencing" description: "Master internal cross-linking, external resources, new-tab behaviour, and static asset referencing." --- docmd provides a reliable, filesystem-aware linking system. Write links to your source `.md` files naturally in any format - the engine normalises them into clean, SEO-optimised URLs automatically. ::: callout info "Write Naturally, Ship Perfectly" You do not need special linking conventions. Write `overview.md`, `overview/`, or `overview` - the build engine produces the exact same clean, trailing-slash URL in every case. ::: ## URL Normalisation During the build process, the engine normalises every internal link automatically. This applies to Markdown text, button containers, tags, and navigation configuration. | What You Write | What Gets Rendered | Why | | :--- | :--- | :--- | | `overview.md` | `overview/` | `.md` extension stripped, trailing `/` added. | | `overview` | `overview/` | Trailing `/` added automatically. | | `overview/` | `overview/` | Already correct. No change. | | `api/commands.md` | `api/commands/` | Subdirectory link normalised. | | `localisation/index.md` | `localisation/` | `index` stripped, the folder is the canonical URL. | | `../index.md` | `../` | Parent directory index resolved cleanly. | | `overview.md#settings` | `overview/#settings` | Hash fragment preserved. | | `https://example.com` | `https://example.com` | External links pass through untouched. | ## Internal Links Link to other pages using relative paths to the source `.md` files. The engine resolves them correctly regardless of directory depth. | Target | Example | | :--- | :--- | | Sibling page | `[System Overview](overview.md)` | | Subdirectory page | `[API Reference](api/node-api.md)` | | Subdirectory index | `[Localisation](localisation/index.md)` | | Parent directory | `[Back to Home](../index.md)` | ## Section Anchors Navigate directly to a heading using standard URL hash fragments. ```markdown <!-- Intra-page anchor --> [Jump to Roadmap](#project-roadmap) <!-- Cross-page anchor --> [Review CLI Flags](../api/cli-commands.md#available-flags) ``` Hash fragments are preserved through normalisation. The cross-page link above renders as `../api/cli-commands/#available-flags` in production. ## Opening in a New Tab Prepend `external:` to any link URL to force it to open in a new browser tab. This works in standard Markdown links, buttons, and tags. ```markdown [Open in New Tab](external:./configuration/overview.md) [GitHub](external:https://github.com/docmd-io/docmd) ``` The `external:` prefix is stripped from the rendered URL. By default, all links open in the same window. ## Linking to Raw Files Use the `raw:` prefix to bypass normalisation and link directly to a downloadable file. The extension and path are preserved exactly as written. ```markdown [View Raw Source](raw:docs/readme.md) ``` ## Buttons & Tags The `::: button` and `::: tag` containers support all standard linking conventions, including `external:` and `raw:` prefixes. ```markdown ::: button "Get Started" ./getting-started/quick-start.md icon:rocket ::: button "View on GitHub" external:https://github.com/docmd-io/docmd icon:github ::: button "Download Source" raw:docs/readme.md icon:download ::: tag "v0.8.2" link:release-notes/0-8-2.md icon:tag color:#22c55e ::: tag "Open Externally" link:external:./configuration/overview.md icon:external-link ``` ## Navigation Configuration Paths defined in `navigation.json` and `docmd.config.json` are normalised at build time. Write them in any format - all three entries below produce the identical canonical URL. ```json "navigation.json" [ { "title": "Overview", "path": "configuration/overview" }, { "title": "Overview", "path": "configuration/overview.md" }, { "title": "Overview", "path": "configuration/overview/" } ] ``` For items that should open in a new tab, set the `external` flag. ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "Index Pages in Navigation" When linking to a directory's index page, use the folder path rather than explicitly referencing `index.md`. Both work identically, but the folder path is cleaner. ```markdown <!-- Preferred --> [Localisation](localisation/) <!-- Also works --> [Localisation](localisation/index.md) ``` ::: ## Protocols & External Resources The engine respects standard browser protocols for external resources and never modifies these links. * **HTTPS** - `[docmd Homepage](https://docmd.io)` - opens in the same tab. * **Mail** - `[Support](mailto:help@docmd.io)` - opens the email client. * **Assets** - `[Download CLI Binary](/assets/bin/docmd-mac.zip)` - not normalised. ## Static Assets Place downloadable files within your project's `assets/` directory. The builder moves these files to the production root without path modifications. ```markdown [Download Documentation PDF](/assets/pdf/handbook.pdf) [View Raw Global Config](/assets/config/docmd.config.json) ``` ::: callout tip "Semantic Linkage for AI" Prefer **descriptive anchor text** (e.g., `[Optimise PWA caching](../plugins/pwa.md)`) over generic labels (e.g., `[Read more](../plugins/pwa.md)`). Detailed link labels give AI agents a high-fidelity map of semantic relationships in the `llms.txt` stream. ::: --- ## [Contributing](https://docs.docmd.io/contributing/) --- title: "Contributing" description: "Guidelines and setup instructions for contributing to docmd." --- Thank you for your interest in contributing to `docmd`. We appreciate bug fixes, documentation improvements, new features, and design suggestions. ## Development Environment `docmd` is a monorepo managed with [pnpm](https://pnpm.io/). ### Prerequisites - **Node.js**: v22.x or later (LTS recommended) - **pnpm**: v10.x or later ### Project Setup Clone the repository and run the initial setup to install dependencies and build the monorepo: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` To link the local `docmd` command globally for testing in other projects: ```bash pnpm verify --link ``` ### Local Development We provide a master proxy command to run any `docmd` command against our internal `_playground` directory. This makes development identical to the user CLI experience: ```bash pnpm docmd dev # Starts playground dev server (also: pnpm dev) pnpm docmd build # Builds playground documentation ``` To watch internal source files (engine, templates, and plugins) with hot-reload, set the `DOCMD_DEV` environment variable: ```bash DOCMD_DEV=true pnpm dev ``` ## Quality Standards ### Linting Ensure your code complies with our ESLint configuration. To automatically fix formatting issues, run: ```bash pnpm lint --fix ``` ### Verification Before submitting a Pull Request, you **MUST** ensure the entire monorepo passes our intensive verification pipeline. This simulates a fresh release environment, audits for security vulnerabilities, and verifies monorepo integrity: ```bash pnpm prep ``` *(This chains `pnpm reset`, dependency installation, lint checks, 7-pillar E2E tests, and the final release dry-run.)* ## GitHub Workflow 1. **Fork and Branch**: Create a feature branch from the latest `main`. 2. **Verify**: Ensure `pnpm prep` returns `🛡️ docmd is ready for production!`. 3. **Pull Request**: Open a PR with a clear description of the problem solved or the feature added. ### Commit Guidelines We use [Conventional Commits](https://www.conventionalcommits.org/). Please prefix your commit messages with: - `feat:` (New features) - `fix:` (Bug fixes) - `docs:` (Documentation changes) - `refactor:` (Internal refactorings) ### Source Headers All new files within the `packages/` directory MUST include the standard project copyright header: ```javascript /** * -------------------------------------------------------------------- * docmd : the zero-config documentation engine. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @licence MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` --- ## [Browser-API (Clientseitig)](https://docs.docmd.io/de/07/api/browser-api/) --- title: "Browser-API (Clientseitig)" description: "Interagieren Sie vom Browser aus mit docmd - Live-Kompilierung und Plugin-Kommunikation im Entwicklungsmodus." --- `docmd` bietet zwei Browser-APIs: die **isomorphe Compile-Engine** zum Rendern von Markdown im Browser und die **Plugin-API für den Entwicklungsmodus** für die Echtzeitkommunikation mit dem Dev-Server. ## Isomorphe Compile-Engine Dieselbe Engine, die statische Websites in Node.js generiert, kann vollständig in einem Webbrowser ausgeführt werden. Dies ist ideal für den Aufbau von CMS-Vorschauen, interaktiven Playgrounds oder die Einbettung von Dokumentationen in bestehende Webanwendungen. ### Installation via CDN ```html <!-- Kern-Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Die isomorphe Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` Kompiliert rohes Markdown unter Verwendung des Standard-`docmd`-Layouts in einen vollständigen HTML-Dokument-String. **Parameter:** - `markdown` (String): Der rohe Markdown-Inhalt. - `config` (Object): Konfigurations-Überschreibungen (gleiches Schema wie `docmd.config.js`). **Rückgabe:** `Promise<String>`: Das vollständige HTML-Dokument. ### Beispiel: Live-Vorschau Um eine Stil-Isolation zu gewährleisten, wird empfohlen, die Ausgabe innerhalb eines `<iframe>` mittels des `srcdoc`-Attributs zu rendern. ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: 'Vorschau', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## Plugin-API für den Entwicklungsmodus Während `docmd dev` aktiv ist, wird automatisch eine globale `window.docmd`-Variable in jede Seite eingefügt. Diese API ermöglicht die Echtzeitkommunikation zwischen clientseitigem Plugin-Code und serverseitigen Action-Handlern via WebSocket RPC. ::: callout info "Nur im Entwicklungsmodus" Die unten aufgeführten Plugin-API-Methoden sind nur während `docmd dev` verfügbar. Sie sind nicht in Produktions-Builds enthalten. ::: ### `docmd.call(action, payload)` Ruft einen serverseitigen Action-Handler auf, der von einem Plugin registriert wurde. Gibt ein Promise zurück, das mit dem Rückgabewert des Handlers aufgelöst wird. ```javascript // Eine Plugin-Aktion aufrufen und das Ergebnis erhalten const threads = await docmd.call('threads:get-threads', { file: 'docs/erste-schritte.md' }); console.log(threads); // Array von Thread-Objekten ``` Wenn die Aktion Quelldateien modifiziert, lädt die Seite nach Auflösung des Promises automatisch neu. ### `docmd.send(name, data)` Sendet ein „Fire-and-forget“-Ereignis an den Server. Es wird keine Antwort zurückgegeben. ```javascript // Den Server über einen Seitenaufruf benachrichtigen docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` Abonniert vom Server gesendete Ereignisse (Server-pushed Events). Gibt eine Unsubscribe-Funktion zurück. ### `docmd.afterReload(name, callback)` & `docmd.scheduleReload(name, context)` Ermöglichen die Erhaltung des Zustands (z. B. Scrollposition) über einen automatischen Neuladevorgang hinweg, indem Daten im `sessionStorage` zwischengespeichert werden. ## Wichtige Hinweise - **Kein Dateisystem**: Die Browser-Engine kann keine Ordner scannen. Sie müssen das `navigation`-Array explizit im Konfigurationsobjekt angeben, wenn Sie eine Seitenleiste benötigen. - **Node-only Plugins**: Plugins, die auf Node.js-APIs angewiesen sind (wie Sitemap oder LLM), sind im Browser deaktiviert. --- ## [CLI-Befehle](https://docs.docmd.io/de/07/api/cli-commands/) --- title: "CLI-Befehle" description: "Befehlszeilenreferenz für docmd - alle verfügbaren Befehle und Optionen." --- ## Befehlsübersicht | Befehl | Beschreibung | |:--------|:------------| | [`docmd init`](#docmd-init) | Erstellt ein neues Dokumentationsprojekt | | [`docmd dev`](#docmd-dev) | Startet den Entwicklungsserver mit Hot-Reload | | [`docmd build`](#docmd-build) | Erzeugt eine statische Website für die Produktion | | [`docmd live`](#docmd-live) | Startet den browserbasierten Live-Editor | | [`docmd stop`](#docmd-stop) | Beendet laufende Entwicklungsserver | | [`docmd deploy`](#docmd-deploy) | Erzeugt Bereitstellungskonfigurationen (Docker, Nginx, Caddy) | | [`docmd migrate`](#docmd-migrate) | Aktualisiert Legacy-Konfigurationen auf das V2-Schema | | [`docmd add <plugin>`](#docmd-add-plugin) | Installiert und konfiguriert ein Plugin | | [`docmd remove <plugin>`](#docmd-remove-plugin) | Entfernt ein Plugin und dessen Konfiguration | ## Globale Optionen | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei (Standard: `docmd.config.js`) | | `--verbose` | `-V` | Detaillierte Build-Protokolle anzeigen | | `--version` | `-v` | Die installierte Version ausgeben | | `--help` | `-h` | Hilfemenü anzeigen | | `--cwd <path>` | - | Arbeitsverzeichnis überschreiben (für Monorepos) | ## `docmd init` Erstellt ein neues Dokumentationsprojekt im aktuellen Verzeichnis. ```bash docmd init ``` Erstellt: - `docs/index.md` - Beispiel-Startseite - `docmd.config.js` - Empfohlene Standardeinstellungen - Aktualisierte `package.json` mit Build-Skripten ## `docmd dev` Startet einen Entwicklungsserver mit sofortigem Hot-Reload. ```bash docmd dev [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--port <number>` | `-p` | Server-Port (Standard: `3000`) | | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei | ## `docmd build` Erzeugt eine produktionsreife statische Website im Verzeichnis `site/`. ```bash docmd build [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--offline` | - | Links auf `.html` umschreiben für `file://` Browsing | | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei | ## `docmd live` Startet den browserbasierten Live-Editor. ```bash docmd live [options] ``` | Option | Beschreibung | |:-------|:------------| | `--build-only` | Erzeugt das Editor-Bundle, ohne den Server zu starten | ## `docmd stop` Beendet laufende docmd-Entwicklungsserver. ```bash docmd stop [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--port <number>` | `-p` | Nur den Server auf diesem Port stoppen | | `--force` | `-f` | Auch `serve`-Prozesse auf den Ports 3000, 3001, 8080, 8081 beenden | ## `docmd deploy` Erzeugt Konfigurationsdateien für die Bereitstellung. ```bash docmd deploy [options] ``` | Option | Beschreibung | |:-------|:------------| | `--docker` | Erzeugt ein `Dockerfile` | | `--nginx` | Erzeugt `nginx.conf` | | `--caddy` | Erzeugt `Caddyfile` | | `--force` | Bestehende Bereitstellungsdateien überschreiben | ## `docmd migrate` Aktualisiert Legacy docmd V1-Konfigurationen auf das V2-Schema. ```bash docmd migrate ``` Ordnet automatisch veraltete Schlüssel neu zu (z. B. `siteTitle` → `title`) und strukturiert das Konfigurationsobjekt um. ## `docmd add <plugin>` Installiert und konfiguriert ein offizielles oder Community-Plugin. ```bash docmd add <plugin-name> ``` | Beispiel | Beschreibung | |:--------|:------------| | `docmd add analytics` | Installiert `@docmd/plugin-analytics` | | `docmd add search` | Installiert `@docmd/plugin-search` | Die CLI erkennt Ihren Paketmanager (npm, pnpm, yarn oder bun) und fügt empfohlene Standardeinstellungen in die `docmd.config.js` ein. ## `docmd remove <plugin>` Deinstalliert sicher ein Plugin und bereinigt dessen Konfiguration. ```bash docmd remove <plugin-name> ``` Entfernt: - Das npm-Paket - Plugin-Konfiguration aus der `docmd.config.js` ::: callout tip "Agenten-kompatible Protokollierung :robot:" `docmd` verwendet strukturierte Terminal-Protokolle. KI-Agenten können die Ausgabe präzise parsen für Fehlererkennung und automatisierte Wartung. ::: --- ## [Client-seitige Ereignisse](https://docs.docmd.io/de/07/api/client-side-events/) --- title: "Client-seitige Ereignisse" description: "Nutzen Sie den SPA-Lebenszyklus von docmd, um interaktive Funktionen hinzuzufügen." --- `docmd` nutzt einen leichtgewichtigen Single Page Application (SPA) Router, um sofortige Seitenübergänge zu ermöglichen. Da der Browser beim Navigieren kein vollständiges Neuladen durchführt, werden Skripte, die auf `DOMContentLoaded` basieren, nicht erneut ausgeführt. Um dies zu handhaben, sendet `docmd` benutzerdefinierte Lebenszyklus-Ereignisse (Events), auf die Sie in Ihren `customJs`-Dateien hören können. ## `docmd:page-mounted` Dieses Ereignis wird immer dann ausgelöst, wenn eine neue Seite erfolgreich abgerufen und in das DOM eingefügt wurde. ### Verwendung Fügen Sie einen Listener zum `document`-Objekt hinzu, um Bibliotheken von Drittanbietern neu zu initialisieren oder benutzerdefinierte Animationen auszulösen. ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`Navigiert zu: ${url}`); // Komponenten neu initialisieren // Beispiel: Prism.highlightAll(); }); ``` ### Ereignis-Details (`event.detail`) | Eigenschaft | Typ | Beschreibung | | :--- | :--- | :--- | | `url` | `String` | Die absolute URL der Seite, die gerade gemountet wurde. | ## Best Practices 1. **Idempotenz**: Stellen Sie sicher, dass Ihre Initialisierungslogik sicher mehrmals auf derselben Seite aufgerufen werden kann oder vor der nächsten Navigation bereinigt wird. 2. **Globaler Scope**: Skripte, die über `customJs` hinzugefügt werden, laufen im globalen Geltungsbereich. Verwenden Sie eine IIFE (Immediately Invoked Function Expression), um eine Verschmutzung des `window`-Objekts zu vermeiden. 3. **Bereinigung**: Wenn Ihr Skript globale Event-Listener hinzufügt (z. B. `window.onresize`), sollten Sie in Erwägung ziehen, den aktuellen Pfad zu verfolgen, um diese zu entfernen, wenn der Benutzer die Seite verlässt. --- ## [Live-Editor](https://docs.docmd.io/de/07/api/live-api/) --- title: "Live-Editor" description: "Verständnis des docmd Live-Editors und seines browserbasierten Authoring-Workflows." --- Der `docmd` Live-Editor ist eine spezialisierte Umgebung für das Schreiben von Dokumentationen in Echtzeit. Er nutzt den isomorphen Kern von `docmd`, um eine sofortige Side-by-Side-Vorschau Ihrer Markdown-Inhalte zu ermöglichen, ohne dass ein Backend-Build-Prozess erforderlich ist. ## Editor starten Starten Sie den lokalen Live-Editor mit dem Befehl: ```bash docmd live ``` Der Editor ist normalerweise unter `http://localhost:3000` erreichbar. ## Architektur Im Gegensatz zum Standard-`dev`-Server, der Dateien auf der Festplatte neu baut, führt der Live-Editor die `docmd`-Engine direkt in Ihrem Browser aus. Dies ermöglicht: 1. **Sofortiges Feedback**: Inhalte werden bereits während des Schreibens neu gerendert. 2. **Portable Playgrounds**: Der Editor kann in eine statische Website gebündelt werden, um beispielsweise auf GitHub Pages gehostet zu werden. 3. **Plattformübergreifende Konsistenz**: Die Vorschau nutzt exakt dieselbe Rendering-Logik wie der Produktions-Build. ## Statische Bereitstellung Generieren Sie eine teilbare, eigenständige Version des Editors: ```bash docmd live --build-only ``` Dies erstellt ein `dist/`-Verzeichnis, das das HTML des Editors und die gebündelte isomorphe Engine enthält. --- ## [Node.js API](https://docs.docmd.io/de/07/api/node-api/) --- title: "Node.js API" description: "Integrieren Sie die Build-Engine von docmd in Ihre benutzerdefinierten Node.js-Skripte und Automatisierungs-Pipelines." --- Für fortgeschrittene Workflows können Sie die `docmd`-Build-Engine direkt in Ihren eigenen Node.js-Anwendungen importieren und verwenden. Dies ist ideal für benutzerdefinierte CI/CD-Pipelines, automatisierte Dokumentationserstellung oder die Erweiterung von `docmd` für spezialisierte Umgebungen. ## Installation Stellen Sie sicher, dass `@docmd/core` in Ihrem Projekt installiert ist: ```bash npm install @docmd/core ``` ## Kernfunktionen ### `buildSite(configPath, options)` Die primäre Build-Funktion. Sie übernimmt das Laden der Konfiguration, das Parsen von Markdown und die Generierung von Assets. ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.js', { isDev: false, // Auf true setzen für Watch-Modus-Logik offline: false, // Auf true setzen zur Optimierung für file:// Zugriff zeroConfig: false // Auf true setzen, um die Erkennung der Konfigurationsdatei zu umgehen }); } ``` ### `buildLive(options)` Erzeugt das Bundle für den browserbasierten **Live Editor**. ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true startet einen lokalen Server; false erzeugt statische Dateien port: 3000 // Benutzerdefinierter Port, wenn serve true ist }); } ``` ## Beispiel: Benutzerdefinierte Pipeline Sie können `docmd` kapseln, um komplexe Dokumentations-Workflows zu erstellen. ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. Dynamische Inhalte generieren await fs.writeFile('./docs/dynamic.md', '# Generierter Inhalt'); // 2. docmd-Build ausführen await buildSite('./docmd.config.js'); // 3. Ausgabe verschieben await fs.move('./site', './public/docs'); } ``` ::: callout tip Die programmatische API ist hochgradig kompatibel mit **KI-gesteuerter Dokumentation**. Agenten können Builds nach Inhaltsaktualisierungen auslösen, um die Integrität zu prüfen und Bereitstellungen autonom zu verwalten. ::: ## Plugin-API (`@docmd/api`) Das Paket `@docmd/api` ist die dedizierte Heimat für das Plugin-System. Es bietet Hook-Registrierung, WebSocket-RPC-Dispatch, Quellcode-Editierwerkzeuge und **zentralisierte URL-Utilities**. ```bash npm install @docmd/api ``` ### URL-Utilities Plugins sollten diese zentralisierten Utilities verwenden, anstatt eine eigene URL-Logik zu implementieren. #### `outputPathToSlug(outputPath)` Konvertiert einen Ausgabe-Pfad der Build-Engine in einen sauberen Slug im Verzeichnis-Stil. ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` Konvertiert in einen Wurzel-relativen Pfadnamen (Pathname). ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` Erstellt eine vollständige kanonische URL. ```javascript import { outputPathToCanonical } from '@docmd/api'; outputPathToCanonical('guide/index.html', 'https://example.com'); // → 'https://example.com/guide/' ``` #### `sanitizeUrl(url)` Fasst Doppelschrägstriche zusammen (außer nach dem Protokoll). ```javascript import { sanitizeUrl } from '@docmd/api'; sanitizeUrl('https://example.com//path/'); // → 'https://example.com/path/' sanitizeUrl('/foo//bar/'); // → '/foo/bar/' ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` Erstellt eine absolute URL mit Locale- und Versions-Präfixen. ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` Normalisiert vom Benutzer geschriebene Hrefs zu sauberen URLs. Behandelt das Entfernen von `.md`, abschließende Schrägstriche sowie `external:` und `raw:` Präfixe. ```javascript import { resolveHref } from '@docmd/api'; resolveHref('overview.md'); // → { href: 'overview/', isExternal: false, isRaw: false } resolveHref('external:https://github.com/docmd-io/docmd'); // → { href: 'https://github.com/docmd-io/docmd', isExternal: true, isRaw: false } resolveHref('raw:docs/readme.md'); // → { href: 'docs/readme.md', isExternal: false, isRaw: true } ``` ### Vorberechnete Seiten-URLs Jedes Seiten-Objekt enthält vorberechnete URL-Daten. Plugins können diese direkt lesen - keine Berechnung erforderlich. ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); // "guide/" console.log(page.urls.canonical); // "https://example.com/guide/" console.log(page.urls.pathname); // "/guide/" } } ``` | Eigenschaft | Typ | Beschreibung | |:------------|:-----|:------------| | `slug` | `string` | Sauberer Slug im Verzeichnis-Stil (z. B. `guide/` oder `/`) | | `canonical` | `string` | Vollständige kanonische URL (nur wenn `config.url` gesetzt ist) | | `pathname` | `string` | Wurzel-relativer Pfad (z. B. `/guide/`) | > **Abwärtskompatibilität:** Alle Exporte aus `@docmd/api` werden auch aus `@docmd/core` re-exportiert, sodass bestehender Code ohne Änderungen weiterhin funktioniert. Neue Projekte werden ermutigt, direkt aus `@docmd/api` zu importieren. ### `createActionDispatcher(hooks, options)` Erstellt einen Dispatcher, der WebSocket-RPC-Nachrichten an Plugin-Aktions-/Event-Handler leitet. ```javascript import { createActionDispatcher } from '@docmd/api'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` Erstellt Werkzeuge zur Quellcode-Bearbeitung für die Manipulation von Markdown-Dateien. ```javascript import { createSourceTools } from '@docmd/api'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // Block-Informationen an einem bestimmten Zeilenbereich abrufen const block = await source.getBlockAt('docs/page.md', [10, 12]); // Text mit Syntax-Markierungen umschließen await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### `loadPlugins(config, options)` Lädt, validiert und registriert alle in der Konfiguration deklarierten Plugins. Gibt das gefüllte Hook-Register zurück. ```javascript import { loadPlugins, hooks } from '@docmd/api'; const registeredHooks = await loadPlugins(config, { resolvePaths: [__dirname] // Hilft beim Auflösen von Plugins in pnpm-Workspaces }); ``` ### Typ-Exporte Für TypeScript-Plugin-Autoren stehen folgende Typen zur Verfügung: ```typescript import type { PluginModule, // Vollständiges Plugin-Vertragsinterface PluginDescriptor, // Plugin-Metadaten (Name, Version, Fähigkeiten) PluginHooks, // Form des Hook-Registers PageContext, // Kontext für Build-Hooks (sourcePath, html etc.) Capability, // Deklaration der Hook-Kategorie (init, body, actions, etc.) ActionContext, // Kontext, der an Aktions-/Event-Handler übergeben wird ActionHandler, // Signatur für Aktions-Handler EventHandler, // Signatur für Event-Handler SourceTools, // Interface für Quellcode-Editierwerkzeuge BlockInfo, // Von getBlockAt zurückgegebene Block-Informationen TextLocation, // Von findText zurückgegebene Textposition } from '@docmd/api'; ``` --- ## [Vergleich](https://docs.docmd.io/de/07/comparison/) --- title: "Vergleich" description: "Warum docmd? Erfahren Sie, wie es im Vergleich zu Docusaurus, VitePress, MkDocs und anderen Tools abschneidet." --- Sie haben sich schon früher für ein Dokumentations-Tool entschieden. Sie werden es wieder tun. Hier ist das, was wirklich zählt - und wo docmd steht. ## Schreiben in 3 Sekunden starten, nicht in 30 Minuten ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` Fertig. Ihre Doku ist live. Keine Konfigurationsdateien, kein Projekt-Scaffolding, kein Abhängigkeits-Labyrinth. == tab "Docusaurus" ```bash npx create-docusaurus@latest mein-projekt classic cd mein-projekt npm install npm start ``` Vier Befehle, ein generiertes Projekt mit ~250 MB in `node_modules` und eine `docusaurus.config.js`, die Sie bearbeiten müssen, bevor etwas Nützliches passiert. == tab "VitePress" ```bash npx vitepress init ``` Stellt Ihnen 5 Fragen, generiert eine Konfigurationsdatei, dann führen Sie `vitepress dev` aus. Sauber - erfordert aber dennoch Scaffolding. == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new mein-projekt && cd mein-projekt mkdocs serve ``` Python-Ökosystem. Sie benötigen `pip`, eine virtuelle Umgebung und eine `mkdocs.yml`, bevor die erste Seite gerendert wird. ::: ## Der Payload-Unterschied ist real Ihre Leser sollten keine React-App herunterladen müssen, nur um einen Absatz zu lesen. Das ist es, was der Browser bei einer Website mit 50 Seiten tatsächlich empfängt: | Generator | Initialer Download (gesamt) | JS Payload | CSS Payload | |:----------|:---------------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "Warum das wichtig ist" Alle 100 KB JavaScript kosten auf einem Mittelklasse-Smartphone etwa 50 ms Zeit zum Parsen. Die 12 KB JS von docmd bedeuten, dass Ihre Doku sofort lädt, selbst bei 3G-Verbindungen. Docusaurus liefert 16-mal mehr JavaScript für denselben Inhalt aus. ::: ## Build-Geschwindigkeit Erstellung derselben Website mit 50 Seiten auf einem M1 MacBook Air: | Generator | Kaltstart (Build) | Hot Rebuild (Dev) | |:----------|:-----------------:|:-----------------:| | **docmd** | **~1,2s** | **~80ms** | | VitePress | ~2,5s | ~150ms | | MkDocs Material | ~3,0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd-Rebuilds sind so schnell, dass die Seite aktualisiert wird, bevor Sie das Fenster gewechselt haben. ## i18n, das tatsächlich funktioniert Hier scheitern die meisten Tools. Sie fügen 6 Sprachen hinzu, übersetzen 3 Seiten ins Hindi, und plötzlich stoßen Ihre Benutzer bei jeder nicht übersetzten Seite auf einen 404-Fehler. | Funktion | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | Fallback pro Seite auf Default-Locale | ✅ | ❌ (404) | ❌ (404) | ✅ | | Lokalisierte Warnung "nicht übersetzt" | ✅ | ❌ | ❌ | ✅ | | Automatische Deaktivierung fehlender Sprachen im Switcher | ✅ | ❌ | ❌ | ❌ | | Sofortige Prüfung der Seitensexistenz (offline) | ✅ | ❌ | ❌ | ❌ | | Kombination aus Versionierung + i18n | ✅ | ❌ | ❌ | ❌ | | Zero-Config (kein individuelles React/Vue) | ✅ | Teilweise | ❌ | ✅ | ::: callout warning "Was in VitePress und Docusaurus passiert" Wenn ein Leser auf Hindi wechselt und diese Seite nicht übersetzt ist, erhält er eine **404-Fehlermeldung**. Die einzige Abhilfe sind serverseitige Weiterleitungen oder das Schreiben einer eigenen React/Vue-Komponente. docmd regelt dies zum Build-Zeitpunkt - nicht verfügbare Locales erhalten ein "N/A"-Badge, und nicht übersetzte Seiten fallen lautlos auf den Standard zurück, begleitet von einem lokalisierten Warnungs-Callout. ::: ## Vollständige Feature-Matrix | Feature | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **Zero-Config Start** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Konfiguration erforderlich** | Keine | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **SPA-Navigation** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **Native Versionierung** | ✅ | ✅ | ❌ | Plugin | ❌ | ✅ | | **Natives i18n** | ✅ | ✅ | Manuell | Plugin | ✅ | ✅ | | **Integrierte Suche** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | Cloud | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Inline-Diskussionen** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA-Unterstützung** | ✅ | Community | ❌ | ❌ | ❌ | ❌ | | **Self-hosted** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **Deployment-Config-Generator** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## Konfigurationsaufwand Erforderliche Konfigurationszeilen für eine Website mit Versionierung, i18n, Suche und Sitemap: | Generator | Konfigurationszeilen | Erforderliche Dateien | |:----------|:--------------------:|:---------------------:| | **docmd** | **~15 Zeilen** | 1 (`docmd.config.js`) | | MkDocs Material | ~50 Zeilen | 1 + Plugins | | VitePress | ~80 Zeilen | 1 + Theme-Ordner | | Docusaurus | ~120 Zeilen | 3+ Konfig-Dateien | ## Qualitätssicherung docmd wird mit einer Brute-Test-Suite ausgeliefert, die **25 verschiedene Szenarien** anhand von **85 Assertionen** validiert - wobei jedes Feature isoliert und in Kombination abgedeckt wird. Jedes Release muss alle 85 Assertionen und 13 interne Failsafe-Checks bestehen, bevor es ausgeliefert wird. ::: callout tip "Führen Sie die Tests selbst aus" ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: Kein anderer Dokumentationsgenerator in dieser Klasse veröffentlicht eine vergleichbare End-to-End-Feature-Test-Suite als Teil seines Quellcodes. --- ## [Layout & UI-Zonen](https://docs.docmd.io/de/07/configuration/layout-ui/) --- title: "Layout & UI-Zonen" description: "Steuern Sie die Schnittstellenstruktur durch die Verwaltung von Headern, Seitenleisten und funktionalen UI-Slots." --- Eine Standard-`docmd`-Seite ist in sechs primäre Funktionsbereiche unterteilt: 1. **Menüleiste (Menubar)**: Eine horizontale Navigationsleiste am oberen Rand für globale Website-Links. 2. **Header**: Die permanente sekundäre Leiste, die den Seitentitel und Werkzeug-Schaltflächen enthält. 3. **Seitenleiste (Sidebar)**: Der primäre Navigationsbaum (normalerweise auf der linken Seite). 4. **Inhaltsbereich (Content Area)**: Der zentrale Bereich für die Markdown-Anzeige, einschließlich **Breadcrumbs**. 5. **Inhaltsverzeichnis (TOC)**: Navigationsmenü auf der rechten Seite für die Überschriften der aktuellen Seite. 6. **Fußzeile (Footer)**: Bereich am unteren Rand für Urheberrecht, Branding und website-weite Links. ## Globale Komponenten Die meisten UI-Zonen werden im Bereich `layout` Ihrer `docmd.config.js` konfiguriert. ### Menüleiste Die Menüleiste bietet eine übergeordnete Navigationsebene über Ihrer Dokumentation. ```javascript layout: { menubar: { enabled: true, position: 'top', // 'top' (fixiert) oder 'header' (im Inhaltsfluss) left: [ { type: 'title', text: 'Marke', url: '/', icon: 'home' }, { text: 'Funktionen', url: '/features' } ], right: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', icon: 'github' } ] } } ``` ### Der Seiten-Header Der Header ist standardmäßig aktiviert. Sie können ihn website-weit deaktivieren oder bestimmte Elemente über das Frontmatter auf Seitenebene ausblenden. ```javascript // docmd.config.js layout: { header: { enabled: true // Auf false setzen, um den gesamten oberen Header website-weit auszublenden }, breadcrumbs: true // Auf false setzen, um den Breadcrumb-Pfad website-weit auszublenden } ``` **Überschreibung auf Seitenebene (Frontmatter):** ```yaml --- title: "Spezialseite" hideTitle: true # Blendet den Titel im fixierten Header für diese spezifische Seite aus --- ``` ## Werkzeugmenüs (Optionsmenü) Das `optionsMenu` fasst Kernfunktionen wie **Suche**, **Theme-Umschalter** und **Sponsoring** zusammen. ```javascript layout: { optionsMenu: { position: 'header', // Optionen: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Volltextsuche aktivieren themeSwitch: true, // Hell-/Dunkelmodus-Umschalter aktivieren sponsor: 'https://github.com/sponsors/dein-profil' } } } ``` ::: callout info "Container-Fallback" Wenn die gewählte Position auf einen Container zielt, der deaktiviert ist, rendert `docmd` das Optionsmenü automatisch im Slot `sidebar-top`, um sicherzustellen, dass die Kernfunktionen zugänglich bleiben. ::: ## Seitenleisten- & Fußzeilen-Steuerung ### Verhalten der Seitenleiste ```javascript layout: { sidebar: { enabled: true, collapsible: true, // Ermöglicht die Ein-/Ausklapp-Animation defaultCollapsed: false, // Legt den initialen Status der Seitenleiste fest position: 'left' } } ``` ### Footer-Branding `docmd` bietet sowohl **minimale** als auch **vollständige** Layouts für den Footer Ihrer Website. ```javascript layout: { footer: { style: 'complete', description: 'Dokumentation erstellt mit docmd.', branding: true, // Steuert das "Build with docmd"-Badge columns: [ { title: 'Community', links: [{ text: 'GitHub', url: '...' }] } ] } } ``` ::: callout tip "KI-optimierte Schnittstelle" Stellen Sie beim Entwerfen benutzerdefinierter Layouts sicher, dass die **Suche** in Ihrem `optionsMenu` prominent platziert ist. KI-Agenten nutzen die Suche häufig als primären Anker, wenn sie Ihre Dokumentation erkunden, um spezifischen technischen Kontext zu lokalisieren. ::: --- ## [Lokalisierung](https://docs.docmd.io/de/07/configuration/localisation/) --- title: "Lokalisierung" description: "Bieten Sie Ihre Dokumentation in mehreren Sprachen an - mit sprachspezifischem Routing, übersetzter Navigation und automatischem Fallback." --- Fügen Sie Ihrer Dokumentationsseite Mehrsprachigkeitsunterstützung hinzu. docmd stellt jede Sprache unter einem eigenen URL-Präfix bereit, übersetzt die System-UI-Strings und nutzt einen eleganten Fallback, falls eine Übersetzung fehlt. ## Sprachen zur Konfiguration hinzufügen ```js // docmd.config.js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }, { id: 'zh', label: '中文' } ] } } ``` Die Standardsprache (`default`) wird im Stammverzeichnis der Website (`/`) gerendert. Alle anderen Sprachen werden unter `/{id}/` gerendert. Sie wählen die IDs, Labels und welche Sprache die Standardsprache ist - es gibt keine fest programmierten Annahmen. Wenn Sie Hindi als Standardsprache möchten, setzen Sie `default: 'hi'`, und Hindi wird unter `/` gerendert, während Englisch unter `/en/` erscheint. | Schlüssel | Typ | Beschreibung | |:----|:-----|:------------| | `default` | `string` | Sprach-ID, die unter `/` gerendert wird. Standardmäßig die erste Sprache, wenn weggelassen. | | `locales` | `array` | Liste von Sprachobjekten. Jedes muss eine `id` haben. | | `position` | `string` | Position des Sprachumschalters. `options-menu` (Standard), `sidebar-top` oder `sidebar-bottom`. | | `stringMode` | `boolean` | Wenn `true`, werden Sprachseiten aus einer einzigen Quelle mittels `data-i18n`-Attribut-Ersetzung generiert. Standard: `false`. | | `inPlace` | `boolean` | Wenn `true` (mit clientseitigem Skript), werden Strings ohne URL-Navigation getauscht. Nur für SPAs/Dashboards. Standard: `false`. | Jedes Sprachobjekt akzeptiert: | Schlüssel | Typ | Standard | Beschreibung | |:----|:-----|:--------|:------------| | `id` | `string` | - | Ein beliebiger Identifikator Ihrer Wahl (z. B. `en`, `hi`, `fr-ca`). Wird als Ordnername und URL-Präfix verwendet. Erforderlich. | | `label` | `string` | Gleich wie `id` | Im Sprachumschalter angezeigter Name. | | `dir` | `string` | `ltr` | Textrichtung. Setzen Sie `rtl` für Arabisch, Hebräisch usw. | | `translations` | `object` | `{}` | Benutzerdefinierte Überschreibungen für UI-Strings (siehe [Benutzerdefinierte UI-Strings](./ui-strings)). | ## URL-Struktur Die Standardsprache hat kein URL-Präfix. Andere Sprachen werden unter `/{id}/` verschachtelt. In Kombination mit [Versionierung](../versioning) lautet die URL `/{locale}/{version}/seite`. ``` / ← Standardsprache, aktuelle Version /getting-started ← Seite der Standardsprache /05/ ← Standardsprache, alte Version /hi/ ← Andere Sprache, aktuelle Version /hi/getting-started ← Seite der anderen Sprache /hi/05/ ← Andere Sprache, alte Version ``` Der Sprachumschalter behält die aktuelle Seite und Version beim Sprachwechsel bei. Der Versionsumschalter behält die aktuelle Sprache bei. ## Fehlende Locale-Verzeichnisse Wenn eine Locale in `locales` deklariert ist, aber das zugehörige Quellverzeichnis nicht existiert (z. B. kein Ordner `docs/hi/`), **deaktiviert** docmd diese Locale automatisch im Sprachumschalter. Die Locale erscheint weiterhin im Dropdown - mit einem „N/A"-Badge und ausgegrautem Stil - aber ein Klick darauf bewirkt nichts. Dies verhindert 404-Fehler, wenn Sie geplante Sprachen auflisten, bevor deren Inhalte fertig sind. ## Positionierung des Sprachumschalters Steuern Sie die Position des Sprachumschalters mit der Option `position`: ```js i18n: { position: 'options-menu', // Standard // ... } ``` | Position | Verhalten | |:---------|:----------| | `options-menu` | Kompaktes Erdkugel-Icon neben Theme-Umschalter und Suche. Standard. | | `sidebar-top` | Vollständiges Dropdown mit Label oben in der Seitenleiste. | | `sidebar-bottom` | Vollständiges Dropdown mit Label unten in der Seitenleiste. | ## String-Modus (nur für noStyle-Seiten) Standard-i18n verwendet separate Verzeichnisse pro Sprache (`docs/en/`, `docs/hi/`), jedes mit eigenen Markdown-Dateien. **String Mode** ist eine einfachere Alternative, die speziell für [noStyle-Seiten](../../content/no-style-pages.md) entwickelt wurde - Seiten, die reines HTML anstelle von Markdown verwenden. ```js // docmd.config.js export default { i18n: { default: 'en', stringMode: true, locales: [ { id: 'en', label: 'English' }, { id: 'zh', label: '中文' } ] } } ``` Mit `stringMode: true`: 1. Quelldateien bleiben im Stammverzeichnis `docs/` (keine Sprach-Unterverzeichnisse) 2. Die Standardsprache wird wie gewohnt unter `/` erstellt 3. Für jede andere Sprache klont docmd das gerenderte HTML und führt eine **serverseitige String-Ersetzung** mittels JSON-Dateien aus `assets/i18n/{locale}.json` durch 4. Die Ausgabe erfolgt unter `/{locale}/` - z. B. `/zh/index.html` - mit vollem SEO (hreflang-Tags, korrektes `lang`-Attribut) 5. Falls eine Übersetzungsdatei fehlt, wird die Seite im Text der Standardsprache gerendert Weitere Details zur Syntax des `data-i18n`-Attributs und zum JSON-Dateiformat finden Sie unter [noStyle String-Ersetzung](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: callout warning "String Mode übersetzt keine Markdown-Inhalte" Die String-Ersetzung funktioniert durch das Finden von `data-i18n`-Attributen im gerenderten HTML. Standard-Markdown-Inhalte (`## Überschrift`, Absätze, Listen) werden in einfache HTML-Tags ohne diese Attribute umgewandelt - daher kann der Ersetzer dort nichts finden. - **Dokumentationsseiten** → verwenden Sie den Verzeichnismodus (Standard). Jede Sprache hat eigene Markdown-Dateien mit vollständig übersetztem Text. - **Landingpages, Marketing-Websites, Dashboards** → verwenden Sie den String-Modus. Dies sind noStyle-Seiten mit benutzerdefiniertem HTML, bei dem Sie jeden Tag kontrollieren und `data-i18n`-Attribute hinzufügen können. Wenn Ihre Website beides hat - zum Beispiel eine noStyle-Landingpage plus Dokumentation - verwenden Sie den Verzeichnismodus für die Dokumentation und fügen Sie Ihrer noStyle-Seite `data-i18n`-Attribute hinzu. Der String-Modus übersetzt das noStyle-HTML, während der Verzeichnismodus die Dokumentationsinhalte verarbeitet. ::: ## Nächste Schritte - [Übersetzte Inhalte](./translated-content.md) - Verzeichnisstruktur, Schreiben von Übersetzungen, Navigation - [UI-Strings & SEO](./ui-strings.md) - Anpassen von Systemtexten, hreflang-Tags - [noStyle String-Ersetzung](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle) - Syntax des `data-i18n`-Attributs und JSON-Format für noStyle-Seiten --- ## [Übersetzte Inhalte](https://docs.docmd.io/de/07/configuration/localisation/translated-content/) --- title: "Übersetzte Inhalte" description: "Organisieren Sie Übersetzungen in Sprach-Unterverzeichnissen mit Fallback pro Datei und sprachspezifischer Navigation." --- ## Verzeichnisstruktur Jede Sprache - einschließlich der Standardsprache - lebt in ihrem eigenen Unterverzeichnis innerhalb des Quellverzeichnisses. Der Ordnername entspricht der Sprach-`id` aus Ihrer Konfiguration. ``` docs/ ├── en/ ← Inhalt der Standardsprache │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← Zweite Sprache │ ├── index.md ← Übersetzte Homepage │ ├── navigation.json ← Übersetzte Navigations-Labels │ └── getting-started/ │ └── installation.md ← Übersetzte Seite └── zh/ ← Dritte Sprache └── index.md ← Nur die Homepage übersetzt ``` Das Quellverzeichnis dient als sauberer Container - es enthält ausschließlich Sprachordner. Wenn i18n aktiviert ist, befinden sich keine Inhaltsdateien auf der Stammebene. ::: callout info "Ordnernamen sind Ihre Wahl" Die Ordnernamen stammen direkt aus den `id`-Werten in Ihrer Konfiguration. Wenn Ihre Konfiguration `{ id: 'fr-ca' }` angibt, lautet Ihr Ordner `docs/fr-ca/`. Wenn Hindi Ihre Standardsprache ist (`default: 'hi'`), dann ist `docs/hi/` das Verzeichnis für den kanonischen Inhalt. ::: ## Fallback pro Datei Sie müssen nicht jede Seite übersetzen. docmd scannt das **Verzeichnis der Standardsprache** als kanonische Liste der Seiten. Für jede andere Sprache wird geprüft, ob eine übersetzte Version der jeweiligen Seite existiert: - Wenn `docs/hi/getting-started/installation.md` existiert → wird die Hindi-Übersetzung ausgeliefert - Wenn sie nicht existiert → wird die Version der Standardsprache für diese Seite ausgeliefert Wenn eine Seite auf den Fallback zurückgreift, kann docmd einen übersetzten Callout (Hinweis) anzeigen, der die Besucher informiert, dass die Seite in der Standardsprache angezeigt wird. Diese Nachricht ist über Ihre [UI-Strings](./ui-strings)-Konfiguration anpassbar. ## Sprach-exklusive Seiten Eine Nicht-Standardsprache kann auch Seiten haben, die in der Standardsprache nicht existieren. Diese werden nur für diese Sprache gerendert - sie erscheinen nicht in anderen Sprachen. ## Navigation übersetzen Jedes Sprachverzeichnis kann eine eigene `navigation.json` haben. `docmd` verwendet ein kaskadierendes Prioritätssystem, um die Seitenleiste aufzulösen. Einzelheiten zur Auflösungshierarchie und visuelle Beispiele finden Sie unter [Priorität der Navigationsauflösung](../navigation#prioritat-der-navigationsauflosung). Die `navigation.json` einer Sprache verwendet dasselbe Format: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "Teilweise Navigation" Sie müssen nur dann eine `navigation.json` für eine Sprache erstellen, wenn Sie übersetzte Labels wünschen. Wenn sie fehlt, wird die Navigation der Standardsprache verwendet - die Seiten werden gerendert, nur mit nicht übersetzten Labels. ::: ## Versionierung und i18n zusammen Wenn sowohl Versionierung als auch i18n konfiguriert sind, sieht die Quellstruktur wie folgt aus: ``` docs/ ← Aktuelle Version (Container) en/ ← Aktuelle Version, Standardsprache hi/ ← Aktuelle Version, übersetzte Sprache docs-v1/ ← Alte Version index.md ← Inhalt der alten Version (keine Sprachstruktur) navigation.json ``` Alte Versionen, die i18n zeitlich vorausgehen, funktionieren automatisch - docmd liest sie direkt aus, wenn keine Sprach-Unterverzeichnisse vorhanden sind. Nur die Standardsprache rendert die alte Version. Um Übersetzungen zu einer alten Version hinzuzufügen, erstellen Sie darin ein Sprach-Unterverzeichnis: ``` docs-v1/ hi/ ← Hindi-Übersetzung für v1 index.md navigation.json ``` Die Ausgabe-URLs verschachteln zuerst die Sprache, dann die Version: ``` / ← Standardsprache, aktuelle Version /hi/ ← Übersetzte Sprache, aktuelle Version /v1/ ← Standardsprache, alte Version /hi/v1/ ← Übersetzte Sprache, alte Version ``` --- ## [UI-Strings Lokalisierung](https://docs.docmd.io/de/07/configuration/localisation/ui-strings/) --- title: "UI-Strings Lokalisierung" description: "Passen Sie die in der docmd-Benutzeroberfläche angezeigten Texte (Such-Platzhalter, Navigations-Labels usw.) durch Konfiguration benutzerdefinierter Übersetzungen an." --- Obwohl `docmd` über integrierte Übersetzungen für gängige Sprachen verfügt, möchten Sie möglicherweise UI-Texte für ein bestimmtes Projekt anpassen (z. B. "Search" in "In der Doku suchen" ändern). ## Globale Konfiguration Sie können Übersetzungen für bestimmte Locales direkt in Ihrer `docmd.config.js` definieren. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ locales: { en: { title: 'English', label: 'English' }, de: { title: 'German', label: 'Deutsch' } }, plugins: { localisation: { translations: { de: { 'search.placeholder': 'Dokumentation durchsuchen...', 'nav.next': 'Nächste Seite', 'nav.prev': 'Vorherige Seite', 'toc.title': 'Auf dieser Seite' } } } } }); ``` ## Verfügbare UI-Keys Dies sind die am häufigsten verwendeten UI-Strings, die Sie überschreiben können: | Key | Standardwert (EN) | Beschreibung | | :--- | :--- | :--- | | `search.placeholder` | `Search...` | Platzhalter im Sucheingabefeld. | | `search.noResults` | `No results found` | Text, wenn keine Übereinstimmungen gefunden wurden. | | `nav.next` | `Next` | Text für den "Weiter"-Button im Pagination-Bereich. | | `nav.prev` | `Previous` | Text für den "Zurück"-Button im Pagination-Bereich. | | `toc.title` | `On this page` | Überschrift über der Inhaltsverzeichnis-Seitenleiste. | | `theme.light` | `Light` | Label für den hellen Modus im Theme-Switcher. | | `theme.dark` | `Dark` | Label für den dunklen Modus im Theme-Switcher. | | `theme.system` | `System` | Label für die Synchronisierung mit dem System im Theme-Switcher. | ## Plugin-Beiträge Wenn Sie ein [Plugin entwickeln](../../plugins/building-plugins.md), können Sie auch neue Übersetzungsschlüssel über den `translations`-Hook bereitstellen: ```javascript export default { name: 'mein-plugin', translations(localeId) { if (localeId === 'de') { return { 'meinplugin.status': 'Status' }; } return { 'meinplugin.status': 'Status' }; } }; ``` ::: callout tip "KI-Übersetzungshilfe" Wenn Sie einen KI-Assistenten bitten, Ihrer Website eine neue Sprache hinzuzufügen, stellen Sie ihm diese Liste der UI-Keys zur Verfügung. Dies stellt sicher, dass die KI nicht nur Ihren Inhalt übersetzt, sondern auch einen passenden Satz lokalisierter UI-Strings für Ihre `.config.js`-Datei liefert. ::: --- ## [Menüleiste](https://docs.docmd.io/de/07/configuration/menubar/) --- title: "Menüleiste" description: "Strukturieren und positionieren Sie Ihre Menüleiste, verwalten Sie Navigationslinks und konfigurieren Sie Dropdown-Menüs." --- Die `menubar` ist eine Navigationsschicht, die globalen Kontext über Ihre gesamte Dokumentationsseite hinweg bietet. Sie kann als fixierte Leiste am oberen Rand des Ansichtsbereichs oder als relatives Element über dem Seiten-Header positioniert werden. ## Konfiguration Die Menüleiste wird im Bereich `layout` Ihrer `docmd.config.js` konfiguriert. ```javascript export default defineConfig({ layout: { menubar: { enabled: true, position: 'top', // 'top' (fixiert) oder 'header' (inline) left: [ { type: 'title', text: 'Marke', url: '/', icon: 'home' }, { text: 'Dokumentation', url: '/docs' }, { type: 'dropdown', text: 'Ökosystem', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Live Editor', url: 'https://live.docmd.io' } ] } ], right: [ { text: 'Support', url: '/support', icon: 'help-circle' } ] } } }); ``` ### Optionen | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | Schaltet die Sichtbarkeit der Menüleiste ein/aus. | | `position` | `String` | `'top'` | `'top'` (fixiert ganz oben) oder `'header'` (über dem Seitentitel positioniert). | | `left` | `Array` | `[]` | Navigationselemente, die links ausgerichtet sind. | | `right` | `Array` | `[]` | Navigationselemente, die rechts ausgerichtet sind. | ## Element-Typen Die Arrays `left` und `right` unterstützen verschiedene Element-Typen, um Ihre Navigation effektiv zu strukturieren: ### 1. Standard-Link Der am häufigsten verwendete Element-Typ. - `text`: Anzeigename. - `url`: Pfad oder externe URL. - `icon`: Optionaler Name eines Lucide-Icons. - `external`: Auf `true` setzen, um in einem neuen Tab zu öffnen. ### 2. Titel (Marke) Setzen Sie `type: 'title'`, um Branding-Styles (normalerweise fett oder mit einer spezifischen Schriftstärke) auf den Link anzuwenden. ### 3. Dropdown-Menü Setzen Sie `type: 'dropdown'` und geben Sie ein `items`-Array an, um ein verschachteltes Menü zu erstellen. ## Werkzeug-Integration Sie können die globale Suche und den Theme-Umschalter in der Menüleiste unterbringen, indem Sie `optionsMenu.position` auf `'menubar'` setzen. ```javascript layout: { optionsMenu: { position: 'menubar' } } ``` Bei der Integration wird das Optionsmenü automatisch im **rechten Bereich** der Menüleiste ausgerichtet und erscheint nach allen im `right`-Array definierten Links. ::: callout info Wenn die `menubar` deaktiviert ist, fallen alle ihr zugewiesenen Werkzeugkomponenten automatisch auf die Position `sidebar-top` zurück. ::: ## Benutzerdefiniertes Styling Sie können das Erscheinungsbild der Menüleiste mithilfe von CSS-Variablen in Ihren `customCss`-Dateien anpassen: ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-color); --menubar-text: var(--docmd-text-primary); } ``` --- ## [Multi-Projekt-Konfiguration](https://docs.docmd.io/de/07/configuration/multi-project/) --- title: "Multi-Projekt-Konfiguration" description: "Erstellen Sie mehrere unabhängige Dokumentationsseiten aus einer einzigen docmd-Instanz. Gemeinsame Assets, unabhängige Versionierung, eine Bereitstellung." --- Erstellen und veröffentlichen Sie mehrere Dokumentationsprojekte aus einem einzigen Repository. Jedes Projekt behält seine eigene Konfiguration, Versionierung und Navigation, während es ein gemeinsames Theme und eine gemeinsame Asset-Pipeline nutzt. ## Übersicht Der Multi-Projekt-Modus ist für Organisationen konzipiert, die mehrere Tools, Bibliotheken oder Produkte unter einer Domain pflegen. Statt mehrere docmd-Instanzen hinter einem Reverse-Proxy zu betreiben, erzeugt ein einzelnes `docmd build` ein einheitliches `site/`-Verzeichnis. ``` docs.example.com/ → Hauptdokumentation docs.example.com/sdk/ → SDK-Referenz docs.example.com/cli/ → CLI-Dokumentation ``` ## Einrichtung ### 1. Verzeichnisstruktur Organisieren Sie Ihr Repository mit einem Verzeichnis pro Projekt: ``` my-docs/ ├── assets/ ← gemeinsame Assets (alle Projekte) ├── main-docs/ │ ├── docmd.config.js ← Projektkonfiguration │ └── v01/ ← versionierte Inhalte │ └── en/ ├── sdk-docs/ │ ├── docmd.config.js ← Projektkonfiguration │ └── docs/ ← nicht-versionierte Inhalte ├── docmd.config.js ← Root-Multi-Projekt-Konfiguration └── package.json ``` ### 2. Root-Konfiguration Die Root-`docmd.config.js` enthält **nur** das `projects`-Array: ```javascript module.exports = defineConfig({ projects: [ { prefix: '/', src: 'main-docs' }, { prefix: '/sdk', src: 'sdk-docs' } ] }); ``` | Schlüssel | Beschreibung | | :-- | :---------- | | `prefix` | URL-Präfix für dieses Projekt. Verwenden Sie `'/'` für das Root-Projekt. | | `src` | Verzeichnis mit der `docmd.config.js` und den Inhalten dieses Projekts. | ::: callout warning Jede Multi-Projekt-Konfiguration **muss** ein Root-Projekt mit `prefix: '/'` enthalten. ::: ### 3. Projektkonfigurationen Jedes Projektverzeichnis hat seine eigene `docmd.config.js` mit vollständig unabhängiger Konfiguration. Fügen Sie **keine** `src`- oder `out`-Schlüssel ein - die übergeordnete Konfiguration stellt diese automatisch bereit. Jedes Projekt kann vollständig unabhängige Einstellungen haben: - **i18n** - verschiedene Sprachen, verschiedene Standardsprachen - **Versionierung** - unterschiedliche Versionsnummern und Strukturen - **Plugins** - nur aktivieren, was jedes Projekt benötigt - **Navigation** - individuelle Seitenleiste für jedes Projekt ## Assets ### Gemeinsame Assets Legen Sie gemeinsame Ressourcen (Logos, Favicons, globales CSS) im Root-`assets/`-Verzeichnis ab. Diese werden automatisch in die Ausgabe jedes Projekts kopiert. ### Projektspezifische Assets Jedes Projekt kann ein eigenes `assets/`-Verzeichnis haben. Projektspezifische Assets haben Vorrang vor gemeinsamen Assets bei Namenskonflikten. ``` my-docs/ ├── assets/ │ └── images/ │ └── logo.png ← von allen Projekten verwendet ├── sdk-docs/ │ └── assets/ │ └── images/ │ └── logo.png ← überschreibt Logo nur für SDK ``` ## Entwicklung Starten Sie den Multi-Projekt-Entwicklungsserver: ```bash docmd dev ``` Der Server erstellt alle Projekte und stellt sie über einen einzigen Port bereit: ``` ┌─ DEV SERVER │ │ Local http://127.0.0.1:3000 │ Network http://192.168.1.5:3000 │ │ Project http://127.0.0.1:3000/ │ Project http://127.0.0.1:3000/sdk └────────────────────────────────────────────────────────── ``` Dateiänderungen in einem Projekt lösen einen gezielten Neubau mit Live-Reload aus. Nur das betroffene Projekt wird neu erstellt - andere Projekte bleiben für schnelle Iteration unberührt. Änderungen an gemeinsamen Assets erstellen alle Projekte neu. ## Erstellen & Bereitstellen ```bash docmd build ``` Die Ausgabe ist ein einzelnes statisches Verzeichnis: ``` site/ ├── index.html ← main-docs Root ├── sdk/ │ └── index.html ← sdk-docs Root ├── assets/ ← zusammengeführte Assets ├── 404.html └── sitemap.xml ``` Veröffentlichen Sie es auf jedem statischen Hosting (GitHub Pages, Netlify, Vercel, Cloudflare Pages) ohne zusätzliche Konfiguration. Keine nginx- oder Proxy-Regeln erforderlich. ## Regeln & Einschränkungen 1. **Root-Projekt erforderlich** - ein Projekt muss `prefix: '/'` haben 2. **Keine doppelten Präfixe** - jedes Projekt benötigt ein einzigartiges URL-Präfix 3. **Kein `src`/`out` in untergeordneten Konfigurationen** - die übergeordnete Konfiguration stellt diese bereit 4. **Alles unabhängig** - jedes Projekt hat eigene Titel, Versionen, i18n, Plugins und Navigation 5. **Root-Konfiguration minimal** - nur `projects` sollte in der Root-`docmd.config.js` stehen --- ## [Navigation](https://docs.docmd.io/de/07/configuration/navigation/) --- title: "Navigation" description: "Definieren Sie die Seitenleistenstruktur Ihrer Website über die globale Konfiguration, verzeichnisspezifische navigation.json-Dateien oder automatisches Dateiscannen." --- `docmd` bietet ein hochflexibles Navigationssystem, das von einfachen Projekten mit nur einem Ordner bis hin zu komplexen Dokumentations-Hubs mit mehreren Versionen und Sprachen skaliert. ## Methoden der Navigationsdefinition Es gibt drei Möglichkeiten, die Navigation zu definieren. Wenn mehrere Methoden gleichzeitig verwendet werden, löst `docmd` diese in der folgenden Prioritätsreihenfolge auf: ### 1. Globale Konfiguration (`docmd.config.js`) Ideal für kleinere Projekte. Die gesamte Navigationslogik wird in der Hauptkonfigurationsdatei gehalten. ```javascript export default { navigation: [ { title: 'Erste Schritte', path: '/intro' }, { title: 'API-Referenz', path: '/api', children: [...] } ] } ``` ### 2. Verzeichnisspezifische Konfiguration (`navigation.json`) Dies ist die **empfohlene Methode** für umfangreiche Dokumentationen. Platzieren Sie eine `navigation.json`-Datei in Ihrem `docs/`-Verzeichnis (oder einem beliebigen Unterverzeichnis). ```json [ { "title": "Übersicht", "path": "overview.md" }, { "title": "Fortgeschrittene Themen", "children": [...] } ] ``` ### 3. Automatisches Dateiscannen (Fallback) Wenn weder eine globale Konfiguration noch eine `navigation.json` definiert ist, scannt `docmd` automatisch Ihr Dateisystem und erstellt eine alphabetische Seitenleiste. ## Attribute von Navigationsobjekten Jeder Navigationseintrag unterstützt die folgenden Attribute: | Attribut | Typ | Beschreibung | | :--- | :--- | :--- | | `title` | `string` | Der in der Seitenleiste angezeigte Text. | | `path` | `string` | Der Pfad zur Quelldatei relativ zum aktuellen Verzeichnis (z. B. `intro.md`). | | `icon` | `string` | Der Name eines Icons aus der Lucide-Bibliothek (z. B. `home`). | | `collapsible` | `boolean` | Ob die Gruppe in der Seitenleiste ein- und ausgeklappt werden kann (Standard: `true`). | | `collapsed` | `boolean` | Ob die Gruppe beim ersten Laden eingeklappt sein soll. | | `external` | `boolean` | Ob der Link in einem neuen Tab geöffnet werden soll. | | `children` | `array` | Eine verschachtelte Liste von Unter-Navigationselementen. | ## Priorität der Navigationsauflösung Wenn ein Benutzer eine Seite besucht, wird die Seitenleiste dynamisch basierend auf der Verzeichnistiefe der Seite berechnet: 1. **Nearest-Neighbor-Match**: Die Engine sucht zuerst nach einer `navigation.json` im selben Ordner wie die aktuelle Seite. 2. **Rekursiver Aufstieg**: Wird keine gefunden, sucht sie im übergeordneten Verzeichnis, bis das Root-Verzeichnis erreicht ist. 3. **Globaler Fallback**: Wenn im gesamten Dateisystem keine `navigation.json` vorhanden ist, werden die Definitionen aus der `docmd.config.js` verwendet. ::: callout tip "Kontextbasierte Navigation" Diese Auflösungslogik ermöglicht es Ihnen, für verschiedene Bereiche Ihrer Website **völlig unterschiedliche** Seitenleisten zu definieren. Beispielsweise kann Ihr `/api/`-Verzeichnis eine Seitenleiste haben, die sich auf technische Definitionen konzentriert, während Ihr `/guides/`-Verzeichnis eine auf Tutorials ausgerichtete Seitenleiste anzeigt. ::: ## Automatisches Sortieren und Verbergen * **Dateien ausschließen**: Wenn eine Datei nicht in der automatisch generierten Seitenleiste erscheinen, aber dennoch erreichbar sein soll, setzen Sie `unlisted: true` im Frontmatter. * **Sortierung**: Die Reihenfolge in der `navigation.json` entspricht exakt der gerenderten Reihenfolge. ::: callout warning "Pfad-Normalisierung" In der `navigation.json` können Sie `overview.md`, `overview` oder `./overview` schreiben. Die Build-Engine normalisiert diese Formate automatisch in saubere URLs für die Produktion. Siehe [Verlinkung & Referenzierung](../content/syntax/linking.md). ::: --- ## [Allgemeine Konfiguration](https://docs.docmd.io/de/07/configuration/overview/) --- title: "Allgemeine Konfiguration" description: "Konfigurieren Sie das Schema der docmd.config.js, Branding, Layout und Engine-Funktionen." --- Die Datei `docmd.config.js` dient als definitive Konfiguration für Ihr Dokumentationsprojekt. Sie steuert die Seitenstruktur, das Branding, das UI-Verhalten und die Verarbeitungsregeln auf Engine-Ebene. ## Die Konfigurationsdatei Wir empfehlen die Verwendung des `defineConfig`-Helpers von `@docmd/core`. Dieser bietet vollständige IDE-Autovervollständigung und Typüberprüfung, was das Entdecken verfügbarer Einstellungen mühelos macht. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ title: 'Mein Projekt', url: 'https://docs.meinprojekt.de', // ... Konfigurationseinstellungen }); ``` ## Kern-Einstellungen `docmd` verwendet ein einfaches Konfigurationsschema. Unten sind die wichtigsten Einstellungen auf oberster Ebene aufgeführt: | Schlüssel | Beschreibung | Standard | | :--- | :--- | :--- | | `title` | Der Name Ihrer Dokumentationsseite. Wird im Header und in Browsertiteln verwendet. | `Documentation` | | `url` | Ihre Produktions-Basis-URL. Wichtig für SEO, Sitemaps und OpenGraph. | `null` | | `src` | Der relative Pfad zum Verzeichnis, das Ihre Markdown-Dateien enthält. | `docs` | | `out` | Der relative Pfad für die generierte statische Website-Ausgabe. | `site` | | `base` | Der Basispfad, wenn die Website in einem Unterordner gehostet wird (z. B. `/docs/`). | `/` | | `i18n` | Konfiguration für die [Sprachunterstützung](./localisation.md). | `null` | | `plugins` | Konfiguration für Standard- oder benutzerdefinierte [Plugins](../plugins/usage.md). | `{}` | ## Branding & Identität Konfigurieren Sie, wie Ihre Marke im Navigations-Header und in Browser-Tabs dargestellt wird. ```javascript logo: { light: 'assets/images/logo-dark.png', // Logo im Hellmodus dark: 'assets/images/logo-light.png', // Logo im Dunkelmodus href: '/', // Ziel-Link beim Klicken auf das Logo alt: 'Unternehmenslogo', // Alternativtext für Barrierefreiheit height: '32px' // Optional: Explizite Höhe für das Logo }, favicon: 'assets/favicon.ico', // Pfad zum Favicon Ihrer Website ``` ## Layout-Architektur `docmd` verfügt über ein modulares Layout-System. Über das `layout`-Objekt können Sie UI-Komponenten umschalten und das Navigationsverhalten konfigurieren. | Bereich | Schlüssel | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | **Global** | `spa` | `true` | Ermöglicht nahtlose Single-Page-Application-Navigation ohne Browser-Reloads. | | **Header** | `header` | `{ enabled: true }` | Schaltet die obere Navigationsleiste ein/aus. | | **Sidebar**| `sidebar`| `{ enabled: true, collapsible: true }` | Steuert den Navigationsbaum der Seitenleiste und sein Verhalten. | | **Footer** | `footer` | `{ style: 'minimal' }` | Unterstützt die Footer-Styles `'minimal'` oder `'complete'`. | ### Werkzeugmenü (Optionsmenü) Das Optionsmenü fasst Werkzeugkomponenten wie **Globale Suche**, **Theme-Umschalter** und **Sponsoring-Links** zusammen. ```javascript layout: { optionsMenu: { position: 'header', // Optionen: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Integrierte Volltextsuche aktivieren themeSwitch: true, // Hell-/Dunkelmodus-Umschalter aktivieren sponsor: 'https://github.com/sponsors/dein-profil' // Optionale URL für ein Herz-Icon/Link } } } ``` ::: callout info Wenn `optionsMenu.position` auf `header` oder `menubar` eingestellt ist, diese Container aber deaktiviert sind, fällt das Menü automatisch auf `sidebar-top` zurück. ::: ## Funktionen der Core-Engine Passen Sie an, wie `docmd` Ihre Dokumentationsinhalte verarbeitet und rendert. ```javascript minify: true, // Minimiert Produktions-Assets (CSS/JS) für bessere Performance autoTitleFromH1: true, // Verwendet die erste H1-Überschrift als Seitentitel, wenn 'title' im Frontmatter fehlt copyCode: true, // Fügt automatisch eine 'Kopieren'-Schaltfläche zu allen Code-Blöcken hinzu pageNavigation: true, // Fügt Navigationslinks für 'Vorherige' und 'Nächste' am Ende der Seiten hinzu ``` ## Unterstützung veralteter Versionen (Legacy) Wenn Sie von einer älteren Version von `docmd` aktualisieren, werden die folgenden Schlüssel automatisch dem modernen Schema zugeordnet, um die Abwärtskompatibilität zu gewährleisten: * `siteTitle` → `title` * `siteUrl` / `baseUrl` → `url` * `srcDir` / `source` → `src` * `outDir` / `outputDir` → `out` ::: callout tip Führen Sie `docmd migrate` aus, um Ihre Konfigurationsdatei automatisch auf das neueste Schema zu aktualisieren, wobei ein Backup Ihrer ursprünglichen Einstellungen erhalten bleibt. ::: --- ## [Weiterleitungen & 404](https://docs.docmd.io/de/07/configuration/redirects/) --- title: "Weiterleitungen & 404" description: "Konfigurieren Sie Metadaten-basierte Weiterleitungen und benutzerdefinierte 404-Fehlerseiten für statische Deployments." --- In einer statischen Hosting-Umgebung gibt es keine serverseitige Logik (wie Nginx-Regeln oder `.htaccess`-Dateien), um dynamisches Routing zu verarbeiten. `docmd` löst dies durch das Generieren nativer HTML-Sicherungsmechanismen, die Weiterleitungen und Fehlerzustände automatisch behandeln. ## Serverlose Weiterleitungen (Redirects) Sie können Traffic von alten URLs auf neue Ziele umleiten, indem Sie ein Mapping im `redirects`-Objekt definieren. ```javascript export default defineConfig({ redirects: { '/setup': '/getting-started/installation', // Kurz-URL zu Deep-Link '/v1/api': '/api-reference' // Alte Version zu modernem Pfad } }); ``` ### Technische Umsetzung Wenn eine Weiterleitung definiert ist, erstellt `docmd` eine `index.html`-Datei am alten Pfad, die ein `<meta http-equiv="refresh">`-Tag enthält. Diese Strategie gewährleistet: 1. **Nahtlose Weiterleitung**: Benutzer werden sofort nach dem Laden der Seite zum neuen Ziel weitergeleitet. 2. **SEO-Erhalt**: Suchmaschinen erkennen die Weiterleitung, was hilft, die Link-Autorität (Link Equity) zu erhalten. 3. **Analytics-Tracking**: Seitenaufrufe werden erfasst, bevor die Weiterleitung stattfindet, wodurch Ihre Traffic-Daten erhalten bleiben. ## Markenkonforme 404-Seiten Wenn ein Benutzer versucht, auf eine nicht existierende URL zuzugreifen, suchen die meisten statischen Hosting-Anbieter (Netlify, Vercel, GitHub Pages) automatisch nach einer `404.html`-Datei im Stammverzeichnis. `docmd` generiert diese Datei standardmäßig und stellt sicher, dass sie das Theme, die Seitenleiste und die SPA-Funktionalität Ihrer Website erbt. ### Fehlerinhalt anpassen Sie können die 404-Fehlermeldung in Ihrer Konfiguration personalisieren: ```javascript export default defineConfig({ notFound: { title: '404: Seite nicht gefunden', content: "Wir konnten die gesuchte Seite nicht finden. Nutzen Sie die Seitenleiste, um zurückzufinden." } }); ``` ::: callout tip "Lokale Entwicklung" Der `docmd dev`-Server liefert automatisch Ihre benutzerdefinierte 404-Seite aus, wann immer eine angeforderte Datei fehlt, sodass Sie das Fehlererlebnis lokal testen können. ::: --- ## [Versionierung](https://docs.docmd.io/de/07/configuration/versioning/) --- title: "Versionierung" description: "Aktivieren Sie mehrdimensionale Dokumentationen mit nahtlosem Wechsel, Beibehaltung des Pfades und isolierten Build-Verzeichnissen." --- `docmd` verfügt über eine native Versionierungs-Engine, mit der Sie mehrere Versionen Ihres Projekts gleichzeitig verwalten und bereitstellen können (z. B. `v1.x`, `v2.x`). Die Engine übernimmt automatisch das URL-Routing, die Aktualisierung der Seitenleiste und die Logik für den Versionswechsel. ## Verzeichnis-Organisation Um die Versionierung zu aktivieren, organisieren Sie Ihre Dokumentation in versionierten Quellordnern. Ein gängiges Schema ist, die aktive Version in `docs/` zu halten und archivierte Versionen in Verzeichnissen mit dem Präfix `docs-` zu speichern. ```text mein-projekt/ ├── docs/ # Aktuelle Version (Hauptversion) ├── docs-v1/ # Veraltete Version ├── docmd.config.js ``` ## Konfiguration Definieren Sie Ihre Versionen innerhalb des `versions`-Objekts: ```javascript export default defineConfig({ versions: { current: 'v2', // Die Version-ID, die im Root (/) erstellt wird position: 'sidebar-top', // Position des Umschalters: 'sidebar-top' oder 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Aktuell)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## Kernfunktionen ### 1. Root-SEO (Die „aktuelle“ Version) Die als `current` festgelegte Version wird direkt in Ihrem Ausgabe-Root generiert (z. B. `meineseite.de/`). Dies stellt sicher, dass Ihr primärer Suchtraffic immer auf Ihrer aktuellsten Dokumentation landet. ### 2. Isolierte Unterverzeichnisse Nicht-aktuelle Versionen werden automatisch in Unterordnern erstellt, die ihrer `id` entsprechen. * `v2 (Aktuell)` → `meineseite.de/` * `v1` → `meineseite.de/v1/` ### 3. Permanenter Wechsel (Pfadbeibehaltung) `docmd` behält den relativen Pfad bei, wenn ein Benutzer die Version wechselt. Wenn ein Benutzer `meineseite.de/erste-schritte` liest und auf **v1** wechselt, wird er automatisch zu `meineseite.de/v1/erste-schritte` weitergeleitet (sofern die Seite existiert), anstatt zur Startseite zurückgeführt zu werden. ### 4. Asset-Isolation Jede Version erbt Ihr globales `assets/`-Verzeichnis, aber `docmd` stellt sicher, dass diese während des Build-Prozesses isoliert werden, um Style-Abweichungen oder Versionskonflikte zu vermeiden. ### 5. Versionierte Navigation Jede Version kann ihre eigene, unabhängige Navigationsstruktur verwalten. `docmd` verwendet ein kaskadierendes Prioritätssystem, um die Seitenleiste aufzulösen. Dies ermöglicht die Verwendung einer zentralen Konfiguration oder versions-/sprachspezifischer `navigation.json`-Dateien. Einzelheiten zur Auflösungshierarchie und visuelle Beispiele finden Sie unter [Priorität der Navigationsauflösung](./navigation#prioritat-der-navigationsauflosung). ## Best Practices 1. **Semantische IDs**: Verwenden Sie prägnante, URL-freundliche IDs wie `v1`, `v2` oder `beta`. 2. **Navigations-Parität**: Behalten Sie konsistente Ordnerstrukturen über die Versionen hinweg bei, um die Effektivität der „Pfadbeibehaltung“ zu maximieren. 3. **Einheitliche Konfiguration**: Sie benötigen keine separaten Konfigurationsdateien für jede Version; `docmd` verarbeitet alle Versionen in einem einzigen Durchgang. --- ## [Buttons](https://docs.docmd.io/de/07/content/containers/buttons/) --- title: "Buttons" description: "Fügen Sie Call-to-Action-Buttons für internes Routing oder externe Ressourcen mit einer einzeiligen Syntax ein." --- Buttons sind einflussreiche UI-Elemente, die für eine prominente Navigation verwendet werden. Im Gegensatz zu Block-Containern ist der `button` **selbstschließend** - er wird in einer einzigen Zeile definiert und benötigt kein schließendes `:::`-Tag. ## Syntax ```markdown ::: button "Beschriftung" Pfad [Optionen] ``` ### Optionen-Referenz | Eigenschaft | Format | Beschreibung | | :--- | :--- | :--- | | **Pfad (Path)** | `/pfad/` | Relative Projekt-URL (wird automatisch für die SPA-Navigation aufgelöst). | | **Extern (External)** | `external:URL`| Öffnet die Ziel-URL in einem neuen Browser-Tab (`target="_blank"`). | | **Farbe (Color)** | `color:WERT` | Wendet eine Hintergrundfarbe an (unterstützt CSS-Namen oder Hex-Codes). | | **Icon** | `icon:NAME` | Fügt ein [Lucide](external:https://lucide.dev/icons)-Icon vor der Button-Beschriftung hinzu. | ## Anwendungsbeispiele ### 1. Interne Navigation Verwenden Sie relative Pfade, um nahtlose Übergänge ohne Neuladen innerhalb der `docmd` SPA zu gewährleisten. ```markdown ::: button "docmd installieren" /getting-started/installation ``` ::: button "docmd installieren" /getting-started/installation ### 2. Link zu externen Ressourcen Stellen Sie der URL `external:` voran, um eine sichere externe Verlinkung zu gewährleisten. ```markdown ::: button "GitHub-Repository anzeigen" external:https://github.com/docmd-io/docmd ``` ::: button "GitHub-Repository anzeigen" external:https://github.com/docmd-io/docmd ### 3. Semantisches & Marken-Styling Passen Sie Buttons durch Farbüberschreibungen an Ihre Markenidentität oder semantische Priorität an. ```markdown ::: button "Gefährliche Aktion" /delete color:crimson ::: button "Erfolgreiche Bestätigung" /success color:#228B22 ``` ::: button "Gefährliche Aktion" ./#delete color:crimson ::: button "Erfolgreiche Bestätigung" ./#success color:#228B22 ### 4. Buttons mit Icons Fügen Sie ein Lucide-Icon hinzu, um die visuelle Klarheit zu verbessern. ```markdown ::: button "Erste Schritte" /getting-started/installation icon:arrow-right ::: button "Quellcode anzeigen" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "Erste Schritte" /getting-started/installation icon:arrow-right ::: button "Quellcode anzeigen" external:https://github.com/docmd-io/docmd icon:github ## Wichtiger Hinweis: Selbstschließende Logik Da Buttons selbstschließend sind, beendet das Hinzufügen einer abschließenden `:::`-Zeile den **übergeordneten Container** (z. B. eine Card oder ein Tab), in dem sich der Button befindet, was potenziell Ihr Layout zerstören kann. **Falsche Sequenz:** ```markdown ::: card "Setup" ::: button "Beginnen" /setup ::: <-- Fehler: Dies schließt die Card vorzeitig. ::: ``` **Richtige Sequenz:** ```markdown ::: card "Setup" ::: button "Beginnen" /setup ::: <-- Richtig: Dies schließt die Card. ``` --- ## [Callouts](https://docs.docmd.io/de/07/content/containers/callouts/) --- title: "Callouts" description: "Heben Sie kritische Warnungen, Pro-Tipps und Hintergrundkonformationen durch semantische visuelle Blöcke hervor." --- Callouts werden verwendet, um Informationen hervorzuheben, die die sofortige Aufmerksamkeit des Lesers erfordern. `docmd` bietet fünf semantische Typen an, die jeweils ein unterschiedliches visuelles Design und thematische Icons besitzen. ::: callout info "Migrationsfreundliche Aliase" Wenn Sie von **VitePress** oder **Docusaurus** migrieren, können Sie deren native Syntax direkt verwenden: - `:::tip`, `:::warning`, `:::danger`, `:::info` (VitePress) - `:::note`, `:::caution` (Docusaurus) Diese Aliase werden identisch zu ihren `docmd`-Äquivalenten gerendert. Leerzeichenlose Syntax wie `:::callout` funktioniert ebenfalls. ::: ## Syntax-Referenz ```markdown ::: callout typ "Optionaler Titel" Der technische Inhalt oder die Warnung wird hier platziert. ::: ``` Fügen Sie einen optionalen `icon:`-Parameter hinzu, um das Standard-Icon des Typs durch ein beliebiges [Lucide](external:https://lucide.dev/icons)-Icon zu ersetzen: ```markdown ::: callout info "Benutzerdefiniertes Icon" icon:sparkles Dieser Callout verwendet ein benutzerdefiniertes Icon anstelle des Standard-Info-Icons. ::: ``` ### Unterstützte semantische Typen | Typ | Absicht | Visuelles Signal | | :--- | :--- | :--- | | `info` | **Allgemeine Daten** | Kontextueller Hintergrund oder hilfreiche, nicht kritische Infos. | | `tip` | **Optimierung** | Performance-Shortcuts oder "Pro-Tipps". | | `warning`| **Vorsicht** | Potenzielle Probleme oder veraltete Funktionen, die beachtet werden sollten. | | `danger` | **Kritisch** | Risiko von Datenverlust, Breaking Changes oder Systemausfall. | | `success`| **Verifizierung** | Bestätigung einer erfolgreichen Konfiguration oder eines erfolgreichen Builds. | ## Implementierungsgalerie ### 1. Minimalistischer Informationshinweis ```markdown ::: callout info Legacy-Konfigurationsschemata werden weiterhin unterstützt, aber nicht mehr empfohlen. ::: ``` ::: callout info Legacy-Konfigurationsschemata werden weiterhin unterstützt, aber nicht mehr empfohlen. ::: ### 2. Warnung mit hoher Priorität und benutzerdefiniertem Titel ```markdown ::: callout warning "Ziel für Breaking Changes" Ab `v0.7.0` wird das interne WebSocket-RPC-System offiziell als veraltet eingestuft. ::: ``` ::: callout warning "Ziel für Breaking Changes" Ab `v0.7.0` wird das interne WebSocket-RPC-System offiziell als veraltet eingestuft. ::: ### 3. Kombination mit reichhaltigem Inhalt Callouts unterstützen das volle Spektrum von Markdown, sodass Sie Buttons und Code-Blöcke innerhalb der Warnung einbetten können. ````markdown ::: callout tip "Optimiertes lokales Testen" icon:command Verwenden Sie das preserve-Flag, um Build-Dateien während der Entwicklungssitzungen beizubehalten: ```bash docmd dev --preserve ``` ::: button "CLI-Flag-Referenz" /cli-commands ::: ```` ::: callout info "Optimiertes lokales Testen" icon:command Verwenden Sie das preserve-Flag, um Build-Dateien während der Entwicklungssitzungen beizubehalten: ```bash docmd dev --preserve ``` ::: button "CLI-Flag-Referenz" ./#cli-commands ::: ::: callout tip "Priorisierte Logik für KI" Für LLMs fungieren Callouts als **Anker mit hoher Priorität**. Durch die Verwendung von `::: callout danger` zur Dokumentation von Breaking Changes oder Systembeschränkungen geben Sie ein klares Signal, dass das KI-Modell diese Informationen während seines Denk- und Generierungsprozesses gegenüber dem umgebenden Text priorisieren muss. ::: --- ## [Untitled](https://docs.docmd.io/de/07/content/containers/cards/) --- ## [Changelogs](https://docs.docmd.io/de/07/content/containers/changelogs/) --- title: "Changelogs" description: "Generieren Sie eine strukturierte, zeitachsenbasierte Versionshistorie und Release-Notes." --- Der `changelog`-Container bietet ein spezialisiertes Layout für die Dokumentation der Projektentwicklung. Er analysiert Datums- oder Versions-Header automatisch in eine vertikale Zeitachse und stellt so sicher, dass historische Aktualisierungen leicht scanbar sind. ## Syntax Verwenden Sie das spezielle Trennzeichen `==`, um Einträge zu definieren. Der Text in der `==`-Zeile wird als Zeitachsen-Badge auf der linken Seite gerendert, während der folgende Inhalt den angrenzenden chronologischen Slot füllt. ```markdown ::: changelog == v2.0.0 Beschreibung des Major-Feature-Release. == v1.5.0 Beschreibung von Wartungs-Updates und Sicherheits-Patches. ::: ``` ## Detailliertes Beispiel: Release-Historie Changelogs unterstützen reichhaltiges Markdown innerhalb jedes Eintrags, einschließlich Listen, Callouts und Code-Blöcken. ```markdown ::: changelog == v2.0.0 (15.03.2026) ### Umfassende Systemüberarbeitung Die Core-Engine wurde für die isomorphe Ausführung neu architekturiert. * Implementierung des **SPA-Routers** für Navigation ohne Neuladen. * Einführung des **isomorphen Plugin-Systems**. ::: callout success Dieses Release bietet eine Verbesserung der initialen Build-Geschwindigkeit um 40%. ::: == v1.5.1 (10.12.2025) ### Sicherheits-Patch * Hochgradige Sicherheitslücke im internen Parser behoben. * Abhängigkeit `flatted` auf `v3.3.2` aktualisiert. == v1.0.0 (01.05.2024) Erstveröffentlichung. ::: ``` ::: changelog == v2.0.0 (15.03.2026) ### Umfassende Systemüberarbeitung Die Core-Engine wurde für die isomorphe Ausführung neu architekturiert. * Implementierung des **SPA-Routers** für Navigation ohne Neuladen. * Einführung des **isomorphen Plugin-Systems**. ::: callout success Dieses Release bietet eine Verbesserung der initialen Build-Geschwindigkeit um 40%. ::: == v1.5.1 (10.12.2025) ### Sicherheits-Patch * Hochgradige Sicherheitslücke im internen Parser behoben. * Abhängigkeit `flatted` auf `v3.3.2` aktualisiert. == v1.0.0 (01.05.2024) Erstveröffentlichung. ::: ::: callout tip "Historischer Kontext für KI" Changelogs liefern eine zeitliche Karte für KI-Agenten. Wenn ein LLM den `llms-full.txt`-Kontext analysiert, ermöglicht die `::: changelog`-Struktur eine genaue Identifizierung, wann spezifische Funktionen, Breaking Changes oder Sicherheitsfixes eingeführt wurden, was zu einer höheren Genauigkeit bei Entwicklungsempfehlungen führt. ::: --- ## [Ausklappbare Abschnitte](https://docs.docmd.io/de/07/content/containers/collapsible/) --- title: "Ausklappbare Abschnitte" description: "Betten Sie interaktive Umschalter im Akkordeon-Stil für FAQs, vertiefende Inhalte und Spoiler ein." --- Der `collapsible`-Container erstellt einen interaktiven, umschaltbaren Abschnitt (Akkordeon). Dieses Muster ist ideal für FAQs, detaillierte technische Konfigurationen oder alle sekundären Informationen, die zugänglich sein sollen, ohne den primären Dokumentationsfluss zu überladen. ::: callout info "VitePress-Alias" Wenn Sie von **VitePress** migrieren, können Sie `:::details` als Alias für `:::collapsible` verwenden. Leerzeichenlose Syntax wie `:::collapsible` funktioniert ebenfalls. ::: ## Syntax ```markdown ::: collapsible [open] "Titel-Text" Der Hauptinhalt wird hier platziert. ::: ``` ### Optionen-Referenz - **`open`**: (Optional) Wenn angegeben, wird der Abschnitt im erweiterten Zustand initialisiert. - **`"Titel"`**: Der Text, der auf der interaktiven Umschaltleiste gerendert wird. Standardmäßig "Klicken zum Erweitern", wenn weggelassen. - **`icon:NAME`**: (Optional) Fügt ein [Lucide](external:https://lucide.dev/icons)-Icon vor dem Titeltext hinzu. ## Detaillierte Implementierungsbeispiele ### Standardverwendung (Initialzustand: Geschlossen) Hauptsächlich für FAQs oder zur Reduzierung der visuellen Dichte technischer Seiten verwendet. ```markdown ::: collapsible "Wie aktualisiere ich docmd?" Führen Sie `npm update -g @docmd/core` aus, um die neueste stabile Engine abzurufen. ::: ``` ::: collapsible "Wie aktualisiere ich docmd?" Führen Sie `npm update -g @docmd/core` aus, um die neueste stabile Engine abzurufen. ::: ### Opt-In-Sichtbarkeit (Initialzustand: Offen) Ideal für Abschnitte, die standardmäßig sichtbar sein sollten, dem Benutzer aber ermöglichen, sie für eine sauberere Ansicht zu minimieren. ```markdown ::: collapsible open "Umgebungsvoraussetzungen" 1. Node.js v18+ (LTS empfohlen) 2. PNPM-Paketmanager ::: ``` ::: collapsible open "Umgebungsvoraussetzungen" 1. Node.js v18+ (LTS empfohlen) 2. PNPM-Paketmanager ::: ### Verschachtelte technische Daten Collapsibles können komplexe Markdown-Elemente enthalten, einschließlich syntax-hervorgehobener Codeblöcke. ````markdown ::: collapsible "Beispiel-JSON-Antwort analysieren" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "Beispiel-JSON-Antwort analysieren" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ::: callout tip Obwohl Inhalte innerhalb eines `collapsible` für den menschlichen Benutzer verborgen sein können, bleiben sie für den `docmd`-Suchindex vollständig sichtbar und sind im einheitlichen `llms-full.txt`-Stream enthalten. Dies stellt sicher, dass KI-Agenten umfassende Antworten basierend auf verborgenen technischen Details geben können, während die für Menschen sichtbare Benutzeroberfläche sauber und priorisiert bleibt. ::: --- ## [URL-Embeds](https://docs.docmd.io/de/07/content/containers/embed/) --- title: URL-Embeds description: Wie Sie dynamische Komponenten, Videos und soziale Medien sicher direkt in Ihre Dokumente einbetten. --- `docmd` wird nativ mit dem hochoptimierten **[embed-lite](external:https://github.com/mgks/embed-lite)**-Parser-Ökosystem ausgeliefert. Dies ermöglicht es Ihnen, rohe externe URLs strikt auf der Seite abzubilden und sie sofort in vollständig sichere UI-Komponenten mit Null-Latenz zu verwandeln! ## Unterstützte Plattformen Die integrierte Engine stellt nativ strukturierte Formatter für die folgenden Netzwerke identisch zur Verfügung: * **Video-Ökosystem:** YouTube (einschließlich nativer 9:16 Shorts-Unterstützung), Vimeo, Dailymotion, TikTok * **Soziale Verbindungen:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **Code & Prototyping:** GitHub Gists, CodePen, Figma, Google Maps * **Musikdienste:** Spotify, SoundCloud ## Nutzungssyntax Sie verwenden einfach den `::: embed`-Container gefolgt von einer beliebigen Ziel-URL. Alle drei umschließenden Formate sind äquivalent: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### Beispiel für Standardergebnis Die Rendering-Engine parst diese URL strikt im Hintergrund, prüft die Validierungsmatrix und fügt native HTML-Knoten strukturell direkt und elegant in Ihre Seitenausgabe ein: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## Fallback-Sicherheit Machen Sie sich keine Sorgen über die Generierung defekter Bildschirme. Wenn der interne Parser ein nicht verifiziertes oder strikt nicht verfügbares Domain-Konfigurations-Mapping scannt, fällt `docmd` elegant auf die Generierung einer einfachen, soliden `<a>`-Hyperlink-Schaltfläche zurück, die explizit auf das Ziel verweist: ```md ::: embed "https://docs.docmd.io/de/content/containers/embed/" ``` *(Fährt fort, genau das zu generieren, was Sie unten sehen würden)* ::: embed "https://docs.docmd.io/de/content/containers/embed/" --- ## [Grids](https://docs.docmd.io/de/07/content/containers/grids/) --- title: "Grids" description: "Organisieren Sie Layouts nahtlos mit sich automatisch anpassenden, responsiven Spalten unter Verwendung nativer Markdown-Container." --- Grids bieten ein natives, Markdown-gesteuertes Layout-System in `docmd`. Anstatt manuelle HTML-Wrapper zu schreiben, können Sie den `grids`-Container nutzen, um Elemente nebeneinander zu strukturieren. Spalten passen ihre Breite automatisch an, um den verfügbaren Platz auszufüllen, und stapeln sich auf kleineren Bildschirmen (Mobilgeräten) logisch zu vertikalen Reihen. ## Syntax-Referenz ```markdown ::: grids ::: grid #### Komponente A Inhalt für die linke Seite. ::: ::: grid #### Komponente B Inhalt für die rechte Seite. ::: ::: ``` ## Praktische Implementierungsbeispiele ### 1. Präsentation von Funktionen nebeneinander Verwenden Sie Grids, um wichtige Funktionen nebeneinander hervorzuheben, indem Sie beispielsweise strukturelle Cards mit Informationsblöcken kombinieren. ```markdown ::: grids ::: grid ::: card "Geschwindigkeit :rocket:" Basiert auf einer nicht-blockierenden I/O-Pipeline für maximale Performance. ::: ::: ::: grid ::: card "Skalierbarkeit :zap:" Entwickelt für massive Monorepos und umfangreiche Projektstrukturen. ::: ::: ::: ``` ::: grids ::: grid ::: card "Geschwindigkeit :rocket:" Basiert auf einer nicht-blockierenden I/O-Pipeline für maximale Performance. ::: ::: ::: grid ::: card "Skalierbarkeit :zap:" Entwickelt für massive Monorepos und umfangreiche Projektstrukturen. ::: ::: ::: ### 2. Layout-Balancierung Grids berechnen automatisch die optimale Breite pro Spalte (bis zu 4 Elemente pro Reihe auf Ultra-Wide-Bildschirmen) basierend auf dem verfügbaren Inhalt und gruppieren Reihen nahtlos auf schmalen Viewports. ::: callout tip "Semantische Layouts" Die Verwendung des `grids`-Containers sorgt dafür, dass Ihre Dokumentationsstruktur rein in Markdown verfasst bleibt, was zu saubereren Quelldateien führt und sicherstellt, dass LLMs Ihre strukturellen Beziehungen fehlerfrei interpretieren! ::: --- ## [Hero-Abschnitte](https://docs.docmd.io/de/07/content/containers/hero/) --- title: "Hero-Abschnitte" description: "Erstellen Sie wirkungsvolle Landingpage-Header und Marketing-Highlights rein in Markdown." --- Der `hero`-Container erstellt professionelle, visuell beeindruckende Landingpage-Header. Er übernimmt komplexe CSS-Anforderungen wie **Split-Layouts**, **Glow-Effekte** und **Slider**, während die Bearbeitungserfahrung einfach bleibt. ## Basissyntax Standardmäßig zentriert der `hero`-Container seinen Inhalt, was ihn ideal für Banner und einfache Schlagzeilen macht. ```markdown ::: hero # Schneller entwickeln. Vom Markdown zur Produktions-Doku mit einem Befehl. ::: button "Erste Schritte" /intro color:blue ::: ``` ## Fortgeschrittene Layouts Der `hero`-Container unterstützt spezielle Flags zur Steuerung seines strukturellen Verhaltens. | Flag | Effekt | | :--- | :--- | | `layout:split` | Teilt den Hero in einen Textbereich (links) und einen Medienbereich (rechts). Stapelt sich auf Mobilgeräten vertikal. | | `layout:slider` | Verwandelt den Hero in einen horizontalen Slider mit Scroll-Snap-Verhalten. | | `glow:true` | Fügt ein subtiles, radiales Verlaufsleuchten im Hintergrund ein. | ### Das Split-Layout (`== side`) Verwenden Sie das Trennzeichen `== side`, um zu definieren, welche Inhalte in den primären Textbereich und welche in den sekundären "Seiten"-Bereich (normalerweise ein Bild oder ein Video-Embed) fließen. ```markdown ::: hero layout:split glow:true # docmd 2.0 Isomorphe Ausführung. KI-optimiert. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 Isomorphe Ausführung. KI-optimiert. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### Das Slider-Layout (`== slide`) Erstellen Sie einen interaktiven Hero-Slider, indem Sie das Trennzeichen `== slide` zwischen verschiedenen Inhaltsknoten verwenden. ```markdown ::: hero layout:slider == slide # Isomorpher Core Die Engine rendert überall. == slide # KI-Optimierung Gebaut für das LLM-Zeitalter. ::: ``` ::: hero layout:slider == slide # Isomorpher Core Die Engine rendert überall. == slide # KI-Optimierung Gebaut für das LLM-Zeitalter. ::: ## Responsives Verhalten Der `hero`-Container ist standardmäßig voll responsiv: - Auf dem **Desktop** wird `layout:split` nebeneinander angezeigt. - Auf **Mobilgeräten** wechselt er automatisch zu einem zentrierten, vertikalen Stapel, um eine optimale Lesbarkeit zu gewährleisten. ## Best Practices 1. **Glow-Effekte**: Verwenden Sie `glow:true` sparsam auf Websites im Dark Mode für ein hochwertiges "Neon"-Gefühl. 2. **Medientypen**: Der "Seiten"-Inhalt eines Split-Layouts eignet sich perfekt für die `::: embed`-Komponente, hochwertige PNGs oder rohe `<video>`-Tags. 3. **CTA-Platzierung**: Platzieren Sie `::: button`-Elemente immer im primären "Hero Copy"-Bereich (vor dem `== side`-Trennzeichen), um sicherzustellen, dass sie das Erste sind, was Benutzer auf Mobilgeräten sehen. --- ## [Container-Übersicht](https://docs.docmd.io/de/07/content/containers/) --- title: "Container-Übersicht" description: "Erweitern Sie Standard-Markdown mit integrierten interaktiven Komponenten, die Ihre Dokumentation von statischen Seiten in funktionsreiche Anwendungen verwandeln." --- `docmd`-Container ermöglichen es Ihnen, komplexe UI-Elemente wie Buttons, Cards, ausklappbare Abschnitte und Tabs direkt in Ihre Dokumentationsquellen einzufügen, ohne HTML oder CSS schreiben zu müssen. ::: callout tip "Migration von anderen Dokumentations-Engines?" `docmd` unterstützt Syntax-Aliase von **VitePress** und **Docusaurus** direkt. Container wie `:::tip`, `:::warning`, `:::note`, `:::details` und `:::caution` funktionieren ohne Änderung. Leerzeichenlose Syntax (z.B. `:::tabs` statt `::: tabs`) wird ebenfalls für alle Container unterstützt. ::: ## Block-Syntax-Referenz Alle Container nutzen eine konsistente Block-Syntax, die eine vorhersehbare Bearbeitungserfahrung im gesamten Projekt gewährleistet. ```markdown ::: typ "Optionaler Titel für die Kopfzeile" Dies ist der primäre Inhaltsbereich. Er unterstützt **Markdown**, Bilder und tiefe Verschachtelung von Komponenten. ::: ``` | Komponente | Schlüsselwort | Primärer Anwendungsfall | | :--- | :--- | :--- | | **[Callouts](callouts.md)** | `callout` | Semantische Hervorhebungen für Tipps, Warnungen und Alarme. | | **[Cards](cards.md)** | `card` | Gerahmte strukturelle Blöcke für Feature-Grids und Layout-Steuerung. | | **[Grids](grids.md)** | `grids` | Sich automatisch anpassende, mehrspaltige Strukturgruppen. | | **[Tabs](tabs.md)** | `tabs` | Interaktive, umschaltbare Fenster für alternative Anweisungen (z.B. Betriebssysteme). | | **[Steps](steps.md)** | `steps` | Visuelle, nummerierte Zeitachsen für "How-to"-Anleitungen und Tutorials. | | **[Tags](tags.md)** | `tag` | Selbstschließende, farbige Labels für Versionen, Status oder Hervorhebungen. | | **[Buttons](buttons.md)** | `button` | Selbstschließende, prominente Call-to-Action-Navigationslinks. | | **[Collapsibles](collapsible.md)**| `collapsible`| Interaktive Akkordeon-Umschalter für FAQs und vertiefende technische Daten. | | **[Changelogs](changelogs.md)** | `changelog` | Strukturierte, zeitachsenbasierte Versionshistorie und Versionshinweise. | | **[Hero](hero.md)** | `hero` | Wirkungsvolle Landingpage-Abschnitte mit Layout- und Slider-Unterstützung. | ## Die strategische Bedeutung von Containern Container bieten mehr als nur optischen Glanz; sie liefern hochpräzise **semantische Signale** an die `docmd`-Engine und nachgeschaltete KI-Agenten: 1. **KI-Kontext-Mapping**: Das Markieren eines Blocks als `callout warning` signalisiert LLMs explizit, diese Informationen während der Denk- und Generierungsphasen zu priorisieren. 2. **Strukturelle Integrität**: Die Kombination von `cards` mit Standard-CSS ermöglicht die Erstellung anspruchsvoller Landingpages, ohne die Markdown-Umgebung zu verlassen. 3. **Wartbarkeit des Quellcodes**: Eliminiert "HTML-Aufblähung" in Ihrem Dokumentationsquellcode und hält Ihre `.md`-Dateien sauber und maschinenlesbar. ## Rekursive Komposition `docmd` unterstützt **unendliche Verschachtelungstiefe**. Sie können jeden Container in einem anderen kombinieren, um komplexe, interaktive Dokumentationsknoten rein in Markdown zu erstellen. ```markdown ::: card "Architektur-Übersicht" ::: callout info Dieses Modul nutzt eine asynchrone I/O-Pipeline. ::: ::: button "Tiefes Eintauchen in den Core" /advanced/developer-guide ::: ``` --- ## [Verschachtelte Container](https://docs.docmd.io/de/07/content/containers/nested-containers/) --- title: "Verschachtelte Container" description: "Nutzen Sie den rekursiven Parser von docmd, um Karten, Tabs und Callouts in hochwertige Seitenlayouts zu kombinieren." --- Eine der leistungsfähigsten technischen Fähigkeiten von `docmd` ist seine **rekursive Parsing-Engine**. Sie können Komponenten unendlich ineinander verschachteln, um komplexe, interaktive Dokumentationsblöcke zu erzeugen, die andernfalls tiefgreifende HTML-Kenntnisse oder benutzerdefinierte Vorlagen erfordern würden. ## Die architektonische Regel Obwohl die Verschachtelung mathematisch gesehen unendlich ist, sollten Sie sich immer an die **Regel für selbstschließende Komponenten** halten: ::: callout warning "Selbstschließende Buttons" Da die `::: button`-Komponente selbstschließend ist (einzeilig), fügen Sie niemals eine abschließende `:::`-Zeile dahinter ein. Dies würde versehentlich den **übergeordneten Container** schließen, in dem sich der Button befindet, was zu einem fehlerhaften Layout führt. ::: ## Beispiele für technische Komposition ### 1. Interaktiver Ressourcenblock Kombinieren Sie eine **Karte (Card)** für den strukturellen Rahmen, **Tabs** für umgebungsspezifische Anweisungen und **Callouts** zur Hervorhebung kritischer Informationen. ````markdown ::: card "Monorepo Schnellstart" Wählen Sie Ihren bevorzugten Initialisierungspfad: ::: tabs == tab "Automatisiert" ```bash pnpm onboard ``` ::: callout success Dieses Skript übernimmt alle Paketinstallationen und Build-Aufgaben automatisch. ::: == tab "Manuell" Holen und verknüpfen Sie die Core-Engine manuell. ::: button "Zum Entwickler-Leitfaden" /advanced/developer-guide ::: ::: ```` ### 2. Multi-Plattform-Tutorials Das Verschachteln von **Tabs** innerhalb von **Schritten (Steps)** ist ein professionelles Muster, um plattformspezifische Anweisungen innerhalb einer Standard-Tutorial-Sequenz bereitzustellen. ```markdown ::: steps 1. **Umgebung einrichten** Konfigurieren Sie Ihr lokales Betriebssystem. ::: tabs == tab "macOS" Stellen Sie sicher, dass Homebrew installiert und aktuell ist. == tab "Linux" Überprüfen Sie das Vorhandensein von `curl` und `bash`. ::: 2. **Kern-Verifizierung** Führen Sie den Versionscheck aus, um die Konnektivität zu bestätigen. ::: ``` ::: steps 1. **Umgebung einrichten** Konfigurieren Sie Ihr lokales Betriebssystem. ::: tabs == tab "macOS" Stellen Sie sicher, dass Homebrew installiert und aktuell ist. == tab "Linux" Überprüfen Sie das Vorhandensein von `curl` und `bash`. ::: 2. **Kern-Verifizierung** Führen Sie den Versionscheck aus, um die Konnektivität zu bestätigen. ::: ## Design-Einschränkungen Um sowohl die Performance als auch die mobile Responsivität zu wahren, beachten Sie die folgenden Einschränkungen: * **Rekursive Tabs**: Das Verschachteln von Tabs innerhalb anderer Tabs wird technisch unterstützt, ist jedoch ausdrücklich nicht empfohlen. Es erzeugt Navigations-"Schleifen", die auf kleineren Viewports optisch verwirrend sind. * **Sequenzieller Konflikt**: Wenn Sie nummerierte Schritte innerhalb eines Tabs benötigen, verwenden Sie eine standardmäßige geordnete Liste (`1. Schritt-Inhalt`) anstelle des `::: steps`-Containers, um Layout-Konflikte zu vermeiden. * **Lesbarkeit**: Obwohl `docmd` keine Einrückung für verschachtelte Blöcke zwingend vorschreibt, verbessert eine Einrückung von 2 oder 4 Leerzeichen die menschliche Lesbarkeit des Markdown-Quellcodes erheblich. ::: callout tip "Wissenssegmentierung für KI" Verschachtelungen bieten klare **semantische Grenzen**. Wenn ein KI-Agent den `llms-full.txt`-Stream analysiert, teilt ein in eine `card` eingebetteter `callout` dem Modell explizit mit, dass der Tipp auf das spezifische Thema dieser Karte bezogen ist. Dies verhindert Kontext-Leaks und verbessert die technische Genauigkeit in generierten Antworten. ::: --- ## [Schritte (Steps)](https://docs.docmd.io/de/07/content/containers/steps/) --- title: "Schritte (Steps)" description: "Verwandeln Sie standardmäßige geordnete Listen in visuell ansprechende Zeitachsen und Tutorials." --- Der Container `steps` wurde speziell für Anleitungen ("How-to") und technische Tutorials entwickelt. Er verwandelt eine standardmäßige geordnete Markdown-Liste in eine elegante, nummerierte vertikale Zeitachse mit automatischer Beabstandung und visueller Hervorhebung. ## Syntax Umschließen Sie jede standardmäßige geordnete Liste mit einem `::: steps`-Block. ```markdown ::: steps 1. **Projekt initialisieren** Führen Sie den Befehl `docmd init` aus, um Ihr Verzeichnis zu erstellen. 2. **Inhalte verfassen** Schreiben Sie Ihre Dokumentation in standardmäßigen Markdown-Dateien. 3. **Erstellen & Bereitstellen** Generieren Sie statische Assets mit `docmd build`. ::: ``` ## Detaillierte Implementierung Die `steps`-Komponente unterstützt reichhaltige Markdown-Inhalte innerhalb jedes Elements, einschließlich Code-Blöcken, Bildern und verschachtelten Containern. ```markdown ::: steps 1. **Produktions-Build generieren** Führen Sie den Build-Befehl aus, um eine hochoptimierte statische Website zu erstellen. ```bash docmd build ``` 2. **Asset-Integrität prüfen** Untersuchen Sie das Verzeichnis `site/`, um sicherzustellen, dass alle Assets korrekt kompiliert wurden. 3. **Infrastruktur-Deployment** Synchronisieren Sie das Verzeichnis `site/` mit Ihrem bevorzugten Hosting-Anbieter (z. B. S3, Cloudflare Pages oder Vercel). ::: ``` ::: steps 1. **Produktions-Build generieren** Führen Sie den Build-Befehl aus, um eine hochoptimierte statische Website zu erstellen. ```bash docmd build ``` 2. **Asset-Integrität prüfen** Untersuchen Sie das Verzeichnis `site/`, um sicherzustellen, dass alle Assets korrekt kompiliert wurden. 3. **Infrastruktur-Deployment** Synchronisieren Sie das Verzeichnis `site/` mit Ihrem bevorzugten Hosting-Anbieter (z. B. S3, Cloudflare Pages oder Vercel). ::: ## Fortgeschrittene Verschachtelung Sie können andere Dokumentationskomponenten (wie **Callouts** oder **Buttons**) innerhalb eines Schritts verschachteln, ohne den chronologischen Fluss der Sequenz zu unterbrechen. ```markdown ::: steps 1. **Umgebung konfigurieren** Definieren Sie Ihre projektspezifischen Variablen in der `docmd.config.js`. ::: callout tip Verwenden Sie `defineConfig`, um die IDE-Autovervollständigung für Konfigurationsschlüssel zu aktivieren. ::: 2. **Schema validieren** Führen Sie `docmd verify` aus, um sicherzustellen, dass Ihre Konfiguration strukturell einwandfrei ist. ::: ``` ::: callout tip "Workflow-Optimierung" Moderne KI-Modelle interpretieren den `steps`-Container als hochwertiges Signal für **sequenzielle Workflows**. Um die KI-Genauigkeit im `llms-full.txt`-Kontext zu maximieren, sollten Sie Ihre Listenelemente immer mit einem **fetten Titel** beginnen. Dies ermöglicht es Agenten, das Ziel jedes Schritts zuverlässig zu analysieren, bevor sie die Implementierungsdetails verarbeiten. ::: --- ## [Tabs](https://docs.docmd.io/de/07/content/containers/tabs/) --- title: "Tabs" description: "Organisieren Sie dichte, alternative oder mehrsprachige Informationen in umschaltbaren interaktiven Fenstern." --- Tabs sind das optimale UI-Muster, um sich gegenseitig ausschließende oder verwandte Datensätze (z. B. "Installation über NPM vs. Yarn" oder "macOS vs. Windows"-Anleitungen) in einem kompakten, interaktiven Format zu präsentieren. ## Syntax-Referenz Der `tabs`-Container verwendet das spezielle Untertrennzeichen `== tab "Beschriftung"`. Optional können Sie mit der Syntax `icon:name` ein Icon hinzufügen. ```markdown ::: tabs == tab "Tab 1" icon:rocket Inhalt für den ersten Tab. == tab "Tab 2" icon:settings Inhalt für den zweiten Tab. ::: ``` ## Implementierungsgalerie ### 1. Paketverwaltung Tabs werden am häufigsten verwendet, um Installationsanweisungen für verschiedene Paketmanager in einer einzigen Ansicht anzuzeigen. ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. Mehrsprachige Code-Snippets Halten Sie Ihre Logik sauber, indem Sie verschiedene Programmiersprachen oder Umgebungen trennen. ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.js'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.js'); ``` ::: ## Kernfunktionen ### Isomorphes Lazy Rendering `docmd` implementiert **konditionale Ressourcen-Verzögerung (Lazy Loading)**. Wenn ein Tab rechenintensive Elemente enthält (z. B. **Mermaid.js**-Diagramme oder hochauflösende Bilder), werden diese Assets erst initialisiert und gerendert, wenn der Benutzer diesen spezifischen Tab aktiviert. Dies gewährleistet schnelle erste Seitenladezeiten. ### Status-Persistenz Der Standard-SPA-Router verfolgt den Index des aktiven Tabs über ähnliche Dokumentationsseiten hinweg. Wenn ein Benutzer auf einer Seite "pnpm" auswählt und zu einer anderen Seite mit einer passenden Tab-Struktur navigiert, bleibt der "pnpm"-Tab automatisch aktiv. ## Technische Einschränkungen | Einschränkung | Hinweis | | :--- | :--- | | **Verschachtelungstiefe** | Um die Layout-Integrität zu bewahren, können Tabs nicht in anderen Tab-Komponenten verschachtelt werden. | | **Interaktiver Konflikt**| Konfliktträchtige Syntax: Um Steps in einem Tab zu verschachteln, verwenden Sie eine standardmäßige geordnete Liste (`1. Schritt eins`) anstelle des `::: steps`-Containers. | | **Responsives Limit** | Es wird empfohlen, die Anzahl der Tabs auf 6 pro Block zu begrenzen, um die Kompatibilität mit Mobilgeräten zu gewährleisten. | ::: callout tip "AI Context Mapping" Wenn Sie Tabs für Code-Snippets verwenden, geben Sie die Zielsprache immer direkt im Tab-Label an (z. B. `== tab "TypeScript"`). Dies ermöglicht es LLMs, den technisch relevanten Abschnitt im `llms-full.txt`-Kontextstream sofort zu identifizieren und zu extrahieren. ::: --- ## [Tags](https://docs.docmd.io/de/07/content/containers/tags/) --- title: "Tags" description: "Verwenden Sie den Tag-Container, um Versionen oder Status zu kennzeichnen oder kurze Textausschnitte nahtlos im Fließtext hervorzuheben." --- Der `tag`-Container ist eine selbstschließende Komponente, mit der kleine, pillenförmige Badges direkt in Ihren Text eingefügt werden können. Im Gegensatz zu Block-Containern erben Tags keine massiven Größen von übergeordneten Elementen wie Überschriften; sie behalten ihre kompakten, sauberen Proportionen bei, egal wo sie platziert werden. ## Grundlegende Verwendung Um einen einfachen Tag zu erstellen, geben Sie einfach den Text an, den Sie anzeigen möchten: ::: tabs == tab "Vorschau" Diese Funktion wurde in ::: tag "v0.7.4" color:blue hinzugefügt und funktioniert perfekt. == tab "Markdown-Quelle" ```markdown Diese Funktion wurde in ::: tag "v0.7.4" hinzugefügt und funktioniert perfekt. ``` ::: ## Farben anpassen Sie können das Standard-Tag-Styling überschreiben, indem Sie einen beliebigen gültigen CSS-Farbstring (z. B. `#ff0000`, `blue` oder `hsl(...)`) über das Attribut `color:` angeben. `docmd` berechnet automatisch einen schönen getönten Hintergrund mit perfekt kontrastiertem Text und Rahmen! ::: tabs == tab "Vorschau" ::: tag "Veraltet" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stabil" color:#22c55e == tab "Markdown-Quelle" ````markdown ::: tag "Veraltet" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stabil" color:#22c55e ```` ::: ## Icons hinzufügen Genau wie bei Buttons und Callouts können Sie ganz einfach ein Icon aus der `docmd`-Icon-Bibliothek über das Attribut `icon:` hinzufügen. ::: tabs == tab "Vorschau" ::: tag "Verifiziert" icon:check-circle color:#10b981 == tab "Markdown-Quelle" ````markdown ::: tag "Verifiziert" icon:check-circle color:#10b981 ```` ::: ## Tags verlinken Wenn Ihr Tag als Hyperlink fungieren soll (z. B. um einen Versions-Tag direkt mit seinen Versionshinweisen zu verknüpfen), können Sie das Attribut `link:` verwenden. Externe Links werden automatisch erkannt und in einem neuen Tab geöffnet. ::: tabs == tab "Vorschau" Sehen Sie sich die neuesten ::: tag "Versionshinweise" icon:external-link link:/release-notes/0-7-4 an. == tab "Markdown-Quelle" ````markdown Sehen Sie sich die neuesten ::: tag "Versionshinweise" icon:external-link link:/release-notes/0-7-4 an. ```` ::: ## Tags in Überschriften verwenden Da Tags echte Inline-Elemente sind, sehen sie hervorragend aus, wenn sie zur Kennzeichnung von Hauptüberschriften verwendet werden. Sie richten sich automatisch an der Grundlinie aus, ohne die massive Schriftgröße der Überschrift zu erben. ::: tabs == tab "Vorschau" # Suchfilterung ::: tag "Neu" color:#8b5cf6 == tab "Markdown-Quelle" ````bash # Suchfilterung ::: tag "Neu" color:#8b5cf6 ```` ::: --- ## [Frontmatter-Referenz](https://docs.docmd.io/de/07/content/frontmatter/) --- title: "Frontmatter-Referenz" description: "Der vollständige Leitfaden zu Metadaten und Konfiguration auf Seitenebene in docmd." --- Frontmatter ermöglicht es Ihnen, globale Einstellungen auf einer pro-Seite-Basis zu überschreiben. Es muss im YAML-Format ganz oben in Ihrer Markdown-Datei stehen. ## Kern-Metadaten | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `title` | `String` | **Erforderlich.** Legt den HTML-`<title>` und die Hauptüberschrift des Abschnitts fest. | | `description` | `String` | Legt die Meta-Beschreibung für SEO und Suchergebnisse fest. | | `keywords` | `Array` | Eine Liste von Schlüsselwörtern für den `<meta name="keywords">`-Tag. | ::: callout warning "Der Titel ist wichtig" Obwohl nicht strikt erforderlich, wird das Feld `title` dringend empfohlen. Ohne diesen greift docmd auf die erste `# H1`-Überschrift oder den Dateinamen zurück - was zu weniger idealen `<title>`-Tags und Suchergebnissen führen kann. ::: ## Sichtbarkeit & Indexierung | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `noindex` | `Boolean` | Schließt die Seite aus dem internen Suchindex aus. | | `llms` | `Boolean` | Auf `false` setzen, um diese Seite aus den KI-Kontextdateien (`llms.txt`) auszuschließen. | | `hideTitle` | `Boolean` | Blendet den Titel im fixierten Header aus (nützlich bei Verwendung einer benutzerdefinierten H1). | | `bodyClass` | `String` | Fügt dem `<body>`-Tag dieser Seite eine benutzerdefinierte CSS-Klasse hinzu. | ## Layout-Steuerung | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `layout` | `String` | Auf `full` setzen, um die volle Inhaltsbreite zu nutzen und die Inhaltsverzeichnis-Sidebar (TOC) auszublenden. | | `toc` | `Boolean` | Auf `false` setzen, um das Inhaltsverzeichnis vollständig zu deaktivieren. | | `noStyle` | `Boolean` | Deaktiviert die gesamte `docmd`-Benutzeroberfläche (Sidebar, Header, Footer) für benutzerdefinierte Seiten. | | `titleAppend` | `Boolean` | Auf `false` setzen, um zu verhindern, dass der Seitentitel an den HTML-`<title>`, OpenGraph (`og:title`) und Twitter-Metadaten-Tags angehängt wird. Standard: `true`. | ### `noStyle`-Komponentensteuerung Wenn `noStyle: true` aktiv ist, müssen Sie sich explizit für die Komponenten entscheiden, die Sie beibehalten möchten: ```yaml --- noStyle: true components: meta: true # Fügt SEO-Metadaten ein favicon: true # Fügt das Website-Favicon ein css: true # Fügt docmd-main.css ein theme: true # Fügt Theme-spezifisches Styling ein highlight: true # Fügt Syntax-Highlighting ein scripts: true # Fügt die SPA-Router-Logik ein sidebar: true # Fügt die Navigations-Sidebar ein footer: true # Fügt den Website-Footer ein --- ``` ## Plugin-Überschreibungen ### SEO (`seo`) * `image`: Benutzerdefinierte URL für das Vorschaubild in sozialen Medien für diese Seite. * `aiBots`: Auf `false` setzen, um speziell KI-Crawler von dieser Seite zu blockieren. * `canonicalUrl`: Legt einen benutzerdefinierten kanonischen Link für SEO fest. --- ## [Live-Vorschau](https://docs.docmd.io/de/07/content/live-preview/) --- title: "Live-Vorschau" description: "Integrieren Sie die docmd-Rendering-Engine in Ihre eigenen Web-Interfaces für sofortige Dokumentationsvorschauen im Browser." --- Die `docmd`-Live-Vorschau-Architektur ermöglicht es Ihnen, die produktionsreife Markdown-Rendering-Engine direkt in benutzerdefinierte Editoren, CMS-Dashboards oder webbasierte IDEs zu bringen. ### 1. Ressourcen-Integration Binden Sie die erforderlichen CSS- und JavaScript-Bundles aus Ihren Assets oder einem CDN ein: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. Isomorphe API Das globale `docmd`-Objekt bietet die `compile`-Methode für verzögerungsfreies Rendering. ```javascript const html = await docmd.compile(markdown, { siteTitle: 'Dynamische Vorschau', theme: { appearance: 'dark' } }); // In einen Iframe injizieren für Stil-Isolation document.getElementById('preview-frame').srcdoc = html; ``` ::: callout tip "KI-Feedback-Schleifen" Die Live-Architektur ist ideal für den Aufbau von **KI-Agenten-Sandboxes**. Anstatt einem Agenten Schreibzugriff auf das Dateisystem zu gewähren, können Sie dessen vorgeschlagene Dokumentationsänderungen in einen Live-Kompilierungspuffer leiten. Dies ermöglicht es Ihnen, KI-Vorschläge in einer "Ghost"-Umgebung visuell zu überprüfen, bevor Sie Änderungen in Ihr Repository übernehmen. ::: --- ## [docmd : Individuelle No-Style Page Demo](https://docs.docmd.io/de/07/content/no-style-example/) --- title: "docmd : Individuelle No-Style Page Demo" description: "Eine funktionale Demonstration der noStyle-Architekturfunktion." noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: center; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-color); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>Individuelle Seitenarchitektur</h1> <p>Demonstration der absoluten Layout-Kontrolle durch <code>noStyle: true</code>.</p> </div> <div class="demo-card"> <h2>Logisches Fundament</h2> <p> Diese Demonstration nutzt die Frontmatter-Direktive <code>noStyle: true</code>, um das globale Dokumentationslayout (Seitenleiste, Header und TOC) zu umgehen. Dies bietet eine "Zero-Friction"-Leinwand für die Erstellung von Marketing-Landingpages oder benutzerdefinierten Produkt-Dashboards. </p> <h3>Aktivierte Systemkomponenten</h3> <p>Im No-Style-Modus entscheiden Sie sich explizit für die Kernfunktionen der Dokumentations-Engine:</p> <ul> <li><strong>SEO-Meta-Engine</strong>: Strukturierte Tags und Social-Graph-Daten bleiben erhalten.</li> <li><strong>Projekt-Branding</strong>: Die globale Favicon-Injektion bleibt aktiv.</li> <li><strong>Grundlegende Typografie</strong>: Das verarbeitete <code>docmd-main.css</code> liefert das Basis-Styling.</li> <li><strong>Theme-Synchronisation</strong>: Der Status des Hell-/Dunkelmodus bleibt vollständig erhalten.</li> <li><strong>Interaktive Funktionen</strong>: Der SPA-Router und die Komponentenlogik bleiben verfügbar.</li> </ul> <h3>Technische Umsetzung</h3> <p> Das Layout für diese Seite wurde mit Standard-HTML-Wrappern und gescoptem CSS erstellt, das im Frontmatter-Feld <code>customHead</code> definiert ist. Dies stellt sicher, dass kein CSS auf den Rest der Dokumentationsseite abfärbt. </p> <a href="../content/no-style-pages.md" class="demo-button">Analyse des Implementierungs-Leitfadens →</a> </div> </div> --- ## [Seiten ohne Stil (No-Style Pages)](https://docs.docmd.io/de/07/content/no-style-pages/) --- title: "Seiten ohne Stil (No-Style Pages)" description: "Erstellen Sie benutzerdefinierte Landingpages und einzigartige Layouts, indem Sie das Standard-Theme von docmd deaktivieren." --- `docmd` ermöglicht es Ihnen, das Standard-Dokumentationslayout (Seitenleiste, Header und Footer) auf einer pro-Seite-Basis zu umgehen. Dies ist ideal für die Erstellung von Produkt-Landingpages, benutzerdefinierten Dashboards oder Marketing-Splash-Screens, während der Zugriff auf die Komponenten der Dokumentations-Engine erhalten bleibt. ## Aktivierung des No-Style-Modus Um die globale Benutzeroberfläche zu deaktivieren, fügen Sie `noStyle: true` zum Frontmatter der Seite hinzu. ```yaml --- title: "Produkt-Showcase" noStyle: true components: meta: true # SEO- und OpenGraph-Tags beibehalten favicon: true # Website-Favicon beibehalten css: true # docmd-main.css für Typografie einfügen --- <!-- Reines HTML oder spezielles Markdown folgt hier --> <div class="hero"> <h1>Dokumentation der nächsten Generation</h1> <p>Zero-config. Isomorph. KI-bereit.</p> </div> ::: callout info "Unterstützung für unbegrenzte Verschachtelung" Auch bei `noStyle: true` werden alle Standard-`docmd`-Container wie `::: card`, `::: tabs` und `::: hero` vollständig unterstützt und können in jeder Tiefe verschachtelt werden. ::: ``` ## Komponenten-Auswahl (Opt-In) Wenn `noStyle` aktiv ist, beginnen Sie mit einer leeren Leinwand. Aktivieren Sie die Kernkomponenten des Systems gezielt nach Bedarf: | Komponente | Beschreibung | | :--- | :--- | | `meta` | Fügt `<title>`, SEO-Meta-Tags und strukturierte OpenGraph-Daten ein. | | `favicon` | Fügt das projektweite Favicon ein. | | `css` | Fügt `docmd-main.css` ein. Dringend empfohlen für grundlegendes Raster und Typografie. | | `menubar` | Fügt die obere Menüleiste der Website ein. | | `theme` | Fügt die CSS-Variablen und Design-Überschreibungen des aktiven Themes ein. | | `scripts` | Fügt die interaktive Komponentenlogik ein (erfordert `mainScripts: true`). | | `spa` | Aktiviert den Single-Page-Application-Router (erfordert `scripts: true`). | ## Komponierbare Landingpages Die Hauptstärke von `noStyle` liegt darin, dass Sie die gesamte Suite der `docmd`-Komponenten als hochwertige „Widgets“ auf einer leeren Leinwand verwenden können. Sie sind nicht auf reines HTML beschränkt; Sie können komplexe, strukturelle Designs rein in Markdown erstellen. ### Erstellung eines modernen Einstiegspunkts ```yaml --- title: "Willkommen" noStyle: true components: meta: true css: true menubar: true # Verwenden Sie die obere Navigation der Website scripts: true # Interaktive Komponenten aktivieren mainScripts: true --- ::: hero layout:split glow:true # Dokumentation, die begeistert. Die Zero-Config-Engine für moderne Entwicklerteams. ::: button "Erste Schritte" ../getting-started/quick-start.md color:blue ::: button "GitHub" github:docmd-io/docmd color:gray == side ::: embed [https://www.youtube.com/watch?v=dQw4w9WgXcQ] ::: ::: ::: grids ::: card "Zero Configuration" Schreiben Sie einfach Markdown. Keine komplexe React-Logik oder Build-Skripte. ::: ::: card "KI-optimiert" Strukturbewusstes Parsing für die Ära der LLMs. ::: ::: card "Schnell ohne Framework-Last" Statische Generierung mit isomorpher SPA-Navigation. ::: ::: ``` ::: callout tip "KI-generierte Layouts" Da `noStyle`-Seiten sowohl reines HTML als auch `docmd`-Container unterstützen, eignen sie sich perfekt für **KI-gesteuertes UI-Design**. Sie können einer KI den Befehl geben: *"Entwirf eine moderne Hero-Sektion mit Tailwind-ähnlichen Utility-Klassen und docmd-Buttons, gehüllt in einen noStyle: true-Container."* Die KI kann das Design innerhalb Ihrer statischen Website-Pipeline ohne zusätzliche Konfiguration iterieren. ::: ## String-Ersetzung (i18n für noStyle) Wenn Ihre Website für [i18n konfiguriert](../configuration/localisation/index.md) ist, erhalten gewöhnliche Dokumentationsseiten automatisch serverseitige Übersetzungen - jede Sprache hat ihre eigenen Markdown-Dateien in separaten Verzeichnissen. Aber noStyle-Seiten verwenden benutzerdefiniertes HTML statt Markdown, weshalb dieser Ansatz dort nicht greift. Stattdessen bietet docmd eine **String-Ersetzung** an - die Übersetzung Ihres HTML über `data-i18n`-Attribute und JSON-Übersetzungsdateien. ::: callout info "Warum dies nur für noStyle-Seiten funktioniert" Die String-Ersetzung findet Elemente mit `data-i18n`-Attributen im gerenderten HTML und tauscht deren Textinhalt aus. Standard-Markdown-Inhalte werden in einfache `<p>`, `<h2>`, `<li>` Tags gerendert - dort gibt es keine `data-i18n`-Attribute, die der Ersetzer findten könnte. Für die Übersetzung von in Markdown verfassten Dokumentationen verwenden Sie den [Verzeichnis-Modus](../configuration/localisation/translated-content.md) - separate Markdown-Dateien pro Sprache. ::: ### Wie es funktioniert Es gibt zwei Modi für die String-Ersetzung: - **Serverseitig (empfohlen)**: Mit [`stringMode: true`](../configuration/localisation/index.md#string-mode-nostyle-pages-only) in Ihrer i18n-Konfiguration löst docmd `data-i18n`-Attribute **zur Build-Zeit** auf und generiert vollständig übersetztes HTML in den Verzeichnissen `/{locale}/`. Jede Sprache erhält ihre eigene URL - vollständig indexierbar für Suchmaschinen. - **Clientseitig**: Das Skript `docmd-i18n-strings.js` lädt Übersetzungen zur Laufzeit via XHR. Dies wird auf noStyle-Seiten automatisch eingefügt, wenn i18n konfiguriert ist. Nützlich für den Austausch an Ort und Stelle ohne Neuladen der Seite (z. B. SPAs, Dashboards). Beide Modi verwenden dieselbe Syntax für `data-i18n`-Attribute und dasselbe JSON-Dateiformat. 1. Platzieren Sie JSON-Übersetzungsdateien in `assets/i18n/` - eine pro Sprache: ``` assets/ i18n/ en.json hi.json zh.json ``` 2. Jede JSON-Datei ist eine flache Schlüssel-Wert-Zuordnung: ```json { "hero.title": "Markdown → Produktions-Docs", "hero.subtitle": "Die Zero-Config-Dokumentations-Engine.", "nav.docs": "Dokumentation", "nav.editor": "Live-Editor", "cta.getStarted": "Erste Schritte", "cta.install": "npm i @docmd/core" } ``` 3. Verwenden Sie `data-i18n`-Attribute in Ihren HTML-Elementen: ```html <h1 data-i18n="hero.title">Markdown → Produktions-Docs</h1> <p data-i18n="hero.subtitle">Die Zero-Config-Dokumentations-Engine.</p> <a data-i18n="nav.docs" href="/docs">Dokumentation</a> ``` Der Text in der Standardsprache wird direkt in das HTML geschrieben (fungiert als Fallback). Wenn eine andere Sprache aktiv ist, lädt das Skript das entsprechende JSON und ersetzt den Text. ### Attribut-Übersetzung Um Elementattribute wie `placeholder`, `title` oder `aria-label` zu übersetzen, verwenden Sie `data-i18n-{attr}`: ```html <input data-i18n-placeholder="search.placeholder" placeholder="Suche..."> <button data-i18n-aria-label="nav.menuLabel" aria-label="Menü öffnen">☰</button> <a data-i18n-title="nav.tooltip" title="Zu den Docs">Docs</a> ``` ### HTML-Inhalt Für Schlüssel, die HTML-Markup enthalten, verwenden Sie `data-i18n-html` anstelle von `data-i18n`: ```html <p data-i18n-html="hero.desc">Statisches HTML für SEO. <br>SPA für Geschwindigkeit.</p> ``` ### Sprachwechsel Das Modul für i18n-Strings stellt eine globale API unter `window.DOCMD_I18N_STRINGS` bereit: ```js // Zu Hindi wechseln DOCMD_I18N_STRINGS.switchLocale('hi'); // Aktuelle Sprache abrufen console.log(DOCMD_I18N_STRINGS.locale); // 'en' // Alle konfigurierten Sprachen abrufen console.log(DOCMD_I18N_STRINGS.locales); // [{ id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }] ``` Mit dieser API können Sie einen benutzerdefinierten Sprachumschalter erstellen: ```html <select onchange="DOCMD_I18N_STRINGS.switchLocale(this.value)"> <option value="en">English</option> <option value="hi">हिन्दी</option> </select> ``` ### Ereignisse (Events) Hören Sie auf das Ereignis `docmd:i18n-applied`, um benutzerdefinierte Logik auszuführen, nachdem die Strings angewendet wurden: ```js document.addEventListener('docmd:i18n-applied', function(e) { console.log('Sprache:', e.detail.locale); console.log('Strings:', e.detail.strings); }); ``` ::: callout info "Automatische Erkennung" Das Skript erkennt die aktive Sprache anhand des URL-Pfad-Präfixes (z. B. `/hi/` → Hindi). Für die Standardsprache (gerendert unter `/`) prüft es den `localStorage` auf eine zuvor gespeicherte Präferenz. Die Funktion `switchLocale()` übernimmt die URL-Navigation automatisch. ::: ### In-Place-Modus (An Ort und Stelle) Für One-Page-Websites (wie Landingpages) möchten Sie beim Sprachwechsel nicht zu einer anderen URL navigieren. Setzen Sie `inPlace: true` in Ihrer i18n-Konfiguration, um Strings ohne URL-Weiterleitung auszutauschen: ```js // docmd.config.js i18n: { defaultLocale: "en", locales: [ { id: "en", label: "English" }, { id: "zh", label: "中文" } ], inPlace: true } ``` Mit `inPlace: true` lädt der Aufruf von `switchLocale()` das JSON für die neue Sprache neu und ersetzt alle `data-i18n`-Strings auf der aktuellen Seite - es findet keine Navigation statt. --- ## [Fortgeschrittene Markdown-Syntax](https://docs.docmd.io/de/07/content/syntax/advanced/) --- title: "Fortgeschrittene Markdown-Syntax" description: "Nutzen Sie den erweiterten Funktionsumfang von docmd: Benutzerdefinierte Attribute, GFM-Erweiterungen und semantische Definitionen." --- Über das Standard-Markdown hinaus unterstützt `docmd` mehrere hochwertige Erweiterungen, die von GitHub Flavored Markdown (GFM) und Plugins für benutzerdefinierte Attribute abgeleitet sind. Diese Werkzeuge bieten Ihnen die volle Kontrolle über die Struktur und das Styling Ihres Dokuments. ## GFM-Erweiterungen ### Aufgabenlisten (Task Lists) Erstellen Sie interaktive oder schreibgeschützte Checklisten für das Roadmap-Tracking. ```markdown - [x] Engine-Optimierung abgeschlossen - [ ] Plugin-API-Finalisierung ``` - [x] Engine-Optimierung abgeschlossen - [ ] Plugin-API-Finalisierung ### Automatische Link-Auflösung Standard-URLs und E-Mail-Adressen werden automatisch erkannt und verlinkt, ohne dass zusätzliches Markup erforderlich ist: `https://docmd.io` ### Shortcode-Emojis `docmd` unterstützt Standard-Shortcodes, um Ihrer Dokumentation eine visuelle Note zu verleihen. > Wir :heart: performante Dokumentationen! :rocket: :smile: ## Benutzerdefinierte Element-Attribute Weisen Sie Überschriften, Bildern und Links mit der Syntax in geschweiften Klammern `{}` eindeutige IDs und CSS-Klassen zu. Dies ist die primäre Methode, um [Benutzerdefinierte CSS-Styles](../../theming/custom-css-js.md) anzuwenden. ### Eindeutige semantische IDs Nützlich für Deep-Links direkt zu technischen Unterabschnitten. ```markdown ## Performance-Benchmarks {#benchmarks-2026} ``` ### Funktionale CSS-Klassen Wenden Sie Styling-Utilities auf spezifische Elemente an. ```markdown ## Zentrierter Abschnitt {.text-center .text-blue} ``` ### Aktions-Schaltflächen (Buttons) Verwandeln Sie jeden Standard-Markdown-Link in eine gestaltete Call-to-Action-Schaltfläche. ```markdown [Neuestes Release herunterladen](#download){.docmd-button} ``` ## Zitate & Definitionen ### Fußnoten-Referenzen Fügen Sie Zitate oder technische Vertiefungen[^1] hinzu, die automatisch gesammelt und am Ende der Seite gerendert werden. ```markdown Architekturentscheidungen sind im RFC dokumentiert[^1]. [^1]: RFC-42: Isomorphe Rendering-Pipeline. ``` ### Definitionslisten Perfekt für API-Parameterbeschreibungen und Glossare. ```markdown PropName : Der eindeutige Bezeichner für den Konfigurationsschlüssel. ``` PropName : Der eindeutige Bezeichner für den Konfigurationsschlüssel. ### Technische Abkürzungen Definieren Sie Abkürzungen global innerhalb einer Seite. Das Bewegen der Maus über den Begriff offenbart seine vollständige Definition. ```markdown *[SPA]: Single Page Application Der docmd-Router ermöglicht ein nahtloses SPA-Erlebnis. ``` *[SPA]: Single Page Application Der docmd-Router ermöglicht ein nahtloses SPA-Erlebnis. ::: callout tip "Kontextuelle Präzision für KI" Die Verwendung von **Definitionen** und **Abkürzungen** liefert KI-Agenten hochwertige technische Signale. Wenn eine KI Ihren `llms-full.txt`-Kontext verarbeitet, verhindern diese expliziten Definitionen lexikalische Doppeldeutigkeiten und stellen sicher, dass das Modell logisch korrekte Erklärungen für die spezifische Terminologie Ihres Projekts generiert. ::: --- ## [Code-Blöcke](https://docs.docmd.io/de/07/content/syntax/code/) --- title: "Code-Blöcke" description: "Dokumentieren Sie technische Implementierungen mit hochwertiger Syntax-Hervorhebung und interaktiven Kopierschaltflächen." --- `docmd` nutzt die extrem schnelle `lite-hl`-Engine, um eine automatische, kontextsensitive Syntax-Hervorhebung für hunderte von Programmiersprachen und Konfigurationsformaten bereitzustellen. ## Syntax-Hervorhebung Verfassen Sie Ihre technischen Beispiele mit standardmäßigen Markdown-Code-Zäunen (Fenced Code Blocks). Geben Sie immer die Sprachkennung an, um sicherzustellen, dass die Highlighting-Engine die korrekten lexikalischen Regeln anwendet. ````markdown ```javascript function initialize() { console.log("docmd engine active."); } ``` ```` **Gerendertes Ergebnis:** ```javascript function initialize() { console.log("docmd engine active."); } ``` ::: callout tip "Portabilität mit einem Klick" Wenn `copyCode: true` in Ihrer Konfiguration aktiviert ist (Standard), erscheint automatisch eine dezente Kopierschaltfläche in der oberen rechten Ecke jedes Code-Blocks beim Darüberfahren mit der Maus. So können Benutzer Ausschnitte sofort in ihre IDE übertragen. ::: ## Strategie für KI-Kontext Beachten Sie beim Dokumentieren von Code für die Nutzung durch LLMs und KI-Agenten diese technischen Best Practices: 1. **Strikte Sprachkennzeichnung**: Die explizite Kennzeichnung von Blöcken als `typescript`, `bash` oder `json` stellt sicher, dass der KI-Parser die Grammatik des Blocks innerhalb des `llms-full.txt`-Streams korrekt interpretiert. 2. **Eingebettete Intention**: Verwenden Sie Inline-Kommentare innerhalb Ihrer Code-Blöcke, um das *Warum* hinter komplexer Logik zu erklären. Dies liefert der KI kritischen Kontext für die Argumentation, der einfachem Text außerhalb des Blocks fehlen könnte. ## Referenz der Sprachunterstützung `docmd` bietet standardmäßige Unterstützung für die gängigsten technischen Ökosysteme, darunter: * **Logik**: `javascript`, `typescript`, `python`, `rust`, `go`, `ruby`, `csharp`. * **Web**: `html`, `css`, `markdown`. * **Daten & Shell**: `json`, `yaml`, `bash`, `powershell`, `dockerfile`. * **Dokumentation**: `mermaid`, `changelog`. --- ## [Bilder & visuelle Medien](https://docs.docmd.io/de/07/content/syntax/images/) --- title: "Bilder & visuelle Medien" description: "Meistern Sie das Medienmanagement: Responsive Bilder, Styling-Attribute und automatische Lightbox-Effekte." --- `docmd` nutzt die Standard-Markdown-Syntax für die Medienintegration. Wir empfehlen, Ihre Medien-Assets im Verzeichnis `assets/images/` innerhalb Ihres Projekt-Quellordners zu zentralisieren. ```markdown ![Technisches Diagramm](/assets/images/architecture.png "Optionaler Tooltip-Titel") ``` ## Referenz für technisches Styling Weisen Sie Ihren Bildern spezielle CSS-Klassen und Attribute direkt mit der Attributsyntax `{ .klasse }` zu. ### Dynamische Größenanpassung ```markdown ![Kleines Format](/assets/icon.png){ .size-small } ![Standardansicht](/assets/preview.png){ .size-medium } ![Großes Format](/assets/banner.png){ .size-large } ``` ### Ausrichtung & Layout ```markdown ![Zentrierter Fokus](/assets/img.png){ .align-center } ![Rechtsfließend](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![Beispiel für fortgeschrittenes Styling](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-center} ## Strukturierte Medienelemente ### Bildunterschriften (Figure Captions) Für präzise, barrierefreie Bildunterschriften verwenden Sie standardmäßige HTML5 `<figure>`-Elemente. ```html <figure> <img src="/assets/diagram.png" alt="Cloud-Infrastruktur-Diagramm"> <figcaption>Abbildung 1.1: Architektur der Kernsystem-Infrastruktur.</figcaption> </figure> ``` ### Bildergalerien Organisieren Sie mehrere Assets in einem responsiven, ausgewogenen Raster mit der Klasse `image-gallery`. ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="Benutzer-Dashboard-Ansicht"> <figcaption>Live-Leistungsmonitor</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="Konfigurationspanel-Ansicht"> <figcaption>Globale Projekteinstellungen</figcaption> </figure> </div> ``` ## Interaktiver Lightbox-Zoom Wenn die Komponente `mainScripts` aktiviert ist (Standard), wendet `docmd` automatisch einen Vollbild-Zoomeffekt auf jedes Bild an, das in einer Galerie enthalten ist oder mit der Klasse `.lightbox` markiert wurde. ```markdown ![Detaillierte Texturanalyse](/assets/sample.png){ .lightbox } ``` ::: callout tip "KI-Kontext & Barrierefreiheit" Geben Sie immer umfassende **Alt-Texte** für visuelle Medien an. Obwohl fortgeschrittene KI-Modelle über Sehfähigkeiten verfügen, liefert beschreibender Text innerhalb der Markdown-Quelle ein direktes, hochwertiges Signal für die Argumentationsebene des Modells - dies verbessert die Architekturanalyse und das Verständnis von Funktionen im `llms-full.txt`-Stream. ::: --- ## [Markdown-Syntax Grundlagen](https://docs.docmd.io/de/07/content/syntax/) --- title: "Markdown-Syntax Grundlagen" description: "Meistern Sie die grundlegenden Formatierungsregeln von docmd: Überschriften, typografische Stile und technische Blöcke." --- `docmd` hält sich an die Standard-Spezifikationen von **GitHub Flavored Markdown (GFM)**. Dieser Leitfaden legt die grundlegenden Standards für das Verfassen von Kerninhalten auf Ihrer Dokumentationsseite fest. ## Typografisches Styling | Attribut | Markdown-Syntax | Visuelles Ergebnis | | :--- | :--- | :--- | | **Hervorhebung** | `**Text**` | **Fette Begriffe** | | **Kursiv** | `*Text*` | *Stilisierte Variablen* | | **Durchgestrichen** | `~~Text~~` | ~~Veraltete Logik~~ | | **Inlined Code** | `` `code` `` | `engine.initialize()` | ## Strukturelle Elemente ### Semantische Überschriftenhierarchie ```markdown # Ebene 1 (Automatisch via Frontmatter) ## Ebene 2 (Hauptabschnitt) ### Ebene 3 (Detailfunktion) ``` ::: callout tip "Logische Integrität für KI" Fortschrittliche KI-Modelle und interne Suchmechanismen verlassen sich auf eine strikte Überschriftenhierarchie, um ein genaues mentales Modell Ihres Projekts aufzubauen. Indem Sie das „Überspringen von Überschriften“ vermeiden (z. B. den Sprung von H2 direkt zu H4), stellen Sie sicher, dass der `llms-full.txt`-Kontextstrom chronologisch und logisch fundiert bleibt. ::: ### Navigation & Referenz Verwenden Sie die Standard-Link-Syntax sowohl für interne Dokumentationsknoten als auch für globale Ressourcen. ```markdown [Globale Ressource](https://docmd.io) [Internes Modul](../api/node-api.md) ``` ### Aufzählung & Listen * **Ungeordnete Segmente**: Verwenden Sie `*` oder `-` für scanbare Aufzählungspunkte. * **Sequenzielle Logik**: Verwenden Sie `1.`, `2.` usw. für geordnete Anweisungen. (Für Tutorials sollten Sie den wirkungsvollen **[Schritte-Container (Steps)](../containers/steps)** in Betracht ziehen). ## Technische Blockelemente ### Blockquotes (Zitate) Die Standard-`>`-Syntax ist ideal zum Hervorheben von Zitaten oder Hintergrundkontext. > Die docmd-Engine definiert die Grenzen zwischen der Generierung statischer Websites und der Bereitstellung dynamischer Anwendungen neu. ### Datenschemata (Tabellen) | Attribut | Datentyp | Standard | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## Unterstützung für eingebettetes HTML Da `docmd` so konzipiert ist, dass das Parsen von Roh-HTML aktiviert ist, können Sie komplexe Layouts oder einzigartige Formatierungen für spezielle UI-Anforderungen direkt in Ihre Markdown-Dateien einfügen. ```html <div style="padding: 2rem; border: 1px solid var(--border-color); border-radius: 12px; text-align: center;"> Maßgeschneiderte UI-Elemente finden hier ihren Platz. </div> ``` --- ## [Verlinkung & Referenzierung](https://docs.docmd.io/de/07/content/syntax/linking/) --- title: "Verlinkung & Referenzierung" description: "Meistern Sie interne Querverweise, externe Ressourcen und zuverlässige Asset-Referenzierung mit der automatischen URL-Normalisierung von docmd." --- `docmd` bietet ein robustes, Dateisystem-bewusstes Verlinkungssystem. Schreiben Sie Links zu Ihren Quell-`.md`-Dateien ganz natürlich - in jedem Format, das Sie bevorzugen - und die Engine normalisiert diese automatisch in saubere, SEO-optimierte URLs für die Produktion. ::: callout info "Natürlich schreiben, perfekt ausliefern" Sie müssen keine speziellen Verlinkungskonventionen befolgen. Egal, ob Sie `overview.md`, `overview/` oder nur `overview` schreiben, die Build-Engine erzeugt dieselbe saubere URL mit abschließendem Schrägstrich. Jeder interne Link wird zur Build-Zeit automatisch normalisiert, sodass Sie sich auf den Inhalt konzentrieren können, nicht auf die URL-Formatierung. ::: ## Wie die URL-Normalisierung funktioniert Während des Build-Prozesses wendet die Engine eine konsistente Reihe von Regeln auf jeden internen Link an - egal ob in Markdown-Texten, Button-Containern, Tags oder der Navigationskonfiguration: | Was Sie schreiben | Was gerendert wird | Warum | | :--- | :--- | :--- | | `overview.md` | `overview/` | `.md`-Erweiterung entfernt, abschließender `/` hinzugefügt | | `overview` | `overview/` | Abschließender `/` wird automatisch hinzugefügt | | `overview/` | `overview/` | Bereits korrekt - keine Änderung | | `api/commands.md` | `api/commands/` | Link in Unterverzeichnis normalisiert | | `localisation/index.md` | `localisation/` | `index` entfernt - der Ordner ist die kanonische URL | | `../index.md` | `../` | Parent-Verzeichnis-Index sauber aufgelöst | | `overview.md#settings` | `overview/#settings` | Hash-Fragment bleibt durch Normalisierung erhalten | | `./guide.md` | `./guide/` | Relatives Präfix bleibt erhalten | | `https://example.com` | `https://example.com` | Externe Links bleiben unberührt | ::: callout tip "SEO Best Practice" Alle internen Seiten werden als URLs im Verzeichnisstil bereitgestellt, die mit einem abschließenden Schrägstrich enden (z. B. `/configuration/overview/`). Dies ist der Industriestandard für statische Websites, verhindert 301-Weiterleitungsketten und gewährleistet konsistente kanonische URLs für die Indizierung durch Suchmaschinen. ::: ## Interne Link-Auflösung Verlinken Sie auf andere Seiten in Ihrer Dokumentation über relative Pfade zu den Quell-`.md`-Dateien. Die Engine löst diese unabhängig von der Verzeichnistiefe korrekt auf. | Zielstrategie | Markdown-Syntax | | :--- | :--- | | **Geschwister-Seite** | `[Systemübersicht](overview.md)` | | **Unterverzeichnis** | `[API-Referenz](api/node-api.md)` | | **Unterverzeichnis-Index**| `[Lokalisierung](localisation/index.md)` | | **Eltern-Verzeichnis** | `[Zurück zur Startseite](../index.md)` | ## Abschnitts-Anker (Deep Linking) Navigieren Sie direkt zu bestimmten Überschriften mit Standard-URL-Hash-Fragmenten. * **Anker auf derselben Seite**: `[Zum Roadmap springen](#project-roadmap)` * **Anker auf anderer Seite**: `[CLI-Flags prüfen](../cli-commands.md#available-flags)` Hash-Fragmente bleiben während des Normalisierungsprozesses erhalten. Der obige Link wird in der Produktion als `../cli-commands/#available-flags` gerendert. ## Links in einem neuen Tab öffnen Verwenden Sie das Präfix `external:` bei jedem Link, um das Öffnen in einem neuen Tab zu erzwingen. Dies funktioniert universell - in Standard-Markdown-Links, Button-Containern, Tags und überall dort, wo Sie eine URL schreiben können. ```markdown <!-- Öffnen in neuem Tab erzwingen --> [In neuem Tab öffnen](external:./configuration/overview.md) <!-- Externer Link zu GitHub --> [GitHub](external:https://github.com/docmd-io/docmd) ``` Standardmäßig werden alle Links (einschließlich HTTP/HTTPS) im selben Fenster geöffnet. Verwenden Sie das Präfix `external:` nur, wenn Sie einen neuen Tab wünschen. Das Präfix `external:` wird aus der gerenderten URL **entfernt** - es ist ein reines Signal für die Build-Zeit. ## Verlinkung zu Rohdateien (Raw Files) Standardmäßig entfernt die Engine `.md`-Erweiterungen und normalisiert Pfade. Wenn Sie tatsächlich auf eine rohe `.md`-Datei verlinken müssen (zum Beispiel eine herunterladbare Quelldatei), verwenden Sie das Präfix `raw:`: ```markdown [Quellcode anzeigen](raw:docs/readme.md) ``` Das Präfix `raw:` umgeht die gesamte Normalisierung - die Erweiterung und der Pfad bleiben exakt so erhalten, wie sie geschrieben wurden. Wie bei `external:` wird das Präfix selbst aus der gerenderten URL entfernt. ## Button-Container Der `::: button`-Container unterstützt dieselben Verlinkungskonventionen wie Standard-Markdown-Links - einschließlich der Präfixe `external:` und `raw:`: ```markdown ::: button "Erste Schritte" ./getting-started/quick-start.md icon:rocket ::: button "Auf GitHub anzeigen" https://github.com/docmd-io/docmd icon:github ::: button "Quelle herunterladen" raw:docs/readme.md icon:download ``` ## Tag-Links Tags mit `link:`-Werten profitieren ebenfalls vom einheitlichen Normalisierer: ```markdown ::: tag "v0.7.6" link:release-notes/0-7-6.md icon:tag color:#22c55e ::: tag "GitHub" link:https://github.com/docmd-io/docmd icon:github ::: tag "Extern öffnen" link:external:./configuration/overview.md icon:external-link ``` ## Navigationskonfiguration Pfade, die in `navigation.json` und `docmd.config.js` definiert sind, werden ebenfalls zur Build-Zeit normalisiert. Sie können sie in jedem Format schreiben: ```json "navigation.json" [ { "title": "Overview", "path": "configuration/overview" }, { "title": "Overview", "path": "configuration/overview.md" }, { "title": "Overview", "path": "configuration/overview/" } ] ``` Alle drei obigen Einträge erzeugen dieselbe kanonische URL: `/configuration/overview/`. Für Navigationselemente, die in einem neuen Tab geöffnet werden sollen, verwenden Sie das Flag `external`: ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "Index-Seiten in der Navigation" Wenn Sie auf die Index-Seite eines Verzeichnisses verlinken, verwenden Sie den Ordnerpfad, anstatt explizit auf `index.md` zu verweisen. Beides funktioniert identisch, aber der Ordnerpfad ist sauberer: ```markdown <!-- Bevorzugt --> [Lokalisierung](localisation/) <!-- Funktioniert auch (auto-normalisiert) --> [Lokalisierung](localisation/index.md) ``` ::: ## Protokolle & Externe Ressourcen Die Engine respektiert Standard-Browserprotokolle für externe Ressourcen. Diese Links werden niemals geändert. * **Globales HTTPS**: `[docmd Homepage](https://docmd.io)` - öffnet im selben Tab (Präfix `external:` für neuen Tab verwenden) * **Mail-Protokoll**: `[Support-Kanal](mailto:help@docmd.io)` - wird nicht in einem neuen Tab geöffnet * **Asset-Protokoll**: `[CLI-Binary herunterladen](/assets/bin/docmd-mac.zip)` - wird nicht normalisiert ## Referenzierung statischer Assets Um Downloads bereitzustellen oder auf rohe Quelldateien zu verweisen, platzieren Sie diese im Verzeichnis `assets/` Ihres Projekts. Der `docmd`-Builder stellt sicher, dass diese Dateien ohne Pfadänderungen in das Produktions-Root verschoben werden. ```markdown [Dokumentations-PDF herunterladen](/assets/pdf/handbook.pdf) [Globale Konfiguration anzeigen](/assets/config/docmd.config.js) ``` ::: callout tip "Semantische Verknüpfung für KI" Verwenden Sie bei der Querverlinkung technischer Module vorrangig **beschreibende Anker** (z. B. `[PWA-Caching optimieren](../plugins/pwa.md)`) anstelle von generischem Text (z. B. `[Mehr lesen](../plugins/pwa.md)`). Detaillierte Link-Labels bieten KI-Agenten eine hochpräzise Karte der semantischen Beziehungen zwischen verschiedenen Dokumentationsknoten im `llms-full.txt`-Kontext. ::: --- ## [Mitwirken (Contributing)](https://docs.docmd.io/de/07/contributing/) --- title: "Mitwirken (Contributing)" description: "Richtlinien und Setup-Anweisungen für die Mitwirkung an docmd." --- Vielen Dank für Ihr Interesse an der Mitwirkung bei `docmd`. Wir freuen uns über Fehlerbehebungen, Verbesserungen der Dokumentation, neue Funktionen und Designvorschläge. ## Entwicklungsumgebung `docmd` ist ein Monorepo, das mit [pnpm](https://pnpm.io/) verwaltet wird. ### Voraussetzungen - **Node.js**: v22.x oder neuer (LTS empfohlen) - **pnpm**: v10.x oder neuer ### Projekt-Setup Klonen Sie das Repository und führen Sie das initiale Setup aus, um Abhängigkeiten zu installieren und das Monorepo zu bauen: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` Um den lokalen `docmd`-Befehl global zu verlinken (zum Testen in anderen Projekten): ```bash pnpm verify --link ``` ### Lokale Entwicklung Wir bieten einen Proxy-Befehl an, um beliebige `docmd`-Befehle in unserem internen `_playground`-Verzeichnis auszuführen: ```bash pnpm docmd dev # Startet den Playground-Dev-Server (auch: pnpm dev) pnpm docmd build # Baut die Playground-Dokumentation ``` Um interne Quelldateien (Engine, Templates, Plugins) mit Hot-Reload zu beobachten, setzen Sie die Umgebungsvariable `DOCMD_DEV`: ```bash DOCMD_DEV=true pnpm dev ``` ## Qualitätsstandards ### Linting Stellen Sie sicher, dass Ihr Code unserer ESLint-Konfiguration entspricht: ```bash pnpm lint --fix ``` ### Verifizierung Bevor Sie einen Pull Request einreichen, **MÜSSEN** Sie sicherstellen, dass das gesamte Monorepo unsere intensive Verifizierungs-Pipeline passiert: ```bash pnpm prep ``` *(Dies führt `pnpm reset`, Installation, Lint-Checks, E2E-Tests und einen Release-Dry-Run aus.)* ## GitHub-Workflow 1. **Fork und Branch**: Erstellen Sie einen Feature-Branch vom aktuellen `main`. 2. **Verifizierung**: Stellen Sie sicher, dass `pnpm prep` mit `🛡️ docmd is ready for production!` abschließt. 3. **Pull Request**: Eröffnen Sie einen PR mit einer klaren Beschreibung. ### Commit-Richtlinien Wir verwenden [Conventional Commits](https://www.conventionalcommits.org/): - `feat:` (Neue Funktionen) - `fix:` (Fehlerbehebungen) - `docs:` (Dokumentationsänderungen) - `refactor:` (Interne Refaktorierungen) --- ## [Caddy](https://docs.docmd.io/de/07/deployment/caddy/) --- title: "Caddy" description: "docmd mit einem produktionsreifen Caddyfile bereitstellen." --- [Caddy](https://caddyserver.com/) ist ein moderner Webserver, der HTTPS-Bereitstellung und Zertifikatserneuerungen automatisch verwaltet. ## Caddyfile generieren ```bash docmd deploy --caddy ``` Dies generiert ein `Caddyfile`, das auf Ihr Projekt zugeschnitten ist: - **Site-Adresse** wird auf den Hostnamen aus Ihrer `url`-Konfiguration gesetzt - Caddy stellt automatisch ein SSL-Zertifikat bereit. Fallback auf `:80`, wenn keine URL konfiguriert ist. - **Root-Verzeichnis** nutzt Ihr konfiguriertes `out`-Verzeichnis (nicht hartcodiert) - **SPA-Fallback** wird nur einbezogen, wenn `layout.spa` in Ihrer Konfiguration `true` ist Wenn Sie eine echte Domain als Site-Adresse verwenden (z.B. `docs.example.com` anstatt `:80`), stellt Caddy automatisch ein kostenloses SSL-Zertifikat über Let's Encrypt bereit - keinerlei HTTPS-Konfiguration nötig. ## Bereitstellungsschritte 1. Bauen Sie Ihre Website: `docmd build` 2. Übertragen Sie Ihren Ausgabe-Ordner und das generierte `Caddyfile` auf Ihren Server. 3. Führen Sie `caddy start` oder `caddy run` im Verzeichnis mit Ihrem Caddyfile aus. ### Neu generieren Site-URL oder Ausgabeverzeichnis geändert? Führen Sie `docmd deploy --caddy` erneut aus - das Caddyfile wird neu generiert, um Ihre aktuelle `docmd.config.js` widerzuspiegeln. --- ## [CI/CD-Pipelines](https://docs.docmd.io/de/07/deployment/ci-cd/) --- title: "CI/CD-Pipelines" description: "Automatisieren Sie die Erstellung und Bereitstellung Ihrer Dokumentation mit CI/CD-Pipelines für GitHub Pages, Vercel, Netlify und mehr." --- Verwenden Sie CI/CD-Workflows, um Ihre `docmd`-Website bei jedem Push von Änderungen automatisch zu erstellen und bereitzustellen. Unten finden Sie einsatzbereite Konfigurationen für gängige Cloud-Plattformen. ## Cloud-Plattformen ::: tabs == tab "GitHub Pages" Die empfohlene Methode ist die Verwendung von **GitHub Actions**, um Ihre Deployments bei jedem Push zu automatisieren. **Erstellen Sie `.github/workflows/deploy.yml`:** ```yaml name: Deploy docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22' } - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. Verbinden Sie Ihr Repository mit Vercel. 2. In den **Build Settings** des Projekts: - **Framework Preset**: `Other` - **Build Command**: `npx @docmd/core build` - **Output Directory**: `site` 3. Deployen. Vercel erkennt automatisch den statischen Output und liefert ihn global aus. == tab "Netlify" 1. Importieren Sie Ihr Projekt von GitHub/GitLab/Bitbucket. 2. Konfigurieren Sie Ihre Build-Einstellungen: - **Build command**: `npx @docmd/core build` - **Publish directory**: `site` 3. Klicken Sie auf **Deploy site**. Das CDN von Netlify kümmert sich um das Routing und die Asset-Auslieferung. == tab "Cloudflare Pages" 1. Erstellen Sie ein neues Projekt im Cloudflare Dashboard unter **Pages**. 2. Verbinden Sie Ihren Git-Provider und wählen Sie Ihr Repository aus. 3. Konfigurieren Sie die Build-Einstellungen: - **Framework preset**: `None` - **Build command**: `npx @docmd/core build` - **Build output directory**: `site` 4. Speichern und Deployen. == tab "Firebase" 1. Installieren Sie das Firebase CLI: `npm install -g firebase-tools`. 2. Erstellen Sie Ihre Website: `npx @docmd/core build`. 3. Führen Sie `firebase init hosting` aus und wählen Sie Ihr Projekt. 4. Setzen Sie das öffentliche Verzeichnis auf `site`. 5. Konfigurieren Sie es als Single-Page-App: `Yes` (dies regelt das 404-Verhalten). 6. Deployen Sie mit `firebase deploy`. ::: ::: callout info "Warum npx @docmd/core?" In CI/CD-Umgebungen, in denen `docmd` nicht global installiert ist, verwenden Sie `npx @docmd/core`, um das Paket direkt auszuführen. Wenn Ihr Projekt `@docmd/core` als `devDependency` gelistet hat, funktioniert auch einfach `docmd build` nach einem `npm install`. ::: ## Manuelle Übertragung / Statischer Server Für klassische Webserver (Apache, IIS etc.): 1. Erstellen Sie die Website: `npx @docmd/core build`. 2. Laden Sie den Inhalt des Ordners `site/` über SFTP, SCP oder Ihr bevorzugtes Deployment-Tool auf Ihren Server hoch. 3. Stellen Sie sicher, dass Ihr Server so konfiguriert ist, dass er `index.html` für Verzeichnisse ausliefert (Standard bei den meisten Servern). --- ## [Docker](https://docs.docmd.io/de/07/deployment/docker/) --- title: "Docker" description: "docmd mit einem Docker-Container bereitstellen - mit einem einzigen Befehl." --- `docmd` generiert statisches HTML - perfekt für leichtgewichtige, reproduzierbare Docker-Container. ## Dockerfile generieren ```bash docmd deploy --docker ``` Dies erstellt ein `Dockerfile` und `.dockerignore` in Ihrem Projektstammverzeichnis, zugeschnitten auf Ihre Konfiguration: - **Ihr Ausgabeverzeichnis** wird im `COPY`-Pfad verwendet (nicht hartcodiert `site/`) - **Ihre exakte `@docmd/core`-Version** wird im Installationsschritt für reproduzierbare Builds fixiert - **Ihre Konfigurationsdatei** wird an `docmd build` übergeben, wenn Sie einen nicht-standardmäßigen Namen verwenden ### Was generiert wird Das Dockerfile verwendet einen optimierten Multi-Stage-Build: 1. **Stage 1 - Build**: Installiert Abhängigkeiten mit Layer-Caching (`package.json` wird zuerst kopiert), installiert die fixierte `@docmd/core`-Version und führt `docmd build` aus. 2. **Stage 2 - Serve**: Kopiert die gebaute Ausgabe in einen minimalen `nginx:alpine`-Container. ::: callout tip "Benutzerdefiniertes Nginx mit Docker" Wenn Sie eine `nginx.conf` (via `docmd deploy --nginx`) vor dem Dockerfile generieren, wird sie automatisch erkannt und im Container konfiguriert. ::: ## Bauen und Ausführen ```bash docker build -t my-docs . docker run -p 8080:80 my-docs ``` Ihre Dokumentation ist jetzt unter `http://localhost:8080` erreichbar. ### Neu generieren Konfiguration geändert? Führen Sie einfach `docmd deploy --docker` erneut aus - die Dateien werden immer neu generiert, um Ihre aktuelle `docmd.config.js` widerzuspiegeln. --- ## [Bereitstellung (Deployment)](https://docs.docmd.io/de/07/deployment/) --- title: "Bereitstellung (Deployment)" description: "Stellen Sie Ihre docmd-Dokumentation mit einem einzigen Befehl auf Docker, Nginx, Caddy oder einer Cloud-Plattform bereit." --- `docmd` generiert eine hochperformante statische Website. Führen Sie den Build-Befehl aus, um das Ausgabeverzeichnis zu erstellen: ```bash docmd build ``` Die Ausgabe ist ein eigenständiger `site/`-Ordner (oder was Sie als `out` in Ihrer Konfiguration festgelegt haben), der überall gehostet werden kann. ## Ein-Befehl-Bereitstellung ::: callout tip "Neu in v0.7.2" `docmd deploy` liest Ihre `docmd.config.js` und generiert Bereitstellungsdateien, die auf Ihr Projekt zugeschnitten sind - keine generischen Vorlagen. ::: Anstatt Dockerfiles und Server-Konfigurationen manuell zu schreiben, lassen Sie docmd diese für Sie generieren: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # Produktions-nginx.conf docmd deploy --caddy # Produktions-Caddyfile ``` ### Was personalisiert wird Der Deploy-Befehl liest Ihre Konfiguration (oder Zero-Config-Standardwerte) und injiziert: | Konfigurationsfeld | Verwendet in | |:--|:--| | `title` | Kommentar-Header in jeder generierten Datei | | `out` | `COPY`-Pfade im Dockerfile, `root`-Direktiven in Nginx/Caddy | | `url` | `server_name` in Nginx, Site-Adresse in Caddy | | `layout.spa` | Steuert, ob SPA-Routing-Fallback enthalten ist | | Konfigurations-Dateipfad | Dockerfile-Build-Schritt verwendet `--config` bei nicht-standardmäßigem Pfad | Keine `docmd.config.js`? Kein Problem - der Befehl nutzt die gleichen Zero-Config-Standardwerte wie `docmd dev` und `docmd build`. ### Immer synchron Jede Ausführung generiert Ihre Bereitstellungsdateien neu, um sie mit Ihrer aktuellen Konfiguration abzugleichen. Site-URL oder Ausgabeverzeichnis geändert? Führen Sie den Deploy-Befehl einfach erneut aus. ### Unterstützte Ziele * [`docmd deploy --docker`](./docker) - Optimiertes Multi-Stage-Dockerfile mit Layer-Caching und Versionspinning. * [`docmd deploy --nginx`](./nginx) - Sicherheitsgehärtete nginx.conf mit GZIP und unveränderlichem Asset-Caching. * [`docmd deploy --caddy`](./caddy) - HTTPS-bereites Caddyfile mit automatischem Routing. Klicken Sie auf jedes Ziel für detaillierte, service-spezifische Dokumentation. *(Cloud-Bereitstellungsziele wie `--vercel` und `--netlify` sind für ein zukünftiges Release geplant.)* ## Cloud-Hosting & CI/CD Wenn Sie verwaltetes Hosting gegenüber selbst gehosteten Servern bevorzugen, stellen Sie Ihren Ausgabe-Ordner direkt auf GitHub Pages, Vercel, Netlify oder Cloudflare Pages bereit. Siehe den [CI/CD-Bereitstellungsleitfaden](./ci-cd) für automatisierte Workflows. ## SPA-Routing `docmd` implementiert einen Mikro-SPA-Router für reibungslose interne Navigation. Jede Seite wird als eigene `index.html`-Datei generiert: - **Keine Rewrite-Regeln nötig** - direkter URL-Zugriff funktioniert, weil `/guide/setup` als `/guide/setup/index.html` aufgelöst wird. - **Deep Linking funktioniert** - sofort einsatzbereit auf jeder Hosting-Plattform. Wenn `layout.spa` in Ihrer Konfiguration auf `false` gesetzt ist, lässt der Deploy-Befehl das SPA-Fallback-Routing in den generierten Server-Konfigurationen weg. ## Produktions-Checkliste 1. **Site-URL**: Setzen Sie die `url`-Eigenschaft in `docmd.config.js` - dies steuert kanonische Tags, Sitemaps, Social-Previews und die Generierung von Bereitstellungsdateien. 2. **Weiterleitungen**: Migration von einem anderen Tool? Verwenden Sie die `redirects`-Konfiguration zur Beibehaltung der SEO-Rankings. 3. **Analytik**: Aktivieren Sie das `analytics`-Plugin zur Verfolgung von Engagement und Suchanfragen. 4. **KI-Kontext**: Aktivieren Sie das `llms`-Plugin zur Generierung von `llms.txt` für die KI-Agent-Aufnahme. ::: callout tip "Benutzerdefinierte 404-Seiten" `docmd` generiert eine `404.html` in Ihrem Ausgabeverzeichnis. Die meisten Hosting-Anbieter verwenden diese Datei automatisch für fehlende Routen. ::: --- ## [NGINX](https://docs.docmd.io/de/07/deployment/nginx/) --- title: "NGINX" description: "docmd mit einer produktionsreifen NGINX-Konfiguration bereitstellen." --- NGINX ist einer der zuverlässigsten Webserver. Da `docmd`-Ausgabe vollständig statisch ist, kann NGINX sie mit nahezu null Latenz bereitstellen. ## nginx.conf generieren ```bash docmd deploy --nginx ``` Dies generiert eine `nginx.conf`, die auf Ihr Projekt zugeschnitten ist: - **`server_name`** wird auf den Hostnamen aus Ihrer `url`-Konfiguration gesetzt (Fallback auf `localhost`) - **SPA-Fallback** (`try_files ... /index.html`) wird nur einbezogen, wenn `layout.spa` in Ihrer Konfiguration `true` ist - **Sicherheitsheader**, GZIP-Kompression und unveränderliches Asset-Caching sind standardmäßig enthalten ## Bereitstellungsschritte 1. Bauen Sie Ihre Website: `docmd build` 2. Laden Sie den Inhalt Ihres Ausgabeverzeichnisses auf den Web-Root Ihres Servers hoch (z.B. `/usr/share/nginx/html/`). 3. Platzieren Sie die generierte `nginx.conf` in die Konfiguration Ihres Servers (z.B. `/etc/nginx/conf.d/default.conf`). 4. Starten Sie NGINX neu: `sudo systemctl restart nginx` ### Neu generieren Site-URL geändert oder SPA-Modus umgeschaltet? Führen Sie `docmd deploy --nginx` erneut aus - die Konfiguration wird neu generiert, um Ihre aktuelle `docmd.config.js` widerzuspiegeln. --- ## [Installation](https://docs.docmd.io/de/07/getting-started/installation/) --- title: "Installation" description: "Installieren Sie docmd global, lokal oder führen Sie es sofort mit npx aus. Erfordert Node.js 18+." --- Wählen Sie die Installationsmethode, die am besten zu Ihrem Workflow passt. ## Sofort ausführen ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: Keine Installation erforderlich. Führt docmd direkt in jedem Ordner mit Markdown-Dateien aus. ::: tabs == tab "npm" icon:box ```bash # Eine produktionsreife statische Website erstellen npx @docmd/core build ``` == tab "Bun" icon:zap ```bash # Eine produktionsreife statische Website erstellen bunx @docmd/core build ``` ::: ## Als Projektabhängigkeit installieren (empfohlen) ::: tabs == tab "npm" icon:package ```bash npm install -D @docmd/core npx @docmd/core init npx @docmd/core dev ``` == tab "pnpm" icon:boxes ```bash pnpm add -D @docmd/core pnpm dlx docmd init pnpm dlx docmd dev ``` == tab "yarn" icon:scroll ```bash yarn add -D @docmd/core yarn docmd init yarn docmd dev ``` == tab "Bun" icon:zap ```bash bun add -D @docmd/core bunx docmd init bunx docmd dev ``` ::: Dies fixiert die Version für Ihr gesamtes Team und Ihre CI/CD-Pipeline. ::: callout tip "Nach der lokalen Installation" Sobald `@docmd/core` zu Ihren Projektabhängigkeiten hinzugefügt wurde, können Sie `docmd` (oder `npm docmd`, `yarn docmd`, `bun docmd`) anstelle von `npx @docmd/core` für alle Befehle verwenden. ::: ## Global installieren ::: tabs == tab "npm" icon:package ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: ```bash # Den 'docmd'-Befehl überall verwenden docmd dev docmd build ``` ## Nur-Browser-Integration ::: callout info "Nur für Bibliotheksnutzung" Diese Methode bettet die docmd-Rendering-Engine in eine andere Webanwendung ein. Dies ist nicht der Standardweg zum Erstellen von Dokumentationsseiten. ::: ```html <!-- Kern-Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Processing-Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` Weitere Details zur Integration finden Sie im [Browser-API](../api/browser-api.md)-Leitfaden. ## Fehlerbehebung ::: callout warning "Berechtigung verweigert (EACCES)" Wenn während der globalen Installation unter macOS oder Linux `EACCES`-Fehler auftreten, wechseln Sie zu einem Node-Versionsmanager wie [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm), anstatt `sudo` zu verwenden. ::: ::: callout info "PowerShell-Skriptausführung (Windows)" Wenn PowerShell die Skriptausführung blockiert, führen Sie dies als Administrator aus: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [Projektstruktur](https://docs.docmd.io/de/07/getting-started/project-structure/) --- title: "Projektstruktur" description: "Wie docmd Ihre Dateien und Ordner auf Seiten, URLs und Navigation abbildet." --- docmd verwendet Ihr Dateisystem als Quelle der Wahrheit. Ordner werden zu Abschnitten, Markdown-Dateien zu Seiten und die Verzeichnishierarchie definiert die URL-Routen. ## Ein Projekt initialisieren ::: tabs == tab "npm" icon:box ```bash mkdir meine-dokumentation && cd meine-dokumentation npx @docmd/core init ``` == tab "Bun" icon:zap ```bash mkdir meine-dokumentation && cd meine-dokumentation bunx @docmd/core init ``` ::: Dies erstellt das Standard-Projektgerüst: ```text meine-dokumentation/ ├── docs/ ← Quellverzeichnis. Ihre .md-Dateien kommen hierher. │ └── index.md ← Startseite (/) ├── assets/ ← Statische Assets (Bilder, eigenes CSS/JS) │ ├── css/ │ ├── js/ │ └── images/ ├── docmd.config.js ← Konfigurationsdatei ├── package.json ← Projektmetadaten und Skripte └── site/ ← Generierte Ausgabe (nach dem Build) ``` ## Datei-zu-URL-Mapping docmd bildet Ihre `docs/`-Verzeichnisstruktur direkt auf URLs ab: | Datei | URL | |:-----|:----| | `docs/index.md` | `/` | | `docs/api.md` | `/api` | | `docs/guides/setup.md` | `/guides/setup` | ::: callout tip "Automatische Titel" Wenn ein Seitentitel nicht im Frontmatter definiert ist, extrahiert docmd die erste `H1`-Überschrift als Titel. ::: ## Entwicklungsserver starten ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: Öffnet `http://localhost:3000` mit Live-Reload. Änderungen an `.md`-Dateien oder der `docmd.config.js` werden sofort übernommen. ## Für die Produktion erstellen ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: Gibt eine statische Website in `./site/` aus. Die Ausgabe besteht ausschließlich aus statischem HTML - stellen Sie sie auf GitHub Pages, Vercel, Netlify oder einem beliebigen statischen Host bereit. Vor der Bereitstellung lokal überprüfen: ::: tabs == tab "npm" icon:box ```bash npx serve site ``` == tab "Bun" icon:zap ```bash bunx serve site ``` ::: --- ## [Schnellstart](https://docs.docmd.io/de/07/getting-started/quick-start/) --- title: "Schnellstart" description: "Gelangen Sie in weniger als einer Minute von einem leeren Ordner zu einer laufenden Dokumentationsseite." --- Führen Sie docmd in jedem Ordner aus, der Markdown-Dateien enthält. Keine Konfigurationsdatei, kein Setup, keine Framework-Kenntnisse erforderlich. ## Entwicklungsserver starten ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: Öffnet `http://localhost:3000`. Ihre Dokumentation ist live. ## Was automatisch passiert docmd scannt Ihr Projekt und richtet alles ein: 1. **Ordnererkennung** - sucht nach `docs/`, `src/docs/`, `documentation/` oder beliebigen `.md`-Dateien 2. **Navigationserstellung** - erstellt eine verschachtelte Seitenleiste aus Ihrer Ordnerstruktur 3. **Metadaten-Extraktion** - liest die `package.json` für den Seitentitel aus, falls verfügbar 4. **Theme-Aktivierung** - wendet das Standard-Theme mit systemabhängigem Hell-/Dunkelmodus an 5. **Suchindexierung** - ermöglicht die integrierte Volltextsuche Es wird keine `docmd.config.js` benötigt. Fügen Sie später eine hinzu, wenn Sie Versionierung, Plugins oder eine benutzerdefinierte Navigation benötigen. ## Für die Produktion erstellen ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: Gibt eine statische Website in `./site/` aus, die überall bereitgestellt werden kann. --- ## [Kontexterhaltung für KI-freundliche Dokumentation](https://docs.docmd.io/de/07/guides/ai-optimisation/context-preservation/) --- title: "Kontexterhaltung für KI-freundliche Dokumentation" description: "Wie Sie sicherstellen, dass KI-Modelle die Beziehungen zwischen verschiedenen Teilen Ihrer Dokumentation verstehen und nutzen können." --- ## Problem Während menschliche Leser problemlos auf einen Hyperlink klicken können, um mehr über einen Begriff zu erfahren, verarbeiten KI-Modelle Dokumentationen oft in isolierten "Chunks" (Stücken). Wenn eine KI auf einen Hyperlink stößt, kann sie ihn nicht "anklicken", um mehr Kontext abzurufen. Wenn kritische Informationen hinter einem Link verborgen sind, anstatt im Kontext erklärt zu werden, kann die KI möglicherweise keine genauen Antworten liefern, was zu Halluzinationen führt. ## Warum es wichtig ist KI-Modelle verlassen sich auf den unmittelbar umgebenden Text, um die Bedeutung und Relevanz von Informationen zu bestimmen. Wenn Ihre Dokumentation stark fragmentiert ist und eine schlechte Kontexterhaltung aufweist, werden KI-gesteuerte Suchwerkzeuge (wie solche, die auf RAG basieren) Schwierigkeiten haben, qualitativ hochwertige Antworten zu liefern. ## Ansatz Verwenden Sie **Inline Context Unrolling** (kontextuelles Entfalten im Text), um neben jedem wichtigen Link den minimal lebensfähigen Kontext bereitzustellen. Nutzen Sie außerdem die spezifischen Funktionen von `docmd`, wie das [LLMs-Plugin](../../plugins/llms.md), um eine einheitliche, maschinenlesbare Ansicht Ihres gesamten Dokumentationssatzes bereitzustellen. ## Implementierung ### 1. Beschreibende Verlinkung und Zusammenfassungen Vermeiden Sie generische Linktexte. Stellen Sie stattdessen eine kurze, einseitige Zusammenfassung des verlinkten Konzepts vor oder nach dem Link selbst bereit. - **❌ Schlecht (Kontext verloren)**: Um das Timeout zu konfigurieren, lesen Sie die [Allgemeine Konfiguration](../../configuration/overview.md). - **✅ Besser (Kontext erhalten)**: Sie können den Parameter `timeoutMs` in der [Allgemeinen Konfiguration](../../configuration/overview.md) konfigurieren, der definiert, wie lange die Engine wartet, bevor eine Netzwerkanfrage fehlschlägt. ### 2. Verwendung von ausklappbaren Abschnitten für Details [Ausklappbare Container](../../content/containers/collapsible.md) eignen sich hervorragend für die KI-Optimierung. Der Inhalt bleibt Teil des rohen Markdown-Quellcodes (den die KI lesen kann), wird aber für menschliche Leser visuell verstaut. ```markdown ### Datenbankverbindung Stellen Sie die Verbindung über den primären URI her. ::: collapsible "Wie lautet das URI-Format?" Der URI folgt dem standardmäßigen PostgreSQL-Format: `postgresql://benutzer:passwort@host:port/datenbank`. ::: ``` ### 3. Aktivierung des LLMs-Plugins Aktivieren Sie das [LLMs-Plugin](../../plugins/llms.md) in Ihrer `docmd.config.js`. Dieses Plugin generiert nach jedem Build automatisch eine `llms-full.txt`-Datei, die Ihren gesamten Dokumentationssatz in einer einzigen Datei mit hohem Kontextgehalt zusammenfasst, die leicht von Large Language Models verarbeitet werden kann. ## Abwägungen Inline Context Unrolling macht Ihre Dokumentation etwas wortreicher und führt zu geringfügigen Redundanzen. Diese Redundanz ist jedoch ein kleiner Preis für die Sicherstellung, dass Ihre Dokumentation "KI-bereit" ist und in der Lage ist, qualitativ hochwertige automatisierte Support- und Sucherlebnisse zu ermöglichen. --- ## [Erstellung deterministischer und chunkbarer Dokumentation](https://docs.docmd.io/de/07/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "Erstellung deterministischer und chunkbarer Dokumentation" description: "So strukturieren Sie Ihre Dokumentation, um sie für Retrieval-Augmented Generation (RAG) und die KI-Verarbeitung zu optimieren." --- ## Problem Wenn KI-Pipelines (wie RAG-Architekturen) Dokumentationen aufnehmen, schneiden sie die Markdown-Quelle in kleinere "Chunks" (z. B. jeweils 500 Token). Wenn ein Dokument aus langen, ausschweifenden Absätzen mit unklaren Grenzen besteht, kann der Slicing-Algorithmus den Kontext mitten im Gedanken trennen. Dies zerstört den Nutzen des Chunks und führt zu unvollständigen oder falschen KI-Antworten. ## Warum es wichtig ist Wenn eine KI einen Chunk abruft, der einen Code-Block enthält, aber den vorangehenden Absatz verpasst, der erklärt, *wann* dieser Code zu verwenden ist, wird der generierten Antwort die notwendige Konditionalität fehlen. Die Strukturierung Ihrer Dokumentation nach "Chunkbarkeit" stellt sicher, dass jeder Textabschnitt genügend Kontext enthält, um für sich allein nützlich zu sein. ## Ansatz Strukturieren Sie Ihre Seiten als Hierarchie deterministischer, atomarer Blöcke. Nutzen Sie Markdown-Überschriften, um Konzepte klar voneinander abzugrenzen, und stellen Sie sicher, dass zusammengehörige Informationen (wie eine Warnung und der dazugehörige Code) in der Quelldatei physisch nah beieinander liegen. ## Implementierung ### 1. Atomare Überschriften-Abschnitte Stellen Sie sicher, dass jede `##`- oder `###`-Überschrift ein einzelnes, atomares Konzept kapselt. Ein gut strukturierter Abschnitt sollte als nützlicher Chunk für ein KI-Modell allein stehen können. - **✅ Gut**: Eine Überschrift "Authentifizierung via OAuth", gefolgt von einer kurzen Erklärung und einem Code-Beispiel. - **❌ Schlecht**: Eine massive "Getting Started"-Seite mit 15 verschiedenen Konzepten ohne Unterüberschriften. ### 2. Räumliche Nähe für kritische Informationen Trennen Sie eine kritische Warnung nicht durch lange Absätze von dem Code, auf den sie sich bezieht. Nutzen Sie [Callouts](../../content/containers/callouts), um sie vertikal aneinander zu binden. Dies erhöht die Wahrscheinlichkeit, dass sie bei der Verarbeitung im selben Vektor-Chunk bleiben. ```markdown ::: callout warning "Destruktive Aktion" Das Ausführen dieses Befehls löscht permanent alle Logs. ::: `docmd logs --clear` ``` ### 3. Automatisierte Zusammenführung Das [LLMs-Plugin](../../plugins/usage) erleichtert das Chunking, indem es eine `llms-full.txt`-Datei generiert. Diese Datei nutzt Standard-Trenner (`---`) zwischen den Seiten und hilft Ingestions-Pipelines so dabei, natürliche Dokumentgrenzen zu erkennen, während der globale Kontext Ihres Projekts erhalten bleibt. ## Abwägungen Dieser Ansatz bevorzugt einen modularen, segmentierten Schreibstil gegenüber langen, fließenden Erzählungen. Während sich dies für einen menschlichen Leser repetitiver anfühlen mag, verbessert es die Leistung von KI-gestützten Suchvorgängen und automatisierten Support-Agenten, die auf Ihre Dokumentation angewiesen sind, erheblich. --- ## [Erstellung von KI-bereiter Dokumentation mit docmd](https://docs.docmd.io/de/07/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "Erstellung von KI-bereiter Dokumentation mit docmd" description: "So nutzen Sie den llms.txt-Standard und die integrierten Tools von docmd, um optimierten Kontext für KI-Assistenten bereitzustellen." --- ## Problem Entwickler verlassen sich zunehmend auf KI-Coding-Assistenten (wie Cursor, GitHub Copilot und ChatGPT), um Dokumentationen für sie zu lesen und zu interpretieren. Wenn Ihre Dokumentation nur über einen Webbrowser zugänglich ist und mit Navigationselementen, Trackern und komplexem HTML überladen ist, verbrauchen KI-Agenten unnötig viele Token für irrelevante Daten, was ihre Kontextfenster schnell erschöpft. ## Warum es wichtig ist Die Bereitstellung einer sauberen, Token-optimierten Textversion Ihrer Dokumentation ist das moderne Äquivalent zur Bereitstellung einer hochwertigen REST-API. Sie stellt sicher, dass KI-Agenten Ihren gesamten Dokumentationssatz schnell aufnehmen können, was zu genaueren Code-Vorschlägen und einem besseren Support für Entwickler führt, die Ihr Produkt nutzen. ## Ansatz Nutzen Sie das integrierte **LLMs-Plugin** von `docmd`. Dieses Plugin implementiert nativ den aufkommenden `llms.txt`-Standard und generiert bei jedem Build-Prozess automatisch Token-optimierte Zusammenfassungen und Vollkontext-Dateien. ## Implementierung Das `llms`-Plugin ist in `docmd >= 0.7.0` verfügbar und kann in Ihrer [Plugin-Konfiguration](../../plugins/usage) konfiguriert werden. ### 1. Konfiguration der Website-URL Stellen Sie sicher, dass die Eigenschaft `url` in Ihrer `docmd.config.js` korrekt gesetzt ist. Dies ermöglicht es dem Plugin, absolute URLs für alle Seiten in der Datei `llms.txt` zu generieren. ```javascript // docmd.config.js export default { title: 'Mein Projekt Docs', url: 'https://docs.example.com', plugins: ['llms'] }; ``` ### 2. Ausgabedateien Während des Build-Prozesses generiert `docmd` zwei wichtige Dateien im Root-Verzeichnis Ihrer Website: - **`llms.txt`**: Eine prägnante, strukturierte Markdown-Zusammenfassung aller Ihrer Seiten, einschließlich ihrer Titel, Beschreibungen und vollständigen URLs. - **`llms-full.txt`**: Eine umfassende Datei, die den rohen Markdown-Inhalt Ihrer gesamten Website enthält, zusammengeführt durch Standard-Trenner (`---`). Dies bietet die ultimative "Source of Truth" für KI-Modelle. ### 3. Steuerung der Verarbeitung Sie können bestimmte Seiten von der KI-bereiten Ausgabe ausschließen, indem Sie die Eigenschaft `llms` im [Seiten-Frontmatter](../../content/frontmatter) verwenden. ```yaml --- title: "Interner Debugging-Leitfaden" llms: false --- ``` ## Abwägungen Die Generierung von `llms-full.txt` erzeugt eine einzige, sehr große Datei. Bei außergewöhnlich umfangreichen Dokumentations-Websites kann diese Datei mehrere Megabyte groß werden. Während dies ideal für moderne LLMs mit großen Kontextfenstern (wie Gemini 1.5 Pro oder Claude 3.5 Sonnet) ist, kann sie für kleinere Modelle zu groß sein. Stellen Sie sicher, dass Sie Ihre [Navigation](../../configuration/navigation) logisch strukturieren, damit die KI die wichtigsten Abschnitte priorisieren kann. --- ## [Minimierung von KI-Halluzinationen durch Dokumentation](https://docs.docmd.io/de/07/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "Minimierung von KI-Halluzinationen durch Dokumentation" description: "So schreiben Sie explizite, in sich geschlossene Dokumentationen, die verhindern, dass KI-Modelle falsche Informationen erfinden." --- ## Problem KI-Modelle sind Vorhersagesysteme, keine Logiksysteme. Wenn ein API-Anwendungsbeispiel unvollständig ist, mehrdeutige Platzhalter verwendet oder auf implizitem Wissen beruht, wird die KI oft "halluzinieren" , sie erfindet die fehlenden Teile basierend auf allgemeinen Mustern, die sie während des Trainings gelernt hat. Diese Erfindungen sind für Ihre spezifische Software häufig falsch, was zu Frustration bei den Entwicklern führt. ## Warum es wichtig ist Halluzinierter Code zerstört das Vertrauen der Nutzer. Wenn ein Entwickler eine KI um Hilfe bittet und Code erhält, der einen Syntaxfehler auslöst oder nicht existierende Parameter verwendet, macht er oft die Software selbst für die "Fehlerhaftigkeit" oder "schlechte Dokumentation" verantwortlich. Die Minimierung von Halluzinationen ist entscheidend für den professionellen Ruf Ihres Projekts. ## Ansatz Praktizieren Sie **Defensive Dokumentation**. Dies bedeutet, extrem explizite, vollständig instanziierte Codeblöcke zu schreiben, die keinen Raum für Mehrdeutigkeiten lassen. Gehen Sie niemals davon aus, dass der Leser (oder die KI) die erforderlichen Imports, Umgebungsvariablen oder vorausgesetzten Konfigurationen kennt. ## Implementierung ### 1. Vollständig qualifizierte Codeblöcke Fügen Sie in jedem Snippet die erforderlichen Imports oder den Setup-Code ein. Dies stellt sicher, dass der Codeblock eine in sich geschlossene Einheit der Wahrheit bleibt, wenn eine KI Ihre Dokumentation in Chunks zerlegt. - **❌ Halluzinations-Risiko**: ```javascript const config = loadConfig(); // Woher kommt loadConfig? ``` - **✅ Halluzinations-Sicher**: ```javascript import { loadConfig } from '@docmd/core'; const config = loadConfig(); ``` ### 2. Konkrete Beispiele statt Platzhalter Vermeiden Sie vage Platzhalter wie `ihr-api-key` oder `env-name`. Geben Sie stattdessen konkrete, gültige Beispiele an oder nutzen Sie Kommentare, um strikte Enum-Anforderungen zu spezifizieren. ```javascript // Gültige Umgebungen: "development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. Inline-Code-Kommentare Platzieren Sie kritische Anforderungen als Kommentare *innerhalb* des Codeblocks, anstatt nur im umgebenden Markdown-Text. KI-Modelle bewerten Kommentare innerhalb des Codes bei der Generierung ähnlicher Snippets sehr hoch. ```javascript export default { // KRITISCH: Der outputPath muss ein absoluter Dateisystempfad sein. outputPath: '/var/www/html/docs' }; ``` ### 4. Kategorisierte Warnungen Nutzen Sie [Callouts](../../content/containers/callouts), um veraltete Funktionen oder bahnbrechende Änderungen (Breaking Changes) klar zu markieren. KI-Modelle halten sich eher an einen `::: callout warning`-Block als an einen einfachen Satz in einem Absatz. ## Abwägungen Defensive Dokumentation macht Codeblöcke länger und repetitiver. Menschliche Leser empfinden es vielleicht als etwas ermüdend, in jedem Snippet dieselben `import`-Anweisungen zu sehen. Der Vorteil einer "KI-sicheren" Dokumentation, die Support-Tickets und Benutzerfehler deutlich reduziert, überwiegt jedoch bei weitem die geringen Kosten der Wortreichtum. --- ## [Design für semantische Suche und RAG](https://docs.docmd.io/de/07/guides/ai-optimisation/semantic-search-design/) --- title: "Design für semantische Suche und RAG" description: "So strukturieren Sie Ihre Dokumentation, um sie für die vektorbasierte Suche und Retrieval-Augmented Generation zu optimieren." --- ## Problem Die herkömmliche Stichwortsuche (wie die [integrierte Suche von docmd](../../plugins/search)) verlässt sich auf exakte Texttreffer. Wenn ein Benutzer nach "Authentifizierung" sucht, findet eine einfache Keyword-Engine eine Seite mit dem Titel "Integration von OAuth2" unter Umständen nicht, falls dieses spezifische Wort nicht oft genug vorkommt. Die semantische Suche, die Vektor-Embeddings nutzt, um die *Bedeutung* einer Abfrage zu verstehen, löst dieses Problem, erfordert jedoch spezifische Dokumentationsstrukturen, um effektiv zu sein. ## Warum es wichtig ist Entwickler von heute erwarten intuitive, intent-basierte Sucherlebnisse. Wenn Ihre Dokumentation relevante Inhalte aufgrund geringfügiger terminologischer Unterschiede nicht anzeigt, werden Benutzer Ihre Seite schnell verlassen und woanders Hilfe suchen. Ein Design für die semantische Suche stellt sicher, dass Ihre Dokumentation auffindbar bleibt, selbst wenn Benutzer unterschiedliche Begriffe verwenden. ## Ansatz Strukturieren Sie Ihre Dokumentation so, dass sie leicht von Retrieval-Augmented Generation (RAG)-Pipelines verarbeitet werden kann. Dies beinhaltet die Erstellung "semantisch dichter" Inhalte, in denen Konzepte klar definiert sind und Pronomen durch explizite Begriffe ersetzt werden, um den Kontext während des Chunking- und Vektorisierungsprozesses zu erhalten. ## Implementierung ### 1. Reichhaltige Frontmatter-Metadaten Nutzen Sie [Frontmatter](../../content/frontmatter), um explizite Schlüsselwörter und Beschreibungen bereitzustellen, die im Fließtext vielleicht nicht natürlich vorkommen würden. Dies gibt der Suchmaschine zusätzliche Anhaltspunkte für Ihren Inhalt. ```yaml --- title: "Integration von OAuth2" description: "Erfahren Sie, wie Sie sichere Benutzerauthentifizierung und SSO implementieren." keywords: ["login", "authentifizierung", "sso", "security", "identity"] --- ``` ### 2. Die "Semantische Dichte"-Strategie RAG-Systeme zerlegen Dokumente in kleine Stücke (Vektoren). Der erste Absatz jedes Abschnitts sollte die höchste Dichte an relevanten Substantiven und Verben zu diesem Thema enthalten. Dies stellt sicher, dass die primäre "Bedeutung" des Abschnitts bereits im initialen Vektor erfasst wird. - **✅ Gut**: "Dieser Leitfaden erklärt, wie Sie **OAuth2 Single Sign-On (SSO)** implementieren, um eine sichere **Authentifizierung** für Ihre Dokumentationsseite bereitzustellen." - **❌ Schlecht**: "In diesem Abschnitt sprechen wir darüber, wie es funktioniert und wie Sie es einfach einrichten können." ### 3. Vermeidung von mehrdeutigen Pronomen In einer zerlegten Datenbank ist ein Satz wie "Es funktioniert mit jedem Anbieter" nutzlos, wenn der vorangehende Absatz, der "Es" definiert, in einen anderen Chunk geschnitten wurde. Seien Sie explizit. - **❌ Mehrdeutig**: "Es ist hochgradig skalierbar." - **✅ Explizit**: "Die **docmd Search Engine** ist so konzipiert, dass sie hochgradig skalierbar ist." ## Abwägungen Das Schreiben für semantische Dichte kann sich manchmal etwas formeller oder repetitiver anfühlen als herkömmliches narratives Schreiben. Die daraus resultierende Verbesserung der Auffindbarkeit und der Genauigkeit von KI-generierten Antworten macht dies jedoch zu einer unverzichtbaren Praxis für moderne, professionelle Dokumentationen. --- ## [Strukturierung der Dokumentation für KI-Agenten](https://docs.docmd.io/de/07/guides/ai-optimisation/structure-for-llms/) --- title: "Strukturierung der Dokumentation für KI-Agenten" description: "Wie Sie von visueller Formatierung zu semantischer Strukturierung übergehen, um die Genauigkeit von KI-Codierungsassistenten zu verbessern." --- ## Problem Menschliche Leser verlassen sich auf visuelle Hinweise, die Navigation in der Seitenleiste und abgeleiteten Kontext, um Dokumentationen zu verstehen. KI-Agenten und Large Language Models (LLMs) konsumieren jedoch primär rohe Textströme. Wenn einer Dokumentation eine strenge semantische Struktur fehlt, haben diese Modelle Schwierigkeiten, Beziehungen zwischen Konzepten abzubilden, was zu mangelhaften Schlussfolgerungen und ungenauen Codierungsvorschlägen führt. ## Warum es wichtig ist Wenn Ihre Dokumentation nicht für LLMs optimiert ist, werden Entwickler, die Tools wie GitHub Copilot, Cursor oder ChatGPT verwenden, bei der Arbeit mit Ihrer Software mehr Halluzinationen erleben. Dies verschlechtert direkt die Entwicklererfahrung, da Benutzer oft das Produkt selbst für die von ihren KI-Assistenten generierten Fehler verantwortlich machen. ## Ansatz Wechseln Sie von einer "Visual-First"-Mentalität zu einer **"Semantic-First"**-Mentalität. Verwenden Sie Standard-Markdown-Funktionen - wie strenge Überschriftenhierarchien, explizite Sprach-Tags für Codeblöcke und beschreibende Alt-Texte - , um einen klaren, maschinenlesbaren Fahrplan für Ihre Inhalte bereitzustellen. `docmd` verarbeitet diese Struktur über das [LLMs-Plugin](../../plugins/llms.md) zu optimierten Ausgaben. ## Implementierung ### 1. Strenge Überschriftenhierarchie Vermeiden Sie es, Überschriftenebenen nur für rein visuelle Effekte zu überspringen. Eine konsistente Hierarchie ermöglicht es LLMs, den Umfang und die Beziehung verschiedener Abschnitte zu verstehen. - **`#` Titel**: Das Hauptthema der Seite. - **`##` Hauptkonzept**: Ein atomares, übergeordnetes Thema. - **`###` Detail**: Eine spezifische Teilaufgabe oder Eigenschaft dieses Konzepts. * **❌ Schlecht**: Die Verwendung von `###` unmittelbar nach `#`, nur weil Ihnen die kleinere Schriftgröße gefällt. * **✅ Gut**: `# Installation` gefolgt von `## Voraussetzungen` und dann `### Systemanforderungen`. ### 2. Beschreibende Metadaten für Medien Da LLMs Bilder oder Diagramme nicht "sehen" können, müssen Sie den architektonischen Kontext im Alternativtext oder einem angrenzenden Absatz bereitstellen. ```markdown ![Systemarchitektur: Die Frontend-React-Anwendung kommuniziert über REST mit der Node.js-API, die wiederum einen Redis-Cache und eine PostgreSQL-Datenbank abfragt.](../../static/img/architecture.png) ``` ### 3. Explizite Kennzeichnung von Codeblöcken Geben Sie für jeden Fenced Code Block immer die Sprache mithilfe von [Syntax Highlighting](../../content/syntax/index.md) an. Dies ermöglicht es LLMs, den Abstract Syntax Tree (AST) des Codes korrekt zu parsen. ```javascript // docmd.config.js export default { plugins: ['llms'] }; ``` ### 4. Semantische Container Verwenden Sie [Callouts](../../content/containers/callouts.md) anstelle von generischen Blockzitaten, um eine Absicht (Intent) zu vermitteln. Die semantischen Container von `docmd` helfen KI-Modellen, zwischen Kernanweisungen und ergänzenden Tipps oder Warnungen zu unterscheiden. ## Abwägungen Semantische Strenge erfordert Disziplin von den Autoren. Sie können Markdown-Funktionen (wie Blockzitate oder Überschriften) nicht mehr als rein dekorative Elemente verwenden. Diese Disziplin führt jedoch zu einer Dokumentation, die sowohl für KI-Agenten als auch für menschliche Leser, die assistierende Technologien verwenden, deutlich zugänglicher ist. --- ## [Anti-Patterns vermeiden](https://docs.docmd.io/de/07/guides/content-ux/avoiding-anti-patterns/) --- title: "Anti-Patterns vermeiden" description: "So identifizieren und eliminieren Sie häufige Dokumentationsfehler, welche die User Experience verschlechtern und \"Content Debt\" erhöhen." --- ## Problem Im Laufe der Zeit sammeln sich in Dokumentations-Repositories oft "Quick Fixes" für Content-Probleme an, welche die User Experience ungewollt verschlechtern. Diese Anti-Patterns , wie vage Linktexte oder überladene Codebeispiele , verfestigen sich im Projekt, was die Dokumentation schwerer wartbar und für Entwickler weniger nützlich macht. ## Warum es wichtig ist Anti-Patterns tragen zur "Content Debt" (Inhaltsschulden) bei. Sie verschlechtern das Ranking in Suchmaschinen (SEO), verringern die Barrierefreiheit für Menschen mit Behinderungen und erhöhen die kognitive Belastung für Leser erheblich, die lediglich eine schnelle Lösung für ein technisches Problem suchen. Eine qualitativ hochwertige Dokumentation erfordert ständige Wachsamkeit, um sie sauber, prägnant und professionell zu halten. ## Ansatz Identifizieren und eliminieren Sie gängige Anti-Patterns konsequent während des [Peer-Review-Prozesses](../workflows-teams/git-based-workflows.md). Nutzen Sie automatisierte Prose-Linter wie Vale sowie manuelle Reviews, um sicherzustellen, dass Ihre Inhalte auf allen Seiten hochwertig, zugänglich und konsistent bleiben. ## Implementierung ### 1. Nicht-descriptive Hyperlinks Vermeiden Sie generische Texte wie "hier klicken" oder "mehr lesen" für Links. Dies schadet der SEO und macht die Dokumentation unzugänglich für Nutzer von Screenreadern, die oft navigieren, indem sie von Link zu Link springen. * **❌ Schlecht**: Um Ihren Server zu konfigurieren, [klicken Sie hier](../../configuration/overview.md). * **✅ Gut**: Lesen Sie die [globale Konfiguration](../../configuration/overview.md), um Ihren Produktionsserver einzurichten. ### 2. Die "Wand aus Boilerplate" Das Einfügen dutzender Zeilen von Standard-Imports und Boilerplate-Konfiguration vor der eigentlichen Logik in Codebeispielen lenkt den Leser vom eigentlichen Punkt des Beispiels ab. * **Lösung**: Konzentrieren Sie sich auf das relevante Code-Snippet. Wenn Boilerplate für den Kontext notwendig ist, verwenden Sie Kommentare, um darauf hinzuweisen, dass Standard-Imports aus Gründen der Kürze weggelassen wurden, oder nutzen Sie [Callouts](../../content/containers/callouts.md), um das erforderliche Setup zu erläutern. ### 3. FAQs als "Müllhalde" nutzen "Häufig gestellte Fragen" (FAQ) werden oft zu einem Sammelbecken für Informationen, die zu schwierig in die Hauptanleitungen zu integrieren waren. Wenn eine Frage tatsächlich "häufig gestellt" wird, ist dies ein klares Zeichen dafür, dass Ihre Kerndokumentation dieses Konzept nicht effektiv erklärt hat. * **Lösung**: Anstatt die FAQ zu erweitern, sollten Sie das entsprechende Tutorial oder die konzeptionelle Anleitung überarbeiten, um die Unklarheit direkt dort zu beseitigen, wo der Benutzer sie zuerst bemerkt. Verwenden Sie einen [wichtigen Callout](../../content/containers/callouts.md), wenn die Information kritisch für den Erfolg ist. ## Abwägungen Das Eliminieren von FAQs erfordert von den Autoren, bestehende Dokumentationshierarchien ständig zu überarbeiten und zu verbessern, sobald neue Support-Themen auftauchen. Dies verursacht zwar mehr initialen Wartungsaufwand als das einfache Hinzufügen eines Stichpunkts zu einer FAQ-Liste, führt aber zu einer deutlich konsistenteren, professionelleren und nützlicheren Dokumentationsseite für Ihre Benutzer. --- ## [Verbesserung der Lesbarkeit](https://docs.docmd.io/de/07/guides/content-ux/improving-readability/) --- title: "Verbesserung der Lesbarkeit" description: "Wie Sie visuellen Rhythmus, Informationshierarchie und die strukturellen Werkzeuge von docmd nutzen, um hochgradig lesbare Dokumentationen zu erstellen." --- ## Problem Technische Dokumentationen sind oft dicht, fachsprachlich überladen und schwer zu scannen. Wenn Leser auf "Textwüsten" ohne visuelle Auflockerung stoßen, neigen sie dazu, wichtige Details zu überfliegen oder kritische Sicherheitswarnungen ganz zu übersehen. Eine dichte Formatierung erhöht die kognitive Belastung und führt zu Frustration beim Benutzer sowie potenziellen Fehlern. ## Warum es wichtig ist Lesbarkeit ist nicht nur eine ästhetische Entscheidung - sie ist eine funktionale Anforderung. Wenn ein Entwickler eine Warnung übersieht, weil sie in einem langen Absatz vergraben war, können die Folgen schwerwiegend sein. Eine klare Informationshierarchie stellt sicher, dass Benutzer die benötigten Informationen schnell finden, genau verstehen und sicher danach handeln können. ## Ansatz Etablieren Sie einen vorhersehbaren visuellen Rhythmus, indem Sie lange Textabschnitte aufbrechen und [thematische Container](../../content/containers/index.md) verwenden, um kritische Informationen hervorzuheben. Durch die Nutzung der integrierten strukturellen Werkzeuge von `docmd` können Sie eine Hierarchie erstellen, die das Auge des Lesers natürlich zu den wichtigsten Teilen der Seite führt. ## Implementierung ### 1. Die "Kraft der Kürze" Versuchen Sie, Absätze auf nicht mehr als drei oder vier Sätze zu beschränken. Kürzere Absätze sind auf Bildschirmen leichter zu erfassen und bieten natürlichen "Atemraum" für komplexe technische Konzepte. Wenn sich ein Absatz zu lang anfühlt, erwägen Sie, ihn in eine Liste aufzuteilen oder eine Unterüberschrift zu verwenden, um die Informationen neu zu kategorisieren. ### 2. Kategorisierung mit Callouts Verwenden Sie [Callouts](../../content/containers/callouts.md) konsistent, um Informationen zu kategorisieren. Dies ermöglicht es Benutzern, die den Text nur überfliegen, die Absicht eines Blocks anhand seines visuellen Stils sofort zu erkennen: * **Info**: Hintergrundkontext oder ergänzende Details, die ein tieferes Verständnis vermitteln. * **Tip**: Best Practices, Abkürzungen und "Pro-Tipps" für mehr Effizienz. * **Warning/Danger**: Kritische Aktionen, die zu Fehlern, Datenverlust oder Sicherheitsrisiken führen könnten. ```markdown ::: callout warning "Produktionssicherheit" Führen Sie diesen Befehl niemals an einer Live-Datenbank aus, ohne vorher Ihre Backups überprüft zu haben. ::: ``` ### 3. Sequenzielle Anweisungen mit Steps Vermeiden Sie bei Tutorials und Schritt-für-Schritt-Anleitungen narrative Beschreibungen von Aktionen. Verwenden Sie stattdessen den [Steps-Container](../../content/containers/steps.md), um einen klaren, nummerierten Ablauf zu erstellen, dem man leicht folgen kann. ```markdown ::: steps 1. **Initialisieren**: Führen Sie `npx @docmd/core init` im Projekt-Root aus. 2. **Konfigurieren**: Aktualisieren Sie Ihre `docmd.config.js` mit Ihrem Seitentitel und der Navigation. 3. **Build**: Führen Sie `npx @docmd/core build` aus, um Ihre produktionsreifen statischen Dateien zu generieren. ::: ``` ## Abwägungen Die Verwendung spezialisierter Container wie `::: steps` oder `::: callout` erfordert von den Mitwirkenden das Erlernen von `docmd`-spezifischen Markdown-Erweiterungen. Dies bedeutet zwar eine kleine Lernkurve, aber die signifikante Verbesserung der Informationsdichte, Klarheit und professionellen Präsentation überwiegt bei weitem den minimalen Aufwand für das Erlernen dieser leistungsstarken strukturellen Tags. --- ## [Navigation für große Sites](https://docs.docmd.io/de/07/guides/content-ux/navigation-large-sites/) --- title: "Navigation für große Sites" description: "So organisieren Sie komplexe Dokumentations-Sets in einer intuitiven, skalierbaren Navigationsstruktur unter Verwendung der Layout-Tools von docmd." --- ## Problem Wenn eine Dokumentations-Website von ein paar Dutzend Seiten auf Hunderte oder Tausende anwächst, verwandelt sich eine einfache Sidebar oft in ein verwirrendes Labyrinth aus tief verschachtelten Ordnern. Wenn Benutzer gezwungen sind, mehrere Hierarchieebenen aufzuklappen, nur um eine bestimmte Referenz zu finden, verlieren sie den Kontext, werden frustriert und geben die Dokumentation oft zugunsten von "Trial-and-Error" auf. ## Warum es wichtig ist Die Navigation ist die "Landkarte" der Funktionen Ihres Produkts. Wenn die Navigation schwer zu bedienen ist, verlassen sich die Benutzer ausschließlich auf die Suchleiste, was zu fragmentiertem Wissen führen kann. Ein gut strukturiertes Navigationssystem vermittelt dem Benutzer beim Durchsuchen die Logik und Taxonomie Ihres Produkts und hilft ihm, mit der Zeit kompetenter und eigenständiger zu werden. ## Ansatz Priorisieren Sie **Top-Level Context Switching** gegenüber tiefer Verschachtelung. Versuchen Sie, Ihre linke Sidebar auf maximal zwei oder drei Ebenen Tiefe zu beschränken. Nutzen Sie den horizontalen [Menübar](../../configuration/menubar), um verschiedene Dokumentations-"Domänen" (z. B. Anleitungen, API-Referenz und Community) voneinander zu trennen. Dies ermöglicht es jeder einzelnen Sidebar, fokussiert, relevant und übersichtlich zu bleiben. ## Implementierung ### 1. Domänenbasierte Trennung Verwenden Sie in Ihrer `docmd.config.js` den [Menübar](../../configuration/menubar), um Ihre Inhalte in übergeordnete Kategorien zu unterteilen. Dieser Ansatz ermöglicht es Ihnen, für jede Domäne eine völlig andere Sidebar anzuzeigen, was verhindert, dass ein einzelner Navigationsbaum überladen wird. ### 2. Flachhalten der Hierarchie Anstatt ein einzelnes Konzept auf viele winzige Markdown-Seiten aufzuteilen, sollten Sie verwandte Informationen in umfassenden übergeordneten Seiten konsolidieren. Verwenden Sie eine klare [Überschriften-Hierarchie](../../content/syntax), damit Benutzer innerhalb der Seite mithilfe des automatisch generierten Inhaltsverzeichnisses (TOC) auf der rechten Seite navigieren können. * **❌ Schlechte IA**: Ein Ordner namens "Sicherheit", der zehn separate Dateien mit jeweils nur einem Absatz für verschiedene Protokolle enthält. * **✅ Bessere IA**: Eine einzige, gut strukturierte Seite "Sicherheitsübersicht", die alle Protokolle abdeckt und Überschriften für ein sauberes Inhaltsverzeichnis nutzt. ### 3. Nutzung von einklappbaren Abschnitten Für große Gruppen verwandter Inhalte, auf die nicht ständig zugegriffen wird, verwenden Sie die Eigenschaft `collapsible` in Ihrer [Navigations-Konfiguration](../../configuration/navigation). Dies hält die Benutzeroberfläche sauber, indem sekundäre Informationen ausgeblendet werden, bis sie vom Benutzer explizit angefordert werden. ```json // navigation.json { "title": "API-Referenz", "collapsible": true, "collapsed": true, "children": [ { "title": "Authentifizierung", "path": "api/auth" }, { "title": "Endpunkte", "path": "api/endpoints" } ] } ``` ## Abwägungen Das Konsolidieren von Inhalten in weniger, längeren Seiten erfordert von den Autoren Disziplin in Bezug auf strukturelle Klarheit und die Verwendung von Überschriften. Wenn eine Seite ohne ordentliche interne Navigation (TOC) zu lang wird, kann sie selbst zu einer "Textwand" werden. Die deutliche Reduzierung von "Klick-Ermüdung" und das bessere Auffinden verwandter Inhalte machen eine flachere, domänenbasierte Hierarchie für große Dokumentations-Sets jedoch deutlich überlegen. --- ## [Skalierbares technisches Schreiben](https://docs.docmd.io/de/07/guides/content-ux/scalable-technical-writing/) --- title: "Skalierbares technisches Schreiben" description: "Wie Sie Progressive Disclosure (schrittweise Offenlegung) und strukturelle Container nutzen, um wachsende Dokumentationskomplexität zu bewältigen, ohne Ihre Benutzer zu überfordern." --- ## Problem In der Anfangsphase eines Produkts kann die Dokumentation einer Funktion nur wenige Absätze umfassen. Wenn sich das Produkt jedoch zu einer Unternehmensplattform entwickelt, können diese Absätze zu einem Meer aus Grenzfällen, plattformspezifischen Variationen (Docker, Kubernetes, Cloud) und komplexen Konfigurationsoptionen explodieren. Dies führt zu einem "vertikalen Aufblähen", bei dem eine einzelne Seite zu einer unlesbaren Textwüste wird, die schwer zu navigieren und zu warten ist. ## Warum es wichtig ist Vertikales Aufblähen zerstört das Verständnis und erhöht die kognitive Belastung. Wenn Benutzer gezwungen sind, durch seitenlange Inhalte zu scrollen, die für ihre spezifische Umgebung oder ihren Anwendungsfall irrelevant sind, werden sie überfordert und nehmen oft an, dass das Produkt komplexer ist, als es tatsächlich ist. Skalierbares Schreiben stellt sicher, dass Benutzer in jedem Moment nur die Informationen sehen, die sie benötigen, und bewahrt so einen klaren Weg zum Erfolg. ## Ansatz Implementieren Sie **Progressive Disclosure**. Diese Technik beinhaltet, nur die kritischsten Informationen vorab zu präsentieren (den "Happy Path") und komplexere, technische oder spezifischere Details hinter interaktiven UI-Strukturen zu verbergen. `docmd` bietet mehrere integrierte Container, die speziell entwickelt wurden, um Ihnen zu helfen, diese Komplexität effektiv und elegant zu bewältigen. ## Implementierung ### 1. Umgang mit Variationen durch Tabs Anstatt Anweisungen für mehrere Paketmanager, Betriebssysteme oder Cloud-Anbieter nacheinander aufzulisten, verwenden Sie den [Tabs-Container](../../content/containers/tabs.md). Dies ermöglicht es dem Benutzer, seine spezifische Umgebung auszuwählen, wodurch irrelevante Befehle sofort ausgeblendet und visuelles Rauschen reduziert wird. ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. Bewältigung von Grenzfällen mit Collapsibles Wenn ein Schritt zur Fehlerbehebung oder ein spezifischer Grenzfall nur für einen kleinen Prozentsatz der Benutzer gilt, lassen Sie ihn nicht den logischen Fluss Ihres Haupt-Tutorials unterbrechen. Verwenden Sie den [Collapsible-Container](../../content/containers/collapsible.md), um diese Details zu verbergen, während sie bei Bedarf leicht zugänglich bleiben. ```markdown 1. Starten Sie den Entwicklungsserver durch Ausführen von `npx @docmd/core dev`. ::: collapsible "Fehlerbehebung: Port wird bereits verwendet" Wenn Sie einen `EADDRINUSE`-Fehler erhalten, können Sie einen benutzerdefinierten Port mit dem `--port`-Flag angeben: `npx @docmd/core dev --port 4000`. ::: ``` ### 3. Progressive Details mit Callouts Verwenden Sie [Callouts](../../content/containers/callouts.md), um ergänzende Informationen bereitzustellen, die für die Hauptaufgabe nicht erforderlich sind, aber wertvollen Kontext für fortgeschrittene Benutzer bieten. ## Abwägungen Das Verbergen von Inhalten in Tabs oder Collapsibles kann es für Benutzer gelegentlich schwieriger machen, Informationen mithilfe der nativen `Strg+F`-Suche des Browsers zu finden. Die integrierte [Suchmaschine](../../plugins/search.md) von `docmd` indiziert jedoch alle Inhalte innerhalb dieser Container. So wird sichergestellt, dass Benutzer über die primäre Suchoberfläche der Website immer noch genau das finden, was sie brauchen, während sie gleichzeitig ein viel saubereres Leseerlebnis genießen. --- ## [Aufgabe vs. Konzept](https://docs.docmd.io/de/07/guides/content-ux/task-vs-concept/) --- title: "Aufgabe vs. Konzept" description: "So wenden Sie das Diátaxis-Framework an, um \"How-To\"-Anleitungen von konzeptionellen Erklärungen zu trennen und eine effektivere Dokumentationsstruktur aufzubauen." --- ## Problem Ein häufiger Fehler beim technischen Schreiben ist die Vermischung der Frage, *warum* etwas funktioniert, mit der Frage, *wie* man es tatsächlich umsetzt. Ein Tutorial zur "Konfiguration von SSO" kann beispielsweise leicht durch seitenlange Erklärungen zur Geschichte des SAML-Protokolls überladen werden, was den Benutzer von seinem unmittelbaren Ziel ablenkt, die Funktion zum Laufen zu bringen. ## Warum es wichtig ist Die Absicht des Benutzers variiert je nach aktuellem Kontext erheblich. Ein Entwickler, der nachts um 2 Uhr ein Problem in der Produktion beheben muss, sucht nach konkreten, umsetzbaren Schritten und nicht nach Architekturphilosophie. Umgekehrt muss ein technischer Leiter, der Ihre Plattform evaluiert, die zugrunde liegende Logik verstehen, bevor er sich auf eine Implementierung festlegt. Die Trennung dieser Aspekte stellt sicher, dass beide Personas die benötigten Informationen ohne unnötige Reibung finden. ## Ansatz Nutzen Sie das **Diátaxis-Framework**, das Dokumentation in vier Quadranten unterteilt: Tutorials, How-To-Anleitungen, Erklärungen (Konzepte) und technische Referenz. In diesem Leitfaden konzentrieren wir uns auf die kritische Trennung zwischen **aufgabenorientierten Inhalten** (umsetzbare Schritte) und **konzeptorientierten Inhalten** (tieferes Verständnis). ## Implementierung ### 1. Die aufgabenorientierte Anleitung (How-To) Konzentrieren Sie sich ganz auf ein spezifisches, eng gefasstes Ziel. Verzichten Sie auf langatmige theoretische Erklärungen und fokussieren Sie sich auf die minimalen Schritte, die zum Erreichen des Ziels erforderlich sind. Verwenden Sie den [Steps-Container](../../content/containers/steps), um einen klaren, unmissverständlichen Pfad aufzuzeigen. * **Titel-Beispiel**: "So konfigurieren Sie Webhooks" * **Struktur**: * Voraussetzungen * Direkte, umsetzbare Anweisungen * Verifizierungsschritte (Woran erkenne ich, dass es funktioniert hat?) ### 2. Die konzeptorientierte Anleitung (Erklärung) Konzentrieren Sie sich auf das "Big Picture", einschließlich Architektur, Designphilosophie und dem "Warum" hinter bestimmten Entscheidungen. Vermeiden Sie es, in diesen Abschnitten direkte Anweisungen oder Befehle zu geben. * **Titel-Beispiel**: "Die Webhook-Delivery-Architektur verstehen" * **Struktur**: * High-Level Architektur-Diagramme * Retry-Logik und Reliability-Philosophie * Sicherheitsaspekte ### 3. Effektive Querverweise Anstatt beide Inhaltsarten zu vermischen, nutzen Sie die Verlinkungs-Tools von `docmd`, um eine Brücke für Benutzer zu schlagen, die mehr Kontext benötigen oder bereit für die Implementierung sind. * **In einer How-To-Anleitung**: "Für tiefere Einblicke in unsere Retry-Logik lesen Sie [Webhook-Architektur](../../guides/performance-delivery/caching-strategies)." * **In einer konzeptionellen Anleitung**: "Bereit für den Start? Folgen Sie unserer [Anleitung zur Webhook-Konfiguration](../../guides/integrations/alongside-other-tools)." ## Abwägungen Die Trennung von Aufgaben und Konzepten erhöht die Anzahl der Seiten in Ihrer Navigation und erfordert eine konsequentere Verlinkung. Diese modulare Struktur verbessert jedoch die langfristige Wartbarkeit, Durchsuchbarkeit und die allgemeine Professionalität Ihrer Dokumentation erheblich. --- ## [Anpassen von Favicons und Metadaten](https://docs.docmd.io/de/07/guides/customisation/custom-favicons-metadata/) --- title: "Anpassen von Favicons und Metadaten" description: "So konfigurieren Sie die visuelle Identität Ihrer Website im Browser und optimieren die Vorschau in sozialen Medien." --- ## Problem Eine Standard-Dokumentationsseite hat im Browser oft keine eigene visuelle Identität (sie verwendet ein generisches Favicon) und bietet mangelhafte Vorschauen, wenn Links in sozialen Medien oder Kommunikationstools wie Slack und Discord geteilt werden. Dies verringert den Wiedererkennungswert der Marke und die Klickraten. ## Warum es wichtig ist Ihr Favicon ist der primäre visuelle Anker in einem überfüllten Browserfenster. Hochwertige OpenGraph- und Twitter-Metadaten stellen sicher, dass Ihre Dokumentation professionell und vertrauenswürdig aussieht, wenn sie geteilt wird, und bieten Kontext durch Titel, Beschreibungen und Hero-Images. ## Ansatz `docmd` bietet eine integrierte `favicon`-Eigenschaft für die einfache Konfiguration von Icons. Für fortgeschrittene SEO- und soziale Metadaten nutzen Sie das [SEO-Plugin](../../plugins/seo), das die Generierung von Meta-Tags basierend auf Ihrer Projektkonfiguration und dem Seiten-Frontmatter automatisiert. ## Implementierung ### 1. Konfiguration des Favicons Platzieren Sie Ihre Favicon-Datei (z. B. `favicon.svg` oder `favicon.ico`) in Ihrem Quellverzeichnis und referenzieren Sie diese in Ihrer `docmd.config.js`. `docmd` kümmert sich automatisch um die relativen Pfade und das Cache-Busting. ```javascript // docmd.config.js export default { title: 'Mein Projekt', favicon: '/favicon.svg' // Relativ zum Quellverzeichnis }; ``` ### 2. Globale SEO-Konfiguration Aktivieren und konfigurieren Sie das [SEO-Plugin](../../plugins/seo), um Standard-Vorschauen für Ihre gesamte Website festzulegen. ```javascript // docmd.config.js export default { url: 'https://docs.example.com', plugins: { seo: { defaultDescription: 'Der ultimative Leitfaden zu unserer fantastischen Software.', openGraph: { defaultImage: '/static/og-banner.png' }, twitter: { siteUsername: '@meinprojekt', cardType: 'summary_large_image' } } } }; ``` ### 3. Seitenspezifische Overrides Sie können die SEO-Einstellungen für einzelne Seiten über die Eigenschaft `seo` im [Frontmatter](../../content/frontmatter) überschreiben. ```yaml --- title: "Major Release v2.0" description: "Alles, was Sie über unsere neue Engine wissen müssen." seo: image: "/assets/v2-hero-banner.png" keywords: ["release", "v2", "update", "performance"] --- ``` ## Abwägungen Die `favicon`-Eigenschaft ist zwar praktisch, unterstützt jedoch nur eine einzelne Datei. Für komplexe Favicon-Sets mit mehreren Größen (Apple Touch Icons, Android Manifests usw.) müssen Sie möglicherweise ein eigenes Plugin verwenden, um zusätzliche `<link>`-Tags in den `<head>` einzufügen. --- ## [Benutzerdefinierte Schriftarten und Branding](https://docs.docmd.io/de/07/guides/customisation/custom-fonts-branding/) --- title: "Benutzerdefinierte Schriftarten und Branding" description: "So passen Sie das Erscheinungsbild Ihrer Dokumentation mithilfe von CSS-Variablen an Ihre Unternehmensidentität an." --- ## Problem Die nahtlose Anpassung Ihrer Dokumentationsplattform an Ihre Unternehmensidentität ist entscheidend für ein professionelles Erscheinungsbild. Die Standard-Schriftarten und Farbpaletten sind auf allgemeine Lesbarkeit ausgelegt, spiegeln jedoch möglicherweise nicht Ihre spezifische Markenpersönlichkeit wider. ## Warum es wichtig ist Die Dokumentation ist ein wichtiger Marken-Touchpoint. Wenn Ihr Hauptprodukt eine bestimmte Typografie (wie "Outfit") und eine markante Primärfarbe verwendet, sollte Ihre Dokumentation dieselben Entscheidungen widerspiegeln. Konsistenz über alle Ihre Web-Assets hinweg schafft Vertrauen und bietet eine kohärentere User Experience. ## Ansatz `docmd` verwendet ein System von CSS-Variablen (Custom Properties), die die visuellen Token des Layouts definieren. Sie können diese Variablen ganz einfach in einem benutzerdefinierten Stylesheet überschreiben, ohne die Core-Engine ändern zu müssen. ## Implementierung ### 1. Erstellen eines benutzerdefinierten Stylesheets Erstellen Sie eine Datei namens `custom.css` in Ihrem Quellverzeichnis (oder einem Unterverzeichnis) und überschreiben Sie die `:root`-Variablen. ```css /* Importieren Sie Ihre Markenschriftart */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* Marken-Typografie */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* Markenfarben (Light Mode) */ --link-color: #8a2be2; /* Ihre primäre Markenfarbe */ --link-color-hover: #7b1fa2; --bg-color: #fcfcfd; /* Dezente Hintergrundtönung */ } /* Overrides für Dark Mode */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. Registrieren des Stylesheets Fügen Sie Ihre benutzerdefinierte CSS-Datei dem Array `theme.customCss` in Ihrer `docmd.config.js` hinzu. ```javascript // docmd.config.js export default { theme: { customCss: ['/custom.css'] } }; ``` ## Abwägungen Das Importieren externer Schriftarten (z. B. von Google Fonts) führt zu einer geringfügigen Verzögerung beim ersten Laden der Seite. Um die Performance zu optimieren, sollten Sie in Erwägung ziehen, Ihre Schriftdateien lokal in Ihrem Projekt zu hosten und `font-display: swap` zu verwenden, um ein "Flackern von unformatiertem Text" (FOUT) während des Ladens zu verhindern. --- ## [Gestaltung von benutzerdefinierten Landing-Pages](https://docs.docmd.io/de/07/guides/customisation/custom-landing-pages/) --- title: "Gestaltung von benutzerdefinierten Landing-Pages" description: "So nutzen Sie die Hero- und Grid-Container von docmd, um hochwertige Landing-Pages für Ihre Dokumentation zu erstellen." --- ## Problem Standardmäßig sieht die `index.md`-Datei in den meisten Dokumentationsgeneratoren wie eine gewöhnliche technische Seite aus. Die Erstellung einer wirkungsvollen Landing-Page in Marketing-Qualität erfordert normalerweise ein separates Web-Framework (wie Next.js oder Astro), was den Dokumentations-Workflow verkompliziert. ## Warum es wichtig ist Die Startseite Ihrer Dokumentation ist oft der erste Kontakt eines Entwicklers mit Ihrem Produkt. Eine generische, aus Markdown geparste Seite kann das Vertrauen in die Professionalität und Qualität Ihres Projekts mindern. Eine benutzerdefinierte Landing-Page kann Benutzer gezielter zu den wichtigsten Abschnitten führen und gleichzeitig die visuelle Identität Ihrer Marke stärken. ## Ansatz `docmd` bietet spezialisierte [Hero](../../content/containers/hero.md)- und [Grid](../../content/containers/grids.md)-Container, die speziell für den Aufbau hochwertiger Landing-Pages entwickelt wurden. Für vollständige kreative Freiheit können Sie auch die Frontmatter-Eigenschaft `noStyle` verwenden, um die volle Kontrolle über HTML und Styling einer Seite zu übernehmen. ## Implementierung ### 1. Verwendung des Hero-Containers Der `hero`-Container unterstützt verschiedene Layouts, darunter `split` (für Side-by-side-Inhalte) und `glow` (für eine moderne Ästhetik). ```markdown ::: hero layout:split glow:true # Schneller aufbauen mit docmd Die Zero-Config Documentation Engine für moderne Entwicklerteams. [Erste Schritte](../../getting-started/quick-start.md) [Auf GitHub ansehen](https://github.com/docmd-io/docmd) == side ![Dashboard Vorschau](../../static/img/hero-preview.png) ::: ``` ### 3. Inhalte mit Grids organisieren Nutzen Sie [Grids und Cards](../../content/containers/grids.md), um übergeordnete Navigationsbereiche zu erstellen, die den Benutzern helfen, schnell zu finden, was sie suchen. ```markdown ::: grids ::: grid ::: card "Quick Start" icon:rocket In weniger als 5 Minuten einsatzbereit. [Mehr erfahren](../../getting-started/quick-start.md) ::: ::: ::: grid ::: card "API Referenz" icon:code Umfassende Dokumentation für alle unsere Endpunkte. [API erkunden](../../api/node-api.md) ::: ::: ::: ``` ### 3. Vollständige Anpassung mit noStyle Wenn Sie ein komplett individuelles Design benötigen, das das Standard-Layout (ohne Sidebar oder Header) ignoriert, verwenden Sie die Eigenschaft `noStyle` im [Seiten-Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Benutzerdefiniertes Dashboard" noStyle: true --- ``` Wenn `noStyle: true` gesetzt ist, rendert `docmd` nur den von Ihnen bereitgestellten rohen HTML/Markdown-Inhalt. Dies ermöglicht es Ihnen, eigenes CSS und JavaScript für ein pixelgenaues Erlebnis einzubinden. ## Abwägungen Die Verwendung von `noStyle: true` bedeutet, dass Sie auf die nativen Funktionen für Navigation, Suche und Theme-Umschaltung von `docmd` verzichten. Sie sind selbst dafür verantwortlich, dass die benutzerdefinierte Seite responsiv und barrierefrei ist. In den meisten Fällen bietet die Kombination aus `hero`- und `grid`-Containern innerhalb des Standard-Layouts die beste Balance zwischen Ästhetik und Funktionalität. --- ## [docmd mit benutzerdefinierten Plugins erweitern](https://docs.docmd.io/de/07/guides/customisation/extending-custom-plugins/) --- title: "docmd mit benutzerdefinierten Plugins erweitern" description: "So nutzen Sie die Lifecycle-Hooks von docmd, um eigene Funktionen zu erstellen und die Dokumentations-Engine zu erweitern." --- ## Problem Manchmal haben Sie eine sehr spezifische Anforderung, die nicht durch integrierte Funktionen oder vorhandene Plugins abgedeckt wird. Beispielsweise müssen Sie während des Build-Prozesses Daten von einer internen API abrufen oder komplexe Transformationen am generierten HTML vornehmen, die über einfaches CSS hinausgehen. ## Warum es wichtig ist Erweiterbarkeit ist das, was ein statisches Tool von einem professionellen Dokumentations-Framework unterscheidet. Ohne eine saubere Möglichkeit, eigene Logik einzufügen, sind Teams oft gezwungen, fragile Shell-Skripte oder Post-Processing-Wrapper zu pflegen, was den Build-Prozess schwer verwaltbar und fehleranfällig macht. ## Ansatz `docmd` verfügt über eine robuste, Hook-basierte [Plugin-API](../../plugins/api). Sie können einfache Node.js-Module schreiben, die den Dokumentations-Lifecycle in verschiedenen Phasen abfangen , von der initialen Konfiguration bis zur finalen HTML-Generierung , und so Inhalte und Verhalten beliebig anpassen. ## Implementierung ### 1. Erstellen eines lokalen Plugins Ein Plugin ist ein Standard-JavaScript-Modul, das einen Deskriptor und mehrere Lifecycle-Hooks exportiert. ```javascript // plugins/version-injector.js export default { // Plugin-Metadaten plugin: { name: 'version-injector', version: '1.0.0', capabilities: ['build'] // Erforderlich, um 'build'-Hooks zu nutzen }, // Status, der zwischen Hooks geteilt wird latestVersion: '0.0.0', // Wird ausgeführt, sobald die Konfiguration aufgelöst wurde async onConfigResolved(config) { // Daten von einer internen API abrufen const response = await fetch('https://api.internal.com/version'); this.latestVersion = await response.text(); console.log(`[Plugin] Version abgerufen: ${this.latestVersion}`); }, // Abfangen des Seitenkontexts vor dem Template-Rendering async onBeforeRender(page) { if (!page.html) return; // Platzhalter durch dynamische Daten in HTML und Frontmatter ersetzen page.html = page.html.replace(/\{\{VERSION\}\}/g, this.latestVersion); page.frontmatter.computedVersion = this.latestVersion; } }; ``` ### 2. Registrieren des Plugins Sie können Ihr lokales Plugin registrieren, indem Sie es in Ihre `docmd.config.js` importieren. ```javascript // docmd.config.js import VersionInjector from './plugins/version-injector.js'; export default { title: 'Meine Projekt-Docs', plugins: { // Registrierung durch Angabe des importierten Moduls 'version-injector': VersionInjector } }; ``` ## Abwägungen Benutzerdefinierte Plugins laufen während des Builds in der Node.js-Umgebung. Sie sind zwar leistungsstark, können aber die Build-Performance beeinträchtigen, wenn sie nicht optimiert sind. Jede Logik in Hooks wie `onAfterParse` oder `onPageReady` wird für *jede* Seite Ihrer Website ausgeführt. Stellen Sie sicher, dass Ihre Transformationen effizient sind (z. B. durch optimierte Regex), um die Build-Zeiten kurz zu halten. --- ## [Neben anderen Tools](https://docs.docmd.io/de/07/guides/integrations/alongside-other-tools/) --- title: "Neben anderen Tools" description: "Strategien zur Integration von docmd in ein Multi-Tool-Dokumentations-Ökosystem, um eine nahtlose User Experience zu schaffen." --- ## Problem Große Organisationen nutzen selten ein einziges Tool für all ihre Dokumentationsanforderungen. Ihr Unternehmen verwendet vielleicht Confluence für interne Spezifikationen, Stoplight für das API-Design und GitHub für Codebeispiele. Die Integration dieser unterschiedlichen Quellen in eine einheitliche User Journey ist eine große Herausforderung, da sich Benutzer oft zwischen getrennten Portalen mit unterschiedlichen Stilen und Navigationsstrukturen wiederfinden. ## Warum es wichtig ist Eine fragmentierte Dokumentationserfahrung schadet dem Vertrauen der Entwickler und erhöht die kognitive Belastung. Wenn ein Benutzer gezwungen ist, zwischen völlig unterschiedlichen Oberflächen zu wechseln, nur um einem Tutorial zu folgen, verliert er eher den Kontext oder gibt Ihr Produkt ganz auf. Die Vereinheitlichung Ihrer Tools gewährleistet eine professionelle, zusammenhängende Erfahrung, die zum Erkunden und Lernen einlädt. ## Ansatz Nutzen Sie `docmd` als Ihren primären Dokumentations-Hub oder "Single Pane of Glass". Durch die Verwendung des [Menübars](../../configuration/menubar) für eine einheitliche Navigation und von [Embed-Containern](../../content/containers/embed) für Drittanbieter-Inhalte können Sie eine nahtlose Oberfläche schaffen, welche die Komplexität Ihrer Multi-Tool-Infrastruktur verbirgt. ## Implementierung ### 1. Einheitliche globale Navigation Verwenden Sie die `menubar`-Konfiguration, um Ihre verschiedenen Dokumentationsportale miteinander zu verknüpfen. Dies stellt sicher, dass Benutzer immer den Weg zurück zu den Hauptanleitungen finden, unabhängig davon, auf welcher Subdomain sie sich gerade befinden. ```javascript // docmd.config.js export default { layout: { menubar: { left: [ { text: 'Anleitungen', url: '/' }, // docmd-Seite { text: 'API-Referenz', url: 'https://api.example.com' }, // Externes Tool { text: 'Community', url: 'https://forum.example.com', external: true } ] } } }; ``` ### 2. Nahtloses Embedding Für Tools, die eine Weboberfläche bieten (wie interaktive API-Explorer oder Dashboard-Vorschauen), verwenden Sie den `::: embed`-Container, um diese direkt in Ihren `docmd`-Seiten anzuzeigen. Dies hält die Benutzer innerhalb Ihrer markengerechten Umgebung. ```markdown # Interaktiver API-Explorer ::: embed "https://api.example.com/v1/explorer" ::: ``` Weitere Informationen finden Sie in der [Embed-Referenz](../../content/containers/embed). ### 3. Inhaltsaggregation Für externe Inhalte, die zusammen mit Ihrer Kerndokumentation durchsuchbar sein müssen, sollten Sie einen Build-Schritt in Betracht ziehen, der Daten aus anderen Quellen abruft und in Markdown umwandelt. Dies ermöglicht es `docmd`, all Ihre Informationen in einem einzigen, einheitlichen [Suchindex](../../plugins/search) zu erfassen. ## Abwägungen Während das Einbetten einen einheitlichen Look bietet, kann es gelegentlich Performance-Overhead oder Probleme mit verschachtelten Scrollbalken auf mobilen Geräten verursachen. Zudem werden Inhalte innerhalb eines Iframes nicht nativ von der `docmd`-Suchmaschine indiziert. Wenn die Durchsuchbarkeit aller Inhalte kritisch ist, wird die Priorisierung von [OpenAPI-Generierung](./openapi-generation) oder anderen Markdown-basierten Ingestion-Methoden empfohlen. --- ## [Vorhandene Markdown-Repos](https://docs.docmd.io/de/07/guides/integrations/existing-markdown-repos/) --- title: "Vorhandene Markdown-Repos" description: "So generieren Sie aus Ihren vorhandenen Markdown-Dateien sofort eine professionelle Dokumentations-Website , ganz ohne Konfiguration." --- ## Problem Sie verfügen über ein bestehendes Repository mit hunderten oder tausenden von Markdown-Dateien , vielleicht ein altes Wiki, ein Obsidian-Vault oder eine Sammlung technischer Notizen. Das manuelle Konvertieren von Frontmatter, das Reparieren fehlerhafter Links und das Umstrukturieren von Dateien für eine neue Engine ist eine gewaltige Aufgabe, die Teams oft davon abhält, ihre Dokumentation zu modernisieren. ## Warum es wichtig ist Ihre Inhalte sollten portabel und tool-unabhängig bleiben. Eine hochwertige Dokumentations-Engine sollte sich an Ihre vorhandenen Dateien anpassen und nicht Ihre Dateien dazu zwingen, sich an die Engine anzupassen. Die Vermeidung von Vendor-Lock-in stellt sicher, dass Ihr geistiges Eigentum standardisiert, lesbar und zukunftssicher bleibt. ## Ansatz `docmd` hält sich an strikte CommonMark-Spezifikationen und ist standardmäßig auf **Zero-Config** ausgelegt. Sie können die `docmd`-CLI auf ein beliebiges Verzeichnis mit Markdown-Dateien richten, und sie wird intelligent eine voll funktionsfähige Dokumentations-Website erstellen, ohne auch nur eine einzige Zeile Ihres Quellinhalts zu verändern. ## Implementierung ### 1. Sofortiges Bootstrapping Navigieren Sie zu Ihrem vorhandenen Markdown-Ordner und starten Sie den Entwicklungsserver. `docmd` scannt Ihre Verzeichnisstruktur und erstellt sofort eine funktionale Website im Arbeitsspeicher. ```bash cd meine-vorhandenen-docs/ npx @docmd/core dev ``` ### 2. Automatische Navigation (Auto-Router) Wenn keine `navigation.json` oder `docmd.config.js` gefunden wird, aktiviert `docmd` seinen [Auto-Router](../../configuration/navigation#automatic-sidebar-generation). Dieser bildet Ihre Ordnerstruktur rekursiv ab, verschönert Verzeichnisnamen (z. B. wird aus `getting-started` "Getting Started") und generiert automatisch eine logische Sidebar-Taxonomie. ### 3. Intelligente Titel-Ermittlung Sie müssen nicht jeder Datei ein `title`-Frontmatter hinzufügen. `docmd` nutzt eine kaskadierende Strategie zur Ermittlung von Seitentiteln: 1. **Frontmatter**: Prüft auf einen `title`- oder `h1`-Key. 2. **Erste Überschrift**: Extrahiert die erste gefundene `# Überschrift` aus dem Dateiinhalt. 3. **Dateiname**: Verschönert den Dateinamen als Fallback (z. B. wird aus `install-guide.md` "Install Guide"). ### 4. Resiliente Syntax-Verarbeitung `docmd` ist auf Resilienz ausgelegt. Wenn Ihre vorhandenen Dateien proprietäre Syntax oder veraltete Shortcodes von anderen Engines enthalten, werden diese sicher als Rohtext gerendert oder übersprungen. Dies stellt sicher, dass Ihr Build niemals aufgrund von Inhalten fehlschlägt, die Sie noch nicht migriert haben. ## Abwägungen Automatisch generierte Sidebars werden in der Regel alphabetisch nach Dateinamen sortiert. Während Dateinamen wie `01-intro.md` und `02-setup.md` gut funktionieren, können rein beschreibende Dateinamen in einer nicht intuitiven Reihenfolge erscheinen. Für produktionsreife Websites empfehlen wir den Übergang zu einer manuellen [Navigations-Konfiguration](../../configuration/navigation), um die volle Kontrolle über die User Journey zu erhalten. --- ## [GitHub Actions CI/CD](https://docs.docmd.io/de/07/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "So automatisieren Sie Ihre Dokumentations-Builds und -Deployments mit GitHub Actions und docmd für einen hocheffizienten Dokumentations-Workflow." --- ## Problem Das manuelle Bauen und Bereitstellen von Dokumentationen von einem lokalen Rechner aus ist anfällig für Fehler, Umgebungsinkonsistenzen (z. B. unterschiedliche Node.js-Versionen) und Sicherheitsrisiken. Zudem entsteht ein Flaschenhals, da Deployments von der Verfügbarkeit und dem lokalen Setup einer einzelnen Person abhängen. ## Warum es wichtig ist Continuous Deployment (CD) stellt sicher, dass Ihre Dokumentation immer synchron mit Ihrer Software ist. Wenn ein technisches Update gemergt wird, sollte es Ihre Benutzer innerhalb von Minuten erreichen, nicht erst nach Tagen. Automatisierung garantiert, dass jeder Build in einer sauberen, reproduzierbaren Umgebung stattfindet, was hohe Qualitäts- und Zuverlässigkeitsstandards wahrt. ## Ansatz Nutzen Sie GitHub Actions, um die `docmd`-Build-Pipeline bei jedem Push oder Pull Request auszuführen. Die resultierenden statischen Assets können dann automatisch auf Hosting-Providern wie GitHub Pages, Cloudflare Pages oder in containerisierten Umgebungen mit Docker bereitgestellt werden. ## Implementierung ### 1. Standard-Workflow für GitHub Pages Erstellen Sie `.github/workflows/docs.yml`, um den Build- und Deployment-Prozess zu automatisieren. ```yaml name: Docs bereitstellen on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # Baut die Seite in das Verzeichnis 'site/' - run: npx @docmd/core build - name: Artefakt hochladen uses: actions/upload-pages-artifact@v3 with: path: site/ - name: Auf GitHub Pages bereitstellen uses: actions/deploy-pages@v4 ``` ### 2. Containerisiertes Deployment (Docker) Wenn Sie Ihre Dokumentation selbst hosten, verwenden Sie den [Deploy-Befehl](../../deployment), um ein produktionsreifes `Dockerfile` und Serverkonfigurationen zu generieren. ```bash # Docker- und Nginx-Configs lokal generieren npx @docmd/core deploy --docker --nginx ``` Sie können dann Ihre GitHub Action aktualisieren, um dieses Docker-Image zu bauen und bei jedem Release in eine Registry (wie Docker Hub oder GitHub Container Registry) zu pushen. ### 3. Pull Request Previews Verbessern Sie Ihren Workflow, indem Sie für jeden Pull Request kurzlebige Preview-Umgebungen generieren. Dies ermöglicht es Reviewern, die gerenderte Dokumentation zu sehen, bevor sie in den Hauptzweig gemergt wird. Weitere Details finden Sie im [Leitfaden zum Vorschauen von Änderungen](../workflows-teams/previewing-changes). ## Abwägungen Automatisiertes CI/CD erfordert initialen Setup-Aufwand und die Verwaltung von Secrets (z. B. API-Tokens). Die langfristigen Vorteile eines automatisierten Deployment-Prozesses , darunter weniger menschliche Fehler und schnellere Update-Zyklen , überwiegen jedoch bei weitem die Anfangsinvestition. Stellen Sie bei großen Sites sicher, dass Ihr Workflow nur ausgelöst wird, wenn Dateien in Ihrem Dokumentationsverzeichnis geändert wurden, um CI-Minuten zu sparen. --- ## [OpenAPI-Generierung](https://docs.docmd.io/de/07/guides/integrations/openapi-generation/) --- title: "OpenAPI-Generierung" description: "So integrieren Sie OpenAPI/Swagger-Schemas in Ihren docmd-Workflow für eine automatisierte und synchronisierte API-Referenzdokumentation." --- ## Problem Die manuelle Pflege einer REST-API-Dokumentation stellt ein erhebliches betriebliches Risiko dar. In dem Moment, in dem ein Entwickler einen Endpunkt ändert oder ein Schema im Code aktualisiert, veraltet die Dokumentation. Diese manuell synchron zu halten, ist mühsam, fehleranfällig und führt häufig zu Integrationsfehlern bei Ihren API-Konsumenten. ## Warum es wichtig ist Ungenaue API-Referenzen sind eine Hauptursache für Frustration bei Entwicklern und erhöhte Support-Tickets. Die Automatisierung stellt sicher, dass Ihre Dokumentation die "Source of Truth" (einzige Quelle der Wahrheit) bleibt und den tatsächlichen Zustand Ihrer API in Echtzeit (oder bei jedem Build) widerspiegelt. Dies ermöglicht es Entwicklern, sich auf das Erstellen von Funktionen zu konzentrieren, anstatt Dokumentationstabellen manuell zu aktualisieren. ## Ansatz Implementieren Sie eine asynchrone Build-Pipeline, die Ihr `openapi.json`- oder `swagger.yaml`-Schema in Standard-Markdown-Dateien konvertiert. Da `docmd` hervorragend darin ist, Markdown mit komplexen [Containern](../../content/containers/index.md) zu rendern, fühlt sich die resultierende API-Referenz integriert und visuell konsistent mit dem Rest Ihrer Dokumentation an. ## Implementierung ### 1. Build-Pipeline-Integration Sie können ein Tool wie `widdershins` oder ein benutzerdefiniertes Skript verwenden, um Markdown aus Ihrem OpenAPI-Schema als Pre-Build-Schritt in Ihrer CI/CD-Pipeline zu generieren. ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. Optimierung von API-Layouts API-Referenzen sind oft inhaltsdicht, mit großen Tabellen für Parameter und verschachtelten Schemas. Verwenden Sie [Frontmatter](../../content/frontmatter.md), um das Seitenlayout für eine bessere Lesbarkeit zu optimieren. ```markdown --- title: "REST-API-Referenz" layout: "full" # Maximiert den horizontalen Platz für dichte Tabellen --- ``` Durch das Setzen von `layout: "full"` wird die rechte Seitenleiste mit dem Inhaltsverzeichnis entfernt, wodurch mehr Platz für breite Codeblöcke und Antwortbeispiele entsteht. ### 3. Erweiterung mit docmd-Containern Sie können das generierte Markdown nachbearbeiten, um `docmd`-Funktionen wie [Tabs](../../content/containers/tabs.md) für mehrsprachige Codebeispiele oder [Callouts](../../content/containers/callouts.md) für Authentifizierungswarnungen einzufügen. ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## Abwägungen Maschinell generierte Dokumentationen eignen sich hervorragend für technische Genauigkeit, lassen aber oft die "menschliche Note" vermissen, die für effektives Lernen erforderlich ist. Wir empfehlen, die OpenAPI-Generierung für die **technische Referenz** (Endpunkte, Parameter, Schemas) zu verwenden, während Sie handgeschriebene **Tutorials** und **konzeptionelle Leitfäden** bereitstellen, um den Kontext und die Anwendungsfälle für Ihre API zu erläutern. --- ## [Caching-Strategien](https://docs.docmd.io/de/07/guides/performance-delivery/caching-strategies/) --- title: "Caching-Strategien" description: "So optimieren Sie die Performance Ihrer Dokumentations-Website durch Immutable Caching, Etag-Revalidierung und produktionsreife Serverkonfigurationen." --- ## Problem Wenn eine Dokumentations-Website ohne ordnungsgemäße `Cache-Control`-Header bereitgestellt wird, laden Browser bei jedem Besuch unnötigerweise Bilder, CSS- und JavaScript-Bundles erneut herunter. Dies führt zu visuellem Ruckeln, erhöhtem Bandbreitenverbrauch und einer schlechten Erfahrung für wiederkehrende Benutzer, die erwarten, dass die Dokumentation sofort geladen wird. ## Warum es wichtig ist Effektives Caching ist einer der wirkungsvollsten Wege, um die "gefühlte Performance" Ihrer Website zu verbessern. Indem Sie sicherstellen, dass statische Assets lokal im Browser des Benutzers gespeichert werden, eliminieren Sie die Latenz wiederholter Netzwerkanfragen. Dadurch fühlt sich das Navigieren in Ihrer Dokumentation flüssig und zuverlässig an, selbst bei instabilen Netzwerkverbindungen. ## Ansatz Implementieren Sie eine zweistufige Caching-Strategie: **Immutable Caching** für statische Assets (CSS, JS, Bilder) und **Etag-Revalidierung** für dynamische Inhalte (HTML, JSON). `docmd` erleichtert dies durch die Generierung produktionsreifer Konfigurationen, die das Cache-Busting automatisch über Versions-Hashes abwickeln. ## Implementierung ### 1. Produktionsreife Server-Konfigurationen Der einfachste Weg, optimales Caching zu implementieren, ist die Verwendung des [Deploy-Befehls](../../deployment) zur Generierung Ihrer Serverkonfiguration. ```bash # Generieren einer optimierten Nginx-Konfiguration npx @docmd/core deploy --nginx ``` ### 2. Immutable Assets Für Assets, die sich nicht häufig ändern (wie Theme-Styles und Kern-Skripte), verwenden Sie langfristiges Caching. `docmd` fügt diesen Assets Versions-Hashes hinzu, um sicherzustellen, dass Benutzer neue Versionen nur dann herunterladen, wenn Sie Ihre Dokumentation aktualisieren. ```nginx # Beispiel einer Nginx-Regel für Immutable Assets location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML- & Navigations-Revalidierung Ihre HTML-Dateien und die `navigation.json` sollten immer auf Updates geprüft werden, damit Benutzer sofort den neuesten Inhalt und die aktuelle Struktur sehen. Verwenden Sie die Anweisung `no-cache`, um den Browser zu zwingen, die Gültigkeit beim Server mittels Etags zu validieren. ```nginx # Beispiel einer Nginx-Regel für HTML-Dateien location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## Abwägungen ### Veralteter Inhalt vs. Performance Die Einstellung langer Cache-Zeiten für Assets ist hochperformant, erfordert jedoch eine robuste "Cache-Busting"-Strategie. `docmd` übernimmt dies automatisch für seine Kerndateien. Wenn Sie jedoch manuell Assets zu Ihrem `static/`-Verzeichnis hinzufügen, müssen Sie sicherstellen, dass Sie deren Referenzen aktualisieren (z. B. durch Ändern des Dateinamens oder Hinzufügen eines Query-Parameters), wenn sich der Inhalt ändert. ### CDN-Integration Wenn Sie ein CDN (wie Cloudflare oder AWS CloudFront) verwenden, stellen Sie sicher, dass dieses so konfiguriert ist, dass es die `Cache-Control`-Header Ihres Servers berücksichtigt. Die meisten modernen CDNs bieten "Instant Purge"-Funktionen an. Wir empfehlen, diese als Teil Ihrer CI/CD-Pipeline auszulösen, wann immer Sie eine neue Version Ihrer Dokumentation bereitstellen. --- ## [CDN- & Edge-Deployment](https://docs.docmd.io/de/07/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN- & Edge-Deployment" description: "So minimieren Sie die globale Latenz, indem Sie Ihre statische Dokumentation auf einem Content Delivery Network (CDN) oder Edge-Netzwerk bereitstellen." --- ## Problem Das Hosting Ihrer Dokumentation auf einem einzelnen Server in einer geografischen Region (z. B. US-East) bedeutet, dass Benutzer in anderen Teilen der Welt (z. B. Europa oder Asien) eine erhebliche Netzwerklatenz erfahren. Jeder Seitenaufruf, jedes Bild und jedes Skript muss Tausende von Kilometern zurücklegen, wodurch sich Ihre Dokumentation für ein globales Publikum träge und langsam anfühlt. ## Warum es wichtig ist Hohe Latenz schadet direkt der Developer Experience. Selbst wenn Ihre Dokumentation gut geschrieben und leichtgewichtig ist, wird die "Time to First Byte" (TTFB) durch die Gesetze der Physik begrenzt. Wenn sich Ihre Website langsam anfühlt, verlieren Entwickler eher den Fokus oder geben Ihr Tool ganz zugunsten eines anderen mit schnellerer, besser zugänglicher Dokumentation auf. ## Ansatz Die optimale Lösung besteht darin, Ihre Website auf einem Edge-CDN bereitzustellen. Da `docmd` rein statische Assets generiert (HTML, CSS, JS), ist es perfekt für die Verteilung über Edge-Netzwerke geeignet. CDNs replizieren Ihre Dateien auf Hunderte von weltweit verteilten "Edge-Nodes" und bedienen Ihre Benutzer vom nächstgelegenen Rechenzentrum aus. ## Implementierung ### 1. Plattform wählen `docmd` ist nativ kompatibel mit allen modernen statischen Hosting- und Edge-Plattformen. Wir empfehlen die folgenden aufgrund ihrer globalen Performance und einfachen Handhabung: * **Cloudflare Pages**: Extrem schnelles globales Edge-Netzwerk mit integriertem DDoS-Schutz. * **Vercel**: Optimiert für Performance mit exzellenter Integration in den Entwickler-Workflow. * **Netlify**: Leistungsstarke Automatisierungsfunktionen und ein robustes globales CDN. ### 2. Build automatisieren Verwenden Sie eine CI/CD-Pipeline, um Ihre Website automatisch zu erstellen und bereitzustellen, wann immer Sie Änderungen pushen. Detaillierte Beispiele finden Sie im [GitHub Actions Leitfaden](../../guides/integrations/github-actions-cicd). ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # Buildet die Website in das Standard-Verzeichnis 'site/' - run: npm install && npx @docmd/core build # Beispiel: Deployment auf Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: mein-projekt directory: site ``` ### 3. Verifizierung Nach dem Deployment können Sie Ihre globale Performance mit Tools wie PageSpeed Insights oder globalen Ping-Tests überprüfen. Sie sollten Antwortzeiten unter 100 ms von fast jedem Standort weltweit sehen. ## Abwägungen Globale Edge-Netzwerke nehmen Ihnen das Server-Management ab, was ein großer Vorteil für Dokumentationsteams ist. Das Debuggen regionaler Caching-Probleme kann jedoch gelegentlich komplexer sein als das Überprüfen eines einzelnen Server-Logs. Die Verwendung von Plattformen mit robuster "sofortiger Cache-Invalidierung" stellt sicher, dass Ihre Benutzer unmittelbar nach einem Deployment immer die neueste Version Ihrer Dokumentation sehen. --- ## [Optimierung für Low-End-Geräte](https://docs.docmd.io/de/07/guides/performance-delivery/low-end-devices/) --- title: "Optimierung für Low-End-Geräte" description: "So erstellen Sie leistungsstarke, barrierefreie Dokumentationen, die auf schwächerer Hardware und bei langsamen Netzwerkverbindungen nahtlos funktionieren." --- ## Problem Moderne Dokumentations-Websites verlassen sich oft auf schwere JavaScript-Runtimes, nur um statischen Text anzuzeigen. Für Benutzer mit älteren Mobiltelefonen, günstigen Laptops oder langsamen 3G/4G-Verbindungen kann das Laden dieser Seiten mehrere Sekunden dauern. Der Prozessor des Geräts hat Mühe, große JS-Bundles zu verarbeiten, was zu "Input-Lag", ruckelnden Animationen und einem insgesamt schlechten Leseerlebnis führt. ## Warum es wichtig ist Technische Dokumentationen sollten universell zugänglich sein. Wenn Benutzer in Schwellenländern oder mit eingeschränkter Hardware gezwungen sind, ein schweres Framework herunterzuladen und auszuführen, nur um ein Tutorial zu lesen, schafft dies eine unnötige Hürde beim Lernen. Eine leichtgewichtige Website stellt sicher, dass Ihre Produktinformationen für jeden verfügbar sind, unabhängig von der Hardware oder Internetgeschwindigkeit. ## Ansatz Setzen Sie auf eine **HTML-First-Strategie**. `docmd` ist mit einer Zero-Framework-Architektur konzipiert, die sicherstellt, dass der primäre Inhalt während des Build-Prozesses in Standard-HTML gerendert wird. Dies hält den Hauptthread des Browsers frei und gewährleistet flüssiges Scrollen sowie eine schnelle Navigation, selbst auf Budget-Geräten. ## Implementierung ### 1. Minimaler Runtime-Footprint Standardmäßig verwendet `docmd` weder React, Vue noch ein anderes schweres clientseitiges Framework für seine Kern-UI. Dieser vorgerenderte Ansatz stellt sicher, dass der erste "First Contentful Paint" fast sofort erfolgt. Um diese Performance beizubehalten: * **Eigene Skripte begrenzen**: Vermeiden Sie das Hinzufügen großer Drittanbieter-Bibliotheken in Ihrer `customJs`-Konfiguration. * **Native Browser-Funktionen nutzen**: Verlassen Sie sich auf Standard-CSS und HTML5-Elemente, die von allen modernen Browsern hochgradig optimiert sind. ### 2. Strategisches Plugin-Management Während [Plugins](../../plugins/usage) leistungsstarke Funktionen hinzufügen, können sie einen erheblichen Performance-Overhead verursachen. Zum Beispiel benötigt das [Mermaid-Plugin](../../plugins/mermaid) eine große Engine, um Diagramme zu rendern. Wenn Ihre Benutzer hauptsächlich Low-End-Geräte verwenden, sollten Sie statische Bilder für Diagramme anstelle von clientseitigem Rendering in Betracht ziehen. ### 3. Responsive und optimierte Medien Vermeiden Sie es, übergroße Bilder an mobile Benutzer auszuliefern. Verwenden Sie moderne Formate wie WebP und nutzen Sie das `<picture>`-Tag für eine granulare Kontrolle über responsive Assets. ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="Feature-Übersicht" loading="lazy"> </picture> ``` Die Verwendung des Attributs `loading="lazy"` stellt sicher, dass Bilder erst heruntergeladen werden, wenn sie in den Viewport des Benutzers gelangen, was Bandbreite bei langsamen Verbindungen spart. ### 4. Effiziente Suchindexierung `docmd` generiert "gescopte" Suchindizes, um den Speicherbedarf gering zu halten. Bei extrem großen Websites kann das [Search-Plugin](../../plugins/search) jedoch weiterhin speicherintensiv sein. Ermutigen Sie mobile Benutzer, die Suchleiste nur bei Bedarf zu verwenden, oder optimieren Sie Ihren Index, wie im [Local-First Suchleitfaden](../search/local-first-search) beschrieben. ## Abwägungen Die Priorisierung der Performance für Low-End-Geräte bedeutet oft, auf "schwere" interaktive Funktionen wie komplexe 3D-Visualisierungen oder große clientseitige Datenverarbeitung zu verzichten. Dies ist eine bewusste Designentscheidung, die **Inklusivität und Geschwindigkeit** über visuelle Komplexität stellt und sicherstellt, dass Ihre Dokumentation für ein möglichst breites Publikum eine nützliche Ressource bleibt. --- ## [JS-Payload reduzieren](https://docs.docmd.io/de/07/guides/performance-delivery/reducing-javascript-payload/) --- title: "JS-Payload reduzieren" description: "So erhalten Sie eine leistungsstarke Dokumentations-Website, indem Sie Ihre JavaScript-Abhängigkeiten optimieren und die Zero-Framework-Architektur von docmd nutzen." --- ## Problem Viele moderne Dokumentationswerkzeuge verlassen sich auf schwere JavaScript-Frameworks (wie React oder Vue), nur um statischen Text zu rendern. Diese Frameworks können mehrere hundert Kilobyte zu Ihrer initialen Seitenlast hinzufügen und zwingen den Browser dazu, große Mengen an Code herunterzuladen, zu parsen und auszuführen, bevor die Seite vollständig interaktiv wird. Dies führt zu langsamen Ladezeiten und "Ghost-Clicks" auf leistungsschwächeren Geräten. ## Warum es wichtig ist Ein großer JavaScript-Payload beeinflusst direkt die "Time to Interactive" (TTI). In der technischen Dokumentation, wo Benutzer schnell Antworten benötigen, ist jede Verzögerung durch eine schwere Framework-Initialisierung eine erhebliche Hürde für die Benutzerfreundlichkeit. Wenn Sie Ihren Payload klein halten, stellen Sie sicher, dass Suche, Navigation und Theme-Wechsel von dem Moment an, in dem die Seite erscheint, augenblicklich funktionieren. ## Ansatz `docmd` verwendet eine **Zero-Framework-Architektur** für seine Kern-Client-Logik. Durch die Nutzung von Vanilla JavaScript und nativen Browser-APIs anstelle eines schweren virtuellen DOM halten wir den gesamten JS-Payload für eine Standard-Website unter **20 KB**. Dieses leichtgewichtige Fundament gewährleistet maximale Performance auf allen Geräten und unter allen Netzwerkbedingungen. ## Implementierung ### 1. Native Browser-APIs nutzen Vermeiden Sie den Import schwerer Bibliotheken wie jQuery oder Lodash für einfache Aufgaben. Moderne Browser verfügen über robuste native APIs, die fast jede dokumentationsbezogene Anforderung ohne Overhead bewältigen können. ```javascript // docmd.config.js export default { // ✅ Nutzen Sie ein kleines, zweckgebundenes Skript anstelle einer schweren Bibliothek customJs: ['/static/js/meine-eigene-logik.js'] }; ``` ### 2. Strategisches Plugin-Management Während [Plugins](../../plugins/usage) leistungsstarke Funktionen hinzufügen, können einige Ihren JavaScript-Payload erheblich vergrößern. Zum Beispiel benötigt das [Mermaid-Plugin](../../plugins/mermaid) eine große clientseitige Bibliothek, um Diagramme zu rendern. Aktivieren Sie schwere Plugins nur, wenn sie für Ihren Inhalt essenziell sind, und berücksichtigen Sie deren Auswirkungen auf das Gesamtgewicht der Seite. ### 3. Nicht-kritische Skripte verzögert laden Wenn Sie Drittanbieter-Dienste wie Analytics oder Feedback-Widgets einbinden müssen, stellen Sie sicher, dass diese asynchron oder verzögert geladen werden, damit sie das Rendering Ihrer Dokumentation nicht blockieren. ```html <!-- In Ihrer benutzerdefinierten Head-Injektion --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. Assets optimieren Stellen Sie sicher, dass jedes von Ihnen bereitgestellte benutzerdefinierte JavaScript minifiziert und komprimiert ist. `docmd` übernimmt die Minifizierung seiner Kern-Assets, aber Sie sind für die Optimierung aller Dateien verantwortlich, die Sie Ihrem `static/`-Verzeichnis hinzufügen. ## Abwägungen Das Erstellen komplexer interaktiver Funktionen mit Vanilla JavaScript kann mehr manuellen Aufwand erfordern als die Verwendung eines deklarativen Frameworks. Für die Dokumentation jedoch , wo 95 % des Inhalts aus statischem Text und Bildern bestehen , überwiegen die Performance-Vorteile eines Zero-Framework-Ansatzes bei weitem die Bequemlichkeit eines schweren Frameworks. --- ## [Sub-100ms Navigation](https://docs.docmd.io/de/07/guides/performance-delivery/sub-100ms-navigation/) --- title: "Sub-100ms Navigation" description: "Wie der native SPA-Router von docmd und das intentionsbasierte Prefetching sofortige Seitenübergänge für ein optimales Leseerlebnis ermöglichen." --- ## Problem Herkömmliche Multi-Page-Navigation, bei der jeder Klick auf einen Link ein vollständiges Neuladen des Browsers auslöst, erzeugt ein störendes "weißes Blinken" und unterbricht den Lesefluss. Der Browser muss den aktuellen Status verwerfen, neues HTML anfordern und CSS sowie JavaScript neu parsen , selbst wenn sich nur der zentrale Inhaltsbereich geändert hat. ## Warum es wichtig ist Dokumentationsbenutzer springen häufig zwischen verschiedenen Abschnitten wie Tutorials, API-Referenzen und konzeptionellen Anleitungen hin und her. Wenn jeder Übergang eine Sekunde oder länger dauert, führt dies zu kognitiver Reibung und entmutigt eine gründliche Exploration. Eine sofortige Navigation sorgt dafür, dass sich die Dokumentation wie eine native Anwendung anfühlt, was die Benutzerzufriedenheit und das Engagement erheblich steigert. ## Ansatz `docmd` nutzt einen leistungsstarken **Single Page Application (SPA) Router**, der auf vorab generierten statischen Dateien aufbaut. Dies ermöglicht es dem Browser, Klicks auf Links abzufangen, nur die notwendigen Inhalte im Hintergrund abzurufen und die Seite dynamisch zu aktualisieren, ohne sie vollständig neu zu laden. Dieser Ansatz bewahrt den Status der Sidebar, des Inhaltsverzeichnisses und der Theme-Einstellungen, was zu nahezu sofortigen Übergängen führt. ## Implementierung Der `docmd` SPA-Router ist standardmäßig aktiviert und nutzt mehrere fortschrittliche Techniken, um Navigationsgeschwindigkeiten unter 100 ms zu erreichen: ### 1. Intentionsbasiertes Prefetching Wenn ein Benutzer mit der Maus über einen Navigationslink fährt, erkennt `docmd` die Absicht zur Navigation und startet im Hintergrund das Abrufen der Inhalte der Zielseite. Bis der Benutzer den Link tatsächlich klickt, sind die Daten oft schon im Browser-Cache verfügbar, wodurch sich der Übergang augenblicklich anfühlt. ### 2. Partielle DOM-Updates Anstatt die gesamte Seite neu zu rendern, aktualisiert `docmd` intelligent nur die notwendigen Funktionszonen: * **Hauptinhalt (Main Content)**: Der primäre, per Markdown gerenderte Textkörper. * **Inhaltsverzeichnis (TOC)**: Wird aktualisiert, um den Überschriften der neuen Seite zu entsprechen. * **Navigationsstatus**: Aktualisiert die aktiven und ausgeklappten Zustände in der Sidebar. ### 3. Lifecycle-Events für eigene Logik Da der Browser kein vollständiges Neuladen durchführt, werden Standard-Events wie `DOMContentLoaded` nur einmal ausgelöst. Um nach jeder Navigation eigenen JavaScript-Code auszuführen , wie das Neuinitialisieren eines Drittanbieter-Widgets oder das Tracking von Seitenaufrufen , sollten Sie auf das Event `docmd:page-mounted` hören. ```javascript // Beispiel: Neuinitialisierung einer eigenen Komponente nach der Navigation document.addEventListener('docmd:page-mounted', (event) => { const currentPath = event.detail.path; console.log(`Erfolgreich navigiert zu: ${currentPath}`); // Eigene Logik hier if (currentPath.includes('/api/')) { initApiConsole(); } }); ``` Weitere Details finden Sie in der Dokumentation zu [Client-seitigen Events](../../api/client-side-events). ## Abwägungen ### Skript-Ausführung Der SPA-Router führt `<script>`-Tags, die sich im Markdown-Textkörper der neuen Seite befinden, automatisch neu aus. Globale Skripte, die in Ihrem Theme oder Layout definiert sind, laufen jedoch nur einmal beim ersten Laden. Verwenden Sie immer das Event `docmd:page-mounted` für Logik, die auf jeder Seite ausgeführt werden muss. ### SEO und Barrierefreiheit Trotz des SPA-ähnlichen Verhaltens generiert `docmd` weiterhin eine vollständige, eigenständige `.html`-Datei für jede Seite. Dies stellt sicher, dass Suchmaschinen-Crawler den vollständigen Inhalt sehen können und die Website auch für Benutzer mit deaktiviertem JavaScript funktionsfähig bleibt, was exzellente SEO- und Barrierefreiheitsstandards gewährleistet. --- ## [Breaking Changes & Veraltete Funktionen](https://docs.docmd.io/de/07/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "Breaking Changes & Veraltete Funktionen" description: "So kommunizieren Sie API-Änderungen und Migrationspfade effektiv durch versionierte Dokumentation und kontextbezogene Callouts." --- ## Problem Wenn ein Produkt eine neue Hauptversion einführt, werden bestimmte APIs, Funktionen oder Konfigurationen zwangsläufig als veraltet markiert oder entfernt. Benutzer, die die neueste Dokumentation durchsuchen, müssen klar gewarnt werden, wenn sie veraltete Muster verwenden. Gleichzeitig sollte sich die Dokumentation auf die moderne Implementierung konzentrieren, um Verwirrung zu vermeiden. ## Warum es wichtig ist Das Versäumnis, Breaking Changes explizit hervorzuheben, führt dazu, dass Entwickler Stunden mit dem Debuggen von Code verschwenden, der von der Engine nicht mehr unterstützt wird. Kontextbezogene Warnungen und klare Migrationspfade sind essenziell, um das Vertrauen der Benutzer zu erhalten, Supportanfragen zu reduzieren und einen reibungslosen Übergang zur neuesten Version Ihrer Software zu gewährleisten. ## Ansatz Kombinieren Sie die [Versioning Engine](../../configuration/versioning.md) von `docmd` mit [Callout-Containern](../../content/containers/callouts.md), um eine klare Trennung zwischen Legacy- und modernen Inhalten zu schaffen. Die Strategie besteht darin, die vollständige Legacy-Dokumentation in eine archivierte Version zu verschieben und gleichzeitig "Migrations-Anker" in der aktuellen Version bereitzustellen, die auf die archivierten Inhalte verweisen. ## Implementierung ### 1. Archivierung von Legacy-Inhalten Verschieben Sie bei der Veröffentlichung einer neuen Hauptversion (z. B. v2.0) Ihre bestehende Dokumentation in ein Archivverzeichnis (z. B. `docs-v1/`). Dies stellt sicher, dass der vollständige Kontext der vorherigen Version für Benutzer erhalten bleibt, die noch nicht migriert sind. ### 2. Kontextbezogene Migrations-Callouts Verwenden Sie in Ihrer neuesten Dokumentation `warning`- oder `important`-Callouts am Anfang von Seiten, auf denen signifikante Änderungen vorgenommen wurden. Dies bietet Benutzern, die versuchen, Legacy-Muster zu verwenden, einen sofortigen Mehrwert. ```markdown # Konfigurations-API ::: callout warning "Migration: Breaking Change in v2.0" Die Eigenschaft `siteTitle` wurde entfernt. Sie wurde durch die globale Eigenschaft `title` ersetzt. * **Migration von v1.x?** Bitte aktualisieren Sie Ihre `docmd.config.js`. * **Benötigen Sie v1.x-Docs?** Siehe [Legacy-Konfigurationsanleitung](../../configuration/overview.md). ::: ``` ### 3. Aufrechterhaltung der AI-Genauigkeit Durch die strikte Trennung von veralteten Inhalten von der aktiven Version verbessern Sie die Genauigkeit von KI-Tools erheblich. Das [LLMs-Plugin](../../plugins/llms.md) von `docmd` generiert Kontextdateien basierend auf der aktiven Version. Die Archivierung von Legacy-Inhalten verhindert, dass KI-Modelle "halluzinieren" und Benutzern, die nach modernen Lösungen suchen, veraltete APIs empfehlen. ## Abwägungen Das aktive Verwalten von Migrations-Callouts bedeutet zusätzlichen Wartungsaufwand. Wenn sie unbefristet stehen bleiben, können Seiten mit alten Warnungen überladen werden. Wir empfehlen eine Richtlinie, Migrations-Callouts zu entfernen, sobald die Legacy-Version ihr Lebensende (EOL) erreicht hat oder nach einem vollständigen Hauptversionszyklus, um die Dokumentation schlank und fokussiert zu halten. --- ## [Zusammenarbeit mehrerer Teams](https://docs.docmd.io/de/07/guides/scaling-architecture/multi-team-collaboration/) --- title: "Zusammenarbeit mehrerer Teams" description: "So nutzen Sie dezentrale Navigation und globale Menüleisten, um mehreren Teams die Zusammenarbeit an einem einheitlichen Dokumentationsprojekt ohne Reibungsverluste zu ermöglichen." --- ## Problem Wenn mehrere unabhängige Teams (z. B. Frontend, Backend, DevOps und Produkt) zu einem einzigen Dokumentations-Repository beitragen, entstehen oft organisatorische Reibungsverluste. Teams könnten versehentlich globale Navigationseinstellungen überschreiben, widersprüchliche Design-Paradigmen erstellen oder bei gleichzeitigen Updates Links über Domänengrenzen hinweg beschädigen. ## Warum es wichtig ist Reibung im Authoring-Prozess führt zu "Dokumentations-Silos", in denen Teams unabhängige, isolierte Wikis erstellen, um der Komplexität eines gemeinsamen Repositorys zu entgehen. Dies zerstört die einheitliche User Experience eines zentralen Dokumentationsportals und macht es für Benutzer erheblich schwerer, umfassende Informationen über das gesamte System zu finden. ## Ansatz Nutzen Sie das dezentrale [Auflösungsprioritätssystem](../../configuration/navigation#navigation-resolution-priority) von `docmd`. Dies ermöglicht es einzelnen Teams, mithilfe lokaler `navigation.json`-Dateien die volle Autonomie über ihre spezifischen Domänen zu behalten, während ein zentrales Team die globale [Menüleiste](../../configuration/menubar) und das visuelle Designsystem verwaltet. ## Implementierung ### 1. Domänenbasierte Verantwortlichkeit Unterteilen Sie Ihre Dokumentation in Top-Level-Verzeichnisse, die spezifischen Teams zugewiesen sind. Jedes Team ist vollständig für den Inhalt und die interne Struktur seines zugewiesenen Ordners verantwortlich. ```text mein-projekt/ ├── docs/ │ ├── frontend/ # Gehört dem UI-Team │ │ ├── navigation.json # Teamspezifische Sidebar │ │ └── komponenten.md │ ├── backend/ # Gehört dem API-Team │ │ ├── navigation.json │ │ └── datenbank.md │ └── docmd.config.js # Gehört dem Plattform-/Core-Team ``` ### 2. Globaler Kontextwechsel (Die Menüleiste) Das zentrale Plattform-Team steuert die [Menüleiste](../../configuration/menubar), die als primäre Navigationsebene dient, um zwischen den verschiedenen Team-Domänen zu wechseln. ```javascript // docmd.config.js export default { menubar: { enabled: true, items: [ { text: 'Frontend', url: '/frontend/komponenten' }, { text: 'Backend', url: '/backend/datenbank' }, { text: 'Infrastruktur', url: '/devops/setup' } ] } }; ``` ### 3. Lokale Autonomie mit navigation.json Wenn ein Benutzer Inhalte innerhalb des `/frontend/`-Verzeichnisses durchsucht, priorisiert `docmd` automatisch die Datei `frontend/navigation.json`. Die Sidebar wird dynamisch aktualisiert und spiegelt nur die frontend-spezifische Hierarchie wider, wodurch verhindert wird, dass die Navigation durch unzusammenhängende Informationen anderer Teams überladen wird. ```json // docs/frontend/navigation.json [ { "title": "Design System", "path": "/frontend/design-system" }, { "title": "Komponenten-Bibliothek", "path": "/frontend/komponenten" } ] ``` ## Abwägungen Dezentrale Navigation erfordert von den Teams Sorgfalt bei domänenübergreifenden Links. Während `docmd` relative Links effektiv verarbeitet, bricht das Verschieben eines kompletten Team-Verzeichnisses die Links in den Dateien anderer Teams. Wir empfehlen die Verwendung von pfad-relativen Pfaden (beginnend mit `/`) für Links zwischen verschiedenen Team-Domänen, um Stabilität zu gewährleisten. --- ## [Verwalten von mehrversionigen Dokumentationen](https://docs.docmd.io/de/07/guides/scaling-architecture/multi-version-documentation/) --- title: "Verwalten von mehrversionigen Dokumentationen" description: "So pflegen Sie mehrere Versionen Ihrer Dokumentation (v1, v2, Legacy) mit einem einheitlichen Switcher und Pfaderhaltung." --- ## Problem Softwareprodukte entwickeln sich weiter, aber Unternehmenskunden bleiben oft bei älteren LTS-Versionen (Long Term Support). Wenn die Dokumentation für v1 bei der Veröffentlichung von v2 eingestellt wird, lässt man diese Benutzer im Stich. Gleichzeitig führt das Pflegen komplett separater Websites für jede Version zu einer fragmentierten User Experience und einer Schwächung der SEO. ## Warum es wichtig ist Ohne eine nahtlose Möglichkeit zum Wechseln zwischen Versionen wenden Entwickler fälschlicherweise Anweisungen aus der neuesten Dokumentation auf Legacy-Umgebungen an, was zu Fehlern und erhöhtem Supportaufwand führt. Ein einheitliches Versionierungssystem stellt sicher, dass Benutzer immer wissen, in welchem Kontext sie sich befinden, und einfach zwischen den Versionen derselben Seite springen können. ## Ansatz `docmd` verfügt über eine native [Versioning Engine](../../configuration/versioning), die Versionen als erstklassige Bestandteile behandelt. Sie isoliert Builds in Verzeichnisse mit Versionspräfix, bietet einen "Sticky Switching"-Mechanismus, der den aktuellen Seitenpfad beibehält, und beschränkt Suchergebnisse korrekt auf den aktiven Versionskontext. ## Implementierung ### 1. Quellverzeichnisse organisieren Bewahren Sie Ihre aktuellste Dokumentation in einem Standardverzeichnis (z. B. `docs/`) auf und platzieren Sie Legacy-Versionen in Geschwisterverzeichnissen (z. B. `docs-v1/`). ```text mein-projekt/ ├── docs/ # v2.x (Aktuell) ├── docs-v1/ # v1.x (Legacy LTS) └── docmd.config.js ``` ### 2. Versions-Map konfigurieren Definieren Sie Ihre Versionsstruktur in der `docmd.config.js`. Die `current`-Version wird unter der Root-URL bereitgestellt, während andere unter `/{id}/` erreichbar sind. ```javascript // docmd.config.js export default { versions: { current: 'v2', // Erreichbar unter / position: 'sidebar-top', // Position des Switchers all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Aktuell)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x (LTS)' } ] } }; ``` ### 3. Navigation pro Version Wenn sich die Navigationsstruktur zwischen den Versionen unterscheidet, können Sie eine `navigation.json`-Datei in das Quellverzeichnis der jeweiligen Version legen. `docmd` erkennt diese automatisch und verwendet sie für diese spezifische Version. ```json // docs-v1/navigation.json [ { "title": "Legacy Setup", "path": "/legacy-setup" }, { "title": "Migration zu v2", "path": "/migration" } ] ``` ### 4. Pfaderhaltung (Sticky Switching) `docmd` versucht automatisch, den aktuellen Pfad des Benutzers beizubehalten, wenn dieser die Version wechselt. Wenn sich ein Benutzer auf der `v2`-Seite unter `/api/auth` befindet und zu `v1` wechselt, versucht die Engine, ihn zu `/v1/api/auth` zu leiten. Wenn die Seite in der Zielversion nicht existiert, erfolgt ein Fallback auf die Startseite dieser Version. ## Abwägungen Das Speichern mehrerer Versionen in einem einzigen Repository erhöht die Größe des Repositorys im Laufe der Zeit. Bei sehr großen Dokumentationsmengen sollten Sie in Erwägung ziehen, Legacy-Verzeichnisse während des Build-Prozesses dynamisch über CI/CD einzubinden, anstatt sie fest in den Haupt-Branch einzuchecken. --- ## [Organisation großer Repositories](https://docs.docmd.io/de/07/guides/scaling-architecture/organising-large-repositories/) --- title: "Organisation großer Repositories" description: "So bewahren Sie Navigationsklarheit und Benutzerfreundlichkeit in komplexen Dokumentationsstrukturen durch Hub-Pages und hierarchische Navigation." --- ## Problem Wenn ein Dokumentations-Repository auf Hunderte von Seiten anwächst, macht die Anzeige jedes Themas in einer einzigen, riesigen Sidebar die Website unbrauchbar. Benutzer leiden unter "Entscheidungsparalyse", wenn das Finden eines bestimmten Moduls das Scrollen durch Dutzende irrelevanter, ausgeklappter Kategorien erfordert. ## Warum es wichtig ist Navigation ist eine kritische Komponente der User Experience. Ein überladenes Interface mindert die wahrgenommene Qualität Ihres Produkts und erschwert es Entwicklern, die benötigten Antworten zu finden. Wenn sich die Navigation chaotisch anfühlt, gehen Benutzer oft davon aus, dass die Software selbst ebenso schwierig zu bedienen ist. ## Ansatz Implementieren Sie eine hierarchische Gruppierungsstrategie mit der [Navigations-Konfiguration](../../configuration/navigation.md) von `docmd`. Das Grundprinzip besteht darin, Komplexität zu verbergen, bis sie benötigt wird. Verwenden Sie ausklappbare Gruppen und "Hub-Pages", um eine übersichtliche Sidebar zu erhalten und sicherzustellen, dass sich Benutzer auf ihre aktuelle Aufgabe konzentrieren können, ohne überfordert zu werden. ## Implementierung ### 1. Hierarchische Gruppierung Verwenden Sie die Eigenschaft `collapsible` in Ihrer `navigation.json` oder Konfigurationsdatei, um verwandte Seiten zu gruppieren. Dies hält die Sidebar übersichtlich und ermöglicht es Benutzern, nur die Abschnitte auszuklappen, die sie interessieren. ```json // docs/navigation.json [ { "title": "Advanced API", "icon": "braces", "collapsible": true, "children": [ { "title": "Authentifizierung", "path": "/api/auth" }, { "title": "Webhooks", "path": "/api/webhooks" }, { "title": "Rate Limiting", "path": "/api/rate-limiting" } ] } ] ``` ### 2. Implementierung von Hub-Pages Anstatt jede einzelne Seite in der Sidebar anzuzeigen, erstellen Sie zentrale "Hub-Pages", die als Verzeichnisse für bestimmte Teilsysteme dienen. Verwenden Sie [Grids und Cards](../../content/containers/grids.md) um eine visuelle, übergeordnete Übersicht über die verfügbaren Inhalte zu geben. ```markdown # Integrations-Hub ::: grids ::: grid ::: card "Datenbank-Integrationen" icon:database Verbinden Sie Ihre Anwendung mit populären Datenbanken wie Postgres und MongoDB. [Datenbank-Anleitungen ansehen](../integrations/openapi-generation.md) ::: ::: ::: grid ::: card "Payment Gateways" icon:credit-card Erfahren Sie, wie Sie Stripe, PayPal und mehr implementieren. [Payment-Anleitungen ansehen](../integrations/alongside-other-tools.md) ::: ::: ::: ``` ### 3. Nutzung von Breadcrumbs `docmd` generiert automatisch [Breadcrumbs](../../content/syntax/advanced.md#breadcrumbs) für jede Seite, basierend auf Ihrer Ordnerstruktur und Navigationshierarchie. Durch die Verwendung von Hub-Pages können Sie die Sidebar fokussiert halten, während Breadcrumbs den notwendigen Kontext und eine einfache Möglichkeit für Benutzer bieten, in der Hierarchie zurückzunavigieren. ## Abwägungen Die Verwendung von Hub-Pages kann einen zusätzlichen "Klick" erfordern, um tiefergehende Inhalte zu erreichen. Dies ist jedoch in der Regel einem überladenen Seitenmenü vorzuziehen, das das Auffinden von Informationen erschwert. Das Ergebnis ist ein saubereres, professionelleres Interface, das die allgemeine Durchsuchbarkeit und den Fokus Ihrer Dokumentation erheblich verbessert. --- ## [Skalierbare Ordnerstruktur](https://docs.docmd.io/de/07/guides/scaling-architecture/scalable-folder-structure/) --- title: "Skalierbare Ordnerstruktur" description: "So organisieren Sie umfangreiche Dokumentationsprojekte unter Verwendung des Diátaxis-Frameworks und des Auflösungssystems von docmd." --- ## Problem Kleine Dokumentations-Websites beginnen oft mit einem flachen `docs/`-Ordner. Wenn das Projekt jedoch wächst und mehrere Module, Tutorials, APIs und konzeptionelle Vertiefungen umfasst, wird eine ungeordnete Ordnerstruktur zu einer erheblichen Wartungslast. Dateien sind schwer zu finden, und die Navigations-Seitenleiste wird zu einer überwältigenden "Wand aus Links". ## Warum es wichtig ist Eine ungeordnete Ordnerstruktur führt direkt zu einer verwirrenden Benutzererfahrung, da das Routing und die Standardnavigation von `docmd` von Ihrem Dateisystem abgeleitet werden. Für Autoren führt das Fehlen einer klaren Struktur zu Inhaltsduplikaten und inkonsistenten Benennungen, was die Verwaltung der Dokumentation erschwert, je mehr Mitwirkende dem Projekt beitreten. ## Ansatz Wir empfehlen die Einführung eines Frameworks für Informationsarchitektur wie [Diátaxis](external:https://diataxis.fr/), das Inhalte in vier verschiedene Kategorien unterteilt: Tutorials, How-To Guides (Anleitungen), Reference (Referenz) und Explanation (Erklärung). Die strikte Abbildung dieser Kategorien auf Ihr physisches Dateisystem bietet einen klaren Fahrplan sowohl für Leser als auch für Autoren. ## Implementierung ### 1. Die Diátaxis-Hierarchie Organisieren Sie Ihr Quellverzeichnis in semantische Unterordner. Diese physische Isolierung erleichtert die Verwaltung großer Dateisätze und gewährleistet eine saubere URL-Struktur. ```text my-project/ ├── docs/ │ ├── tutorials/ (Lernorientiert: Schritt-für-Schritt-Lektionen) │ │ └── getting-started.md │ ├── guides/ (Aufgabenorientiert: Lösung spezifischer Probleme) │ │ └── deployment.md │ ├── reference/ (Informationsorientiert: technische Beschreibungen) │ │ └── api-spec.md │ ├── explanation/ (Verständnisorientiert: theoretischer Hintergrund) │ │ └── architecture.md │ └── navigation.json (Definition der Hauptnavigation) └── docmd.config.js ``` ### 2. Strategische Nutzung von navigation.json Anstatt einen massiven Navigationsbaum in Ihrer globalen Konfiguration zu definieren, verwenden Sie `navigation.json`-Dateien in Ihren Quellverzeichnissen. `docmd` folgt einem [Auflösungsprioritätssystem](../../configuration/navigation#navigation-resolution-priority), das es Ihnen ermöglicht, unterschiedliche Seitenleisten-Hierarchien für verschiedene Abschnitte Ihrer Website zu definieren. ```json // docs/navigation.json [ { "title": "Tutorials", "icon": "book-open", "children": [ { "title": "Erste Schritte", "path": "/tutorials/getting-started" } ] }, { "title": "Referenz", "icon": "braces", "children": [ { "title": "API-Spezifikation", "path": "/reference/api-spec" } ] } ] ``` ### 3. Datei-basiertes Routing Denken Sie daran, dass der Speicherort jeder Markdown-Datei in der Ordnerstruktur ihre endgültige URL bestimmt. Beispielsweise wird `docs/guides/auth.md` zu `ihre-seite.com/guides/auth`. Nutzen Sie dies zu Ihrem Vorteil, um intuitive, einprägsame URLs für Ihre Benutzer zu erstellen. ## Abwägungen Strenge Organisations-Frameworks wie Diátaxis erfordern ein klares Verständnis der Inhaltstypen. Technische Redakteure können es gelegentlich als schwierig empfinden, ein bestimmtes Dokument zu kategorisieren (z. B. "Ist dies ein Guide oder ein Tutorial?"). Die Festlegung klarer interner Richtlinien für Beiträge ist unerlässlich, um die Konsistenz zu wahren, während Ihr Team und Ihre Dokumentation wachsen. --- ## [Skalierung auf 1000+ Seiten](https://docs.docmd.io/de/07/guides/scaling-architecture/scaling/) --- title: "Skalierung auf 1000+ Seiten" description: "So bewahren Sie mit docmd auch in riesigen Dokumentationsprojekten eine hohe Performance und Benutzerfreundlichkeit." --- ## Problem Mit zunehmender Reife eines Softwareprodukts wächst natürlich auch dessen Dokumentation. Wenn ein Projekt auf Hunderte oder Tausende von Markdown-Dateien anwächst, leiden viele Dokumentationsgeneratoren unter trägen Build-Zeiten, langsamen Hot-Reloads des Dev-Servers und Navigationsstrukturen, die sowohl Maintainer als auch Benutzer überfordern. ## Warum es wichtig ist Wenn die Generierung der Dokumentation Minuten statt Sekunden dauert, werden Autoren davon abgehalten, kleine Korrekturen vorzunehmen, was zu veralteten und ungenauen Inhalten führt. Für Benutzer macht ein riesiges, unorganisiertes Sidebar-Menü das Finden von Informationen frustrierend, was zu mehr Support-Anfragen und einer schlechten Developer Experience führt. ## Ansatz `docmd` ist auf Geschwindigkeit und Skalierbarkeit ausgelegt. Durch die Verwendung einer Hochleistungs-Parsing-Engine und einer granularen, dateibasierten Build-Strategie kann es Tausende von Seiten in Sekunden verarbeiten. Die optimierte SPA-Auslieferung (Single Page Application) stellt sicher, dass die Navigation durch eine große Website für den Endbenutzer verzögerungsfrei bleibt. ## Implementierung ### 1. Granulare Projektstruktur Vermeiden Sie es, alle Dateien in einem einzigen flachen Verzeichnis abzulegen. Verwenden Sie eine tief verschachtelte Ordnerstruktur, die die Architektur Ihres Produkts widerspiegelt. Dies macht das Projekt wartungsfreundlicher und ermöglicht es `docmd`, Änderungen während der Entwicklung effizient zu verfolgen. ### 2. Optimierte Suchindexierung Für große Websites ist das [Search-Plugin](../../plugins/search) unerlässlich. `docmd` generiert einen hochkomprimierten Suchindex, der bei Bedarf geladen wird. Dies stellt sicher, dass selbst bei Tausenden von Seiten das erste Laden der Seite schnell bleibt, während gleichzeitig eine Volltextsuche über die gesamte Website ermöglicht wird. ### 3. Versionierung und Archivierung Nutzen Sie die [Versioning Engine](../../configuration/versioning), um Legacy-Inhalte von der aktiven Dokumentation zu trennen. Durch die Isolierung älterer Versionen in eigene Build-Kontexte reduzieren Sie die Anzahl der Seiten, die bei täglichen Updates neu verarbeitet werden müssen, was die Entwicklungsgeschwindigkeit erheblich verbessert. ```javascript // docmd.config.js export default { versions: { current: 'v3', all: [ { id: 'v3', dir: 'docs/current', label: 'v3.x (Aktuell)' }, { id: 'v2', dir: 'docs/v2', label: 'v2.x (Legacy)' } ] } }; ``` ### 4. Komponentenbasierte Navigation Unterteilen Sie Ihre Navigation mithilfe von `navigation.json`-Dateien in logische Segmente. Dies ermöglicht es Ihnen, separate Sidebar-Hierarchien für verschiedene Abschnitte Ihrer Website zu definieren und so zu verhindern, dass die Hauptnavigation unübersichtlich wird. ## Abwägungen Eine große Website verbraucht während des Build-Prozesses naturgemäß mehr Speicherplatz und RAM. Um auch bei extremen Skalierungen (10.000+ Seiten) Build-Zeiten im Sub-Sekunden-Bereich beizubehalten, sollten Sie eine leistungsstarke CI/CD-Umgebung mit SSD-Speicher und ausreichend RAM in Betracht ziehen, um die parallele Verarbeitung der Dateien zu bewältigen. --- ## [Schnelle & präzise Suche](https://docs.docmd.io/de/07/guides/search/fast-accurate-search/) --- title: "Schnelle & präzise Suche" description: "Wie docmd die Suchindexierung für Geschwindigkeit und Genauigkeit optimiert, selbst in großen Dokumentationsprojekten." --- ## Problem Wenn eine Dokumentation auf Hunderte oder Tausende von Seiten anwächst, kann der kompilierte Suchindex sehr groß werden. Eine monolithische Indexdatei kann den Hauptthread des Browsers während des Downloads und Parsens blockieren, was die "Time to Interactive" verzögert und dazu führt, dass sich die Suchoberfläche träge oder nicht reaktionsfähig anfühlt. ## Warum es wichtig ist Das primäre Ziel der Dokumentationssuche ist die "Time to Answer". Wenn ein Benutzer das Suchmodal aufruft und mehrere Sekunden warten muss, bis der Index geladen ist, geht der Nutzen des Suchwerkzeugs verloren. Schnelle, präzise Suchergebnisse sind essenziell, um eine professionelle Developer Experience zu bieten und Benutzern zu helfen, Informationen reibungslos zu finden. ## Ansatz `docmd` verwendet eine optimierte Indexierungsstrategie, die von einer leistungsstarken Suchbibliothek angetrieben wird. Es setzt auf **Scoping**, **inkrementelles Laden** und **Feldoptimierung**, um sicherzustellen, dass Suchergebnisse fast augenblicklich geliefert werden, unabhängig von der Größe der Dokumentations-Website. ## Implementierung ### 1. Gescopte Suchindizes `docmd` generiert automatisch separate Suchindizes für jedes [Locale](../../configuration/localisation/index.md) und jede [Version](../../configuration/versioning.md). Dies stellt sicher, dass ein Benutzer nur den für seinen aktuellen Kontext relevanten Index herunterlädt. Beispielsweise lädt ein Benutzer, der die deutsche Version Ihrer Dokumentation durchsucht, nur den deutschen Suchindex herunter, was die Payload-Größe erheblich reduziert. ### 2. Intelligentes Field-Stripping Das [Search-Plugin](../../plugins/search.md) ermöglicht es Ihnen zu steuern, welche Inhalte genau indexiert werden. Standardmäßig werden Überschriften und Frontmatter-Metadaten priorisiert, während gängige "Stoppwörter" und unnötige Codesymbole, die den Index ohne Mehrwert aufblähen würden, entfernt werden. Sie können auch spezifische Seiten über die Eigenschaft `search` in Ihrem [Frontmatter](../../content/frontmatter.md) vom Index ausschließen. ```yaml --- title: "Interner Entwickler-Leitfaden" search: false # Diese Seite erscheint nicht in den Suchergebnissen --- ``` ### 3. Lazy Loading & Prefetching Um das erste Laden der Seite schnell zu halten, lädt `docmd` den Suchindex nicht sofort. Stattdessen wird er verzögert im Hintergrund abgerufen oder in dem Moment ausgelöst, in dem ein Benutzer mit der Such-UI interagiert (z. B. durch Klicken auf die Suchleiste oder Verwenden des Tastenkürzels `Cmd+K` / `Ctrl+K`). ### 4. Ranking der Ergebnisse Ergebnisse werden basierend auf einem gewichteten Bewertungssystem eingestuft. Schlüsselwörter, die im Seiten-`title` oder in `h1`-Überschriften gefunden werden, werden deutlich höher gewichtet als solche im Textkörper. Dies stellt sicher, dass die relevantesten Seiten ganz oben in der Ergebnisliste erscheinen. ## Abwägungen Das Ausschließen von Hilfs- oder internen Seiten vom Suchindex erschwert deren Auffindbarkeit. Sie sollten die Eigenschaft `search: false` sparsam einsetzen, um sicherzustellen, dass wertvolle Informationen auffindbar bleiben. Während Lazy Loading die Performance verbessert, können Benutzer mit extrem langsamen Verbindungen eine kurze Verzögerung bemerken, wenn sie zum ersten Mal eine Suche auslösen. --- ## [Suchrelevanz & Struktur](https://docs.docmd.io/de/07/guides/search/improving-search-relevance/) --- title: "Suchrelevanz & Struktur" description: "So strukturieren Sie Ihre Markdown-Inhalte, um die Suchrelevanz zu verbessern und Benutzern zu helfen, Informationen schneller zu finden." --- ## Problem Suchmaschinen priorisieren Inhalte basierend auf ihrer Struktur. Wenn eine hochwertige Anleitung generische Überschriften wie "Einleitung" oder "Schritt 1" verwendet, weist die Suchmaschine den Kern-Keywords, die in den Absätzen vergraben sind, möglicherweise nicht genügend Gewicht zu. Dies führt dazu, dass relevante Seiten tief in den Suchergebnissen vergraben werden, was Benutzer frustriert, die sofortige Antworten erwarten. ## Warum es wichtig ist Benutzer suchen typischerweise nach spezifischen technischen Begriffen (z. B. "Authentifizierungs-Token" oder "Deployment-Limit") statt nach vollständigen Sätzen. Wenn Ihre Dokumentationsstruktur diese Begriffe nicht hervorhebt, kann die Suchmaschine Ihre Inhalte nicht sicher ranken. Eine hohe Suchrelevanz ist der entscheidende Unterschied zwischen einem Self-Service-Dokumentationsportal und einem hohen Aufkommen an Support-Tickets. ## Ansatz Strukturieren Sie Ihr Markdown so, dass der Suchindexer Kernkonzepte automatisch identifizieren und priorisieren kann. Die Suchmaschine von `docmd` weist dem Seiten-`title`, der `description` und den `headers` ein höheres Gewicht zu als dem Textkörper. Durch die Optimierung dieser strukturellen Elemente verbessern Sie die Auffindbarkeit Ihrer Inhalte erheblich. ## Implementierung ### 1. Frontmatter-Metadaten optimieren Verwenden Sie den [Frontmatter](../../content/frontmatter)-Block, um explizite Schlüsselwörter und eine aussagekräftige Zusammenfassung bereitzustellen. Das [Search-Plugin](../../plugins/search) indexiert diese Felder, um bessere Ergebnisse und nützlichere Snippets in der Such-UI anzuzeigen. ```yaml --- title: "AWS S3 Speicher-Konfiguration" description: "So konfigurieren Sie IAM-Rollen und Bucket-Berechtigungen für die AWS S3-Integration." keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. Semantische Überschriften verwenden Vermeiden Sie generische Überschriften. Fügen Sie stattdessen relevante Schlüsselwörter in Ihre Überschriften ein, um sowohl dem Benutzer als auch der Suchmaschine Kontext zu bieten. * **Niedrige Relevanz:** `## Schritt 1: Konfiguration` * **Hohe Relevanz:** `## Schritt 1: Konfigurieren von AWS IAM-Rollen` ### 3. Callouts für Schlüsselinformationen nutzen Die Verwendung von [Callout-Containern](../../content/containers/callouts) für kritische Warnungen oder "Pro-Tipps" kann ebenfalls die Suchrelevanz verbessern. Inhalte innerhalb von Callouts sind oft semantisch isoliert und können vom Indexer anders gewichtet werden, um wichtige Schritte zur Fehlerbehebung hervorzuheben. ## Abwägungen Die Optimierung der Suchrelevanz erfordert diszipliniertes Schreiben. Wenn sich Ihr Produkt weiterentwickelt, können Schlüsselwörter im Frontmatter veralten, wenn sie nicht regelmäßig überprüft werden. Darüber hinaus kann das Einfügen zu vieler Schlüsselwörter in Überschriften (Keyword-Stuffing) dazu führen, dass sich die Dokumentation repetitiv und weniger natürlich liest. Streben Sie ein Gleichgewicht zwischen SEO und Lesbarkeit an. --- ## [Local-First Suchoptimierung](https://docs.docmd.io/de/07/guides/search/local-first-search/) --- title: "Local-First Suchoptimierung" description: "So optimieren Sie Ihre Dokumentationsinhalte für die leistungsstarke, clientseitige Suchmaschine von docmd." --- ## Problem Local-First-Suchmaschinen laufen vollständig im Browser und liefern sofortige Ergebnisse ohne Server-Umweg. Das bedeutet jedoch auch, dass sie durch den Speicher und die Rechenleistung des Browsers begrenzt sind. Wenn ein Suchindex nicht ordnungsgemäß optimiert ist, kann er übermäßig viel RAM verbrauchen, was dazu führt, dass der Browser-Tab ruckelt oder sogar abstürzt , besonders auf mobilen Geräten. ## Warum es wichtig ist Eine nahtlose Sucherfahrung ist essenziell für die Produktivität von Entwicklern. Wenn das Suchwerkzeug Performance-Probleme verursacht oder zu viel Speicher verbraucht, werden Benutzer es meiden. Die Optimierung Ihrer Inhalte für die Local-First-Suche stellt sicher, dass Ihre Dokumentation auf allen Geräten und unter allen Netzwerkbedingungen schnell, reaktionsschnell und zuverlässig bleibt. ## Ansatz Das [Search-Plugin](../../plugins/search) von `docmd` verwendet während des Builds eine Extraktions-Pipeline, um einen hochoptimierten Index zu erstellen. Durch das Entfernen unnötiger Daten und die Konzentration auf hochwertige semantische Felder wird sichergestellt, dass der resultierende Index sowohl umfassend als auch leichtgewichtig ist. ## Implementierung ### 1. Extraktion während des Build-Prozesses Während des Builds verarbeitet `docmd` Ihre Markdown-Dateien, um nur den relevantesten Text für die Indexierung zu extrahieren. Dabei werden automatisch entfernt: * HTML-Tags und struktureller Boilerplate-Code. * Markdown-Syntaxzeichen, die keinen semantischen Mehrwert bieten. * Reine Formatierungselemente, die den Index unnötig aufblähen würden. Dies stellt sicher, dass der Indexer nur sauberen, aussagekräftigen Text erhält, was die finale Indexgröße erheblich reduziert. ### 2. Strategische Indexierung mit Frontmatter Sie können [Frontmatter](../../content/frontmatter) verwenden, um explizit zu steuern, wie eine Seite indexiert wird. Wenn eine Seite beispielsweise große Mengen an repetitiven Daten enthält (wie rohe JSON-Logs), die für die Suche nicht nützlich sind, können Sie festlegen, dass nur die Überschriften und Metadaten indexiert werden. ```yaml --- title: "API Log Referenz" search: indexBody: false # Nur Titel und Überschriften indexieren --- ``` ### 3. Clientseitiges Speichermanagement `docmd` verwaltet den Lebenszyklus des Suchindex im Browser sorgfältig. Es verwendet eine On-Demand-Ladestrategie, was bedeutet, dass die Suchmaschine erst initialisiert wird, wenn der Benutzer zum ersten Mal damit interagiert. Dies hält den Footprint beim ersten Laden der Seite gering und stellt sicher, dass Systemressourcen nur bei Bedarf verbraucht werden. ## Abwägungen Das aggressive Entfernen von Inhalten aus dem Suchindex (z. B. das Ausschließen großer Codeblöcke) kann manchmal dazu führen, dass sehr spezifische Ergebnisse fehlen. Sie müssen die Notwendigkeit eines leichtgewichtigen, schnellen Index gegen die Anforderung an eine gründliche Suchabdeckung abwägen. Wir empfehlen, Überschriften und konzeptionelle Beschreibungen zu priorisieren, da dies die häufigsten Suchziele für Entwickler sind. --- ## [Git-basierte Workflows](https://docs.docmd.io/de/07/guides/workflows-teams/git-based-workflows/) --- title: "Git-basierte Workflows" description: "So verwalten Sie Dokumentationsbeiträge effektiv mit Git, Pull Requests und automatisierten CI/CD-Checks." --- ## Problem Direkte Pushes in den Hauptzweig der Dokumentation führen oft zu fehlerhaften Links, inkonsistenter Formatierung und ungeprüften technischen Informationen. Gleichzeitig schreckt zu viel Reibung , etwa die Anforderung separater CMS-Accounts , Community-Mitglieder und interne Entwickler davon ab, wertvolle Updates beizusteuern. ## Warum es wichtig ist Zusammenarbeit ist das Lebenselixier großartiger Dokumentation. Wenn ein Entwickler einen Tippfehler oder ein veraltetes Beispiel findet, sollte er in der Lage sein, innerhalb von Minuten eine Korrektur einzureichen. Ein Git-basierter Workflow bietet eine vertraute, transparente und sichere Umgebung für Beiträge und stellt sicher, dass jede Änderung vor der Veröffentlichung geprüft und validiert wird. ## Ansatz Implementieren Sie ein "Pull Request" (PR)-Modell, das durch automatisierte Validierung und Preview-Umgebungen unterstützt wird. `docmd` ist für diesen Workflow konzipiert, da es auf Standard-Markdown-Dateien basiert, die mit vertrauten Git-Tools einfach verglichen (diff), geprüft und gemergt werden können. ## Implementierung ### 1. "Diese Seite bearbeiten"-Links aktivieren Sie können `docmd` so konfigurieren, dass automatisch "Diese Seite bearbeiten"-Links in der Fußzeile oder Sidebar generiert werden. Dies ermöglicht es Benutzern, direkt von einer Dokumentationsseite zur entsprechenden Quelldatei in Ihrem Repository zu springen. ```javascript // docmd.config.js export default { editLink: { enabled: true, baseUrl: 'https://github.com/my-org/meine-docs/edit/main/docs', text: 'Änderung vorschlagen' } }; ``` Weitere Details finden Sie unter [Edit-Link-Konfiguration](../../configuration/overview.md#editlink). ### 2. Kontextbezogene Reviews mit Threads Verwenden Sie für komplexe Updates, die detailliertes Feedback erfordern, das [Threads-Plugin](../../plugins/threads.md). Dies ermöglicht es Autoren und Reviewern, während der Review-Phase Inline-Kommentare direkt im Markdown-Inhalt zu hinterlassen, wodurch Diskussionen kontextbezogen bleiben. ```markdown ::: thread "Name des Reviewers" Sollten wir hier ein Code-Beispiel für den neuen Authentifizierungs-Flow einfügen? ::: ``` ### 3. Automatisierte Validierung in der CI Integrieren Sie `docmd` in Ihre CI/CD-Pipeline (z. B. [GitHub Actions](../integrations/github-actions-cicd.md)), um jeden PR zu validieren. Ihre Pipeline sollte mindestens den Build-Befehl ausführen, um sicherzustellen, dass keine Syntaxfehler oder fehlerhafte Konfigurationen eingeführt werden. ```bash # In Ihrer CI-Pipeline npm install npx @docmd/core build ``` ## Abwägungen Strikte Git-Workflows können gelegentlich kleinere Updates verlangsamen, wie das Beheben eines kritischen Tippfehlers oder das Aktualisieren einer Servicestatus-Meldung. Für Teams mit hoher Geschwindigkeit empfehlen wir die Benennung von "Documentation Owners", die die Befugnis haben, kleine Änderungen schnell durchzuwinken, während sie bei signifikanten technischen Updates strenge Review-Standards einhalten. --- ## [Konsistenz wahren](https://docs.docmd.io/de/07/guides/workflows-teams/maintaining-consistency/) --- title: "Konsistenz wahren" description: "So gewährleisten Sie eine einheitliche Stimme und professionelle Qualität in großen Dokumentationsteams durch Linting und standardisierte Muster." --- ## Problem In großen Teams hat jeder technische Redakteur einen anderen Stil und eigene Vorlieben. Einige verwenden Fettdruck zur Hervorhebung, andere Kursivschrift. Einige bevorzugen "Klicken Sie auf die Schaltfläche", während andere "Wählen Sie die Option" verwenden. Mit der Zeit kann Ihre Dokumentation zu einem "Flickenteppich" aus widersprüchlichen Stilen werden, was es für Benutzer erschwert, Informationen schnell zu erfassen, und das professionelle Vertrauen in Ihr Produkt mindert. ## Warum es wichtig ist Konsistenz schafft Vertrautheit. Wenn Benutzer komplexe APIs oder Workflows erlernen, verlassen sie sich auf ein konsistentes Vokabular und strukturelle Muster, um effektiv durch die Inhalte zu navigieren. Eine einheitliche Stimme sorgt dafür, dass sich Ihre Dokumentation wie ein zusammenhängendes, hochwertiges Produkt anfühlt, was wiederum das Vertrauen in die Software selbst stärkt. ## Ansatz Setzen Sie Konsistenz mechanisch durch [standardisierte Container](../../content/containers) und automatisierte Linting-Tools durch. Indem Sie Low-Level-Stil- und Syntaxprüfungen automatisieren, geben Sie Ihren Redakteuren den Freiraum, sich auf die High-Level-Qualität, Genauigkeit und Klarheit der Inhalte zu konzentrieren. ## Implementierung ### 1. Standardisierte docmd-Muster nutzen Ermutigen Sie alle Mitwirkenden, die integrierten thematischen Container von `docmd` zu verwenden, anstatt mit manueller Markdown-Formatierung zu improvisieren. Dies stellt sicher, dass jede Warnung, jeder Tipp oder Hinweis auf der gesamten Website identisch aussieht und funktioniert. ```markdown <!-- ❌ Vermeiden: inkonsistent und ohne Styling --> **Hinweis:** Bitte starten Sie den Dienst neu. <!-- ✅ Empfohlen: konsistent, barrierefrei und thematisch passend --> ::: callout info Bitte starten Sie den Dienst neu. ::: ``` Die Verwendung von [Callouts](../../content/containers/callouts) stellt sicher, dass Ihre Dokumentation ein professionelles Erscheinungsbild behält und Barrierefreiheitsstandards erfüllt, ohne dass der Autor zusätzlichen Aufwand betreiben muss. ### 2. Prose-Linting implementieren Integrieren Sie Tools wie **Vale** oder **Markdownlint**, um Markenterminologie, Tonfall und Grammatik durchzusetzen. Diese Tools können so konfiguriert werden, dass sie automatisch auf Passiv, voreingenommene Sprache oder falsche Schreibweisen von Produktnamen prüfen. ```ini # Beispiel für .vale.ini MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. Automatisierte Durchsetzung in der CI/CD Integrieren Sie Konsistenzprüfungen in Ihre [GitHub Actions](../../guides/integrations/github-actions-cicd) oder andere CI/CD-Pipelines. Dies stellt sicher, dass jeder Pull Request automatisch auf Stil- und Strukturkonsistenz geprüft wird, bevor er gemergt werden kann. ```bash # Beispiel für einen CI-Schritt zum Linting - name: Dokumentation prüfen run: vale docs/ ``` ## Abwägungen Striktes Linting kann Community-Mitglieder entmutigen, wenn sie bei einer einfachen Tippfehler-Korrektur mit mehreren "Stilfehlern" konfrontiert werden. Wir empfehlen, die Empfindlichkeit Ihres Linters für externe Beiträge auf `warning` zu stellen und den `error`-Status für interne Team-Updates zu reservieren, um ein Gleichgewicht zwischen Konsistenz und Inklusivität zu finden. --- ## [Änderungen vorschauen](https://docs.docmd.io/de/07/guides/workflows-teams/previewing-changes/) --- title: "Änderungen vorschauen" description: "So richten Sie lokale und cloudbasierte Preview-Umgebungen ein, um sicherzustellen, dass Ihre Dokumentation vor der Veröffentlichung perfekt gerendert wird." --- ## Problem Das Schreiben von Markdown ohne Live-Vorschau führt häufig zu Formatierungsfehlern, fehlerhaften Containern und falschen Bildpfaden, die erst sichtbar werden, wenn der Inhalt bereits live ist. Dies führt zu einer frustrierenden Erfahrung für Benutzer und zu Mehrarbeit für Maintainer, die ständig Hotfixes für einfache Rendering-Probleme nachschieben müssen. ## Warum es wichtig ist Eine qualitativ hochwertige Dokumentation ist essenziell für das Vertrauen der Entwickler. Eine fehlerhafte Warnbox oder nicht gerenderte Syntax wirkt unprofessionell und kann Benutzer sogar über die Funktionsweise Ihrer Software irreführen. Die Dokumentation so zu sehen, wie sie später tatsächlich aussieht, ist der effektivste Weg, um Fehler abzufangen, die Lesbarkeit zu verbessern und eine nahtlose User Experience zu gewährleisten. ## Ansatz Implementieren Sie eine mehrstufige Preview-Strategie: Nutzen Sie den [lokalen Entwicklungsserver](../../getting-started/quick-start#local-development) von `docmd` für sofortiges Feedback während des Schreibens und setzen Sie kurzlebige Cloud-Umgebungen (wie Vercel oder Cloudflare Pages) für finale Reviews innerhalb Ihrer Pull Requests ein. ## Implementierung ### 1. Sofortige lokale Vorschau Der schnellste Weg, Ihre Änderungen zu sehen, ist der Befehl `docmd dev`. Er bietet Hot Module Replacement (HMR), wodurch Ihr Browser automatisch aktualisiert wird, sobald Sie eine Markdown-Datei speichern. ```bash # Lokalen Entwicklungsserver starten npx @docmd/core dev ``` ### 2. Cloudbasierte Preview-Umgebungen Konfigurieren Sie für die gemeinsame Review-Arbeit Ihre CI/CD-Plattform so, dass für jeden Pull Request eindeutige "Preview-URLs" generiert werden. Da `docmd` standardmäßige statische Dateien ausgibt, ist es mit allen gängigen Hosting-Anbietern kompatibel. * **Build-Befehl**: `npx @docmd/core build` * **Output-Verzeichnis**: `site` Dies ermöglicht es Reviewern, genau zu sehen, wie die Änderungen in einer produktionsnahen Umgebung aussehen und funktionieren, bevor sie in den Hauptzweig gemergt werden. ### 3. Gemeinsame Reviews mit Threads Kombinieren Sie Ihre Cloud-Previews mit dem [Threads-Plugin](../../plugins/usage). Dies ermöglicht es Teammitgliedern, Feedback direkt auf der gerenderten Vorschauseite zu hinterlassen, wodurch die Lücke zwischen dem Markdown-Quellcode und der finalen User Experience geschlossen wird. ## Abwägungen Das Erstellen einer vollständigen statischen Website bei jedem Commit in einem riesigen Repository (Tausende von Seiten) kann zeitaufwendig sein und CI/CD-Ressourcen kosten. Um dies zu optimieren, konfigurieren Sie Ihre CI-Pipeline so, dass ein Dokumentations-Build nur dann ausgelöst wird, wenn Dateien innerhalb Ihres Quellverzeichnisses (z. B. `/docs`) geändert wurden. --- ## [Workflow einrichten](https://docs.docmd.io/de/07/guides/workflows-teams/setting-up-workflow/) --- title: "Workflow einrichten" description: "So etablieren Sie einen hocheffizienten Dokumentations-Workflow für mehrere Autoren unter Verwendung von docmd und Docs-as-Code-Prinzipien." --- ## Problem Wenn Teams kein strukturiertes Dokumentations-Workflow haben, werden Aktualisierungen oft verzögert, vergessen oder nur über Ad-hoc-Nachrichten geteilt. Ohne einen klaren Prozess werden Inhalte fragmentiert, die Formatierung wird inkonsistent und technische Redakteure verbringen mehr Zeit damit, Merge-Konflikte zu lösen, als hochwertige Inhalte zu schreiben. ## Warum es wichtig ist Ohne einen formalen Prozess veraltet die Dokumentation schnell und verliert ihren Wert. Wenn die Aktualisierung der Dokumentation das Warten auf einen langsamen Software-Release-Zyklus erfordert, bleiben Ihre Anleitungen permanent asynchron zu den tatsächlichen Produktfunktionen, was zu Frustration bei den Benutzern und einem erhöhten Supportaufkommen führt. ## Ansatz Entkoppeln Sie das Deployment der Dokumentation von den Software-Release-Zyklen und übernehmen Sie gleichzeitig dieselben robusten Prozesse, die in der Softwareentwicklung verwendet werden (Branches → Pull Requests → CI/CD-Previews). Die Leichtigkeit von `docmd` ermöglicht es Teams, "Documentation as Code" mit minimalem Overhead zu praktizieren und sicherzustellen, dass Ihre Anleitungen so zuverlässig und aktuell sind wie Ihre Software. ## Implementierung ### 1. Repository-Strategie Wählen Sie die Strategie, die am besten zu Ihrer Organisationsstruktur passt: * **Monorepo-Strategie**: Behalten Sie einen `/docs`-Ordner innerhalb Ihres Haupt-Anwendungs-Repositorys. Dies ist ideal, um sicherzustellen, dass Dokumentationsänderungen im selben Pull Request wie der beschriebene Code gemergt werden, was eine perfekte Synchronisation gewährleistet. * **Separate Repository-Strategie**: Am besten geeignet für große Organisationen oder Open-Source-Projekte, bei denen ein dediziertes Team die Dokumentation unabhängig von der Build-Pipeline der Hauptanwendung verwaltet. ### 2. Validierung mit CI/CD Integrieren Sie `docmd` in Ihre CI/CD-Pipeline, um sicherzustellen, dass jedes Update technisch einwandfrei ist. Ihre Pipeline sollte mindestens den Build-Befehl ausführen, um auf Syntaxfehler und Konfigurationsprobleme zu prüfen. ```bash # Beispiel für einen Validierungsschritt in GitHub Actions - name: Dokumentation validieren run: npm install && npx @docmd/core build ``` Detaillierte Setup-Anweisungen finden Sie im [GitHub Actions Leitfaden](../../guides/integrations/github-actions-cicd). ### 3. Kollaborativer Review-Prozess Etablieren Sie eine Kultur des Peer-Reviews für alle Dokumentations-Updates. Nutzen Sie Pull Requests, um Änderungen zu diskutieren, die Formatierung zu überprüfen und die technische Genauigkeit sicherzustellen. Sie können das [Threads-Plugin](../../plugins/usage) nutzen, um detaillierte Diskussionen direkt am gerenderten Inhalt zu führen. ## Abwägungen Die Einführung eines "Docs-as-Code"-Workflows kann eine Hürde für nicht-technische Mitarbeiter (z. B. Produktmanager oder Rechtsabteilung) darstellen, die Git und Markdown möglicherweise einschüchternd finden. Um dies abzumildern, sollten Sie den integrierten Web-Editor von GitHub für kleinere Korrekturen in Betracht ziehen oder die [Live-Preview](../../content/live-preview)-Funktion nutzen, um ein visuelles und intuitiveres Authoring-Erlebnis zu bieten. --- ## [Versionierungs-Workflows](https://docs.docmd.io/de/07/guides/workflows-teams/versioning-release-workflows/) --- title: "Versionierungs-Workflows" description: "So synchronisieren Sie Dokumentations-Releases mit Software-Deployments unter Verwendung der Versionierungs-Engine und der Promotions-Strategien von docmd." --- ## Problem Die Synchronisierung von Software-Releases mit den entsprechenden Dokumentations-Updates ist eine erhebliche Koordinationsherausforderung. Häufig wird die Dokumentation auf der Live-Site aktualisiert, bevor der neue Code bereitgestellt wurde (was aktuelle Benutzer verwirrt), oder sie wird erst Tage nach dem Release veröffentlicht (was Early Adopters frustriert). ## Warum es wichtig ist Eine Desynchronisierung zwischen dem Verhalten der Software und ihrer Dokumentation ist eine Hauptursache für Frustration bei Entwicklern. Damit Dokumentation effektiv ist, muss sie strikt der spezifischen Version der Software entsprechen, die der Benutzer gerade verwendet. Die Bereitstellung des korrekten Kontextes für jede Version gewährleistet ein reibungsloses Onboarding- und Troubleshooting-Erlebnis. ## Ansatz Isolieren Sie die Dokumentation für die aktive Entwicklung mithilfe der [Versionierungs-Engine](../../configuration/versioning) von `docmd`. Dies ermöglicht es Ihrem Team, Inhalte für kommende Funktionen asynchron in einem separaten Verzeichnis (z. B. `docs-next/`) zu entwerfen und sie erst dann in den Status "Stabil" oder "Aktuell" zu befördern, wenn das offizielle Software-Release erfolgt. ## Implementierung ### 1. Verzeichnisstruktur organisieren Behalten Sie Ihre stabile Dokumentation im primären `docs/`-Ordner bei und erstellen Sie ein dediziertes Verzeichnis für das kommende Release. ```text projekt-root/ ├── docs/ # Aktuell Stabil (v1.x) ├── docs-v2/ # Kommendes Release (v2.0) └── docmd.config.js ``` ### 2. Versionen konfigurieren Registrieren Sie beide Versionen in Ihrer Konfiguration. Sie können die kommende Version als "Beta" oder "Next" kennzeichnen, um den Benutzern über den Versions-Switcher den Status zu signalisieren. ```javascript // docmd.config.js export default { versions: { current: 'v1.0', all: [ { id: 'v1.0', dir: 'docs', label: 'v1.x (Stabil)' }, { id: 'v2.0', dir: 'docs-v2', label: 'v2.0 (Beta)' } ] } }; ``` ### 3. Der Promotions-Prozess Wenn Sie bereit sind, die neue Version offiziell zu veröffentlichen: 1. **Konfiguration aktualisieren**: Ändern Sie die `current` Versions-ID in `docmd.config.js` auf `v2.0`. 2. **Labels aktualisieren**: Entfernen Sie den "(Beta)"-Tag vom `label` im `all`-Array. 3. **Alte Dokumentation archivieren**: Behalten Sie den `v1.0`-Eintrag im `all`-Array bei, damit Benutzer älterer Versionen weiterhin auf die für sie relevante Dokumentation zugreifen können. ## Abwägungen ### Wartungsaufwand Die Pflege mehrerer Dokumentationsversionen erfordert Disziplin. Wenn ein kritischer Tippfehler oder eine Sicherheitswarnung in der stabilen Version korrigiert wird, stellen Sie sicher, dass dies auch auf das Verzeichnis der kommenden Version angewendet wird, um "Regressionen" in der Klarheit zu vermeiden. ### SEO und Suche Mehrere Versionen können gelegentlich dazu führen, dass Suchergebnisse auf ältere Dokumentationen verweisen. Verwenden Sie das `seo`-Plugin und korrekte Canonical-Tags, um sicherzustellen, dass die "Aktuelle" Version von Suchmaschinen immer priorisiert wird. Weitere Informationen zum Verwalten von Übergängen finden Sie unter [Umgang mit Breaking Changes](../scaling-architecture/breaking-changes-deprecations). --- ## [docmd Dokumentation: Zero-Config Docs aus Markdown](https://docs.docmd.io/de/07/) --- title: "docmd Dokumentation: Zero-Config Docs aus Markdown" description: "Erstellen Sie in Sekundenschnelle produktionsreife Dokumentationen aus Markdown. Zero Setup, standardmäßig schnell, SEO-freundlich und KI-bereit." titleAppend: false --- ::: hero # docmd Von Markdown zu produktionsreifen Dokumenten mit einem einzigen Befehl. Statisches HTML für SEO. SPA für Geschwindigkeit. Standardmäßig KI-bereit. ::: button "Erste Schritte" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#333 icon:github ::: ## Start Starten Sie eine produktionsreife Dokumentationsseite in Sekunden - ohne Boilerplate, ohne Konfigurationsdateien. ```bash npx @docmd/core dev ``` Das ist alles. Schreiben Sie Markdown in einen `docs/`-Ordner und docmd erstellt eine vollständige Dokumentationsseite mit Navigation, Suche, SEO, Sitemap und mehr - alles direkt einsatzbereit. ## Kernfunktionen Alles, was Sie brauchen, ist bereits enthalten. Keine Plugins für die Essentials erforderlich. ::: grids ::: grid ::: card "Sofortiges Setup" icon:rocket Ein Befehl, um von Markdown-Dateien zu einer produktionsreifen Dokumentationsseite zu gelangen. Keine Konfigurationsdateien erforderlich. ::: ::: ::: grid ::: card "KI-optimiert" icon:brain-circuit Generiert automatisch `llms.txt` und `llms-full.txt` für die Nutzung von LLMs. Ihre Dokumentation ist standardmäßig KI-bereit. ::: ::: ::: grid ::: card "Integrierte Suche" icon:search Clientseitige Volltextsuche, unterstützt durch MiniSearch. Funktioniert über Versionen und Sprachen hinweg ohne Konfiguration. ::: ::: ::: grid ::: card "Live-Vorschau" icon:monitor Betten Sie interaktive, editierbare Code-Sandboxes direkt in Ihre Dokumentationsseiten ein. ::: ::: ::: grid ::: card "Theming-Engine" icon:palette Wechseln Sie zwischen integrierten Themes oder erstellen Sie Ihr eigenes. Unterstützt Hell-, Dunkel- und System-Modus. ::: ::: ::: grid ::: card "Native i18n" icon:globe Erstklassige Mehrsprachigkeitsunterstützung mit sprachspezifischen URLs, Suche pro Sprache und übersetzten UI-Strings. ::: ::: ::: ## Markdown erweitern Gehen Sie über statischen Text hinaus. docmd bietet eine reiche Container-Syntax direkt in Markdown - Callouts, Tabs, Karten, Raster, Hero-Bereiche, ausklappbare Abschnitte und mehr. ::: button "Container erkunden" ./content/containers/index.md icon:blocks ::: grids ::: grid ::: card "Interaktive Sandboxes" Betten Sie interaktive, editierbare Vorschaufenster natürlich in Ihre Seiten ein, indem Sie die [Live Preview](./content/live-preview.md) API nutzen. ::: ::: ::: grid ::: card "Inline-Kollaboration" Wählen Sie Text im Entwicklungsmodus aus, um [Threads](./plugins/threads.md) zu öffnen und Kommentare mit Ihrem Dokumentationsteam zu hinterlassen. ::: ::: ::: --- ## [Migration von Docusaurus](https://docs.docmd.io/de/07/migration/docusaurus/) --- title: "Migration von Docusaurus" description: "Ein umfassender Leitfaden zum Umzug Ihres Docusaurus v2/v3-Projekts zu docmd." --- # Migration von Docusaurus zu docmd Docusaurus ist ein beliebtes Dokumentations-Framework, das auf React basiert. `docmd` bietet eine schnelle, konfigurationsfreie Alternative, die deutlich schneller kompiliert und keine React-Komponenten benötigt, um umfangreiche Funktionen zu rendern. ## Schritt 1: Ausführen der Migration-Engine Führen Sie den folgenden Befehl im Root-Verzeichnis Ihres bestehenden Docusaurus-Projekts aus (dort, wo sich Ihre `docusaurus.config.js` oder `docusaurus.config.ts` befindet): ```bash npx @docmd/core migrate --docusaurus ``` ### Was automatisch passiert 1. **Backup**: Ihr gesamtes Projekt (außer `node_modules` und `.git`) wird sicher in ein neues Verzeichnis `docusaurus-backup/` verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Root-Verzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. 3. **Konfigurationserstellung**: Eine `docmd.config.js` wird generiert, wobei der Seitentitel (`title`) aus Ihrer Docusaurus-Konfiguration extrahiert wird. ## Schritt 2: Testen des Setups Sobald der Befehl abgeschlossen ist, können Sie Ihre Markdown-Inhalte sofort in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Seitenleiste wird leer sein. ## Schritt 3: Manuelle Konfiguration Docusaurus verfügt über komplexe programmatische Konfigurationen, die `docmd` nicht zu erraten versucht. Diese müssen Sie manuell zuordnen. ### 1. Navigations-Setup Docusaurus-Seitenleisten werden oft automatisch generiert oder in `sidebars.js` konfiguriert. **Erforderliche Aktion:** Erstellen Sie eine `navigation.json` in Ihrem neuen `docs/`-Verzeichnis, um Ihre `docmd`-Seitenleiste zu strukturieren. Siehe den [Leitfaden zur Navigation](../configuration/navigation.md). ### 2. Ersetzen von MDX-Komponenten Docusaurus stützt sich stark auf MDX (`.mdx`), um benutzerdefinierte React-Komponenten (wie Tabs, Admonitions oder benutzerdefinierte UI-Elemente) zu rendern. `docmd` wird rein über Markdown gesteuert und verwendet kein React. **Erforderliche Aktion:** Sie müssen alle benutzerdefinierten `<MyReactComponent />`-Tags in Standard-Markdown umwandeln oder die nativen [Container](../content/containers/callouts.md) von `docmd` verwenden. #### Beispiel: Umwandeln von Admonitions (Hinweisen) **Docusaurus:** ```markdown :::tip Mein Tipp Dies ist ein hilfreicher Tipp. ::: ``` **docmd:** (Die Lernkurve ist fast bei Null, außer einigen geänderten Schlüsselwörtern für eine bessere Benutzererfahrung. `docmd` unterstützt nativ Admonitions im Docusaurus-Stil als Callouts). ```markdown ::: callout tip "Mein Tipp" Dies ist ein hilfreicher Tipp. ::: ``` #### Beispiel: Umwandeln von Tabs **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> Dies ist ein Apfel. </TabItem> <TabItem value="orange" label="Orange"> Dies ist eine Orange. </TabItem> </Tabs> ``` **docmd:** (Umwandlung in die native `docmd`-Tabs-Container-Syntax) ```markdown ::: tabs == tab "Apple" Dies ist ein Apfel. == tab "Orange" Dies ist eine Orange. ::: ``` ### 3. Lokalisierung (i18n) Wenn Sie die `i18n`-Funktionen von Docusaurus verwendet haben, befanden sich Ihre übersetzten Dateien wahrscheinlich in `i18n/locale/docusaurus-plugin-content-docs/current/`. **Erforderliche Aktion:** Verschieben Sie diese Dateien in die Verzeichnisstruktur von `docmd` (`docs/en/`, `docs/de/` usw.) und konfigurieren Sie die Locales in der `docmd.config.js`. Siehe den [Leitfaden zur Lokalisierung](../configuration/localisation/index.md). ## Nächste Schritte - Entdecken Sie die Einstellungen für [Layout & UI](../configuration/layout-ui.md), um Ihr Docusaurus-Theme anzupassen. - Wandeln Sie React-basierte Hero-Header in `docmd` [Hero-Container](../content/containers/hero.md) um. --- ## [Migration von MkDocs](https://docs.docmd.io/de/07/migration/mkdocs/) --- title: "Migration von MkDocs" description: "Ein umfassender Leitfaden zum Umzug Ihres MkDocs- (oder Material for MkDocs-) Projekts zu docmd." --- # Migration von MkDocs zu docmd MkDocs, insbesondere mit dem Material-Theme, ist ein beliebter Python-basierter Dokumentationsgenerator. `docmd` bietet eine ähnliche Markdown-First-Erfahrung, setzt jedoch auf Node.js/Bun für unglaublich schnelle Builds und reichhaltige interaktive Funktionen, ohne dass komplexe Python-Erweiterungen erforderlich sind. ## Schritt 1: Ausführen der Migration-Engine Führen Sie den folgenden Befehl im Root-Verzeichnis Ihres bestehenden MkDocs-Projekts aus (dort, wo sich Ihre `mkdocs.yml` befindet): ```bash npx @docmd/core migrate --mkdocs ``` ### Was automatisch passiert 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues Verzeichnis `mkdocs-backup/` verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Root-Verzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. 3. **Konfigurationserstellung**: Eine `docmd.config.js` wird generiert, wobei der Projektname (`site_name`) aus Ihrer `mkdocs.yml` extrahiert wird. ## Schritt 2: Testen des Setups Sobald der Befehl abgeschlossen ist, zeigen Sie Ihre Inhalte in `docmd` in der Vorschau an: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Seitenleiste wird leer sein. ## Schritt 3: Manuelle Konfiguration MkDocs verwendet die `mkdocs.yml`, um die Navigation und Erweiterungen der Website zu definieren. Sie müssen dieses Setup auf `docmd` übertragen. ### 1. Navigations-Setup In MkDocs wird die Navigation strikt im Schlüssel `nav` der `mkdocs.yml` definiert. **Erforderliche Aktion:** Sie müssen eine `navigation.json` in Ihrem `docs/`-Ordner erstellen. **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "Startseite", "path": "/" }, { "title": "Leitfaden", "collapsible": true, "children": [ { "title": "Einrichtung", "path": "/setup" }, { "title": "Nutzung", "path": "/usage" } ] } ] ``` ### 2. Ersetzen von Python-Markdown-Erweiterungen Wenn Sie "Material for MkDocs" verwendet haben, haben Sie sich wahrscheinlich auf Python-Markdown-Erweiterungen wie PyMdown Extensions für Tabs, Admonitions oder Aufgabenlisten verlassen. **Erforderliche Aktion:** Wandeln Sie die MkDocs-spezifische Erweiterungssyntax in die nativen [Container](../content/containers/callouts.md) von `docmd` um. #### Beispiel: Umwandeln von Admonitions (Hinweisen) **MkDocs (PyMdown):** ```markdown !!! note "Optionaler Titel" Dies ist ein Inhaltsblock für einen Hinweis. ``` **docmd:** ```markdown ::: callout info "Optionaler Titel" Dies ist ein Inhaltsblock für einen Hinweis. ::: ``` #### Beispiel: Umwandeln von Tabs **MkDocs (SuperFences):** ```markdown === "Tab 1" Inhalt für Tab 1. === "Tab 2" Inhalt für Tab 2. ``` **docmd:** ```markdown ::: tabs == tab "Tab 1" Inhalt für Tab 1. == tab "Tab 2" Inhalt für Tab 2. ::: ``` ## Nächste Schritte - `docmd` verfügt über eine integrierte Suche. Sie müssen kein Such-Plugin konfigurieren. - Entdecken Sie die [Theme-Optionen](../theming/customisation.md), um die Farben Ihrer Website an Ihr altes Material-Theme anzupassen. --- ## [Migrationsübersicht](https://docs.docmd.io/de/07/migration/overview/) --- title: "Migrationsübersicht" description: "Erfahren Sie, wie Sie Ihre bestehende Dokumentation einfach auf docmd migrieren können." --- # Migration zu docmd `docmd` bietet eine vollautomatische **Migrations-Engine**, mit der Sie mit nur einem einzigen Befehl von alten oder konkurrierenden Dokumentationsplattformen wechseln können. Das Ziel der Migrations-Engine ist es, Ihnen die mühsame Arbeit des Verschiebens von Markdown-Dateien und der Umstrukturierung Ihres Projektverzeichnisses abzunehmen. ## Wie es funktioniert Der Migrationsbefehl führt Folgendes aus: 1. **Erkennt** Ihre bestehende Konfigurationsdatei (z.B. `docusaurus.config.js`, `mkdocs.yml`). 2. **Extrahiert** grundlegende Metadaten wie den `title` Ihrer Website. 3. **Sichert** Ihre bestehenden Dateien und Verzeichnisse sicher in einem `*-backup/`-Verzeichnis (z.B. `docusaurus-backup/`). 4. **Kopiert** Ihre Markdown-Inhalte in das standardmäßige `docmd` `docs/`-Verzeichnis. 5. **Erzeugt** eine neue, speziell auf Ihre Inhalte zugeschnittene `docmd.config.js`. Anschließend können Sie direkt `npx @docmd/core dev` ausführen, um Ihre Inhalte sofort in der `docmd`-Engine zu sehen. ## Was wird migriert? | Funktion | Automatisch migriert? | | :--- | :--- | | **Markdown-Dateien** | ✅ Ja, alle `.md` und `.mdx` Dateien werden nach `docs/` verschoben | | **Verzeichnisstruktur** | ✅ Ja, Ihre Ordner-Verschachtelung bleibt erhalten | | **Website-Titel** | ✅ Ja, aus Ihrer Konfiguration extrahiert | | **Container-Syntax** | ✅ Ja, VitePress/Docusaurus-Container funktionieren ohne Änderungen | | **Navigation / Sidebar** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Lokalisierung (i18n)** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Versionierung** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Eigene React/Vue-Komponenten** | ❌ Nein, diese müssen durch `docmd` Container ersetzt werden | ::: callout success "Container-Syntax-Kompatibilität" Ab `docmd` 0.7.8 funktioniert die Container-Syntax von **VitePress** (`:::tip`, `:::warning`, `:::danger`, `:::info`, `:::details`) und **Docusaurus** (`:::note`, `:::caution`) ohne Änderung. Ihre bestehenden Admonitions und ausklappbaren Abschnitte werden in `docmd` korrekt gerendert. **MkDocs** verwendet `!!!`-Syntax, die eine manuelle Konvertierung in das `:::`-Format erfordert. ::: ## Warum Navigation und i18n nicht automatisch migriert werden Jede Dokumentationsplattform behandelt Navigations-Sidebars, Übersetzungen und Multi-Versionierung unterschiedlich. Beispielsweise verwendet Docusaurus komplexe JavaScript-Objekte oder automatisch generierte Sidebars, während MkDocs auf strikt eingerückte YAML-Strukturen setzt. Um fehlerhafte Migrationen durch das Erraten komplexer Konfigurationen zu vermeiden, verschiebt `docmd` Ihre Inhalte sicher und bittet Sie darum, die Navigation, Lokalisierung und Versionierung mithilfe der einfachen JSON-basierten APIs von `docmd` nativ zu konfigurieren. - **Navigation:** Erfahren Sie unter [Navigations-Setup](../configuration/navigation.md), wie Sie eine `navigation.json` erstellen. - **Lokalisierung:** Lesen Sie den [Leitfaden zur Lokalisierung](../configuration/localisation/index.md), um mehrsprachige Dokumentationen einzurichten. - **Versionierung:** Beziehen Sie sich auf das [Versions-Setup](../configuration/versioning.md). ## Unterstützte Plattformen Wählen Sie Ihre aktuelle Plattform für spezifische Migrationsanweisungen aus: - [Von Docusaurus migrieren](./docusaurus.md) - [Von MkDocs migrieren](./mkdocs.md) - [Von VitePress migrieren](./vitepress.md) - [Von Astro Starlight migrieren](./starlight.md) --- ## [Von Astro Starlight migrieren](https://docs.docmd.io/de/07/migration/starlight/) --- title: "Von Astro Starlight migrieren" description: "Ein umfassender Leitfaden zur Migration Ihres Astro Starlight-Projekts zu docmd." --- # Von Astro Starlight migrieren zu docmd Starlight ist ein hervorragendes Dokumentations-Theme, das auf dem Astro-Framework basiert. `docmd` bietet eine ähnliche Standarderfahrung ohne JavaScript, macht jedoch die Konfiguration eines vollständigen Web-Frameworks (Astro) überflüssig, was die Lernkurve für technische Redakteure drastisch reduziert. ## Schritt 1: Führen Sie die Migrations-Engine aus Führen Sie den folgenden Befehl im Hauptverzeichnis Ihres bestehenden Starlight-Projekts aus (dort, wo sich Ihre `astro.config.mjs` befindet): ```bash npx @docmd/core migrate --starlight ``` ### Was passiert automatisch 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues `starlight-backup/`-Verzeichnis verschoben. 2. **Inhaltsmigration**: Starlight speichert die Dokumentation in `src/content/docs/`. Die Migrations-Engine extrahiert dieses spezifische Verzeichnis automatisch und verschiebt seinen Inhalt zur Nutzung durch `docmd` in den Stammordner `docs/`. 3. **Konfigurationsgenerierung**: Eine `docmd.config.js` wird generiert, die Ihren Website-`title` aus der Starlight-Integration innerhalb der `astro.config.mjs` extrahiert. ## Schritt 2: Testen Sie das Setup Sobald der Befehl abgeschlossen ist, können Sie Ihre Inhalte in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Sidebar bleibt zunächst leer. ## Schritt 3: Manuelle Konfiguration ### 1. Navigations-Setup Starlight definiert die Navigation in der `astro.config.mjs` über das Array `sidebar`. **Aktion erforderlich:** Sie müssen eine `navigation.json` in Ihrem neuen `docs/`-Ordner erstellen. **Starlight (`astro.config.mjs`):** ```js sidebar: [ { label: 'Guides', items: [ { label: 'Setup', link: '/guides/setup/' } ], }, ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. Astro-Komponenten ersetzen (MDX/Markdoc) Starlight verwendet Astro-Komponenten (`<Tabs>`, `<Card>` usw.), die über MDX oder Markdoc eingebettet sind. Da sich `docmd` auf reine Markdown-Syntax anstelle von UI-Komponenten verlässt, müssen diese konvertiert werden. **Aktion erforderlich:** Ersetzen Sie Astro-Komponenten durch `docmd` [Container](../content/containers/callouts.md). #### Beispiel: Tabs konvertieren **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### Beispiel: Admonitions (Asides) konvertieren **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter-Zuordnung Starlight verfügt über eine strikte Frontmatter-Typisierung über Astro Content Collections. Das Frontmatter von `docmd` ist einfacher gehalten. Wenn Sie in Starlight `hero`- oder `banner`-Frontmatter-Eigenschaften für Landingpages verwendet haben, müssen Sie diese durch [Hero-Bereiche](../content/containers/hero.md) von `docmd` ersetzen, die direkt in den Markdown-Text geschrieben werden. ## Nächste Schritte - Entdecken Sie das integrierte [Such-Plugin](../plugins/search.md) von `docmd` (Starlight verwendet Pagefind, während `docmd` nativ einen hochoptimierten lokalen Suchindexer mitliefert). --- ## [Von VitePress migrieren](https://docs.docmd.io/de/07/migration/vitepress/) --- title: "Von VitePress migrieren" description: "Ein umfassender Leitfaden zur Migration Ihres VitePress-Projekts zu docmd." --- # Von VitePress migrieren zu docmd VitePress ist ein schnelles, Vue-basiertes SSG-Framework. Genau wie VitePress ist `docmd` außergewöhnlich schnell, erreicht dies jedoch, indem absolut keine JavaScript-Framework-Logik an den Client ausgeliefert wird (kein Overhead durch Vue-Hydration). ## Schritt 1: Führen Sie die Migrations-Engine aus Führen Sie den folgenden Befehl im Hauptverzeichnis Ihres bestehenden VitePress-Projekts aus: ```bash npx @docmd/core migrate --vitepress ``` ### Was passiert automatisch 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues `vitepress-backup/`-Verzeichnis verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Stammverzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. Der versteckte `.vitepress`-Konfigurationsordner wird vollständig aus dem neuen `docs/`-Verzeichnis entfernt, um Konflikte zu vermeiden. 3. **Konfigurationsgenerierung**: Eine `docmd.config.js` wird generiert, die Ihren Website-`title` aus Ihrer `.vitepress/config.js` oder `.ts` extrahiert. ## Schritt 2: Testen Sie das Setup Sobald der Befehl abgeschlossen ist, können Sie Ihre Inhalte in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Sidebar bleibt zunächst leer. ## Schritt 3: Manuelle Konfiguration VitePress konfiguriert die Navigation in seiner Konfigurationsdatei und verwendet Vue-Komponenten innerhalb von Markdown. Sie müssen diese auf `docmd` umstellen. ### 1. Navigations-Setup VitePress verwendet ein Array von Objekten unter `themeConfig.sidebar`. **Aktion erforderlich:** Erstellen Sie eine `navigation.json` in Ihrem `docs/`-Verzeichnis. **VitePress (`.vitepress/config.js`):** ```js themeConfig: { sidebar: [ { text: 'Guide', items: [ { text: 'Introduction', link: '/introduction' }, { text: 'Getting Started', link: '/getting-started' } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. Vue-Komponenten ersetzen VitePress erlaubt es Autoren, Vue-Komponenten (z. B. `<MyComponent />`) direkt in Markdown-Dateien einzubetten. Da `docmd` Vue nicht auf dem Client ausführt, müssen Sie diese benutzerdefinierten Komponenten entfernen oder durch natives Markdown ersetzen. **Aktion erforderlich:** Ersetzen Sie Vue-spezifische UI-Komponenten durch `docmd` [Container](../content/containers/callouts.md). #### Beispiel: Admonitions (Benutzerdefinierte Container) VitePress verwendet eine benutzerdefinierte Block-Syntax für markdown-it, die der von `docmd` sehr ähnlich sieht. **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` *Hinweis: VitePress verwendet `info`, `tip`, `warning`, `danger`, `details`. `docmd` unterstützt diese direkt, aber Sie möchten sich möglicherweise die vollständige Liste der [docmd Callouts](../content/containers/callouts.md) ansehen.* ## Nächste Schritte - Entdecken Sie den `docmd`-Leitfaden [Bauen & Bereitstellen](../deployment/index.md), da `docmd` nicht auf die Build-Pipeline von Vite angewiesen ist. --- ## [Analytics-Plugin](https://docs.docmd.io/de/07/plugins/analytics/) --- title: "Analytics-Plugin" description: "Integrieren Sie Google Analytics 4 oder Legacy Universal Analytics und verfolgen Sie Benutzerinteraktionen automatisch." --- Das Plugin `@docmd/plugin-analytics` ermöglicht es Ihnen, Google Analytics nahtlos in Ihre Dokumentation zu integrieren. Es unterstützt den modernen Google Analytics 4 (GA4) Standard, das ältere Universal Analytics (UA) und beinhaltet natives Event-Tracking für interaktionsreiche Dokumentationsseiten. ## Konfiguration Aktivieren Sie Analytics, indem Sie Ihre Tracking-Anmeldedaten zum Abschnitt `plugins` der `docmd.config.js` hinzufügen. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { analytics: { // 1. Google Analytics 4 (Empfohlen) googleV4: { measurementId: 'G-XXXXXXX' }, // 2. Älteres Universal Analytics googleUA: { trackingId: 'UA-XXXXXXX-X' }, // 3. Einstellungen für Verhaltens-Tracking autoEvents: true, // Klicks, Downloads und TOC-Interaktionen verfolgen trackSearch: true // Von Lesern verwendete Suchbegriffe verfolgen } } }); ``` ## Verfolgte Ereignisse (Events) Wenn `autoEvents` aktiviert ist, erfasst das Plugin automatisch die folgenden Benutzerinteraktionen und sendet sie an Ihren Analytics-Anbieter: * **Externe Links**: Verfolgen, wann Benutzer die Seite für externe Ressourcen verlassen. * **Datei-Downloads**: Automatisches Protokollieren von Klicks auf Links mit dem `download`-Attribut oder gängigen Dateiendungen (`.pdf`, `.zip`, `.tar` etc.). * **Inhaltsverzeichnis (TOC)**: Überwachen, welche Abschnitte am interessantesten sind, indem Klicks in der rechten Seitennavigation verfolgt werden. * **Überschrift-Anker**: Protokollieren, wenn Benutzer auf „Permalinks“ (Anker von Überschriften) klicken, um spezifische Abschnitte zu teilen. * **Suchanfragen**: Wenn `trackSearch` aktiv ist, werden Suchbegriffe erfasst (mit einer Verzögerung von 1 Sekunde), um Ihnen zu helfen zu verstehen, wonach Ihre Benutzer suchen. ## Technische Details Das Plugin fügt die erforderlichen Tracking-Skripte in den `<head>` jeder Seite ein. Event-Listener werden unter Verwendung einer effizienten Ereignisdelegation an das `<body>`-Element angehängt, um sicherzustellen, dass keine Auswirkungen auf die Ladeleistung der Seite oder die Übergänge der Single Page Application (SPA) entstehen. ::: callout info "Datenschutz & DSGVO" Standardmäßig anonymisiert dieses Plugin IP-Adressen nicht, da dies nun nativ von GA4 gehandhabt wird. Wenn Sie ein erweitertes Cookie-Einwilligungsmanagement benötigen, können Sie Ihre Skripte für den Consent-Manager manuell über `customCss` oder einen benutzerdefinierten Plugin-Hook einbinden. ::: --- ## [Plugins entwickeln](https://docs.docmd.io/de/07/plugins/building-plugins/) --- title: "Plugins entwickeln" description: "Ein umfassender Leitfaden zur Erweiterung von docmd mit benutzerdefinierter Logik, Dateneinfügung und interaktiven Funktionen." --- Plugins sind der primäre Erweiterungsmechanismus für `docmd`. Sie ermöglichen das Einfügen von benutzerdefiniertem HTML, das Ändern der Markdown-Parslogik, das Einschleusen von Build-Zeit-Daten vor dem Template-Rendering und die Automatisierung von Post-Build-Aufgaben. Dieser Leitfaden beschreibt die Plugin-API und Best Practices für die Erstellung wiederverwendbarer Komponenten. ## Plugin-Deskriptor Jedes Plugin sollte einen `plugin`-Deskriptor exportieren, der seine Identität und Fähigkeiten deklariert. Dies ermöglicht der Engine, Fähigkeitsgrenzen beim Laden zu validieren, zu isolieren und durchzusetzen. ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` > **Hinweis:** Der Deskriptor ist derzeit optional (Soft-Deprecation-Warnung). Er wird **ab 0.8.0 erforderlich sein**. ## Kern-Fähigkeiten Das `capabilities`-Array bestimmt, welche Hooks Ihr Plugin verwenden darf. | Fähigkeit | Erlaubte Hooks | Phase | | :--- | :--- | :--- | | `init` | `onConfigResolved` | Init | | `markdown` | `markdownSetup` | Setup | | `head` | `generateMetaTags`, `generateScripts` (head) | Rendering | | `body` | `generateScripts` (body) | Rendering | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeRender`, `onPageReady` | Build | | `post-build`| `onPostBuild` | Post-Build | | `dev` | `onDevServerReady` | Dev-Server | | `assets` | `getAssets` | Ausgabe | | `actions` | `actions` | Interaktiv | | `events` | `events` | Interaktiv | | `translations`| `translations` | i18n | Legacy-Plugins ohne Deskriptor erhalten vollen Zugriff auf alle Hooks, sodass während der Übergangsphase nichts abbricht. ## Plugin-API-Referenz Ein `docmd`-Plugin ist ein Standard-JavaScript-Objekt (oder ein Modul, das eines als Standard exportiert), das einen oder mehrere der folgenden Hooks implementiert. | Hook | Beschreibung | | :--- | :--- | | `markdownSetup(md, opts)` | Erweitert die `markdown-it`-Instanz. Synchron. | | `generateMetaTags(config, page, root)` | Fügt `<meta>`- oder `<link>`-Tags in den `<head>` ein. | | `generateScripts(config, opts)` | Gibt ein Objekt mit `headScriptsHtml` und `bodyScriptsHtml` zurück. | | `getAssets(opts)` | Definiert externe Dateien oder CDN-Skripte zum Einbinden. | | `onPostBuild(ctx)` | Führt Logik nach der Generierung aller HTML-Dateien aus. | | `translations(localeId)` | Gibt ein Objekt mit übersetzten Strings für das angegebene Gebietsschema zurück. | | `actions` | Objekt mit benannten Aktions-Handlern für WebSocket-RPC-Aufrufe vom Browser. | | `events` | Objekt mit benannten Event-Handlern für Fire-and-Forget-Nachrichten vom Browser. | ## Ein lokales Plugin erstellen Ein Plugin zu erstellen ist so einfach wie das Definieren einer JavaScript-Datei. Zum Beispiel `my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, markdownSetup: (md, options) => { // Beispiel: Regel hinzufügen oder markdown-it-Plugin verwenden }, generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`Benutzerdefiniertes Plugin: ${pages.length} Seiten überprüft.`); } }; ``` Verweisen Sie in Ihrer `docmd.config.js` über den **vollständigen Paketnamen** auf Ihr Plugin: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { 'my-awesome-plugin': { // Ihre benutzerdefinierten Optionen hier } } }); ``` > **Hinweis:** Kurzformen (z.B. `math`, `search`) sind ausschließlich für offizielle `@docmd/plugin-*`-Pakete reserviert. Drittanbieter-Plugins müssen immer mit ihrem vollständigen npm-Paketnamen referenziert werden. ### Plugin-Isolierung Jeder Hook-Aufruf ist in eine try/catch-Grenze eingebettet. Ein defektes Plugin kann den Build nicht zum Absturz bringen oder andere Plugins stören. Fehler werden protokolliert und am Ende des Builds in einer Zusammenfassung gesammelt. ## Lebenszyklus-Hooks docmd bietet tiefe Integrations-Hooks, die es Plugins ermöglichen, Konfiguration, Rohquellen und Seitendaten während der gesamten Build-Pipeline zu manipulieren. | Hook | Beschreibung | Erwarteter Rückgabewert | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | Liest oder modifiziert die aktive normalisierte Konfiguration direkt nach der Initialisierung. | `void` oder `Promise<void>` | | **`onDevServerReady(server, wss)`** | Gibt den rohen Node.js `http.Server` und `WebSocketServer` im Entwicklungsmodus frei. | `void` oder `Promise<void>` | | **`onBeforeParse(src, frontmatter)`** | Vorverarbeitet rohe Markdown-Zeichenkettendaten unmittelbar bevor sie zur Analyse übergeben werden. | `string` oder `Promise<string>` | | **`onAfterParse(html, frontmatter)`** | Nachverarbeitet den generierten HTML-Code, der das Markdown-Body-Segment darstellt. | `string` oder `Promise<string>` | | **`onBeforeRender(page)`** | Wird vor dem Template-Rendering aufgerufen. Empfängt den vollständigen `PageContext`. Änderungen an `frontmatter` und `html` werden in der gerenderten Ausgabe widergespiegelt. | `void` oder `Promise<void>` | | **`onPageReady(page)`** | Greift auf die vollständig zusammengestellten Seitenmetadaten zu, kurz bevor die Seite in die Zieldatei geschrieben wird. | `void` oder `Promise<void>` | ### `onBeforeRender` und `PageContext` Der `onBeforeRender`-Hook ist der richtige Ort für Plugins, die Build-Zeit-Daten aus der Quelldatei einschleusen müssen - Datei-Metadaten lesen, benutzerdefinierte Frontmatter-Felder berechnen oder Daten aus externen Quellen laden. ```typescript interface PageContext { sourcePath: string; // Absoluter Pfad zur .md-Quelldatei. Immer gesetzt. frontmatter: Record<string, any>; // Veränderbar - Änderungen in der Template-Ausgabe widergespiegelt html: string; // Veränderbar - gerenderter Markdown-Body localeId?: string; versionId?: string; relativePathToRoot?: string; } ``` ```javascript export default { plugin: { name: 'my-metadata-plugin', version: '1.0.0', capabilities: ['build'] }, onBeforeRender: async (page) => { // sourcePath ist immer verfügbar - kein Raten oder Pfadkonstruktion nötig const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } }; ``` ## Vertiefung: Asset-Einbindung Der `getAssets()`-Hook ermöglicht es Ihrem Plugin, clientseitige Logik sicher zu bündeln. ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), dest: 'assets/js/plugin-init.js', type: 'js', location: 'body' } ]; } ``` ## Plugins übersetzen (i18n) Plugins, die clientseitige UI rendern, sollten übersetzbare Strings über den `translations(localeId)`-Hook bereitstellen. ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['translations', 'body'] }, translations: (localeId) => { try { const p = path.join(__dirname, 'i18n', `${localeId}.json`); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } try { const p = path.join(__dirname, 'i18n', 'en.json'); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } return {}; } } ``` ## WebSocket-RPC-Aktionen Plugins können **Aktions-Handler** und **Event-Handler** registrieren, die auf dem Dev-Server laufen und über die `window.docmd`-API vom Browser aufrufbar sind. ```javascript export default { plugin: { name: 'my-live-plugin', version: '1.0.0', capabilities: ['actions', 'events'] }, actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`Seite aufgerufen: ${data.path}`); } } }; ``` Das `ctx`-Objekt (ActionContext) bietet: | Methode | Beschreibung | | :--- | :--- | | `ctx.readFile(path)` | Liest eine Datei relativ zum Projektstamm. | | `ctx.writeFile(path, content)` | Schreibt eine Datei (löst Rebuild + Reload aus). | | `ctx.readFileLines(path)` | Liest eine Datei als Zeilenarray. | | `ctx.broadcast(event, data)` | Sendet ein Event an alle verbundenen Browser. | | `ctx.source` | Quellbearbeitungswerkzeuge für blockbasierte Markdown-Manipulation. | | `ctx.projectRoot` | Absoluter Pfad zum Projektstamm. | | `ctx.config` | Aktuelle docmd-Seitenkonfiguration. | ::: callout info "Nur Entwicklungsmodus 🛡️" Das WebSocket-RPC-System ist nur während `docmd dev` aktiv. Produktions-Builds enthalten weder den API-Client noch serverseitige Aktionsverarbeitung. ::: ## Best Practices 1. **Fähigkeiten deklarieren**: Exportieren Sie immer einen `plugin`-Deskriptor mit Ihren deklarierten Fähigkeiten. Ab `0.8.0` wird dies erforderlich sein. 2. **`onBeforeRender` für Dateneinfügung verwenden**: Wenn Ihr Plugin die Quelldatei liest oder Frontmatter-Felder berechnet, verwenden Sie `onBeforeRender` - nicht `generateMetaTags`. `sourcePath` ist im `PageContext` immer verfügbar. 3. **Async/Await**: Verwenden Sie immer `async`-Funktionen für `onPostBuild`, `onBeforeRender` und Aktions-Handler. 4. **Zustandslosigkeit**: Vermeiden Sie die Beibehaltung von Zustand im Plugin-Objekt, da `docmd` Plugins während Entwicklungs-Rebuilds neu initialisieren kann. 5. **Namenskonvention**: Für Community-Plugins, stellen Sie `docmd-plugin-` voran (z.B. `docmd-plugin-analytics`). 6. **Aktions-Namensräume**: Stellen Sie Ihren Plugin-Namen voran (z.B. `my-plugin:save-note`) um Kollisionen zu vermeiden. 7. **Aktionsvalidierung**: Definieren Sie immer ein explizites Payload-Schema in Ihren Aktionen. 8. **Logging**: Verwenden Sie den bereitgestellten `log()`-Helfer in `onPostBuild`. ::: callout tip "KI-optimiertes Design 🤖" Die `docmd`-Plugin-API ist **LLM-optimal** gestaltet. Da die Hooks Standard-JavaScript-Objekte und -Typen ohne versteckte komplexe Klassenhierarchien verwenden, können KI-Agenten fehlerfreie benutzerdefinierte Plugins mit minimaler Anleitung generieren. ::: --- ## [Git-Plugin](https://docs.docmd.io/de/07/plugins/git/) --- title: "Git-Plugin" description: "Zeigt Zeitstempel der letzten Aktualisierung und Commit-Verlauf direkt aus Ihrem Git-Repository an." --- Das **Git-Plugin** fügt Ihren Dokumentationsseiten Repository-basierte Metadaten hinzu. Es zeigt an, wann jede Seite zuletzt geändert wurde, wer beigetragen hat, und bietet optional einen "Diese Seite bearbeiten"-Link - alles direkt aus Ihrem Git-Verlauf ohne Konfiguration. ::: callout info "Core-Plugin" Das Git-Plugin ist in `@docmd/core` enthalten und standardmäßig aktiviert. Es erkennt automatisch, ob sich Ihr Projekt in einem Git-Repository befindet, und deaktiviert sich selbst, wenn nicht. Für die Grundfunktionalität ist keine Installation oder Konfiguration erforderlich. ::: ## Funktionen ### Zeitstempel der letzten Aktualisierung Jede Seite zeigt automatisch an, wann sie zuletzt geändert wurde. Der Zeitstempel wird aus dem letzten Git-Commit abgeleitet, der die Quelldatei betrifft. Zeitstempel verwenden relative Formatierung für aktuelle Änderungen ("vor 2 Std.", "vor 3 T.") und wechseln zu absoluten Daten für ältere Inhalte ("15. März 2026"). ### Commit-Verlauf-Tooltip Bewegen Sie den Mauszeiger über den Text "Zuletzt aktualisiert", um einen Tooltip mit den letzten Commits für diese Seite anzuzeigen. Jeder Eintrag zeigt die Commit-Nachricht, den Autor (mit Gravatar-Avatar) und den relativen Zeitstempel. Dies bietet schnellen Kontext über aktuelle Änderungen, ohne die Seite zu verlassen - nützlich, um zu verstehen, was aktualisiert wurde und von wem. ### Bearbeitungslinks Bei Konfiguration mit einer Repository-URL zeigt das Plugin einen "Diese Seite bearbeiten"-Link an, der die Quelldatei direkt im Web-Editor Ihres Git-Anbieters öffnet. ```javascript plugins: { git: { repo: 'https://github.com/ihre-org/ihre-docs', branch: 'main' } } ``` Das Plugin erkennt automatisch GitHub-, GitLab- und Bitbucket-URLs und erstellt das korrekte Bearbeitungslink-Format für jeden Anbieter. ## Konfiguration | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | Repository-URL (z.B. `https://github.com/org/repo`). Erforderlich für Bearbeitungslinks. | | `branch` | `string` | `'main'` | Branch-Name für Bearbeitungslinks. | | `editLink` | `boolean` | `true` | "Diese Seite bearbeiten"-Link anzeigen, wenn `repo` gesetzt ist. | | `lastUpdated` | `boolean` | `true` | Zeitstempel der letzten Aktualisierung anzeigen. | | `commitHistory` | `boolean` | `true` | Commit-Verlauf-Tooltip beim Hovern anzeigen. | | `maxCommits` | `number` | `6` | Maximale Anzahl der Commits im Tooltip. | | `dateFormat` | `string` | `'relative'` | Zeitstempel-Format: `relative` (relativ), `iso` (ISO-Format) oder `locale-aware` (lokalisiertes Format). | ### Vollständiges Beispiel ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { git: { repo: 'https://github.com/docmd-io/docs', branch: 'main', editLink: true, lastUpdated: true, commitHistory: true, maxCommits: 5 } } }); ``` ## Seitenspezifische Steuerung Deaktivieren Sie das Git-Plugin für bestimmte Seiten über Frontmatter: ```markdown --- title: "Interne Notizen" plugins: git: false --- Diese Seite zeigt keine Zeitstempel oder Bearbeitungslinks an. ``` ## Funktionsweise Das Plugin liest den Git-Verlauf zur Build-Zeit mit Standard-Git-Befehlen. Für jede Markdown-Datei: 1. Führt `git log` aus, um den Commit-Verlauf abzurufen 2. Extrahiert Zeitstempel, Autoren und Commit-Nachrichten 3. Fügt die Daten in den Seitenkontext ein 4. Client-seitiges JavaScript rendert die UI-Komponenten ::: callout tip "Performance" Git-Daten werden während des Build-Prozesses gecacht. Der Verlauf jeder Datei wird nur einmal abgefragt, unabhängig davon, wie oft die Seite gerendert wird (z.B. über mehrere Sprachen hinweg). ::: ## Anforderungen - Die Dokumentationsquelle muss sich in einem Git-Repository befinden - Git muss in der Build-Umgebung verfügbar sein - Dateien müssen mindestens einen Commit in ihrem Verlauf haben Seiten ohne Git-Verlauf (neue, noch nicht committete Dateien) zeigen keine Zeitstempel oder Commit-Verlauf an. ## Migration von editLink Wenn Sie zuvor die `editLink`-Konfigurationsoption verwendet haben, bietet das Git-Plugin dieselbe Funktionalität mit zusätzlichen Features: **Vorher (editLink-Konfiguration):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs', text: 'Diese Seite bearbeiten' } }); ``` **Nachher (Git-Plugin):** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', branch: 'main' } } }); ``` Das Git-Plugin erstellt automatisch die Bearbeitungs-URL aus Repository und Branch, sodass Sie den vollständigen Bearbeitungspfad nicht mehr manuell angeben müssen. ::: callout warning "Hinweis zur Veraltung" Die eigenständige `editLink`-Konfigurationsoption ist veraltet und wird in einer zukünftigen Version entfernt. Bitte migrieren Sie zum Git-Plugin für die Bearbeitungslink-Funktionalität. ::: ## Lokalisierung Das Plugin enthält Übersetzungen für alle UI-Strings. Unterstützte Sprachen: - Englisch (en) - Deutsch (de) - Chinesisch (zh) Benutzerdefinierte Übersetzungen können über das Standard-[UI-Strings](../configuration/localisation/ui-strings.md)-System bereitgestellt werden. --- ## [LLM Context Plugin](https://docs.docmd.io/de/07/plugins/llms/) --- title: "LLM Context Plugin" description: "Optimieren Sie Ihre Dokumentation für den KI-Konsum mit automatisierter Generierung von llms.txt und llms-full.txt." --- Das `@docmd/plugin-llms`-Plugin stellt sicher, dass Ihre Dokumentation perfekt für Large Language Models (LLMs) und KI-Agenten optimiert ist. Es folgt dem wachsenden Industriestandard, eine übergeordnete Zusammenfassung und eine umfassende Kontextdatei bereitzustellen, die KI-Tools einlesen können, um Ihr Projekt mit minimalen Halluzinationen zu verstehen. ## Konfiguration Das LLM-Plugin ist standardmäßig aktiviert. Damit es korrekt funktioniert, müssen Sie eine `url` in Ihrer `docmd.config.js` angeben. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ url: 'https://docs.example.com', plugins: { llms: { fullContext: true // Generiert llms-full.txt } } }); ``` ### Eine Seite ausschließen Wenn eine Seite sensible Informationen oder interne Notizen enthält, die KI-Modelle nicht lernen sollen, verwenden Sie das Flag `llms: false` in Ihrem Frontmatter: ```yaml --- title: "Interne Entwicklergeheimnisse" llms: false --- ``` ::: callout tip "Maximierung der KI-Genauigkeit :robot:" Detaillierte Best Practices zur Strukturierung Ihres Markdowns (semantische Überschriften, Alt-Text usw.) finden Sie in unserem Leitfaden [Optimierung für KI-Agenten](../guides/ai-optimisation/generating-ai-ready-docs.md). ::: --- ## [Math-Plugin](https://docs.docmd.io/de/07/plugins/math/) --- title: "Math-Plugin" description: "Native KaTeX/LaTeX-Mathematik-Integration für docmd." --- Das **Math-Plugin** fügt Ihren docmd-Websites native Unterstützung für LaTeX und KaTeX hinzu. Es nutzt `markdown-it-texmath` in sicherer Integration mit der `katex`-Engine, um sowohl Inline-Mathematik als auch mathematische Blöcke reibungslos zu rendern, ohne dass komplexe clientseitige JavaScript-Bibliotheken erforderlich sind. ## Setup ```bash docmd add math ``` ```javascript plugins: { math: {} } ``` ## Funktionsweise 1. Aktivieren Sie das Plugin über Ihre `docmd.config.js`. 2. Umschließen Sie Ihre Standard-LaTeX-Mathematik mit `$` (inline) oder `$$` (Block). 3. Der Server verarbeitet diese mathematischen Regeln während des Static-Site-Builds intelligent als reine statische HTML-Tags. 4. Minimal eingefügtes CSS übernimmt das Styling dieser Klassen automatisch, was zu einer sofortigen Visualisierung führt, sobald der Benutzer die Seite aufruft! ## Verwendung ### Inline-Mathematik Sie können Standard-Gleichungen mithilfe von einfachen Dollarzeichen `$` nahtlos in einen Textabschnitt einfügen: ```markdown Hier ist eine Inline-Gleichung: $E = mc^2$ ``` Hier ist eine Inline-Gleichung: $E = mc^2$ ### Mathematische Blöcke Verwenden Sie für umfangreichere mathematische Beweise oder eigenständige Formeln doppelte Dollarzeichen `$$` für die Blockformatierung: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid-Diagramme](https://docs.docmd.io/de/07/plugins/mermaid/) --- title: "Mermaid-Diagramme" description: "Erstellen Sie professionelle Architekturdiagramme, Flussdiagramme und Sequenzdiagramme direkt in Ihren Markdown-Dateien mithilfe der Mermaid.js-Syntax." --- Das `@docmd/plugin-mermaid`-Plugin integriert die leistungsstarke [Mermaid.js](external:https://mermaid.js.org/)-Engine in Ihre Dokumentations-Pipeline. Es ermöglicht Ihnen, reine Textbeschreibungen in hochauflösende, interaktive Diagramme zu verwandeln, ohne jemals Ihre Markdown-Umgebung verlassen zu müssen. ## Hauptmerkmale - **Zero Scripting**: Es ist nicht erforderlich, externe Skripte oder CDN-Links manuell einzubinden. `docmd` erkennt die Verwendung und injiziert die Rendering-Engine nur dort, wo sie benötigt wird. - **Theme-Bewusstsein**: Diagramme passen ihre Farbschemata automatisch an den Wechsel zwischen **Light**- und **Dark**-Mode Ihrer Website an. - **Isomorphes Lazy Loading**: Für optimale Performance werden Diagramme erst initialisiert und gerendert, wenn sie in das Sichtfeld des Benutzers gelangen. - **Interaktive Steuerung**: Jedes Diagramm verfügt über integrierte Funktionen für **Pan** (Schwenken), **Zoom** und **Vollbild**, um sicherzustellen, dass auch große Architekturdiagramme auf allen Bildschirmgrößen lesbar bleiben. - **Icon-Integration**: Umfassende Unterstützung für das Icon-Paket, sodass Sie die Syntax `icon:name` innerhalb von Architekturdiagrammen verwenden können. - **Technische Lesbarkeit**: Diagramme bleiben in Ihrem Quellcode reiner Text, was sie leicht versionierbar und für KI-Agenten lesbar macht. ## Konfiguration Um die Diagramm-Unterstützung zu aktivieren, fügen Sie das `mermaid`-Plugin zu Ihrer `docmd.config.js` hinzu: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { mermaid: {} // Aktiviert mit Zero-Config } }); ``` ## Implementierungsgalerie Um ein Diagramm zu rendern, platzieren Sie Ihre Mermaid-Syntax in einem Fenced Code Block mit der Sprachkennung `mermaid`. ### 1. Sequenzdiagramme Ideal zur Veranschaulichung von Interaktionen zwischen mehreren Systemkomponenten. ::: tabs == tab "Vorschau" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Gibt URL ein Browser->>Server: HTTP-Anfrage Server-->>Browser: HTTP-Antwort Browser-->>User: Zeigt Seite an ``` == tab "Markdown-Quelle" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Gibt URL ein Browser->>Server: HTTP-Anfrage Server-->>Browser: HTTP-Antwort Browser-->>User: Zeigt Seite an ``` ```` ::: ### 2. Analytische Diagramme Visualisieren Sie Daten mit integrierten Diagrammtypen wie Torten- oder Balkendiagrammen. ::: tabs == tab "Vorschau" ```mermaid pie title Projektzusammensetzung "Dokumentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI-Komponenten" : 10 ``` == tab "Markdown-Quelle" ````markdown ```mermaid pie title Projektzusammensetzung "Dokumentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI-Komponenten" : 10 ``` ```` ::: ### 3. Git-Workflows Visualisieren Sie Branching- und Merging-Strategien für Ihre Entwickler-Leitfäden. ::: tabs == tab "Vorschau" ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` == tab "Markdown-Quelle" ````markdown ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` ```` ::: ### 4. Architektur & Icons Verwenden Sie das integrierte **Lucide**-Icon-Paket, um detailreiche Architekturdiagramme zu erstellen, die zum visuellen Stil Ihrer Website passen. ::: tabs == tab "Vorschau" ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Datenbank] in api service disk(icon:hard-drive)[Speicher] in api db:L -- R:disk ``` == tab "Markdown-Quelle" ````markdown ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Datenbank] in api service disk(icon:hard-drive)[Speicher] in api db:L -- R:disk ``` ```` ::: ## Technische Implementierung Das Mermaid-Plugin fängt `mermaid`-Codeblöcke während der Parsing-Phase ab und hüllt sie in einen speziellen `<div class="mermaid">`-Container. 1. **Erkennung**: Die Engine scannt das gerenderte HTML nach dem Vorhandensein von Mermaid-Containern. 2. **Asset-Injektion**: Wenn Container gefunden werden, injiziert `docmd` ein leichtgewichtiges `init-mermaid.js`-Modul. 3. **Rendering**: Die Mermaid-Bibliothek wird asynchron geladen und rendert die Diagramme clientseitig. So bleibt Ihr initiales HTML-Paket klein und schnell. ::: callout tip "Diagramme für KI-Agenten" Während Diagramme für Menschen visuell hilfreich sind, sind sie für KIs technisch transparent. Da die Quelle reiner Text ist, können Modelle wie GPT-4 oder Claude Ihre Systemarchitektur oder Logikflüsse über den `llms-full.txt`-Stream "sehen". Dies ermöglicht es der KI, komplexe architektonische Beziehungen basierend auf Ihren Diagrammen zu erklären. ::: --- ## [OpenAPI-Plugin](https://docs.docmd.io/de/07/plugins/openapi/) --- title: "OpenAPI-Plugin" description: "Rendert OpenAPI 3.x API-Referenzdokumentation direkt aus JSON- oder YAML-Spezifikationsdateien in Ihren Markdown-Seiten." --- Das **OpenAPI-Plugin** wandelt OpenAPI 3.x Spezifikationsdateien in strukturierte API-Referenzseiten um - zur Build-Zeit gerendert, ohne clientseitiges JavaScript und ohne Drittanbieter-Abhängigkeiten. Jeder Endpunkt, Parameter, Request-Body und jede Response wird in semantische HTML-Tabellen konvertiert. ::: callout info "Kern-Plugin" Das OpenAPI-Plugin ist jetzt standardmäßig in `@docmd/core` **enthalten**. Eine separate Installation ist nicht erforderlich. Es folgt der Docmd-Philosophie des Build-Zeit-Renderings - das Plugin liest Ihre Spezifikation und gibt saubere, zugängliche HTML-Tabellen ohne clientseitiges JavaScript aus. ::: ## Installation ```bash docmd add openapi # oder manuell: npm install @docmd/plugin-openapi ``` In Ihrer Konfiguration aktivieren: ```javascript export default defineConfig({ plugins: { openapi: {} } }); ``` ## Verwendung Betten Sie eine OpenAPI-Spezifikation in jede Markdown-Seite ein, indem Sie einen umzäunten Codeblock mit dem `openapi`-Sprach-Tag verwenden: ````markdown ### Live-Beispiel ```openapi assets/docmd-api.json ``` ```` ### Ergebnis ```openapi assets/docmd-api.json ``` Der Pfad wird relativ zu Ihrem `src`-Verzeichnis aufgelöst. Sowohl **JSON** als auch **YAML**-Formate werden unterstützt. YAML erfordert die Installation von `js-yaml`: ```bash npm install js-yaml ``` ## Was gerendert wird Für jeden Pfad und jede HTTP-Methode in der Spezifikation rendert das Plugin: - **Methoden-Badge** - farbkodiert (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`) - **Pfad** - der vollständige Endpunkt-Pfad - **Zusammenfassung und Beschreibung** - aus dem Operationsobjekt - **Parameter-Tabelle** - Name, Position (`path`, `query`, `header`, `cookie`), Typ, Pflichtfeld, Beschreibung - **Request-Body-Tabelle** - Schema-Eigenschaften mit Typen und Standardwerten - **Response-Tabelle** - Status-Codes mit Beschreibungen und Response-Schema-Typen - **Veraltungshinweis** - als `deprecated: true` markierte Operationen werden inline gekennzeichnet ::: callout tip "Build-Zeit-Rendering" Alles Rendering erfolgt zur Build-Zeit. Die generierten Seiten sind vollständig statisch - kein JavaScript ist erforderlich, um die API-Dokumentation anzuzeigen, was schnelle Seitenladevorgänge und vollständige Suchindexierung bedeutet. ::: ## Unterstützte OpenAPI-Funktionen | Funktion | Unterstützung | | :--- | :--- | | OpenAPI 3.x | ✓ | | Swagger 2.x | ✗ (zuerst in 3.x konvertieren) | | JSON-Format | ✓ | | YAML-Format | ✓ (erfordert `js-yaml`) | | `$ref`-Auflösung | ✓ (interne `#/components/schemas/`-Refs) | | `oneOf` / `anyOf`-Typen | ✓ (als Union-Type-Strings angezeigt) | | Verschachtelte Schema-Tabellen | ✓ | | `deprecated`-Flag | ✓ | | Externe `$ref` (Remote-URLs) | ✗ (nur lokale Refs) | ## Konfiguration Das OpenAPI-Plugin kann in Ihrer `docmd.config.js` konfiguriert werden: ```javascript export default defineConfig({ plugins: { openapi: { info: true, // API-Titel und Versions-Header anzeigen download: true, // 'Download JSON/YAML'-Link in der Benutzeroberfläche bereitstellen summaryOnly: false, // Nur Zusammenfassungen anzeigen, Parameter/Antworten ausblenden allowRawHtml: false // HTML in Beschreibungen zulassen (mit Vorsicht verwenden) } } }); ``` | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `info` | `boolean` | `true` | Zeigt API-Titel, Version und Beschreibung aus dem `info`-Objekt der Spezifikation an. | | `download` | `boolean` | `false` | Wenn wahr, wird ein Link im Header der Spezifikation hinzugefügt, um die rohe JSON/YAML-Datei herunterzuladen/anzusehen. **Empfohlen für KI-Barrierefreiheit.** | | `summaryOnly` | `boolean` | `false` | Wenn wahr, werden nur Methode, Pfad und Zusammenfassung gerendert. Nützlich für große API-Indizes. | | `allowRawHtml` | `boolean` | `false` | Wenn wahr, wird das Escaping von HTML-Tags in Beschreibungen verhindert. | ## Seitenspezifische Steuerung Plugin für bestimmte Seiten über Frontmatter deaktivieren: ```markdown --- title: "Interne Notizen" plugins: openapi: false --- ``` --- ## [PWA & Offline-Support](https://docs.docmd.io/de/07/plugins/pwa/) --- title: "PWA & Offline-Support" description: "Verwandeln Sie Ihre Dokumentation in eine Progressive Web App mit Offline-Caching und mobil-optimierten Funktionen." --- Das **PWA-Plugin** verwandelt Ihre Dokumentation in eine Progressive Web App mit Offline-Caching und mobiler Installation. Es fügt ein Web-Manifest für die mobile Installation hinzu und registriert einen Service Worker für das intelligente Offline-Caching. So bleibt Ihre technische Dokumentation auch in Umgebungen mit schlechter Internetverbindung zugänglich. ## Setup ```bash docmd add pwa ``` ## Konfiguration Das PWA-Plugin kann innerhalb des Abschnitts `plugins` der `docmd.config.js` an Ihr Branding angepasst werden. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { pwa: { enabled: true, // Standardmäßig aktiviert, wenn das Plugin geladen ist themeColor: '#1e293b', // Die Primärfarbe der mobilen Benutzeroberfläche bgColor: '#ffffff', // Hintergrundfarbe für den Startbildschirm (Splash Screen) logo: '/assets/logo.png' // Fallback für App-Icons, falls nicht explizit definiert } } }); ``` ## Kernfunktionen ### 1. Offline-Caching Das Plugin generiert automatisch eine `service-worker.js`-Datei, die eine „Stale-While-Revalidate“-Caching-Strategie implementiert. Wenn ein Benutzer eine Seite besucht, tut der Service Worker Folgendes: * Er liefert sofort die im Cache gespeicherte Version für maximale Geschwindigkeit aus. * Er lädt im Hintergrund die neueste Version aus dem Netzwerk. * Er aktualisiert den Cache für den nächsten Besuch. ### 2. Mobile Installation Durch die Erstellung einer `manifest.webmanifest` und das Einfügen der erforderlichen `<meta>`-Tags ermöglicht das Plugin Benutzern unter iOS und Android die Funktion „Zum Home-Bildschirm hinzufügen“. Ihre Dokumentation verhält sich dann wie eine eigenständige Anwendung mit eigenem Startbildschirm und Fensterrahmen. ### 3. Intelligente Asset-Auflösung Das Plugin versucht, App-Icons automatisch zu generieren, indem es nach dem `logo` oder `favicon` Ihres Projekts sucht. Für mehr Kontrolle können Sie ein explizites `icons`-Array angeben: ```javascript pwa: { icons: [ { src: '/icons/icon-192x192.png', sizes: '192x192', type: 'image/png' }, { src: '/icons/icon-512x512.png', sizes: '512x512', type: 'image/png' } ] } ``` ## Technische Umsetzung Der Service Worker ist so konzipiert, dass er mit dem Single Page Application (SPA)-Routing kompatibel ist. Er enthält spezifische Ausfallsicherungslogik für die strengen Sicherheitsrichtlinien von Safari in Bezug auf umgeleitete Streams und gewährleistet so Stabilität in allen modernen Browsern. ::: callout tip "Entwicklungsmodus" Service Worker werden im lokalen Entwicklungsmodus (`docmd dev`) normalerweise deaktiviert oder umgangen, um zu verhindern, dass aggressives Caching Ihre Bearbeitungen stört. Um die PWA-Funktionalität zu testen, führen Sie einen Produktions-Build mit `docmd build` aus und stellen Sie das Ausgabe-Verzeichnis über einen statischen Host bereit. ::: ### Vollständiges Entfernen Löschen Sie einfach den `pwa`-Block aus Ihren `plugins`. Beim nächsten Ausführen von `docmd build` wird kein neues Manifest generiert. Wenn Benutzer die Website besuchen, prüft der clientseitige Bootstrap von docmd (`docmd-main.js`) das Vorhandensein von `<link rel="manifest">`. Falls dieser fehlt, aber ein Service Worker registriert ist, werden automatisch **alle vorhandenen Service Worker deregistriert** und der Cache geleert - es ist keine Aktion des Benutzers erforderlich. ::: callout warning Die Dateien `manifest.webmanifest` und `service-worker.js` aus einem vorherigen Build bleiben auf der Festplatte erhalten, bis Sie Ihr Ausgabe-Verzeichnis (standardmäßig `site/`) mit `docmd build` überschreiben oder mittels `rm -rf site` löschen. Dies ist ein Artefakt im Dateisystem, keine aktive PWA. ::: ## Konfigurationsreferenz Alle Felder sind optional. Die Standardwerte sind für die Nutzung ohne Konfiguration ausgelegt. ```javascript export default { plugins: { pwa: { // --- Icon-Konfiguration --- // Priorität: pwa.logo > config.logo > config.favicon > (keine Icons) logo: 'assets/images/app-icon.png', // Pfad relativ zu Ihrem Quellordner // Oder für die volle manuelle Kontrolle: icons: [ { src: '/assets/images/icon-192.png', sizes: '192x192', type: 'image/png' }, { src: '/assets/images/icon-512.png', sizes: '512x512', type: 'image/png' } ], // --- Manifest-Farben --- themeColor: '#1e293b', // Browser-Chrome / Primärfarbe der oberen Leiste bgColor: '#ffffff', // Hintergrund des Startbildschirms während der Installation // --- Das Plugin komplett deaktivieren --- enabled: false } } } ``` ### Priorität der Icon-Auflösung docmd löst Ihr PWA-Icon gemäß der folgenden Rangfolge auf: 1. `pwa.icons` - Manuelles Array, wird unverändert verwendet. 2. `pwa.logo` - Einzelner Bildpfad, wird für Einträge in 192x192 und 512x512 verwendet. 3. `config.logo` - Ihr globales Website-Logo. 4. `config.favicon` - Ihr globales Favicon. 5. *(Keine Icons im Manifest deklariert)* - Falls keiner der obigen Punkte gesetzt ist. ## Lokales Testen Browser beschränken Service Worker auf `https://` oder `localhost`. Verwenden Sie: ```bash docmd dev ``` Öffnen Sie die Chrome DevTools → **Application** → **Manifest** und **Service Workers**, um die aktivierte Registrierung in Echtzeit zu sehen. Das Safari-Panel → **Entwickler** → **Service-Worker** funktioniert gleichermaßen. --- ## [Such-Plugin](https://docs.docmd.io/de/07/plugins/search/) --- title: "Such-Plugin" description: "Aktivieren Sie eine extrem schnelle, Offline-first Volltextsuche für Ihre Dokumentation mit MiniSearch." --- Das `@docmd/plugin-search`-Plugin bietet ein leistungsstarkes, clientseitiges Sucherlebnis für Ihre Dokumentation. Es verwendet [MiniSearch](external:https://github.com/lucaong/minisearch), um während des Build-Prozesses einen leichtgewichtigen Index zu erstellen, der es Benutzern ermöglicht, technische Informationen sofort und ohne serverseitige Datenbank zu finden. ## Konfiguration Die Suche ist in den meisten `docmd`-Templates standardmäßig aktiviert. Sie können ihre Sichtbarkeit und Platzierung über die `layout`-Konfiguration steuern. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ layout: { optionsMenu: { position: 'header', // 'header', 'sidebar-top', 'sidebar-bottom' oder 'menubar' components: { search: true // Auf false setzen, um das Such-Plugin vollständig zu deaktivieren } } } }); ``` ## Funktionsweise ### 1. Indizierung (Build-Zeit) Während des `docmd build`-Prozesses iteriert das Such-Plugin über jede Seite Ihrer Website. Es extrahiert den Titel, Überschriften und den Fließtext und komprimiert diese Daten dann in eine `search-index.json`-Datei. * **Deep Linking**: Der Indexer registriert automatisch jede Überschrift (`#`, `##` etc.) als suchbares Ziel. * **Relevanz-Gewichtung**: Titel erhalten das höchste Gewicht, gefolgt von Überschriften und schließlich dem Seiteninhalt. ### 2. Abruf (Client-seitig) Wenn ein Benutzer das Suchmodal öffnet (normalerweise über `/` oder `Strg+K`), wird die `search-index.json` vom Browser geladen. Suchen werden lokal mit Fuzzy-Matching (erlaubt kleine Tippfehler) und sofortigem Präfix-Matching durchgeführt. ## Suchverhalten anpassen Obwohl das Such-Plugin auf Einfachheit ohne Konfiguration ausgelegt ist, können Sie bestimmte Seiten vom Index ausschließen, indem Sie das `noindex`-Flag in deren Frontmatter verwenden: ```yaml --- title: "Interne Spezifikation" noindex: true # Diese Seite wird nicht in den Suchergebnissen oder Sitemaps erscheinen --- ``` ## Technische Implementierung Das Plugin injiziert ein leichtgewichtiges Suchmodal in den `<body>` Ihrer Website. Es ist vollständig barrierefrei (ARIA-konform) und unterstützt die Tastaturnavigation für ein Erlebnis, das sich wie eine native App anfühlt. ::: callout tip "Such-Analyse" Wenn Sie das [Analytics-Plugin](./analytics.md) aktiviert haben, werden die von Ihren Lesern verwendeten Suchbegriffe automatisch erfasst und an Ihren Analytics-Anbieter gesendet. So erhalten Sie Einblicke, welche Informationen fehlen oder am schwersten zu finden sind. ::: Da die Suche vollständig auf dem Client stattfindet, werden niemals Daten - nicht einmal Tastaturanschläge - an einen Server gesendet. Dies macht `docmd` zum Goldstandard für die Dokumentationssuche in datenschutzsensiblen Branchen (Gesundheitswesen, Finanzen, Sicherheit). ## Vergleich Viele Dokumentationsgeneratoren (wie Docusaurus) verlassen sich auf **Algolia DocSearch**. Obwohl Algolia leistungsstark ist, bringt es Hürden mit sich: | Feature | docmd Suche | Algolia / Extern | | :--- | :--- | :--- | | **Einrichtung** | **Zero Config** (Automatisch) | Komplex (API-Keys, CI/CD Crawling) | | **Datenschutz** | **100% Privat** (Client-seitig) | Daten werden an Drittserver gesendet | | **Offline** | **Ja** | Nein | | **Kosten** | **Kostenlos** | Kostenloses Kontingent oder kostenpflichtig | | **Geschwindigkeit** | **Sofort** (In-Memory) | Schnell (Abhängig von Netzwerklatenz) | --- ## [SEO-Plugin](https://docs.docmd.io/de/07/plugins/seo/) --- title: "SEO-Plugin" description: "Optimieren Sie Ihre Dokumentation für Suchmaschinen und steuern Sie den Zugriff von KI-Crawlern mit nativer Meta-Tag-Generierung." --- Das `@docmd/plugin-seo`-Plugin ist für die Generierung hochwertiger Metadaten für jede Seite verantwortlich. Es stellt sicher, dass Ihre Dokumentation nicht nur von menschlichen Lesern in Suchmaschinen gefunden wird, sondern auch von KI-Modellen und Social-Media-Plattformen korrekt interpretiert wird. ## Globale Konfiguration Konfigurieren Sie projektweite SEO-Standardwerte in Ihrer `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { seo: { defaultDescription: 'Umfassende Dokumentation für das docmd-Ökosystem.', aiBots: false, // Auf false setzen, um gängige KI-Crawler (GPTBot etc.) zu blockieren openGraph: { defaultImage: '/assets/og-image.png' }, twitter: { siteUsername: '@docmd_io', cardType: 'summary_large_image' } } } }); ``` ## Überschreibungen auf Seitenebene Sie können SEO-Einstellungen für einzelne Seiten über das Frontmatter feinabstimmen. Einstellungen auf Seitenebene haben immer Vorrang vor globalen Standardwerten. ```yaml --- title: "Erweiterte Konfiguration" description: "Lernen Sie, wie Sie die interne Engine von docmd meistern." noindex: true # Diese spezifische Seite vor allen Suchmaschinen verbergen seo: keywords: ["docmd", "javascript", "ssg"] ogType: "article" canonicalUrl: "https://meineseite.de/kanonischer-pfad" aiBots: true # Globalen Block überschreiben, um KI-Zugriff auf diese Seite zu erlauben --- ``` ## Kernfunktionen ### 1. Intelligenter Beschreibungs-Fallback Wenn im Frontmatter oder in der globalen Konfiguration keine Beschreibung angegeben ist, extrahiert das Plugin automatisch die ersten 150 Zeichen des Fließtexts der Seite, um sie als `<meta name="description">` zu verwenden. So wird sichergestellt, dass jede Seite über grundlegende Metadaten für Suchergebnisse verfügt. ### 2. KI-Bot-Steuerung Durch das Setzen von `aiBots: false` injiziert das Plugin `noindex`-Anweisungen speziell für große KI-Crawler (einschließlich `GPTBot`, `Claude-Web` und `Google-Extended`). Dies ermöglicht es Ihnen, zwischen herkömmlicher Suchmaschinenindizierung und LLM-Trainingssitzungen zu unterscheiden. ### 3. Kanonische Auflösung Das Plugin generiert automatisch `<link rel="canonical">`-Tags basierend auf Ihrer `siteUrl`. Es verarbeitet Verzeichnisindizes intelligent und konvertiert `guide/index.html` in eine saubere kanonische `/guide/`-URL, um Probleme mit doppeltem Inhalt zu vermeiden. ### 4. Ansprechende Social-Media-Vorschauen Die native Unterstützung für Open Graph und Twitter Cards stellt sicher, dass Links zu Ihrer Dokumentation professionell aussehen, wenn sie auf Plattformen wie X (Twitter), LinkedIn und Discord geteilt werden. ::: callout tip "Sichtbarkeit in der Suche" Für die besten SEO-Ergebnisse stellen Sie sicher, dass Ihre `siteUrl` im Root Ihrer Konfiguration definiert ist. Ohne eine Basis-URL kann das Plugin keine absoluten kanonischen Links oder Pfade für Open-Graph-Bilder generieren. ::: ## Strukturierte Daten (LD+JSON) `docmd` kann automatisch das [Article Schema](external:https://developers.google.com/search/docs/appearance/structured-data/article) generieren, um Suchmaschinen bei der Anzeige von Rich Snippets zu unterstützen. ```yaml --- title: "Wie man ein docmd-Plugin erstellt" seo: ldJson: true --- ``` ::: callout tip "Strukturierte Daten" Ein gut konfiguriertes SEO-Plugin hilft KI-gestützten Suchmaschinen (wie SearchGPT oder Perplexity), Ihre Website genau zusammenzufassen. Durch die Bereitstellung klarer Beschreibungen und das Blockieren von Bots steuern Sie genau, wie KI-Modelle Ihre Inhalte online wahrnehmen und als Quelle verwenden. ::: --- ## [Sitemap-Plugin](https://docs.docmd.io/de/07/plugins/sitemap/) --- title: "Sitemap-Plugin" description: "Generieren Sie automatisch eine standardkonforme sitemap.xml für eine bessere Sichtbarkeit in Suchmaschinen." --- Das Plugin `@docmd/plugin-sitemap` generiert automatisch eine `sitemap.xml`-Datei im Stammverzeichnis Ihres Build-Ordners. Diese Datei bietet Suchmaschinen wie Google und Bing eine umfassende Karte der Architektur Ihrer Website und stellt sicher, dass alle Seiten - einschließlich Deep-Links innerhalb versionierter Dokumentationen - gecrawlt und indexiert werden. ## Konfiguration Aktivieren Sie die Sitemap-Generierung, indem Sie Ihre `siteUrl` in der Hauptkonfiguration angeben. Sie können die Crawling-Gewichtung verschiedener Abschnitte innerhalb des `plugins`-Objekts anpassen. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ siteUrl: 'https://docs.beispiel.de', // Erforderlich für die Sitemap-Generierung plugins: { sitemap: { defaultChangefreq: 'weekly', // 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never' defaultPriority: 0.8, // Standardgewichtung für normale Seiten rootPriority: 1.0 // Gewichtung für die Startseite (index.md) } } }); ``` ## Steuerungen auf Seitenebene Sie können das Sitemap-Verhalten für spezifische Seiten über das Frontmatter überschreiben. ```yaml --- title: "Archiv-Seite" priority: 0.3 # Niedrigere Gewichtung für alte Inhalte changefreq: "monthly" # Hinweis an Crawler, dass sich diese Seite selten ändert lastmod: "2024-03-15" # Explizites Setzen des letzten Änderungsdatums sitemap: false # Diese spezifische Seite aus der sitemap.xml ausschließen --- ``` ## Kernfunktionen ### 1. Automatische URL-Konstruktion Das Plugin löst Seitenpfade intelligent in ihre kanonischen öffentlichen URLs auf. Es verarbeitet Verzeichnis-Indizes automatisch und stellt sicher, dass `guide/index.html` als `https://meineseite.de/guide/` aufgeführt wird, um eine saubere URL-Struktur beizubehalten. ### 2. Entdeckung von Versionen Wenn Ihr Projekt [Versionierung](../configuration/versioning) verwendet, schließt das Sitemap-Plugin automatisch alle Seiten aus allen Versionen ein (z. B. `/v1/erste-schritte`, `/v2/erste-schritte`). Dies ermöglicht es Suchmaschinen, Ihre archivierten Dokumentationen ohne manuelle Konfiguration zu entdecken. ### 3. Intelligente Ausschlüsse Seiten, die in ihrem Frontmatter mit `noindex: true` oder `sitemap: false` markiert sind, werden automatisch von der generierten `sitemap.xml` ausgeschlossen. Dies gibt Ihnen eine granulare Kontrolle darüber, was den Suchmaschinen präsentiert wird. ::: callout tip "Validierung" Nach dem Build Ihrer Website finden Sie die Sitemap normalerweise unter `ihr-ausgabe-ordner/sitemap.xml`. Die meisten Search-Engine-Konsolen ermöglichen es Ihnen, diese Datei direkt einzureichen, um die Indexierung zu beschleunigen. ::: --- ## [Threads-Plugin](https://docs.docmd.io/de/07/plugins/threads/) --- title: "Threads-Plugin" description: "Fügen Sie Ihrer Dokumentation Inline-Diskussionsstränge hinzu - direkt in Ihren Markdown-Dateien gespeichert." --- Das **Threads-Plugin** bringt kollaborative Inline-Kommentare in Ihre Dokumentation. Wählen Sie einen beliebigen Text auf der Seite aus, hinterlassen Sie einen Kommentar, starten Sie eine Diskussion - alles wird direkt in Ihren Markdown-Quelldateien gespeichert, ganz ohne Datenbank. Originalautor: [@svallory](external:https://github.com/svallory) ::: callout info "Alpha-Release" Dieses Plugin befindet sich in der Alpha-Phase. Die API und das Speicherformat sind stabil, aber die Benutzeroberfläche wird aktiv weiterentwickelt. ::: ## Einrichtung ```bash docmd add threads ``` ```javascript plugins: { threads: {} } ``` ### Konfigurationsoptionen | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | Wenn `true`, bleiben Threads am Ende der Seite gruppiert. Wenn `false` (Standard), werden Threads inline neben dem markierten Text positioniert. | ```javascript // Threads am Ende der Seite behalten statt inline plugins: { threads: { sidebar: true } } ``` ## Funktionsweise 1. **Text markieren** auf einer beliebigen Dokumentationsseite während `docmd dev`. 2. Ein **Kommentar-Popover** erscheint - schreiben Sie Ihren Kommentar und senden Sie ihn ab. 3. Der ausgewählte Text wird mit einem Thread-Marker **hervorgehoben**. 4. Threads werden als `::: threads`-Blöcke am Ende der Markdown-Datei gespeichert. 5. **Keine Datenbank** - Ihre Markdown-Dateien sind die "Source of Truth". ## Vorschau So sehen Threads auf einer Live-Seite aus. Text mit Diskussionen wird <span class="threads-preview-highlight">so hervorgehoben</span> und Thread-Karten erscheinen darunter. <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 2 T.</div> <div class="threads-preview-body">Dieser Abschnitt könnte ein Diagramm vertragen, um die Architektur zu erklären. Was denkst du?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · vor 1 T.</div> <div class="threads-preview-body">Gute Idee - ich füge ein Mermaid-Flowchart hinzu. Funktioniert <code>sequenceDiagram</code> hier?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 12 Std.</div> <div class="threads-preview-body">Perfekt. Ein einfaches Flowchart wäre ideal.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Und hier ist eine <span class="threads-preview-highlight-blue">zweite Hervorhebung mit einer anderen Farbe</span> - Threads durchlaufen automatisch eine Farbpalette. <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · vor 3 T.</div> <div class="threads-preview-body">Sollten wir hier die Abwärtskompatibilität erwähnen?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Erledigte Threads erscheinen ausgegraut: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 5 T.  <span class="threads-preview-resolved-badge">✓ Erledigt</span></div> <div class="threads-preview-body">Tippfehler im Konfigurationsbeispiel behoben.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Ein schwebender **Diskussions-Button** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span> erscheint in der unteren rechten Ecke und zeigt die Anzahl der offenen Threads an. Klicken Sie darauf, um zum ersten Thread auf der Seite zu springen. ## Speicherformat Threads werden unter Verwendung der Container-Syntax von docmd in Ihr Markdown eingebettet: ```markdown # Meine Dokumentationsseite Inhalt mit ==markiertem Text=={t-a1b2c3d4}, der einen Thread hat. ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" Dieser Text muss klargestellt werden. ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 Habe es aktualisiert - passt das so? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` Die Syntax `==Text=={threadId}` verknüpft markierten Text im Dokumentenkörper mit einem spezifischen Thread. ## Features | Feature | Beschreibung | | :--- | :--- | | **Textauswahl** | Markieren Sie beliebigen Text, um einen neuen Thread zu starten | | **Antworten** | Verschachtelte Antwortketten innerhalb jedes Threads | | **Reaktionen** | Emoji-Reaktionen auf einzelne Kommentare | | **Bearbeiten / Löschen** | Ändern oder entfernen Sie Ihre Kommentare | | **Erledigen** | Markieren Sie Threads als erledigt mit Autor + Zeitstempel | | **Autorenprofile** | Git-basierte Autorenerkennung mit Gravatar-Unterstützung | | **Highlight-Marker** | Visuelle Indikatoren auf der Seite, die zeigen, wo Threads verankert sind | | **Schwebender Button** | Schnellzugriff-FAB mit Anzahl der offenen Threads | | **Scroll-Erhaltung** | Die Seite bleibt nach dem Hinzufügen von Kommentaren an derselben Position | ## Actions API Das Threads-Plugin macht die folgenden Aktionen über das WebSocket-RPC-System verfügbar. Diese können von Browser-Plugins über `docmd.call()` aufgerufen werden: | Aktion | Beschreibung | | :--- | :--- | | `threads:get-threads` | Parst und gibt alle Threads aus einer Datei zurück | | `threads:add-thread` | Erstellt einen neuen Thread mit seinem ersten Kommentar | | `threads:add-comment` | Fügt einen Kommentar zu einem bestehenden Thread hinzu | | `threads:edit-comment` | Bearbeitet den Inhalt eines bestehenden Kommentars | | `threads:delete-comment` | Entfernt einen Kommentar aus einem Thread | | `threads:delete-thread` | Entfernt einen kompletten Thread und bereinigt die Highlights | | `threads:resolve-thread` | Schaltet den Status zwischen erledigt/offen um | | `threads:toggle-reaction` | Schaltet eine Emoji-Reaktion auf einen Kommentar um | | `threads:get-authors` | Liest die Autorenprofil-Map aus | | `threads:upsert-author` | Erstellt oder aktualisiert ein Autorenprofil | ## Autorenprofile Autoreninformationen werden in `<docsRoot>/.threads/authors.json` gespeichert: ```json { "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } } ``` Während der Entwicklung erkennt das Plugin automatisch Ihren Git-Benutzernamen und Ihre E-Mail zur Autorenidentifikation. ::: callout tip "Versionskontrollfreundlich" Da Threads in Ihren Markdown-Dateien gespeichert werden, unterliegen sie automatisch der Versionskontrolle mit Git. Überprüfen Sie Kommentare in PRs, verfolgen Sie die Diskussionshistorie und arbeiten Sie über Ihren bestehenden Workflow zusammen. ::: --- ## [Plugin-Mechanismus & Verwendung](https://docs.docmd.io/de/07/plugins/usage/) --- title: "Plugin-Mechanismus & Verwendung" description: "Erfahren Sie mehr über die Lifecycle-Hooks von docmd, den Plugin-Sicherheitsmechanismus und wie Sie die Funktionen der Engine erweitern können." --- `docmd` folgt einer steckbaren Architektur. Fast alle Kernfunktionen - von der Suche über SEO bis hin zur Live-Vorschau - sind als Plugins implementiert. Dieses Design stellt sicher, dass die Engine leichtgewichtig bleibt, während Entwickler Funktionen selektiv basierend auf ihren spezifischen Projektanforderungen aktivieren können. ## Plugin-Übersicht | Plugin | Funktion | | :--- | :--- | | **[Suche (Search)](search.md)** | Bietet eine leistungsstarke, Offline-first Volltextsuche. | | **[SEO](seo.md)** | Generiert automatisch Meta-Tags, Sitemaps und steuert den Zugriff von KI-Crawlern. | | **[Mermaid](mermaid.md)** | Rendert Flussdiagramme, Sequenzdiagramme und Gantt-Charts. | | **[LLMs](llms.md)** | Generiert einen maschinenlesbaren Stream der gesamten Dokumentation für KI-Training oder Suche. | | **[Live-Vorschau (Live)](../content/live-preview.md)** | Stellt eine im Browser laufende Rendering-Engine für benutzerdefinierte Editoren bereit. | ## Lifecycle-Hooks Plugins können in den Build-Prozess eingreifen, indem sie sich in die folgenden Lifecycle-Hooks einklinken: | Hook | Beschreibung | | :--- | :--- | | `onInit(ctx)` | Wird sofort nach dem Start der Engine und dem Laden der Konfiguration ausgeführt | | `onPostBuild(ctx)` | Ausführung von Logik nach der Generierung aller HTML-Dateien | | `translations(localeId)` | Gibt übersetzte UI-Strings für ein Locale zurück | | `actions` | Serverseitige Handler, die über WebSocket-RPC vom Browser aus aufrufbar sind | | `events` | "Fire-and-Forget"-Handler für vom Browser gepushte Events | ## Plugin-Sicherheit Das Plugin-System bietet integrierte Sicherheitsgarantien: - **Validierung**: Plugins können einen `plugin`-Deskriptor mit `name`, `version` und `capabilities` deklarieren. Ungültige Deskriptoren werden zum Ladezeitpunkt abgelehnt. - **Isolierung**: Jeder Hook-Aufruf ist in einen Try/Catch-Block gehüllt. Ein fehlerhaftes Plugin kann weder den Build zum Absturz bringen noch andere Plugins beeinflussen. - **Erzwingung von Fähigkeiten**: Plugins, die Fähigkeiten (Capabilities) deklarieren, können sich nur für Hooks registrieren, die sie explizit deklariert haben. Nicht deklarierte Hooks werden mit einer Warnung übersprungen. Siehe [Plugins erstellen](building-plugins.md) für die vollständige API-Referenz. ::: callout tip "KI-transparente Architektur :robot:" Die Plugin-Architektur ist auf **Determinismus** ausgelegt. Jeder von einem Plugin injizierte Meta-Tag und jedes Skript ist rückverfolgbar, was es KI-Agenten (und menschlichen Entwicklern) ermöglicht, genau zu verstehen, wie sich die Website verhält, ohne versteckte Nebeneffekte. ::: --- ## [Release Notes - 0.7.0](https://docs.docmd.io/de/07/release-notes/0-7-0/) --- title: "Release Notes - 0.7.0" description: "Erstklassige Internationalisierung, Zero-Config-Core-Plugins und echte Zero-Config-Standardwerte." --- Das `docmd` 0.7.0 Release ist ein großer Schritt nach vorn - es führt native Multi-Sprachen-Unterstützung (i18n) mit einem integrierten Übersetzungssystem und echte Zero-Config-Standardwerte ein, bei denen alle Core-Plugins standardmäßig aktiv sind. ## ✨ Highlights ### 🌍 Internationalisierung (i18n) docmd bietet nun erstklassige i18n-Unterstützung. Konfigurieren Sie mehrere Sprachen (Locales), und docmd baut für jede Sprache eine vollständige, lokalisierte Version Ihrer Website - mit sprachengebundenen URLs (`/de/`, `/zh/`), übersetzten UI-Strings und automatischer Spracherkennung. Jede Sprache lebt in ihrem eigenen Unterverzeichnis - einschließlich der Standardsprache. Dies hält Ihr Quellverzeichnis sauber und macht die Struktur auf einen Blick verständlich: ``` docs/ en/ ← Standard-Sprache (gerendert unter /) de/ ← Deutsch (gerendert unter /de/) zh/ ← Chinesisch (gerendert unter /zh/) ``` Die Sprach-IDs, Ordnernamen und die Standardsprache sind völlig frei wählbar - `en`, `de`, `fr`, `ja` oder jede andere ID, die Sie bevorzugen. Dies beinhaltet **pro Sprache separate Suchindizes**, die automatisch über Ihre Versionen hinweg erstellt werden, sowie übersetzte UI-Komponenten für offizielle Plugins wie Suche und Threads! ### 🚀 Zero-Config Core-Plugins In `0.7.0` verfolgt docmd eine echte Zero-Config-Philosophie. Alle offiziellen Core-Plugins (`search`, `seo`, `sitemap`, `pwa`, `analytics`, `llms`, `mermaid`) sind nun **standardmäßig automatisch enthalten**. Sie müssen sie nicht mehr manuell in Ihrem `plugins`-Array deklarieren, um sie zu nutzen. Wenn Sie ein Core-Plugin deaktivieren möchten, können Sie es einfach auf `false` setzen. ## 📝 Vollständiger Changelog ### 🌍 i18n-Architektur - **Saubere Sprachverzeichnisse**: Jede Sprache (einschließlich der Standardeinstellung) lebt in ihrem eigenen Unterverzeichnis innerhalb von `src`. - **Sprachgebundene URL-Generierung**: Der Build-Prozess erstellt nun verschachtelte Verzeichnisse für jede konfigurierte Sprache. - **Fallback pro Datei**: Nicht-Standard-Sprachen übernehmen Seiten aus der Standardsprache, wenn eine Übersetzung fehlt, ergänzt durch einen automatischen Warnhinweis. - **Navigation pro Sprache**: Jedes Sprachverzeichnis kann eine eigene `navigation.json` haben. - **Versionierung + i18n**: Alte Versionen ohne Sprachverzeichnisse werden nur in der Standardsprache gerendert. - **Übersetzte UI-Strings**: Natives Übersetzungssystem für alle UI-Elemente und Templates unter Verwendung von JSON-Sprachdateien. - **Plugin i18n-API**: Plugins unterstützen nun einen neuen `translations(localeId)`-Hook. - **Global Search Locales**: Der lokale MiniSearch-Index wird nun pro Sprache erstellt. - **String Mode (`stringMode: true`)**: Ein neuer i18n-Modus für noStyle-Seiten - generieren Sie lokalspezifisches HTML aus einer einzigen Quelldatei mittels `data-i18n`-Attributen. ### 🔌 Plugin-System & Engine - **Auto-Aktivierung von Core-Plugins**: Zero-Config-Standards bieten die komplette docmd-Suite ohne Konfigurationsaufwand. - **Optimierung der Asset-Generierung**: Statische Ressourcen werden nur noch einmal im Root-Verzeichnis gebaut. ### 🎨 UI & Container - **Container `icon:` Parameter**: Callouts, Cards, ausklappbare Abschnitte und Buttons akzeptieren jetzt einen `icon:` Parameter für Lucide-Icons. - **`titleAppend` Frontmatter-Option**: Ermöglicht das Unterdrücken des automatischen Seiten-Suffixes im `<title>`-Tag. - **Pillen-Design für Versionen & Sprachen**: Dropdowns in der Seitenleiste werden nun als kompakte Pillen-Buttons nebeneinander gerendert. - **Konfigurations-Hot-Reload**: Änderungen an der `docmd.config.js` lösen im Entwicklungsmodus nun automatisch einen Rebuild aus. ## 🐛 Fehlerbehebungen (Bug Fixes) - Konflikte zwischen Versionierung und i18n bei alten Verzeichnissen ohne Sprachunterordner gelöst. - Fehlerhafte URL-Duplikation beim Sprachwechsel in alten Versionen korrigiert. - Diverse Korrekturen an der automatischen Navigationssuche und der Titel-Generierung. ## 🧪 Qualitätssicherung Das 0.7.0 Release hat eine umfassende Test-Suite mit über **25 Szenarien** und **85 Einzelprüfungen** erfolgreich bestanden. ## ⚠️ Breaking Changes - Kurznamen von Drittanbieter-Plugins werden nicht mehr automatisch aufgelöst (vollständiger Paketname erforderlich). - `pnpm onboard` wurde entfernt und in `pnpm prep` integriert. - Das PWA-Plugin ist nun ein optionales Plugin und nicht mehr standardmäßig enthalten (nutzen Sie `docmd add pwa`). ## Migrationleitfaden Aktualisieren Sie mittels `npm install docmd@latest`. Dann: 1. Entfernen Sie Core-Plugins aus Ihrem `plugins`-Array, sofern diese mit Standardeinstellungen genutzt wurden. 2. Aktualisieren Sie Drittanbieter-Plugins auf ihren vollständigen Paketnamen. --- ## [Release Notes - 0.7.1](https://docs.docmd.io/de/07/release-notes/0-7-1/) --- title: "Release Notes - 0.7.1" description: "Dediziertes Plugin-API-Paket, Plugin-Deskriptoren, Isolation und Durchsetzung von Fähigkeiten." --- Das `docmd` 0.7.1 Release führt eine wesentliche architektonische Verbesserung ein - das Plugin-System wurde in ein dediziertes `@docmd/api`-Paket ausgelagert. Dies bringt Plugin-Deskriptoren, Absturz-Isolation und die Durchsetzung von Fähigkeiten (Capability Enforcement) in das Ökosystem. ## ✨ Highlights ### 📦 `@docmd/api` - Dediziertes Plugin-Paket Die Plugin-API - bestehend aus Hook-Registrierung, WebSocket-RPC-Dispatching und Werkzeugen zur Quelltextbearbeitung - befindet sich nun in einem eigenen Paket: `@docmd/api`. Dies entkoppelt das Plugin-Ökosystem von der eigentlichen Build-Engine. Plugin-Entwickler können nun gegen einen leichtgewichtigen API-Vertrag entwickeln, ohne das gesamte `@docmd/core`-Paket einbinden zu müssen. > **Abwärtskompatibel:** Alle Exporte aus `@docmd/api` werden von `@docmd/core` re-exportiert. Bestehender Code funktioniert weiterhin ohne Änderungen. ### 🛡️ Plugin-Deskriptoren Plugins können nun einen `plugin`-Deskriptor exportieren, der ihren Namen, ihre Version und ihre Fähigkeiten deklariert. Die Engine validiert diese Deskriptoren beim Laden. > **Mibrations-Hinweis:** Deskriptoren sind in 0.7.x **optional**. Ab **Version 0.8.0 werden sie zwingend erforderlich** sein. ### 🔒 Plugin-Isolation Jeder Hook-Aufruf ist nun in eine Try/Catch-Grenze gehüllt. Ein fehlerhaftes Plugin kann den Build-Prozess nicht mehr zum Absturz bringen oder andere Plugins beeinträchtigen. Fehler werden gesammelt und am Ende des Builds in einer Zusammenfassung angezeigt. ### 🔑 Durchsetzung von Fähigkeiten (Capability Enforcement) Plugins, die Fähigkeiten deklarieren, können sich nur noch für Hooks registrieren, die zu diesen Deklarationen passen. Wenn ein Plugin einen Hook exportiert, den es nicht deklariert hat, wird dieser von der Engine mit einer Warnung übersprungen. ## 📝 Vollständiger Changelog ### 📦 Architektur - Auslagerung von `loadPlugins`, `createActionDispatcher`, `createSourceTools` und allen Plugin/RPC-Typen in das Paket `@docmd/api`. - Bereinigung von totem Code in `@docmd/core` nach der Migration. ### 🔌 Plugin-System - Einführung des **Plugin-Deskriptors** (Export von `plugin`) mit Name, Version und Fähigkeiten. - Strikte Validierung für `@docmd/plugin-*`-Pakete. - **Isolation**: Sicherheits-Wrapper (`safeCall`) für alle Hooks. - **Erweiterte Lebenszyklus-Hooks**: Einführung von `onConfigResolved`, `onDevServerReady`, `onBeforeParse`, `onAfterParse` und `onPageReady`. - Zusammenfassung von Plugin-Fehlern am Ende des Builds. ### 🐛 Fehlerbehebungen (Bug Fixes) - Korrektur der Anzeige von Rohschlüsseln auf der 404-Seite bei fehlenden Übersetzungen. - Behebung eines Problems, bei dem clientseitiger i18n-Code im `stringMode` fälschlicherweise in noStyle-Seiten eingefügt wurde. - Fix der Plugin-Auflösung in `pnpm`-Workspaces. ## ⚠️ Breaking Changes ### Plugin-API Import-Pfad Der offizielle Ort für die Plugin-API ist nun `@docmd/api`. Plugin-Entwickler werden gebeten, ihre Importe von `@docmd/core` auf `@docmd/api` zu aktualisieren. ### Threads-Plugin Peer-Dependency Das Paket `@docmd/plugin-threads` hängt nun von `@docmd/api` ab (Peer-Dependency) statt von `@docmd/core`. ## Migrationsleitfaden Für **Endbenutzer**: Keine Änderungen erforderlich. `npm install docmd@latest` genügt. Für **Plugin-Entwickler**: 1. Fügen Sie Ihrem Standard-Export einen **Plugin-Deskriptor** hinzu. 2. Aktualisieren Sie Ihre **Importe** von `@docmd/core` zu `@docmd/api`. 3. Aktualisieren Sie die **Peer-Dependencies** in Ihrer `package.json`. --- ## [Release Notes - 0.7.2](https://docs.docmd.io/de/07/release-notes/0-7-2/) --- title: "Release Notes - 0.7.2" description: "Einführung des konfigurationsbewussten 'docmd deploy', Sicherheits-Header in Produktionsqualität und die 7-Pillar Failsafe Verification Engine." --- Das `docmd` 0.7.2 Release führt den Befehl **`docmd deploy`** ein - einen konfigurationsbewussten Deployment-Scaffolder, der Ihr Projekt liest und maßgeschneiderte, produktionsreite Serverkonfigurationen generiert. Kein anderes Dokumentationstool macht das so. Docusaurus, VitePress, MkDocs - sie alle überlassen Ihnen das manuelle Schreiben von Dockerfiles und Serverkonfigurationen. `docmd` liest Ihre `docmd.config.js` (oder die Zero-Config-Standardwerte) und generiert Dateien, die sofort einsatzbereit sind. ## ✨ `docmd deploy` - Konfigurationsbewusste Bereitstellung Ein einziger Befehl generiert produktionsreife, auf Ihr Projekt zugeschnittene Bereitstellungsdateien: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # nginx.conf docmd deploy --caddy # Caddyfile ``` ### Was es intelligent macht Der Deploy-Befehl **liest Ihre Konfiguration** vor der Generierung. Er extrahiert: - **Projekttitel** - wird als Kommentar-Header in jede generierte Datei eingetragen - **Ausgabeverzeichnis** (`out`) - verwendet in `COPY`-Pfaden, `root`-Direktiven und File-Server-Konfigurationen statt hartcodierter Werte - **Site-URL** (`url`) - der extrahierte Hostname wird als `server_name` (Nginx) oder Caddy-Site-Adresse injiziert - **SPA-Modus** (`layout.spa`) - SPA-Routing-Fallback (`try_files`) wird nur generiert, wenn der SPA-Modus aktiv ist - **Konfigurationsdateipfad** - bei nicht-standardmäßigem Konfigurationsnamen führt der Dockerfile-Build-Schritt `docmd build --config ihre-config.js` aus Existiert keine `docmd.config.js`? Der Befehl nutzt die gleichen Zero-Config-Standardwerte wie `docmd dev` und `docmd build`. ### Immer synchron Jede Ausführung generiert die Bereitstellungsdateien neu, um sie mit Ihrer aktuellen Konfiguration abzugleichen. URL oder Ausgabeverzeichnis geändert? Führen Sie `docmd deploy --nginx` einfach erneut aus. Ihre Konfigurationen spiegeln immer den neuesten Stand Ihres Projekts wider. ### Qualität der generierten Dateien - **Docker**: Multi-Stage-Builds mit `package.json`-Layer-Caching und exakter `@docmd/core`-Versionsbindung für reproduzierbare Builds - **Nginx**: Sicherheits-Header (`X-Content-Type-Options`, `X-Frame-Options`), GZIP-Komprimierung, unveränderliches Asset-Caching - **Caddy**: HTTPS-bereite Adressierung, Sicherheits-Header, SPA-Routing, statisches Asset-Caching ## 🛡️ Die 7-Pillar Failsafe Engine Unsere interne Verifizierungs-Engine wurde in **7 logische Säulen der Stabilität** refaktoriert. Dies beinhaltet eine neue **Dynamic Integrity Engine**, die Versionskonflikte über das gesamte Monorepo hinweg sofort erkennt. ## 🌍 Globale Erweiterung des Ökosystems Wichtige Lokalisierungs-Updates in diesem Release: - **Native Sprachunterstützung**: Integrierte UI-Übersetzungen für **Deutsch, Spanisch, Japanisch und Französisch** in der Core-Engine - diese Sprachen funktionieren sofort für alle UI-Komponenten. - **Vollständige deutsche Übersetzung**: Die gesamte Dokumentations-Suite ist jetzt auf Deutsch verfügbar (`/de/`). ## 📝 Vollständiger Changelog ### 🚀 Funktionen & Verbesserungen - **Neuer Befehl**: `docmd deploy` mit `--docker`, `--nginx`, `--caddy` Zielen. - **Konfigurationsbewusstes Scaffolding**: Der Deploy-Befehl liest `docmd.config.js` (oder Zero-Config-Standardwerte) und personalisiert generierte Dateien mit Projekttitel, Ausgabeverzeichnis, Hostname, SPA-Modus und Konfigurationspfad. - **Immer aktuelle Konfigurationen**: Bereitstellungsdateien werden bei jeder Ausführung neu generiert, um mit Konfigurationsänderungen synchron zu bleiben. - **Docker-Scaffolding**: Multi-Stage-Dockerfile mit `package.json`-Layer-Caching und versionsgepinntem `@docmd/core`. - **Webserver-Scaffolding**: Gehärtete Nginx- und Caddy-Vorlagen mit Sicherheits-Headern, GZIP und intelligentem 404/SPA-Routing. - **Vereinheitlichte Config-Labels**: Alle internen Module (SEO, Sitemap, LLMS, PWA, Deployer, Generator) nutzen jetzt die modernen Config-Schlüssel (`config.title`, `config.url`, `config.out`, `config.src`) anstelle verstreuter Legacy-Fallbacks. Standardwerte werden einmalig in `normalizeConfig` definiert - die einzige Quelle der Wahrheit. - **Failsafe**: Verifizierungslogik in eine schnellere, professionellere 7-Stufen-Pipeline konsolidiert. - **Versionierung**: Neue Integrity-Engine markiert automatisch veraltete interne Workspace-Referenzen. - **SEO-Plugin**: Berücksichtigt die `titleAppend`-Frontmatter-Eigenschaft für Social-Media-Metadaten (OG/Twitter). - **Native Unterstützung**: Integrierte UI-Übersetzungen für **Deutsch, Spanisch, Japanisch und Französisch** in der Core-Engine. - **Lokalisierung**: Umfassende **deutsche** Übersetzung und optimierte **chinesische** Übersetzung für die Dokumentations-Website. ### 🐛 Fehlerbehebungen - **Deploy CLI**: Argument-Parsing bei Ausführung über `pnpm`-Proxy-Skripte mit `--cwd` behoben. - **Deploy UX**: Unbekannte Argumente zeigen jetzt eine hilfreiche Nutzungszusammenfassung anstelle eines Rohfehlers mit Exit-Code 1. - **Caddy-Konfiguration**: Korrektur der Cache-Control-Header-Syntax für Caddyfile-Kompatibilität. - **Bump-Skript**: Regex-`lastIndex`-Bug in `scripts/bump.js` behoben. - **CLI-Sicherheit**: Ordnungsgemäße asynchrone Fehlerbehandlung für alle Deployment-Befehle hinzugefügt. - **Live-Editor**: Mobile Overflow-Probleme und Template-Switching-State-Tracking behoben. ## Migrationsleitfaden Für **Endbenutzer**: Keine Breaking Changes. Aktualisieren Sie und probieren Sie `docmd deploy`, um auf Ihr Projekt zugeschnittene Bereitstellungskonfigurationen zu generieren. Für **Plugin-Entwickler**: Keine Änderungen erforderlich. --- ## [Release Notes - 0.7.3](https://docs.docmd.io/de/07/release-notes/0-7-3/) --- title: "Release Notes - 0.7.3" description: "Einführung von Code-Block-Titeln, der Multi-Service-Migrations-Engine, interaktiven Mermaid-Diagrammen mit Lucide-Icons und erstklassiger Unterstützung für das Bun-Ökosystem." --- Das `docmd` 0.7.3 Release bringt bedeutende neue Authoring-Funktionen, eine produktionsreife Migrations-Engine für Benutzer, die von konkurrierenden Plattformen wechseln, und eine komplette Überarbeitung der Mermaid-Diagramm-Rendering-Pipeline. Wir haben außerdem die Icon-Rendering-Logik in allen interaktiven Containern vereinheitlicht und eine tief kontextbezogene Paginierungslogik eingeführt. ## ✨ Highlights ### 🚀 Multi-Service-Migrations-Engine Wir haben das veraltete interne Konfigurationsmigrationstool durch eine voll funktionsfähige **Migrations-Engine** ersetzt, die Ihr gesamtes Dokumentationsprojekt mit einem einzigen Befehl von einer konkurrierenden Plattform zu `docmd` verschieben kann. ### Unterstützte Quellen | Quelle | Befehl | Erkannte Konfiguration | |---|---|---| | **Docusaurus** | `npx @docmd/core migrate --docusaurus` | `docusaurus.config.js` / `.ts` | | **MkDocs** | `npx @docmd/core migrate --mkdocs` | `mkdocs.yml` | | **VitePress** | `npx @docmd/core migrate --vitepress` | `.vitepress/config.[js\|ts\|mjs]` | | **Astro Starlight** | `npx @docmd/core migrate --starlight` | `astro.config.mjs` / `.ts` | Jede Migration führt automatisch Folgendes aus: 1. Erkennt die Konfigurationsdatei des Quellprojekts und extrahiert den Website-Titel. 2. Verschiebt alle vorhandenen Dateien sicher in ein `<source>-backup/`-Verzeichnis. 3. Kopiert die Dokumentations-Quelldateien (z. B. `docs/`, `src/content/docs/` usw.) in die Standard-`docs/`-Struktur von `docmd`. 4. Erzeugt eine sofort einsatzbereite `docmd.config.js` mit sinnvollen Standardwerten. ```bash cd my-docusaurus-site npx @docmd/core migrate --docusaurus npx @docmd/core dev ``` > **Hinweis:** Da jede Dokumentationsplattform komplexe Logik wie Sidebars, Versionierung und Lokalisierung (i18n) über proprietären Code oder APIs abwickelt, versucht `docmd` nicht, diese Konfigurationen automatisch zu übersetzen, um zu vermeiden, dass Ihr Build zerstört wird. Die Migrations-Engine konzentriert sich ausschließlich darauf, Ihre Markdown-Inhalte und Assets sicher zu verschieben, während die Einrichtung von `navigation.json` und `localisation` Ihnen über die einfachen nativen APIs von `docmd` überlassen bleibt. Lesen Sie unsere neuen umfassenden [Migrationsleitfäden](../migration/overview.md), um genau zu sehen, was migriert wird und welche einfachen Schritte erforderlich sind, um die Konfiguration Ihres vorherigen Tools auf `docmd` abzubilden. ### 📝 Code-Block-Titel Sie können nun jedem umzäunten Code-Block einen beschreibenden **Dateinamen oder Titel** hinzufügen, indem Sie eine in Anführungszeichen gesetzte Zeichenfolge nach dem Sprachbezeichner platzieren. Dies rendert eine saubere, Mintlify-ähnliche Kopfzeile über dem Code. ````markdown ```javascript "config.js" export default { title: "My Site" }; ``` ```` Der Titel wird als semantische Beschriftung (nicht als Überschrift) gerendert, sodass er niemals im Inhaltsverzeichnis erscheint oder Ihre Seitenstruktur stört. ### 📊 Interaktive Mermaid-Diagramme Wir haben die Art und Weise, wie `docmd` Mermaid-Diagramme rendert, komplett überarbeitet und statische SVGs in tief interaktive visuelle Elemente verwandelt. - **Intelligente Skalierung**: Diagramme werden in voller Mermaid-Qualität gerendert und dann intelligent skaliert, um sich mit CSS-Transformationen an die Inhaltsbreite anzupassen, wobei alle Beschriftungen und Kantenpositionierungen erhalten bleiben. - **Schwenken & Ziehen**: Klicken und ziehen Sie, um in großen Diagrammen zu schwenken. Es gibt jetzt auch native Pfeiltasten im UI für einfachere mobile Bedienung. - **Zoom-Steuerelemente**: Spezielle Vergrößern/Verkleinern-Schaltflächen werden beim Überfahren mit der Maus für eine präzise Überprüfung angezeigt. - **Vollbildmodus**: Eine native Vollbild-Umschaltung ermöglicht es Benutzern, komplexe Diagramme für eine ablenkungsfreie Anzeige zu erweitern. - **Lucide Icon Integration**: Das Lucide Icon-Paket wird direkt in die Mermaid-Engine registriert (`icon:icon-name`), was reichhaltige Architekturdiagramme mit denselben Icons ermöglicht, die auch in Ihrer Sidebar und Ihren Tabs verwendet werden. - **Dunkelmodus**: Diagramme und ihre Container werden jetzt im Dunkelmodus mit richtig thematisierten Rahmen und Hintergründen korrekt gerendert. ### ✨ Isomorphe Container-Icons Wir haben den Kernparser überarbeitet, um eine gemeinsame **Container Integrity Engine** zu verwenden. Dadurch wird sichergestellt, dass alle interaktiven Elemente - Callouts, Cards, Collapsibles und jetzt **Tabs** - eine einheitliche `icon:name`-Syntax unterstützen. ### Icons in Tabs Sie können nun jedes beliebige Lucide-Icon direkt zu Ihren Tab-Beschriftungen hinzufügen, um Ihren Benutzern einen sofortigen visuellen Kontext zu bieten. ```markdown ::: tabs == tab "npm" icon:box npx @docmd/core dev == tab "Bun" icon:zap bunx docmd dev ::: ``` ### ⚡ Erstklassige Bun-Unterstützung Nach der schnellen Verbreitung der Bun-Laufzeitumgebung haben wir die gesamte Kerndokumentation und die "Erste Schritte"-Leitfäden aktualisiert, um native Bun-Beispiele (`bunx`, `bun add`) einzuschließen. Englische, chinesische und deutsche Leitfäden wurden synchronisiert. ### 🧭 Kontextbezogene Paginierungsnavigation Die "Vorherige" und "Nächste" Seite Paginierungslinks am Ende der Artikel haben ein großes Intelligenz-Upgrade erhalten. Die Core Engine versteht nun nativ den `outputPrefix`-Kontext und stellt sicher, dass Ihre Leser beim sequenziellen Navigieren durch Ihre Dokumentation perfekt in ihrem aktuellen Sprach- und Versionssilo bleiben. ### 🎨 Visuelle Verfeinerungen - Alle Code-Blöcke weisen nun weichere `border-radius`-Ecken und dezente Box-Schatten auf. - Im Dunkelmodus wurde eine dedizierte `--border-color-codeblock`-Variable hinzugefügt, wodurch unsichtbare Ränder bei Code-Blöcken und Diagramm-Containern behoben werden. - Mermaid-Diagramme sind jetzt in einem umrandeten, gepolsterten Container verpackt. ## Migration Guide Für **Endbenutzer**: Keine Änderungen erforderlich. Ein einfaches `npm update @docmd/core` genügt. Für **Plugin-Autoren**: Wenn Sie bisher Tab-Header manuell analysiert haben, empfehlen wir den Wechsel zum exportierten Dienstprogramm `parseTitleAndIcon` aus `@docmd/parser`, um die Kompatibilität mit zukünftigen Icon-Verbesserungen aufrechtzuerhalten. Für **Benutzer anderer Dokumentationsplattformen**: Führen Sie `npx @docmd/core migrate --help` aus, um alle verfügbaren Migrationsquellen anzuzeigen und in Sekunden loszulegen. --- ## [Versionshinweise - 0.7.4](https://docs.docmd.io/de/07/release-notes/0-7-4/) --- title: "Versionshinweise - 0.7.4" description: "Einführung der kontextbezogenen Versionsfilterung für die Offline-Suche sowie Standardisierung des Renderings von Mermaid-Icons." --- Die `docmd`-Version 0.7.4 führt eine leistungsstarke neue Funktion für unser Offline-Such-Plugin ein: **Kontextbezogene Versionsfilterung**. Außerdem enthält sie einen Hotfix für das Rendering von Mermaid-Icons und die Syntax-Standardisierung. ## ✨ Highlights ### 🔍 Versionsfilterung in der Suche Beim Erstellen einer Dokumentation mit mehreren Versionen kann es schwierig sein, die richtigen Informationen zu finden. Das integrierte Such-Modal versteht nun nativ Versionssilos und generiert automatisch eine dynamische Filterleiste. - **Intelligente Versionserkennung**: Die Suchmaschine extrahiert automatisch alle verfügbaren Versionen aus Ihrem Index und generiert klickbare Filter-Tags. - **Farbcodierte Tags**: Jedem Versions-Tag wird automatisch eine einzigartige, ästhetisch ansprechende Farbe aus einer vordefinierten Palette zugewiesen, um Benutzern die visuelle Unterscheidung verschiedener Dokumentations-Silos zu erleichtern. - **Echtzeit-Umschaltung**: Benutzer können auf Tags klicken, um ihre Suchergebnisse sofort auf eine oder mehrere spezifische Versionen einzugrenzen, was ein wesentlich saubereres und genaueres Sucherlebnis bietet. ### 🏷️ Inline-Tags-Container Wir haben einen brandneuen `tag`-Container eingeführt! Dies ist eine selbstschließende Inline-Komponente, die dafür entwickelt wurde, pillenförmige Badges direkt in Ihren Text oder Ihre Überschriften einzufügen. - **Vollständig anpassbar**: Überschreiben Sie Standardfarben mit einem beliebigen CSS-Farbstring (`color:#ef4444`). - **Icon-Unterstützung**: Fügen Sie ganz einfach ein beliebiges Lucide-Icon (`icon:check-circle`) direkt zum Tag hinzu. - **Hyperlinks**: Verwandeln Sie Tags nahtlos in Links, indem Sie das Attribut `link:` verwenden. - **Überschriften-kompatibel**: Tags richten sich automatisch an der Grundlinie aus, ohne massive Schriftgrößen zu übernehmen, wenn sie in `<h1>`- oder `<h2>`-Elementen verwendet werden. ## 🐛 Fehlerbehebungen - **Mermaid-Icon-Registrierung**: Ein Problem wurde behoben, bei dem das Lucide-Icon-Paket in Mermaid-Flussdiagrammen nicht ordnungsgemäß von der benutzerseitigen Syntax entkoppelt war. - **Architektursyntax-Unterstützung**: Wir haben unsere dokumentierte Unterstützung für Mermaid-Icons offiziell auf die nativen Diagrammtypen `architecture` und `architecture-beta` von Mermaid umgestellt, welche eingebettete Iconify-Knoten perfekt unterstützen. ## 🛡️ Sicherheit - **Abhängigkeits-Audit**: Mehrere Sicherheitshinweise wurden behoben, indem tief verschachtelte Unterabhängigkeiten im gesamten Monorepo (`cross-spawn`, `dompurify`, `lodash-es`, `uuid` und `mermaid`) zwangsweise aktualisiert wurden. Das gesamte Engine-Ökosystem ist nun zu 100 % sauber und frei von Schwachstellen. ## ✨ Standardisierte Icon-Syntax Um die zugrunde liegende Icon-Bibliothek (derzeit Lucide) aus Ihren Diagrammen zu abstrahieren, haben wir das Paket generisch als `icon` registriert. Das bedeutet, dass Sie nun `icon:` anstelle einer expliziten Bindung Ihrer Dokumentation an `lucide:` verwenden sollten. Dies macht Ihre Diagramme zukunftssicher , sollten wir jemals die zugrunde liegende Icon-Bibliothek in `docmd` erweitern oder ändern, werden Ihre Diagramme diese Updates automatisch übernehmen, ohne dass Sie etwas ändern müssen! **Beispiel:** ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Database] in api service disk(icon:hard-drive)[Storage] in api db:L -- R:disk ``` ## Migrationsleitfaden Für **Endbenutzer**: Aktualisieren Sie auf den neuesten Patch mit `npm update @docmd/core`. Wenn Sie zuvor `lucide:` in Ihren Mermaid-Diagrammen verwendet haben, ersetzen Sie dieses bitte durch das neue Präfix `icon:`. --- ## [Versionshinweise - 0.7.5](https://docs.docmd.io/de/07/release-notes/0-7-5/) --- title: "Versionshinweise - 0.7.5" description: "Sicherheitspatch und i18n-Optimierung: Beseitigt die uuid-Schwachstelle, fügt Sprachumschalter-Absicherungen hinzu und führt Build-Zeit-Seitenmanifeste für latenzfreies Umschalten ein." --- Die `docmd`-Version 0.7.5 kombiniert einen Sicherheitsfix mit bedeutenden i18n-Optimierungen. Sie beseitigt die vorgelagerte `uuid`-Schwachstelle aus dem Mermaid-Plugin, fügt mehrschichtige Absicherungen für den Sprachumschalter hinzu und führt ein **Build-Zeit-Seitenmanifest** ein, das alle Laufzeit-Netzwerkprüfungen durch sofortige lokale Abfragen ersetzt. ## 🛡️ Sicherheit ### Mermaid-Plugin - Korrektur des Abhängigkeitsbaums Das Paket `@docmd/plugin-mermaid` deklarierte `mermaid` zuvor als Produktions-`dependency`. Dies führte dazu, dass die verwundbare transitive Unterabhängigkeit `uuid@<14.0.0` in jedem `node_modules`-Verzeichnis des Verbrauchers installiert wurde, obwohl das Paket diese zur Laufzeit nie verwendet. **Ursache**: Die Mermaid-Bibliothek wird zur Laufzeit ausschließlich über ein CDN im Browser geladen. Das npm-Paket `mermaid` wurde nur während der Entwicklung für die TypeScript-Typprüfung und den esbuild-Bundling-Schritt benötigt. Es war fälschlicherweise als Produktionsabhängigkeit kategorisiert. **Lösung**: `mermaid` wurde in `@docmd/plugin-mermaid` von `dependencies` nach `devDependencies` verschoben. Das veröffentlichte Paket wird nun mit **null Produktionsabhängigkeiten** ausgeliefert, sodass `mermaid` und seine verwundbare `uuid`-Unterabhängigkeit für Endbenutzer nie installiert werden. - `npm audit` / `pnpm audit` meldet jetzt **0 Schwachstellen** für Projekte, die `@docmd/plugin-mermaid` verwenden. - Keine funktionalen Änderungen - die Mermaid-Rendering-Pipeline ist vollständig unbeeinträchtigt. ## 🌐 i18n - Absicherung der Sprachumschaltung Wenn bisher eine Locale in `i18n.locales` deklariert war, aber das zugehörige Quellverzeichnis (z. B. `docs/hi/`) nicht existierte, wurde sie in der Sprachumschaltung dennoch als klickbar dargestellt - was beim Auswählen zu einem **404-Fehler** führte. **Lösung**: Die Engine **prüft Locale-Verzeichnisse** jetzt zur Build-Zeit vorab. Locales ohne Quellverzeichnis werden in der Sprachumschaltung automatisch mit einem **N/A**-Badge, dem Attribut `aria-disabled` und einem nicht klickbaren Zustand deaktiviert. - **Build-Zeit-Erkennung**: Die Engine prüft vor dem Rendern, welche Locale-Verzeichnisse tatsächlich existieren. - **Template-Deaktivierung**: Nicht verfügbare Locales erscheinen ausgegraut mit einem „N/A"-Badge und `href="#"`. - **Client-seitige Absicherung**: Das Klicken auf eine deaktivierte Locale löst keine Navigation aus - kein 404. - **Verketteter Fallback**: Wenn eine Locale verfügbar ist, aber eine bestimmte Seite fehlt, greift die Engine auf die Version der Standardsprache zurück und zeigt einen lokalisierten Warnhinweis an. ## ⚡ i18n - Build-Zeit-Seitenmanifest Bisher verwendete der Sprachumschalter `fetch(url, { method: 'HEAD' })`, um zu prüfen, ob eine Seite in der Zielsprache existiert. Dies verursachte Latenz, funktionierte bei einigen CDNs nicht und war offline nicht verfügbar. **Lösung**: Die Engine generiert jetzt ein **Seitenmanifest** zur Build-Zeit - eine kleine JS-Datei (`docmd-i18n-manifest.js`), die jede Locale ihren verfügbaren Seitenpfaden zuordnet. Der Client-seitige Umschalter liest dieses Manifest synchron. - **Null Netzwerkanfragen**: Die Seitenexistenz wird lokal aus dem Manifest geprüft - keine HEAD-Abfragen. - **Funktioniert offline**: Das Manifest wird mit den Site-Assets ausgeliefert. - **CDN-agnostisch**: Keine Abhängigkeit davon, wie der Hosting-Anbieter HEAD-Anfragen behandelt. - **Graceful Degradation**: Falls das Manifest nicht geladen werden kann, fällt der Umschalter automatisch auf HEAD-Abfragen zurück. ::: callout info Wenn i18n aktiviert ist, **muss** jede Locale ein eigenes Unterverzeichnis unter dem Quellverzeichnis haben (z. B. `docs/en/`, `docs/hi/`). Das Verzeichnis der Standardsprache ist als Fallback-Quelle für teilweise übersetzte Locales erforderlich. ::: ## i18n-Absicherung - docmd im Vergleich | Fähigkeit | docmd | VitePress | Docusaurus | Starlight | |:----------|:-----:|:---------:|:----------:|:---------:| | Seitenweiser Fallback auf Standardsprache | ✅ | ❌ (404) | ❌ (404) | ✅ | | Lokalisierter „nicht übersetzt"-Hinweis | ✅ | ❌ | ❌ | ✅ | | Fehlende Locales automatisch deaktivieren | ✅ | ❌ | ❌ | ❌ | | Client-seitige Navigationsabsicherung | ✅ | ❌ | ❌ | ❌ | | Versionierung + i18n kombiniert | ✅ | ❌ | ❌ | ❌ | | Alte Versionen ohne Locale-Verzeichnisse | ✅ | N/A | N/A | N/A | | RTL-Richtungsunterstützung | ✅ | ✅ | ✅ | ✅ | | Zero-Config (ohne React/Vue-Komponenten) | ✅ | Teilweise | ❌ | ✅ | VitePress und Docusaurus liefern **404-Fehler**, wenn eine Seite in einer nicht-standardmäßigen Locale fehlt - was serverseitige Redirects oder benutzerdefinierte Komponenten erfordert. Starlight (Astro) bietet einen seitenweisen Fallback mit einem Übersetzungshinweis, ähnlich wie docmd - deaktiviert aber fehlende Locale-Verzeichnisse nicht automatisch und schützt nicht vor client-seitiger Navigation zu nicht vorhandenen Locales. ## Migrationsleitfaden Für **Endbenutzer**: Aktualisieren Sie auf den neuesten Patch mit `npm update @docmd/plugin-mermaid` oder `pnpm update @docmd/plugin-mermaid`. Es sind keine Konfigurationsänderungen erforderlich. --- ## [Release Notes - 0.7.6](https://docs.docmd.io/de/07/release-notes/0-7-6/) --- title: "Release Notes - 0.7.6" description: "Einheitliche URL-Normalisierungs-Engine, universelle external:- und raw:-Link-Präfixe, SEO-Trailing-Slash-Erzwingung, Fix für die SPA-Hash-Navigation und stumme Plugin-Warnungen." --- Die `docmd` 0.7.6 Version führt eine **einheitliche URL-Normalisierungs-Engine** ein, die 301-Weiterleitungen eliminiert, Trailing-Slash-URLs für SEO erzwingt und eine konsistente Link-Handhabung über alle Oberflächen hinweg bietet. ## ✨ Highlights ### Einheitliche URL-Normalisierung Die gesamte URL-Verarbeitung erfolgt nun über eine einzige `resolveHref()`-Funktion in `@docmd/parser`. Die Erzwingung von Trailing-Slashes, das Entfernen von `index.md` und die Vermeidung von Doppelslashes werden konsistent auf Markdown-Links, Button-Container, Navigation und Menüleiste angewendet. - **301-Weiterleitungen eliminieren**: URLs wie `/configuration/overview` werden direkt zum Build-Zeitpunkt zu `/configuration/overview/` aufgelöst. - **Keine Pfad-Artefakte**: Keine `/index`-Überbleibsel oder `.md`-Erweiterungen mehr in gerenderten Links. - **Hreflang-Genauigkeit**: Alternate-Tags entfernen nun korrekt die Locale-Präfixe aus den Seitenpfaden. Weitere Details finden Sie im Leitfaden [Verlinkung & Referenzierung](https://docs.docmd.io/de/content/syntax/linking/) mit der vollständigen URL-Übersetzungstabelle. ### Universelle Präfixe `external:` und `raw:` Wir haben zwei neue magische Präfixe eingeführt, um Ihnen die volle Kontrolle über das Link-Verhalten in allen `docmd`-Komponenten zu geben. - **`external:` - Neuer Tab erzwingen**: Fügen Sie dies zu jedem Link hinzu (Markdown, Buttons, Menüleiste), um das Öffnen in einem neuen Tab zu erzwingen. - **`raw:` - Normalisierung umgehen**: Verwenden Sie dies, wenn Sie auf eine originale `.md`-Datei verlinken müssen, ohne dass die Engine deren Erweiterung entfernt. ```markdown [In neuem Tab öffnen](external:./configuration/overview.md) ::: button "API-Dokumentation" external:./api/node-api.md [Template herunterladen](raw:templates/starter.md) ``` **Verhaltensänderung**: HTTP/HTTPS-Links werden nicht mehr automatisch in einem neuen Tab geöffnet. Verwenden Sie explizit `external:`, wenn Sie dieses Verhalten wünschen. ### Zentralisierte URL-API für Plugins Eine neue URL-Utility-Ebene in `@docmd/parser` wird über `@docmd/api` re-exportiert. Plugins müssen den `outputPath` nicht mehr manuell parsen - die Engine berechnet saubere URLs für jede Seite vorab: ```typescript import { outputPathToSlug, sanitizeUrl } from '@docmd/api'; export async function onPostBuild({ pages }) { for (const page of pages) { page.urls.slug; // "guide/" page.urls.canonical; // "https://example.com/guide/" page.urls.pathname; // "/guide/" } } ``` Weitere Informationen finden Sie in der [Plugin-Entwicklung](https://docs.docmd.io/de/advanced/plugins/) Referenz. ## 🔧 Developer Experience ### Stummschaltung von Plugin-Warnungen Zuvor druckte ein fehlendes oder falsch konfiguriertes Plugin bei **jeder Dateiänderung** während `docmd dev` eine Warnung aus. Diese Warnungen werden nun **nur einmal** pro Dev-Session ausgegeben und bei nachfolgenden Rebuilds unterdrückt, um Ihr Terminal sauber zu halten. ``` ↻ Change in docs/en/guide.md... ⚠️ Could not load plugin: @docmd/plugin-math Done. ``` ### Fix für SPA-Hash-Navigation Im SPA-Modus führt das Klicken auf einen `#heading`-Anker auf der aktuellen Seite nun zu einem sanften Scrollen zum Ziel-Element. Das Vor- und Zurückblättern im Browser durch die Hash-Historie (via `popstate`) funktioniert ebenfalls korrekt. ```markdown [Zur Konfiguration springen](#configuration) <!-- funktioniert jetzt im SPA-Modus --> ``` ## 🚀 SEO-Verbesserungen - **Trailing Slashes**: Alle internen URLs werden mit Trailing Slashes gerendert, um 301-Weiterleitungsketten zu eliminieren. - **Saubere Pfade**: Kanonische und Hreflang-`<link>`-Tags verwenden die korrekten normalisierten Pfade. - **Keine Artefakte**: Keine `.md`-Erweiterungen oder `/index`-Fragmente im Produktions-HTML. ## Migrationsleitfaden Aktualisieren Sie auf die neueste Version mit `npm update @docmd/core` oder `pnpm update @docmd/core`. Keine Konfigurationsänderungen erforderlich. ::: callout info Wenn Sie benutzerdefinierte serverseitige Redirect-Regeln haben, die Trailing Slashes entfernen, sollten Sie diese entfernen, da die Engine nun nativ das kanonische Trailing-Slash-Format erzeugt. ::: --- ## [Release Notes - 0.7.7](https://docs.docmd.io/de/07/release-notes/0-7-7/) --- title: "Release Notes - 0.7.7" description: "Einführung der Multi-Projekt-Unterstützung, des Universal TUI Design Systems und eines erstklassigen, emoji-freien Terminal-Erlebnisses für professionelle Dokumentations-Workflows." --- Das `docmd` 0.7.7 Release führt die **Multi-Projekt-Unterstützung** ein , die Möglichkeit, mehrere unabhängige Dokumentations-Websites aus einem einzigen Repository heraus zu orchestrieren. Parallel zu dieser architektonischen Weiterentwicklung debütiert das **Universal TUI Design System**, eine komplette Modernisierung unserer Terminal-Schnittstelle, die durch ein neues eigenständiges Styling-Paket ein erstklassiges, signalreiches Entwicklererlebnis bietet. ## ✨ Highlights ### 🚀 Multi-Projekt-Unterstützung Sie können jetzt mehrere unabhängige Dokumentations-Websites von einer einzigen `docmd`-Instanz aus erstellen und bereitstellen. Eine einzige Root-Konfiguration ermöglicht es Ihnen, mehrere Projekte zu definieren, jedes mit eigenem Präfix, unabhängiger Versionierung und isolierter Navigation, während sie ein gemeinsames Theme und eine einheitliche Deployment-Pipeline nutzen. ```javascript // docmd.config.js (root) import { defineConfig } from '@docmd/api'; export default defineConfig({ projects: [ { prefix: '/', src: 'docmd-main' }, { prefix: '/search', src: 'docmd-search' } ] }); ``` Jedes Projekt behält seine eigene Verzeichnisstruktur und Konfiguration bei, was es Ihnen ermöglicht, komplexe Dokumentations-Ökosysteme (z. B. eine Core-Engine und ihre Satelliten-Tools) unter einer einzigen Domain ohne Versionskonflikte zu verwalten. ### 🖥️ Universal TUI Design System Wir haben die `docmd`-Terminalschnittstelle komplett neu gestaltet, um ein professionelles, signalreiches Erlebnis zu bieten. Das neue System verzichtet auf "spielerische" Emojis und verwendet stattdessen raffinierte Box-Drawing-Zeichen (Rahmenzeichen) und eine kuratierte Farbpalette, um klares, handlungsorientiertes Feedback zu geben. - **Verbessertes Branding**: Die zentralisierte ASCII-Logo-Definition innerhalb des TUI-Systems sorgt für eine konsistente Markenpräsenz bei allen CLI-Interaktionen. - **Signalreiche Ausgabe**: Protokolle sind jetzt in einer sauberen, tabellarischen Ästhetik strukturiert, die die Lesbarkeit sowohl in der lokalen Entwicklung als auch in CI/CD-Umgebungen priorisiert. - **Konsistenz**: Egal, ob Sie eine Website erstellen, einen Dev-Server ausführen oder ein Migrations-Tool verwenden , das Terminal-Erlebnis bleibt perfekt vereinheitlicht. ### 📦 Eigenständiges `@docmd/tui` Paket Um dieses neue Designsystem zu unterstützen, haben wir die Terminal-Ästhetik von der Kernlogik entkoppelt und in ein dediziertes `@docmd/tui`-Paket ausgelagert. Dieser architektonische Schritt eliminiert zirkuläre Abhängigkeiten und ermöglicht es Plugin-Autoren, dieselben professionellen UI-Komponenten wie die Core-Engine zu verwenden. Durch die Zentralisierung unserer "Terminal User Interface"-Logik stellen wir sicher, dass jede Ausgabe , von Core-Build-Protokollen bis hin zu Plugin-Warnungen von Drittanbietern , derselben hochwertigen Designsprache folgt. ### 🚫 Emoji-freie Professionalität Im Einklang mit unserem Engagement für ein erstklassiges Entwicklererlebnis stellt 0.7.7 auf einen **emoji-freien Standard** um. Wir haben veraltete emoji-basierte Statusmarkierungen durch eine anspruchsvolle Box-Drawing-Ästhetik ersetzt. Diese Änderung stellt sicher, dass sich `docmd` wie ein Werkzeug für den Produktiveinsatz anfühlt und eine sauberere Schnittstelle bietet, die sich nahtlos in professionelle IDEs und Terminal-Emulatoren integriert. ### 🔍 Intelligente Konfigurationsvalidierung Konfigurationsfehler verursachen keine Node.js-Stack-Traces mehr. Wir haben das Echtzeit-Konfigurationsfeedback mit standardisierten TUI-Komponenten verbessert, um saubere, menschenlesbare Fehlermeldungen bereitzustellen. Der Validator erkennt nun Multi-Projekt-Root-Konfigurationen und bietet spezifische Hilfestellung bei fehlenden Eigenschaften oder Tippfehlern. Wenn ein Konfigurationsfehler auftritt, präsentiert `docmd` nun einen klaren "Error Report" mit exakten Zeilenverweisen und Lösungsvorschlägen, damit Sie weniger Zeit mit dem Debugging und mehr Zeit mit dem Schreiben verbringen. ### ⚡ Multi-Projekt-Dev-Server Der Befehl `docmd dev` wurde für die Multi-Projekt-Orchestrierung aktualisiert. Er erstellt alle Projekte und stellt sie über einen einzigen Port bereit, mit intelligentem File-Watching, das gezielte Rebuilds für das jeweils bearbeitete Projekt auslöst. ``` ──────────────────────────────────────── MULTI-PROJECT DEV SERVER Lokal: http://127.0.0.1:3000 Netzwerk: http://192.168.1.5:3000 Projekt: / → docmd-main/ Projekt: /search → docmd-search/ ──────────────────────────────────────── ``` ## 🛠️ Interne Refaktorierung Dieses Release enthält signifikante architektonische Härtungen, um die neuen TUI- und Multi-Projekt-Funktionen zu unterstützen: - **Abhängigkeitsarchitektur**: Optimierte Paketabhängigkeiten, um einen strikt gerichteten azyklischen Fluss zu gewährleisten und zirkuläre Importe zwischen Engine- und UI-Ebenen zu verhindern. - **Logger-Refaktorierung**: Veraltete Logger-Utilities wurden vollständig zugunsten des zentralisierten TUI-Systems eingestellt. - **Projekt-Orchestrierung**: Der Multi-Projekt-Handler befindet sich in einem eigenständigen Modul, das Verzeichniskontexte (`chdir`) sicher verwaltet und unabhängige Ausgaben in einer einheitlichen Site-Struktur zusammenführt, ohne die bestehende Build-Pipeline zu verändern. ## 📝 Vollständiges Changelog ### 🚀 Funktionen & Verbesserungen - **Multi-Projekt-Engine**: Unterstützung für `projects[]` in der Root-Konfiguration mit gemeinsamen Assets und unabhängiger Versionierung. - **Universal TUI**: Überarbeitete Terminalschnittstelle mit Box-Drawing-Zeichen und professionellem Styling. - **Eigenständiges TUI-Paket**: Neue `@docmd/tui`-Bibliothek für eine einheitliche CLI-Ästhetik im gesamten Monorepo. - **Verbessertes Branding**: Einführung eines zentralisierten ASCII-Logos für alle CLI-Einstiegspunkte. - **Konfigurationsvalidierung**: Verbessertes Echtzeit-Feedback mit menschenlesbaren Fehlerberichten ohne Stack-Traces. - **Abhängigkeitsoptimierung**: Strikt erzwungener azyklischer Abhängigkeitsfluss über alle internen Pakete hinweg. ### 🧹 Bereinigungen & Entfernungen - **Emoji-freier Standard**: Alle veralteten emoji-basierten Terminalausgaben wurden entfernt. - **Redundant Protokolle**: Ad-hoc-Aufrufe von `chalk` und `console.log` wurden zugunsten des TUI-Loggers eliminiert. - **Veraltete Utilities**: Entfernung veralteter interner Logger-Hilfsmittel. ## Migration Guide ### Für bestehende Projekte **Bestehende Einzelprojekt-Setups erfordern keine Änderungen.** Die Engine unterstützt standardmäßig weiterhin den gewohnten Einzelprojekt-Workflow. ### Einführung der Multi-Projekt-Unterstützung So wechseln Sie zu einem Multi-Projekt-Setup: 1. Verschieben Sie Ihre bestehende Dokumentationsquelle in ein Unterverzeichnis. 2. Erstellen Sie eine Root-`docmd.config.js` und definieren Sie Ihre Projekte mit dem `projects`-Array. 3. Entfernen Sie redundante `src`- und `out`-Pfade aus den untergeordneten Konfigurationen, da der Root-Orchestrator diese nun verwaltet. ### Für Plugin-Autoren Wir empfehlen, alle benutzerdefinierten `console.log`- oder `chalk`-Anweisungen auf das neue `@docmd/tui`-Paket zu migrieren, um sicherzustellen, dass die Ausgabe Ihres Plugins der Core-`docmd`-Ästhetik entspricht. --- ## [Release Notes - 0.7.8](https://docs.docmd.io/de/07/release-notes/0-7-8/) --- title: "Release Notes - 0.7.8" description: "Einführung des Git-Plugins, eine neu gestaltete Terminal-Oberfläche mit Live-Fortschrittsanzeige, parallele Seitenverarbeitung für deutlich schnellere Builds, automatische Installation für offizielle Plugins und Container-Syntax-Kompatibilität." --- Das `docmd` 0.7.8 Release führt das **Git-Plugin** für Repository-basierte Metadaten ein, eine komplett **neu gestaltete Terminal-Oberfläche** mit Live-Fortschritts-Feedback, **parallele Seitenverarbeitung** für dramatisch schnellere Builds, **automatische Plugin-Installation** für offizielle Plugins und **Container-Syntax-Kompatibilität** für Benutzer, die von anderen Dokumentations-Engines migrieren. ## Highlights ### Build-Engine - Parallele Verarbeitung Die Seiten-Rendering-Pipeline wurde von sequentiell zu **gebündelter paralleler Verarbeitung** umgestaltet und liefert signifikante Beschleunigung für Dokumentationsseiten aller Größen. **Was sich geändert hat:** - **Gebündelte Datei-I/O**: Dateien werden jetzt 64 gleichzeitig gelesen und 128 gleichzeitig geschrieben via `Promise.all`, statt einzeln sequentiell - **Pipeline-Überlappung**: Dateilesen, Markdown-Parsing und HTML-Schreiben überlappen sich jetzt über Batches hinweg - **Parallele Schreibvorgänge**: Alle gerenderten HTML-Dateien werden gleichzeitig in Batches auf die Festplatte geschrieben **Voraussichtliche Leistung (einfache Seiten):** | Skalierung | Vorher (0.7.7) | Nachher (0.7.8) | Verbesserung | | :--- | :--- | :--- | :--- | | ~1.000 Seiten | ~22s | ~12s | **~45% schneller** | | ~10.000 Seiten | ~4 Min+ | ~1,5 Min | **~60% schneller** | | Datei-Lesephase | Sequentiell | 64-Datei-Batches | **64x Parallelität** | | Datei-Schreibphase | Sequentiell | 128-Datei-Batches | **128x Parallelität** | | Fortschritts-Feedback | Keines (stumm) | Live-Fortschrittsbalken | Echtzeit | ::: callout tip "Skaliert mit Ihrer Dokumentation" Die Leistungsverbesserung skaliert mit der Dokumentationsgröße. Größere Seiten (1.000+ Seiten) mit umfangreicher I/O profitieren am meisten von der gebündelten parallelen Verarbeitung. ::: ### Terminal-Oberfläche - Einheitliches TUI Alle Terminal-Ausgaben wurden in ein **einheitliches, signalstarkes Designsystem** umgestaltet, das über alle Befehle hinweg geteilt wird. Keine stummen Wartezeiten, inkonsistente Formatierung oder unübersichtliche mehrzeilige Ausgaben mehr. **Neue TUI-Primitiven:** | Feature | Beschreibung | | :--- | :--- | | **Fortschrittsbalken** | `━━━━━━━━━━━━───────── 42/100 (42%)` - einzeilig, aktualisiert sich in-place | | **Spinner** | `⠋ ⠙ ⠹` - Braille-Punkt-Animation während langer Operationen | | **Timer** | Jeder Build, Rebuild und jedes Projekt zeigt die vergangene Zeit | | **Sektionen** | Konsistente `┌─ Sektion / └──` Rahmung über alle Befehle | **Einheitliche Ausgabe über alle Befehle:** ``` ┌─ Build │ Source docs/ │ Output site/ │ Versions 2 (v06, v07) │ Locales 4 (en, hi, zh, fr) │ Processing pages ━━━━━━━━━━━━━━━━━━━━ 419/419 (100%) └────────────────────────────────────────────────────────── ┌─ Post-Build Tasks │ Search index [ DONE ] │ Sitemap [ DONE ] └────────────────────────────────────────────────────────── ⬢ Build complete. Generated 238 pages in 1.4s. ``` **Vereinheitlichte Befehle:** - **`docmd build`** - Sektions-Header mit Quelle/Ausgabe/Versionen/Sprachen, Fortschrittsbalken, Zeitanzeige - **`docmd dev`** - Animierter Spinner während des initialen Builds und bei Rebuilds, Zeit pro Rebuild - **Multi-Projekt-Builds** - Spinner-Animation pro Projekt, Zeit pro Projekt, Gesamtübersicht - **`docmd live`** - Konsistente Sektions-Rahmung wie bei allen anderen Befehlen ### Git-Plugin (Core) Das neue **Git-Plugin** bringt Repository-basierte Metadaten auf Ihre Dokumentationsseiten - Zeitstempel der letzten Aktualisierung, Commit-Verlauf-Tooltips und Bearbeitungslinks - alles direkt aus Ihrem Git-Verlauf ohne Konfiguration. ```javascript // Optional: Bearbeitungslinks konfigurieren plugins: { git: { repo: 'https://github.com/ihre-org/docs', branch: 'main' } } ``` **Funktionen:** - **Zeitstempel der letzten Aktualisierung**: Zeigt an, wann jede Seite zuletzt geändert wurde, mit relativer Formatierung für aktuelle Änderungen - **Commit-Verlauf-Tooltip**: Hover zeigt aktuelle Commits mit Autorennamen und Nachrichten - **Bearbeitungslinks**: Erstellt automatisch "Diese Seite bearbeiten"-Links für GitHub, GitLab und Bitbucket - **Graceful Degradation**: Deaktiviert sich automatisch, wenn das Projekt nicht in einem Git-Repository ist Das Plugin ersetzt die veraltete `editLink`-Konfigurationsoption durch eine funktionsreichere Alternative. Siehe die [Git-Plugin-Dokumentation](/plugins/git) für vollständige Details. ### Automatische Installation für offizielle Plugins Offizielle Plugins, die in Ihrer `docmd.config.js` aufgeführt sind, werden jetzt automatisch installiert, wenn sie fehlen. Wenn Sie ein Plugin zu Ihrer Konfiguration hinzufügen, das nicht installiert ist, lädt docmd es beim nächsten Build von npm herunter. ```javascript // docmd.config.js plugins: { pwa: {}, // Nicht installiert? docmd installiert es automatisch threads: {} // Dasselbe hier } ``` **Sicherheitsfunktionen:** - Funktioniert nur für offizielle `@docmd/plugin-*`-Pakete in der Registry - Installiert die exakte Version, die zu Ihrer `@docmd/core`-Version passt - Verwendet den Paketmanager Ihres Projekts (npm, pnpm, yarn oder bun) - Zeigt Fortschritt im Terminal an ### Container-Syntax-Kompatibilität Benutzer, die von **VitePress**, **Docusaurus** oder ähnlichen Dokumentations-Engines migrieren, können jetzt vertraute Container-Syntax ohne Änderungen verwenden. **VitePress-Style-Container funktionieren jetzt:** ```markdown :::tip Dies wird als Tipp-Callout gerendert. ::: :::warning Dies wird als Warnung-Callout gerendert. ::: :::details Klicken zum Erweitern Dies wird als zusammenklappbarer Abschnitt gerendert. ::: ``` **Docusaurus-Style-Container funktionieren jetzt:** ```markdown :::note Dies wird als Info-Callout gerendert. ::: :::caution Dies wird als Warnung-Callout gerendert. ::: ``` Zusätzlich wird **Syntax ohne Leerzeichen** jetzt für alle Container unterstützt: ```markdown :::callout info Funktioniert genauso wie ::: callout info ::: :::tabs Funktioniert genauso wie ::: tabs ::: ``` Dies ermöglicht die Migration von Dokumentation aus anderen Engines mit minimalen Änderungen. ### Migrationsfreundliche Aliase | Alias | Entspricht | Herkunft | | :--- | :--- | :--- | | `:::tip` | `callout tip` | VitePress | | `:::warning` | `callout warning` | VitePress | | `:::danger` | `callout danger` | VitePress | | `:::info` | `callout info` | VitePress | | `:::details` | `collapsible` | VitePress | | `:::note` | `callout info` | Docusaurus | | `:::caution` | `callout warning` | Docusaurus | ::: callout tip "Nahtlose Migration" Diese Aliase funktionieren stillschweigend neben der Standard-`docmd`-Syntax. Ihre bestehende Dokumentation funktioniert weiterhin unverändert, während importierte Inhalte aus anderen Engines korrekt gerendert werden. ::: ## Interne Verbesserungen ### Britisches Englisch Standardisierung Die Dokumentation wurde aktualisiert, um durchgehend britische englische Schreibweisen zu verwenden. Dies umfasst Terminologie wie "optimised", "centralised", "localisation" und "colour", wo angemessen. ### Code-Qualität - Em-Striche durch Standard-Bindestriche in Dokumentation und Code-Kommentaren ersetzt für verbesserte Lesbarkeit - Standardisierte Kommentarformatierung in Quelldateien - Verbesserte TypeScript-Typdefinitionen für Plugin-APIs ## Vollständiges Changelog ### Funktionen - **Git-Plugin (Core)**: Neues Core-Plugin für Zeitstempel der letzten Aktualisierung, Commit-Verlauf und Bearbeitungslinks mit Graceful Degradation - **Auto-Install**: Offizielle Plugins in der Konfiguration werden automatisch installiert, wenn sie fehlen - **Container-Aliase**: VitePress- und Docusaurus-Container-Syntax funktioniert jetzt sofort - **Container ohne Leerzeichen**: Alle Container akzeptieren jetzt Syntax mit oder ohne Leerzeichen nach `:::` - **Parallele Verarbeitung**: Gebündelte Datei-I/O mit 64-Datei-Lese- und 128-Datei-Schreib-Parallelität - **Einheitliches TUI**: Fortschrittsbalken, Spinner, Timer und konsistente Sektions-Ausgabe über alle Befehle ### Verbesserungen - **Build-Leistung**: Bis zu ~60% schnellere Builds bei großen Seiten durch paralleles I/O-Batching - **Live-Fortschritt**: Echtzeit-Fortschrittsbalken während der Seitenverarbeitung - **Animierte Spinner**: Visuelles Feedback während Builds, Rebuilds und Multi-Projekt-Verarbeitung - **Build-Zeitanzeige**: Jede Operation meldet die vergangene Zeit - **Git-Widget UI**: Tooltip verwendet CSS `:hover`/`:focus-within` für flüssige, ruckelfreie Anzeige - **Code-Block-Styling**: `docmd-code-block-wrapper` verwendet jetzt die universelle `--shadow-sm`-Variable - **Live-Editor TUI**: Einheitliche Sektions-Rahmung und Graceful Shutdown - **Dokumentation**: Britisches Englisch Schreibweisen-Standardisierung - **Code-Stil**: Konsistente Formatierung in der gesamten Codebasis - **Plugin-Registry**: Git-Plugin zur offiziellen Registry hinzugefügt ### Veraltungen - **editLink-Konfiguration**: Die eigenständige `editLink`-Konfigurationsoption ist zugunsten des Git-Plugins veraltet ## Migrationsanleitung ### Übernahme des Git-Plugins Wenn Sie die `editLink`-Konfiguration verwendet haben, ersetzen Sie diese durch das `git`-Plugin. Der neue Ansatz ist intelligenter - er erkennt automatisch Ihr git-Repository-Stammverzeichnis und berechnet den korrekten Dateipfad, sodass Sie kein Verzeichnis mehr in der URL hartcodieren müssen. **Vorher (veraltet):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs' // ← hartcodiertes Verzeichnis } }); ``` **Nachher:** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', // ← nur das Repository, kein Pfad nötig branch: 'main' } } }); ``` Das Plugin löst den korrekten Dateipfad relativ zum git-Stammverzeichnis automatisch auf. Das bedeutet, dass Bearbeitungslinks in Monorepos und Multi-Projekt-Setups ohne manuelle Pfadkonfiguration korrekt funktionieren. **Weitere Optionen:** | Option | Standard | Beschreibung | | :--- | :--- | :--- | | `repo` | - | Repository-URL (beliebiger Anbieter) | | `branch` | `'main'` | Zu verlinkender Branch | | `editPath` | `'edit'` | URL-Segment für die Bearbeitungsseite. `'-/edit'` für GitLab, `'src'` für Bitbucket | | `editLink` | `true` | Auf `false` setzen, um den Bearbeitungslink zu deaktivieren | | `editLinkText` | i18n-String | Benutzerdefinierte Beschriftung für den Bearbeitungslink | ::: callout warning "Breaking Change: editLink baseUrl Format" Wenn Sie `editLink.baseUrl` mit einem hartcodierten Unterverzeichnis verwendet haben (z.B. `.../edit/main/docs`), wird dieses Verzeichnissegment jetzt automatisch berechnet. Beim Wechsel zum git-Plugin muss das Unterverzeichnis aus der URL entfernt werden - verwenden Sie als `repo`-Wert nur `https://github.com/org/repo`. ::: ### Für Benutzer, die von anderen Engines migrieren Wenn Sie Dokumentation von VitePress, Docusaurus oder ähnlichen Engines importieren: 1. Ihre bestehenden `:::tip`, `:::warning`, `:::note`-Container werden korrekt gerendert 2. Syntax ohne Leerzeichen wie `:::tabs` funktioniert neben dem Standard `::: tabs` 3. Keine Änderungen an Ihren Markdown-Dateien sind erforderlich Wir empfehlen, schrittweise zur Standard-`docmd`-Syntax (`::: callout tip`) für neue Inhalte überzugehen, da sie mehr Flexibilität mit Titeln und Icons bietet. --- ## [Versionshinweise - 0.7.9](https://docs.docmd.io/de/07/release-notes/0-7-9/) --- title: "Versionshinweise - 0.7.9" description: "OpenAPI-Plugin, Plugin-API-Verbesserungen mit onBeforeRender-Hook und sourcePath, Fehlerbehebung bei der Git-Plugin-Commit-Verlauf-Genauigkeit für Multi-Projekt-Builds, Mitwirkenden-Avatare und smarter Sticky-Footer." --- Das `docmd` 0.7.9-Release führt **inkrementelle Builds** für eine nahezu verzögerungsfreie Entwicklung, das **OpenAPI-Plugin** und massive Performance-Optimierungen über eine **parallele Plugin-Architektur** ein. Es behebt zudem kritische Speicherlecks bei Konfigurationsdateien, verbessert die Genauigkeit des Git-Verlaufs in Monorepos, fügt Mitwirkenden-Avatare hinzu und implementiert einen smarten Sticky-Footer. ## ✨ Highlights ### OpenAPI-Plugin Das neue **OpenAPI-Plugin** rendert API-Referenzdokumentation direkt aus OpenAPI 3.x Spezifikationsdateien in Markdown-Seiten - zur Build-Zeit, ohne clientseitiges JavaScript und ohne Drittanbieter-UI-Bibliotheken (kein Swagger UI, kein Redoc). Fügen Sie eine Spezifikationseinbettung in jedes Markdown ein: ````markdown ```openapi ./api/openapi.json ``` ```` Das Plugin liest die Spezifikation zur Build-Zeit und gibt statisches HTML aus: farbkodierte Methoden-Badges, Parameter-Tabellen, Request/Response-Schema-Tabellen und Status-Code-Beschreibungen. Unterstützt JSON- und YAML-Spezifikationen, löst interne `$ref`-Referenzen auf und verarbeitet `oneOf`/`anyOf`-Union-Typen. **Neu in 0.7.9:** Option `download: true` hinzugefügt, um direkte Links zur rohen Spezifikationsdatei bereitzustellen - ideal für KI-Modelle (wie GPT-4 oder Claude), um Ihre API-Dokumentation programmatisch zu nutzen. ```bash docmd add openapi ``` Weitere Details finden Sie in der [OpenAPI-Plugin-Dokumentation](../plugins/openapi/). ### Inkrementelle Builds (Instant Dev-Modus) Der Entwicklungs-Server bietet nun ein System für **gezielte Rebuilds**. Zuvor löste jede Änderung an einer Markdown-Datei einen vollständigen Build der Website aus. Bei Websites mit hunderten Seiten konnte dies 10+ Sekunden dauern. In 0.7.9 rendert `docmd dev` nur noch die spezifische Datei neu, die Sie geändert haben. Seiten-Reloads sind nun **sofort (<1s)** verfügbar, selbst bei riesigen Projekten. Das System erhält dabei alle Navigations-, Versions- und Asset-Kontexte korrekt aufrecht. ### Parallele Plugin-Architektur (Multi-Threaded Performance) Die Build-Engine wurde grundlegend überarbeitet, um die **parallele Ausführung von Plugins** zu unterstützen. Zuvor liefen Plugin-Hooks wie `onBeforeRender` sequenziell für jede Seite ab. Für Plugins, die I/O-Operationen durchführen oder Kindprozesse starten (wie das Git-Plugin), war dies ein erheblicher Flaschenhals. In 0.7.9 verarbeitet die Engine das Seiten-Rendering nun in parallelen Batches. In Kombination mit dem neuen **asynchronen Git-Plugin**, das nicht-blockierende `execFile`-Aufrufe verwendet, sind die Build-Zeiten für große Websites mit hunderten von Seiten bis zu **3x schneller**. **Wichtige Verbesserungen:** - **Batched Rendering**: Phase 3 des Generators läuft jetzt in parallelen Batches von 64 Seiten. - **Asynchrone Hooks**: Alle Plugin-Hooks können jetzt `async` sein, und die Engine wartet parallel auf deren Abschluss. - **Git-Plugin Überarbeitung**: Synchrones `execSync` wurde durch asynchrones, nicht-blockierendes Prozess-Spawning ersetzt. ## 📝 Vollständiges Änderungsprotokoll ### Fehlerbehebungen - **Git-Plugin - Datei-spezifischer Commit-Verlauf in Multi-Projekt-Builds**: Der Singleton-Zustand auf Modulebene wurde zu einem Pro-Verzeichnis-Cache behoben, sodass jede Datei immer in ihrem eigenen Repository-Kontext abgefragt wird. Korrekt in Einzel-Projekt-, Multi-Projekt-, versionierten und mehrsprachigen Konfigurationen. - **Git-Plugin - SPA-Hydration**: Behoben, um auf das `docmd:page-mounted`-Ereignis zu hören, sodass Zeitstempel nach SPA-Navigation korrekt formatiert werden. ### Neue Funktionen - **OpenAPI-Plugin (`@docmd/plugin-openapi`)**: Build-Zeit OpenAPI 3.x Spezifikations-Renderer, ohne clientseitige Abhängigkeiten. - **Plugin-API - `onBeforeRender`-Hook**: Wird vor dem Template-Rendering aufgerufen, empfängt den vollständigen `PageContext` mit `sourcePath`. - **Plugin-API - `PageContext`-Typ**: Formal typisiert und aus `@docmd/api` exportiert. - **Git-Plugin - Mitwirkenden-Avatare**: Commit-Verlauf-Tooltip zeigt jetzt Gravatar-Bilder an. - **Git-Plugin - Konfigurierbares Datumsformat**: Neue `dateFormat`-Option: `relative` (Standard), `iso` oder `locale-aware`. ```javascript plugins: { git: { dateFormat: 'locale-aware' } } ``` ### Verbesserungen - **Parallele Build-Pipeline**: Der Generator parallelisiert nun die Phase des Template-Renderings. Plugins können nun zeitaufwändige Operationen (wie Git-Aufrufe oder OpenAPI-Parsing) gleichzeitig auf mehreren CPU-Kernen über Kindprozesse ausführen. - **Asynchrones Git-Plugin**: Das Git-Plugin ist nun vollständig asynchron. Es nutzt nicht-blockierende Kindprozesse und Pfad-Normalisierung, um hohe Performance und Genauigkeit auch in komplexen Monorepo-Strukturen zu gewährleisten. - **Inkrementelles Build-System**: Der Dev-Server führt nun gezielte Teil-Builds durch. Das Bearbeiten einer Datei rendert nur diese Datei neu und reduziert die Reload-Zeiten von 10s+ auf unter 300ms. - **OpenAPI-Plugin - Download-Spezifikation**: Neue `download`-Option bietet einen Link zur rohen JSON/YAML-Spezifikation im Seiten-Header für KI-Zugänglichkeit. - **UI - Smarter Sticky-Footer**: Der Footer ist jetzt immer mit Flex-Layout am unteren Rand des Viewports verankert. (Behoben). ### Intern - **Bearbeitungslink-Pfadauflösung**: Wird vom Git-Repository-Root berechnet, nicht von `config.src` or `process.cwd()`. - **Config-Loader - Härtung**: Obligatorische Bereinigung für verwaiste temporäre Konfigurationsdateien (`docmd.config-*.js`) implementiert und `try-finally`-Sicherheit hinzugefügt, um Lecks bei Syntaxfehlern zu verhindern. --- ## [Asset-Management](https://docs.docmd.io/de/07/theming/assets-management/) --- title: "Asset-Management" description: "Wie docmd CSS-, JavaScript- und Bild-Assets während des Build-Prozesses verarbeitet." --- `docmd` verfolgt einen "Mirror & Map"-Ansatz für Assets. Dies stellt sicher, dass Ihre lokalen Entwicklungspfade konsistent mit Ihrem Produktions-Build bleiben. ## Verzeichnisstruktur Standardmäßig sucht `docmd` nach einem `assets/`-Ordner in Ihrem Projekt-Root. ```bash my-docs/ ├── assets/ # Quell-Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Inhalt ├── docmd.config.js └── site/ # Build-Output (automatisch gespiegelt) ``` ## Automatisches Kopieren Wenn Sie `docmd build` oder `docmd dev` ausführen: 1. **Die Spiegelungs-Logik**: Der gesamte Inhalt Ihres `assets/`-Ordners wird rekursiv nach `site/assets/` kopiert. 2. **Stabilität**: Wir verwenden eine gehärtete Kopier-Engine mit automatischen Wiederholungsversuchen, um "File Busy"- oder "ENOENT"-Fehler auf macOS und modernen SSDs zu vermeiden. 3. **Referenzierung**: Sie sollten Assets in Ihrem Markdown oder in der Konfiguration immer über den **root-relativen** Pfad referenzieren: ```markdown ![Logo](/assets/images/logo.png) ``` ## Integration von benutzerdefiniertem CSS & JS Um Ihre Assets auf jeder Seite einzubinden, fügen Sie sie Ihrer Theme-Konfiguration hinzu: ```javascript // docmd.config.js export default { theme: { customCss: ['/assets/css/branding.css'] }, customJs: ['/assets/js/utils.js'] } ``` ::: callout info "KI-Erkennungsstrategie :robot:" * **Nach Typ organisieren**: Halten Sie `/css`, `/js` und `/images` getrennt. Dies hilft KI-Agenten, relevante Stile oder Skripte sofort zu finden, wenn Sie sie bitten, "die Farbe des Headers zu ändern". * **Beschreibende Dateinamen verwenden**: Die Benennung eines Bildes als `authentication-flow-diagram.png` bietet dem `llms.txt`-Crawler viel mehr Kontext als `img_01.png`. ::: --- ## [Verfügbare Themes](https://docs.docmd.io/de/07/theming/available-themes/) --- title: "Verfügbare Themes" description: "Entdecken Sie die integrierten Themes von docmd, darunter Sky, Ruby und Retro. Erfahren Sie, wie Sie Themes mit einer einzigen Konfigurationszeile wechseln." --- `docmd` bietet eine Reihe von professionell gestalteten Themes mit responsivem Light/Dark-Mode. Sie können die gesamte Ästhetik Ihrer Website durch Ändern eines einzigen Schlüssels in der `docmd.config.js` anpassen. ## So wechseln Sie Themes ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system', // Optionen: 'light', 'dark', 'system' } } ``` ## Galerie der integrierten Themes | Theme | Bestens geeignet für | Vibe | | :--- | :--- | :--- | | `default` | Schlichte Dokumentation | Sauber, leichtgewichtig, neutral | | `sky` | Produktdokumentation | Modern, hochwertig, Standard | | `ruby` | Markenidentität | Anspruchsvoll, Serif-Header, lebendig | | `retro` | Entwickler-Tools | 80er-Jahre-Terminals, Monospace, Neon-Akzente | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` Genau das Theme, das für diese Dokumentationsseite verwendet wird. Nutzen Sie dieses, wenn Sie umfangreiches benutzerdefiniertes CSS hinzufügen möchten und keine störenden integrierten Designschichten wünschen. ### 2. `sky` Der Goldstandard für moderne Dokumentation. Es bietet klare Typografie, subtile Übergänge und kontrastreiche Light/Dark-Modi, die zu modernen SaaS-Plattformen passen. ### 3. `ruby` Ein hochelegantes Theme mit Serif-Typografie für Überschriften und einer tiefen, juwelenfarbenen Farbpalette. Perfekt für Dokumentationen, die autoritär und hochwertig wirken sollen. ### 4. `retro` Ein von Nostalgie geprägtes Theme, inspiriert von klassischem Computing. Zu den Merkmalen gehören phosphorgrüner Text auf schwarzem Hintergrund (im Dark Mode), Scanline-Effekte und Monospace-Schriftarten wie Fira Code als Standard. ## Theme-Architektur 1. **CSS-Layering**: Themes sind additiv. Die Wahl von `sky` lädt tatsächlich die Basisstile von `default` und legt dann die `sky`-Ästhetik darüber. 2. **Nativer Dark-Mode**: Jedes Theme enthält eine erstklassige Dark-Mode-Implementierung. 3. **Kein Refresh**: Wenn Benutzer Themes über die UI wechseln, aktualisiert die SPA-Engine die `--docmd-primary`-Variablen sofort ohne Neuladen der Seite. ::: callout tip Wenn Sie Ihr Dokumentationslayout einem KI-Entwickler-Tool beschreiben, hilft die Erwähnung Ihres Themes (z. B. "Ich verwende das `retro`-Theme") dem Modell, benutzerdefinierte CSS-Überschreibungen vorzuschlagen, die zum Variablenschema dieses spezifischen Themes passen. ::: --- ## [Eigene Styles & Skripte](https://docs.docmd.io/de/07/theming/custom-css-js/) --- title: "Eigene Styles & Skripte" description: "Fügen Sie Ihre eigenen CSS- und JS-Dateien hinzu, um die Funktionalität und das Branding von docmd zu erweitern." --- Obwohl `docmd`-Themes hochflexibel sind, möchten Sie möglicherweise Ihre eigenen Stylesheets oder interaktiven Skripte einbinden. Dies geschieht über die Arrays `theme.customCss` und `customJs` in Ihrer Konfiguration. ## Eigenes CSS Verwenden Sie `theme.customCss`, um bestehende Styles zu überschreiben oder neue hinzuzufügen. ```javascript // docmd.config.js export default { theme: { customCss: [ '/assets/css/branding.css' // Pfad relativ zum Website-Root ] } } ``` ### Funktionsweise 1. Platzieren Sie Ihre CSS-Datei in den Assets-Ordner Ihres Projekts (z. B. `docs/assets/css/branding.css`). 2. `docmd` kopiert diese automatisch in den Build-Ordner und fügt ein `<link>`-Tag in jede Seite ein. 3. Eigenes CSS wird **nach** den Theme-Styles geladen, wodurch Ihre Überschreibungen Vorrang haben. ## Eigenes JavaScript Verwenden Sie das übergeordnete `customJs`-Array für Skripte, die Verhalten hinzufügen oder Dienste von Drittanbietern integrieren. ```javascript // docmd.config.js export default { customJs: [ '/assets/js/feedback-widget.js' ] } ``` ### Beachtung des Lebenszyklus Skripte werden am Ende des `<body>`-Tags eingefügt. Da `docmd` eine **Single Page Application (SPA)** ist, denken Sie daran: * Die Seite wird beim Navigieren zwischen Links nicht vollständig neu geladen. * Möglicherweise müssen Sie auf benutzerdefinierte Lebenszyklus-Ereignisse hören, um Ihre Skripte auf neuen Seiten neu zu initialisieren. Die vollständige Liste der Ereignisse und Anwendungsbeispiele finden Sie unter [Client-Side Events](../api/client-side-events). ::: callout tip Das Hinzufügen von eigenem CSS und JS ermöglicht es KI-Modellen (wie ChatGPT), maßgeschneiderte UI-Verbesserungen vorzuschlagen. Wenn Sie erwähnen: „Ich habe eine eigene `branding.css`-Datei“, kann das Modell spezifische Selektoren liefern, die nicht mit der `docmd`-Kern-Engine kollidieren. ::: --- ## [Anpassung & Variablen](https://docs.docmd.io/de/07/theming/customisation/) --- title: "Anpassung & Variablen" description: "Eine vollständige Referenz der CSS-Variablen und Komponentonklassen von docmd für fortgeschrittenes Styling." --- `docmd` basiert auf einer CSS-Variablen-Architektur. Das bedeutet, dass Sie Ihre gesamte Website neu gestalten können, indem Sie einfach ein paar Schlüssel in einem `:root`-Block überschreiben, ohne komplexe CSS-Selektoren schreiben zu müssen. ## Referenz der globalen Variablen | Variable | Standard (Hell) | Standard (Dunkel) | Beschreibung | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | Hintergrund der Hauptseite. | | `--text-color` | `#3f3f46` | `#a1a1aa` | Standardfließtext. | | `--text-heading` | `#09090b` | `#fafafa` | Farben für Titel und Überschriften. | | `--link-color` | `#068ad5` | `#068ad5` | Primäre Akzentfarbe / Links. | | `--border-color` | `#e4e4e7` | `#27272a` | Trennlinien und Rahmen. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Hintergrund der Navigation. | | `--ui-border-radius` | `6px` | `6px` | Rundung für alle UI-Elemente. | | `--sidebar-width` | `260px` | `260px` | Breite der Seitenleiste. | ## Beispiel für eine Überschreibung Um die primäre Akzentfarbe Ihrer Website zu ändern, fügen Sie dies zu Ihrem `customCss` hinzu: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Ansprechen von Komponenten Wenn Sie bestimmte Komponenten stylen möchten, verwenden Sie diese übergeordneten Klassen: * `.main-content`: Der Wrapper für alle Markdown-Inhalte. * `.sidebar-nav`: Die interne Navigationsliste. * `.page-header`: Die obere Navigationsleiste. * `.docmd-search-modal`: Das Such-Overlay. * `.docmd-tabs`: Komponenten des Tab-Containers. * `.callout`: Die Hinweis- und Warnungsboxen. ## Fehlerbehebung bei der Selektivität (Specificity) Die meisten `docmd`-Styles verwenden eine niedrige Selektivität. Wenn Ihre Überschreibungen nicht übernommen werden, stellen Sie sicher, dass Ihr `customCss` korrekt registriert ist und prüfen Sie, ob das Hinzufügen eines `body`-Präfixes (z. B. `body .main-content`) hilft. ::: callout tip Da `docmd` Standard-CSS-Variablen verwendet, können Sie eine KI fragen: *"Gib mir eine professionelle Farbpalette mit --link-color und --bg-color für docmd"*. Das Modell wird in der Lage sein, sofort kopierbares CSS bereitzustellen, das sich perfekt in die integrierten Themes integriert. ::: --- ## [Icons](https://docs.docmd.io/de/07/theming/icons/) --- title: "Icons" description: "So verwenden und passen Sie Lucide-Icons in Ihrer Dokumentation an." --- `docmd` verfügt über integrierte Unterstützung für die [Lucide](external:https://lucide.dev/)-Icon-Bibliothek. Icons können in Ihrer Navigations-Seitenleiste, in Buttons und in benutzerdefinierten Komponenten verwendet werden, um visuelle Hinweise zu geben und die Scannbarkeit zu verbessern. ## Navigations-Icons Weisen Sie jedem Navigationselement in Ihrer `docmd.config.js` ein Icon zu. Verwenden Sie den Kebab-Case-Namen eines beliebigen Icons, das Sie auf der Lucide-Website finden. ```javascript navigation: [ { title: 'Home', path: '/', icon: 'home' }, { title: 'Setup', path: '/setup', icon: 'settings' } ] ``` ## Icons in Containern Sie können Icons auch innerhalb Ihrer Buttons, Tags, Tabs und anderen Containern verwenden, indem Sie den rohen HTML-Code einbinden oder das standardmäßige `icon:`-Präfix in docmd nutzen. ```markdown ::: button "Download" /download icon:download ``` ## CSS-Styling Alle Icons werden als Inline-SVGs mit der Klasse `.lucide-icon` gerendert. Sie können deren Größe oder Linienstärke global in Ihrem `customCss` ändern: ```css .lucide-icon { stroke-width: 1.5px; /* Dünnere Icons für einen modernen Look */ width: 1.2rem; height: 1.2rem; } /* Gezielte Anpassung eines Icons */ .icon-rocket { color: #ff5733; } ``` ## Icon-Referenz Wir unterstützen die gesamte Lucide-Bibliothek. Sie können die Tausenden von verfügbaren Icons hier durchsuchen: ::: button "Lucide-Icons durchsuchen" external:https://lucide.dev/icons icon:globe --- ## [Hell- & Dunkelmodus](https://docs.docmd.io/de/07/theming/light-dark-mode/) --- title: "Hell- & Dunkelmodus" description: "So konfigurieren Sie den Standard-Ansichtsmodus und verwalten den Theme-Umschalter für die beste Benutzererfahrung." --- `docmd` bietet integrierte Unterstützung für helle und dunkle Farbschemata. Es erkennt automatisch die Systemeinstellungen der Benutzer und ermöglicht manuelle Überschreibungen über einen UI-Umschalter. ## Standard-Ansichtsmodus Sie legen den Anfangszustand Ihrer Dokumentation in der `docmd.config.js` fest. ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system' // Optionen: 'light', 'dark', 'system' (Standard) } } ``` * **`system`**: Entspricht der Betriebssystem-Präferenz des Benutzers (Empfohlen). * **`light`**: Erzwingt den Hellmodus beim ersten Laden. * **`dark`**: Erzwingt den Dunkelmodus beim ersten Laden. ## Konfiguration der Umschalt-Schaltfläche Der Theme-Umschalter ist Teil des **Optionsmenüs**. Sie können dessen Sichtbarkeit und Position innerhalb des `layout`-Objekts steuern. ```javascript layout: { optionsMenu: { position: 'header', // Optionen: 'header', 'sidebar-top', 'sidebar-bottom' components: { themeSwitch: true // Sun/Moon-Umschalter ein- oder ausblenden } } } ``` ## Funktionsweise (Technisch) Die Theme-Engine wendet ein `data-theme`-Attribut auf das `<body>`-Tag an: * `<body data-theme="light">` * `<body data-theme="dark">` Wenn Sie ein themenbasiertes Design wie `sky` verwenden, lautet das Attribut `sky-light` oder `sky-dark`. ### CSS-Variablen `docmd`-Themes verwenden CSS-Variablen für alle Farben. Sie können diese Variablen in Ihrem eigenen CSS überschreiben, um das Aussehen beider Modi anzupassen. ```css /* Benutzerdefinierte CSS-Überschreibung */ :root { --docmd-primary: #4f46e5; /* Primärer Akzent für Hellmodus */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* Primärer Akzent für Dunkelmodus */ } ``` ## Benutzer-Persistenz Wenn ein Benutzer den Modus manuell umschaltet, wird seine Präferenz im `localStorage` gespeichert. `docmd` liest diesen Wert bei jedem Seitenladen sofort aus, um "Theme-Flackern" (FOUC) zu verhindern. ::: callout tip Bei der Generierung von Inhalten bevorzugen LLMs kontrastreiche Strukturen. `docmd` stellt sicher, dass Code-Snippets und Callouts in beiden Modi barrierefrei bleiben. Dies gewährleistet, dass `llms-full.txt`-Payloads als semantische Blöcke korrekt verstanden werden, unabhängig davon, welcher Modus während des Builds aktiv war. ::: --- ## [Browser-API (Clientseitig)](https://docs.docmd.io/de/api/browser-api/) --- title: "Browser-API (Clientseitig)" description: "Interagieren Sie vom Browser aus mit docmd - Live-Kompilierung und Plugin-Kommunikation im Entwicklungsmodus." --- `docmd` bietet zwei Browser-APIs: die **isomorphe Compile-Engine** zum Rendern von Markdown im Browser und die **Plugin-API für den Entwicklungsmodus** für die Echtzeitkommunikation mit dem Dev-Server. ## Isomorphe Compile-Engine Dieselbe Engine, die statische Websites in Node.js generiert, kann vollständig in einem Webbrowser ausgeführt werden. Dies ist ideal für den Aufbau von CMS-Vorschauen, interaktiven Playgrounds oder die Einbettung von Dokumentationen in bestehende Webanwendungen. ### Installation via CDN ```html <!-- Kern-Styles --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Die isomorphe Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` Kompiliert rohes Markdown unter Verwendung des Standard-`docmd`-Layouts in einen vollständigen HTML-Dokument-String. **Parameter:** - `markdown` (String): Der rohe Markdown-Inhalt. - `config` (Object): Konfigurations-Überschreibungen (gleiches Schema wie `docmd.config.js`). **Rückgabe:** `Promise<String>`: Das vollständige HTML-Dokument. ### Beispiel: Live-Vorschau Um eine Stil-Isolation zu gewährleisten, wird empfohlen, die Ausgabe innerhalb eines `<iframe>` mittels des `srcdoc`-Attributs zu rendern. ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: 'Vorschau', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## Plugin-API für den Entwicklungsmodus Während `docmd dev` aktiv ist, wird automatisch eine globale `window.docmd`-Variable in jede Seite eingefügt. Diese API ermöglicht die Echtzeitkommunikation zwischen clientseitigem Plugin-Code und serverseitigen Action-Handlern via WebSocket RPC. ::: callout info "Nur im Entwicklungsmodus" Die unten aufgeführten Plugin-API-Methoden sind nur während `docmd dev` verfügbar. Sie sind nicht in Produktions-Builds enthalten. ::: ### `docmd.call(action, payload)` Ruft einen serverseitigen Action-Handler auf, der von einem Plugin registriert wurde. Gibt ein Promise zurück, das mit dem Rückgabewert des Handlers aufgelöst wird. ```javascript // Eine Plugin-Aktion aufrufen und das Ergebnis erhalten const threads = await docmd.call('threads:get-threads', { file: 'docs/erste-schritte.md' }); console.log(threads); // Array von Thread-Objekten ``` Wenn die Aktion Quelldateien modifiziert, lädt die Seite nach Auflösung des Promises automatisch neu. ### `docmd.send(name, data)` Sendet ein „Fire-and-forget“-Ereignis an den Server. Es wird keine Antwort zurückgegeben. ```javascript // Den Server über einen Seitenaufruf benachrichtigen docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` Abonniert vom Server gesendete Ereignisse (Server-pushed Events). Gibt eine Unsubscribe-Funktion zurück. ### `docmd.afterReload(name, callback)` & `docmd.scheduleReload(name, context)` Ermöglichen die Erhaltung des Zustands (z. B. Scrollposition) über einen automatischen Neuladevorgang hinweg, indem Daten im `sessionStorage` zwischengespeichert werden. ## Wichtige Hinweise - **Kein Dateisystem**: Die Browser-Engine kann keine Ordner scannen. Sie müssen das `navigation`-Array explizit im Konfigurationsobjekt angeben, wenn Sie eine Seitenleiste benötigen. - **Node-only Plugins**: Plugins, die auf Node.js-APIs angewiesen sind (wie Sitemap oder LLM), sind im Browser deaktiviert. --- ## [CLI-Befehle](https://docs.docmd.io/de/api/cli-commands/) --- title: "CLI-Befehle" description: "Befehlszeilenreferenz für docmd - alle verfügbaren Befehle und Optionen." --- ## Befehlsübersicht | Befehl | Beschreibung | |:--------|:------------| | [`docmd init`](#docmd-init) | Erstellt ein neues Dokumentationsprojekt | | [`docmd dev`](#docmd-dev) | Startet den Entwicklungsserver mit Hot-Reload | | [`docmd build`](#docmd-build) | Erzeugt eine statische Website für die Produktion | | [`docmd live`](#docmd-live) | Startet den browserbasierten Live-Editor | | [`docmd stop`](#docmd-stop) | Beendet laufende Entwicklungsserver | | [`docmd deploy`](#docmd-deploy) | Erzeugt Bereitstellungskonfigurationen (Docker, Nginx, Caddy) | | [`docmd migrate`](#docmd-migrate) | Aktualisiert Legacy-Konfigurationen auf das V2-Schema | | [`docmd add <plugin>`](#docmd-add-plugin) | Installiert und konfiguriert ein Plugin | | [`docmd remove <plugin>`](#docmd-remove-plugin) | Entfernt ein Plugin und dessen Konfiguration | ## Globale Optionen | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei (Standard: `docmd.config.js`) | | `--verbose` | `-V` | Detaillierte Build-Protokolle anzeigen | | `--version` | `-v` | Die installierte Version ausgeben | | `--help` | `-h` | Hilfemenü anzeigen | | `--cwd <path>` | - | Arbeitsverzeichnis überschreiben (für Monorepos) | ## `docmd init` Erstellt ein neues Dokumentationsprojekt im aktuellen Verzeichnis. ```bash docmd init ``` Erstellt: - `docs/index.md` - Beispiel-Startseite - `docmd.config.js` - Empfohlene Standardeinstellungen - Aktualisierte `package.json` mit Build-Skripten ## `docmd dev` Startet einen Entwicklungsserver mit sofortigem Hot-Reload. ```bash docmd dev [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--port <number>` | `-p` | Server-Port (Standard: `3000`) | | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei | ## `docmd build` Erzeugt eine produktionsreife statische Website im Verzeichnis `site/`. ```bash docmd build [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--offline` | - | Links auf `.html` umschreiben für `file://` Browsing | | `--config <path>` | `-c` | Pfad zur Konfigurationsdatei | ## `docmd live` Startet den browserbasierten Live-Editor. ```bash docmd live [options] ``` | Option | Beschreibung | |:-------|:------------| | `--build-only` | Erzeugt das Editor-Bundle, ohne den Server zu starten | ## `docmd stop` Beendet laufende docmd-Entwicklungsserver. ```bash docmd stop [options] ``` | Option | Alias | Beschreibung | |:-------|:------|:------------| | `--port <number>` | `-p` | Nur den Server auf diesem Port stoppen | | `--force` | `-f` | Auch `serve`-Prozesse auf den Ports 3000, 3001, 8080, 8081 beenden | ## `docmd deploy` Erzeugt Konfigurationsdateien für die Bereitstellung. ```bash docmd deploy [options] ``` | Option | Beschreibung | |:-------|:------------| | `--docker` | Erzeugt ein `Dockerfile` | | `--nginx` | Erzeugt `nginx.conf` | | `--caddy` | Erzeugt `Caddyfile` | | `--force` | Bestehende Bereitstellungsdateien überschreiben | ## `docmd migrate` Aktualisiert Legacy docmd V1-Konfigurationen auf das V2-Schema. ```bash docmd migrate ``` Ordnet automatisch veraltete Schlüssel neu zu (z. B. `siteTitle` → `title`) und strukturiert das Konfigurationsobjekt um. ## `docmd add <plugin>` Installiert und konfiguriert ein offizielles oder Community-Plugin. ```bash docmd add <plugin-name> ``` | Beispiel | Beschreibung | |:--------|:------------| | `docmd add analytics` | Installiert `@docmd/plugin-analytics` | | `docmd add search` | Installiert `@docmd/plugin-search` | Die CLI erkennt Ihren Paketmanager (npm, pnpm, yarn oder bun) und fügt empfohlene Standardeinstellungen in die `docmd.config.js` ein. ## `docmd remove <plugin>` Deinstalliert sicher ein Plugin und bereinigt dessen Konfiguration. ```bash docmd remove <plugin-name> ``` Entfernt: - Das npm-Paket - Plugin-Konfiguration aus der `docmd.config.js` ::: callout tip "Agenten-kompatible Protokollierung :robot:" `docmd` verwendet strukturierte Terminal-Protokolle. KI-Agenten können die Ausgabe präzise parsen für Fehlererkennung und automatisierte Wartung. ::: --- ## [Client-seitige Ereignisse](https://docs.docmd.io/de/api/client-side-events/) --- title: "Client-seitige Ereignisse" description: "Nutzen Sie den SPA-Lebenszyklus von docmd, um interaktive Funktionen hinzuzufügen." --- `docmd` nutzt einen leichtgewichtigen Single Page Application (SPA) Router, um sofortige Seitenübergänge zu ermöglichen. Da der Browser beim Navigieren kein vollständiges Neuladen durchführt, werden Skripte, die auf `DOMContentLoaded` basieren, nicht erneut ausgeführt. Um dies zu handhaben, sendet `docmd` benutzerdefinierte Lebenszyklus-Ereignisse (Events), auf die Sie in Ihren `customJs`-Dateien hören können. ## `docmd:page-mounted` Dieses Ereignis wird immer dann ausgelöst, wenn eine neue Seite erfolgreich abgerufen und in das DOM eingefügt wurde. ### Verwendung Fügen Sie einen Listener zum `document`-Objekt hinzu, um Bibliotheken von Drittanbietern neu zu initialisieren oder benutzerdefinierte Animationen auszulösen. ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`Navigiert zu: ${url}`); // Komponenten neu initialisieren // Beispiel: Prism.highlightAll(); }); ``` ### Ereignis-Details (`event.detail`) | Eigenschaft | Typ | Beschreibung | | :--- | :--- | :--- | | `url` | `String` | Die absolute URL der Seite, die gerade gemountet wurde. | ## Best Practices 1. **Idempotenz**: Stellen Sie sicher, dass Ihre Initialisierungslogik sicher mehrmals auf derselben Seite aufgerufen werden kann oder vor der nächsten Navigation bereinigt wird. 2. **Globaler Scope**: Skripte, die über `customJs` hinzugefügt werden, laufen im globalen Geltungsbereich. Verwenden Sie eine IIFE (Immediately Invoked Function Expression), um eine Verschmutzung des `window`-Objekts zu vermeiden. 3. **Bereinigung**: Wenn Ihr Skript globale Event-Listener hinzufügt (z. B. `window.onresize`), sollten Sie in Erwägung ziehen, den aktuellen Pfad zu verfolgen, um diese zu entfernen, wenn der Benutzer die Seite verlässt. --- ## [Live-Editor](https://docs.docmd.io/de/api/live-api/) --- title: "Live-Editor" description: "Verständnis des docmd Live-Editors und seines browserbasierten Authoring-Workflows." --- Der `docmd` Live-Editor ist eine spezialisierte Umgebung für das Schreiben von Dokumentationen in Echtzeit. Er nutzt den isomorphen Kern von `docmd`, um eine sofortige Side-by-Side-Vorschau Ihrer Markdown-Inhalte zu ermöglichen, ohne dass ein Backend-Build-Prozess erforderlich ist. ## Editor starten Starten Sie den lokalen Live-Editor mit dem Befehl: ```bash docmd live ``` Der Editor ist normalerweise unter `http://localhost:3000` erreichbar. ## Architektur Im Gegensatz zum Standard-`dev`-Server, der Dateien auf der Festplatte neu baut, führt der Live-Editor die `docmd`-Engine direkt in Ihrem Browser aus. Dies ermöglicht: 1. **Sofortiges Feedback**: Inhalte werden bereits während des Schreibens neu gerendert. 2. **Portable Playgrounds**: Der Editor kann in eine statische Website gebündelt werden, um beispielsweise auf GitHub Pages gehostet zu werden. 3. **Plattformübergreifende Konsistenz**: Die Vorschau nutzt exakt dieselbe Rendering-Logik wie der Produktions-Build. ## Statische Bereitstellung Generieren Sie eine teilbare, eigenständige Version des Editors: ```bash docmd live --build-only ``` Dies erstellt ein `dist/`-Verzeichnis, das das HTML des Editors und die gebündelte isomorphe Engine enthält. --- ## [MCP-Server](https://docs.docmd.io/de/api/mcp-server/) --- title: "MCP-Server" description: "Verbinden Sie KI-Agenten mit Ihrem Dokumentations-Workspace über das Model Context Protocol." --- docmd enthält einen nativen Model Context Protocol (MCP) Server, der es KI-Agenten ermöglicht, programmatisch mit Ihrem Dokumentations-Workspace zu interagieren. ## Was ist MCP? Das [Model Context Protocol](external:https://modelcontextprotocol.io/) ist ein offener Standard zur Verbindung von KI-Modellen mit externen Werkzeugen und Datenquellen. Es verwendet JSON-RPC 2.0 Nachrichten über eine Transportschicht (stdio, HTTP). docmd implementiert den `stdio`-Transport — der Agent startet `docmd mcp` als Kindprozess und kommuniziert über stdin/stdout. ## Schnellstart ```bash docmd mcp ``` Der MCP-Server wird über `stdio` gestartet. Es werden keine Netzwerk-Ports geöffnet — die gesamte Kommunikation erfolgt über Standard-Ein-/Ausgabeströme. ### Claude Desktop Konfiguration Fügen Sie Folgendes zu Ihrer `claude_desktop_config.json` hinzu: ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/pfad/zu/ihrem/docs/projekt" } } } ``` ### Cursor / Windsurf Konfiguration ```json { "command": "npx @docmd/core mcp", "transport": "stdio" } ``` ## Verfügbare Werkzeuge | Werkzeug | Beschreibung | | :--- | :--- | | **`search_docs`** | Volltextsuche über alle Dokumentationsdateien. | | **`read_doc`** | Liest den rohen Markdown-Inhalt einer Datei anhand des relativen Pfads. | | **`validate_docs`** | Führt eine Link-Validierung über alle Markdown-Dateien durch. | | **`get_llms_context`** | Gibt den vollständigen `llms-full.txt`-Kontext zurück. | ## Protokolldetails docmd implementiert die MCP-Spezifikation (Protokollversion `2025-03-26`): - **Transport**: `stdio` — JSON-RPC 2.0 Nachrichten über stdin/stdout - **Diagnose**: Wird nach `stderr` protokolliert - **Lebenszyklus**: `initialize` → `notifications/initialized` → Werkzeugaufrufe - **Ping**: Antwortet auf `ping`-Anfragen mit `{}` für Verbindungszustandsprüfungen ## Datenschutz & Sicherheit - **Nur lokal**: Der Server läuft als Kindprozess — keine Netzwerkexposition - **Sandboxed**: Dateioperationen sind auf das Projektverzeichnis beschränkt - **Keine Telemetrie**: Es werden keine Daten gesendet ## Ergänzende Funktionen - **`llms.txt` / `llms-full.txt`**: Wird zur Build-Zeit vom `llms`-Plugin generiert. - **Kontext-kopieren-Widget**: Browser-Schaltfläche zum Kopieren von seitenoptimiertem KI-Kontext. - **SKILL.md**: Von `docmd init` generiertes Agenten-Handbuch. Verweist auf [docmd-skills](external:https://github.com/docmd-io/docmd-skills). --- ## [Node.js API](https://docs.docmd.io/de/api/node-api/) --- title: "Node.js API" description: "Integrieren Sie die Build-Engine von docmd in Ihre benutzerdefinierten Node.js-Skripte und Automatisierungs-Pipelines." --- Für fortgeschrittene Workflows können Sie die `docmd`-Build-Engine direkt in Ihren eigenen Node.js-Anwendungen importieren und verwenden. Dies ist ideal für benutzerdefinierte CI/CD-Pipelines, automatisierte Dokumentationserstellung oder die Erweiterung von `docmd` für spezialisierte Umgebungen. ## Installation Stellen Sie sicher, dass `@docmd/core` in Ihrem Projekt installiert ist: ```bash npm install @docmd/core ``` ## Kernfunktionen ### `buildSite(configPath, options)` Die primäre Build-Funktion. Sie übernimmt das Laden der Konfiguration, das Parsen von Markdown und die Generierung von Assets. ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.js', { isDev: false, // Auf true setzen für Watch-Modus-Logik offline: false, // Auf true setzen zur Optimierung für file:// Zugriff zeroConfig: false // Auf true setzen, um die Erkennung der Konfigurationsdatei zu umgehen }); } ``` ### `buildLive(options)` Erzeugt das Bundle für den browserbasierten **Live Editor**. ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true startet einen lokalen Server; false erzeugt statische Dateien port: 3000 // Benutzerdefinierter Port, wenn serve true ist }); } ``` ## Beispiel: Benutzerdefinierte Pipeline Sie können `docmd` kapseln, um komplexe Dokumentations-Workflows zu erstellen. ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. Dynamische Inhalte generieren await fs.writeFile('./docs/dynamic.md', '# Generierter Inhalt'); // 2. docmd-Build ausführen await buildSite('./docmd.config.js'); // 3. Ausgabe verschieben await fs.move('./site', './public/docs'); } ``` ::: callout tip Die programmatische API ist hochgradig kompatibel mit **KI-gesteuerter Dokumentation**. Agenten können Builds nach Inhaltsaktualisierungen auslösen, um die Integrität zu prüfen und Bereitstellungen autonom zu verwalten. ::: ## Plugin-API (`@docmd/api`) Das Paket `@docmd/api` ist die dedizierte Heimat für das Plugin-System. Es bietet Hook-Registrierung, WebSocket-RPC-Dispatch, Quellcode-Editierwerkzeuge und **zentralisierte URL-Utilities**. ```bash npm install @docmd/api ``` ### URL-Utilities Plugins sollten diese zentralisierten Utilities verwenden, anstatt eine eigene URL-Logik zu implementieren. #### `outputPathToSlug(outputPath)` Konvertiert einen Ausgabe-Pfad der Build-Engine in einen sauberen Slug im Verzeichnis-Stil. ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` Konvertiert in einen Wurzel-relativen Pfadnamen (Pathname). ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` Erstellt eine vollständige kanonische URL. ```javascript import { outputPathToCanonical } from '@docmd/api'; outputPathToCanonical('guide/index.html', 'https://example.com'); // → 'https://example.com/guide/' ``` #### `sanitizeUrl(url)` Fasst Doppelschrägstriche zusammen (außer nach dem Protokoll). ```javascript import { sanitizeUrl } from '@docmd/api'; sanitizeUrl('https://example.com//path/'); // → 'https://example.com/path/' sanitizeUrl('/foo//bar/'); // → '/foo/bar/' ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` Erstellt eine absolute URL mit Locale- und Versions-Präfixen. ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` Normalisiert vom Benutzer geschriebene Hrefs zu sauberen URLs. Behandelt das Entfernen von `.md`, abschließende Schrägstriche sowie `external:` und `raw:` Präfixe. ```javascript import { resolveHref } from '@docmd/api'; resolveHref('overview.md'); // → { href: 'overview/', isExternal: false, isRaw: false } resolveHref('external:https://github.com/docmd-io/docmd'); // → { href: 'https://github.com/docmd-io/docmd', isExternal: true, isRaw: false } resolveHref('raw:docs/readme.md'); // → { href: 'docs/readme.md', isExternal: false, isRaw: true } ``` ### Vorberechnete Seiten-URLs Jedes Seiten-Objekt enthält vorberechnete URL-Daten. Plugins können diese direkt lesen - keine Berechnung erforderlich. ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); // "guide/" console.log(page.urls.canonical); // "https://example.com/guide/" console.log(page.urls.pathname); // "/guide/" } } ``` | Eigenschaft | Typ | Beschreibung | |:------------|:-----|:------------| | `slug` | `string` | Sauberer Slug im Verzeichnis-Stil (z. B. `guide/` oder `/`) | | `canonical` | `string` | Vollständige kanonische URL (nur wenn `config.url` gesetzt ist) | | `pathname` | `string` | Wurzel-relativer Pfad (z. B. `/guide/`) | > **Abwärtskompatibilität:** Alle Exporte aus `@docmd/api` werden auch aus `@docmd/core` re-exportiert, sodass bestehender Code ohne Änderungen weiterhin funktioniert. Neue Projekte werden ermutigt, direkt aus `@docmd/api` zu importieren. ### `createActionDispatcher(hooks, options)` Erstellt einen Dispatcher, der WebSocket-RPC-Nachrichten an Plugin-Aktions-/Event-Handler leitet. ```javascript import { createActionDispatcher } from '@docmd/api'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` Erstellt Werkzeuge zur Quellcode-Bearbeitung für die Manipulation von Markdown-Dateien. ```javascript import { createSourceTools } from '@docmd/api'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // Block-Informationen an einem bestimmten Zeilenbereich abrufen const block = await source.getBlockAt('docs/page.md', [10, 12]); // Text mit Syntax-Markierungen umschließen await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### `loadPlugins(config, options)` Lädt, validiert und registriert alle in der Konfiguration deklarierten Plugins. Gibt das gefüllte Hook-Register zurück. ```javascript import { loadPlugins, hooks } from '@docmd/api'; const registeredHooks = await loadPlugins(config, { resolvePaths: [__dirname] // Hilft beim Auflösen von Plugins in pnpm-Workspaces }); ``` ### Typ-Exporte Für TypeScript-Plugin-Autoren stehen folgende Typen zur Verfügung: ```typescript import type { PluginModule, // Vollständiges Plugin-Vertragsinterface PluginDescriptor, // Plugin-Metadaten (Name, Version, Fähigkeiten) PluginHooks, // Form des Hook-Registers PageContext, // Kontext für Build-Hooks (sourcePath, html etc.) Capability, // Deklaration der Hook-Kategorie (init, body, actions, etc.) ActionContext, // Kontext, der an Aktions-/Event-Handler übergeben wird ActionHandler, // Signatur für Aktions-Handler EventHandler, // Signatur für Event-Handler SourceTools, // Interface für Quellcode-Editierwerkzeuge BlockInfo, // Von getBlockAt zurückgegebene Block-Informationen TextLocation, // Von findText zurückgegebene Textposition } from '@docmd/api'; ``` --- ## [Vergleich](https://docs.docmd.io/de/comparison/) --- title: "Vergleich" description: "Warum docmd? Erfahren Sie, wie es im Vergleich zu Docusaurus, VitePress, MkDocs und anderen Tools abschneidet." --- Sie haben sich schon früher für ein Dokumentations-Tool entschieden. Sie werden es wieder tun. Hier ist das, was wirklich zählt - und wo docmd steht. ## Schreiben in 3 Sekunden starten, nicht in 30 Minuten ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` Fertig. Ihre Doku ist live. Keine Konfigurationsdateien, kein Projekt-Scaffolding, kein Abhängigkeits-Labyrinth. == tab "Docusaurus" ```bash npx create-docusaurus@latest mein-projekt classic cd mein-projekt npm install npm start ``` Vier Befehle, ein generiertes Projekt mit ~250 MB in `node_modules` und eine `docusaurus.config.js`, die Sie bearbeiten müssen, bevor etwas Nützliches passiert. == tab "VitePress" ```bash npx vitepress init ``` Stellt Ihnen 5 Fragen, generiert eine Konfigurationsdatei, dann führen Sie `vitepress dev` aus. Sauber - erfordert aber dennoch Scaffolding. == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new mein-projekt && cd mein-projekt mkdocs serve ``` Python-Ökosystem. Sie benötigen `pip`, eine virtuelle Umgebung und eine `mkdocs.yml`, bevor die erste Seite gerendert wird. ::: ## Der Payload-Unterschied ist real Ihre Leser sollten keine React-App herunterladen müssen, nur um einen Absatz zu lesen. Das ist es, was der Browser bei einer Website mit 50 Seiten tatsächlich empfängt: | Generator | Initialer Download (gesamt) | JS Payload | CSS Payload | |:----------|:---------------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "Warum das wichtig ist" Alle 100 KB JavaScript kosten auf einem Mittelklasse-Smartphone etwa 50 ms Zeit zum Parsen. Die 12 KB JS von docmd bedeuten, dass Ihre Doku sofort lädt, selbst bei 3G-Verbindungen. Docusaurus liefert 16-mal mehr JavaScript für denselben Inhalt aus. ::: ## Build-Geschwindigkeit Erstellung derselben Website mit 50 Seiten auf einem M1 MacBook Air: | Generator | Kaltstart (Build) | Hot Rebuild (Dev) | |:----------|:-----------------:|:-----------------:| | **docmd** | **~1,2s** | **~80ms** | | VitePress | ~2,5s | ~150ms | | MkDocs Material | ~3,0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd-Rebuilds sind so schnell, dass die Seite aktualisiert wird, bevor Sie das Fenster gewechselt haben. ## i18n, das tatsächlich funktioniert Hier scheitern die meisten Tools. Sie fügen 6 Sprachen hinzu, übersetzen 3 Seiten ins Hindi, und plötzlich stoßen Ihre Benutzer bei jeder nicht übersetzten Seite auf einen 404-Fehler. | Funktion | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | Fallback pro Seite auf Default-Locale | ✅ | ❌ (404) | ❌ (404) | ✅ | | Lokalisierte Warnung "nicht übersetzt" | ✅ | ❌ | ❌ | ✅ | | Automatische Deaktivierung fehlender Sprachen im Switcher | ✅ | ❌ | ❌ | ❌ | | Sofortige Prüfung der Seitensexistenz (offline) | ✅ | ❌ | ❌ | ❌ | | Kombination aus Versionierung + i18n | ✅ | ❌ | ❌ | ❌ | | Zero-Config (kein individuelles React/Vue) | ✅ | Teilweise | ❌ | ✅ | ::: callout warning "Was in VitePress und Docusaurus passiert" Wenn ein Leser auf Hindi wechselt und diese Seite nicht übersetzt ist, erhält er eine **404-Fehlermeldung**. Die einzige Abhilfe sind serverseitige Weiterleitungen oder das Schreiben einer eigenen React/Vue-Komponente. docmd regelt dies zum Build-Zeitpunkt - nicht verfügbare Locales erhalten ein "N/A"-Badge, und nicht übersetzte Seiten fallen lautlos auf den Standard zurück, begleitet von einem lokalisierten Warnungs-Callout. ::: ## Workspace (Arbeitsbereich) Organisationen, die mehrere Tools unter einer Domain verwalten, benötigen für jedes eigene Dokumentationen - unterschiedliche Versionen, unterschiedliche Navigationen, unterschiedliche Release-Zyklen. Die meisten Generatoren zwingen Sie entweder dazu, separate Websites zu pflegen oder sich mit Plugin-Systemen zu behelfen. | Funktion | docmd | Docusaurus | VitePress | MkDocs | Starlight | |:-----------|:-----:|:----------:|:---------:|:------:|:---------:| | Native Workspace-Unterstützung | ✅ | Plugin | ❌ | Plugin | ❌ | | Einzelne Konfigurationszeile pro Projekt | ✅ | ❌ | ❌ | ❌ | ❌ | | Unabhängige Versionierung pro Projekt | ✅ | ✅ | ❌ | ❌ | ❌ | | Unabhängiges i18n pro Projekt | ✅ | ❌ | ❌ | ❌ | ❌ | | Gemeinsam genutzte Assets über Projekte hinweg | ✅ | ❌ | ❌ | ❌ | ❌ | | Einzige `site/`-Ausgabe (kein Proxy erforderlich) | ✅ | ❌ | ❌ | ❌ | ❌ | | Zero-Config-Erkennung | ✅ | ❌ | ❌ | ❌ | ❌ | ::: callout info "Wie docmd es macht" ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Docs" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK" } ] } } ``` Jeder Projektordner hat seine eigene `docmd.config.json` mit unabhängiger Konfiguration. Ein `npx @docmd/core build` erzeugt ein einziges bereitstellbares Verzeichnis - kein Reverse-Proxy, kein Nginx, keine separaten CI-Pipelines. ::: Docusaurus erreicht Ähnliches mit Multi-Instance-Plugins, erfordert jedoch eine komplexe Konfiguration - jede Instanz benötigt separate Plugin-Einträge, Sidebar-Dateien und manuelle Routenkonfiguration. MkDocs erfordert das Drittanbieter-Plugin `mkdocs-monorepo-plugin`. VitePress, Starlight und Mintlify bieten keine native Workspace-Unterstützung. ## Vollständige Feature-Matrix | Feature | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **Zero-Config Start** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Konfiguration erforderlich** | Keine | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **Workspace-Unterstützung** | ✅ | Plugin | ❌ | Plugin | ❌ | ❌ | | **SPA-Navigation** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **Native Versionierung** | ✅ | ✅ | ❌ | Plugin | ❌ | ✅ | | **Natives i18n** | ✅ | ✅ | Manuell | Plugin | ✅ | ✅ | | **Integrierte Suche** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | Cloud | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **MCP-Server** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Agent Skills** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Docker-Image** | ✅ | ❌ | ✅ | ❌ | ❌ | N/A | | **Inline-Diskussionen** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA-Unterstützung** | ✅ | Community | ❌ | ❌ | ❌ | ❌ | | **Self-hosted** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **Deployment-Config-Generator** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## Konfigurationsaufwand Erforderliche Konfigurationszeilen für eine Website mit Versionierung, i18n, Suche und Sitemap: | Generator | Konfigurationszeilen | Erforderliche Dateien | |:----------|:--------------------:|:---------------------:| | **docmd** | **~15 Zeilen** | 1 (`docmd.config.js`) | | MkDocs Material | ~50 Zeilen | 1 + Plugins | | VitePress | ~80 Zeilen | 1 + Theme-Ordner | | Docusaurus | ~120 Zeilen | 3+ Konfig-Dateien | ## Qualitätssicherung docmd wird mit einer Brute-Test-Suite ausgeliefert, die **25 verschiedene Szenarien** anhand von **85 Assertionen** validiert - wobei jedes Feature isoliert und in Kombination abgedeckt wird. Jedes Release muss alle 85 Assertionen und 13 interne Failsafe-Checks bestehen, bevor es ausgeliefert wird. ::: callout tip "Führen Sie die Tests selbst aus" ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: Kein anderer Dokumentationsgenerator in dieser Klasse veröffentlicht eine vergleichbare End-to-End-Feature-Test-Suite als Teil seines Quellcodes. --- ## [Layout & UI-Zonen](https://docs.docmd.io/de/configuration/layout-ui/) --- title: "Layout & UI-Zonen" description: "Steuern Sie die Schnittstellenstruktur durch die Verwaltung von Headern, Seitenleisten und funktionalen UI-Slots." --- Eine Standard-`docmd`-Seite ist in sechs primäre Funktionsbereiche unterteilt: 1. **Menüleiste (Menubar)**: Eine horizontale Navigationsleiste am oberen Rand für globale Website-Links. 2. **Header**: Die permanente sekundäre Leiste, die den Seitentitel und Werkzeug-Schaltflächen enthält. 3. **Seitenleiste (Sidebar)**: Der primäre Navigationsbaum (normalerweise auf der linken Seite). 4. **Inhaltsbereich (Content Area)**: Der zentrale Bereich für die Markdown-Anzeige, einschließlich **Breadcrumbs**. 5. **Inhaltsverzeichnis (TOC)**: Navigationsmenü auf der rechten Seite für die Überschriften der aktuellen Seite. 6. **Fußzeile (Footer)**: Bereich am unteren Rand für Urheberrecht, Branding und website-weite Links. ## Globale Komponenten Die meisten UI-Zonen werden im Bereich `layout` Ihrer `docmd.config.js` konfiguriert. ### Menüleiste Die Menüleiste bietet eine übergeordnete Navigationsebene über Ihrer Dokumentation. ```javascript layout: { menubar: { enabled: true, position: 'top', // 'top' (fixiert) oder 'header' (im Inhaltsfluss) left: [ { type: 'title', text: 'Marke', url: '/', icon: 'home' }, { text: 'Funktionen', url: '/features' } ], right: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', icon: 'github' } ] } } ``` ### Der Seiten-Header Der Header ist standardmäßig aktiviert. Sie können ihn website-weit deaktivieren oder bestimmte Elemente über das Frontmatter auf Seitenebene ausblenden. ```javascript // docmd.config.js layout: { header: { enabled: true // Auf false setzen, um den gesamten oberen Header website-weit auszublenden }, breadcrumbs: true // Auf false setzen, um den Breadcrumb-Pfad website-weit auszublenden } ``` **Überschreibung auf Seitenebene (Frontmatter):** ```yaml --- title: "Spezialseite" hideTitle: true # Blendet den Titel im fixierten Header für diese spezifische Seite aus --- ``` ### Kopier-Widgets (KI-Integration) Um Entwicklern und LLM-Agenten die Arbeit mit Ihrer Dokumentation zu erleichtern, enthält docmd integrierte Kopierschaltflächen in der Breadcrumbs-Leiste. Diese Schaltflächen ermöglichen das Kopieren des rohen Markdowns der Seite oder des vereinheitlichten LLM-Kontexts. Konfigurieren Sie diese Schaltflächen im Einstellungsblock `theme.copyWidgets` in Ihrer `docmd.config.json`: ```json { "theme": { "copyWidgets": { "enabled": true, "raw": true, "context": true } } } ``` * `enabled`: Auf `false` setzen, um die Kopier-Widgets-Leiste vollständig zu deaktivieren. * `raw`: Auf `false` setzen, um die Schaltfläche "Copy Markdown" auszublenden. * `context`: Auf `false` setzen, um die Schaltfläche "Copy Context" auszublenden. ## Werkzeugmenüs (Optionsmenü) Das `optionsMenu` fasst Kernfunktionen wie **Suche**, **Theme-Umschalter** und **Sponsoring** zusammen. ```javascript layout: { optionsMenu: { position: 'header', // Optionen: 'header', 'sidebar-top', 'sidebar-bottom', 'menubar' components: { search: true, // Volltextsuche aktivieren themeSwitch: true, // Hell-/Dunkelmodus-Umschalter aktivieren sponsor: 'https://github.com/sponsors/dein-profil' } } } ``` ::: callout info "Container-Fallback" Wenn die gewählte Position auf einen Container zielt, der deaktiviert ist, rendert `docmd` das Optionsmenü automatisch im Slot `sidebar-top`, um sicherzustellen, dass die Kernfunktionen zugänglich bleiben. ::: ## Seitenleisten- & Fußzeilen-Steuerung ### Verhalten der Seitenleiste ```javascript layout: { sidebar: { enabled: true, collapsible: true, // Ermöglicht die Ein-/Ausklapp-Animation defaultCollapsed: false, // Legt den initialen Status der Seitenleiste fest position: 'left' } } ``` ### Footer-Branding `docmd` bietet sowohl **minimale** als auch **vollständige** Layouts für den Footer Ihrer Website. ```javascript layout: { footer: { style: 'complete', description: 'Dokumentation erstellt mit docmd.', branding: true, // Steuert das "Build with docmd"-Badge columns: [ { title: 'Community', links: [{ text: 'GitHub', url: '...' }] } ] } } ``` ::: callout tip "KI-optimierte Schnittstelle" Stellen Sie beim Entwerfen benutzerdefinierter Layouts sicher, dass die **Suche** in Ihrem `optionsMenu` prominent platziert ist. KI-Agenten nutzen die Suche häufig als primären Anker, wenn sie Ihre Dokumentation erkunden, um spezifischen technischen Kontext zu lokalisieren. ::: --- ## [Lokalisierung](https://docs.docmd.io/de/configuration/localisation/) --- title: "Lokalisierung" description: "Bieten Sie Ihre Dokumentation in mehreren Sprachen an - mit sprachspezifischem Routing, übersetzter Navigation und automatischem Fallback." --- Fügen Sie Ihrer Dokumentationsseite Mehrsprachigkeitsunterstützung hinzu. docmd stellt jede Sprache unter einem eigenen URL-Präfix bereit, übersetzt die System-UI-Strings und nutzt einen eleganten Fallback, falls eine Übersetzung fehlt. ## Sprachen zur Konfiguration hinzufügen ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "hi", "label": "हिन्दी" }, { "id": "zh", "label": "中文" } ] } } ``` Die Standardsprache (`default`) wird im Stammverzeichnis der Website (`/`) gerendert. Alle anderen Sprachen werden unter `/{id}/` gerendert. Sie wählen die IDs, Labels und welche Sprache die Standardsprache ist - es gibt keine fest programmierten Annahmen. Wenn Sie Hindi als Standardsprache möchten, setzen Sie `default: 'hi'`, und Hindi wird unter `/` gerendert, während Englisch unter `/en/` erscheint. | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `default` | `String` | Sprach-ID, die unter `/` gerendert wird. Standardmäßig die erste Sprache, wenn weggelassen. | | `locales` | `Array` | Liste von Sprachobjekten. Jedes muss eine `id` haben. | | `position` | `String` | Position des Sprachumschalters. `options-menu` (Standard), `sidebar-top` oder `sidebar-bottom`. | | `stringMode` | `Boolean` | Wenn `true`, werden Sprachseiten aus einer einzigen Quelle mittels `data-i18n`-Attribut-Ersetzung generiert. Standard: `false`. | | `inPlace` | `Boolean` | Wenn `true` (mit clientseitigem Skript), werden Strings ohne URL-Navigation getauscht. Nur für SPAs/Dashboards. Standard: `false`. | Jedes Sprachobjekt akzeptiert: | Schlüssel | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `id` | `String` | - | Ein beliebiger Identifikator Ihrer Wahl (z. B. `en`, `hi`, `fr-ca`). Wird als Ordnername und URL-Präfix verwendet. Erforderlich. | | `label` | `String` | Gleich wie `id` | Im Sprachumschalter angezeigter Name. | | `dir` | `String` | `ltr` | Textrichtung. Setzen Sie `rtl` für Arabisch, Hebräisch usw. | | `translations` | `Object` | `{}` | Benutzerdefinierte Überschreibungen für UI-Strings (siehe [Benutzerdefinierte UI-Strings](ui-strings.md)). | ## URL-Struktur Die Standardsprache hat kein URL-Präfix. Andere Sprachen werden unter `/{id}/` verschachtelt. In Kombination mit [Versionierung](../versioning.md) lautet die URL `/{locale}/{version}/seite`. ``` / ← Standardsprache, aktuelle Version /getting-started ← Seite der Standardsprache /05/ ← Standardsprache, alte Version /hi/ ← Andere Sprache, aktuelle Version /hi/getting-started ← Seite der anderen Sprache /hi/05/ ← Andere Sprache, alte Version ``` Der Sprachumschalter behält die aktuelle Seite und Version beim Sprachwechsel bei. Der Versionsumschalter behält die aktuelle Sprache bei. ## Fehlende Locale-Verzeichnisse Wenn eine Locale in `locales` deklariert ist, aber das zugehörige Quellverzeichnis nicht existiert (z. B. kein Ordner `docs/hi/`), **deaktiviert** docmd diese Locale automatisch im Sprachumschalter. Die Locale erscheint weiterhin im Dropdown - mit einem „N/A"-Badge und ausgegrautem Stil - aber ein Klick darauf bewirkt nichts. Dies verhindert 404-Fehler, wenn Sie geplante Sprachen auflisten, bevor deren Inhalte fertig sind. ## Positionierung des Sprachumschalters <img width="500" class="with-border" src="/assets/previews/menu-i18n.webp"> Steuern Sie die Position des Sprachumschalters mit der Option `position`: ```json { "i18n": { "position": "sidebar-top" } } ``` | Position | Verhalten | | :--- | :--- | | `options-menu` | Kompaktes Erdkugel-Icon neben Theme-Umschalter und Suche. Standard. | | `sidebar-top` | Vollständiges Dropdown mit Label oben in der Seitenleiste. | | `sidebar-bottom` | Vollständiges Dropdown mit Label unten in der Seitenleiste. | ## String-Modus (nur für noStyle-Seiten) Standard-i18n verwendet separate Verzeichnisse pro Sprache (`docs/en/`, `docs/hi/`), jedes mit eigenen Markdown-Dateien. **String Mode** ist eine einfachere Alternative, die speziell für [noStyle-Seiten](../../content/no-style-pages.md) entwickelt wurde - Seiten, die reines HTML anstelle von Markdown verwenden. ```json { "i18n": { "default": "en", "stringMode": true, "locales": [ { "id": "en", "label": "English" }, { "id": "zh", "label": "中文" } ] } } ``` Mit `stringMode: true`: 1. Quelldateien bleiben im Stammverzeichnis `docs/` (keine Sprach-Unterverzeichnisse) 2. Die Standardsprache wird wie gewohnt unter `/` erstellt 3. Für jede andere Sprache klont docmd das gerenderte HTML und führt eine **serverseitige String-Ersetzung** mittels JSON-Dateien aus `assets/i18n/{locale}.json` durch 4. Die Ausgabe erfolgt unter `/{locale}/` - z. B. `/zh/index.html` - mit vollem SEO (hreflang-Tags, korrektes `lang`-Attribut) 5. Falls eine Übersetzungsdatei fehlt, wird die Seite im Text der Standardsprache gerendert Weitere Details zur Syntax des `data-i18n`-Attributs und zum JSON-Dateiformat finden Sie unter [noStyle String-Ersetzung](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: callout warning "String Mode übersetzt keine Markdown-Inhalte" icon:info Die String-Ersetzung funktioniert durch das Finden von `data-i18n`-Attributen im gerenderten HTML. Standard-Markdown-Inhalte (`## Überschrift`, Absätze, Listen) werden in einfache HTML-Tags ohne diese Attribute umgewandelt - daher kann der Ersetzer dort nichts finden. - **Dokumentationsseiten** → verwenden Sie den Verzeichnismodus (Standard). Jede Sprache hat eigene Markdown-Dateien mit vollständig übersetztem Text. - **Landingpages, Marketing-Websites, Dashboards** → verwenden Sie den String-Modus. Dies sind noStyle-Seiten mit benutzerdefiniertem HTML, bei dem Sie jeden Tag kontrollieren und `data-i18n`-Attribute hinzufügen können. Wenn Ihre Website beides hat - zum Beispiel eine noStyle-Landingpage plus Dokumentation - verwenden Sie den Verzeichnismodus für die Dokumentation und fügen Sie Ihrer noStyle-Seite `data-i18n`-Attribute hinzu. Der String-Modus übersetzt das noStyle-HTML, während der Verzeichnismodus die Dokumentationsinhalte verarbeitet. ::: ## Nächste Schritte - [Übersetzte Inhalte](translated-content.md) - Verzeichnisstruktur, Schreiben von Übersetzungen, Navigation - [UI-Strings & SEO](ui-strings.md) - Anpassen von Systemtexten, hreflang-Tags - [noStyle String-Ersetzung](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle) - Syntax des `data-i18n`-Attributs und JSON-Format für noStyle-Seiten --- ## [Übersetzte Inhalte](https://docs.docmd.io/de/configuration/localisation/translated-content/) --- title: "Übersetzte Inhalte" description: "Organisieren Sie Übersetzungen in Sprach-Unterverzeichnissen mit Fallback pro Datei und sprachspezifischer Navigation." --- ## Verzeichnisstruktur Jede Sprache - einschließlich der Standardsprache - lebt in ihrem eigenen Unterverzeichnis innerhalb des Quellverzeichnisses. Der Ordnername entspricht der Sprach-`id` aus Ihrer Konfiguration. ``` docs/ ├── en/ ← Inhalt der Standardsprache │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← Zweite Sprache │ ├── index.md ← Übersetzte Homepage │ ├── navigation.json ← Übersetzte Navigations-Labels │ └── getting-started/ │ └── installation.md ← Übersetzte Seite └── zh/ ← Dritte Sprache └── index.md ← Nur die Homepage übersetzt ``` Das Quellverzeichnis dient als sauberer Container - es enthält ausschließlich Sprachordner. Wenn i18n aktiviert ist, befinden sich keine Inhaltsdateien auf der Stammebene. ::: callout info "Ordnernamen sind Ihre Wahl" Die Ordnernamen stammen direkt aus den `id`-Werten in Ihrer Konfiguration. Wenn Ihre Konfiguration `{ id: 'fr-ca' }` angibt, lautet Ihr Ordner `docs/fr-ca/`. Wenn Hindi Ihre Standardsprache ist (`default: 'hi'`), dann ist `docs/hi/` das Verzeichnis für den kanonischen Inhalt. ::: ## Fallback pro Datei Sie müssen nicht jede Seite übersetzen. docmd scannt das **Verzeichnis der Standardsprache** als kanonische Liste der Seiten. Für jede andere Sprache wird geprüft, ob eine übersetzte Version der jeweiligen Seite existiert: - Wenn `docs/hi/getting-started/installation.md` existiert → wird die Hindi-Übersetzung ausgeliefert - Wenn sie nicht existiert → wird die Version der Standardsprache für diese Seite ausgeliefert Wenn eine Seite auf den Fallback zurückgreift, kann docmd einen übersetzten Callout (Hinweis) anzeigen, der die Besucher informiert, dass die Seite in der Standardsprache angezeigt wird. Diese Nachricht ist über Ihre [UI-Strings](./ui-strings)-Konfiguration anpassbar. ## Sprach-exklusive Seiten Eine Nicht-Standardsprache kann auch Seiten haben, die in der Standardsprache nicht existieren. Diese werden nur für diese Sprache gerendert - sie erscheinen nicht in anderen Sprachen. ## Navigation übersetzen Jedes Sprachverzeichnis kann eine eigene `navigation.json` haben. `docmd` verwendet ein kaskadierendes Prioritätssystem, um die Seitenleiste aufzulösen. Einzelheiten zur Auflösungshierarchie und visuelle Beispiele finden Sie unter [Priorität der Navigationsauflösung](../navigation#prioritat-der-navigationsauflosung). Die `navigation.json` einer Sprache verwendet dasselbe Format: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "Teilweise Navigation" Sie müssen nur dann eine `navigation.json` für eine Sprache erstellen, wenn Sie übersetzte Labels wünschen. Wenn sie fehlt, wird die Navigation der Standardsprache verwendet - die Seiten werden gerendert, nur mit nicht übersetzten Labels. ::: ## Versionierung und i18n zusammen Wenn sowohl Versionierung als auch i18n konfiguriert sind, sieht die Quellstruktur wie folgt aus: ``` docs/ ← Aktuelle Version (Container) en/ ← Aktuelle Version, Standardsprache hi/ ← Aktuelle Version, übersetzte Sprache docs-v1/ ← Alte Version index.md ← Inhalt der alten Version (keine Sprachstruktur) navigation.json ``` Alte Versionen, die i18n zeitlich vorausgehen, funktionieren automatisch - docmd liest sie direkt aus, wenn keine Sprach-Unterverzeichnisse vorhanden sind. Nur die Standardsprache rendert die alte Version. Um Übersetzungen zu einer alten Version hinzuzufügen, erstellen Sie darin ein Sprach-Unterverzeichnis: ``` docs-v1/ hi/ ← Hindi-Übersetzung für v1 index.md navigation.json ``` Die Ausgabe-URLs verschachteln zuerst die Sprache, dann die Version: ``` / ← Standardsprache, aktuelle Version /hi/ ← Übersetzte Sprache, aktuelle Version /v1/ ← Standardsprache, alte Version /hi/v1/ ← Übersetzte Sprache, alte Version ``` --- ## [UI-Strings & SEO](https://docs.docmd.io/de/configuration/localisation/ui-strings/) --- title: "UI-Strings & SEO" description: "Passen Sie System-UI-Texte pro Sprache an und verstehen Sie automatische SEO-Tags für mehrsprachige Websites." --- ## Integrierter Sprachsupport `docmd` und seine offiziellen Plugins enthalten integrierte Übersetzungen für gängige Sprachen. Wenn Sie eine unterstützte Sprache konfigurieren, übersetzt die Engine Systemtexte wie Suchplatzhalter, Navigations-Labels und Theme-Umschalter automatisch. Für nicht unterstützte Sprachen oder benutzerdefinierte Formulierungen greift das System auf Englisch zurück. Sie können jeden String pro Sprache überschreiben. ## Benutzerdefinierte UI-Strings Verwenden Sie die Eigenschaft `translations` bei einer beliebigen Sprache, um Systemtexte zu überschreiben: ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "ar", "label": "العربية", "dir": "rtl", "translations": { "onThisPage": "في هذه الصفحة", "previous": "السابق", "next": "التالي", "search": "بحث", "toggleTheme": "تبديل المظهر", "editThisPage": "تعديل هذه الصفحة", "selectLanguage": "اختر اللغة", "selectVersion": "اختر الإصدار", "fallbackMessage": "هذه الصفحة غير متاحة بعد باللغة {active}. عرض اللغة الافتراضية ({default})." } } ] } } ``` Die Zusammenführungsreihenfolge lautet: **Systemübersetzungen → Plugin-Übersetzungen → Ihre Konfigurationsübersetzungen**. Ihre Konfiguration gewinnt immer. ## Verfügbare Schlüssel Statt eine feste Liste der verfügbaren Schlüssel bereitzustellen, können Sie die vollständige Sammlung der unterstützten Sprachen und Übersetzungsschlüssel direkt im docmd-Quellcode-Repository einsehen. **[Übersetzungsquellen auf GitHub anzeigen](external:https://github.com/docmd-io/docmd/tree/main/packages/ui/translations)** Der Schlüssel `fallbackMessage` unterstützt die Platzhalter `{active}` und `{default}`. Die Engine ersetzt diese zur Build-Zeit durch die entsprechenden Sprach-Labels. ## SEO und Hreflang `docmd` generiert automatisch `<link rel="alternate" hreflang="...">`-Tags für jede Seite über alle Sprachen hinweg. Die Standardsprache erhält zudem den `x-default` hreflang-Wert. ```html <!-- Automatisch auf jeder Seite generiert --> <link rel="alternate" hreflang="en" href="/"> <link rel="alternate" hreflang="x-default" href="/"> <link rel="alternate" hreflang="hi" href="/hi/"> <link rel="alternate" hreflang="zh" href="/zh/"> ``` Es ist keine Konfiguration erforderlich. Die Engine fügt diese Tags in jede Seite ein, wenn i18n aktiviert ist. ::: callout info "noStyle-Seiten" Das UI-Strings-System gilt für Standard-Themen-Layout-Seiten. Für noStyle-Seiten, die benutzerdefiniertes HTML verwenden, siehe [Clientseitige String-Ersetzung](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle). ::: --- ## [Menüleiste](https://docs.docmd.io/de/configuration/menubar/) --- title: "Menüleiste" description: "Strukturieren und positionieren Sie Ihre Menüleiste, verwalten Sie Navigationslinks und konfigurieren Sie Dropdown-Menüs." --- Die `menubar` ist eine Navigationsschicht, die globalen Kontext über Ihre gesamte Dokumentationsseite hinweg bietet. Sie kann als fixierte Leiste am oberen Rand des Ansichtsbereichs oder als relatives Element über dem Seiten-Header positioniert werden. ## Konfiguration Die Menüleiste wird im Bereich `layout` Ihrer `docmd.config.js` konfiguriert. ```javascript export default defineConfig({ layout: { menubar: { enabled: true, position: 'top', // 'top' (fixiert) oder 'header' (inline) left: [ { type: 'title', text: 'Marke', url: '/', icon: 'home' }, { text: 'Dokumentation', url: '/docs' }, { type: 'dropdown', text: 'Ökosystem', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: 'Live Editor', url: 'https://live.docmd.io' } ] } ], right: [ { text: 'Support', url: '/support', icon: 'help-circle' } ] } } }); ``` ### Optionen | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | Schaltet die Sichtbarkeit der Menüleiste ein/aus. | | `position` | `String` | `'top'` | `'top'` (fixiert ganz oben) oder `'header'` (über dem Seitentitel positioniert). | | `left` | `Array` | `[]` | Navigationselemente, die links ausgerichtet sind. | | `right` | `Array` | `[]` | Navigationselemente, die rechts ausgerichtet sind. | ## Element-Typen Die Arrays `left` und `right` unterstützen verschiedene Element-Typen, um Ihre Navigation effektiv zu strukturieren: ### 1. Standard-Link Der am häufigsten verwendete Element-Typ. - `text`: Anzeigename. - `url`: Pfad oder externe URL. - `icon`: Optionaler Name eines Lucide-Icons. - `external`: Auf `true` setzen, um in einem neuen Tab zu öffnen. ### 2. Titel (Marke) Setzen Sie `type: 'title'`, um Branding-Styles (normalerweise fett oder mit einer spezifischen Schriftstärke) auf den Link anzuwenden. ### 3. Dropdown-Menü Setzen Sie `type: 'dropdown'` und geben Sie ein `items`-Array an, um ein verschachteltes Menü zu erstellen. ## Werkzeug-Integration Sie können die globale Suche und den Theme-Umschalter in der Menüleiste unterbringen, indem Sie `optionsMenu.position` auf `'menubar'` setzen. ```javascript layout: { optionsMenu: { position: 'menubar' } } ``` Bei der Integration wird das Optionsmenü automatisch im **rechten Bereich** der Menüleiste ausgerichtet und erscheint nach allen im `right`-Array definierten Links. ::: callout info Wenn die `menubar` deaktiviert ist, fallen alle ihr zugewiesenen Werkzeugkomponenten automatisch auf die Position `sidebar-top` zurück. ::: ## Benutzerdefiniertes Styling Sie können das Erscheinungsbild der Menüleiste mithilfe von CSS-Variablen in Ihren `customCss`-Dateien anpassen: ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-color); --menubar-text: var(--docmd-text-primary); } ``` --- ## [Navigations-Konfiguration](https://docs.docmd.io/de/configuration/navigation/) --- title: "Navigations-Konfiguration" description: "Strukturieren Sie Ihre Seitenleiste, kategorisieren Sie Links und konfigurieren Sie Icons für Leser und Suchmaschinen." --- Der Compiler bietet eine explizite Kontrolle über Ihre Website-Navigation. Eine klare Navigationshierarchie schafft eine logische Lesereihenfolge. Dies optimiert das SPA-Erlebnis und bietet eine eindeutige Kontextkarte für die Suchindexierung und KI-Modelle. ## 1. Das Navigations-Schema Ein Array von Link-Objekten in Ihrer `docmd.config.json`-Datei steuert die Seitenleiste. Jedes Objekt ist ein direkter Link oder eine geschachtelte Kategoriegruppe. <img width="260" class="with-border" src="/assets/previews/navigation-hierarchy.webp"> ```json { "navigation": [ { "title": "Übersicht", "path": "/", "icon": "home" }, { "title": "Schnellstart", "path": "/getting-started/quick-start", "icon": "rocket" } ] } ``` ## 2. Unterstützte Eigenschaften Jedes Element unterstützt folgende Einstellungen: | Eigenschaft | Typ | Erforderlich | Beschreibung | | :--- | :--- | :--- | :--- | | `title` | `String` | Ja | Der in der Seitenleiste angezeigte Menütext. | | `path` | `String` | Nein | Ziel-URL. Relative lokale Pfade müssen mit einem Schrägstrich (`/`) beginnen. | | `icon` | `String` | Nein | Name eines beliebigen [Lucide-Icons](external:https://lucide.dev/icons) im Kebab-Case-Format (z. B. `git-branch`). | | `children` | `Array` | Nein | Ein Array von verschachtelten Navigationselementen, um ein Untermenü zu erstellen. | | `collapsible`| `Boolean`| Nein | Wenn `true`, kann der Benutzer den Kategorieordner erweitern oder einklappen. | | `external` | `Boolean`| Nein | Wenn `true`, wird der Link in einem neuen Browser-Tab geöffnet. | ## 3. Organisation von Bereichsgruppen Strukturieren Sie Ihre Seitenleiste mithilfe von zwei primären Gruppierungsmethoden: ### Klickbare Gruppe (Direkte Seite + Unterordner) Geben Sie neben `children` auch einen `path` für eine Kategorieüberschrift an. Durch Klicken auf den Titel wird die Landingpage geladen und die untergeordneten Links werden ausgeklappt. ```json { "title": "Cloud-Dienste", "path": "/cloud/overview", "children": [ { "title": "AWS Setup", "path": "/cloud/aws" }, { "title": "GCP Setup", "path": "/cloud/gcp" } ] } ``` ### Statisches Label (Nur Kategorieüberschriften) Lassen Sie den Parameter `path` weg. Die Überschrift dient als nicht anklickbarer Titel zur Gruppierung verwandter Links. Verwenden Sie dies, um größere technische Kategorien ohne eine eigene Landingpage zu unterteilen. ```json { "title": "Formatierung & Elemente", "icon": "layout-grid", "children": [ { "title": "Syntax-Leitfaden", "path": "/content/syntax" }, { "title": "Rich Container", "path": "/content/containers" } ] } ``` ## 4. Automatische Breadcrumbs Die Engine generiert automatisch kontextbezogene Breadcrumbs (Brotkrümelnavigation) für jede Seite. Diese werden direkt über der Hauptüberschrift der Seite angezeigt, um eine schnelle Orientierung zu erleichtern. <img width="500" class="with-border" src="/assets/previews/navigation-breadcrumb.webp"> ### Wichtigste Verhaltensweisen * **Automatische Auflösung**: Die Engine verfolgt die aktive Route durch Ihren Navigationsbaum, um die Hierarchie zu erstellen. * **Aktiver Indikator**: Die aktuelle Seite ist das letzte, nicht verlinkte Breadcrumb-Element. * **Mobile Optimierung**: Breadcrumbs werden auf kleinen Bildschirmen vereinfacht oder dynamisch ausgeblendet, um Platz zu sparen. ### Deaktivieren von Breadcrumbs Breadcrumbs sind standardmäßig aktiviert. Aktualisieren Sie Ihre Website-Layout-Optionen, um sie global zu deaktivieren: ```json { "layout": { "breadcrumbs": false } } ``` ## 5. Kaskadierende Navigationsauflösung Der Compiler verwendet ein kaskadierendes Auflösungssystem nach dem Prinzip „nächste Datei gewinnt“. Dies unterstützt mehrere Versionen oder Sprachen, ohne Ihre globale Konfiguration aufzublähen. ```text my-project/ ├── docmd.config.json [Ebene 3: Globale Konfiguration] - Standard-Fallback ├── docs-v1.0/ │ ├── navigation.json [Ebene 2: Versions-Navigation] - Überschreibt Global │ └── zh/ │ └── navigation.json [Ebene 1: Sprach-Navigation] - Absolute Priorität ``` 1. **Ebene 1: Sprachspezifisch** (`navigation.json` in einem Sprachordner): Überschreibt alle Einstellungen für diese spezifische Sprache und Version. 2. **Ebene 2: Versionsspezifisch** (`navigation.json` in einem Versionsordner): Überschreibt die globale Konfiguration für diese Version über alle Sprachen hinweg. 3. **Ebene 3: Globale Konfiguration** (`config.navigation`): Die grundlegende Fallback-Definition in der zentralen Konfigurationsdatei. ### Intelligenter Schutz vor toten Links Die Engine prüft beim Navigations-Fallback auf Ebene 2 oder 3 automatisch, ob die Zieldateien existieren. Fehlende Dateien werden dynamisch aus der Seitenleiste gefiltert. Dies verhindert tote Links für ältere Versionen oder fehlende Übersetzungen. ## 6. Icon-Integration Der Compiler enthält das vollständige **Lucide-Icon-System**. Verwenden Sie den offiziellen Lucide-Namen im Kebab-Case-Format (z. B. `settings`, `folder-open`, `book-marked`), um ein Icon anzuwenden. ::: callout tip "Optimierung von Seitenleisten-Labels" Halten Sie die Titel in der Seitenleiste klar und prägnant. Eine saubere Navigationsstruktur ermöglicht es KI-Agenten, Ihre Sitemap problemlos aus dem kompilierten `llms.txt`-Feed zu analysieren. ::: --- ## [Allgemeine Konfiguration](https://docs.docmd.io/de/configuration/overview/) --- title: "Allgemeine Konfiguration" description: "Konfigurieren Sie docmd.config.json zur Verwaltung von Branding, benutzerdefinierten Schemas, Routing, Layout-Verhalten und Build-Engines." --- Die Datei `docmd.config.json` ist die zentrale Konfiguration für Ihren Workspace. Sie steuert das Styling der Website, die Sidebar-Hierarchien, Lokalisierungsdetails und Compiler-Optionen. ## 1. Das Konfigurationsschema JSON ist das Standard-Konfigurationsformat. Dies ermöglicht eine hochperformante Serialisierung über die Worker-Pools der Engine. Jedoch werden `docmd.config.js` und `docmd.config.ts` weiterhin vollständig unterstützt, falls Sie dynamische JavaScript-Logik benötigen. ```json { "title": "Mein Projekt", "url": "https://docs.myproject.com", "src": "docs", "out": "site", "base": "/" } ``` ## 2. Kerneinstellungen Diese Parameter auf oberster Ebene konfigurieren die Basis-Eingaben und -Ziele des Compilers. | Parameter | Typ | Standardwert | Beschreibung | | :--- | :--- | :--- | :--- | | `title` | `String` | `"Documentation"` | Der formelle Name Ihrer Website. Erscheint in Navigations-Headern und Browser-Titelleisten. | | `url` | `String` | `null` | Ihre kanonische Produktions-URL. Wichtig für die SEO-Validierung, Sitemap-Indexierung und OpenGraph-Metadaten. | | `src` | `String` | `"docs"` | Relativer Pfad zum Ordner, der Ihre Markdown-Quelldateien (.md) enthält. | | `out` | `String` | `"site"` | Relativer Pfad, in den der Compiler die optimierte statische Website schreibt. | | `base` | `String` | `"/"` | Der Stamm-Basispfad Ihrer Website (z. B. auf `/docs/` setzen, wenn sie in einem Unterordner gehostet wird). | | `tmp` | `String` | `null` | Benutzerdefiniertes Verzeichnis für temporäre Kompilierungsdateien und Caching. Standardmäßig wird ein isolierter temporärer Systemordner verwendet. | | `i18n` | `Object` | `null` | Parameter für Mehrsprachigkeit. Siehe den [Leitfaden zur Lokalisierung](localisation/translated-content.md). | | `plugins` | `Object` | `{}` | Key-Value-Mapping zur Konfiguration von Standard- und benutzerdefinierten Plugins. Siehe [Plugin-Leitfaden](../plugins/usage.md). | | `engine` | `String` | `"js"` | Die aktive Verarbeitungs-Engine: `"js"` oder `"rust"` (Vorschau). | ## 3. Branding & Identität Verwalten Sie, wie Ihre Marke im Header und in den Browser-Tabs erscheint. ```json { "logo": { "light": "assets/images/logo-dark.png", "dark": "assets/images/logo-light.png", "href": "/", "alt": "Firmenlogo", "height": "32px" }, "favicon": "assets/favicon.ico" } ``` ## 4. UI-Layout & Verhalten Die Engine bietet ein modulares Header- und Sidebar-Layout. Passen Sie funktionale Bereiche an. Ändern Sie die Sichtbarkeit von Komponenten wie Suche und Dark-Mode-Umschalter. Aktivieren oder deaktivieren Sie Breadcrumbs. ```json { "layout": { "spa": true, "header": { "enabled": true }, "sidebar": { "collapsible": true, "defaultCollapsed": false }, "optionsMenu": { "position": "header", "components": { "search": true, "themeSwitch": true } } } } ``` Siehe den Leitfaden [Layout & UI-Zonen](layout-ui.md) für alle Optionen zur visuellen Anpassung. ## 5. Kernfunktionen der Engine Feinabstimmung, wie der Parser Ihre Inhaltsdateien verarbeitet. ```json { "minify": true, "autoTitleFromH1": true, "copyCode": true, "pageNavigation": true, "markdown": { "breaks": true } } ``` | Option | Typ | Standardwert | Beschreibung | | :--- | :--- | :--- | :--- | | `minify` | `Boolean` | `true` | Komprimiert Ausgabe-HTML und -JS-Strukturen für maximale Geschwindigkeit. | | `autoTitleFromH1` | `Boolean` | `true` | Löst fehlende Seitentitel anhand der ersten H1-Überschrift in der Datei auf. | | `copyCode` | `Boolean` | `true` | Zeigt eine Schaltfläche "Code kopieren" oben rechts in Syntaxblöcken an. | | `pageNavigation` | `Boolean` | `true` | Generiert automatisch ein rechtsseitiges Inhaltsverzeichnis ("Auf dieser Seite"). | | `markdown.breaks` | `Boolean` | `true` | Standardisiert Zeilenumbrüche. Auf `false` setzen, wenn Sie Markdown-Zeilen bei 80 Spalten umbrechen. | ::: callout warning "Eigenständiger editLink veraltet" icon:alert-triangle Die eigenständige `editLink`-Konfiguration ist veraltet. Verwenden Sie stattdessen das Kern-[Git-Plugin](../plugins/git.md). Es bietet dieselbe Editierlink-Funktionalität zusammen mit Commit-Zeitstempeln und Metadaten-Protokollen. ::: --- ## [Weiterleitungen & 404](https://docs.docmd.io/de/configuration/redirects/) --- title: "Weiterleitungen & 404" description: "Konfigurieren Sie Metadaten-basierte Weiterleitungen und benutzerdefinierte 404-Fehlerseiten für statische Deployments." --- In einer statischen Hosting-Umgebung gibt es keine serverseitige Logik (wie Nginx-Regeln oder `.htaccess`-Dateien), um dynamisches Routing zu verarbeiten. `docmd` löst dies durch das Generieren nativer HTML-Sicherungsmechanismen, die Weiterleitungen und Fehlerzustände automatisch behandeln. ## Serverlose Weiterleitungen (Redirects) Sie können Traffic von alten URLs auf neue Ziele umleiten, indem Sie ein Mapping im `redirects`-Objekt definieren. ```javascript export default defineConfig({ redirects: { '/setup': '/getting-started/installation', // Kurz-URL zu Deep-Link '/v1/api': '/api-reference' // Alte Version zu modernem Pfad } }); ``` ### Technische Umsetzung Wenn eine Weiterleitung definiert ist, erstellt `docmd` eine `index.html`-Datei am alten Pfad, die ein `<meta http-equiv="refresh">`-Tag enthält. Diese Strategie gewährleistet: 1. **Nahtlose Weiterleitung**: Benutzer werden sofort nach dem Laden der Seite zum neuen Ziel weitergeleitet. 2. **SEO-Erhalt**: Suchmaschinen erkennen die Weiterleitung, was hilft, die Link-Autorität (Link Equity) zu erhalten. 3. **Analytics-Tracking**: Seitenaufrufe werden erfasst, bevor die Weiterleitung stattfindet, wodurch Ihre Traffic-Daten erhalten bleiben. ## Markenkonforme 404-Seiten Wenn ein Benutzer versucht, auf eine nicht existierende URL zuzugreifen, suchen die meisten statischen Hosting-Anbieter (Netlify, Vercel, GitHub Pages) automatisch nach einer `404.html`-Datei im Stammverzeichnis. `docmd` generiert diese Datei standardmäßig und stellt sicher, dass sie das Theme, die Seitenleiste und die SPA-Funktionalität Ihrer Website erbt. ### Fehlerinhalt anpassen Sie können die 404-Fehlermeldung in Ihrer Konfiguration personalisieren: ```javascript export default defineConfig({ notFound: { title: '404: Seite nicht gefunden', content: "Wir konnten die gesuchte Seite nicht finden. Nutzen Sie die Seitenleiste, um zurückzufinden." } }); ``` ::: callout tip "Lokale Entwicklung" Der `docmd dev`-Server liefert automatisch Ihre benutzerdefinierte 404-Seite aus, wann immer eine angeforderte Datei fehlt, sodass Sie das Fehlererlebnis lokal testen können. ::: --- ## [Versionierung](https://docs.docmd.io/de/configuration/versioning/) --- title: "Versionierung" description: "Aktivieren Sie mehrdimensionale Dokumentationen mit nahtlosem Wechsel, Beibehaltung des Pfades und isolierten Build-Verzeichnissen." --- `docmd` verfügt über eine native Versionierungs-Engine, mit der Sie mehrere Versionen Ihres Projekts gleichzeitig verwalten und bereitstellen können (z. B. `v1.x`, `v2.x`). Die Engine übernimmt automatisch das URL-Routing, die Aktualisierung der Seitenleiste und die Logik für den Versionswechsel. ## Verzeichnis-Organisation Um die Versionierung zu aktivieren, organisieren Sie Ihre Dokumentation in versionierten Quellordnern. Ein gängiges Schema ist, die aktive Version in `docs/` zu halten und archivierte Versionen in Verzeichnissen mit dem Präfix `docs-` zu speichern. ```text mein-projekt/ ├── docs/ # Aktuelle Version (Hauptversion) ├── docs-v1/ # Veraltete Version ├── docmd.config.js ``` ## Konfiguration <img width="500" class="with-border" src="/assets/previews/menu-versioning.webp"> Definieren Sie Ihre Versionen innerhalb des `versions`-Objekts: ```javascript export default defineConfig({ versions: { current: 'v2', // Die Version-ID, die im Root (/) erstellt wird position: 'sidebar-top', // Position des Umschalters: 'sidebar-top' oder 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x (Aktuell)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## Kernfunktionen ### 1. Root-SEO (Die „aktuelle“ Version) Die als `current` festgelegte Version wird direkt in Ihrem Ausgabe-Root generiert (z. B. `meineseite.de/`). Dies stellt sicher, dass Ihr primärer Suchtraffic immer auf Ihrer aktuellsten Dokumentation landet. ### 2. Isolierte Unterverzeichnisse Nicht-aktuelle Versionen werden automatisch in Unterordnern erstellt, die ihrer `id` entsprechen. * `v2 (Aktuell)` → `meineseite.de/` * `v1` → `meineseite.de/v1/` ### 3. Permanenter Wechsel (Pfadbeibehaltung) `docmd` behält den relativen Pfad bei, wenn ein Benutzer die Version wechselt. Wenn ein Benutzer `meineseite.de/erste-schritte` liest und auf **v1** wechselt, wird er automatisch zu `meineseite.de/v1/erste-schritte` weitergeleitet (sofern die Seite existiert), anstatt zur Startseite zurückgeführt zu werden. ### 4. Asset-Isolation Jede Version erbt Ihr globales `assets/`-Verzeichnis, aber `docmd` stellt sicher, dass diese während des Build-Prozesses isoliert werden, um Style-Abweichungen oder Versionskonflikte zu vermeiden. ### 5. Versionierte Navigation Jede Version kann ihre eigene, unabhängige Navigationsstruktur verwalten. `docmd` verwendet ein kaskadierendes Prioritätssystem, um die Seitenleiste aufzulösen. Dies ermöglicht die Verwendung einer zentralen Konfiguration oder versions-/sprachspezifischer `navigation.json`-Dateien. Einzelheiten zur Auflösungshierarchie und visuelle Beispiele finden Sie unter [Priorität der Navigationsauflösung](./navigation#prioritat-der-navigationsauflosung). ## Best Practices 1. **Semantische IDs**: Verwenden Sie prägnante, URL-freundliche IDs wie `v1`, `v2` oder `beta`. 2. **Navigations-Parität**: Behalten Sie konsistente Ordnerstrukturen über die Versionen hinweg bei, um die Effektivität der „Pfadbeibehaltung“ zu maximieren. 3. **Einheitliche Konfiguration**: Sie benötigen keine separaten Konfigurationsdateien für jede Version; `docmd` verarbeitet alle Versionen in einem einzigen Durchgang. --- ## [Workspaces](https://docs.docmd.io/de/configuration/workspaces/) --- title: "Workspaces" description: "Erstellen Sie mehrere unabhängige Dokumentationsprojekte aus einer einzigen docmd-Instanz, mit globaler Konfigurationsvererbung und einem integrierten Projekt-Switcher." --- Mit Workspaces können Sie mehrere Dokumentationsprojekte aus einem einzigen Repository erstellen und bereitstellen. Jedes Projekt behält seine eigene Konfiguration. Globale Einstellungen, die am Workspace-Root definiert sind, vererben sich automatisch an jedes Projekt. ```text docs.example.com/ → Hauptdokumentation docs.example.com/sdk/ → SDK-Referenz docs.example.com/cli/ → CLI-Dokumentation ``` ## Einrichtung ### 1. Verzeichnisstruktur Ein Verzeichnis pro Projekt. Gemeinsame Assets und die globale Konfiguration befinden sich im Repository-Root. ```text my-docs/ ├── assets/ ← Gemeinsame Assets (werden von allen Projekten geerbt) ├── main-docs/ │ ├── docmd.config.json ← Projektkonfiguration (überschreibt Root-Standards) │ └── docs/ ← Projektinhalte ├── sdk-docs/ │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← Workspace-Root-Konfiguration └── package.json ``` ### 2. Root-Workspace-Konfiguration Die Root-Datei `docmd.config.json` verwendet den Schlüssel `workspace`. Alle übergeordneten Schlüssel (z. B. `theme`, `menubar`, `logo`) dienen als **globale Standardwerte** für jedes Projekt. ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Doku" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK-Referenz" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg" }, "menubar": [ { "text": "GitHub", "url": "https://github.com/my-org/my-repo", "external": true } ] } ``` #### `workspace`-Optionen | Schlüssel | Typ | Beschreibung | | :-- | :--- | :---------- | | `projects` | `Array` | Liste der Projekteinträge. Mindestens ein Eintrag muss `prefix: "/"` verwenden. | | `switcher` | `Object` | Steuert die Sichtbarkeit und Position des [Projekt-Switchers](#projekt-switcher). | #### Projekteintragsfelder | Schlüssel | Typ | Erforderlich | Beschreibung | | :-- | :--- | :------- | :---------- | | `prefix` | `String` | ✅ | URL-Präfix. Verwenden Sie `"/"` für das Root-Projekt. | | `src` | `String` | ✅ | Verzeichnispfad (relativ zum CWD), der die Inhalte des Projekts und eine optionale `docmd.config.json` enthält. | | `title` | `String` | - | Anzeigename, der in der UI des Projekt-Switchers angezeigt wird. | ### 3. Konfiguration auf Projektebene Jedes Projektverzeichnis kann eine eigene `docmd.config.json` besitzen. Hier definierte Einstellungen **überschreiben** die Standards des Workspace-Roots. ```json { "title": "SDK-Referenz", "src": "docs", "plugins": { "search": {}, "openapi": {} } } ``` Wenn keine lokale Konfigurationsdatei gefunden wird, wendet die Engine ein Zero-Config-Auto-Routing unter Verwendung der Workspace-Standards an. ### 4. Globale Konfigurationsvererbung Jeder im Root-Workspace definierte Schlüssel gilt automatisch für jedes Projekt. Projektkonfigurationen können selektiv alle diese globalen Werte überschreiben. | Ebene | Priorität | | :---- | :--------- | | Root-Workspace-Konfiguration | Niedrigste (wird zuerst als Standard angewendet) | | Projekt-`docmd.config.json` | Höher (überschreibt Root-Standards) | | Projekt-`navigation.json` | Höchste (gewinnt immer für die Navigation) | **Beispiel**: Definieren Sie Ihr globales `theme` und `menubar` einmal im Root. Jedes Projekt muss nur `title`, `src` and seine eigenen `plugins` festlegen. ::: callout info "Priorität der Navigation" icon:info Eine `navigation.json`-Datei auf Projektebene **hat immer Vorrang** vor jedem `navigation`-Array, das in der Root-Konfiguration des Workspace definiert ist. Wenn keine von beiden existiert, fällt docmd auf die automatische Verzeichnis-Scannung zurück. ::: ## Projekt-Switcher Der Projekt-Switcher rendert eine schlanke UI-Komponente zum Navigieren zwischen Workspace-Projekten. ### Konfiguration ```json { "workspace": { "switcher": { "enabled": true, "position": "sidebar-top" } } } ``` | Position | Beschreibung | | :------- | :---------- | | `sidebar-top` (Standard) | Oben in der Seitenleiste angeheftet, über der Navigation. | | `sidebar-bottom` | Unten in der Seitenleiste angeheftet. | | `options-menu` | Integriert in das Header-Optionsmenü neben Suche und Theme-Umschaltern. | Der Switcher wird nur gerendert, wenn zwei oder mehr Projekte definiert sind. ## Assets ### Gemeinsame Assets Platzieren Sie Logos, Favicons und globales CSS im Root-Verzeichnis `assets/`. Die Engine kopiert diese bei `dev` und `build` automatisch in die Ausgabe jedes Projekts. ### Projektspezifische Assets Jedes Projekt kann ein eigenes `assets/`-Verzeichnis besitzen. Projekt-Assets haben bei Namenskonflikten Vorrang vor gemeinsamen Assets. ## Bauen & Entwicklung ### Dev-Server ```bash npx @docmd/core dev ``` Baut alle Projekte und stellt sie über einen einzigen Port bereit. Dateiänderungen lösen **zielgerichtete, projektspezisifische** Rebuilds aus - nur das modifizierte Projekt wird neu gerendert, nicht der gesamte Workspace. Änderungen an der Root-Konfiguration lösen einen vollständigen Workspace-Rebuild aus. ### Produktions-Build ```bash npx @docmd/core build ``` Gibt ein einzelnes statisches Verzeichnis aus. Alle Projekte werden in ihre jeweiligen Unterpfade zusammengeführt. Es ist kein Reverse-Proxy oder eine komplexe CI-Pipeline erforderlich. ## Regeln & Einschränkungen 1. **Root-Projekt erforderlich**: Genau ein Projekt muss `prefix: "/"` verwenden. 2. **Eindeutige Präfixe**: Jedes Projekt muss ein eindeutiges URL-Präfix verwenden. 3. **`out` nur im Root**: Nur die Root-Workspace-Konfiguration steuert das Ausgabeverzeichnis. Konfigurationen von Child-Projekten dürfen `out` nicht definieren. 4. **Keine Präfixkonflikte**: Wenn ein Root-Projekt einen Ordner namens `sdk/` hat und ein anderes Projekt `prefix: "/sdk"` verwendet, gibt die Engine eine Konfliktwarnung aus. Das präfigierte Projekt gewinnt immer. ## Migration von Legacy-Konfigurationen Die Syntax des `projects`-Arrays vor 0.8.3 und andere ältere Konfigurationsschlüssel werden zur Abwärtskompatibilität automatisch in das moderne `workspace`-Schema überführt. Obwohl manuelle Updates nicht zwingend erforderlich sind, können Sie Ihre Konfigurationsdatei mithilfe der CLI automatisch auf das moderne Schema aktualisieren. ::: callout tip "Mit einem Befehl migrieren" icon:lightbulb Führen Sie `npx @docmd/core migrate --upgrade` aus, um Ihre Root-Konfiguration automatisch auf das aktuelle Schema umzuschreiben. ::: --- ## [Zero-Config](https://docs.docmd.io/de/configuration/zero-config/) --- title: "Zero-Config" description: "Erfahren Sie, wie die Heuristik-Engine von docmd Ihre Website automatisch und ohne Konfigurationsdateien strukturiert." --- `docmd` verfügt über eine intelligente Heuristik-Engine, die Ihre Dokumentation automatisch analysiert und strukturiert. Sie können mit dem Schreiben, Bereitstellen und Übersetzen Ihrer Dokumentation beginnen, ohne eine einzige Zeile Konfiguration schreiben zu müssen. ## Wie es funktioniert Wenn das Tool ohne eine `docmd.config.json`-Datei ausgeführt wird, aktiviert die Engine automatisch den **Zero-Config-Modus**. Sie scannt das Workspace-Verzeichnis nach Inhalten und wendet die folgenden Heuristiken an: ### 1. Erkennung des Quellverzeichnisses Die Engine sucht in dieser Reihenfolge nach Dokumentationsdateien in den folgenden Kandidatenverzeichnissen: 1. `docs/` 2. `src/docs/` 3. `documentation/` 4. `content/` 5. `.` (Fallback auf das Stammverzeichnis) Wenn eines der Kandidatenverzeichnisse gefunden wird und Markdown-Dateien enthält, wird es als Quelle ausgewählt. Wenn kein Verzeichnis gefunden wird, aber das Projektstammverzeichnis Markdown-Dateien enthält, wird das Stammverzeichnis verwendet (wobei `node_modules`, `.git` sowie Ausgabeordner wie `site/`, `dist/` und `out/` automatisch ignoriert werden). Wenn überhaupt kein Dokumentationsinhalt gefunden wird, initialisiert `docmd` automatisch eine neue Standardstruktur. ### 2. Heuristiken für Versionen und Locales Die Ordnerstruktur wird gescannt, um Metadaten für Versionierung und Lokalisierung dynamisch zu extrahieren: - **Versionen**: Unterverzeichnisse, die auf `v[0-9]+` passen (z. B. `v1.0`, `v08`), werden als Dokumentationsversionen analysiert. - **Locales (Sprachen)**: Unterverzeichnisse mit zweistelligen Sprachcodes (z. B. `en`, `de`, `zh`) werden als lokalisierte Varianten behandelt. - **Strukturextraktion**: Die höchste Version wird als aktuelles Release festgelegt, und die erste gefundene Sprache (wobei `en` bevorzugt wird, falls vorhanden) wird als Standardsprache festgelegt. ### 3. Automatische Navigationsrouten Wenn keine Versionen oder Sprachen auf Root-Ebene vorhanden sind, erstellt die Engine dynamisch einen Navigationsbaum, indem sie die Dateistruktur analysiert: - Unterverzeichnisse werden Navigationsgruppen zugeordnet. - Titel werden dynamisch aus den Dateinamen generiert. Z. B. wird `getting-started.md` als `Getting Started` formatiert. - Indexdateien (`index.md`, `README.md`) werden als Startseite des aktuellen Verzeichnisses geroutet. ## Best Practices für Zero-Config Um den Zero-Config-Modus optimal zu nutzen, beachten Sie folgende Strukturempfehlungen: - **Eindeutige Dateibenennung**: Verwenden Sie klare Dateinamen mit Bindestrichen oder in camelCase. Der Autoloader konvertiert diese in lesbare Titel. - **Ordnerbasierte Abschnitte**: Platzieren Sie zusammengehörige Dokumente in Unterordnern, um sie automatisch in der Seitenleiste zu gruppieren. - **Index-Fallback**: Platzieren Sie immer eine `index.md` oder `README.md` im Stammverzeichnis Ihres Quellordners, um als Startseite zu dienen. - **Sauberer Ausgabepfad**: Wenn Sie das Stammverzeichnis `.` als Quelle verwenden, belassen Sie Ihre erstellten Assets im Standardordner `site/`, da dieser automatisch ignoriert wird. --- ## [Buttons](https://docs.docmd.io/de/content/containers/buttons/) --- title: "Buttons" description: "Fügen Sie Call-to-Action-Buttons für internes Routing oder externe Ressourcen mit einer einzeiligen Syntax ein." --- Buttons sind einflussreiche UI-Elemente, die für eine prominente Navigation verwendet werden. Im Gegensatz zu Block-Containern ist der `button` **selbstschließend** - er wird in einer einzigen Zeile definiert und benötigt kein schließendes `:::`-Tag. ## Syntax ```markdown ::: button "Beschriftung" Pfad [Optionen] ``` ### Optionen-Referenz | Eigenschaft | Format | Beschreibung | | :--- | :--- | :--- | | **Pfad (Path)** | `/pfad/` | Relative Projekt-URL (wird automatisch für die SPA-Navigation aufgelöst). | | **Extern (External)** | `external:URL`| Öffnet die Ziel-URL in einem neuen Browser-Tab (`target="_blank"`). | | **Farbe (Color)** | `color:WERT` | Wendet eine Hintergrundfarbe an (unterstützt CSS-Namen oder Hex-Codes). | | **Icon** | `icon:NAME` | Fügt ein [Lucide](external:https://lucide.dev/icons)-Icon vor der Button-Beschriftung hinzu. | ## Anwendungsbeispiele ### 1. Interne Navigation Verwenden Sie relative Pfade, um nahtlose Übergänge ohne Neuladen innerhalb der `docmd` SPA zu gewährleisten. ```markdown ::: button "docmd installieren" /getting-started/installation ``` ::: button "docmd installieren" /getting-started/installation ### 2. Link zu externen Ressourcen Stellen Sie der URL `external:` voran, um eine sichere externe Verlinkung zu gewährleisten. ```markdown ::: button "GitHub-Repository anzeigen" external:https://github.com/docmd-io/docmd ``` ::: button "GitHub-Repository anzeigen" external:https://github.com/docmd-io/docmd ### 3. Semantisches & Marken-Styling Passen Sie Buttons durch Farbüberschreibungen an Ihre Markenidentität oder semantische Priorität an. ```markdown ::: button "Gefährliche Aktion" /delete color:crimson ::: button "Erfolgreiche Bestätigung" /success color:#228B22 ``` ::: button "Gefährliche Aktion" ./#delete color:crimson ::: button "Erfolgreiche Bestätigung" ./#success color:#228B22 ### 4. Buttons mit Icons Fügen Sie ein Lucide-Icon hinzu, um die visuelle Klarheit zu verbessern. ```markdown ::: button "Erste Schritte" /getting-started/installation icon:arrow-right ::: button "Quellcode anzeigen" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "Erste Schritte" /getting-started/installation icon:arrow-right ::: button "Quellcode anzeigen" external:https://github.com/docmd-io/docmd icon:github ## Wichtiger Hinweis: Selbstschließende Logik Da Buttons selbstschließend sind, beendet das Hinzufügen einer abschließenden `:::`-Zeile den **übergeordneten Container** (z. B. eine Card oder ein Tab), in dem sich der Button befindet, was potenziell Ihr Layout zerstören kann. **Falsche Sequenz:** ```markdown ::: card "Setup" ::: button "Beginnen" /setup ::: <-- Fehler: Dies schließt die Card vorzeitig. ::: ``` **Richtige Sequenz:** ```markdown ::: card "Setup" ::: button "Beginnen" /setup ::: <-- Richtig: Dies schließt die Card. ``` --- ## [Callouts](https://docs.docmd.io/de/content/containers/callouts/) --- title: "Callouts" description: "Heben Sie kritische Warnungen, Pro-Tipps und Hintergrundkonformationen durch semantische visuelle Blöcke hervor." --- Callouts werden verwendet, um Informationen hervorzuheben, die die sofortige Aufmerksamkeit des Lesers erfordern. `docmd` bietet fünf semantische Typen an, die jeweils ein unterschiedliches visuelles Design und thematische Icons besitzen. ::: callout info "Migrationsfreundliche Aliase" Wenn Sie von **VitePress** oder **Docusaurus** migrieren, können Sie deren native Syntax direkt verwenden: - `:::tip`, `:::warning`, `:::danger`, `:::info` (VitePress) - `:::note`, `:::caution` (Docusaurus) Diese Aliase werden identisch zu ihren `docmd`-Äquivalenten gerendert. Leerzeichenlose Syntax wie `:::callout` funktioniert ebenfalls. ::: ## Syntax-Referenz ```markdown ::: callout typ "Optionaler Titel" Der technische Inhalt oder die Warnung wird hier platziert. ::: ``` Fügen Sie einen optionalen `icon:`-Parameter hinzu, um das Standard-Icon des Typs durch ein beliebiges [Lucide](external:https://lucide.dev/icons)-Icon zu ersetzen: ```markdown ::: callout info "Benutzerdefiniertes Icon" icon:sparkles Dieser Callout verwendet ein benutzerdefiniertes Icon anstelle des Standard-Info-Icons. ::: ``` ### Unterstützte semantische Typen | Typ | Absicht | Visuelles Signal | | :--- | :--- | :--- | | `info` | **Allgemeine Daten** | Kontextueller Hintergrund oder hilfreiche, nicht kritische Infos. | | `tip` | **Optimierung** | Performance-Shortcuts oder "Pro-Tipps". | | `warning`| **Vorsicht** | Potenzielle Probleme oder veraltete Funktionen, die beachtet werden sollten. | | `danger` | **Kritisch** | Risiko von Datenverlust, Breaking Changes oder Systemausfall. | | `success`| **Verifizierung** | Bestätigung einer erfolgreichen Konfiguration oder eines erfolgreichen Builds. | ## Implementierungsgalerie ### 1. Minimalistischer Informationshinweis ```markdown ::: callout info Legacy-Konfigurationsschemata werden weiterhin unterstützt, aber nicht mehr empfohlen. ::: ``` ::: callout info Legacy-Konfigurationsschemata werden weiterhin unterstützt, aber nicht mehr empfohlen. ::: ### 2. Warnung mit hoher Priorität und benutzerdefiniertem Titel ```markdown ::: callout warning "Ziel für Breaking Changes" Ab `v0.7.0` wird das interne WebSocket-RPC-System offiziell als veraltet eingestuft. ::: ``` ::: callout warning "Ziel für Breaking Changes" Ab `v0.7.0` wird das interne WebSocket-RPC-System offiziell als veraltet eingestuft. ::: ### 3. Kombination mit reichhaltigem Inhalt Callouts unterstützen das volle Spektrum von Markdown, sodass Sie Buttons und Code-Blöcke innerhalb der Warnung einbetten können. ````markdown ::: callout tip "Optimiertes lokales Testen" icon:command Verwenden Sie das preserve-Flag, um Build-Dateien während der Entwicklungssitzungen beizubehalten: ```bash docmd dev --preserve ``` ::: button "CLI-Flag-Referenz" /cli-commands ::: ```` ::: callout info "Optimiertes lokales Testen" icon:command Verwenden Sie das preserve-Flag, um Build-Dateien während der Entwicklungssitzungen beizubehalten: ```bash docmd dev --preserve ``` ::: button "CLI-Flag-Referenz" ./#cli-commands ::: ::: callout tip "Priorisierte Logik für KI" Für LLMs fungieren Callouts als **Anker mit hoher Priorität**. Durch die Verwendung von `::: callout danger` zur Dokumentation von Breaking Changes oder Systembeschränkungen geben Sie ein klares Signal, dass das KI-Modell diese Informationen während seines Denk- und Generierungsprozesses gegenüber dem umgebenden Text priorisieren muss. ::: --- ## [Untitled](https://docs.docmd.io/de/content/containers/cards/) --- ## [Changelogs](https://docs.docmd.io/de/content/containers/changelogs/) --- title: "Changelogs" description: "Generieren Sie eine strukturierte, zeitachsenbasierte Versionshistorie und Release-Notes." --- Der `changelog`-Container bietet ein spezialisiertes Layout für die Dokumentation der Projektentwicklung. Er analysiert Datums- oder Versions-Header automatisch in eine vertikale Zeitachse und stellt so sicher, dass historische Aktualisierungen leicht scanbar sind. ## Syntax Verwenden Sie das spezielle Trennzeichen `==`, um Einträge zu definieren. Der Text in der `==`-Zeile wird als Zeitachsen-Badge auf der linken Seite gerendert, während der folgende Inhalt den angrenzenden chronologischen Slot füllt. ```markdown ::: changelog == v2.0.0 Beschreibung des Major-Feature-Release. == v1.5.0 Beschreibung von Wartungs-Updates und Sicherheits-Patches. ::: ``` ## Detailliertes Beispiel: Release-Historie Changelogs unterstützen reichhaltiges Markdown innerhalb jedes Eintrags, einschließlich Listen, Callouts und Code-Blöcken. ```markdown ::: changelog == v2.0.0 (15.03.2026) ### Umfassende Systemüberarbeitung Die Core-Engine wurde für die isomorphe Ausführung neu architekturiert. * Implementierung des **SPA-Routers** für Navigation ohne Neuladen. * Einführung des **isomorphen Plugin-Systems**. ::: callout success Dieses Release bietet eine Verbesserung der initialen Build-Geschwindigkeit um 40%. ::: == v1.5.1 (10.12.2025) ### Sicherheits-Patch * Hochgradige Sicherheitslücke im internen Parser behoben. * Abhängigkeit `flatted` auf `v3.3.2` aktualisiert. == v1.0.0 (01.05.2024) Erstveröffentlichung. ::: ``` ::: changelog == v2.0.0 (15.03.2026) ### Umfassende Systemüberarbeitung Die Core-Engine wurde für die isomorphe Ausführung neu architekturiert. * Implementierung des **SPA-Routers** für Navigation ohne Neuladen. * Einführung des **isomorphen Plugin-Systems**. ::: callout success Dieses Release bietet eine Verbesserung der initialen Build-Geschwindigkeit um 40%. ::: == v1.5.1 (10.12.2025) ### Sicherheits-Patch * Hochgradige Sicherheitslücke im internen Parser behoben. * Abhängigkeit `flatted` auf `v3.3.2` aktualisiert. == v1.0.0 (01.05.2024) Erstveröffentlichung. ::: ::: callout tip "Historischer Kontext für KI" Changelogs liefern eine zeitliche Karte für KI-Agenten. Wenn ein LLM den `llms-full.txt`-Kontext analysiert, ermöglicht die `::: changelog`-Struktur eine genaue Identifizierung, wann spezifische Funktionen, Breaking Changes oder Sicherheitsfixes eingeführt wurden, was zu einer höheren Genauigkeit bei Entwicklungsempfehlungen führt. ::: --- ## [Ausklappbare Abschnitte](https://docs.docmd.io/de/content/containers/collapsible/) --- title: "Ausklappbare Abschnitte" description: "Betten Sie interaktive Umschalter im Akkordeon-Stil für FAQs, vertiefende Inhalte und Spoiler ein." --- Der `collapsible`-Container erstellt einen interaktiven, umschaltbaren Abschnitt (Akkordeon). Dieses Muster ist ideal für FAQs, detaillierte technische Konfigurationen oder alle sekundären Informationen, die zugänglich sein sollen, ohne den primären Dokumentationsfluss zu überladen. ::: callout info "VitePress-Alias" Wenn Sie von **VitePress** migrieren, können Sie `:::details` als Alias für `:::collapsible` verwenden. Leerzeichenlose Syntax wie `:::collapsible` funktioniert ebenfalls. ::: ## Syntax ```markdown ::: collapsible [open] "Titel-Text" Der Hauptinhalt wird hier platziert. ::: ``` ### Optionen-Referenz - **`open`**: (Optional) Wenn angegeben, wird der Abschnitt im erweiterten Zustand initialisiert. - **`"Titel"`**: Der Text, der auf der interaktiven Umschaltleiste gerendert wird. Standardmäßig "Klicken zum Erweitern", wenn weggelassen. - **`icon:NAME`**: (Optional) Fügt ein [Lucide](external:https://lucide.dev/icons)-Icon vor dem Titeltext hinzu. ## Detaillierte Implementierungsbeispiele ### Standardverwendung (Initialzustand: Geschlossen) Hauptsächlich für FAQs oder zur Reduzierung der visuellen Dichte technischer Seiten verwendet. ```markdown ::: collapsible "Wie aktualisiere ich docmd?" Führen Sie `npm update -g @docmd/core` aus, um die neueste stabile Engine abzurufen. ::: ``` ::: collapsible "Wie aktualisiere ich docmd?" Führen Sie `npm update -g @docmd/core` aus, um die neueste stabile Engine abzurufen. ::: ### Opt-In-Sichtbarkeit (Initialzustand: Offen) Ideal für Abschnitte, die standardmäßig sichtbar sein sollten, dem Benutzer aber ermöglichen, sie für eine sauberere Ansicht zu minimieren. ```markdown ::: collapsible open "Umgebungsvoraussetzungen" 1. Node.js v18+ (LTS empfohlen) 2. PNPM-Paketmanager ::: ``` ::: collapsible open "Umgebungsvoraussetzungen" 1. Node.js v18+ (LTS empfohlen) 2. PNPM-Paketmanager ::: ### Verschachtelte technische Daten Collapsibles können komplexe Markdown-Elemente enthalten, einschließlich syntax-hervorgehobener Codeblöcke. ````markdown ::: collapsible "Beispiel-JSON-Antwort analysieren" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "Beispiel-JSON-Antwort analysieren" ```javascript "status": "success", "data": { "version": "0.6.2" } ``` ::: ::: callout tip Obwohl Inhalte innerhalb eines `collapsible` für den menschlichen Benutzer verborgen sein können, bleiben sie für den `docmd`-Suchindex vollständig sichtbar und sind im einheitlichen `llms-full.txt`-Stream enthalten. Dies stellt sicher, dass KI-Agenten umfassende Antworten basierend auf verborgenen technischen Details geben können, während die für Menschen sichtbare Benutzeroberfläche sauber und priorisiert bleibt. ::: --- ## [URL-Embeds](https://docs.docmd.io/de/content/containers/embed/) --- title: URL-Embeds description: Wie Sie dynamische Komponenten, Videos und soziale Medien sicher direkt in Ihre Dokumente einbetten. --- `docmd` wird nativ mit dem hochoptimierten **[embed-lite](external:https://github.com/mgks/embed-lite)**-Parser-Ökosystem ausgeliefert. Dies ermöglicht es Ihnen, rohe externe URLs strikt auf der Seite abzubilden und sie sofort in vollständig sichere UI-Komponenten mit Null-Latenz zu verwandeln! ## Unterstützte Plattformen Die integrierte Engine stellt nativ strukturierte Formatter für die folgenden Netzwerke identisch zur Verfügung: * **Video-Ökosystem:** YouTube (einschließlich nativer 9:16 Shorts-Unterstützung), Vimeo, Dailymotion, TikTok * **Soziale Verbindungen:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **Code & Prototyping:** GitHub Gists, CodePen, Figma, Google Maps * **Musikdienste:** Spotify, SoundCloud ## Nutzungssyntax Sie verwenden einfach den `::: embed`-Container gefolgt von einer beliebigen Ziel-URL. Alle drei umschließenden Formate sind äquivalent: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### Beispiel für Standardergebnis Die Rendering-Engine parst diese URL strikt im Hintergrund, prüft die Validierungsmatrix und fügt native HTML-Knoten strukturell direkt und elegant in Ihre Seitenausgabe ein: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## Fallback-Sicherheit Machen Sie sich keine Sorgen über die Generierung defekter Bildschirme. Wenn der interne Parser ein nicht verifiziertes oder strikt nicht verfügbares Domain-Konfigurations-Mapping scannt, fällt `docmd` elegant auf die Generierung einer einfachen, soliden `<a>`-Hyperlink-Schaltfläche zurück, die explizit auf das Ziel verweist: ```md ::: embed "https://docs.docmd.io/de/content/containers/embed/" ``` *(Fährt fort, genau das zu generieren, was Sie unten sehen würden)* ::: embed "https://docs.docmd.io/de/content/containers/embed/" --- ## [Grids](https://docs.docmd.io/de/content/containers/grids/) --- title: "Grids" description: "Organisieren Sie Layouts nahtlos mit sich automatisch anpassenden, responsiven Spalten unter Verwendung nativer Markdown-Container." --- Grids bieten ein natives, Markdown-gesteuertes Layout-System in `docmd`. Anstatt manuelle HTML-Wrapper zu schreiben, können Sie den `grids`-Container nutzen, um Elemente nebeneinander zu strukturieren. Spalten passen ihre Breite automatisch an, um den verfügbaren Platz auszufüllen, und stapeln sich auf kleineren Bildschirmen (Mobilgeräten) logisch zu vertikalen Reihen. ## Syntax-Referenz ```markdown ::: grids ::: grid #### Komponente A Inhalt für die linke Seite. ::: ::: grid #### Komponente B Inhalt für die rechte Seite. ::: ::: ``` ## Praktische Implementierungsbeispiele ### 1. Präsentation von Funktionen nebeneinander Verwenden Sie Grids, um wichtige Funktionen nebeneinander hervorzuheben, indem Sie beispielsweise strukturelle Cards mit Informationsblöcken kombinieren. ```markdown ::: grids ::: grid ::: card "Geschwindigkeit :rocket:" Basiert auf einer nicht-blockierenden I/O-Pipeline für maximale Performance. ::: ::: ::: grid ::: card "Skalierbarkeit :zap:" Entwickelt für massive Monorepos und umfangreiche Projektstrukturen. ::: ::: ::: ``` ::: grids ::: grid ::: card "Geschwindigkeit :rocket:" Basiert auf einer nicht-blockierenden I/O-Pipeline für maximale Performance. ::: ::: ::: grid ::: card "Skalierbarkeit :zap:" Entwickelt für massive Monorepos und umfangreiche Projektstrukturen. ::: ::: ::: ### 2. Layout-Balancierung Grids berechnen automatisch die optimale Breite pro Spalte (bis zu 4 Elemente pro Reihe auf Ultra-Wide-Bildschirmen) basierend auf dem verfügbaren Inhalt und gruppieren Reihen nahtlos auf schmalen Viewports. ::: callout tip "Semantische Layouts" Die Verwendung des `grids`-Containers sorgt dafür, dass Ihre Dokumentationsstruktur rein in Markdown verfasst bleibt, was zu saubereren Quelldateien führt und sicherstellt, dass LLMs Ihre strukturellen Beziehungen fehlerfrei interpretieren! ::: --- ## [Hero-Abschnitte](https://docs.docmd.io/de/content/containers/hero/) --- title: "Hero-Abschnitte" description: "Erstellen Sie wirkungsvolle Landingpage-Header und Marketing-Highlights rein in Markdown." --- Der `hero`-Container erstellt professionelle, visuell beeindruckende Landingpage-Header. Er übernimmt komplexe CSS-Anforderungen wie **Split-Layouts**, **Glow-Effekte** und **Slider**, während die Bearbeitungserfahrung einfach bleibt. ## Basissyntax Standardmäßig zentriert der `hero`-Container seinen Inhalt, was ihn ideal für Banner und einfache Schlagzeilen macht. ```markdown ::: hero # Schneller entwickeln. Vom Markdown zur Produktions-Doku mit einem Befehl. ::: button "Erste Schritte" /intro color:blue ::: ``` ## Fortgeschrittene Layouts Der `hero`-Container unterstützt spezielle Flags zur Steuerung seines strukturellen Verhaltens. | Flag | Effekt | | :--- | :--- | | `layout:split` | Teilt den Hero in einen Textbereich (links) und einen Medienbereich (rechts). Stapelt sich auf Mobilgeräten vertikal. | | `layout:slider` | Verwandelt den Hero in einen horizontalen Slider mit Scroll-Snap-Verhalten. | | `glow:true` | Fügt ein subtiles, radiales Verlaufsleuchten im Hintergrund ein. | ### Das Split-Layout (`== side`) Verwenden Sie das Trennzeichen `== side`, um zu definieren, welche Inhalte in den primären Textbereich und welche in den sekundären "Seiten"-Bereich (normalerweise ein Bild oder ein Video-Embed) fließen. ```markdown ::: hero layout:split glow:true # docmd 2.0 Isomorphe Ausführung. KI-optimiert. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 Isomorphe Ausführung. KI-optimiert. ::: button "Quickstart" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### Das Slider-Layout (`== slide`) Erstellen Sie einen interaktiven Hero-Slider, indem Sie das Trennzeichen `== slide` zwischen verschiedenen Inhaltsknoten verwenden. ```markdown ::: hero layout:slider == slide # Isomorpher Core Die Engine rendert überall. == slide # KI-Optimierung Gebaut für das LLM-Zeitalter. ::: ``` ::: hero layout:slider == slide # Isomorpher Core Die Engine rendert überall. == slide # KI-Optimierung Gebaut für das LLM-Zeitalter. ::: ## Responsives Verhalten Der `hero`-Container ist standardmäßig voll responsiv: - Auf dem **Desktop** wird `layout:split` nebeneinander angezeigt. - Auf **Mobilgeräten** wechselt er automatisch zu einem zentrierten, vertikalen Stapel, um eine optimale Lesbarkeit zu gewährleisten. ## Best Practices 1. **Glow-Effekte**: Verwenden Sie `glow:true` sparsam auf Websites im Dark Mode für ein hochwertiges "Neon"-Gefühl. 2. **Medientypen**: Der "Seiten"-Inhalt eines Split-Layouts eignet sich perfekt für die `::: embed`-Komponente, hochwertige PNGs oder rohe `<video>`-Tags. 3. **CTA-Platzierung**: Platzieren Sie `::: button`-Elemente immer im primären "Hero Copy"-Bereich (vor dem `== side`-Trennzeichen), um sicherzustellen, dass sie das Erste sind, was Benutzer auf Mobilgeräten sehen. --- ## [Benutzerdefinierte interaktive Container](https://docs.docmd.io/de/content/containers/) --- title: "Benutzerdefinierte interaktive Container" description: "Ein umfassendes Verzeichnis der in docmd verfügbaren interaktiven UI-Bausteine." --- Standard-Markdown eignet sich hervorragend für die grundlegende Textformatierung, aber eine professionelle technische Dokumentation erfordert reichhaltige strukturelle Komponenten, um komplexe Logik effektiv zu vermitteln. `docmd` erweitert Markdown um eine Reihe von **isomorphen Containern**, die in responsive, hochpräzise UI-Elemente gerendert werden. ::: callout tip "Migration von anderen Dokumentations-Engines?" `docmd` unterstützt Syntax-Aliase von **VitePress** und **Docusaurus** direkt. Container wie `:::tip`, `:::warning`, `:::note`, `:::details` und `:::caution` funktionieren ohne Änderung. Die leerzeichenlose Syntax (z. B. `:::tabs` statt `::: tabs`) wird ebenfalls für alle Container unterstützt. ::: ## Block-Syntax-Referenz Alle Container nutzen eine konsistente Block-Syntax, die eine vorhersehbare Bearbeitungserfahrung im gesamten Projekt gewährleistet. ```markdown ::: typ "Optionaler Titel für die Kopfzeile" Dies ist der primäre Inhaltsbereich. Er unterstützt **Markdown**, Bilder und tiefe Verschachtelung von Komponenten. ::: ``` | Komponente | Schlüsselwort | Primärer Anwendungsfall | | :--- | :--- | :--- | | **[Callouts](callouts.md)** | `callout` | Semantische Hervorhebungen für Tipps, Warnungen und Alarme. | | **[Cards](cards.md)** | `card` | Gerahmte strukturelle Blöcke für Feature-Grids und Layout-Steuerung. | | **[Grids](grids.md)** | `grids` | Sich automatisch anpassende, mehrspaltige Strukturgruppen. | | **[Tabs](tabs.md)** | `tabs` | Interaktive, umschaltbare Fenster für alternative Anweisungen. | | **[Steps](steps.md)** | `steps` | Visuelle, nummerierte Zeitachsen für "How-to"-Anleitungen und Tutorials. | | **[Collapsibles](collapsible.md)** | `collapsible` | Interaktive Akkordeon-Umschalter für FAQs und vertiefende technische Daten. | | **[Buttons](buttons.md)** | `button` | Selbstschließende, prominente Call-to-Action-Navigationslinks. | | **[Tags](tags.md)** | `tag` | Selbstschließende, farbige Labels für Versionen, Status oder Hervorhebungen. | | **[Hero](hero.md)** | `hero` | Wirkungsvolle Landingpage-Abschnitte mit Layout- und Slider-Unterstützung. | | **[URL-Einbettungen](embed.md)** | `embed` | Sichere Einbettungen mit minimaler Ladezeit für Videos, Social Media und interaktive Inhalte. | | **[Changelogs](changelogs.md)** | `changelog` | Strukturierte, zeitachsenbasierte Versionshistorie und Versionshinweise. | | **[Verschachtelte Container](nested-containers.md)** | - | Rekursive Kompositionsmuster für komplexe Layouts aus mehreren Komponenten. | ## Die strategische Bedeutung von Containern Container bieten mehr als nur optischen Glanz; sie liefern hochpräzise **semantische Signale** an die `docmd`-Engine und nachgeschaltete KI-Agenten: 1. **KI-Kontext-Mapping**: Das Markieren eines Blocks als `callout warning` signalisiert LLMs explizit, diese Informationen während der Denk- und Generierungsphasen zu priorisieren. 2. **Strukturelle Integrität**: Die Kombination von `cards` mit Standard-CSS ermöglicht die Erstellung anspruchsvoller Landingpages, ohne die Markdown-Umgebung zu verlassen. 3. **Wartbarkeit des Quellcodes**: Eliminiert "HTML-Aufblähung" in Ihrem Dokumentationsquellcode und hält Ihre `.md`-Dateien sauber und maschinenlesbar. ## Rekursive Komposition `docmd` unterstützt **unendliche Verschachtelungstiefe**. Sie können jeden Container in einem anderen kombinieren, um komplexe, interaktive Dokumentationsknoten rein in Markdown zu erstellen. ```markdown ::: card "Architektur-Übersicht" ::: callout info Dieses Modul nutzt eine asynchrone I/O-Pipeline. ::: ::: button "Tiefes Eintauchen in den Core" /advanced/developer-guide ::: ``` [Meistern Sie die Verschachtelungs-Anleitung](nested-containers.md) --- ## [Verschachtelte Container](https://docs.docmd.io/de/content/containers/nested-containers/) --- title: "Verschachtelte Container" description: "Nutzen Sie den rekursiven Parser von docmd, um Karten, Tabs und Callouts in hochwertige Seitenlayouts zu kombinieren." --- Eine der leistungsfähigsten technischen Fähigkeiten von `docmd` ist seine **rekursive Parsing-Engine**. Sie können Komponenten unendlich ineinander verschachteln, um komplexe, interaktive Dokumentationsblöcke zu erzeugen, die andernfalls tiefgreifende HTML-Kenntnisse oder benutzerdefinierte Vorlagen erfordern würden. ## Die architektonische Regel Obwohl die Verschachtelung mathematisch gesehen unendlich ist, sollten Sie sich immer an die **Regel für selbstschließende Komponenten** halten: ::: callout warning "Selbstschließende Buttons" Da die `::: button`-Komponente selbstschließend ist (einzeilig), fügen Sie niemals eine abschließende `:::`-Zeile dahinter ein. Dies würde versehentlich den **übergeordneten Container** schließen, in dem sich der Button befindet, was zu einem fehlerhaften Layout führt. ::: ## Beispiele für technische Komposition ### 1. Interaktiver Ressourcenblock Kombinieren Sie eine **Karte (Card)** für den strukturellen Rahmen, **Tabs** für umgebungsspezifische Anweisungen und **Callouts** zur Hervorhebung kritischer Informationen. ````markdown ::: card "Monorepo Schnellstart" Wählen Sie Ihren bevorzugten Initialisierungspfad: ::: tabs == tab "Automatisiert" ```bash pnpm onboard ``` ::: callout success Dieses Skript übernimmt alle Paketinstallationen und Build-Aufgaben automatisch. ::: == tab "Manuell" Holen und verknüpfen Sie die Core-Engine manuell. ::: button "Zum Entwickler-Leitfaden" /advanced/developer-guide ::: ::: ```` ### 2. Multi-Plattform-Tutorials Das Verschachteln von **Tabs** innerhalb von **Schritten (Steps)** ist ein professionelles Muster, um plattformspezifische Anweisungen innerhalb einer Standard-Tutorial-Sequenz bereitzustellen. ```markdown ::: steps 1. **Umgebung einrichten** Konfigurieren Sie Ihr lokales Betriebssystem. ::: tabs == tab "macOS" Stellen Sie sicher, dass Homebrew installiert und aktuell ist. == tab "Linux" Überprüfen Sie das Vorhandensein von `curl` und `bash`. ::: 2. **Kern-Verifizierung** Führen Sie den Versionscheck aus, um die Konnektivität zu bestätigen. ::: ``` ::: steps 1. **Umgebung einrichten** Konfigurieren Sie Ihr lokales Betriebssystem. ::: tabs == tab "macOS" Stellen Sie sicher, dass Homebrew installiert und aktuell ist. == tab "Linux" Überprüfen Sie das Vorhandensein von `curl` und `bash`. ::: 2. **Kern-Verifizierung** Führen Sie den Versionscheck aus, um die Konnektivität zu bestätigen. ::: ## Design-Einschränkungen Um sowohl die Performance als auch die mobile Responsivität zu wahren, beachten Sie die folgenden Einschränkungen: * **Rekursive Tabs**: Das Verschachteln von Tabs innerhalb anderer Tabs wird technisch unterstützt, ist jedoch ausdrücklich nicht empfohlen. Es erzeugt Navigations-"Schleifen", die auf kleineren Viewports optisch verwirrend sind. * **Sequenzieller Konflikt**: Wenn Sie nummerierte Schritte innerhalb eines Tabs benötigen, verwenden Sie eine standardmäßige geordnete Liste (`1. Schritt-Inhalt`) anstelle des `::: steps`-Containers, um Layout-Konflikte zu vermeiden. * **Lesbarkeit**: Obwohl `docmd` keine Einrückung für verschachtelte Blöcke zwingend vorschreibt, verbessert eine Einrückung von 2 oder 4 Leerzeichen die menschliche Lesbarkeit des Markdown-Quellcodes erheblich. ::: callout tip "Wissenssegmentierung für KI" Verschachtelungen bieten klare **semantische Grenzen**. Wenn ein KI-Agent den `llms-full.txt`-Stream analysiert, teilt ein in eine `card` eingebetteter `callout` dem Modell explizit mit, dass der Tipp auf das spezifische Thema dieser Karte bezogen ist. Dies verhindert Kontext-Leaks und verbessert die technische Genauigkeit in generierten Antworten. ::: --- ## [Schritte (Steps)](https://docs.docmd.io/de/content/containers/steps/) --- title: "Schritte (Steps)" description: "Verwandeln Sie standardmäßige geordnete Listen in visuell ansprechende Zeitachsen und Tutorials." --- Der Container `steps` wurde speziell für Anleitungen ("How-to") und technische Tutorials entwickelt. Er verwandelt eine standardmäßige geordnete Markdown-Liste in eine elegante, nummerierte vertikale Zeitachse mit automatischer Beabstandung und visueller Hervorhebung. ## Syntax Umschließen Sie jede standardmäßige geordnete Liste mit einem `::: steps`-Block. ```markdown ::: steps 1. **Projekt initialisieren** Führen Sie den Befehl `docmd init` aus, um Ihr Verzeichnis zu erstellen. 2. **Inhalte verfassen** Schreiben Sie Ihre Dokumentation in standardmäßigen Markdown-Dateien. 3. **Erstellen & Bereitstellen** Generieren Sie statische Assets mit `docmd build`. ::: ``` ## Detaillierte Implementierung Die `steps`-Komponente unterstützt reichhaltige Markdown-Inhalte innerhalb jedes Elements, einschließlich Code-Blöcken, Bildern und verschachtelten Containern. ```markdown ::: steps 1. **Produktions-Build generieren** Führen Sie den Build-Befehl aus, um eine hochoptimierte statische Website zu erstellen. ```bash docmd build ``` 2. **Asset-Integrität prüfen** Untersuchen Sie das Verzeichnis `site/`, um sicherzustellen, dass alle Assets korrekt kompiliert wurden. 3. **Infrastruktur-Deployment** Synchronisieren Sie das Verzeichnis `site/` mit Ihrem bevorzugten Hosting-Anbieter (z. B. S3, Cloudflare Pages oder Vercel). ::: ``` ::: steps 1. **Produktions-Build generieren** Führen Sie den Build-Befehl aus, um eine hochoptimierte statische Website zu erstellen. ```bash docmd build ``` 2. **Asset-Integrität prüfen** Untersuchen Sie das Verzeichnis `site/`, um sicherzustellen, dass alle Assets korrekt kompiliert wurden. 3. **Infrastruktur-Deployment** Synchronisieren Sie das Verzeichnis `site/` mit Ihrem bevorzugten Hosting-Anbieter (z. B. S3, Cloudflare Pages oder Vercel). ::: ## Fortgeschrittene Verschachtelung Sie können andere Dokumentationskomponenten (wie **Callouts** oder **Buttons**) innerhalb eines Schritts verschachteln, ohne den chronologischen Fluss der Sequenz zu unterbrechen. ```markdown ::: steps 1. **Umgebung konfigurieren** Definieren Sie Ihre projektspezifischen Variablen in der `docmd.config.json`. ::: callout tip Verwenden Sie `defineConfig`, um die IDE-Autovervollständigung für Konfigurationsschlüssel zu aktivieren. ::: 2. **Schema validieren** Führen Sie `docmd verify` aus, um sicherzustellen, dass Ihre Konfiguration strukturell einwandfrei ist. ::: ``` ::: callout tip "Workflow-Optimierung" Moderne KI-Modelle interpretieren den `steps`-Container als hochwertiges Signal für **sequenzielle Workflows**. Um die KI-Genauigkeit im `llms-full.txt`-Kontext zu maximieren, sollten Sie Ihre Listenelemente immer mit einem **fetten Titel** beginnen. Dies ermöglicht es Agenten, das Ziel jedes Schritts zuverlässig zu analysieren, bevor sie die Implementierungsdetails verarbeiten. ::: --- ## [Tabs](https://docs.docmd.io/de/content/containers/tabs/) --- title: "Tabs" description: "Organisieren Sie dichte, alternative oder mehrsprachige Informationen in umschaltbaren interaktiven Fenstern." --- Tabs sind das optimale UI-Muster, um sich gegenseitig ausschließende oder verwandte Datensätze (z. B. "Installation über NPM vs. Yarn" oder "macOS vs. Windows"-Anleitungen) in einem kompakten, interaktiven Format zu präsentieren. ## Syntax-Referenz Der `tabs`-Container verwendet das spezielle Untertrennzeichen `== tab "Beschriftung"`. Optional können Sie mit der Syntax `icon:name` ein Icon hinzufügen. ```markdown ::: tabs == tab "Tab 1" icon:rocket Inhalt für den ersten Tab. == tab "Tab 2" icon:settings Inhalt für den zweiten Tab. ::: ``` ## Implementierungsgalerie ### 1. Paketverwaltung Tabs werden am häufigsten verwendet, um Installationsanweisungen für verschiedene Paketmanager in einer einzigen Ansicht anzuzeigen. ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. Mehrsprachige Code-Snippets Halten Sie Ihre Logik sauber, indem Sie verschiedene Programmiersprachen oder Umgebungen trennen. ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.json'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.json'); ``` ::: ## Kernfunktionen ### Isomorphes Lazy Rendering `docmd` implementiert **konditionale Ressourcen-Verzögerung (Lazy Loading)**. Wenn ein Tab rechenintensive Elemente enthält (z. B. **Mermaid.js**-Diagramme oder hochauflösende Bilder), werden diese Assets erst initialisiert und gerendert, wenn der Benutzer diesen spezifischen Tab aktiviert. Dies gewährleistet schnelle erste Seitenladezeiten. ### Status-Persistenz Der Standard-SPA-Router verfolgt den Index des aktiven Tabs über ähnliche Dokumentationsseiten hinweg. Wenn ein Benutzer auf einer Seite "pnpm" auswählt und zu einer anderen Seite mit einer passenden Tab-Struktur navigiert, bleibt der "pnpm"-Tab automatisch aktiv. ## Technische Einschränkungen | Einschränkung | Hinweis | | :--- | :--- | | **Verschachtelungstiefe** | Um die Layout-Integrität zu bewahren, können Tabs nicht in anderen Tab-Komponenten verschachtelt werden. | | **Interaktiver Konflikt**| Konfliktträchtige Syntax: Um Steps in einem Tab zu verschachteln, verwenden Sie eine standardmäßige geordnete Liste (`1. Schritt eins`) anstelle des `::: steps`-Containers. | | **Responsives Limit** | Es wird empfohlen, die Anzahl der Tabs auf 6 pro Block zu begrenzen, um die Kompatibilität mit Mobilgeräten zu gewährleisten. | ::: callout tip "AI Context Mapping" Wenn Sie Tabs für Code-Snippets verwenden, geben Sie die Zielsprache immer direkt im Tab-Label an (z. B. `== tab "TypeScript"`). Dies ermöglicht es LLMs, den technisch relevanten Abschnitt im `llms-full.txt`-Kontextstream sofort zu identifizieren und zu extrahieren. ::: --- ## [Tags](https://docs.docmd.io/de/content/containers/tags/) --- title: "Tags" description: "Verwenden Sie den Tag-Container, um Versionen oder Status zu kennzeichnen oder kurze Textausschnitte nahtlos im Fließtext hervorzuheben." --- Der `tag`-Container ist eine selbstschließende Komponente, mit der kleine, pillenförmige Badges direkt in Ihren Text eingefügt werden können. Im Gegensatz zu Block-Containern erben Tags keine massiven Größen von übergeordneten Elementen wie Überschriften; sie behalten ihre kompakten, sauberen Proportionen bei, egal wo sie platziert werden. ## Grundlegende Verwendung Um einen einfachen Tag zu erstellen, geben Sie einfach den Text an, den Sie anzeigen möchten: ::: tabs == tab "Vorschau" Diese Funktion wurde in ::: tag "v0.7.4" color:blue hinzugefügt und funktioniert perfekt. == tab "Markdown-Quelle" ```markdown Diese Funktion wurde in ::: tag "v0.7.4" hinzugefügt und funktioniert perfekt. ``` ::: ## Farben anpassen Sie können das Standard-Tag-Styling überschreiben, indem Sie einen beliebigen gültigen CSS-Farbstring (z. B. `#ff0000`, `blue` oder `hsl(...)`) über das Attribut `color:` angeben. `docmd` berechnet automatisch einen schönen getönten Hintergrund mit perfekt kontrastiertem Text und Rahmen! ::: tabs == tab "Vorschau" ::: tag "Veraltet" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stabil" color:#22c55e == tab "Markdown-Quelle" ````markdown ::: tag "Veraltet" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "Stabil" color:#22c55e ```` ::: ## Icons hinzufügen Genau wie bei Buttons und Callouts können Sie ganz einfach ein Icon aus der `docmd`-Icon-Bibliothek über das Attribut `icon:` hinzufügen. ::: tabs == tab "Vorschau" ::: tag "Verifiziert" icon:check-circle color:#10b981 == tab "Markdown-Quelle" ````markdown ::: tag "Verifiziert" icon:check-circle color:#10b981 ```` ::: ## Tags verlinken Wenn Ihr Tag als Hyperlink fungieren soll (z. B. um einen Versions-Tag direkt mit seinen Versionshinweisen zu verknüpfen), können Sie das Attribut `link:` verwenden. Externe Links werden automatisch erkannt und in einem neuen Tab geöffnet. ::: tabs == tab "Vorschau" Sehen Sie sich die neuesten ::: tag "Versionshinweise" icon:external-link link:/release-notes/0-7-4 an. == tab "Markdown-Quelle" ````markdown Sehen Sie sich die neuesten ::: tag "Versionshinweise" icon:external-link link:/release-notes/0-7-4 an. ```` ::: ## Tags in Überschriften verwenden Da Tags echte Inline-Elemente sind, sehen sie hervorragend aus, wenn sie zur Kennzeichnung von Hauptüberschriften verwendet werden. Sie richten sich automatisch an der Grundlinie aus, ohne die massive Schriftgröße der Überschrift zu erben. ::: tabs == tab "Vorschau" # Suchfilterung ::: tag "Neu" color:#8b5cf6 == tab "Markdown-Quelle" ````bash # Suchfilterung ::: tag "Neu" color:#8b5cf6 ```` ::: --- ## [Frontmatter-Referenz](https://docs.docmd.io/de/content/frontmatter/) --- title: "Frontmatter-Referenz" description: "Der vollständige Leitfaden zu Metadaten und Konfiguration auf Seitenebene in docmd." --- Frontmatter ermöglicht es Ihnen, globale Einstellungen auf einer pro-Seite-Basis zu überschreiben. Es muss im YAML-Format ganz oben in Ihrer Markdown-Datei stehen. ## Kern-Metadaten | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `title` | `String` | **Erforderlich.** Legt den HTML-`<title>` und die Hauptüberschrift des Abschnitts fest. | | `description` | `String` | Legt die Meta-Beschreibung für SEO und Suchergebnisse fest. | | `keywords` | `Array` | Eine Liste von Schlüsselwörtern für den `<meta name="keywords">`-Tag. | ::: callout warning "Der Titel ist wichtig" Obwohl nicht strikt erforderlich, wird das Feld `title` dringend empfohlen. Ohne diesen greift docmd auf die erste `# H1`-Überschrift oder den Dateinamen zurück - was zu weniger idealen `<title>`-Tags und Suchergebnissen führen kann. ::: ## Sichtbarkeit & Indexierung | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `noindex` | `Boolean` | Schließt die Seite aus dem internen Suchindex aus. | | `llms` | `Boolean` | Auf `false` setzen, um diese Seite aus den KI-Kontextdateien (`llms.txt`) auszuschließen. | | `hideTitle` | `Boolean` | Blendet den Titel im fixierten Header aus (nützlich bei Verwendung einer benutzerdefinierten H1). | | `bodyClass` | `String` | Fügt dem `<body>`-Tag dieser Seite eine benutzerdefinierte CSS-Klasse hinzu. | ## Layout-Steuerung | Schlüssel | Typ | Beschreibung | | :--- | :--- | :--- | | `layout` | `String` | Auf `full` setzen, um die volle Inhaltsbreite zu nutzen und die Inhaltsverzeichnis-Sidebar (TOC) auszublenden. | | `toc` | `Boolean` | Auf `false` setzen, um das Inhaltsverzeichnis vollständig zu deaktivieren. | | `noStyle` | `Boolean` | Deaktiviert die gesamte `docmd`-Benutzeroberfläche (Sidebar, Header, Footer) für benutzerdefinierte Seiten. | | `titleAppend` | `Boolean` | Auf `false` setzen, um zu verhindern, dass der Seitentitel an den HTML-`<title>`, OpenGraph (`og:title`) und Twitter-Metadaten-Tags angehängt wird. Standard: `true`. | ### `noStyle`-Komponentensteuerung Wenn `noStyle: true` aktiv ist, müssen Sie sich explizit für die Komponenten entscheiden, die Sie beibehalten möchten: ```yaml --- noStyle: true components: meta: true # Fügt SEO-Metadaten ein favicon: true # Fügt das Website-Favicon ein css: true # Fügt docmd-main.css ein theme: true # Fügt Theme-spezifisches Styling ein highlight: true # Fügt Syntax-Highlighting ein scripts: true # Fügt die SPA-Router-Logik ein sidebar: true # Fügt die Navigations-Sidebar ein footer: true # Fügt den Website-Footer ein --- ``` ## Plugin-Überschreibungen ### SEO (`seo`) * `image`: Benutzerdefinierte URL für das Vorschaubild in sozialen Medien für diese Seite. * `aiBots`: Auf `false` setzen, um speziell KI-Crawler von dieser Seite zu blockieren. * `canonicalUrl`: Legt einen benutzerdefinierten kanonischen Link für SEO fest. --- ## [Live-Vorschau](https://docs.docmd.io/de/content/live-preview/) --- title: "Live-Vorschau" description: "Führen Sie die Engine mithilfe der Live-Architektur vollständig im Browser ohne Backend-Server aus." --- Der Compiler verfügt über eine modulare Architektur, die Dateisystemoperationen von der Kernlogik trennt. Dies ermöglicht es der Engine, vollständig im Browser zu laufen, und erleichtert Live-Editoren sowie CMS-Vorschauen ohne ein Node.js-Backend. <img width="720" class="with-border" src="/assets/previews/live-editor-preview.webp"> ::: button "Live-Editor öffnen" external:https://live.docmd.io ## Der Live-Editor Der integrierte Live-Editor bietet eine leistungsstarke Split-Pane-Oberfläche. Schreiben Sie Ihr Markdown im linken Bereich und sehen Sie in Echtzeit, wie die gerenderte Ausgabe im rechten Bereich synchronisiert und aktualisiert wird. ### Lokale Ausführung Starten Sie den Live-Editor lokal in Ihrem Projekt: ```bash npx @docmd/core live ``` ### Statische Bereitstellung Generieren Sie eine eigenständige, statische Version des Editors, die Sie auf Plattformen wie Vercel oder GitHub Pages hosten können: ```bash npx @docmd/core live --build-only ``` Dies erzeugt ein `dist/`-Verzeichnis mit der Einstiegsdatei `index.html` und der gebündelten `docmd-live.js`-Engine. ## Einbetten von @docmd/core Integrieren Sie das browserkompatible Bundle in Ihre eigenen Anwendungen, um interne Markdown-Rendering- oder Vorschaufähigkeiten bereitzustellen. ### 1. Ressourcen-Integration Binden Sie die erforderlichen CSS- und JavaScript-Bundles aus Ihren Assets oder einem CDN ein: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. Isomorphe API Das globale `docmd`-Objekt stellt die `compile`-Methode für sofortiges Rendering bereit. ```javascript const html = await docmd.compile(markdown, { "title": "Dynamische Vorschau", "theme": { "appearance": "dark" } }); document.getElementById("preview-frame").srcdoc = html; ``` ::: callout tip "KI-Feedback-Schleifen" icon:sparkles Die Live-Architektur ist ideal für den Aufbau von **KI-Agenten-Sandboxes**. Leiten Sie die vorgeschlagenen Änderungen eines Agenten in einen Live-Kompilierungspuffer. Überprüfen Sie KI-Vorschläge visuell, bevor Sie die Änderungen in Ihr Repository übernehmen. ::: --- ## [docmd : Individuelle No-Style Page Demo](https://docs.docmd.io/de/content/no-style-example/) --- title: "docmd : Individuelle No-Style Page Demo" description: "Eine funktionale Demonstration der noStyle-Architekturfunktion." noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: center; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-color); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>Individuelle Seitenarchitektur</h1> <p>Demonstration der absoluten Layout-Kontrolle durch <code>noStyle: true</code>.</p> </div> <div class="demo-card"> <h2>Logisches Fundament</h2> <p> Diese Demonstration nutzt die Frontmatter-Direktive <code>noStyle: true</code>, um das globale Dokumentationslayout (Seitenleiste, Header und TOC) zu umgehen. Dies bietet eine "Zero-Friction"-Leinwand für die Erstellung von Marketing-Landingpages oder benutzerdefinierten Produkt-Dashboards. </p> <h3>Aktivierte Systemkomponenten</h3> <p>Im No-Style-Modus entscheiden Sie sich explizit für die Kernfunktionen der Dokumentations-Engine:</p> <ul> <li><strong>SEO-Meta-Engine</strong>: Strukturierte Tags und Social-Graph-Daten bleiben erhalten.</li> <li><strong>Projekt-Branding</strong>: Die globale Favicon-Injektion bleibt aktiv.</li> <li><strong>Grundlegende Typografie</strong>: Das verarbeitete <code>docmd-main.css</code> liefert das Basis-Styling.</li> <li><strong>Theme-Synchronisation</strong>: Der Status des Hell-/Dunkelmodus bleibt vollständig erhalten.</li> <li><strong>Interaktive Funktionen</strong>: Der SPA-Router und die Komponentenlogik bleiben verfügbar.</li> </ul> <h3>Technische Umsetzung</h3> <p> Das Layout für diese Seite wurde mit Standard-HTML-Wrappern und gescoptem CSS erstellt, das im Frontmatter-Feld <code>customHead</code> definiert ist. Dies stellt sicher, dass kein CSS auf den Rest der Dokumentationsseite abfärbt. </p> <a href="../content/no-style-pages.md" class="demo-button">Analyse des Implementierungs-Leitfadens →</a> </div> </div> --- ## [Seiten ohne Stil (No-Style Pages)](https://docs.docmd.io/de/content/no-style-pages/) --- title: "Seiten ohne Stil (No-Style Pages)" description: "Erstellen Sie benutzerdefinierte Landingpages und einzigartige Layouts, indem Sie das Standard-Theme von docmd deaktivieren." --- `docmd` ermöglicht es Ihnen, das Standard-Dokumentationslayout (Seitenleiste, Header und Footer) auf einer pro-Seite-Basis zu umgehen. Dies ist ideal für die Erstellung von Produkt-Landingpages, benutzerdefinierten Dashboards oder Marketing-Splash-Screens, während der Zugriff auf die Komponenten der Dokumentations-Engine erhalten bleibt. ## Aktivierung des No-Style-Modus Um die globale Benutzeroberfläche zu deaktivieren, fügen Sie `noStyle: true` zum Frontmatter der Seite hinzu. ```yaml --- title: "Produkt-Showcase" noStyle: true components: meta: true # SEO- und OpenGraph-Tags beibehalten favicon: true # Website-Favicon beibehalten css: true # docmd-main.css für Typografie einfügen --- <!-- Reines HTML oder spezielles Markdown folgt hier --> <div class="hero"> <h1>Dokumentation der nächsten Generation</h1> <p>Zero-config. Isomorph. KI-bereit.</p> </div> ::: callout info "Unterstützung für unbegrenzte Verschachtelung" Auch bei `noStyle: true` werden alle Standard-`docmd`-Container wie `::: card`, `::: tabs` und `::: hero` vollständig unterstützt und können in jeder Tiefe verschachtelt werden. ::: ``` ## Komponenten-Auswahl (Opt-In) Wenn `noStyle` aktiv ist, beginnen Sie mit einer leeren Leinwand. Aktivieren Sie die Kernkomponenten des Systems gezielt nach Bedarf: | Komponente | Beschreibung | | :--- | :--- | | `meta` | Fügt `<title>`, SEO-Meta-Tags und strukturierte OpenGraph-Daten ein. | | `favicon` | Fügt das projektweite Favicon ein. | | `css` | Fügt `docmd-main.css` ein. Dringend empfohlen für grundlegendes Raster und Typografie. | | `menubar` | Fügt die obere Menüleiste der Website ein. | | `theme` | Fügt die CSS-Variablen und Design-Überschreibungen des aktiven Themes ein. | | `scripts` | Fügt die interaktive Komponentenlogik ein (erfordert `mainScripts: true`). | | `spa` | Aktiviert den Single-Page-Application-Router (erfordert `scripts: true`). | ## Komponierbare Landingpages Die Hauptstärke von `noStyle` liegt darin, dass Sie die gesamte Suite der `docmd`-Komponenten als hochwertige „Widgets“ auf einer leeren Leinwand verwenden können. Sie sind nicht auf reines HTML beschränkt; Sie können komplexe, strukturelle Designs rein in Markdown erstellen. ### Erstellung eines modernen Einstiegspunkts ```yaml --- title: "Willkommen" noStyle: true components: meta: true css: true menubar: true # Verwenden Sie die obere Navigation der Website scripts: true # Interaktive Komponenten aktivieren mainScripts: true --- ::: hero layout:split glow:true # Dokumentation, die begeistert. Die Zero-Config-Engine für moderne Entwicklerteams. ::: button "Erste Schritte" ../getting-started/quick-start.md color:blue ::: button "GitHub" github:docmd-io/docmd color:gray == side ::: embed [https://www.youtube.com/watch?v=dQw4w9WgXcQ] ::: ::: ::: grids ::: card "Zero Configuration" Schreiben Sie einfach Markdown. Keine komplexe React-Logik oder Build-Skripte. ::: ::: card "KI-optimiert" Strukturbewusstes Parsing für die Ära der LLMs. ::: ::: card "Schnell ohne Framework-Last" Statische Generierung mit isomorpher SPA-Navigation. ::: ::: ``` ::: callout tip "KI-generierte Layouts" Da `noStyle`-Seiten sowohl reines HTML als auch `docmd`-Container unterstützen, eignen sie sich perfekt für **KI-gesteuertes UI-Design**. Sie können einer KI den Befehl geben: *"Entwirf eine moderne Hero-Sektion mit Tailwind-ähnlichen Utility-Klassen und docmd-Buttons, gehüllt in einen noStyle: true-Container."* Die KI kann das Design innerhalb Ihrer statischen Website-Pipeline ohne zusätzliche Konfiguration iterieren. ::: ## String-Ersetzung (i18n für noStyle) Wenn Ihre Website für [i18n konfiguriert](../configuration/localisation/index.md) ist, erhalten gewöhnliche Dokumentationsseiten automatisch serverseitige Übersetzungen - jede Sprache hat ihre eigenen Markdown-Dateien in separaten Verzeichnissen. Aber noStyle-Seiten verwenden benutzerdefiniertes HTML statt Markdown, weshalb dieser Ansatz dort nicht greift. Stattdessen bietet docmd eine **String-Ersetzung** an - die Übersetzung Ihres HTML über `data-i18n`-Attribute und JSON-Übersetzungsdateien. ::: callout info "Warum dies nur für noStyle-Seiten funktioniert" Die String-Ersetzung findet Elemente mit `data-i18n`-Attributen im gerenderten HTML und tauscht deren Textinhalt aus. Standard-Markdown-Inhalte werden in einfache `<p>`, `<h2>`, `<li>` Tags gerendert - dort gibt es keine `data-i18n`-Attribute, die der Ersetzer findten könnte. Für die Übersetzung von in Markdown verfassten Dokumentationen verwenden Sie den [Verzeichnis-Modus](../configuration/localisation/translated-content.md) - separate Markdown-Dateien pro Sprache. ::: ### Wie es funktioniert Es gibt zwei Modi für die String-Ersetzung: - **Serverseitig (empfohlen)**: Mit [`stringMode: true`](../configuration/localisation/index.md#string-mode-nostyle-pages-only) in Ihrer i18n-Konfiguration löst docmd `data-i18n`-Attribute **zur Build-Zeit** auf und generiert vollständig übersetztes HTML in den Verzeichnissen `/{locale}/`. Jede Sprache erhält ihre eigene URL - vollständig indexierbar für Suchmaschinen. - **Clientseitig**: Das Skript `docmd-i18n-strings.js` lädt Übersetzungen zur Laufzeit via XHR. Dies wird auf noStyle-Seiten automatisch eingefügt, wenn i18n konfiguriert ist. Nützlich für den Austausch an Ort und Stelle ohne Neuladen der Seite (z. B. SPAs, Dashboards). Beide Modi verwenden dieselbe Syntax für `data-i18n`-Attribute und dasselbe JSON-Dateiformat. 1. Platzieren Sie JSON-Übersetzungsdateien in `assets/i18n/` - eine pro Sprache: ``` assets/ i18n/ en.json hi.json zh.json ``` 2. Jede JSON-Datei ist eine flache Schlüssel-Wert-Zuordnung: ```json { "hero.title": "Markdown → Produktions-Docs", "hero.subtitle": "Die Zero-Config-Dokumentations-Engine.", "nav.docs": "Dokumentation", "nav.editor": "Live-Editor", "cta.getStarted": "Erste Schritte", "cta.install": "npm i @docmd/core" } ``` 3. Verwenden Sie `data-i18n`-Attribute in Ihren HTML-Elementen: ```html <h1 data-i18n="hero.title">Markdown → Produktions-Docs</h1> <p data-i18n="hero.subtitle">Die Zero-Config-Dokumentations-Engine.</p> <a data-i18n="nav.docs" href="/docs">Dokumentation</a> ``` Der Text in der Standardsprache wird direkt in das HTML geschrieben (fungiert als Fallback). Wenn eine andere Sprache aktiv ist, lädt das Skript das entsprechende JSON und ersetzt den Text. ### Attribut-Übersetzung Um Elementattribute wie `placeholder`, `title` oder `aria-label` zu übersetzen, verwenden Sie `data-i18n-{attr}`: ```html <input data-i18n-placeholder="search.placeholder" placeholder="Suche..."> <button data-i18n-aria-label="nav.menuLabel" aria-label="Menü öffnen">☰</button> <a data-i18n-title="nav.tooltip" title="Zu den Docs">Docs</a> ``` ### HTML-Inhalt Für Schlüssel, die HTML-Markup enthalten, verwenden Sie `data-i18n-html` anstelle von `data-i18n`: ```html <p data-i18n-html="hero.desc">Statisches HTML für SEO. <br>SPA für Geschwindigkeit.</p> ``` ### Sprachwechsel Das Modul für i18n-Strings stellt eine globale API unter `window.DOCMD_I18N_STRINGS` bereit: ```js // Zu Hindi wechseln DOCMD_I18N_STRINGS.switchLocale('hi'); // Aktuelle Sprache abrufen console.log(DOCMD_I18N_STRINGS.locale); // 'en' // Alle konfigurierten Sprachen abrufen console.log(DOCMD_I18N_STRINGS.locales); // [{ id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }] ``` Mit dieser API können Sie einen benutzerdefinierten Sprachumschalter erstellen: ```html <select onchange="DOCMD_I18N_STRINGS.switchLocale(this.value)"> <option value="en">English</option> <option value="hi">हिन्दी</option> </select> ``` ### Ereignisse (Events) Hören Sie auf das Ereignis `docmd:i18n-applied`, um benutzerdefinierte Logik auszuführen, nachdem die Strings angewendet wurden: ```js document.addEventListener('docmd:i18n-applied', function(e) { console.log('Sprache:', e.detail.locale); console.log('Strings:', e.detail.strings); }); ``` ::: callout info "Automatische Erkennung" Das Skript erkennt die aktive Sprache anhand des URL-Pfad-Präfixes (z. B. `/hi/` → Hindi). Für die Standardsprache (gerendert unter `/`) prüft es den `localStorage` auf eine zuvor gespeicherte Präferenz. Die Funktion `switchLocale()` übernimmt die URL-Navigation automatisch. ::: ### In-Place-Modus (An Ort und Stelle) Für One-Page-Websites (wie Landingpages) möchten Sie beim Sprachwechsel nicht zu einer anderen URL navigieren. Setzen Sie `inPlace: true` in Ihrer i18n-Konfiguration, um Strings ohne URL-Weiterleitung auszutauschen: ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "zh", "label": "中文" } ], "inPlace": true } } ``` Mit `inPlace: true` lädt der Aufruf von `switchLocale()` das JSON für die neue Sprache neu und ersetzt alle `data-i18n`-Strings auf der aktuellen Seite - es findet keine Navigation statt. --- ## [Fortgeschrittene Markdown-Syntax](https://docs.docmd.io/de/content/syntax/advanced/) --- title: "Fortgeschrittene Markdown-Syntax" description: "Nutzen Sie den erweiterten Funktionsumfang von docmd: Benutzerdefinierte Attribute, GFM-Erweiterungen und semantische Definitionen." --- Über das Standard-Markdown hinaus unterstützt `docmd` mehrere hochwertige Erweiterungen, die von GitHub Flavored Markdown (GFM) und Plugins für benutzerdefinierte Attribute abgeleitet sind. Diese Werkzeuge bieten Ihnen die volle Kontrolle über die Struktur und das Styling Ihres Dokuments. ## GFM-Erweiterungen ### Aufgabenlisten (Task Lists) Erstellen Sie interaktive oder schreibgeschützte Checklisten für das Roadmap-Tracking. ```markdown - [x] Engine-Optimierung abgeschlossen - [ ] Plugin-API-Finalisierung ``` - [x] Engine-Optimierung abgeschlossen - [ ] Plugin-API-Finalisierung ### Automatische Link-Auflösung Standard-URLs und E-Mail-Adressen werden automatisch erkannt und verlinkt, ohne dass zusätzliches Markup erforderlich ist: `https://docmd.io` ### Shortcode-Emojis `docmd` unterstützt Standard-Shortcodes, um Ihrer Dokumentation eine visuelle Note zu verleihen. > Wir :heart: performante Dokumentationen! :rocket: :smile: ## Benutzerdefinierte Element-Attribute Weisen Sie Überschriften, Bildern und Links mit der Syntax in geschweiften Klammern `{}` eindeutige IDs und CSS-Klassen zu. Dies ist die primäre Methode, um [Benutzerdefinierte CSS-Styles](../../theming/custom-css-js.md) anzuwenden. ### Eindeutige semantische IDs Nützlich für Deep-Links direkt zu technischen Unterabschnitten. ```markdown ## Performance-Benchmarks {#benchmarks-2026} ``` ### Funktionale CSS-Klassen Wenden Sie Styling-Utilities auf spezifische Elemente an. ```markdown ## Zentrierter Abschnitt {.text-center .text-blue} ``` ### Aktions-Schaltflächen (Buttons) Verwandeln Sie jeden Standard-Markdown-Link in eine gestaltete Call-to-Action-Schaltfläche. ```markdown [Neuestes Release herunterladen](#download){.docmd-button} ``` ## Zitate & Definitionen ### Fußnoten-Referenzen Fügen Sie Zitate oder technische Vertiefungen[^1] hinzu, die automatisch gesammelt und am Ende der Seite gerendert werden. ```markdown Architekturentscheidungen sind im RFC dokumentiert[^1]. [^1]: RFC-42: Isomorphe Rendering-Pipeline. ``` ### Definitionslisten Perfekt für API-Parameterbeschreibungen und Glossare. ```markdown PropName : Der eindeutige Bezeichner für den Konfigurationsschlüssel. ``` PropName : Der eindeutige Bezeichner für den Konfigurationsschlüssel. ### Technische Abkürzungen Definieren Sie Abkürzungen global innerhalb einer Seite. Das Bewegen der Maus über den Begriff offenbart seine vollständige Definition. ```markdown *[SPA]: Single Page Application Der docmd-Router ermöglicht ein nahtloses SPA-Erlebnis. ``` *[SPA]: Single Page Application Der docmd-Router ermöglicht ein nahtloses SPA-Erlebnis. ::: callout tip "Kontextuelle Präzision für KI" Die Verwendung von **Definitionen** und **Abkürzungen** liefert KI-Agenten hochwertige technische Signale. Wenn eine KI Ihren `llms-full.txt`-Kontext verarbeitet, verhindern diese expliziten Definitionen lexikalische Doppeldeutigkeiten und stellen sicher, dass das Modell logisch korrekte Erklärungen für die spezifische Terminologie Ihres Projekts generiert. ::: --- ## [Code-Blöcke](https://docs.docmd.io/de/content/syntax/code/) --- title: "Code-Blöcke" description: "Dokumentieren Sie technische Implementierungen mit hochwertiger Syntax-Hervorhebung und interaktiven Kopierschaltflächen." --- `docmd` nutzt die extrem schnelle `lite-hl`-Engine, um eine automatische, kontextsensitive Syntax-Hervorhebung für hunderte von Programmiersprachen und Konfigurationsformaten bereitzustellen. ## Syntax-Hervorhebung Verfassen Sie Ihre technischen Beispiele mit standardmäßigen Markdown-Code-Zäunen (Fenced Code Blocks). Geben Sie immer die Sprachkennung an, um sicherzustellen, dass die Highlighting-Engine die korrekten lexikalischen Regeln anwendet. ````markdown ```javascript function initialize() { console.log("docmd engine active."); } ``` ```` **Gerendertes Ergebnis:** ```javascript function initialize() { console.log("docmd engine active."); } ``` ::: callout tip "Portabilität mit einem Klick" Wenn `copyCode: true` in Ihrer Konfiguration aktiviert ist (Standard), erscheint automatisch eine dezente Kopierschaltfläche in der oberen rechten Ecke jedes Code-Blocks beim Darüberfahren mit der Maus. So können Benutzer Ausschnitte sofort in ihre IDE übertragen. ::: ## Strategie für KI-Kontext Beachten Sie beim Dokumentieren von Code für die Nutzung durch LLMs und KI-Agenten diese technischen Best Practices: 1. **Strikte Sprachkennzeichnung**: Die explizite Kennzeichnung von Blöcken als `typescript`, `bash` oder `json` stellt sicher, dass der KI-Parser die Grammatik des Blocks innerhalb des `llms-full.txt`-Streams korrekt interpretiert. 2. **Eingebettete Intention**: Verwenden Sie Inline-Kommentare innerhalb Ihrer Code-Blöcke, um das *Warum* hinter komplexer Logik zu erklären. Dies liefert der KI kritischen Kontext für die Argumentation, der einfachem Text außerhalb des Blocks fehlen könnte. ## Referenz der Sprachunterstützung `docmd` bietet standardmäßige Unterstützung für die gängigsten technischen Ökosysteme, darunter: * **Logik**: `javascript`, `typescript`, `python`, `rust`, `go`, `ruby`, `csharp`. * **Web**: `html`, `css`, `markdown`. * **Daten & Shell**: `json`, `yaml`, `bash`, `powershell`, `dockerfile`. * **Dokumentation**: `mermaid`, `changelog`. --- ## [Bilder & visuelle Medien](https://docs.docmd.io/de/content/syntax/images/) --- title: "Bilder & visuelle Medien" description: "Meistern Sie das Medienmanagement: Responsive Bilder, Styling-Attribute und automatische Lightbox-Effekte." --- `docmd` nutzt die Standard-Markdown-Syntax für die Medienintegration. Wir empfehlen, Ihre Medien-Assets im Verzeichnis `assets/images/` innerhalb Ihres Projekt-Quellordners zu zentralisieren. ```markdown ![Technisches Diagramm](/assets/images/architecture.png "Optionaler Tooltip-Titel") ``` ## Referenz für technisches Styling Weisen Sie Ihren Bildern spezielle CSS-Klassen und Attribute direkt mit der Attributsyntax `{ .klasse }` zu. ### Dynamische Größenanpassung ```markdown ![Kleines Format](/assets/icon.png){ .size-small } ![Standardansicht](/assets/preview.png){ .size-medium } ![Großes Format](/assets/banner.png){ .size-large } ``` ### Ausrichtung & Layout ```markdown ![Zentrierter Fokus](/assets/img.png){ .align-center } ![Rechtsfließend](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![Beispiel für fortgeschrittenes Styling](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-center} ## Strukturierte Medienelemente ### Bildunterschriften (Figure Captions) Für präzise, barrierefreie Bildunterschriften verwenden Sie standardmäßige HTML5 `<figure>`-Elemente. ```html <figure> <img src="/assets/diagram.png" alt="Cloud-Infrastruktur-Diagramm"> <figcaption>Abbildung 1.1: Architektur der Kernsystem-Infrastruktur.</figcaption> </figure> ``` ### Bildergalerien Organisieren Sie mehrere Assets in einem responsiven, ausgewogenen Raster mit der Klasse `image-gallery`. ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="Benutzer-Dashboard-Ansicht"> <figcaption>Live-Leistungsmonitor</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="Konfigurationspanel-Ansicht"> <figcaption>Globale Projekteinstellungen</figcaption> </figure> </div> ``` ## Interaktiver Lightbox-Zoom Wenn die Komponente `mainScripts` aktiviert ist (Standard), wendet `docmd` automatisch einen Vollbild-Zoomeffekt auf jedes Bild an, das in einer Galerie enthalten ist oder mit der Klasse `.lightbox` markiert wurde. ```markdown ![Detaillierte Texturanalyse](/assets/sample.png){ .lightbox } ``` ::: callout tip "KI-Kontext & Barrierefreiheit" Geben Sie immer umfassende **Alt-Texte** für visuelle Medien an. Obwohl fortgeschrittene KI-Modelle über Sehfähigkeiten verfügen, liefert beschreibender Text innerhalb der Markdown-Quelle ein direktes, hochwertiges Signal für die Argumentationsebene des Modells - dies verbessert die Architekturanalyse und das Verständnis von Funktionen im `llms-full.txt`-Stream. ::: --- ## [Markdown-Syntax Grundlagen](https://docs.docmd.io/de/content/syntax/) --- title: "Markdown-Syntax Grundlagen" description: "Meistern Sie die grundlegenden Formatierungsregeln von docmd: Überschriften, typografische Stile und technische Blöcke." --- `docmd` hält sich an die Standard-Spezifikationen von **GitHub Flavored Markdown (GFM)**. Dieser Leitfaden legt die grundlegenden Standards für das Verfassen von Kerninhalten auf Ihrer Dokumentationsseite fest. ## Typografisches Styling | Attribut | Markdown-Syntax | Visuelles Ergebnis | | :--- | :--- | :--- | | **Hervorhebung** | `**Text**` | **Fette Begriffe** | | **Kursiv** | `*Text*` | *Stilisierte Variablen* | | **Durchgestrichen** | `~~Text~~` | ~~Veraltete Logik~~ | | **Inlined Code** | `` `code` `` | `engine.initialize()` | ## Strukturelle Elemente ### Semantische Überschriftenhierarchie ```markdown # Ebene 1 (Automatisch via Frontmatter) ## Ebene 2 (Hauptabschnitt) ### Ebene 3 (Detailfunktion) ``` ::: callout tip "Logische Integrität für KI" Fortschrittliche KI-Modelle und interne Suchmechanismen verlassen sich auf eine strikte Überschriftenhierarchie, um ein genaues mentales Modell Ihres Projekts aufzubauen. Indem Sie das „Überspringen von Überschriften“ vermeiden (z. B. den Sprung von H2 direkt zu H4), stellen Sie sicher, dass der `llms-full.txt`-Kontextstrom chronologisch und logisch fundiert bleibt. ::: ### Navigation & Referenz Verwenden Sie die Standard-Link-Syntax sowohl für interne Dokumentationsknoten als auch für globale Ressourcen. ```markdown [Globale Ressource](https://docmd.io) [Internes Modul](../api/node-api.md) ``` ### Aufzählung & Listen * **Ungeordnete Segmente**: Verwenden Sie `*` oder `-` für scanbare Aufzählungspunkte. * **Sequenzielle Logik**: Verwenden Sie `1.`, `2.` usw. für geordnete Anweisungen. (Für Tutorials sollten Sie den wirkungsvollen **[Schritte-Container (Steps)](../containers/steps)** in Betracht ziehen). ## Technische Blockelemente ### Blockquotes (Zitate) Die Standard-`>`-Syntax ist ideal zum Hervorheben von Zitaten oder Hintergrundkontext. > Die docmd-Engine definiert die Grenzen zwischen der Generierung statischer Websites und der Bereitstellung dynamischer Anwendungen neu. ### Datenschemata (Tabellen) | Attribut | Datentyp | Standard | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## Unterstützung für eingebettetes HTML Da `docmd` so konzipiert ist, dass das Parsen von Roh-HTML aktiviert ist, können Sie komplexe Layouts oder einzigartige Formatierungen für spezielle UI-Anforderungen direkt in Ihre Markdown-Dateien einfügen. ```html <div style="padding: 2rem; border: 1px solid var(--border-color); border-radius: 12px; text-align: center;"> Maßgeschneiderte UI-Elemente finden hier ihren Platz. </div> ``` --- ## [Verlinkung & Referenzierung](https://docs.docmd.io/de/content/syntax/linking/) --- title: "Verlinkung & Referenzierung" description: "Meistern Sie interne Querverweise, externe Ressourcen, das Verhalten beim Öffnen in neuen Tabs und die Referenzierung statischer Assets." --- `docmd` bietet ein zuverlässiges, Dateisystem-bewusstes Verlinkungssystem. Schreiben Sie Links zu Ihren Quell-`.md`-Dateien ganz natürlich in jedem beliebigen Format - die Engine normalisiert diese automatisch in saubere, SEO-optimierte URLs. ::: callout info "Natürlich schreiben, perfekt ausliefern" Sie müssen keine speziellen Verlinkungskonventionen befolgen. Schreiben Sie `overview.md`, `overview/` oder `overview` - die Build-Engine erzeugt in jedem Fall die exakt gleiche saubere URL mit abschließendem Schrägstrich. ::: ## URL-Normalisierung Während des Build-Prozesses normalisiert die Engine jeden internen Link automatisch. Dies gilt für Markdown-Texte, Button-Container, Tags und die Navigationskonfiguration. | Was Sie schreiben | Was gerendert wird | Warum | | :--- | :--- | :--- | | `overview.md` | `overview/` | `.md`-Erweiterung entfernt, abschließender Schrägstrich `/` hinzugefügt. | | `overview` | `overview/` | Abschließender Schrägstrich `/` wird automatisch hinzugefügt. | | `overview/` | `overview/` | Bereits korrekt. Keine Änderung. | | `api/commands.md` | `api/commands/` | Link im Unterverzeichnis normalisiert. | | `localisation/index.md` | `localisation/` | `index` entfernt - der Ordner ist die kanonische URL. | | `../index.md` | `../` | Parent-Verzeichnis-Index sauber aufgelöst. | | `overview.md#settings` | `overview/#settings` | Hash-Fragment bleibt erhalten. | | `https://example.com` | `https://example.com` | Externe Links bleiben unberührt. | ## Interne Links Verlinken Sie auf andere Seiten über relative Pfade zu den Quell-`.md`-Dateien. Die Engine löst diese unabhängig von der Verzeichnistiefe korrekt auf. | Ziel | Beispiel | | :--- | :--- | | **Geschwister-Seite** | `[Systemübersicht](overview.md)` | | **Unterverzeichnis-Seite** | `[API-Referenz](api/node-api.md)` | | **Unterverzeichnis-Index**| `[Lokalisierung](localisation/index.md)` | | **Eltern-Verzeichnis** | `[Zurück zur Startseite](../index.md)` | ## Abschnitts-Anker (Deep Linking) Navigieren Sie direkt zu einer bestimmten Überschrift mit Standard-URL-Hash-Fragmenten. ```markdown <!-- Anker auf derselben Seite --> [Zum Roadmap springen](#project-roadmap) <!-- Anker auf anderer Seite --> [CLI-Flags prüfen](../api/cli-commands.md#available-flags) ``` Hash-Fragmente bleiben bei der Normalisierung erhalten. Der obige seitenübergreifende Link wird in der Produktion als `../api/cli-commands/#available-flags` gerendert. ## In einem neuen Tab öffnen Setzen Sie das Präfix `external:` vor eine beliebige Link-URL, um das Öffnen in einem neuen Browser-Tab zu erzwingen. Dies funktioniert in Standard-Markdown-Links, Buttons und Tags. ```markdown [In neuem Tab öffnen](external:./configuration/overview.md) [GitHub](external:https://github.com/docmd-io/docmd) ``` Das Präfix `external:` wird aus der gerenderten URL entfernt. Standardmäßig werden alle Links im selben Fenster geöffnet. ## Verlinkung zu Rohdateien (Raw Files) Verwenden Sie das Präfix `raw:`, um die Normalisierung zu umgehen und direkt auf eine herunterladbare Datei zu verlinken. Die Erweiterung und der Pfad bleiben exakt so erhalten, wie sie geschrieben wurden. ```markdown [Quellcode anzeigen](raw:docs/readme.md) ``` ## Buttons & Tags Die Container `::: button` und `::: tag` unterstützen alle Standard-Verlinkungskonventionen, einschließlich der Präfixe `external:` und `raw:`: ```markdown ::: button "Erste Schritte" ./getting-started/quick-start.md icon:rocket ::: button "Auf GitHub anzeigen" external:https://github.com/docmd-io/docmd icon:github ::: button "Quelle herunterladen" raw:docs/readme.md icon:download ::: tag "v0.8.2" link:release-notes/0-8-2.md icon:tag color:#22c55e ::: tag "Extern öffnen" link:external:./configuration/overview.md icon:external-link ``` ## Navigationskonfiguration In `navigation.json` und `docmd.config.json` definierte Pfade werden zur Build-Zeit normalisiert. Schreiben Sie sie in einem beliebigen Format - alle drei Einträge unten erzeugen die identische kanonische URL. ```json "navigation.json" [ { "title": "Overview", "path": "configuration/overview" }, { "title": "Overview", "path": "configuration/overview.md" }, { "title": "Overview", "path": "configuration/overview/" } ] ``` Für Elemente, die in einem neuen Tab geöffnet werden sollen, setzen Sie das Flag `external`. ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "Index-Seiten in der Navigation" Wenn Sie auf die Index-Seite eines Verzeichnisses verlinken, verwenden Sie den Ordnerpfad, anstatt explizit auf `index.md` zu verweisen. Beides funktioniert identisch, aber der Ordnerpfad ist sauberer: ```markdown <!-- Bevorzugt --> [Lokalisierung](localisation/) <!-- Funktioniert auch --> [Lokalisierung](localisation/index.md) ``` ::: ## Protokolle & Externe Ressourcen Die Engine respektiert Standard-Browserprotokolle für externe Ressourcen und ändert diese Links niemals. * **HTTPS** - `[docmd Homepage](https://docmd.io)` - öffnet sich im selben Tab. * **Mail** - `[Support](mailto:help@docmd.io)` - öffnet den E-Mail-Client. * **Assets** - `[CLI-Binary herunterladen](/assets/bin/docmd-mac.zip)` - wird nicht normalisiert. ## Statische Assets Platzieren Sie herunterladbare Dateien im Verzeichnis `assets/` Ihres Projekts. Der Builder verschiebt diese Dateien ohne Pfadänderungen in das Produktions-Root. ```markdown [Dokumentations-PDF herunterladen](/assets/pdf/handbook.pdf) [Globale Konfiguration anzeigen](/assets/config/docmd.config.json) ``` ::: callout tip "Semantische Verknüpfung für KI" Verwenden Sie bei Querverweisen vorrangig **beschreibenden Ankertext** (z. B. `[PWA-Caching optimieren](../plugins/pwa.md)`) anstelle von generischen Labels (z. B. `[Mehr lesen](../plugins/pwa.md)`). Ausführliche Link-Labels bieten KI-Agenten eine hochpräzise Karte der semantischen Beziehungen im `llms.txt`-Stream. ::: --- ## [Mitwirken (Contributing)](https://docs.docmd.io/de/contributing/) --- title: "Mitwirken (Contributing)" description: "Richtlinien und Setup-Anweisungen für die Mitwirkung an docmd." --- Vielen Dank für Ihr Interesse an der Mitwirkung bei `docmd`. Wir freuen uns über Fehlerbehebungen, Verbesserungen der Dokumentation, neue Funktionen und Designvorschläge. ## Entwicklungsumgebung `docmd` ist ein Monorepo, das mit [pnpm](https://pnpm.io/) verwaltet wird. ### Voraussetzungen - **Node.js**: v22.x oder neuer (LTS empfohlen) - **pnpm**: v10.x oder neuer ### Projekt-Setup Klonen Sie das Repository und führen Sie das initiale Setup aus, um Abhängigkeiten zu installieren und das Monorepo zu bauen: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` Um den lokalen `docmd`-Befehl global zu verlinken (zum Testen in anderen Projekten): ```bash pnpm verify --link ``` ### Lokale Entwicklung Wir bieten einen Proxy-Befehl an, um beliebige `docmd`-Befehle in unserem internen `_playground`-Verzeichnis auszuführen: ```bash pnpm docmd dev # Startet den Playground-Dev-Server (auch: pnpm dev) pnpm docmd build # Baut die Playground-Dokumentation ``` Um interne Quelldateien (Engine, Templates, Plugins) mit Hot-Reload zu beobachten, setzen Sie die Umgebungsvariable `DOCMD_DEV`: ```bash DOCMD_DEV=true pnpm dev ``` ## Qualitätsstandards ### Linting Stellen Sie sicher, dass Ihr Code unserer ESLint-Konfiguration entspricht: ```bash pnpm lint --fix ``` ### Verifizierung Bevor Sie einen Pull Request einreichen, **MÜSSEN** Sie sicherstellen, dass das gesamte Monorepo unsere intensive Verifizierungs-Pipeline passiert: ```bash pnpm prep ``` *(Dies führt `pnpm reset`, Installation, Lint-Checks, E2E-Tests und einen Release-Dry-Run aus.)* ## GitHub-Workflow 1. **Fork und Branch**: Erstellen Sie einen Feature-Branch vom aktuellen `main`. 2. **Verifizierung**: Stellen Sie sicher, dass `pnpm prep` mit `🛡️ docmd is ready for production!` abschließt. 3. **Pull Request**: Eröffnen Sie einen PR mit einer klaren Beschreibung. ### Commit-Richtlinien Wir verwenden [Conventional Commits](https://www.conventionalcommits.org/): - `feat:` (Neue Funktionen) - `fix:` (Fehlerbehebungen) - `docs:` (Dokumentationsänderungen) - `refactor:` (Interne Refaktorierungen) --- ## [Caddy](https://docs.docmd.io/de/deployment/caddy/) --- title: "Caddy" description: "docmd mit einem produktionsreifen Caddyfile bereitstellen." --- [Caddy](https://caddyserver.com/) ist ein moderner Webserver, der HTTPS-Bereitstellung und Zertifikatserneuerungen automatisch verwaltet. ## Caddyfile generieren ```bash docmd deploy --caddy ``` Dies generiert ein `Caddyfile`, das auf Ihr Projekt zugeschnitten ist: - **Site-Adresse** wird auf den Hostnamen aus Ihrer `url`-Konfiguration gesetzt - Caddy stellt automatisch ein SSL-Zertifikat bereit. Fallback auf `:80`, wenn keine URL konfiguriert ist. - **Root-Verzeichnis** nutzt Ihr konfiguriertes `out`-Verzeichnis (nicht hartcodiert) - **SPA-Fallback** wird nur einbezogen, wenn `layout.spa` in Ihrer Konfiguration `true` ist Wenn Sie eine echte Domain als Site-Adresse verwenden (z.B. `docs.example.com` anstatt `:80`), stellt Caddy automatisch ein kostenloses SSL-Zertifikat über Let's Encrypt bereit - keinerlei HTTPS-Konfiguration nötig. ## Bereitstellungsschritte 1. Bauen Sie Ihre Website: `docmd build` 2. Übertragen Sie Ihren Ausgabe-Ordner und das generierte `Caddyfile` auf Ihren Server. 3. Führen Sie `caddy start` oder `caddy run` im Verzeichnis mit Ihrem Caddyfile aus. ### Neu generieren Site-URL oder Ausgabeverzeichnis geändert? Führen Sie `docmd deploy --caddy` erneut aus - das Caddyfile wird neu generiert, um Ihre aktuelle `docmd.config.js` widerzuspiegeln. --- ## [Cloudflare Pages](https://docs.docmd.io/de/deployment/cloudflare-pages/) --- title: "Cloudflare Pages" description: "Stellen Sie Ihre docmd-Dokumentation auf Cloudflare Pages über das globale Edge-Netzwerk bereit. CI/CD-bereit mit automatischen Builds." --- [Cloudflare Pages](https://pages.cloudflare.com/) hostet Ihre docmd-Website auf dem globalen Edge-Netzwerk von Cloudflare mit Zero-Konfigurations-CI/CD. Verbinden Sie Ihr Repository, und jeder Push löst einen automatischen Build und ein Deployment aus. ## Einrichtung im Dashboard 1. Gehen Sie zum [Cloudflare Dashboard](https://dash.cloudflare.com/) und navigieren Sie zu **Workers & Pages → Create → Pages**. 2. Verbinden Sie Ihren Git-Anbieter (GitHub oder GitLab) und wählen Sie Ihr Repository aus. 3. Konfigurieren Sie die Build-Einstellungen: | Einstellung | Wert | | :--- | :--- | | Framework-Preset | `Keines` (`None`) | | Build-Befehl | `npx @docmd/core build` | | Ausgabe-Verzeichnis | `site` | 4. Klicken Sie auf **Save and Deploy**. Cloudflare Pages erkennt die statische Ausgabe und verteilt sie automatisch über sein Edge-Netzwerk. ## Eigene Domain Fügen Sie eine benutzerdefinierte Domain unter **Pages → Ihr Projekt → Custom domains** hinzu. Cloudflare stellt automatisch ein SSL-Zertifikat bereit. Setzen Sie das Feld `url` in der Datei `docmd.config.json` so, dass es Ihrer Domain entspricht. Dies stellt sicher, dass kanonische Tags, Sitemaps und das LLMs-Plugin korrekte absolute URLs generieren. ## CI/CD-Hinweise Cloudflare Pages führt bei jedem Commit, der auf den verbundenen Branch gepusht wird, einen frischen CI/CD-Build aus. Sie benötigen keinen separaten GitHub Actions-Workflow. Cloudflare verwaltet die Build-Pipeline. ::: callout info "Warum `npx @docmd/core`?" In CI/CD-Umgebungen, in denen docmd nicht global installiert ist, lädt `npx @docmd/core` das Paket direkt herunter und führt es aus. Wenn Ihr Projekt `@docmd/core` als `devDependency` auflistet, funktioniert die Ausführung von `npx @docmd/core build` nach `npm install` einwandfrei. ::: ## SPA-Routing docmd generiert jede Seite als eigene `index.html`. Der direkte Zugriff auf URLs funktioniert ohne Rewrite-Regeln. Es ist keine zusätzliche Cloudflare-Konfiguration erforderlich. --- ## [Bereitstellung mit dem Deployer-Paket](https://docs.docmd.io/de/deployment/deployer-package/) --- title: "Bereitstellung mit dem Deployer-Paket" description: "Wie das modulare @docmd/deployer-Paket von docmd automatisch anbieterspezifische Deployment-Konfigurationen aus Ihrer Projektkonfiguration generiert." --- ## Übersicht docmd wird mit einem dedizierten `@docmd/deployer`-Paket ausgeliefert. Es liest Ihre `docmd.config.json` und generiert automatisch anbieterspezifische Bereitstellungsdateien. Jede generierte Datei ist auf Ihre genaue Konfiguration zugeschnitten – Ihr Ausgabeverzeichnis, Ihre Website-URL, SPA-Routing-Regeln und Ihre Node.js-Version werden alle ohne manuelle Bearbeitung berücksichtigt. ## Unterstützte Anbieter | Anbieter | Befehls-Flag | Generierte Dateien | | :------- | :----------- | :----------------- | | Docker + Nginx | `--docker` | `Dockerfile`, `.dockerignore` | | Nginx | `--nginx` | `nginx.conf` | | Caddy | `--caddy` | `Caddyfile` | | GitHub Pages | `--github-pages` | `.github/workflows/deploy.yml` | | Vercel | `--vercel` | `vercel.json` | | Netlify | `--netlify` | `netlify.toml` | ## Verwendung Führen Sie den Befehl im Projekt-Root aus (dort, wo sich Ihre `docmd.config.json` befindet): ```bash # Einzelner Anbieter npx @docmd/core deploy --github-pages # Mehrere Anbieter gleichzeitig npx @docmd/core deploy --docker --nginx # Vorhandene Dateien überschreiben npx @docmd/core deploy --vercel --force ``` ## Details zu den Anbietern ### GitHub Pages ```bash npx @docmd/core deploy --github-pages ``` Generiert `.github/workflows/deploy.yml` mit einer vollständigen Build-and-Deploy-Pipeline. Der Workflow: - Checkt Ihr Repository aus - Installiert Node.js (passend zu der von Ihrem Projekt benötigten Version) - Führt `npx @docmd/core build` aus - Lädt das Ausgabeverzeichnis auf GitHub Pages hoch ### Vercel ```bash npx @docmd/core deploy --vercel ``` Generiert `vercel.json` mit SPA-Routing-Regeln (leitet alle Pfade auf `index.html` um) und Ihrem konfigurierten Ausgabeverzeichnis. ### Netlify ```bash npx @docmd/core deploy --netlify ``` Generiert `netlify.toml` mit Ihrem Build-Befehl, dem Veröffentlichungsverzeichnis und SPA-Redirect-Regeln. ### Docker ```bash npx @docmd/core deploy --docker ``` Generiert ein `Dockerfile` unter Verwendung eines mehrstufigen Builds (Multi-stage Build): 1. **Build-Stufe**: Installiert Ihre exakte, festgeschriebene `@docmd/core`-Version und führt den Build aus. 2. **Serve-Stufe**: Kopiert die Ausgabe in ein minimales `nginx:alpine`-Image. Wenn in Ihrem Projekt-Root bereits eine `nginx.conf` existiert, kopiert das Dockerfile diese automatisch in den Container. ```bash # Docker- und Nginx-Konfigurationen zusammen generieren npx @docmd/core deploy --docker --nginx ``` ### Nginx ```bash npx @docmd/core deploy --nginx ``` Generiert eine `nginx.conf` mit SPA-Routing, gzip-Komprimierung und dem korrekten `root`-Pfad für Ihr Ausgabeverzeichnis. ### Caddy ```bash npx @docmd/core deploy --caddy ``` Generiert ein `Caddyfile` mit automatischem HTTPS, SPA-Routing und Dateibereitstellung aus Ihrem Ausgabeverzeichnis. ## Erneutes Generieren Haben Sie Ihre Konfiguration geändert? Führen Sie denselben Deploy-Befehl erneut aus. Verwenden Sie `--force`, um vorhandene Dateien zu überschreiben: ```bash npx @docmd/core deploy --docker --force ``` ## Abwägungen Generierte Konfigurationen sind bewährte Startpunkte. Sie sind für die Mehrheit der docmd-Bereitstellungen korrekt, erfordern jedoch möglicherweise Anpassungen für fortgeschrittene Szenarien wie benutzerdefinierte Domains, CDN-Rewrites oder mandantenfähige Bereitstellungen. Überprüfen Sie generierte Dateien immer, bevor Sie sie in der Produktion bereitstellen. --- ## [Deployer](https://docs.docmd.io/de/deployment/deployer/) --- title: "Deployer" description: "Generiert providerspezifische Deployment-Konfigurationsdateien aus Ihrer docmd-Projektkonfiguration – mit einem einzigen Befehl." --- Der `deploy`-Befehl liest Ihre `docmd.config.json` und generiert Deployment-Konfigurationsdateien, die exakt auf Ihr Projekt zugeschnitten sind — Ausgabeverzeichnis, Site-URL, SPA-Routing und Node.js-Version werden automatisch übernommen. Keine generischen Vorlagen. ## Unterstützte Provider | Provider | Flag | Generierte Dateien | | :------- | :--- | :----------------- | | Docker + Nginx | `--docker` | `Dockerfile`, `.dockerignore` | | Nginx | `--nginx` | `nginx.conf` | | Caddy | `--caddy` | `Caddyfile` | | GitHub Pages | `--github-pages` | `.github/workflows/deploy.yml` | | Vercel | `--vercel` | `vercel.json` | | Netlify | `--netlify` | `netlify.toml` | ## Verwendung Ausführen im Projektstamm (dort, wo `docmd.config.json` liegt): ```bash # Einzelner Provider npx @docmd/core deploy --github-pages # Mehrere Provider gleichzeitig npx @docmd/core deploy --docker --nginx # Vorhandene Dateien überschreiben npx @docmd/core deploy --vercel --force ``` ## Was personalisiert wird Der Deploy-Befehl liest Ihre Konfiguration (oder Zero-Config-Standardwerte) und injiziert: | Konfigurationsfeld | Verwendet in | |:--|:--| | `title` | Kommentar-Header in jeder generierten Datei | | `out` | `COPY`-Pfade im Dockerfile, `root`-Direktiven in Nginx/Caddy | | `url` | `server_name` in Nginx, Site-Adresse in Caddy | | `layout.spa` | Steuert, ob SPA-Routing-Fallback enthalten ist | | Konfigurations-Dateipfad | Dockerfile-Build-Schritt verwendet `--config` bei nicht-standardmäßigem Pfad | Keine `docmd.config.json`? Kein Problem. Der Befehl nutzt die gleichen Zero-Config-Standardwerte wie `npx @docmd/core dev` und `npx @docmd/core build`. ## Immer synchron Jede Ausführung generiert Ihre Deployment-Dateien neu, um sie mit Ihrer aktuellen Konfiguration abzugleichen. Site-URL oder Ausgabeverzeichnis geändert? Deploy-Befehl einfach erneut ausführen. Mit `--force` werden vorhandene Dateien ohne Rückfrage überschrieben. ## Provider-Details ### GitHub Pages ```bash npx @docmd/core deploy --github-pages ``` Generiert `.github/workflows/deploy.yml` mit einer vollständigen Build-und-Deploy-Pipeline. Der Workflow checkt Ihr Repository aus, installiert Node.js, führt `npx @docmd/core build` aus und lädt die Ausgabe auf GitHub Pages hoch. ::: callout tip "Lieber die GitHub Action nutzen?" Wenn Sie auf GitHub Pages deployen möchten, ohne selbst eine Workflow-Datei zu generieren, verwenden Sie direkt die [GitHub Action](./github-action) — sie erledigt alles in einem einzigen kombinierbaren Schritt. ::: ### Docker ```bash npx @docmd/core deploy --docker ``` Generiert ein `Dockerfile` mit einem Multi-Stage-Build: 1. **Build-Stage** — installiert Ihre exakt gepinnte `@docmd/core`-Version und führt den Build aus. 2. **Serve-Stage** — kopiert die Ausgabe in ein minimales `nginx:alpine`-Image. Wenn bereits eine `nginx.conf` im Projektstamm vorhanden ist, kopiert das Dockerfile diese automatisch in den Container. ```bash # Docker und Nginx-Konfiguration gemeinsam generieren npx @docmd/core deploy --docker --nginx ``` ::: callout tip "Offizielles Docker-Image" Möchten Sie docmd in einem Container betreiben, ohne ein eigenes Image zu bauen? Siehe die [Docker-Image](./docker)-Seite für das offizielle vorgefertigte Image. ::: ### Nginx ```bash npx @docmd/core deploy --nginx ``` Generiert `nginx.conf` mit SPA-Routing, Gzip-Komprimierung und dem korrekten `root`-Pfad für Ihr Ausgabeverzeichnis. Siehe die [NGINX](./nginx)-Seite für die vollständige generierte Konfiguration. ### Caddy ```bash npx @docmd/core deploy --caddy ``` Generiert ein `Caddyfile` mit automatischem HTTPS, SPA-Routing und Datei-Serving aus Ihrem Ausgabeverzeichnis. Siehe die [Caddy](./caddy)-Seite für die vollständige generierte Konfiguration. ### Vercel ```bash npx @docmd/core deploy --vercel ``` Generiert `vercel.json` mit SPA-Routing-Regeln und Ihrem konfigurierten Ausgabeverzeichnis. Deployment-Schritte finden Sie auf der [Vercel](./vercel)-Seite. ### Netlify ```bash npx @docmd/core deploy --netlify ``` Generiert `netlify.toml` mit Ihrem Build-Befehl, Publish-Verzeichnis und SPA-Redirect-Regeln. Deployment-Schritte finden Sie auf der [Netlify](./netlify)-Seite. ## Hinweise Generierte Konfigurationen sind meinungsstarke Ausgangspunkte. Sie sind für die meisten docmd-Deployments korrekt, können aber für fortgeschrittene Szenarien wie benutzerdefinierte Domains, CDN-Rewrites oder Multi-Region-Deployments Anpassungen erfordern. Überprüfen Sie generierte Dateien immer vor dem Deployment in der Produktion. --- ## [Docker](https://docs.docmd.io/de/deployment/docker/) --- title: "Docker" description: "Führen Sie docmd in einem Docker-Container aus — verwenden Sie das offizielle vorgefertigte Image oder generieren Sie ein benutzerdefiniertes Dockerfile aus Ihrer Projektkonfiguration." --- docmd generiert statisches HTML, was es ideal für leichtgewichtige, reproduzierbare Docker-Container macht. Es gibt zwei verschiedene Ansätze, abhängig von Ihrem Anwendungsfall. ## Offizielles Docker-Image Das offizielle Image ermöglicht es Ihnen, Ihre Dokumentation zu erstellen und bereitzustellen, ohne lokal etwas zu installieren. Es unterstützt mehrere Architekturen (`linux/amd64` und `linux/arm64`). ### Schnellstart ```bash # Ziehen Sie das neueste Image docker pull ghcr.io/docmd-io/docmd:latest # Erstellen Sie Ihre Dokumentation (mountet lokale Docs und gibt in ./site aus) docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build # Führen Sie die integrierte Demo-Site aus docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest ``` ### Docker Compose Verwenden Sie Docker Compose, um Build und Serving in einem Workflow zu kombinieren: ```yaml version: '3.8' services: docs: image: ghcr.io/docmd-io/docmd:latest command: build volumes: - ./docs:/docs - ./site:/site - ./docmd.config.json:/docmd.config.json:ro serve: image: nginx:alpine ports: - "8080:80" volumes: - ./site:/usr/share/nginx/html:ro depends_on: - docs ``` ### Image-Details | Eigenschaft | Wert | |:--|:--| | Basis | Alpine Linux (minimale Dateigröße) | | Sicherheit | Wird als non-root-Benutzer ausgeführt | | Health-Checks | Integrierte Container-Zustandsüberwachung | | SBOM | Software-Stückliste enthalten | | Architekturen | `linux/amd64`, `linux/arm64` | ## Benutzerdefiniertes Dockerfile (über Deployer) Für produktives Self-Hosting generieren Sie ein `Dockerfile`, das auf Ihre Projektkonfiguration zugeschnitten ist, mit dem [Deployer](./deployer): ```bash npx @docmd/core deploy --docker ``` Dies generiert ein `Dockerfile` mit einem Multi-Stage-Build: 1. **Build-Stage** — installiert Ihre exakt gepinnte `@docmd/core`-Version und führt den Build aus. 2. **Serve-Stage** — kopiert die Ausgabe in ein minimales `nginx:alpine`-Image. Generieren Sie Docker- und Nginx-Konfigurationen gemeinsam für ein vollständiges Self-Hosting-Setup: ```bash npx @docmd/core deploy --docker --nginx ``` ### Erstellen und Ausführen ```bash docker build -t meine-docs . docker run -p 8080:80 meine-docs ``` Ihre Dokumentation ist dann unter `http://localhost:8080` erreichbar. ::: callout tip "Neu generieren" Konfiguration geändert? Führen Sie `npx @docmd/core deploy --docker` erneut aus. Verwenden Sie `--force`, um vorhandene Dateien zu überschreiben. ::: --- ## [Firebase Hosting](https://docs.docmd.io/de/deployment/firebase/) --- title: "Firebase Hosting" description: "Stellen Sie Ihre docmd-Dokumentation auf Firebase Hosting bereit. Funktioniert manuell oder über GitHub Actions." --- [Firebase Hosting](https://firebase.google.com/products/hosting) stellt Ihre statische docmd-Website über ein globales CDN mit integriertem SSL bereit. Es lässt sich über die Firebase-CLI oder GitHub Actions sauber in CI/CD-Pipelines integrieren. ## Voraussetzungen Installieren Sie die Firebase-CLI: ```bash npm install -g firebase-tools firebase login ``` ## Einrichtung 1. Bauen Sie Ihre Website: ```bash npx @docmd/core build ``` 2. Initialisieren Sie Firebase Hosting in Ihrem Projekt-Root: ```bash firebase init hosting ``` Nach Aufforderung: - Wählen Sie Ihr Firebase-Projekt aus (oder erstellen Sie ein neues). - Setzen Sie das **öffentliche Verzeichnis** auf `site`. - Als Single-Page-App konfigurieren: **Nein** (docmd generiert pro Seite eine eigene `index.html`. Ein universeller Rewrite ist nicht erforderlich). - Überschreiben Sie `site/index.html` nicht. 3. Bereitstellen: ```bash firebase deploy --only hosting ``` ## CI/CD mit GitHub Actions Um bei jedem Push automatisch bereitzustellen, erstellen Sie `.github/workflows/firebase.yml`: ```yaml name: Deploy to Firebase Hosting on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: "20" - run: npm install - run: npx @docmd/core build - uses: FirebaseExtended/action-hosting-deploy@v0 with: repoToken: ${{ secrets.GITHUB_TOKEN }} firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} channelId: live ``` Richten Sie `FIREBASE_SERVICE_ACCOUNT` in den **Settings → Secrets** Ihres Repositories unter Verwendung des JSON-Schlüssels eines Firebase-Dienstkontos ein. ::: callout info "Warum `npx @docmd/core`?" In CI/CD-Umgebungen, in denen docmd nicht global installiert ist, lädt `npx @docmd/core` das Paket direkt herunter und führt es aus. Wenn Ihr Projekt `@docmd/core` als `devDependency` auflistet, funktioniert die Ausführung von `npx @docmd/core build` nach `npm install` einwandfrei. ::: ## Eigene Domain Fügen Sie eine benutzerdefinierte Domain in der Firebase-Konsole unter **Hosting → Add custom domain** hinzu. Firebase stellt SSL automatisch bereit. Setzen Sie das Feld `url` in der Datei `docmd.config.json` so, dass es Ihrer Domain entspricht. Dies stellt sicher, dass kanonische Tags und Sitemaps korrekte absolute URLs generieren. --- ## [GitHub Action](https://docs.docmd.io/de/deployment/github-action/) --- title: "GitHub Action" description: "Verwenden Sie die offizielle docmd GitHub Action, um Ihre Dokumentation auf GitHub Pages bereitzustellen — Zero-Config, ein kombinierbarer Schritt." --- Die `docmd-io/deploy` Action erstellt Ihre Dokumentationswebsite und gibt den Pfad zu den kompilierten Assets aus, bereit zum Hochladen auf GitHub Pages oder ein anderes Hosting-Ziel. Sie übernimmt Node.js-Setup, Konfigurationserkennung, Abhängigkeitsinstallation und den Build-Schritt in einer einzigen, kombinierbaren Action. ::: button "Im GitHub Marketplace ansehen" external:https://github.com/marketplace/actions/build-and-deploy-documentation-with-docmd icon:github ::: button "Quellcode" external:https://github.com/docmd-io/deploy icon:code ::: callout tip "Neues Projekt starten?" Verwenden Sie die [Starter-Vorlage](./starter-template) — sie enthält eine vorkonfigurierte Workflow-Datei und eine einsatzbereite Repository-Struktur. Die GitHub Action eignet sich am besten zum Hinzufügen von docmd-Deployment zu einem **bestehenden** Repository. ::: ## Schnellstart Fügen Sie die Action zu einer beliebigen Workflow-Datei in Ihrem Repository hinzu: ```yaml # .github/workflows/docs.yml name: Dokumentation bereitstellen on: push: branches: [main] permissions: contents: write pages: write id-token: write jobs: docs: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deploy.outputs.page_url }} steps: - uses: actions/checkout@v4 - uses: docmd-io/deploy@v1 id: build - uses: actions/upload-pages-artifact@v3 with: path: ${{ steps.build.outputs.site-dir }} - uses: actions/deploy-pages@v4 id: deploy ``` ## Wiederverwendbarer Workflow Für minimalen Boilerplate verwenden Sie den gehosteten wiederverwendbaren Workflow. Er übernimmt Berechtigungen, Checkout, Build, Upload und Deploy in einem Aufruf: ```yaml # .github/workflows/docs.yml on: push: branches: [main] jobs: docs: uses: docmd-io/deploy/.github/workflows/deploy.yml@v1 ``` ## Eingabeparameter | Parameter | Standard | Beschreibung | |-----------|----------|--------------| | `node` | `20` | Node.js-Version für den Build | ## Ausgabeparameter | Ausgabe | Beschreibung | |---------|--------------| | `site-dir` | Relativer Pfad zum kompilierten Site-Verzeichnis (z. B. `site/`) | ## Was die Action tut 1. **Node.js einrichten** — mit der angegebenen Version. 2. **Konfiguration erkennen** — sucht im Repository-Baum (bis zu zwei Ebenen tief) nach `docmd.config.json`, `docmd.config.js` oder `docmd.config.ts`. Unterverzeichnis-Konfigurationen werden vollständig unterstützt. 3. **docmd initialisieren** — falls keine Konfiguration gefunden wird, führt `npx @docmd/core init` aus. 4. **Abhängigkeiten installieren** — führt `npm ci` aus, wenn eine `package.json` vorhanden ist, andernfalls wird `@docmd/core` direkt installiert. 5. **Website erstellen** — führt `npx @docmd/core build` aus und liest das Ausgabeverzeichnis aus der Konfiguration. 6. **Pfad ausgeben** — stellt `site-dir` bereit, damit der Upload-Schritt die kompilierten Assets findet. ## Erstmalige Einrichtung GitHub Pages muss so konfiguriert sein, dass die Bereitstellung über **GitHub Actions** erfolgt (nicht über einen Branch). Dies ist ein einmaliger Schritt pro Repository: 1. Öffnen Sie Ihr Repository auf GitHub. 2. Navigieren Sie zu **Settings → Pages**. 3. Wählen Sie unter **Source** die Option **GitHub Actions**. 4. Speichern. Nach diesem Schritt löst jeder Push zu `main` automatisch ein Deployment aus. ## Unterstützung für verschachtelte Konfigurationen Befindet sich Ihre `docmd.config.json` in einem Unterverzeichnis – beispielsweise `packages/docs/docmd.config.json` in einem Monorepo – erkennt die Action dies automatisch und übergibt `--cwd` an docmd. Eine manuelle Pfadkonfiguration ist nicht erforderlich. ## Benutzerdefinierte Domain So verwenden Sie eine benutzerdefinierte Domain: 1. Fügen Sie eine `CNAME`-Datei mit Ihrer Domain zu Ihrem `docs/`-Verzeichnis hinzu (oder Ihrem konfigurierten Assets-Ordner), z. B. `docs.example.com`. 2. Setzen Sie das Feld `url` in `docmd.config.json` auf Ihre benutzerdefinierte Domain, damit Sitemaps und kanonische Tags korrekt sind. 3. Konfigurieren Sie die Domain unter **Settings → Pages → Custom domain**. ## Action-Version festlegen Für Produktions-Dokumentationsseiten verwenden Sie einen spezifischen Release-Tag anstelle von `@v1`: ```yaml - uses: docmd-io/deploy@v1.0.0 id: build ``` Dies verhindert unerwartetes Verhalten durch zukünftige Minor-Updates. ## Fehlerbehebung **`Error: Dependencies lock file is not found`** Dieser Fehler tritt auf, wenn `actions/setup-node` mit `cache: 'npm'` konfiguriert ist, aber keine `package-lock.json` vorhanden ist. Die `docmd-io/deploy` Action verwaltet das Caching intern — fügen Sie keinen separaten `actions/setup-node`-Schritt mit `cache: 'npm'` hinzu, wenn Sie diese Action verwenden. **Build erfolgreich, aber die Website ist nicht live** Stellen Sie sicher, dass GitHub Pages auf die Bereitstellung über **GitHub Actions** und nicht über einen Branch eingestellt ist. Siehe [Erstmalige Einrichtung](#erstmalige-einrichtung) oben. **Konfiguration nicht erkannt** Die Action durchsucht bis zu zwei Verzeichnisebenen. Wenn Ihre Konfiguration tiefer liegt, übergeben Sie `--cwd` manuell in einem benutzerdefinierten Workflow-Schritt oder verwenden Sie den [Deployer](./deployer), um eine maßgeschneiderte Workflow-Datei zu generieren. --- ## [GitHub Pages](https://docs.docmd.io/de/deployment/github-pages/) --- title: "GitHub Pages" description: "Stellen Sie Ihre docmd-Dokumentation automatisch auf GitHub Pages bereit unter Verwendung eines generierten GitHub Actions CI/CD-Workflows." --- Der Befehl `npx @docmd/core deploy --github-pages` generiert eine direkt verwendbare GitHub Actions-Workflow-Datei unter `.github/workflows/deploy.yml`. Pushen Sie diese in Ihr Repository. GitHub baut und stellt Ihre Website bei jedem Push auf `main` automatisch bereit. ```bash npx @docmd/core deploy --github-pages ``` Dies erstellt eine auf Ihr Projekt zugeschnittene Datei `.github/workflows/deploy.yml`. Es ist keine manuelle Bearbeitung erforderlich. ## Was generiert wird Der Workflow führt folgende Schritte aus: 1. Checkt Ihr Repository aus. 2. Installiert Node.js und Ihre Projekt-Abhängigkeiten. 3. Installiert die exakte Version von `@docmd/core`, die zur Erstellung der Datei verwendet wurde. 4. Führt `npx @docmd/core build` aus. 5. Lädt das Ausgabeverzeichnis als GitHub Pages-Artefakt hoch. 6. Stellt es auf GitHub Pages bereit. ## GitHub Pages aktivieren Bevor Sie den Workflow pushen, aktivieren Sie GitHub Pages in Ihrem Repository: 1. Gehen Sie zu **Settings → Pages**. 2. Setzen Sie die **Source** auf **GitHub Actions**. Sobald dies aktiviert ist, löst jeder Push auf `main` ein Deployment aus. ## Den Workflow anpassen Die generierte Datei ist einfaches YAML. Sie können sie frei bearbeiten. Häufige Änderungen betreffen: - **Branch**: Ändern Sie `branches: [main]` in den Namen Ihres Standard-Branches. - **Node-Version**: Aktualisieren Sie `node-version: "20"`, um sie an Ihr Projekt anzupassen. - **Build-Befehl**: Der Workflow verwendet standardmäßig `npx @docmd/core build`. Wenn Sie eine benutzerdefinierte Konfigurationsdatei verwenden, führen Sie `npx @docmd/core deploy --github-pages --config Ihre-Konfig.json` aus, um den Workflow neu zu generieren. ## Eigene Domain Nach der Bereitstellung können Sie in den Repository-Einstellungen unter **Settings → Pages → Custom domain** eine benutzerdefinierte Domain hinzufügen. Tragen Sie diese Domain auch im Feld `url` Ihrer `docmd.config.json` ein und deployen Sie neu, damit Sitemaps und kanonische Tags korrekt bleiben. --- ## [Deployment-Übersicht](https://docs.docmd.io/de/deployment/) --- title: "Deployment-Übersicht" description: "Wählen Sie, wie Sie Ihre docmd-Dokumentationsseite bereitstellen — von Zero-Config-Vorlagen über selbst gehostete Server bis hin zu Cloud-Plattformen." --- docmd erstellt eine vollständig statische Website. Die Ausgabe ist ein eigenständiger Ordner (Standard: `site/`), der überall gehostet werden kann — keine serverseitige Laufzeitumgebung erforderlich. ```bash npx @docmd/core build ``` ## Deployment-Methode wählen Es gibt drei Hauptwege, abhängig von Ihrer Situation: | Methode | Am besten für | |:--|:--| | [Starter-Vorlage](./starter-template) | Ein neues Projekt von Grund auf starten | | [GitHub Action](./github-action) | Automatisches Deployment zu einem bestehenden Repository hinzufügen | | [Deployer](./deployer) | Server-Konfigurationen generieren (Docker, Nginx, Caddy, Vercel, Netlify) | ## Starter-Vorlage Der schnellste Einstieg. Klonen Sie das offizielle Vorlagen-Repository — es enthält eine `docmd.config.json`, eine Beispielseite und einen vorkonfigurierten GitHub Actions-Workflow, der bei jedem Push auf GitHub Pages bereitstellt. → [Starter-Vorlage](./starter-template) ## GitHub Action Die `docmd-io/deploy` Action erstellt Ihre Website und gibt den kompilierten Pfad aus, bereit zum Hochladen auf GitHub Pages oder ein anderes Ziel. Verwenden Sie dies, um docmd-Deployment zu einem bestehenden Repository hinzuzufügen, ohne Ihre Projektstruktur zu ändern. → [GitHub Action](./github-action) ## Deployer Der `deploy`-Befehl liest Ihre `docmd.config.json` und generiert providerspezifische Konfigurationsdateien, die auf Ihr Projekt zugeschnitten sind. Keine generischen Vorlagen — jede Datei spiegelt Ihr tatsächliches Ausgabeverzeichnis, Ihre Site-URL und SPA-Einstellungen wider. ```bash # Selbst gehostet npx @docmd/core deploy --docker # Dockerfile + .dockerignore npx @docmd/core deploy --nginx # Produktions-nginx.conf npx @docmd/core deploy --caddy # Produktions-Caddyfile # Cloud / CI npx @docmd/core deploy --github-pages # GitHub Actions-Workflow npx @docmd/core deploy --vercel # vercel.json npx @docmd/core deploy --netlify # netlify.toml ``` → [Deployer-Referenz](./deployer) ## Cloud-Plattformen Für verwaltetes Hosting ohne eigenen Server: - [Docker-Image](./docker) — Offizielles Multi-Arch-Image für containerisierte Deployments - [NGINX](./nginx) — Selbst gehostet mit generierter Konfiguration - [Caddy](./caddy) — Selbst gehostet mit automatischem HTTPS - [Vercel](./vercel) — Zero-Config Cloud-Deployment - [Netlify](./netlify) — Git-verbundenes Continuous Deployment - [Cloudflare Pages](./cloudflare-pages) — Edge-natives Hosting mit integriertem CI/CD - [Firebase Hosting](./firebase) — Google CDN mit GitHub Actions-Integration ## Produktions-Checkliste 1. **Site-URL** — Setzen Sie `url` in `docmd.config.json`. Dies steuert kanonische Tags, Sitemaps, Social-Previews und generierte Deployment-Dateien. 2. **Weiterleitungen** — Migration von einem anderen Tool? Verwenden Sie die `redirects`-Konfiguration zur Beibehaltung der SEO-Rankings. 3. **Analytik** — Aktivieren Sie das `analytics`-Plugin zur Verfolgung von Engagement und Suchanfragen. 4. **KI-Kontext** — Aktivieren Sie das `llms`-Plugin zur Generierung von `llms.txt` für die KI-Agent-Aufnahme. ::: callout tip "Benutzerdefinierte 404-Seiten" docmd generiert eine `404.html` in Ihrem Ausgabeverzeichnis. Die meisten Hosting-Anbieter verwenden diese automatisch für fehlende Routen. ::: --- ## [Netlify](https://docs.docmd.io/de/deployment/netlify/) --- title: "Netlify" description: "Stellen Sie Ihre docmd-Dokumentation unter Verwendung einer generierten netlify.toml auf Netlify bereit." --- Der Befehl `npx @docmd/core deploy --netlify` generiert eine `netlify.toml`-Datei im Root Ihres Projekts. Sie ist bereits mit dem korrekten Build-Befehl, dem Veröffentlichungsverzeichnis (Publish Directory), Cache-Headern und SPA-Redirects konfiguriert. ```bash npx @docmd/core deploy --netlify ``` ## Was generiert wird Die `netlify.toml` konfiguriert Folgendes: - **Build-Befehl** – Installiert `@docmd/core` und führt `npx @docmd/core build` aus. - **Publish-Verzeichnis** – Entspricht Ihrem konfigurierten `out`-Verzeichnis. - **Node-Version** – Festgelegt auf Node 20. - **Cache-Header** – Unveränderlich (immutable) für Assets, no-cache für HTML-Seiten. - **SPA-Redirects** – Ein Rewrite von `/*` zu `/index.html`, wenn `layout.spa` aktiviert ist. ## Bereitstellung Verbinden Sie Ihr Repository über das [Netlify-Dashboard](https://app.netlify.com) mit Netlify. Es erkennt die `netlify.toml` automatisch und führt bei jedem Push ein Deployment aus. Alternativ können Sie die [Netlify-CLI](https://docs.netlify.com/cli/get-started/) verwenden: ```bash npm install -g netlify-cli netlify deploy --prod ``` ## Erneutes Generieren Führen Sie `npx @docmd/core deploy --netlify` jederzeit aus, wenn Sie `out` or andere Konfigurationsfelder ändern. Dies hält die `netlify.toml` synchron. --- ## [NGINX](https://docs.docmd.io/de/deployment/nginx/) --- title: "NGINX" description: "docmd mit einer produktionsreifen NGINX-Konfiguration bereitstellen." --- NGINX ist einer der zuverlässigsten Webserver. Da `docmd`-Ausgabe vollständig statisch ist, kann NGINX sie mit nahezu null Latenz bereitstellen. ## nginx.conf generieren ```bash docmd deploy --nginx ``` Dies generiert eine `nginx.conf`, die auf Ihr Projekt zugeschnitten ist: - **`server_name`** wird auf den Hostnamen aus Ihrer `url`-Konfiguration gesetzt (Fallback auf `localhost`) - **SPA-Fallback** (`try_files ... /index.html`) wird nur einbezogen, wenn `layout.spa` in Ihrer Konfiguration `true` ist - **Sicherheitsheader**, GZIP-Kompression und unveränderliches Asset-Caching sind standardmäßig enthalten ## Bereitstellungsschritte 1. Bauen Sie Ihre Website: `docmd build` 2. Laden Sie den Inhalt Ihres Ausgabeverzeichnisses auf den Web-Root Ihres Servers hoch (z.B. `/usr/share/nginx/html/`). 3. Platzieren Sie die generierte `nginx.conf` in die Konfiguration Ihres Servers (z.B. `/etc/nginx/conf.d/default.conf`). 4. Starten Sie NGINX neu: `sudo systemctl restart nginx` ### Neu generieren Site-URL geändert oder SPA-Modus umgeschaltet? Führen Sie `docmd deploy --nginx` erneut aus - die Konfiguration wird neu generiert, um Ihre aktuelle `docmd.config.js` widerzuspiegeln. --- ## [Starter-Vorlage](https://docs.docmd.io/de/deployment/starter-template/) --- title: "Starter-Vorlage" description: "Verwenden Sie die offizielle docmd Starter-Vorlage, um in unter einer Minute eine vorkonfigurierte Dokumentationswebsite mit automatischer GitHub Pages-Bereitstellung zu erstellen." --- # docmd Starter-Vorlage Das `docmd-template`-Repository ist der schnellste Weg, eine neue Dokumentationswebsite zu starten. Es enthält eine funktionierende `docmd.config.json`, eine Beispielseite, eine `package.json` für die lokale Entwicklung und einen vorkonfigurierten GitHub Actions-Workflow, der bei jedem Push automatisch auf GitHub Pages bereitstellt. ::: button "Vorlage verwenden" external:https://github.com/docmd-io/docmd-template/generate icon:github color:#2ea44f ::: button "Repository ansehen" external:https://github.com/docmd-io/docmd-template icon:external-link ## Schnellstart ### 1. Ihr Repository erstellen Klicken Sie auf GitHub auf **[Vorlage verwenden](https://github.com/docmd-io/docmd-template/generate)**. Geben Sie Ihrem Repository einen Namen und klicken Sie auf **Create repository**. Sie müssen es nicht forken — die Vorlage erstellt eine saubere, unabhängige Kopie. ### 2. Ihre Website konfigurieren Öffnen Sie `docmd.config.json` in Ihrem neuen Repository und aktualisieren Sie die Felder `title` und `url`: ```json { "title": "Meine Dokumentation", "url": "https://benutzername.github.io/repo-name" } ``` Ersetzen Sie `benutzername` und `repo-name` durch Ihren GitHub-Benutzernamen und den Repository-Namen. ### 3. GitHub Pages aktivieren Dies ist ein einmaliger Schritt pro Repository: 1. Gehen Sie zu **Settings → Pages**. 2. Wählen Sie unter **Source** die Option **GitHub Actions**. 3. Speichern. ### 4. Pushen und bereitstellen Pushen Sie eine beliebige Änderung zu `main`. Der enthaltene Workflow erstellt Ihre Website und stellt sie automatisch auf GitHub Pages bereit. Ihre Dokumentation ist erreichbar unter: ``` https://<benutzername>.github.io/<repo-name>/ ``` ## Enthaltene Dateien ``` .github/ workflows/ docs.yml # Automatischer Build und Deploy bei Push zu main docmd.config.json # Website-Titel, URL und Ausgabeverzeichnis docs/ index.md # Ihre erste Dokumentationsseite package.json # Skripte für die lokale Entwicklung ``` ## Lokale Entwicklung Klonen Sie Ihr Repository und starten Sie den Entwicklungsserver: ```bash npm install npm run dev ``` Die Website ist unter `http://localhost:3000` mit Live-Reload verfügbar. Änderungen an Markdown-Dateien werden sofort übernommen. Lokaler Build einer Produktionskopie: ```bash npm run build ``` Die kompilierte Website wird standardmäßig in `site/` geschrieben. ## Ihre erste Seite hinzufügen Erstellen Sie eine neue Markdown-Datei in `docs/`: ```bash docs/ index.md # Startseite erste-schritte.md api-referenz.md ``` Fügen Sie eine `navigation.json` hinzu, um die Seitenleiste zu steuern: ```json [ { "title": "Startseite", "path": "/" }, { "title": "Erste Schritte", "path": "/erste-schritte" }, { "title": "API-Referenz", "path": "/api-referenz" } ] ``` Die vollständige Navigationskonfiguration finden Sie unter [Navigationskonfiguration](../configuration/navigation.md). ## Benutzerdefinierte Domain So verwenden Sie eine benutzerdefinierte Domain (z. B. `docs.example.com`): 1. Aktualisieren Sie das Feld `url` in `docmd.config.json`: ```json { "url": "https://docs.example.com" } ``` 2. Fügen Sie eine `CNAME`-Datei mit Ihrer Domain in Ihr `docs/`-Verzeichnis ein. 3. Konfigurieren Sie die Domain unter **Settings → Pages → Custom domain**. ## Starter-Vorlage vs. GitHub Action Die Vorlage gibt Ihnen von Anfang an die volle Kontrolle über die Workflow-Datei und Konfiguration. Die [GitHub Action](./github-action) eignet sich besser zum Hinzufügen von docmd-Deployment zu einem bestehenden Repository, ohne es umzustrukturieren. | | Starter-Vorlage | GitHub Action | |---|---|---| | Ausgangspunkt | Neues Repository | Bestehendes Repository | | Workflow-Datei | Enthalten, frei bearbeitbar | Sie schreiben sie, Action übernimmt Build | | Konfiguration | Vorkonfiguriert | Automatisch erkannt oder generiert | | Geeignet für | Neue Projekte | Dokumentation zu bestehenden Repos hinzufügen | --- ## [Vercel](https://docs.docmd.io/de/deployment/vercel/) --- title: "Vercel" description: "Stellen Sie Ihre docmd-Dokumentation unter Verwendung einer generierten vercel.json auf Vercel bereit." --- Der Befehl `npx @docmd/core deploy --vercel` generiert eine `vercel.json`-Datei im Root Ihres Projekts. Sie ist automatisch auf das Ausgabeverzeichnis Ihrer Website und die SPA-Routing-Einstellungen konfiguriert. ```bash npx @docmd/core deploy --vercel ``` ## Was generiert wird Die `vercel.json` konfiguriert Folgendes: - **Build-Befehl** – Führt `npx @docmd/core build` aus. - **Ausgabeverzeichnis (Output Directory)** – Entspricht der Eigenschaft `out` in Ihrer Konfiguration. - **Installationsbefehl** – Installiert die exakte verwendete Version von `@docmd/core`. - **Cache-Header** – Unveränderliches Caching für Assets, no-cache für HTML. - **SPA-Routing** – Eine Catch-all-Route zu `index.html`, wenn `layout.spa` aktiviert ist. ## Bereitstellung Nachdem Sie die Datei generiert haben, stellen Sie sie mit der [Vercel-CLI](https://vercel.com/docs/cli) bereit: ```bash npm install -g vercel vercel ``` Alternativ können Sie Ihr Repository über das Dashboard mit Vercel verbinden. Es erkennt die `vercel.json` automatisch. ## Erneutes Generieren Wenn Sie Ihr `out`-Verzeichnis oder Ihre `url` in der `docmd.config.json` ändern, führen Sie den Befehl erneut aus, um die Datei neu zu generieren. Dies hält die Konfiguration synchron. --- ## [JavaScript-Engine](https://docs.docmd.io/de/engines/js/) --- title: "JavaScript-Engine" description: "Erforschen Sie docmds native JavaScript-Ausführungs-Engine im Detail: Anwendungsfälle, Portabilität, Funktionen und Grenzen." --- Die **JavaScript-Engine** ist die grundlegende, in docmd integrierte Ausführungs-Engine. Sie läuft problemlos auf modernen JavaScript-Laufzeiten. Sie liefert eine hervorragende Leistung ohne externe Abhängigkeiten oder komplexe Compiler. Standardmäßig verlässt sich jedes docmd-Repository auf die JavaScript-Engine. Sie bietet eine äußerst zuverlässige Dateidurchquerung, Metadaten-Indizierung und Build-Generierung. ## Konfiguration Um docmd explizit anzuweisen, das JavaScript-Backend zu verwenden, definieren Sie die Eigenschaft `engine` als `"js"` in der Datei `docmd.config.json`. ```json { "title": "Entwickler-Handbuch", "engine": "js", "src": "docs", "out": "site" } ``` ## Ideale Anwendungsfälle & Stärken Die JavaScript-Engine ist außergewöhnlich vielseitig. Sie glänzt unter den folgenden Bedingungen: - **Standard-Repositories**: Websites mit bis zu mehreren hundert Seiten bauen extrem schnell. Sie nutzt optimierte JIT-Kompilierung und natives JSON-Parsing. - **Maximale Portabilität**: Wenn Ihr Team unterschiedliche Betriebssysteme oder eingeschränkte Unternehmensnetzwerke nutzt, garantiert die JavaScript-Engine überall fehlerfreie Builds. - **Schnelles Prototyping**: Lokale Entwicklungs-Builds profitieren von sofortigem Hot-Reloading (`npx @docmd/core dev`) mit geringer Initialisierungslatenz. - **Benutzerdefiniertes Scripting**: Konfigurations-Fallbacks und Plugin-Integrationen werden nativ in JavaScript ausgeführt. Standard-String-Parsing vermeidet grenzüberschreitende Serialisierungskosten. ## Verfügbare Geräte & Host-Kompatibilität Da sie vollständig in nativen Laufzeitumgebungen arbeitet, unterstützt die JavaScript-Engine eine umfassende Palette von Zielplattformen: - **Betriebssysteme**: macOS, Linux, Windows, FreeBSD und OpenBSD. - **Hardware-Architekturen**: x64, ARM64 (Apple Silicon, AWS Graviton), ARMv7 und RISC-V. - **Container-Umgebungen**: Alpine Linux, Standard-Debian/Ubuntu, Serverless-Build-Runner (Vercel, Netlify) und eingebettete CI-Pipelines. ## Funktionen & Einschränkungen | Dimension | JavaScript-Engine-Profil | Operative Auswirkung | | :--- | :--- | :--- | | **Konkurrenzmodell** | Node.js-Event-Loop + Native Worker-Threads | Hervorragende asynchrone Planung für Netzwerkantworten. Festplattenintensive Blöcke arbeiten reibungslos. | | **Git-Metadaten-Verarbeitung** | Subprozess-Orchestrierung (`child_process.execFile`) | Startet sicher native Git-Binärdateien, um Commit-Verläufe zu erfassen. Enthält dauerhaften Festplatten-Caching. | | **Einrichtung & Initialisierung** | Zero-Configuration | Startet augenblicklich. Keine Postinstall-Kompilierung von Paketen erforderlich. | | **Skalierungsgrenze** | Hochperformant bis ca. 1.000 Dokumente | Bei monolithischen Repositories mit mehr als tausend komplexen Dateien kann der Overhead sequenzieller Subprozesse geringfügige Latenzen verursachen. | ## Feature-Vollständigkeit Die JavaScript-Engine bietet **exklusive universelle Feature-Unterstützung**. Jedes Core-Feature, jede erweiterte Syntax, jede Template-Zone und jedes offizielle Plugin ist so konzipiert, dass es hier reibungslos ausgeführt wird. Ob mathematische Formeln kompiliert, Live-Suchindizes gerendert oder statische Sitemaps generiert werden – die JavaScript-Engine garantiert deterministische Builds. --- ## [Übersicht der Engines](https://docs.docmd.io/de/engines/overview/) --- title: "Übersicht der Engines" description: "Verstehen Sie die steckbare Build-Engine-Architektur und wählen Sie das beste Verarbeitungs-Backend." --- Der Compiler verfügt über eine hochmodulare, mehrthreadige **steckbare Engine-Architektur**. Sie entkoppelt die Orchestrierung von Rechenaufgaben, um rechenintensive Workloads effizient auszuführen. Wählen Sie zwischen der konfigurierungsfreien **JavaScript-Engine** und der beschleunigten **Rust-Engine**. Wählen Sie die Engine basierend auf der Größe Ihres Repositories, der Plattform und Ihren Leistungsanforderungen. ## Verfügbare Engines | Engine | Bezeichner | Standard | Ziel-Anwendungsfall | Hauptstärke | | :--- | :--- | :---: | :--- | :--- | | **JavaScript-Engine** | `"js"` | ✅ Ja | Standard-Websites, schnelles lokales Prototyping, Portabilität. | Läuft universell auf jedem Gerät, das Node.js unterstützt. | | **Rust-Engine (Vorschau)** | `"rust"` | ❌ Nein | Riesige Repositories (mehr als 1000 Dateien), Enterprise CI/CD-Builds. | Maximiert parallele Datei-I/O via Tokio. | ## Konfigurationsoptionen Konfigurieren Sie Ihre Build-Engine in der Datei `docmd.config.json`. Setzen Sie den Parameter `engine` direkt. ```json { "title": "Enterprise-Referenz", "engine": "js", "src": "docs", "out": "site" } ``` ### Vollständige Optionsreferenz | Schlüssel | Unterstützte Werte | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `engine` | `"js"`, `"rust"` | `"js"` | Die Ausführungsebene, die die Dateierkennung und Batch-Lesevorgänge verarbeitet. | ## Übergreifende Funktionen & Einschränkungen Beide Engines teilen sich eine strikte Ausführungsgrenze. Die Core-API-Ebene erzwingt einheitliche Sicherheit und deterministische Ausgaben. ### Gemeinsame Funktionen - **Thread-Isolation**: Engines führen asynchrone Aufgaben sicher in isolierten Worker-Threads aus. Dies verhindert das Blockieren des primären Server-Loops. - **Aufgaben-Verifizierung**: Strikte Whitelists verhindern unbefugten Festplattenzugriff oder unbestätigte Ausführungsmuster. - **Nahtlose Interoperabilität**: Plugins fordern Daten über standardisierte Schnittstellen (`runWorkerTask`) an. Sie bleiben vom zugrunde liegenden Backend unabhängig. ### Architektonische Einschränkungen - **Serialisierungs-Overhead**: Daten überschreiten native Laufzeitgrenzen (N-API). Hochgradig iterative Aufgaben, die große JSON-Objekte übergeben, verursachen eine geringe Serialisierungsgebühr. - **Binärkompatibilität**: Die JavaScript-Engine läuft überall nativ. Die Rust-Engine verlässt sich auf betriebssystemspezifische Plattform-Binärdateien, die über npm verteilt werden. ## So funktioniert der Engine-Loader Beim Start von `@docmd/core` prüft der interne Loader Ihre aktive Konfiguration: 1. **Auflösung**: Wenn für `"rust"` konfiguriert, lädt die Engine das architekturspezifische native Paket verzögert (z. B. `@docmd/engine-rust-darwin-arm64`). 2. **Sanfter Fallback**: Wenn die Binärdatei fehlt oder nicht unterstützt wird, protokolliert die Engine einen Hinweis. Sie weicht dann transparent auf die JavaScript-Engine aus. Ihr Build gelingt in jedem Fall. Erfahren Sie mehr in der Detaildokumentation für jede Engine: - [JavaScript-Engine Referenz](js.md) - [Rust-Engine Referenz](rust.md) --- ## [Rust-Engine](https://docs.docmd.io/de/engines/rust/) --- title: "Rust-Engine" description: "Erkunden Sie die optionale native Rust-Engine: Anwendungsfälle, Dateizugriffs-Funktionen, unterstützte Pakete und Einschränkungen." --- Die **Rust-Engine** ist eine optionale Hochleistungs-Ausführungs-Engine. Sie beschleunigt schwere I/O-Workloads in riesigen Dokumentationsprojekten. Durch die Verwendung nativer Binärdateien über N-API umgeht sie die Einschränkungen des Standard-Event-Loops, um mehrthreadiges Dateilesen und Subprozess-Orchestrierung zu ermöglichen. Verfügbar als **experimentelle Vorschau**, richtet sich die Rust-Engine an Unternehmen. Sie glänzt dort, wo tausende von Markdown-Dateien und umfangreiche Git-Logs zu Kompilierungs-Engpässen führen. ## Konfiguration Um die native Rust-Beschleunigung zu aktivieren, konfigurieren Sie die Direktive `engine` in Ihrer Datei `docmd.config.json` als `"rust"`. ```json { "title": "Global API Registry", "engine": "rust", "src": "docs", "out": "site" } ``` ## Ideale Anwendungsfälle & Stärken Die Rust-Engine löst spezifische Kompilierungs-Engpässe. Sie bietet in folgenden Szenarien hervorragende Effizienzgewinne: - **Riesige Repositories (mehr als 1.000 Dateien)**: Monolithische Projekte profitieren immens von asynchronem, parallelem Dateisystemzugriff, der über Tokio orchestriert wird. - **Intensives Erfassen von Git-Metadaten**: Das Extrahieren tiefer Commit-Logs über hunderte von Seiten hinweg erfordert schweres Starten von Subprozessen. Die Rust-Engine verarbeitet `git:log`-Aufgaben bis zu **1,24× schneller** als JavaScript. - **Kaltstart-Beschleunigung in CI/CD**: In Umgebungen, in denen keine warmen Festplatten-Caches verfügbar sind, reduziert der rohe Dateilesedurchsatz die Gesamtverarbeitungszeit. Echte Benchmarks zeigen eine **Beschleunigung von ca. 25 % bei Kaltstarts** und eine **Verbesserung von ca. 17 % bei Warmstarts**. ## Unterstützte Geräte & Plattform-Pakete Die Engine führt vorkompilierten Maschinencode aus. Sie erfordert dedizierte native Binärdateien, die auf Ihre Zielarchitektur zugeschnitten sind. Das grundlegende Paket `@docmd/engine-rust` lädt beim Start automatisch die richtige Plattform-Binärdatei verzögert. Folgende Plattform-Pakete werden derzeit bereitgestellt: | Plattform-Paket | Zielarchitektur | Host-Betriebssystem | | :--- | :--- | :--- | | `@docmd/engine-rust-darwin-arm64` | ARM64 (Apple Silicon) | macOS | | `@docmd/engine-rust-darwin-x64` | x64 (Intel) | macOS | | `@docmd/engine-rust-linux-x64-gnu` | x64 | Linux (glibc-Umgebungen) | | `@docmd/engine-rust-linux-arm64-gnu` | ARM64 | Linux (glibc-Umgebungen) | | `@docmd/engine-rust-win32-x64-msvc` | x64 | Windows | ::: callout info "Sanfter automatischer Fallback" Wenn in Ihrer Umgebung keine vorkompilierte Binärdatei verfügbar ist, protokolliert die Engine eine unschädliche Benachrichtigung und **weicht automatisch** auf die hochperformante JavaScript-Engine aus. Ihre Builds bleiben vollkommen deterministisch. ::: ## Funktionen & Strategische Einschränkungen Um den maximalen Nutzen zu erzielen, müssen Sie die architektonischen Kompromisse verstehen. Die Engine eignet sich hervorragend für I/O-gebundene Operationen, verursacht jedoch Overhead bei der grenzüberschreitenden Serialisierung. | Funktion / Aufgabe | Rust-Engine Leistungsprofil | Architektonisches Urteil | | :--- | :--- | :--- | | **Batch-Dateierkennung & -Lesevorgänge** | Beschleunigt über parallele Tokio-Worker. | ✅ Äußerst effektiv für riesige Verzeichnisse. | | **Erfassung von Git-Commit-Logs** | Schnelle Subprozess-Orchestrierung unter Umgehung des Node-Event-Loops. | ✅ Hervorragend geeignet für Git-Metadatenextraktion bei Kaltstarts. | | **Dauerhaftes Festplatten-Caching** | Native Unterstützung für verankerte Festplatten-Caches, um redundante Lesevorgänge zu eliminieren. | ✅ Äußerst effektiv für Warmstarts. | | **CPU-gebundene Suchindizierung** | **Langsamer als native JavaScript-JIT**. | ❌ Ineffizient aufgrund des doppelten Serialisierungs-Overheads. | ### Die Serialisierungssteuer erklärt Die Kommunikation zwischen dem Core-Orchestrator von docmd und der nativen Rust-Engine beruht auf stringifiziertem JSON, das die N-API-Laufzeitgrenze überschreitet: ```text JS Worker → JSON.stringify() → NAPI Boundary → Serde Deserialisierung → [Rust-Aufgabe] → Serde Serialisierung → NAPI Boundary → JSON.parse() ``` Bei I/O-lastigen Operationen wie dem Abfragen von Git-Historien oder dem Lesen von Festplattenpuffern überwiegt die eingesparte Verarbeitungszeit die String-Konvertierungskosten bei weitem. Bei hochgradig iterativen, CPU-gebundenen Aufgaben wie der Volltextsuchindizierung (`search:index`) verbraucht der **Serialisierungs-Roundtrip jedoch mehr CPU-Ressourcen als die eigentliche Aufgabe selbst**. Das Hin- und Herserialisieren großer Inhaltsarrays führt dazu, dass die Rust-Implementierung langsamer läuft als die native JIT-Stringmanipulation von Node. Infolgedessen bleibt die **JavaScript-Engine die empfohlene Laufzeit für semantische Suchpipelines**. Aktivieren Sie die Rust-Engine selektiv für große Git- und Dateiverarbeitungs-Workloads. --- ## [Installation](https://docs.docmd.io/de/getting-started/installation/) --- title: "Installation" description: "Installieren Sie @docmd/core global, lokal in einem Projekt oder führen Sie es containerisiert über das offizielle Docker-Image aus. Benötigt Node.js 18+." --- Wählen Sie die Installationsmethode, die zu Ihrem Workflow passt. Node.js 18 oder höher ist für lokale Builds erforderlich. ## 1. Lokale Installation (empfohlen) Die lokale Ausführung von `docmd` hält Ihre Dokumentationskonfiguration mit Ihrem Quellcode versioniert. ::: tabs == tab "npm" icon:box ```bash # Als Entwicklungsabhängigkeit installieren npm install -D @docmd/core # Ein neues Projekt initialisieren npx docmd init ``` == tab "pnpm" icon:boxes ```bash # Als Entwicklungsabhängigkeit installieren pnpm add -D @docmd/core # Ein neues Projekt initialisieren pnpm dlx docmd init ``` == tab "yarn" icon:scroll ```bash # Als Entwicklungsabhängigkeit installieren yarn add -D @docmd/core # Ein neues Projekt initialisieren yarn dlx docmd init ``` == tab "Bun" icon:zap ```bash # Als Entwicklungsabhängigkeit installieren bun add -D @docmd/core # Ein neues Projekt initialisieren bunx docmd init ``` == tab "Docker" icon:container ```bash # Ziehen Sie das offizielle Multi-Architektur-Image docker pull ghcr.io/docmd-io/docmd:latest # Dokumentation von lokalem docs/ nach site/ erstellen docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` Siehe [Leitfaden zur Docker-Bereitstellung](../deployment/docker.md) für Docker Compose und Kubernetes-Konfigurationen. ::: <img width="500" class="with-border" src="/assets/previews/terminal-npx-init.webp"> ::: callout tip "Kurzbefehle" icon:sparkles Nach der lokalen Installation können Sie `npx docmd dev` verwenden, um den Live-Vorschau-Server zu starten, oder Skripte direkt zu Ihrer `package.json` hinzufügen. ::: ## 2. Globale Installation Installieren Sie das Paket global, um überall auf Ihrem System Websites zu erstellen oder in der Vorschau anzuzeigen, ohne ein lokales Projekt anzulegen. ::: tabs == tab "npm" icon:box ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: Nach der Installation ist die `docmd`-Binärdatei überall verfügbar: ```bash docmd dev # Lokalen Entwicklungsserver starten docmd build # Statische Ausgabe erstellen ``` ## 3. Nur-Browser-Integration Betten Sie die Engine direkt über ein CDN in eine bestehende Web-Anwendung ein. ::: callout info "Spezialisierte Bibliotheksintegration" icon:help-circle Dies umgeht die CLI und lädt die Parsing-Engine im Browser des Lesers. Verwenden Sie dies für dynamische Portale, nicht für statische SEO-Websites. ::: Fügen Sie das Stylesheet und die JavaScript-Engine zu Ihrem HTML hinzu. ```html <!-- Haupt-Stylesheet --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Isomorphe Rendering-Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` Siehe [Leitfaden zur Browser-API](../api/browser-api.md) für vollständige Integrationsdetails. ## 4. Fehlerbehebung ### Berechtigung verweigert (`EACCES`-Fehler) Verwenden Sie nicht `sudo` für globale Installationen unter macOS oder Linux. Beheben Sie Berechtigungskonflikte mit einem Node.js-Versionsmanager wie [nvm](https://github.com/nvm-sh/nvm) oder [fnm](https://github.com/Schniz/fnm). ### PowerShell-Ausführungsrichtlinien (Windows) Wenn Windows die Ausführung blockiert, öffnen Sie PowerShell als Administrator und aktivieren Sie die Ausführung von Skripten für den aktuellen Benutzer. ```powershell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser ``` --- ## [Projektstruktur](https://docs.docmd.io/de/getting-started/project-structure/) --- title: "Projektstruktur" description: "Erfahren Sie, wie `@docmd/core` physische Ordner und Markdown-Dateien auf dynamische URLs und eine saubere Navigation abbildet." --- Der Compiler verwendet Ihr lokales Dateisystem als Quelle der Wahrheit. Ordner werden zu Navigationsabschnitten, Markdown-Dateien zu Inhaltsseiten. Ihre Verzeichnishierarchie wird direkt in Web-URLs übersetzt. ## 1. Standard-Projektgerüst Führen Sie `npx @docmd/core init` aus, um ein minimales Workspace-Layout zu erstellen. Diese Struktur trennt Quellinhalte von Assets und Produktions-Builds. ```text my-docs/ ├── docs/ ← Quellverzeichnis mit Ihren Markdown-Seiten (.md) │ └── index.md ← Die Startseite (wird zu / aufgelöst) ├── assets/ ← Statische Web-Assets, die direkt von der Engine geladen werden │ ├── css/ ← Eigene Stylesheets zur Anpassung des Seitenlayouts │ ├── js/ ← Eigene Skripte zur Erweiterung der clientseitigen Logik │ └── images/ ← Markenlogos, Icons und eingebettete Grafiken ├── docmd.config.json ← Zentrales Konfigurationsschema ├── package.json ← Node-Abhängigkeitsmanifest und Skripte └── site/ ← Optimiertes Produktions-Build-Ausgabeverzeichnis ``` ::: callout info "Auflösung der Konfigurationsdatei" icon:settings `docmd.config.json` (oder `docmd.config.ts`) ist das empfohlene primäre Konfigurationsformat. Das veraltete `docmd.config.js`-Format wird weiterhin unterstützt, dient jedoch nur als Ausweichlösung, wenn keine `.json`- oder `.ts`-Konfigurationsdateien vorhanden sind. ::: ## 2. Zuordnung von Verzeichnissen und URLs Der Compiler ordnet Dateien in Ihrem Quellordner direkt öffentlichen URLs zu. Es gibt keine nachgestellten `.html`-Erweiterungen oder komplexe Routing-Regeln. | Quelldatei | Aufgelöster URL-Pfad | Zweck | | :--- | :--- | :--- | | `docs/index.md` | `/` | Startseite | | `docs/api.md` | `/api` | Haupt-API-Referenz | | `docs/guides/setup.md` | `/guides/setup` | Technischer Leitfaden für Unterabschnitt | | `docs/getting-started/quick-start.md` | `/getting-started/quick-start` | Mehrstufige Inhaltsseite | ::: callout tip "Automatische Überschriftenanalyse" icon:info Wenn eine Datei keinen `title` im YAML-Frontmatter enthält, extrahiert die Engine die erste `H1`-Überschrift (`# Überschrift`). Dieser Titel repräsentiert die Seite in Breadcrumbs und der Suche. ::: ## 3. Workspace-Monorepo-Struktur Für komplexe Layouts oder große Projekte mit mehreren unterschiedlichen Produkten (wie einer Kernplattform, einem SDK und einem CLI-Tool) unterstützt `docmd` nativ eine **Workspace-Monorepo**-Verzeichnisstruktur. Dies ermöglicht es Ihnen, mehrere unabhängige Dokumentations-Websites aus einem einzigen Root-Repository zu verwalten und gleichzeitig ein einheitliches Branding beizubehalten. ```text my-docs-monorepo/ ├── docmd.config.json ← Root-Konfiguration (definiert globale Einstellungen) ├── assets/ ← Gemeinsam genutzte globale Assets (von allen Projekten geerbt) │ ├── css/ ← Gemeinsam genutzte globale Stylesheets │ └── images/ ← Gemeinsam genutzte logos und Icons ├── package.json ← Root-Abhängigkeitsmanifest ├── main-site/ ← Hauptprojekt-Verzeichnis │ ├── docmd.config.json ← Projektspezifische Konfigurations-Überschreibungen │ └── docs/ ← Inhalt für Hauptprojekt (wird zu / aufgelöst) │ └── index.md └── sdk-reference/ ← Sekundäres Projektverzeichnis ├── docmd.config.json ← Projektspezifische Konfigurations-Überschreibungen └── docs/ ← Inhalt für SDK-Referenz (wird zu /sdk aufgelöst) └── index.md ``` ### Wichtige Workspace-Verzeichnismuster * **Vererbung der globalen Konfiguration:** Jede in der Root-Datei `docmd.config.json` definierte Konfiguration (wie `theme` oder `menubar`) dient als Standard-Fallback. Einzelne Projekte können diese Standards in ihren eigenen lokalen Konfigurationsdateien gezielt überschreiben. * **Asset-Freigabe und Priorität:** Gemeinsame Logos, globale benutzerdefinierte Stile und gemeinsame Skripte werden im globalen `assets/`-Verzeichnis abgelegt. Projekte können auch eigene lokale `assets/`-Verzeichnisse definieren; bei Namenskonflikten haben projektspezifische Assets immer vorrang. * **Konsolidierung der Ausgabe:** Während des Build-Prozesses (`npx @docmd/core build`) führt die Engine automatisch alle Projekte in einem einzigen konsolidierten Produktions-Ausgabeverzeichnis zusammen (z. B. `./site/` und `./site/sdk/`), wodurch komplexe Setups mit Reverse-Proxies oder isolierten Build-Pipelines entfallen. Ausführliche Einrichtungsschritte und fortgeschrittene Vererbungsregeln finden Sie im [Leitfaden zur Workspace-Konfiguration](../configuration/workspaces.md). --- ## [Schnellstart](https://docs.docmd.io/de/getting-started/quick-start/) --- title: "Schnellstart" description: "Gelangen Sie in weniger als einer Minute von einem leeren Ordner zu einer laufenden Dokumentationsseite." --- Führen Sie docmd in jedem Ordner aus, der Markdown-Dateien enthält. Keine Konfigurationsdatei, kein Setup, keine Framework-Kenntnisse erforderlich. ## 1. Entwicklungsserver starten ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: Öffnet `http://localhost:3000`. Ihre Dokumentation ist live. <img width="500" class="with-border" src="/assets/previews/terminal-npx-dev.webp"> ::: callout tip "Automatische Port-Umleitung" Wenn Port `3000` bereits verwendet wird, findet docmd automatisch den nächsten verfügbaren Port (z. B. `3001`). ::: ## 2. Automatische Funktionen Die Engine richtet alles automatisch ein: 1. **Ordnererkennung** - Sucht nach `docs/`, `src/docs/`, `documentation/` oder `.md`-Dateien. 2. **Navigationserstellung** - Erstellt eine verschachtelte Seitenleiste aus Ihrer Ordnerstruktur. 3. **Titel-Auflösung** - Extrahiert automatisch Seitentitel aus dem ersten `H1`-Tag. 4. **Suchindexierung** - Aktiviert sofort die integrierte Volltextsuche. 5. **Intelligentes Caching** - Erzeugt beim Speichern sub-200ms-Neuerstellungen. Es wird keine `docmd.config.json` benötigt. Fügen Sie später eine hinzu, um Layouts, Plugins oder Versionen anzupassen. ## 3. Für die Produktion erstellen Kompilieren Sie Ihre Markdown-Dateien in eine statische, produktionsreife Website. ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: Der Compiler gibt eine statische Website in `./site/` aus. Hosten Sie diese statische Ausgabe überall. Stellen Sie auf GitHub Pages, Vercel, Netlify oder einem anderen statischen Host bereit. --- ## [Kontexterhaltung für KI-freundliche Dokumentation](https://docs.docmd.io/de/guides/ai-optimisation/context-preservation/) --- title: "Kontexterhaltung für KI-freundliche Dokumentation" description: "Wie Sie sicherstellen, dass KI-Modelle die Beziehungen zwischen verschiedenen Teilen Ihrer Dokumentation verstehen und nutzen können." --- ## Problem Während menschliche Leser problemlos auf einen Hyperlink klicken können, um mehr über einen Begriff zu erfahren, verarbeiten KI-Modelle Dokumentationen oft in isolierten "Chunks" (Stücken). Wenn eine KI auf einen Hyperlink stößt, kann sie ihn nicht "anklicken", um mehr Kontext abzurufen. Wenn kritische Informationen hinter einem Link verborgen sind, anstatt im Kontext erklärt zu werden, kann die KI möglicherweise keine genauen Antworten liefern, was zu Halluzinationen führt. ## Warum es wichtig ist KI-Modelle verlassen sich auf den unmittelbar umgebenden Text, um die Bedeutung und Relevanz von Informationen zu bestimmen. Wenn Ihre Dokumentation stark fragmentiert ist und eine schlechte Kontexterhaltung aufweist, werden KI-gesteuerte Suchwerkzeuge (wie solche, die auf RAG basieren) Schwierigkeiten haben, qualitativ hochwertige Antworten zu liefern. ## Ansatz Verwenden Sie **Inline Context Unrolling** (kontextuelles Entfalten im Text), um neben jedem wichtigen Link den minimal lebensfähigen Kontext bereitzustellen. Nutzen Sie außerdem die spezifischen Funktionen von `docmd`, wie das [LLMs-Plugin](../../plugins/llms.md), um eine einheitliche, maschinenlesbare Ansicht Ihres gesamten Dokumentationssatzes bereitzustellen. ## Implementierung ### 1. Beschreibende Verlinkung und Zusammenfassungen Vermeiden Sie generische Linktexte. Stellen Sie stattdessen eine kurze, einseitige Zusammenfassung des verlinkten Konzepts vor oder nach dem Link selbst bereit. - **❌ Schlecht (Kontext verloren)**: Um das Timeout zu konfigurieren, lesen Sie die [Allgemeine Konfiguration](../../configuration/overview.md). - **✅ Besser (Kontext erhalten)**: Sie können den Parameter `timeoutMs` in der [Allgemeinen Konfiguration](../../configuration/overview.md) konfigurieren, der definiert, wie lange die Engine wartet, bevor eine Netzwerkanfrage fehlschlägt. ### 2. Verwendung von ausklappbaren Abschnitten für Details [Ausklappbare Container](../../content/containers/collapsible.md) eignen sich hervorragend für die KI-Optimierung. Der Inhalt bleibt Teil des rohen Markdown-Quellcodes (den die KI lesen kann), wird aber für menschliche Leser visuell verstaut. ```markdown ### Datenbankverbindung Stellen Sie die Verbindung über den primären URI her. ::: collapsible "Wie lautet das URI-Format?" Der URI folgt dem standardmäßigen PostgreSQL-Format: `postgresql://benutzer:passwort@host:port/datenbank`. ::: ``` ### 3. Aktivierung des LLMs-Plugins Aktivieren Sie das [LLMs-Plugin](../../plugins/llms.md) in Ihrer `docmd.config.js`. Dieses Plugin generiert nach jedem Build automatisch eine `llms-full.txt`-Datei, die Ihren gesamten Dokumentationssatz in einer einzigen Datei mit hohem Kontextgehalt zusammenfasst, die leicht von Large Language Models verarbeitet werden kann. ## Abwägungen Inline Context Unrolling macht Ihre Dokumentation etwas wortreicher und führt zu geringfügigen Redundanzen. Diese Redundanz ist jedoch ein kleiner Preis für die Sicherstellung, dass Ihre Dokumentation "KI-bereit" ist und in der Lage ist, qualitativ hochwertige automatisierte Support- und Sucherlebnisse zu ermöglichen. --- ## [Erstellung deterministischer und chunkbarer Dokumentation](https://docs.docmd.io/de/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "Erstellung deterministischer und chunkbarer Dokumentation" description: "So strukturieren Sie Ihre Dokumentation, um sie für Retrieval-Augmented Generation (RAG) und die KI-Verarbeitung zu optimieren." --- ## Problem Wenn KI-Pipelines (wie RAG-Architekturen) Dokumentationen aufnehmen, schneiden sie die Markdown-Quelle in kleinere "Chunks" (z. B. jeweils 500 Token). Wenn ein Dokument aus langen, ausschweifenden Absätzen mit unklaren Grenzen besteht, kann der Slicing-Algorithmus den Kontext mitten im Gedanken trennen. Dies zerstört den Nutzen des Chunks und führt zu unvollständigen oder falschen KI-Antworten. ## Warum es wichtig ist Wenn eine KI einen Chunk abruft, der einen Code-Block enthält, aber den vorangehenden Absatz verpasst, der erklärt, *wann* dieser Code zu verwenden ist, wird der generierten Antwort die notwendige Konditionalität fehlen. Die Strukturierung Ihrer Dokumentation nach "Chunkbarkeit" stellt sicher, dass jeder Textabschnitt genügend Kontext enthält, um für sich allein nützlich zu sein. ## Ansatz Strukturieren Sie Ihre Seiten als Hierarchie deterministischer, atomarer Blöcke. Nutzen Sie Markdown-Überschriften, um Konzepte klar voneinander abzugrenzen, und stellen Sie sicher, dass zusammengehörige Informationen (wie eine Warnung und der dazugehörige Code) in der Quelldatei physisch nah beieinander liegen. ## Implementierung ### 1. Atomare Überschriften-Abschnitte Stellen Sie sicher, dass jede `##`- oder `###`-Überschrift ein einzelnes, atomares Konzept kapselt. Ein gut strukturierter Abschnitt sollte als nützlicher Chunk für ein KI-Modell allein stehen können. - **✅ Gut**: Eine Überschrift "Authentifizierung via OAuth", gefolgt von einer kurzen Erklärung und einem Code-Beispiel. - **❌ Schlecht**: Eine massive "Getting Started"-Seite mit 15 verschiedenen Konzepten ohne Unterüberschriften. ### 2. Räumliche Nähe für kritische Informationen Trennen Sie eine kritische Warnung nicht durch lange Absätze von dem Code, auf den sie sich bezieht. Nutzen Sie [Callouts](../../content/containers/callouts), um sie vertikal aneinander zu binden. Dies erhöht die Wahrscheinlichkeit, dass sie bei der Verarbeitung im selben Vektor-Chunk bleiben. ```markdown ::: callout warning "Destruktive Aktion" Das Ausführen dieses Befehls löscht permanent alle Logs. ::: `docmd logs --clear` ``` ### 3. Automatisierte Zusammenführung Das [LLMs-Plugin](../../plugins/usage) erleichtert das Chunking, indem es eine `llms-full.txt`-Datei generiert. Diese Datei nutzt Standard-Trenner (`---`) zwischen den Seiten und hilft Ingestions-Pipelines so dabei, natürliche Dokumentgrenzen zu erkennen, während der globale Kontext Ihres Projekts erhalten bleibt. ## Abwägungen Dieser Ansatz bevorzugt einen modularen, segmentierten Schreibstil gegenüber langen, fließenden Erzählungen. Während sich dies für einen menschlichen Leser repetitiver anfühlen mag, verbessert es die Leistung von KI-gestützten Suchvorgängen und automatisierten Support-Agenten, die auf Ihre Dokumentation angewiesen sind, erheblich. --- ## [Erstellung von KI-bereiter Dokumentation mit docmd](https://docs.docmd.io/de/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "Erstellung von KI-bereiter Dokumentation mit docmd" description: "So nutzen Sie den llms.txt-Standard und die integrierten Tools von docmd, um optimierten Kontext für KI-Assistenten bereitzustellen." --- ## Problem Entwickler verlassen sich zunehmend auf KI-Coding-Assistenten (wie Cursor, GitHub Copilot und ChatGPT), um Dokumentationen für sie zu lesen und zu interpretieren. Wenn Ihre Dokumentation nur über einen Webbrowser zugänglich ist und mit Navigationselementen, Trackern und komplexem HTML überladen ist, verbrauchen KI-Agenten unnötig viele Token für irrelevante Daten, was ihre Kontextfenster schnell erschöpft. ## Warum es wichtig ist Die Bereitstellung einer sauberen, Token-optimierten Textversion Ihrer Dokumentation ist das moderne Äquivalent zur Bereitstellung einer hochwertigen REST-API. Sie stellt sicher, dass KI-Agenten Ihren gesamten Dokumentationssatz schnell aufnehmen können, was zu genaueren Code-Vorschlägen und einem besseren Support für Entwickler führt, die Ihr Produkt nutzen. ## Ansatz Nutzen Sie das integrierte **LLMs-Plugin** von `docmd`. Dieses Plugin implementiert nativ den aufkommenden `llms.txt`-Standard und generiert bei jedem Build-Prozess automatisch Token-optimierte Zusammenfassungen und Vollkontext-Dateien. ## Implementierung Das `llms`-Plugin ist in `docmd >= 0.7.0` verfügbar und kann in Ihrer [Plugin-Konfiguration](../../plugins/usage) konfiguriert werden. ### 1. Konfiguration der Website-URL Stellen Sie sicher, dass die Eigenschaft `url` in Ihrer `docmd.config.json` korrekt gesetzt ist. Dies ermöglicht es dem Plugin, absolute URLs für alle Seiten in der Datei `llms.txt` zu generieren. ```json { "title": "Mein Projekt Docs", "url": "https://docs.example.com", "plugins": { "llms": {} } } ``` ### 2. Ausgabedateien Während des Build-Prozesses generiert `docmd` zwei wichtige Dateien im Root-Verzeichnis Ihrer Website: - **`llms.txt`**: Eine prägnante, strukturierte Markdown-Zusammenfassung aller Ihrer Seiten, einschließlich ihrer Titel, Beschreibungen und vollständigen URLs. - **`llms-full.txt`**: Eine umfassende Datei, die den rohen Markdown-Inhalt Ihrer gesamten Website enthält, zusammengeführt durch Standard-Trenner (`---`). Dies bietet die ultimative "Source of Truth" für KI-Modelle. ### 3. Steuerung der Verarbeitung Sie können bestimmte Seiten von der KI-bereiten Ausgabe ausschließen, indem Sie die Eigenschaft `llms` im [Seiten-Frontmatter](../../content/frontmatter) verwenden. ```yaml --- title: "Interner Debugging-Leitfaden" llms: false --- ``` ## Abwägungen Die Generierung von `llms-full.txt` erzeugt eine einzige, sehr große Datei. Bei außergewöhnlich umfangreichen Dokumentations-Websites kann diese Datei mehrere Megabyte groß werden. Während dies ideal für moderne LLMs mit großen Kontextfenstern (wie Gemini 1.5 Pro oder Claude 3.5 Sonnet) ist, kann sie für kleinere Modelle zu groß sein. Stellen Sie sicher, dass Sie Ihre [Navigation](../../configuration/navigation) logisch strukturieren, damit die KI die wichtigsten Abschnitte priorisieren kann. --- ## [MCP & Agent-Skills](https://docs.docmd.io/de/guides/ai-optimisation/mcp-and-agent-skills/) --- title: "MCP & Agent-Skills" description: "Optimieren Sie Ihren Dokumentations-Workspace für KI-Entwicklungs-Agenten mithilfe des Model Context Protocols und benutzerdefinierter Skills." --- Die Integration von KI-Entwicklungs-Agenten in Ihren Arbeitsablauf erfordert strukturierte Schnittstellen, über die Modelle den Dokumentationskontext effizient abfragen, lesen und schreiben können. `docmd` erfüllt diese Anforderung durch einen nativen **Model Context Protocol (MCP)** Server und eine erweiterbare **Agent Skills**-Datenbank. ## Einrichtung des Model Context Protocols (MCP) Das Model Context Protocol verbindet LLM-Umgebungen direkt mit den Tools Ihres lokalen Workspaces. ### 1. Claude Desktop Integration Fügen Sie Folgendes zu Ihrer Desktop-Konfigurationsdatei hinzu (normalerweise unter `~/Library/Application Support/Claude/claude_desktop_config.json` unter macOS oder `%APPDATA%\Claude\claude_desktop_config.json` unter Windows): ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/pfad/zu/ihrem/docs/projekt" } } } ``` ### 2. IDE-Integration (Cursor / Windsurf) Fügen Sie im MCP-Einstellungsbereich Ihres Editors einen neuen Server hinzu, der den `stdio`-Transport verwendet: - **Befehl (Command)**: `npx @docmd/core mcp` - **Transport**: `stdio` ## Verfügbare MCP-Werkzeuge Nach erfolgreicher Verbindung stehen dem Agenten folgende Tools zur Verfügung: 1. `search_docs(query)`: Führt eine workspace-weite Volltextsuche durch. 2. `read_doc(route)`: Ruft den rohen Markdown-Inhalt einer bestimmten Route ab. 3. `validate_docs()`: Linter für die gesamte Dokumentation und gibt Validierungsfehler zurück (z. B. fehlerhafte Links). 4. `get_llms_context()`: Ruft die konsolidierte Kontextdatei `llms-full.txt` ab. ## Nutzung von Agent-Skills (`SKILL.md`) Wenn Sie `docmd init` in Ihrem Projekt ausführen, generiert die Engine automatisch eine `SKILL.md`-Datei in Ihrem Workspace-Stammverzeichnis. Diese Datei dient als Prompt-Instruktionskarte für jeden KI-Agenten, der an Ihrem Repository arbeitet. ### Best Practices für KI-Agenten 1. **Zuerst SKILL.md lesen**: Weisen Sie Ihre Agenten an, zu Beginn einer Codierungssitzung die Datei `SKILL.md` zu lesen. Dies vermittelt dem Modell die Nutzung von benutzerdefinierten Callouts, OpenAPI-Markup und Dateistrukturen. 2. **Nach Bearbeitungen validieren**: Wann immer ein Agent Markdown-Dateien ändert, sollte er das Tool `validate_docs` aufrufen (oder `npx @docmd/core validate` ausführen), um sicherzustellen, dass keine relativen Links oder Ankerpfade fehlerhaft sind. 3. **Sprachen synchronisieren**: Wenn das Projekt Versionierung oder mehrere Sprachen verwendet, sollten Agenten die Vergleichsmatrix nutzen, um sicherzustellen, dass alle Übersetzungen synchron bleiben. --- ## [Minimierung von KI-Halluzinationen durch Dokumentation](https://docs.docmd.io/de/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "Minimierung von KI-Halluzinationen durch Dokumentation" description: "So schreiben Sie explizite, in sich geschlossene Dokumentationen, die verhindern, dass KI-Modelle falsche Informationen erfinden." --- ## Problem KI-Modelle sind Vorhersagesysteme, keine Logiksysteme. Wenn ein API-Anwendungsbeispiel unvollständig ist, mehrdeutige Platzhalter verwendet oder auf implizitem Wissen beruht, wird die KI oft "halluzinieren" , sie erfindet die fehlenden Teile basierend auf allgemeinen Mustern, die sie während des Trainings gelernt hat. Diese Erfindungen sind für Ihre spezifische Software häufig falsch, was zu Frustration bei den Entwicklern führt. ## Warum es wichtig ist Halluzinierter Code zerstört das Vertrauen der Nutzer. Wenn ein Entwickler eine KI um Hilfe bittet und Code erhält, der einen Syntaxfehler auslöst oder nicht existierende Parameter verwendet, macht er oft die Software selbst für die "Fehlerhaftigkeit" oder "schlechte Dokumentation" verantwortlich. Die Minimierung von Halluzinationen ist entscheidend für den professionellen Ruf Ihres Projekts. ## Ansatz Praktizieren Sie **Defensive Dokumentation**. Dies bedeutet, extrem explizite, vollständig instanziierte Codeblöcke zu schreiben, die keinen Raum für Mehrdeutigkeiten lassen. Gehen Sie niemals davon aus, dass der Leser (oder die KI) die erforderlichen Imports, Umgebungsvariablen oder vorausgesetzten Konfigurationen kennt. ## Implementierung ### 1. Vollständig qualifizierte Codeblöcke Fügen Sie in jedem Snippet die erforderlichen Imports oder den Setup-Code ein. Dies stellt sicher, dass der Codeblock eine in sich geschlossene Einheit der Wahrheit bleibt, wenn eine KI Ihre Dokumentation in Chunks zerlegt. - **❌ Halluzinations-Risiko**: ```javascript const config = loadConfig(); // Woher kommt loadConfig? ``` - **✅ Halluzinations-Sicher**: ```javascript import { loadConfig } from '@docmd/core'; const config = loadConfig(); ``` ### 2. Konkrete Beispiele statt Platzhalter Vermeiden Sie vage Platzhalter wie `ihr-api-key` oder `env-name`. Geben Sie stattdessen konkrete, gültige Beispiele an oder nutzen Sie Kommentare, um strikte Enum-Anforderungen zu spezifizieren. ```javascript // Gültige Umgebungen: "development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. Inline-Code-Kommentare Platzieren Sie kritische Anforderungen als Kommentare *innerhalb* des Codeblocks, anstatt nur im umgebenden Markdown-Text. KI-Modelle bewerten Kommentare innerhalb des Codes bei der Generierung ähnlicher Snippets sehr hoch. ```javascript // ERFORDERLICH: Muss ein absoluter Dateisystempfad sein. outputPath: "/var/www/html/docs" ``` ### 4. Kategorisierte Warnungen Nutzen Sie [Callouts](../../content/containers/callouts), um veraltete Funktionen oder bahnbrechende Änderungen (Breaking Changes) klar zu markieren. KI-Modelle halten sich eher an einen `::: callout warning`-Block als an einen einfachen Satz in einem Absatz. ## Abwägungen Defensive Dokumentation macht Codeblöcke länger und repetitiver. Menschliche Leser empfinden es vielleicht als etwas ermüdend, in jedem Snippet dieselben `import`-Anweisungen zu sehen. Der Vorteil einer "KI-sicheren" Dokumentation, die Support-Tickets und Benutzerfehler deutlich reduziert, überwiegt jedoch bei weitem die geringen Kosten der Wortreichtum. --- ## [Design für semantische Suche und RAG](https://docs.docmd.io/de/guides/ai-optimisation/semantic-search-design/) --- title: "Design für semantische Suche und RAG" description: "So strukturieren Sie Ihre Dokumentation, um sie für die vektorbasierte Suche und Retrieval-Augmented Generation zu optimieren." --- ## Problem Die herkömmliche Stichwortsuche (wie die [integrierte Suche von docmd](../../plugins/search)) verlässt sich auf exakte Texttreffer. Wenn ein Benutzer nach "Authentifizierung" sucht, findet eine einfache Keyword-Engine eine Seite mit dem Titel "Integration von OAuth2" unter Umständen nicht, falls dieses spezifische Wort nicht oft genug vorkommt. Die semantische Suche, die Vektor-Embeddings nutzt, um die *Bedeutung* einer Abfrage zu verstehen, löst dieses Problem, erfordert jedoch spezifische Dokumentationsstrukturen, um effektiv zu sein. ## Warum es wichtig ist Entwickler von heute erwarten intuitive, intent-basierte Sucherlebnisse. Wenn Ihre Dokumentation relevante Inhalte aufgrund geringfügiger terminologischer Unterschiede nicht anzeigt, werden Benutzer Ihre Seite schnell verlassen und woanders Hilfe suchen. Ein Design für die semantische Suche stellt sicher, dass Ihre Dokumentation auffindbar bleibt, selbst wenn Benutzer unterschiedliche Begriffe verwenden. ## Ansatz Strukturieren Sie Ihre Dokumentation so, dass sie leicht von Retrieval-Augmented Generation (RAG)-Pipelines verarbeitet werden kann. Dies beinhaltet die Erstellung "semantisch dichter" Inhalte, in denen Konzepte klar definiert sind und Pronomen durch explizite Begriffe ersetzt werden, um den Kontext während des Chunking- und Vektorisierungsprozesses zu erhalten. ## Implementierung ### 1. Reichhaltige Frontmatter-Metadaten Nutzen Sie [Frontmatter](../../content/frontmatter), um explizite Schlüsselwörter und Beschreibungen bereitzustellen, die im Fließtext vielleicht nicht natürlich vorkommen würden. Dies gibt der Suchmaschine zusätzliche Anhaltspunkte für Ihren Inhalt. ```yaml --- title: "Integration von OAuth2" description: "Erfahren Sie, wie Sie sichere Benutzerauthentifizierung und SSO implementieren." keywords: ["login", "authentifizierung", "sso", "security", "identity"] --- ``` ### 2. Die "Semantische Dichte"-Strategie RAG-Systeme zerlegen Dokumente in kleine Stücke (Vektoren). Der erste Absatz jedes Abschnitts sollte die höchste Dichte an relevanten Substantiven und Verben zu diesem Thema enthalten. Dies stellt sicher, dass die primäre "Bedeutung" des Abschnitts bereits im initialen Vektor erfasst wird. - **✅ Gut**: "Dieser Leitfaden erklärt, wie Sie **OAuth2 Single Sign-On (SSO)** implementieren, um eine sichere **Authentifizierung** für Ihre Dokumentationsseite bereitzustellen." - **❌ Schlecht**: "In diesem Abschnitt sprechen wir darüber, wie es funktioniert und wie Sie es einfach einrichten können." ### 3. Vermeidung von mehrdeutigen Pronomen In einer zerlegten Datenbank ist ein Satz wie "Es funktioniert mit jedem Anbieter" nutzlos, wenn der vorangehende Absatz, der "Es" definiert, in einen anderen Chunk geschnitten wurde. Seien Sie explizit. - **❌ Mehrdeutig**: "Es ist hochgradig skalierbar." - **✅ Explizit**: "Die **docmd Search Engine** ist so konzipiert, dass sie hochgradig skalierbar ist." ## Abwägungen Das Schreiben für semantische Dichte kann sich manchmal etwas formeller oder repetitiver anfühlen als herkömmliches narratives Schreiben. Die daraus resultierende Verbesserung der Auffindbarkeit und der Genauigkeit von KI-generierten Antworten macht dies jedoch zu einer unverzichtbaren Praxis für moderne, professionelle Dokumentationen. --- ## [Strukturierung der Dokumentation für KI-Agenten](https://docs.docmd.io/de/guides/ai-optimisation/structure-for-llms/) --- title: "Strukturierung der Dokumentation für KI-Agenten" description: "Wie Sie von visueller Formatierung zu semantischer Strukturierung übergehen, um die Genauigkeit von KI-Codierungsassistenten zu verbessern." --- ## Problem Menschliche Leser verlassen sich auf visuelle Hinweise, die Navigation in der Seitenleiste und abgeleiteten Kontext, um Dokumentationen zu verstehen. KI-Agenten und Large Language Models (LLMs) konsumieren jedoch primär rohe Textströme. Wenn einer Dokumentation eine strenge semantische Struktur fehlt, haben diese Modelle Schwierigkeiten, Beziehungen zwischen Konzepten abzubilden, was zu mangelhaften Schlussfolgerungen und ungenauen Codierungsvorschlägen führt. ## Warum es wichtig ist Wenn Ihre Dokumentation nicht für LLMs optimiert ist, werden Entwickler, die Tools wie GitHub Copilot, Cursor oder ChatGPT verwenden, bei der Arbeit mit Ihrer Software mehr Halluzinationen erleben. Dies verschlechtert direkt die Entwicklererfahrung, da Benutzer oft das Produkt selbst für die von ihren KI-Assistenten generierten Fehler verantwortlich machen. ## Ansatz Wechseln Sie von einer "Visual-First"-Mentalität zu einer **"Semantic-First"**-Mentalität. Verwenden Sie Standard-Markdown-Funktionen - wie strenge Überschriftenhierarchien, explizite Sprach-Tags für Codeblöcke und beschreibende Alt-Texte - , um einen klaren, maschinenlesbaren Fahrplan für Ihre Inhalte bereitzustellen. `docmd` verarbeitet diese Struktur über das [LLMs-Plugin](../../plugins/llms.md) zu optimierten Ausgaben. ## Implementierung ### 1. Strenge Überschriftenhierarchie Vermeiden Sie es, Überschriftenebenen nur für rein visuelle Effekte zu überspringen. Eine konsistente Hierarchie ermöglicht es LLMs, den Umfang und die Beziehung verschiedener Abschnitte zu verstehen. - **`#` Titel**: Das Hauptthema der Seite. - **`##` Hauptkonzept**: Ein atomares, übergeordnetes Thema. - **`###` Detail**: Eine spezifische Teilaufgabe oder Eigenschaft dieses Konzepts. * **❌ Schlecht**: Die Verwendung von `###` unmittelbar nach `#`, nur weil Ihnen die kleinere Schriftgröße gefällt. * **✅ Gut**: `# Installation` gefolgt von `## Voraussetzungen` und dann `### Systemanforderungen`. ### 2. Beschreibende Metadaten für Medien Da LLMs Bilder oder Diagramme nicht "sehen" können, müssen Sie den architektonischen Kontext im Alternativtext oder einem angrenzenden Absatz bereitstellen. ```markdown ![Systemarchitektur: Die Frontend-React-Anwendung kommuniziert über REST mit der Node.js-API, die wiederum einen Redis-Cache und eine PostgreSQL-Datenbank abfragt.](../../static/img/architecture.png) ``` ### 3. Explizite Kennzeichnung von Codeblöcken Geben Sie für jeden Fenced Code Block immer die Sprache mithilfe von [Syntax Highlighting](../../content/syntax/index.md) an. Dies ermöglicht es LLMs, den Abstract Syntax Tree (AST) des Codes korrekt zu parsen. ```json { "plugins": { "llms": {} } } ``` ### 4. Semantische Container Verwenden Sie [Callouts](../../content/containers/callouts.md) anstelle von generischen Blockzitaten, um eine Absicht (Intent) zu vermitteln. Die semantischen Container von `docmd` helfen KI-Modellen, zwischen Kernanweisungen und ergänzenden Tipps oder Warnungen zu unterscheiden. ## Abwägungen Semantische Strenge erfordert Disziplin von den Autoren. Sie können Markdown-Funktionen (wie Blockzitate oder Überschriften) nicht mehr als rein dekorative Elemente verwenden. Diese Disziplin führt jedoch zu einer Dokumentation, die sowohl für KI-Agenten als auch für menschliche Leser, die assistierende Technologien verwenden, deutlich zugänglicher ist. --- ## [Anti-Patterns vermeiden](https://docs.docmd.io/de/guides/content-ux/avoiding-anti-patterns/) --- title: "Anti-Patterns vermeiden" description: "So identifizieren und eliminieren Sie häufige Dokumentationsfehler, welche die User Experience verschlechtern und \"Content Debt\" erhöhen." --- ## Problem Im Laufe der Zeit sammeln sich in Dokumentations-Repositories oft "Quick Fixes" für Content-Probleme an, welche die User Experience ungewollt verschlechtern. Diese Anti-Patterns , wie vage Linktexte oder überladene Codebeispiele , verfestigen sich im Projekt, was die Dokumentation schwerer wartbar und für Entwickler weniger nützlich macht. ## Warum es wichtig ist Anti-Patterns tragen zur "Content Debt" (Inhaltsschulden) bei. Sie verschlechtern das Ranking in Suchmaschinen (SEO), verringern die Barrierefreiheit für Menschen mit Behinderungen und erhöhen die kognitive Belastung für Leser erheblich, die lediglich eine schnelle Lösung für ein technisches Problem suchen. Eine qualitativ hochwertige Dokumentation erfordert ständige Wachsamkeit, um sie sauber, prägnant und professionell zu halten. ## Ansatz Identifizieren und eliminieren Sie gängige Anti-Patterns konsequent während des [Peer-Review-Prozesses](../workflows-teams/git-based-workflows.md). Nutzen Sie automatisierte Prose-Linter wie Vale sowie manuelle Reviews, um sicherzustellen, dass Ihre Inhalte auf allen Seiten hochwertig, zugänglich und konsistent bleiben. ## Implementierung ### 1. Nicht-descriptive Hyperlinks Vermeiden Sie generische Texte wie "hier klicken" oder "mehr lesen" für Links. Dies schadet der SEO und macht die Dokumentation unzugänglich für Nutzer von Screenreadern, die oft navigieren, indem sie von Link zu Link springen. * **❌ Schlecht**: Um Ihren Server zu konfigurieren, [klicken Sie hier](../../configuration/overview.md). * **✅ Gut**: Lesen Sie die [globale Konfiguration](../../configuration/overview.md), um Ihren Produktionsserver einzurichten. ### 2. Die "Wand aus Boilerplate" Das Einfügen dutzender Zeilen von Standard-Imports und Boilerplate-Konfiguration vor der eigentlichen Logik in Codebeispielen lenkt den Leser vom eigentlichen Punkt des Beispiels ab. * **Lösung**: Konzentrieren Sie sich auf das relevante Code-Snippet. Wenn Boilerplate für den Kontext notwendig ist, verwenden Sie Kommentare, um darauf hinzuweisen, dass Standard-Imports aus Gründen der Kürze weggelassen wurden, oder nutzen Sie [Callouts](../../content/containers/callouts.md), um das erforderliche Setup zu erläutern. ### 3. FAQs als "Müllhalde" nutzen "Häufig gestellte Fragen" (FAQ) werden oft zu einem Sammelbecken für Informationen, die zu schwierig in die Hauptanleitungen zu integrieren waren. Wenn eine Frage tatsächlich "häufig gestellt" wird, ist dies ein klares Zeichen dafür, dass Ihre Kerndokumentation dieses Konzept nicht effektiv erklärt hat. * **Lösung**: Anstatt die FAQ zu erweitern, sollten Sie das entsprechende Tutorial oder die konzeptionelle Anleitung überarbeiten, um die Unklarheit direkt dort zu beseitigen, wo der Benutzer sie zuerst bemerkt. Verwenden Sie einen [wichtigen Callout](../../content/containers/callouts.md), wenn die Information kritisch für den Erfolg ist. ## Abwägungen Das Eliminieren von FAQs erfordert von den Autoren, bestehende Dokumentationshierarchien ständig zu überarbeiten und zu verbessern, sobald neue Support-Themen auftauchen. Dies verursacht zwar mehr initialen Wartungsaufwand als das einfache Hinzufügen eines Stichpunkts zu einer FAQ-Liste, führt aber zu einer deutlich konsistenteren, professionelleren und nützlicheren Dokumentationsseite für Ihre Benutzer. --- ## [Verbesserung der Lesbarkeit](https://docs.docmd.io/de/guides/content-ux/improving-readability/) --- title: "Verbesserung der Lesbarkeit" description: "Wie Sie visuellen Rhythmus, Informationshierarchie und die strukturellen Werkzeuge von docmd nutzen, um hochgradig lesbare Dokumentationen zu erstellen." --- ## Problem Technische Dokumentationen sind oft dicht, fachsprachlich überladen und schwer zu scannen. Wenn Leser auf "Textwüsten" ohne visuelle Auflockerung stoßen, neigen sie dazu, wichtige Details zu überfliegen oder kritische Sicherheitswarnungen ganz zu übersehen. Eine dichte Formatierung erhöht die kognitive Belastung und führt zu Frustration beim Benutzer sowie potenziellen Fehlern. ## Warum es wichtig ist Lesbarkeit ist nicht nur eine ästhetische Entscheidung - sie ist eine funktionale Anforderung. Wenn ein Entwickler eine Warnung übersieht, weil sie in einem langen Absatz vergraben war, können die Folgen schwerwiegend sein. Eine klare Informationshierarchie stellt sicher, dass Benutzer die benötigten Informationen schnell finden, genau verstehen und sicher danach handeln können. ## Ansatz Etablieren Sie einen vorhersehbaren visuellen Rhythmus, indem Sie lange Textabschnitte aufbrechen und [thematische Container](../../content/containers/index.md) verwenden, um kritische Informationen hervorzuheben. Durch die Nutzung der integrierten strukturellen Werkzeuge von `docmd` können Sie eine Hierarchie erstellen, die das Auge des Lesers natürlich zu den wichtigsten Teilen der Seite führt. ## Implementierung ### 1. Die "Kraft der Kürze" Versuchen Sie, Absätze auf nicht mehr als drei oder vier Sätze zu beschränken. Kürzere Absätze sind auf Bildschirmen leichter zu erfassen und bieten natürlichen "Atemraum" für komplexe technische Konzepte. Wenn sich ein Absatz zu lang anfühlt, erwägen Sie, ihn in eine Liste aufzuteilen oder eine Unterüberschrift zu verwenden, um die Informationen neu zu kategorisieren. ### 2. Kategorisierung mit Callouts Verwenden Sie [Callouts](../../content/containers/callouts.md) konsistent, um Informationen zu kategorisieren. Dies ermöglicht es Benutzern, die den Text nur überfliegen, die Absicht eines Blocks anhand seines visuellen Stils sofort zu erkennen: * **Info**: Hintergrundkontext oder ergänzende Details, die ein tieferes Verständnis vermitteln. * **Tip**: Best Practices, Abkürzungen und "Pro-Tipps" für mehr Effizienz. * **Warning/Danger**: Kritische Aktionen, die zu Fehlern, Datenverlust oder Sicherheitsrisiken führen könnten. ```markdown ::: callout warning "Produktionssicherheit" Führen Sie diesen Befehl niemals an einer Live-Datenbank aus, ohne vorher Ihre Backups überprüft zu haben. ::: ``` ### 3. Sequenzielle Anweisungen mit Steps Vermeiden Sie bei Tutorials und Schritt-für-Schritt-Anleitungen narrative Beschreibungen von Aktionen. Verwenden Sie stattdessen den [Steps-Container](../../content/containers/steps.md), um einen klaren, nummerierten Ablauf zu erstellen, dem man leicht folgen kann. ```markdown ::: steps 1. **Initialisieren**: Führen Sie `npx @docmd/core init` im Projekt-Root aus. 2. **Konfigurieren**: Aktualisieren Sie Ihre `docmd.config.js` mit Ihrem Seitentitel und der Navigation. 3. **Build**: Führen Sie `npx @docmd/core build` aus, um Ihre produktionsreifen statischen Dateien zu generieren. ::: ``` ## Abwägungen Die Verwendung spezialisierter Container wie `::: steps` oder `::: callout` erfordert von den Mitwirkenden das Erlernen von `docmd`-spezifischen Markdown-Erweiterungen. Dies bedeutet zwar eine kleine Lernkurve, aber die signifikante Verbesserung der Informationsdichte, Klarheit und professionellen Präsentation überwiegt bei weitem den minimalen Aufwand für das Erlernen dieser leistungsstarken strukturellen Tags. --- ## [Navigation für große Sites](https://docs.docmd.io/de/guides/content-ux/navigation-large-sites/) --- title: "Navigation für große Sites" description: "So organisieren Sie komplexe Dokumentations-Sets in einer intuitiven, skalierbaren Navigationsstruktur unter Verwendung der Layout-Tools von docmd." --- ## Problem Wenn eine Dokumentations-Website von ein paar Dutzend Seiten auf Hunderte oder Tausende anwächst, verwandelt sich eine einfache Sidebar oft in ein verwirrendes Labyrinth aus tief verschachtelten Ordnern. Wenn Benutzer gezwungen sind, mehrere Hierarchieebenen aufzuklappen, nur um eine bestimmte Referenz zu finden, verlieren sie den Kontext, werden frustriert und geben die Dokumentation oft zugunsten von "Trial-and-Error" auf. ## Warum es wichtig ist Die Navigation ist die "Landkarte" der Funktionen Ihres Produkts. Wenn die Navigation schwer zu bedienen ist, verlassen sich die Benutzer ausschließlich auf die Suchleiste, was zu fragmentiertem Wissen führen kann. Ein gut strukturiertes Navigationssystem vermittelt dem Benutzer beim Durchsuchen die Logik und Taxonomie Ihres Produkts und hilft ihm, mit der Zeit kompetenter und eigenständiger zu werden. ## Ansatz Priorisieren Sie **Top-Level Context Switching** gegenüber tiefer Verschachtelung. Versuchen Sie, Ihre linke Sidebar auf maximal zwei oder drei Ebenen Tiefe zu beschränken. Nutzen Sie den horizontalen [Menübar](../../configuration/menubar), um verschiedene Dokumentations-"Domänen" (z. B. Anleitungen, API-Referenz und Community) voneinander zu trennen. Dies ermöglicht es jeder einzelnen Sidebar, fokussiert, relevant und übersichtlich zu bleiben. ## Implementierung ### 1. Domänenbasierte Trennung Verwenden Sie in Ihrer `docmd.config.js` den [Menübar](../../configuration/menubar), um Ihre Inhalte in übergeordnete Kategorien zu unterteilen. Dieser Ansatz ermöglicht es Ihnen, für jede Domäne eine völlig andere Sidebar anzuzeigen, was verhindert, dass ein einzelner Navigationsbaum überladen wird. ### 2. Flachhalten der Hierarchie Anstatt ein einzelnes Konzept auf viele winzige Markdown-Seiten aufzuteilen, sollten Sie verwandte Informationen in umfassenden übergeordneten Seiten konsolidieren. Verwenden Sie eine klare [Überschriften-Hierarchie](../../content/syntax), damit Benutzer innerhalb der Seite mithilfe des automatisch generierten Inhaltsverzeichnisses (TOC) auf der rechten Seite navigieren können. * **❌ Schlechte IA**: Ein Ordner namens "Sicherheit", der zehn separate Dateien mit jeweils nur einem Absatz für verschiedene Protokolle enthält. * **✅ Bessere IA**: Eine einzige, gut strukturierte Seite "Sicherheitsübersicht", die alle Protokolle abdeckt und Überschriften für ein sauberes Inhaltsverzeichnis nutzt. ### 3. Nutzung von einklappbaren Abschnitten Für große Gruppen verwandter Inhalte, auf die nicht ständig zugegriffen wird, verwenden Sie die Eigenschaft `collapsible` in Ihrer [Navigations-Konfiguration](../../configuration/navigation). Dies hält die Benutzeroberfläche sauber, indem sekundäre Informationen ausgeblendet werden, bis sie vom Benutzer explizit angefordert werden. ```json // navigation.json { "title": "API-Referenz", "collapsible": true, "collapsed": true, "children": [ { "title": "Authentifizierung", "path": "api/auth" }, { "title": "Endpunkte", "path": "api/endpoints" } ] } ``` ## Abwägungen Das Konsolidieren von Inhalten in weniger, längeren Seiten erfordert von den Autoren Disziplin in Bezug auf strukturelle Klarheit und die Verwendung von Überschriften. Wenn eine Seite ohne ordentliche interne Navigation (TOC) zu lang wird, kann sie selbst zu einer "Textwand" werden. Die deutliche Reduzierung von "Klick-Ermüdung" und das bessere Auffinden verwandter Inhalte machen eine flachere, domänenbasierte Hierarchie für große Dokumentations-Sets jedoch deutlich überlegen. --- ## [Skalierbares technisches Schreiben](https://docs.docmd.io/de/guides/content-ux/scalable-technical-writing/) --- title: "Skalierbares technisches Schreiben" description: "Wie Sie Progressive Disclosure (schrittweise Offenlegung) und strukturelle Container nutzen, um wachsende Dokumentationskomplexität zu bewältigen, ohne Ihre Benutzer zu überfordern." --- ## Problem In der Anfangsphase eines Produkts kann die Dokumentation einer Funktion nur wenige Absätze umfassen. Wenn sich das Produkt jedoch zu einer Unternehmensplattform entwickelt, können diese Absätze zu einem Meer aus Grenzfällen, plattformspezifischen Variationen (Docker, Kubernetes, Cloud) und komplexen Konfigurationsoptionen explodieren. Dies führt zu einem "vertikalen Aufblähen", bei dem eine einzelne Seite zu einer unlesbaren Textwüste wird, die schwer zu navigieren und zu warten ist. ## Warum es wichtig ist Vertikales Aufblähen zerstört das Verständnis und erhöht die kognitive Belastung. Wenn Benutzer gezwungen sind, durch seitenlange Inhalte zu scrollen, die für ihre spezifische Umgebung oder ihren Anwendungsfall irrelevant sind, werden sie überfordert und nehmen oft an, dass das Produkt komplexer ist, als es tatsächlich ist. Skalierbares Schreiben stellt sicher, dass Benutzer in jedem Moment nur die Informationen sehen, die sie benötigen, und bewahrt so einen klaren Weg zum Erfolg. ## Ansatz Implementieren Sie **Progressive Disclosure**. Diese Technik beinhaltet, nur die kritischsten Informationen vorab zu präsentieren (den "Happy Path") und komplexere, technische oder spezifischere Details hinter interaktiven UI-Strukturen zu verbergen. `docmd` bietet mehrere integrierte Container, die speziell entwickelt wurden, um Ihnen zu helfen, diese Komplexität effektiv und elegant zu bewältigen. ## Implementierung ### 1. Umgang mit Variationen durch Tabs Anstatt Anweisungen für mehrere Paketmanager, Betriebssysteme oder Cloud-Anbieter nacheinander aufzulisten, verwenden Sie den [Tabs-Container](../../content/containers/tabs.md). Dies ermöglicht es dem Benutzer, seine spezifische Umgebung auszuwählen, wodurch irrelevante Befehle sofort ausgeblendet und visuelles Rauschen reduziert wird. ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. Bewältigung von Grenzfällen mit Collapsibles Wenn ein Schritt zur Fehlerbehebung oder ein spezifischer Grenzfall nur für einen kleinen Prozentsatz der Benutzer gilt, lassen Sie ihn nicht den logischen Fluss Ihres Haupt-Tutorials unterbrechen. Verwenden Sie den [Collapsible-Container](../../content/containers/collapsible.md), um diese Details zu verbergen, während sie bei Bedarf leicht zugänglich bleiben. ```markdown 1. Starten Sie den Entwicklungsserver durch Ausführen von `npx @docmd/core dev`. ::: collapsible "Fehlerbehebung: Port wird bereits verwendet" Wenn Sie einen `EADDRINUSE`-Fehler erhalten, können Sie einen benutzerdefinierten Port mit dem `--port`-Flag angeben: `npx @docmd/core dev --port 4000`. ::: ``` ### 3. Progressive Details mit Callouts Verwenden Sie [Callouts](../../content/containers/callouts.md), um ergänzende Informationen bereitzustellen, die für die Hauptaufgabe nicht erforderlich sind, aber wertvollen Kontext für fortgeschrittene Benutzer bieten. ## Abwägungen Das Verbergen von Inhalten in Tabs oder Collapsibles kann es für Benutzer gelegentlich schwieriger machen, Informationen mithilfe der nativen `Strg+F`-Suche des Browsers zu finden. Die integrierte [Suchmaschine](../../plugins/search.md) von `docmd` indiziert jedoch alle Inhalte innerhalb dieser Container. So wird sichergestellt, dass Benutzer über die primäre Suchoberfläche der Website immer noch genau das finden, was sie brauchen, während sie gleichzeitig ein viel saubereres Leseerlebnis genießen. --- ## [Aufgabe vs. Konzept](https://docs.docmd.io/de/guides/content-ux/task-vs-concept/) --- title: "Aufgabe vs. Konzept" description: "So wenden Sie das Diátaxis-Framework an, um \"How-To\"-Anleitungen von konzeptionellen Erklärungen zu trennen und eine effektivere Dokumentationsstruktur aufzubauen." --- ## Problem Ein häufiger Fehler beim technischen Schreiben ist die Vermischung der Frage, *warum* etwas funktioniert, mit der Frage, *wie* man es tatsächlich umsetzt. Ein Tutorial zur "Konfiguration von SSO" kann beispielsweise leicht durch seitenlange Erklärungen zur Geschichte des SAML-Protokolls überladen werden, was den Benutzer von seinem unmittelbaren Ziel ablenkt, die Funktion zum Laufen zu bringen. ## Warum es wichtig ist Die Absicht des Benutzers variiert je nach aktuellem Kontext erheblich. Ein Entwickler, der nachts um 2 Uhr ein Problem in der Produktion beheben muss, sucht nach konkreten, umsetzbaren Schritten und nicht nach Architekturphilosophie. Umgekehrt muss ein technischer Leiter, der Ihre Plattform evaluiert, die zugrunde liegende Logik verstehen, bevor er sich auf eine Implementierung festlegt. Die Trennung dieser Aspekte stellt sicher, dass beide Personas die benötigten Informationen ohne unnötige Reibung finden. ## Ansatz Nutzen Sie das **Diátaxis-Framework**, das Dokumentation in vier Quadranten unterteilt: Tutorials, How-To-Anleitungen, Erklärungen (Konzepte) und technische Referenz. In diesem Leitfaden konzentrieren wir uns auf die kritische Trennung zwischen **aufgabenorientierten Inhalten** (umsetzbare Schritte) und **konzeptorientierten Inhalten** (tieferes Verständnis). ## Implementierung ### 1. Die aufgabenorientierte Anleitung (How-To) Konzentrieren Sie sich ganz auf ein spezifisches, eng gefasstes Ziel. Verzichten Sie auf langatmige theoretische Erklärungen und fokussieren Sie sich auf die minimalen Schritte, die zum Erreichen des Ziels erforderlich sind. Verwenden Sie den [Steps-Container](../../content/containers/steps), um einen klaren, unmissverständlichen Pfad aufzuzeigen. * **Titel-Beispiel**: "So konfigurieren Sie Webhooks" * **Struktur**: * Voraussetzungen * Direkte, umsetzbare Anweisungen * Verifizierungsschritte (Woran erkenne ich, dass es funktioniert hat?) ### 2. Die konzeptorientierte Anleitung (Erklärung) Konzentrieren Sie sich auf das "Big Picture", einschließlich Architektur, Designphilosophie und dem "Warum" hinter bestimmten Entscheidungen. Vermeiden Sie es, in diesen Abschnitten direkte Anweisungen oder Befehle zu geben. * **Titel-Beispiel**: "Die Webhook-Delivery-Architektur verstehen" * **Struktur**: * High-Level Architektur-Diagramme * Retry-Logik und Reliability-Philosophie * Sicherheitsaspekte ### 3. Effektive Querverweise Anstatt beide Inhaltsarten zu vermischen, nutzen Sie die Verlinkungs-Tools von `docmd`, um eine Brücke für Benutzer zu schlagen, die mehr Kontext benötigen oder bereit für die Implementierung sind. * **In einer How-To-Anleitung**: "Für tiefere Einblicke in unsere Retry-Logik lesen Sie [Webhook-Architektur](../../guides/performance-delivery/caching-strategies)." * **In einer konzeptionellen Anleitung**: "Bereit für den Start? Folgen Sie unserer [Anleitung zur Webhook-Konfiguration](../../guides/integrations/alongside-other-tools)." ## Abwägungen Die Trennung von Aufgaben und Konzepten erhöht die Anzahl der Seiten in Ihrer Navigation und erfordert eine konsequentere Verlinkung. Diese modulare Struktur verbessert jedoch die langfristige Wartbarkeit, Durchsuchbarkeit und die allgemeine Professionalität Ihrer Dokumentation erheblich. --- ## [Anpassen von Favicons und Metadaten](https://docs.docmd.io/de/guides/customisation/custom-favicons-metadata/) --- title: "Anpassen von Favicons und Metadaten" description: "So konfigurieren Sie die visuelle Identität Ihrer Website im Browser und optimieren die Vorschau in sozialen Medien." --- ## Problem Eine Standard-Dokumentationsseite hat im Browser oft keine eigene visuelle Identität (sie verwendet ein generisches Favicon) und bietet mangelhafte Vorschauen, wenn Links in sozialen Medien oder Kommunikationstools wie Slack und Discord geteilt werden. Dies verringert den Wiedererkennungswert der Marke und die Klickraten. ## Warum es wichtig ist Ihr Favicon ist der primäre visuelle Anker in einem überfüllten Browserfenster. Hochwertige OpenGraph- und Twitter-Metadaten stellen sicher, dass Ihre Dokumentation professionell und vertrauenswürdig aussieht, wenn sie geteilt wird, und bieten Kontext durch Titel, Beschreibungen und Hero-Images. ## Ansatz `docmd` bietet eine integrierte `favicon`-Eigenschaft für die einfache Konfiguration von Icons. Für fortgeschrittene SEO- und soziale Metadaten nutzen Sie das [SEO-Plugin](../../plugins/seo), das die Generierung von Meta-Tags basierend auf Ihrer Projektkonfiguration und dem Seiten-Frontmatter automatisiert. ## Implementierung ### 1. Konfiguration des Favicons Platzieren Sie Ihre Favicon-Datei (z. B. `favicon.svg` oder `favicon.ico`) in Ihrem Quellverzeichnis und referenzieren Sie diese in Ihrer `docmd.config.json`. `docmd` kümmert sich automatisch um die relativen Pfade und das Cache-Busting. ```json { "title": "Mein Projekt", "favicon": "/favicon.svg" } ``` ### 2. Globale SEO-Konfiguration Aktivieren und konfigurieren Sie das [SEO-Plugin](../../plugins/seo), um Standard-Vorschauen für Ihre gesamte Website festzulegen. ```json { "url": "https://docs.example.com", "plugins": { "seo": { "defaultDescription": "Der ultimative Leitfaden zu unserer fantastischen Software.", "openGraph": { "defaultImage": "/static/og-banner.png" }, "twitter": { "siteUsername": "@meinprojekt", "cardType": "summary_large_image" } } } } ``` ### 3. Seitenspezifische Overrides Sie können die SEO-Einstellungen für einzelne Seiten über die Eigenschaft `seo` im [Frontmatter](../../content/frontmatter) überschreiben. ```yaml --- title: "Major Release v2.0" description: "Alles, was Sie über unsere neue Engine wissen müssen." seo: image: "/assets/v2-hero-banner.png" keywords: ["release", "v2", "update", "performance"] --- ``` ## Abwägungen Die `favicon`-Eigenschaft ist zwar praktisch, unterstützt jedoch nur eine einzelne Datei. Für komplexe Favicon-Sets mit mehreren Größen (Apple Touch Icons, Android Manifests usw.) müssen Sie möglicherweise ein eigenes Plugin verwenden, um zusätzliche `<link>`-Tags in den `<head>` einzufügen. --- ## [Benutzerdefinierte Schriftarten und Branding](https://docs.docmd.io/de/guides/customisation/custom-fonts-branding/) --- title: "Benutzerdefinierte Schriftarten und Branding" description: "So passen Sie das Erscheinungsbild Ihrer Dokumentation mithilfe von CSS-Variablen an Ihre Unternehmensidentität an." --- ## Problem Die nahtlose Anpassung Ihrer Dokumentationsplattform an Ihre Unternehmensidentität ist entscheidend für ein professionelles Erscheinungsbild. Die Standard-Schriftarten und Farbpaletten sind auf allgemeine Lesbarkeit ausgelegt, spiegeln jedoch möglicherweise nicht Ihre spezifische Markenpersönlichkeit wider. ## Warum es wichtig ist Die Dokumentation ist ein wichtiger Marken-Touchpoint. Wenn Ihr Hauptprodukt eine bestimmte Typografie (wie "Outfit") und eine markante Primärfarbe verwendet, sollte Ihre Dokumentation dieselben Entscheidungen widerspiegeln. Konsistenz über alle Ihre Web-Assets hinweg schafft Vertrauen und bietet eine kohärentere User Experience. ## Ansatz `docmd` verwendet ein System von CSS-Variablen (Custom Properties), die die visuellen Token des Layouts definieren. Sie können diese Variablen ganz einfach in einem benutzerdefinierten Stylesheet überschreiben, ohne die Core-Engine ändern zu müssen. ## Implementierung ### 1. Erstellen eines benutzerdefinierten Stylesheets Erstellen Sie eine Datei namens `custom.css` in Ihrem Quellverzeichnis (oder einem Unterverzeichnis) und überschreiben Sie die `:root`-Variablen. ```css /* Importieren Sie Ihre Markenschriftart */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* Marken-Typografie */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* Markenfarben (Light Mode) */ --link-color: #8a2be2; /* Ihre primäre Markenfarbe */ --link-color-hover: #7b1fa2; --bg-color: #fcfcfd; /* Dezente Hintergrundtönung */ } /* Overrides für Dark Mode */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. Registrieren des Stylesheets Fügen Sie Ihre benutzerdefinierte CSS-Datei dem Array `theme.customCss` in Ihrer `docmd.config.json` hinzu. ```json { "theme": { "customCss": ["/custom.css"] } } ``` ## Abwägungen Das Importieren externer Schriftarten (z. B. von Google Fonts) führt zu einer geringfügigen Verzögerung beim ersten Laden der Seite. Um die Performance zu optimieren, sollten Sie in Erwägung ziehen, Ihre Schriftdateien lokal in Ihrem Projekt zu hosten und `font-display: swap` zu verwenden, um ein "Flackern von unformatiertem Text" (FOUT) während des Ladens zu verhindern. --- ## [Gestaltung von benutzerdefinierten Landing-Pages](https://docs.docmd.io/de/guides/customisation/custom-landing-pages/) --- title: "Gestaltung von benutzerdefinierten Landing-Pages" description: "So nutzen Sie die Hero- und Grid-Container von docmd, um hochwertige Landing-Pages für Ihre Dokumentation zu erstellen." --- ## Problem Standardmäßig sieht die `index.md`-Datei in den meisten Dokumentationsgeneratoren wie eine gewöhnliche technische Seite aus. Die Erstellung einer wirkungsvollen Landing-Page in Marketing-Qualität erfordert normalerweise ein separates Web-Framework (wie Next.js oder Astro), was den Dokumentations-Workflow verkompliziert. ## Warum es wichtig ist Die Startseite Ihrer Dokumentation ist oft der erste Kontakt eines Entwicklers mit Ihrem Produkt. Eine generische, aus Markdown geparste Seite kann das Vertrauen in die Professionalität und Qualität Ihres Projekts mindern. Eine benutzerdefinierte Landing-Page kann Benutzer gezielter zu den wichtigsten Abschnitten führen und gleichzeitig die visuelle Identität Ihrer Marke stärken. ## Ansatz `docmd` bietet spezialisierte [Hero](../../content/containers/hero.md)- und [Grid](../../content/containers/grids.md)-Container, die speziell für den Aufbau hochwertiger Landing-Pages entwickelt wurden. Für vollständige kreative Freiheit können Sie auch die Frontmatter-Eigenschaft `noStyle` verwenden, um die volle Kontrolle über HTML und Styling einer Seite zu übernehmen. ## Implementierung ### 1. Verwendung des Hero-Containers Der `hero`-Container unterstützt verschiedene Layouts, darunter `split` (für Side-by-side-Inhalte) und `glow` (für eine moderne Ästhetik). ```markdown ::: hero layout:split glow:true # Schneller aufbauen mit docmd Die Zero-Config Documentation Engine für moderne Entwicklerteams. [Erste Schritte](../../getting-started/quick-start.md) [Auf GitHub ansehen](https://github.com/docmd-io/docmd) == side ![Dashboard Vorschau](../../static/img/hero-preview.png) ::: ``` ### 3. Inhalte mit Grids organisieren Nutzen Sie [Grids und Cards](../../content/containers/grids.md), um übergeordnete Navigationsbereiche zu erstellen, die den Benutzern helfen, schnell zu finden, was sie suchen. ```markdown ::: grids ::: grid ::: card "Quick Start" icon:rocket In weniger als 5 Minuten einsatzbereit. [Mehr erfahren](../../getting-started/quick-start.md) ::: ::: ::: grid ::: card "API Referenz" icon:code Umfassende Dokumentation für alle unsere Endpunkte. [API erkunden](../../api/node-api.md) ::: ::: ::: ``` ### 3. Vollständige Anpassung mit noStyle Wenn Sie ein komplett individuelles Design benötigen, das das Standard-Layout (ohne Sidebar oder Header) ignoriert, verwenden Sie die Eigenschaft `noStyle` im [Seiten-Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Benutzerdefiniertes Dashboard" noStyle: true --- ``` Wenn `noStyle: true` gesetzt ist, rendert `docmd` nur den von Ihnen bereitgestellten rohen HTML/Markdown-Inhalt. Dies ermöglicht es Ihnen, eigenes CSS und JavaScript für ein pixelgenaues Erlebnis einzubinden. ## Abwägungen Die Verwendung von `noStyle: true` bedeutet, dass Sie auf die nativen Funktionen für Navigation, Suche und Theme-Umschaltung von `docmd` verzichten. Sie sind selbst dafür verantwortlich, dass die benutzerdefinierte Seite responsiv und barrierefrei ist. In den meisten Fällen bietet die Kombination aus `hero`- und `grid`-Containern innerhalb des Standard-Layouts die beste Balance zwischen Ästhetik und Funktionalität. --- ## [docmd mit benutzerdefinierten Plugins erweitern](https://docs.docmd.io/de/guides/customisation/extending-custom-plugins/) --- title: "docmd mit benutzerdefinierten Plugins erweitern" description: "So nutzen Sie die Lifecycle-Hooks von docmd, um eigene Funktionen zu erstellen und die Dokumentations-Engine zu erweitern." --- ## Problem Manchmal haben Sie eine sehr spezifische Anforderung, die nicht durch integrierte Funktionen oder vorhandene Plugins abgedeckt wird. Beispielsweise müssen Sie während des Build-Prozesses Daten von einer internen API abrufen oder komplexe Transformationen am generierten HTML vornehmen, die über einfaches CSS hinausgehen. ## Warum es wichtig ist Erweiterbarkeit ist das, was ein statisches Tool von einem professionellen Dokumentations-Framework unterscheidet. Ohne eine saubere Möglichkeit, eigene Logik einzufügen, sind Teams oft gezwungen, fragile Shell-Skripte oder Post-Processing-Wrapper zu pflegen, was den Build-Prozess schwer verwaltbar und fehleranfällig macht. ## Ansatz `docmd` verfügt über eine robuste, Hook-basierte [Plugin-API](../../plugins/api). Sie können einfache Node.js-Module schreiben, die den Dokumentations-Lifecycle in verschiedenen Phasen abfangen , von der initialen Konfiguration bis zur finalen HTML-Generierung , und so Inhalte und Verhalten beliebig anpassen. ## Implementierung ### 1. Erstellen eines lokalen Plugins Ein Plugin ist ein Standard-JavaScript-Modul, das einen Deskriptor und mehrere Lifecycle-Hooks exportiert. ```javascript // plugins/version-injector.js export default { // Plugin-Metadaten plugin: { name: 'version-injector', version: '1.0.0', capabilities: ['build'] // Erforderlich, um 'build'-Hooks zu nutzen }, // Status, der zwischen Hooks geteilt wird latestVersion: '0.0.0', // Wird ausgeführt, sobald die Konfiguration aufgelöst wurde async onConfigResolved(config) { // Daten von einer internen API abrufen const response = await fetch('https://api.internal.com/version'); this.latestVersion = await response.text(); console.log(`[Plugin] Version abgerufen: ${this.latestVersion}`); }, // Abfangen des Seitenkontexts vor dem Template-Rendering async onBeforeRender(page) { if (!page.html) return; // Platzhalter durch dynamische Daten in HTML und Frontmatter ersetzen page.html = page.html.replace(/\{\{VERSION\}\}/g, this.latestVersion); page.frontmatter.computedVersion = this.latestVersion; } }; ``` ### 2. Registrieren des Plugins Sie können Ihr lokales Plugin registrieren, indem Sie es in Ihre `docmd.config.js` (oder `docmd.config.ts`) importieren. JSON-Konfigurationsdateien können keine Importe verwenden - nutzen Sie das `.js`- oder `.ts`-Format für die Registrierung von Plugins. ```javascript import VersionInjector from './plugins/version-injector.js'; export default { "title": "Meine Projekt-Docs", "plugins": { // Registrierung durch Angabe des importierten Moduls "version-injector": VersionInjector } }; ``` ## Abwägungen Benutzerdefinierte Plugins laufen während des Builds in der Node.js-Umgebung. Sie sind zwar leistungsstark, können aber die Build-Performance beeinträchtigen, wenn sie nicht optimiert sind. Jede Logik in Hooks wie `onAfterParse` oder `onPageReady` wird für *jede* Seite Ihrer Website ausgeführt. Stellen Sie sicher, dass Ihre Transformationen effizient sind (z. B. durch optimierte Regex), um die Build-Zeiten kurz zu halten. --- ## [Neben anderen Tools](https://docs.docmd.io/de/guides/integrations/alongside-other-tools/) --- title: "Neben anderen Tools" description: "Strategien zur Integration von docmd in ein Multi-Tool-Dokumentations-Ökosystem, um eine nahtlose User Experience zu schaffen." --- ## Problem Große Organisationen nutzen selten ein einziges Tool für all ihre Dokumentationsanforderungen. Ihr Unternehmen verwendet vielleicht Confluence für interne Spezifikationen, Stoplight für das API-Design und GitHub für Codebeispiele. Die Integration dieser unterschiedlichen Quellen in eine einheitliche User Journey ist eine große Herausforderung, da sich Benutzer oft zwischen getrennten Portalen mit unterschiedlichen Stilen und Navigationsstrukturen wiederfinden. ## Warum es wichtig ist Eine fragmentierte Dokumentationserfahrung schadet dem Vertrauen der Entwickler und erhöht die kognitive Belastung. Wenn ein Benutzer gezwungen ist, zwischen völlig unterschiedlichen Oberflächen zu wechseln, nur um einem Tutorial zu folgen, verliert er eher den Kontext oder gibt Ihr Produkt ganz auf. Die Vereinheitlichung Ihrer Tools gewährleistet eine professionelle, zusammenhängende Erfahrung, die zum Erkunden und Lernen einlädt. ## Ansatz Nutzen Sie `docmd` als Ihren primären Dokumentations-Hub oder "Single Pane of Glass". Durch die Verwendung des [Menübars](../../configuration/menubar) für eine einheitliche Navigation und von [Embed-Containern](../../content/containers/embed) für Drittanbieter-Inhalte können Sie eine nahtlose Oberfläche schaffen, welche die Komplexität Ihrer Multi-Tool-Infrastruktur verbirgt. ## Implementierung ### 1. Einheitliche globale Navigation Verwenden Sie die `menubar`-Konfiguration, um Ihre verschiedenen Dokumentationsportale miteinander zu verknüpfen. Dies stellt sicher, dass Benutzer immer den Weg zurück zu den Hauptanleitungen finden, unabhängig davon, auf welcher Subdomain sie sich gerade befinden. ```json { "layout": { "menubar": { "left": [ { "text": "Anleitungen", "url": "/" }, { "text": "API-Referenz", "url": "https://api.example.com" }, { "text": "Community", "url": "https://forum.example.com" } ] } } } ``` ### 2. Nahtloses Embedding Für Tools, die eine Weboberfläche bieten (wie interaktive API-Explorer oder Dashboard-Vorschauen), verwenden Sie den `::: embed`-Container, um diese direkt in Ihren `docmd`-Seiten anzuzeigen. Dies hält die Benutzer innerhalb Ihrer markengerechten Umgebung. ```markdown # Interaktiver API-Explorer ::: embed "https://api.example.com/v1/explorer" ::: ``` Weitere Informationen finden Sie in der [Embed-Referenz](../../content/containers/embed). ### 3. Inhaltsaggregation Für externe Inhalte, die zusammen mit Ihrer Kerndokumentation durchsuchbar sein müssen, sollten Sie einen Build-Schritt in Betracht ziehen, der Daten aus anderen Quellen abruft und in Markdown umwandelt. Dies ermöglicht es `docmd`, all Ihre Informationen in einem einzigen, einheitlichen [Suchindex](../../plugins/search) zu erfassen. ## Abwägungen Während das Einbetten einen einheitlichen Look bietet, kann es gelegentlich Performance-Overhead oder Probleme mit verschachtelten Scrollbalken auf mobilen Geräten verursachen. Zudem werden Inhalte innerhalb eines Iframes nicht nativ von der `docmd`-Suchmaschine indiziert. Wenn die Durchsuchbarkeit aller Inhalte kritisch ist, wird die Priorisierung von [OpenAPI-Generierung](./openapi-generation) oder anderen Markdown-basierten Ingestion-Methoden empfohlen. --- ## [Deployment-Methode wählen](https://docs.docmd.io/de/guides/integrations/choosing-deployment-method/) --- title: "Deployment-Methode wählen" description: "Ein praktischer Leitfaden zur Auswahl zwischen GitHub App, GitHub Action, Starter-Vorlage und Deployer-Paket – mit Entscheidungsmatrix und realen Szenarien." --- # Deployment-Methode wählen docmd bietet vier Wege, Ihre Dokumentation live zu schalten. Alle produzieren dasselbe Ergebnis — eine statische Website, die auf GitHub Pages oder einem Hosting-Anbieter Ihrer Wahl bereitgestellt wird — unterscheiden sich jedoch im gewünschten Kontrollgrad und Ausgangspunkt. ## Schnelle Entscheidungsmatrix | | [GitHub App](../../integrations/github-app.md) | [Starter-Vorlage](../../integrations/starter-template.md) | [GitHub Action](../../integrations/github-action.md) | [Deployer-Paket](../../deployment/deployer-package.md) | |---|---|---|---|---| | **Ausgangspunkt** | Bestehendes Repo | Neues Repo | Beliebig | Beliebig | | **Einrichtungsaufwand** | Ein Klick | Zwei Schritte | YAML schreiben | Befehl ausführen | | **Workflow-Datei** | Auto-generiert | Enthalten | Selbst schreiben | Auto-generiert | | **Anpassbarkeit** | Nach Generierung | Von Anfang an | Vollständig | Vollständig | | **Hosting-Ziel** | GitHub Pages | GitHub Pages | GitHub Pages | Beliebiger Anbieter | | **Monorepo-Support** | ✓ Auto-erkannt | — | Manuell `--cwd` | ✓ | | **Kein GitHub-Hosting** | ✗ | ✗ | Anpassbar | ✓ Docker, Nginx, Vercel, Netlify… | ## Szenario-Leitfaden ### „Ich möchte in unter zwei Minuten live gehen, ohne Konfiguration" Verwenden Sie die **[GitHub App](../../integrations/github-app.md)**. Installieren, Repository auswählen, fertig. Sie erkennt Ihre Konfiguration, generiert den Workflow, aktiviert GitHub Pages und stellt bereit — ohne dass Sie eine einzige Datei anfassen. ::: button "GitHub App installieren" external:https://github.com/apps/docmd/installations/new icon:github color:#2ea44f --- ### „Ich starte eine brandneue Dokumentationswebsite" Verwenden Sie die **[Starter-Vorlage](../../integrations/starter-template.md)**. Klicken Sie auf „Vorlage verwenden", aktualisieren Sie `docmd.config.json` mit Titel und URL, aktivieren Sie GitHub Pages einmalig und pushen. Alles ist bereits vorkonfiguriert. ::: button "Starter-Vorlage verwenden" external:https://github.com/docmd-io/docmd-template/generate icon:github --- ### „Ich habe eine bestehende CI/CD-Pipeline und möchte Docs hinzufügen" Verwenden Sie die **[GitHub Action](../../integrations/github-action.md)**. Fügen Sie `docmd-io/deploy@v1` in Ihren bestehenden Workflow ein. Sie lässt sich sauber mit anderen Schritten kombinieren — Tests ausführen, App bauen, dann Docs bauen, alles in einem Job. --- ### „Ich deploye auf Vercel, Netlify, Docker oder meinen eigenen Server" Verwenden Sie das **[Deployer-Paket](../../deployment/deployer-package.md)**. Führen Sie `npx @docmd/core deploy --vercel` (oder `--netlify`, `--docker`, `--nginx`) aus, um anbieterspezifische Konfigurationsdateien zu generieren, die auf Ihre `docmd.config.json` zugeschnitten sind. --- ### „Ich bin in einem Monorepo mit Docs in einem Unterverzeichnis" Sowohl die **GitHub App** als auch das **Deployer-Paket** behandeln dies automatisch. Die App erkennt Konfigurationen im gesamten Repository-Baum und injiziert das korrekte `--cwd`-Flag. Bei Verwendung der GitHub Action übergeben Sie `--cwd` manuell: ```yaml - run: npx @docmd/core build --cwd packages/docs ``` --- ### „Ich möchte Docs bei jedem Pull Request in der Vorschau sehen" Kombinieren Sie die **GitHub Action** mit einem PR-Vorschau-Dienst (z. B. Cloudflare Pages Preview Deployments oder einer selbst gehosteten Vorschauumgebung). Siehe [Änderungen in der Vorschau anzeigen](../workflows-teams/previewing-changes.md) für eine vollständige Anleitung. --- ## Wie die Methoden zusammenwirken Diese Methoden schließen sich nicht gegenseitig aus. Ein typischer Entwicklungspfad sieht so aus: ``` Mit der GitHub App beginnen (schnellster Weg zu Live) ↓ Die generierte Workflow-Datei nach Bedarf anpassen ↓ Deployer-Paket hinzufügen für Nginx/Docker-Konfigurationen ↓ Action in eine umfassendere CI/CD-Pipeline integrieren ``` ## Weiterführende Links - [GitHub Action Referenz](../../integrations/github-action.md) - [GitHub App Referenz](../../integrations/github-app.md) - [Starter-Vorlage Referenz](../../integrations/starter-template.md) - [Deployer-Paket Referenz](../../deployment/deployer-package.md) - [GitHub Actions CI/CD Leitfaden](./github-actions-cicd.md) - [Änderungen in der Vorschau anzeigen](../workflows-teams/previewing-changes.md) --- ## [Vorhandene Markdown-Repos](https://docs.docmd.io/de/guides/integrations/existing-markdown-repos/) --- title: "Vorhandene Markdown-Repos" description: "So generieren Sie aus Ihren vorhandenen Markdown-Dateien sofort eine professionelle Dokumentations-Website , ganz ohne Konfiguration." --- ## Problem Sie verfügen über ein bestehendes Repository mit hunderten oder tausenden von Markdown-Dateien , vielleicht ein altes Wiki, ein Obsidian-Vault oder eine Sammlung technischer Notizen. Das manuelle Konvertieren von Frontmatter, das Reparieren fehlerhafter Links und das Umstrukturieren von Dateien für eine neue Engine ist eine gewaltige Aufgabe, die Teams oft davon abhält, ihre Dokumentation zu modernisieren. ## Warum es wichtig ist Ihre Inhalte sollten portabel und tool-unabhängig bleiben. Eine hochwertige Dokumentations-Engine sollte sich an Ihre vorhandenen Dateien anpassen und nicht Ihre Dateien dazu zwingen, sich an die Engine anzupassen. Die Vermeidung von Vendor-Lock-in stellt sicher, dass Ihr geistiges Eigentum standardisiert, lesbar und zukunftssicher bleibt. ## Ansatz `docmd` hält sich an strikte CommonMark-Spezifikationen und ist standardmäßig auf **Zero-Config** ausgelegt. Sie können die `docmd`-CLI auf ein beliebiges Verzeichnis mit Markdown-Dateien richten, und sie wird intelligent eine voll funktionsfähige Dokumentations-Website erstellen, ohne auch nur eine einzige Zeile Ihres Quellinhalts zu verändern. ## Implementierung ### 1. Sofortiges Bootstrapping Navigieren Sie zu Ihrem vorhandenen Markdown-Ordner und starten Sie den Entwicklungsserver. `docmd` scannt Ihre Verzeichnisstruktur und erstellt sofort eine funktionale Website im Arbeitsspeicher. ```bash cd meine-vorhandenen-docs/ npx @docmd/core dev ``` ### 2. Automatische Navigation (Auto-Router) Wenn keine `navigation.json` oder `docmd.config.js` gefunden wird, aktiviert `docmd` seinen [Auto-Router](../../configuration/navigation#automatic-sidebar-generation). Dieser bildet Ihre Ordnerstruktur rekursiv ab, verschönert Verzeichnisnamen (z. B. wird aus `getting-started` "Getting Started") und generiert automatisch eine logische Sidebar-Taxonomie. ### 3. Intelligente Titel-Ermittlung Sie müssen nicht jeder Datei ein `title`-Frontmatter hinzufügen. `docmd` nutzt eine kaskadierende Strategie zur Ermittlung von Seitentiteln: 1. **Frontmatter**: Prüft auf einen `title`- oder `h1`-Key. 2. **Erste Überschrift**: Extrahiert die erste gefundene `# Überschrift` aus dem Dateiinhalt. 3. **Dateiname**: Verschönert den Dateinamen als Fallback (z. B. wird aus `install-guide.md` "Install Guide"). ### 4. Resiliente Syntax-Verarbeitung `docmd` ist auf Resilienz ausgelegt. Wenn Ihre vorhandenen Dateien proprietäre Syntax oder veraltete Shortcodes von anderen Engines enthalten, werden diese sicher als Rohtext gerendert oder übersprungen. Dies stellt sicher, dass Ihr Build niemals aufgrund von Inhalten fehlschlägt, die Sie noch nicht migriert haben. ## Abwägungen Automatisch generierte Sidebars werden in der Regel alphabetisch nach Dateinamen sortiert. Während Dateinamen wie `01-intro.md` und `02-setup.md` gut funktionieren, können rein beschreibende Dateinamen in einer nicht intuitiven Reihenfolge erscheinen. Für produktionsreife Websites empfehlen wir den Übergang zu einer manuellen [Navigations-Konfiguration](../../configuration/navigation), um die volle Kontrolle über die User Journey zu erhalten. --- ## [GitHub Actions CI/CD](https://docs.docmd.io/de/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "So automatisieren Sie Ihre Dokumentations-Builds und -Deployments mit GitHub Actions und docmd für einen hocheffizienten Dokumentations-Workflow." --- ## Problem Das manuelle Bauen und Bereitstellen von Dokumentationen von einem lokalen Rechner aus ist anfällig für Fehler, Umgebungsinkonsistenzen (z. B. unterschiedliche Node.js-Versionen) und Sicherheitsrisiken. Zudem entsteht ein Flaschenhals, da Deployments von der Verfügbarkeit und dem lokalen Setup einer einzelnen Person abhängen. ## Warum es wichtig ist Continuous Deployment (CD) stellt sicher, dass Ihre Dokumentation immer synchron mit Ihrer Software ist. Wenn ein technisches Update gemergt wird, sollte es Ihre Benutzer innerhalb von Minuten erreichen, nicht erst nach Tagen. Automatisierung garantiert, dass jeder Build in einer sauberen, reproduzierbaren Umgebung stattfindet, was hohe Qualitäts- und Zuverlässigkeitsstandards wahrt. ## Ansatz Nutzen Sie GitHub Actions, um die `docmd`-Build-Pipeline bei jedem Push oder Pull Request auszuführen. Die resultierenden statischen Assets können dann automatisch auf Hosting-Providern wie GitHub Pages, Cloudflare Pages oder in containerisierten Umgebungen mit Docker bereitgestellt werden. ## Implementierung ### 1. Standard-Workflow für GitHub Pages Erstellen Sie `.github/workflows/docs.yml`, um den Build- und Deployment-Prozess zu automatisieren. ```yaml name: Docs bereitstellen on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # Baut die Seite in das Verzeichnis 'site/' - run: npx @docmd/core build - name: Artefakt hochladen uses: actions/upload-pages-artifact@v3 with: path: site/ - name: Auf GitHub Pages bereitstellen uses: actions/deploy-pages@v4 ``` ### 2. Containerisiertes Deployment (Docker) Wenn Sie Ihre Dokumentation selbst hosten, verwenden Sie den [Deploy-Befehl](../../deployment), um ein produktionsreifes `Dockerfile` und Serverkonfigurationen zu generieren. ```bash # Docker- und Nginx-Configs lokal generieren npx @docmd/core deploy --docker --nginx ``` Sie können dann Ihre GitHub Action aktualisieren, um dieses Docker-Image zu bauen und bei jedem Release in eine Registry (wie Docker Hub oder GitHub Container Registry) zu pushen. ### 3. Pull Request Previews Verbessern Sie Ihren Workflow, indem Sie für jeden Pull Request kurzlebige Preview-Umgebungen generieren. Dies ermöglicht es Reviewern, die gerenderte Dokumentation zu sehen, bevor sie in den Hauptzweig gemergt wird. Weitere Details finden Sie im [Leitfaden zum Vorschauen von Änderungen](../workflows-teams/previewing-changes). ## Abwägungen Automatisiertes CI/CD erfordert initialen Setup-Aufwand und die Verwaltung von Secrets (z. B. API-Tokens). Die langfristigen Vorteile eines automatisierten Deployment-Prozesses , darunter weniger menschliche Fehler und schnellere Update-Zyklen , überwiegen jedoch bei weitem die Anfangsinvestition. Stellen Sie bei großen Sites sicher, dass Ihr Workflow nur ausgelöst wird, wenn Dateien in Ihrem Dokumentationsverzeichnis geändert wurden, um CI-Minuten zu sparen. --- ## [OpenAPI-Generierung](https://docs.docmd.io/de/guides/integrations/openapi-generation/) --- title: "OpenAPI-Generierung" description: "So integrieren Sie OpenAPI/Swagger-Schemas in Ihren docmd-Workflow für eine automatisierte und synchronisierte API-Referenzdokumentation." --- ## Problem Die manuelle Pflege einer REST-API-Dokumentation stellt ein erhebliches betriebliches Risiko dar. In dem Moment, in dem ein Entwickler einen Endpunkt ändert oder ein Schema im Code aktualisiert, veraltet die Dokumentation. Diese manuell synchron zu halten, ist mühsam, fehleranfällig und führt häufig zu Integrationsfehlern bei Ihren API-Konsumenten. ## Warum es wichtig ist Ungenaue API-Referenzen sind eine Hauptursache für Frustration bei Entwicklern und erhöhte Support-Tickets. Die Automatisierung stellt sicher, dass Ihre Dokumentation die "Source of Truth" (einzige Quelle der Wahrheit) bleibt und den tatsächlichen Zustand Ihrer API in Echtzeit (oder bei jedem Build) widerspiegelt. Dies ermöglicht es Entwicklern, sich auf das Erstellen von Funktionen zu konzentrieren, anstatt Dokumentationstabellen manuell zu aktualisieren. ## Ansatz Implementieren Sie eine asynchrone Build-Pipeline, die Ihr `openapi.json`- oder `swagger.yaml`-Schema in Standard-Markdown-Dateien konvertiert. Da `docmd` hervorragend darin ist, Markdown mit komplexen [Containern](../../content/containers/index.md) zu rendern, fühlt sich die resultierende API-Referenz integriert und visuell konsistent mit dem Rest Ihrer Dokumentation an. ## Implementierung ### 1. Build-Pipeline-Integration Sie können ein Tool wie `widdershins` oder ein benutzerdefiniertes Skript verwenden, um Markdown aus Ihrem OpenAPI-Schema als Pre-Build-Schritt in Ihrer CI/CD-Pipeline zu generieren. ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. Optimierung von API-Layouts API-Referenzen sind oft inhaltsdicht, mit großen Tabellen für Parameter und verschachtelten Schemas. Verwenden Sie [Frontmatter](../../content/frontmatter.md), um das Seitenlayout für eine bessere Lesbarkeit zu optimieren. ```markdown --- title: "REST-API-Referenz" layout: "full" # Maximiert den horizontalen Platz für dichte Tabellen --- ``` Durch das Setzen von `layout: "full"` wird die rechte Seitenleiste mit dem Inhaltsverzeichnis entfernt, wodurch mehr Platz für breite Codeblöcke und Antwortbeispiele entsteht. ### 3. Erweiterung mit docmd-Containern Sie können das generierte Markdown nachbearbeiten, um `docmd`-Funktionen wie [Tabs](../../content/containers/tabs.md) für mehrsprachige Codebeispiele oder [Callouts](../../content/containers/callouts.md) für Authentifizierungswarnungen einzufügen. ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## Abwägungen Maschinell generierte Dokumentationen eignen sich hervorragend für technische Genauigkeit, lassen aber oft die "menschliche Note" vermissen, die für effektives Lernen erforderlich ist. Wir empfehlen, die OpenAPI-Generierung für die **technische Referenz** (Endpunkte, Parameter, Schemas) zu verwenden, während Sie handgeschriebene **Tutorials** und **konzeptionelle Leitfäden** bereitstellen, um den Kontext und die Anwendungsfälle für Ihre API zu erläutern. --- ## [Caching-Strategien](https://docs.docmd.io/de/guides/performance-delivery/caching-strategies/) --- title: "Caching-Strategien" description: "So optimieren Sie die Performance Ihrer Dokumentations-Website durch Immutable Caching, Etag-Revalidierung und produktionsreife Serverkonfigurationen." --- ## Problem Wenn eine Dokumentations-Website ohne ordnungsgemäße `Cache-Control`-Header bereitgestellt wird, laden Browser bei jedem Besuch unnötigerweise Bilder, CSS- und JavaScript-Bundles erneut herunter. Dies führt zu visuellem Ruckeln, erhöhtem Bandbreitenverbrauch und einer schlechten Erfahrung für wiederkehrende Benutzer, die erwarten, dass die Dokumentation sofort geladen wird. ## Warum es wichtig ist Effektives Caching ist einer der wirkungsvollsten Wege, um die "gefühlte Performance" Ihrer Website zu verbessern. Indem Sie sicherstellen, dass statische Assets lokal im Browser des Benutzers gespeichert werden, eliminieren Sie die Latenz wiederholter Netzwerkanfragen. Dadurch fühlt sich das Navigieren in Ihrer Dokumentation flüssig und zuverlässig an, selbst bei instabilen Netzwerkverbindungen. ## Ansatz Implementieren Sie eine zweistufige Caching-Strategie: **Immutable Caching** für statische Assets (CSS, JS, Bilder) und **Etag-Revalidierung** für dynamische Inhalte (HTML, JSON). `docmd` erleichtert dies durch die Generierung produktionsreifer Konfigurationen, die das Cache-Busting automatisch über Versions-Hashes abwickeln. ## Implementierung ### 1. Produktionsreife Server-Konfigurationen Der einfachste Weg, optimales Caching zu implementieren, ist die Verwendung des [Deploy-Befehls](../../deployment) zur Generierung Ihrer Serverkonfiguration. ```bash # Generieren einer optimierten Nginx-Konfiguration npx @docmd/core deploy --nginx ``` ### 2. Immutable Assets Für Assets, die sich nicht häufig ändern (wie Theme-Styles und Kern-Skripte), verwenden Sie langfristiges Caching. `docmd` fügt diesen Assets Versions-Hashes hinzu, um sicherzustellen, dass Benutzer neue Versionen nur dann herunterladen, wenn Sie Ihre Dokumentation aktualisieren. ```nginx # Beispiel einer Nginx-Regel für Immutable Assets location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML- & Navigations-Revalidierung Ihre HTML-Dateien und die `navigation.json` sollten immer auf Updates geprüft werden, damit Benutzer sofort den neuesten Inhalt und die aktuelle Struktur sehen. Verwenden Sie die Anweisung `no-cache`, um den Browser zu zwingen, die Gültigkeit beim Server mittels Etags zu validieren. ```nginx # Beispiel einer Nginx-Regel für HTML-Dateien location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## Abwägungen ### Veralteter Inhalt vs. Performance Die Einstellung langer Cache-Zeiten für Assets ist hochperformant, erfordert jedoch eine robuste "Cache-Busting"-Strategie. `docmd` übernimmt dies automatisch für seine Kerndateien. Wenn Sie jedoch manuell Assets zu Ihrem `static/`-Verzeichnis hinzufügen, müssen Sie sicherstellen, dass Sie deren Referenzen aktualisieren (z. B. durch Ändern des Dateinamens oder Hinzufügen eines Query-Parameters), wenn sich der Inhalt ändert. ### CDN-Integration Wenn Sie ein CDN (wie Cloudflare oder AWS CloudFront) verwenden, stellen Sie sicher, dass dieses so konfiguriert ist, dass es die `Cache-Control`-Header Ihres Servers berücksichtigt. Die meisten modernen CDNs bieten "Instant Purge"-Funktionen an. Wir empfehlen, diese als Teil Ihrer CI/CD-Pipeline auszulösen, wann immer Sie eine neue Version Ihrer Dokumentation bereitstellen. --- ## [CDN- & Edge-Deployment](https://docs.docmd.io/de/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN- & Edge-Deployment" description: "So minimieren Sie die globale Latenz, indem Sie Ihre statische Dokumentation auf einem Content Delivery Network (CDN) oder Edge-Netzwerk bereitstellen." --- ## Problem Das Hosting Ihrer Dokumentation auf einem einzelnen Server in einer geografischen Region (z. B. US-East) bedeutet, dass Benutzer in anderen Teilen der Welt (z. B. Europa oder Asien) eine erhebliche Netzwerklatenz erfahren. Jeder Seitenaufruf, jedes Bild und jedes Skript muss Tausende von Kilometern zurücklegen, wodurch sich Ihre Dokumentation für ein globales Publikum träge und langsam anfühlt. ## Warum es wichtig ist Hohe Latenz schadet direkt der Developer Experience. Selbst wenn Ihre Dokumentation gut geschrieben und leichtgewichtig ist, wird die "Time to First Byte" (TTFB) durch die Gesetze der Physik begrenzt. Wenn sich Ihre Website langsam anfühlt, verlieren Entwickler eher den Fokus oder geben Ihr Tool ganz zugunsten eines anderen mit schnellerer, besser zugänglicher Dokumentation auf. ## Ansatz Die optimale Lösung besteht darin, Ihre Website auf einem Edge-CDN bereitzustellen. Da `docmd` rein statische Assets generiert (HTML, CSS, JS), ist es perfekt für die Verteilung über Edge-Netzwerke geeignet. CDNs replizieren Ihre Dateien auf Hunderte von weltweit verteilten "Edge-Nodes" und bedienen Ihre Benutzer vom nächstgelegenen Rechenzentrum aus. ## Implementierung ### 1. Plattform wählen `docmd` ist nativ kompatibel mit allen modernen statischen Hosting- und Edge-Plattformen. Wir empfehlen die folgenden aufgrund ihrer globalen Performance und einfachen Handhabung: * **Cloudflare Pages**: Extrem schnelles globales Edge-Netzwerk mit integriertem DDoS-Schutz. * **Vercel**: Optimiert für Performance mit exzellenter Integration in den Entwickler-Workflow. * **Netlify**: Leistungsstarke Automatisierungsfunktionen und ein robustes globales CDN. ### 2. Build automatisieren Verwenden Sie eine CI/CD-Pipeline, um Ihre Website automatisch zu erstellen und bereitzustellen, wann immer Sie Änderungen pushen. Detaillierte Beispiele finden Sie im [GitHub Actions Leitfaden](../../guides/integrations/github-actions-cicd). ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # Buildet die Website in das Standard-Verzeichnis 'site/' - run: npm install && npx @docmd/core build # Beispiel: Deployment auf Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: mein-projekt directory: site ``` ### 3. Verifizierung Nach dem Deployment können Sie Ihre globale Performance mit Tools wie PageSpeed Insights oder globalen Ping-Tests überprüfen. Sie sollten Antwortzeiten unter 100 ms von fast jedem Standort weltweit sehen. ## Abwägungen Globale Edge-Netzwerke nehmen Ihnen das Server-Management ab, was ein großer Vorteil für Dokumentationsteams ist. Das Debuggen regionaler Caching-Probleme kann jedoch gelegentlich komplexer sein als das Überprüfen eines einzelnen Server-Logs. Die Verwendung von Plattformen mit robuster "sofortiger Cache-Invalidierung" stellt sicher, dass Ihre Benutzer unmittelbar nach einem Deployment immer die neueste Version Ihrer Dokumentation sehen. --- ## [Optimierung für Low-End-Geräte](https://docs.docmd.io/de/guides/performance-delivery/low-end-devices/) --- title: "Optimierung für Low-End-Geräte" description: "So erstellen Sie leistungsstarke, barrierefreie Dokumentationen, die auf schwächerer Hardware und bei langsamen Netzwerkverbindungen nahtlos funktionieren." --- ## Problem Moderne Dokumentations-Websites verlassen sich oft auf schwere JavaScript-Runtimes, nur um statischen Text anzuzeigen. Für Benutzer mit älteren Mobiltelefonen, günstigen Laptops oder langsamen 3G/4G-Verbindungen kann das Laden dieser Seiten mehrere Sekunden dauern. Der Prozessor des Geräts hat Mühe, große JS-Bundles zu verarbeiten, was zu "Input-Lag", ruckelnden Animationen und einem insgesamt schlechten Leseerlebnis führt. ## Warum es wichtig ist Technische Dokumentationen sollten universell zugänglich sein. Wenn Benutzer in Schwellenländern oder mit eingeschränkter Hardware gezwungen sind, ein schweres Framework herunterzuladen und auszuführen, nur um ein Tutorial zu lesen, schafft dies eine unnötige Hürde beim Lernen. Eine leichtgewichtige Website stellt sicher, dass Ihre Produktinformationen für jeden verfügbar sind, unabhängig von der Hardware oder Internetgeschwindigkeit. ## Ansatz Setzen Sie auf eine **HTML-First-Strategie**. `docmd` ist mit einer Zero-Framework-Architektur konzipiert, die sicherstellt, dass der primäre Inhalt während des Build-Prozesses in Standard-HTML gerendert wird. Dies hält den Hauptthread des Browsers frei und gewährleistet flüssiges Scrollen sowie eine schnelle Navigation, selbst auf Budget-Geräten. ## Implementierung ### 1. Minimaler Runtime-Footprint Standardmäßig verwendet `docmd` weder React, Vue noch ein anderes schweres clientseitiges Framework für seine Kern-UI. Dieser vorgerenderte Ansatz stellt sicher, dass der erste "First Contentful Paint" fast sofort erfolgt. Um diese Performance beizubehalten: * **Eigene Skripte begrenzen**: Vermeiden Sie das Hinzufügen großer Drittanbieter-Bibliotheken in Ihrer `customJs`-Konfiguration. * **Native Browser-Funktionen nutzen**: Verlassen Sie sich auf Standard-CSS und HTML5-Elemente, die von allen modernen Browsern hochgradig optimiert sind. ### 2. Strategisches Plugin-Management Während [Plugins](../../plugins/usage) leistungsstarke Funktionen hinzufügen, können sie einen erheblichen Performance-Overhead verursachen. Zum Beispiel benötigt das [Mermaid-Plugin](../../plugins/mermaid) eine große Engine, um Diagramme zu rendern. Wenn Ihre Benutzer hauptsächlich Low-End-Geräte verwenden, sollten Sie statische Bilder für Diagramme anstelle von clientseitigem Rendering in Betracht ziehen. ### 3. Responsive und optimierte Medien Vermeiden Sie es, übergroße Bilder an mobile Benutzer auszuliefern. Verwenden Sie moderne Formate wie WebP und nutzen Sie das `<picture>`-Tag für eine granulare Kontrolle über responsive Assets. ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="Feature-Übersicht" loading="lazy"> </picture> ``` Die Verwendung des Attributs `loading="lazy"` stellt sicher, dass Bilder erst heruntergeladen werden, wenn sie in den Viewport des Benutzers gelangen, was Bandbreite bei langsamen Verbindungen spart. ### 4. Effiziente Suchindexierung `docmd` generiert "gescopte" Suchindizes, um den Speicherbedarf gering zu halten. Bei extrem großen Websites kann das [Search-Plugin](../../plugins/search) jedoch weiterhin speicherintensiv sein. Ermutigen Sie mobile Benutzer, die Suchleiste nur bei Bedarf zu verwenden, oder optimieren Sie Ihren Index, wie im [Local-First Suchleitfaden](../search/local-first-search) beschrieben. ## Abwägungen Die Priorisierung der Performance für Low-End-Geräte bedeutet oft, auf "schwere" interaktive Funktionen wie komplexe 3D-Visualisierungen oder große clientseitige Datenverarbeitung zu verzichten. Dies ist eine bewusste Designentscheidung, die **Inklusivität und Geschwindigkeit** über visuelle Komplexität stellt und sicherstellt, dass Ihre Dokumentation für ein möglichst breites Publikum eine nützliche Ressource bleibt. --- ## [JS-Payload reduzieren](https://docs.docmd.io/de/guides/performance-delivery/reducing-javascript-payload/) --- title: "JS-Payload reduzieren" description: "So erhalten Sie eine leistungsstarke Dokumentations-Website, indem Sie Ihre JavaScript-Abhängigkeiten optimieren und die Zero-Framework-Architektur von docmd nutzen." --- ## Problem Viele moderne Dokumentationswerkzeuge verlassen sich auf schwere JavaScript-Frameworks (wie React oder Vue), nur um statischen Text zu rendern. Diese Frameworks können mehrere hundert Kilobyte zu Ihrer initialen Seitenlast hinzufügen und zwingen den Browser dazu, große Mengen an Code herunterzuladen, zu parsen und auszuführen, bevor die Seite vollständig interaktiv wird. Dies führt zu langsamen Ladezeiten und "Ghost-Clicks" auf leistungsschwächeren Geräten. ## Warum es wichtig ist Ein großer JavaScript-Payload beeinflusst direkt die "Time to Interactive" (TTI). In der technischen Dokumentation, wo Benutzer schnell Antworten benötigen, ist jede Verzögerung durch eine schwere Framework-Initialisierung eine erhebliche Hürde für die Benutzerfreundlichkeit. Wenn Sie Ihren Payload klein halten, stellen Sie sicher, dass Suche, Navigation und Theme-Wechsel von dem Moment an, in dem die Seite erscheint, augenblicklich funktionieren. ## Ansatz `docmd` verwendet eine **Zero-Framework-Architektur** für seine Kern-Client-Logik. Durch die Nutzung von Vanilla JavaScript und nativen Browser-APIs anstelle eines schweren virtuellen DOM halten wir den gesamten JS-Payload für eine Standard-Website unter **20 KB**. Dieses leichtgewichtige Fundament gewährleistet maximale Performance auf allen Geräten und unter allen Netzwerkbedingungen. ## Implementierung ### 1. Native Browser-APIs nutzen Vermeiden Sie den Import schwerer Bibliotheken wie jQuery oder Lodash für einfache Aufgaben. Moderne Browser verfügen über robuste native APIs, die fast jede dokumentationsbezogene Anforderung ohne Overhead bewältigen können. ```json { // Fügen Sie benutzerdefinierte Skripte in docmd.config.json hinzu "customJs": ["/static/js/meine-eigene-logik.js"] } ``` ### 2. Strategisches Plugin-Management Während [Plugins](../../plugins/usage) leistungsstarke Funktionen hinzufügen, können einige Ihren JavaScript-Payload erheblich vergrößern. Zum Beispiel benötigt das [Mermaid-Plugin](../../plugins/mermaid) eine große clientseitige Bibliothek, um Diagramme zu rendern. Aktivieren Sie schwere Plugins nur, wenn sie für Ihren Inhalt essenziell sind, und berücksichtigen Sie deren Auswirkungen auf das Gesamtgewicht der Seite. ### 3. Nicht-kritische Skripte verzögert laden Wenn Sie Drittanbieter-Dienste wie Analytics oder Feedback-Widgets einbinden müssen, stellen Sie sicher, dass diese asynchron oder verzögert geladen werden, damit sie das Rendering Ihrer Dokumentation nicht blockieren. ```html <!-- In Ihrer benutzerdefinierten Head-Injektion --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. Assets optimieren Stellen Sie sicher, dass jedes von Ihnen bereitgestellte benutzerdefinierte JavaScript minifiziert und komprimiert ist. `docmd` übernimmt die Minifizierung seiner Kern-Assets, aber Sie sind für die Optimierung aller Dateien verantwortlich, die Sie Ihrem `static/`-Verzeichnis hinzufügen. ## Abwägungen Das Erstellen komplexer interaktiver Funktionen mit Vanilla JavaScript kann mehr manuellen Aufwand erfordern als die Verwendung eines deklarativen Frameworks. Für die Dokumentation jedoch , wo 95 % des Inhalts aus statischem Text und Bildern bestehen , überwiegen die Performance-Vorteile eines Zero-Framework-Ansatzes bei weitem die Bequemlichkeit eines schweren Frameworks. --- ## [Sub-100ms Navigation](https://docs.docmd.io/de/guides/performance-delivery/sub-100ms-navigation/) --- title: "Sub-100ms Navigation" description: "Wie der native SPA-Router von docmd und das intentionsbasierte Prefetching sofortige Seitenübergänge für ein optimales Leseerlebnis ermöglichen." --- ## Problem Herkömmliche Multi-Page-Navigation, bei der jeder Klick auf einen Link ein vollständiges Neuladen des Browsers auslöst, erzeugt ein störendes "weißes Blinken" und unterbricht den Lesefluss. Der Browser muss den aktuellen Status verwerfen, neues HTML anfordern und CSS sowie JavaScript neu parsen , selbst wenn sich nur der zentrale Inhaltsbereich geändert hat. ## Warum es wichtig ist Dokumentationsbenutzer springen häufig zwischen verschiedenen Abschnitten wie Tutorials, API-Referenzen und konzeptionellen Anleitungen hin und her. Wenn jeder Übergang eine Sekunde oder länger dauert, führt dies zu kognitiver Reibung und entmutigt eine gründliche Exploration. Eine sofortige Navigation sorgt dafür, dass sich die Dokumentation wie eine native Anwendung anfühlt, was die Benutzerzufriedenheit und das Engagement erheblich steigert. ## Ansatz `docmd` nutzt einen leistungsstarken **Single Page Application (SPA) Router**, der auf vorab generierten statischen Dateien aufbaut. Dies ermöglicht es dem Browser, Klicks auf Links abzufangen, nur die notwendigen Inhalte im Hintergrund abzurufen und die Seite dynamisch zu aktualisieren, ohne sie vollständig neu zu laden. Dieser Ansatz bewahrt den Status der Sidebar, des Inhaltsverzeichnisses und der Theme-Einstellungen, was zu nahezu sofortigen Übergängen führt. ## Implementierung Der `docmd` SPA-Router ist standardmäßig aktiviert und nutzt mehrere fortschrittliche Techniken, um Navigationsgeschwindigkeiten unter 100 ms zu erreichen: ### 1. Intentionsbasiertes Prefetching Wenn ein Benutzer mit der Maus über einen Navigationslink fährt, erkennt `docmd` die Absicht zur Navigation und startet im Hintergrund das Abrufen der Inhalte der Zielseite. Bis der Benutzer den Link tatsächlich klickt, sind die Daten oft schon im Browser-Cache verfügbar, wodurch sich der Übergang augenblicklich anfühlt. ### 2. Partielle DOM-Updates Anstatt die gesamte Seite neu zu rendern, aktualisiert `docmd` intelligent nur die notwendigen Funktionszonen: * **Hauptinhalt (Main Content)**: Der primäre, per Markdown gerenderte Textkörper. * **Inhaltsverzeichnis (TOC)**: Wird aktualisiert, um den Überschriften der neuen Seite zu entsprechen. * **Navigationsstatus**: Aktualisiert die aktiven und ausgeklappten Zustände in der Sidebar. ### 3. Lifecycle-Events für eigene Logik Da der Browser kein vollständiges Neuladen durchführt, werden Standard-Events wie `DOMContentLoaded` nur einmal ausgelöst. Um nach jeder Navigation eigenen JavaScript-Code auszuführen , wie das Neuinitialisieren eines Drittanbieter-Widgets oder das Tracking von Seitenaufrufen , sollten Sie auf das Event `docmd:page-mounted` hören. ```javascript // Beispiel: Neuinitialisierung einer eigenen Komponente nach der Navigation document.addEventListener('docmd:page-mounted', (event) => { const currentPath = event.detail.path; console.log(`Erfolgreich navigiert zu: ${currentPath}`); // Eigene Logik hier if (currentPath.includes('/api/')) { initApiConsole(); } }); ``` Weitere Details finden Sie in der Dokumentation zu [Client-seitigen Events](../../api/client-side-events). ## Abwägungen ### Skript-Ausführung Der SPA-Router führt `<script>`-Tags, die sich im Markdown-Textkörper der neuen Seite befinden, automatisch neu aus. Globale Skripte, die in Ihrem Theme oder Layout definiert sind, laufen jedoch nur einmal beim ersten Laden. Verwenden Sie immer das Event `docmd:page-mounted` für Logik, die auf jeder Seite ausgeführt werden muss. ### SEO und Barrierefreiheit Trotz des SPA-ähnlichen Verhaltens generiert `docmd` weiterhin eine vollständige, eigenständige `.html`-Datei für jede Seite. Dies stellt sicher, dass Suchmaschinen-Crawler den vollständigen Inhalt sehen können und die Website auch für Benutzer mit deaktiviertem JavaScript funktionsfähig bleibt, was exzellente SEO- und Barrierefreiheitsstandards gewährleistet. --- ## [Breaking Changes & Veraltete Funktionen](https://docs.docmd.io/de/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "Breaking Changes & Veraltete Funktionen" description: "So kommunizieren Sie API-Änderungen und Migrationspfade effektiv durch versionierte Dokumentation und kontextbezogene Callouts." --- ## Problem Wenn ein Produkt eine neue Hauptversion einführt, werden bestimmte APIs, Funktionen oder Konfigurationen zwangsläufig als veraltet markiert oder entfernt. Benutzer, die die neueste Dokumentation durchsuchen, müssen klar gewarnt werden, wenn sie veraltete Muster verwenden. Gleichzeitig sollte sich die Dokumentation auf die moderne Implementierung konzentrieren, um Verwirrung zu vermeiden. ## Warum es wichtig ist Das Versäumnis, Breaking Changes explizit hervorzuheben, führt dazu, dass Entwickler Stunden mit dem Debuggen von Code verschwenden, der von der Engine nicht mehr unterstützt wird. Kontextbezogene Warnungen und klare Migrationspfade sind essenziell, um das Vertrauen der Benutzer zu erhalten, Supportanfragen zu reduzieren und einen reibungslosen Übergang zur neuesten Version Ihrer Software zu gewährleisten. ## Ansatz Kombinieren Sie die [Versioning Engine](../../configuration/versioning.md) von `docmd` mit [Callout-Containern](../../content/containers/callouts.md), um eine klare Trennung zwischen Legacy- und modernen Inhalten zu schaffen. Die Strategie besteht darin, die vollständige Legacy-Dokumentation in eine archivierte Version zu verschieben und gleichzeitig "Migrations-Anker" in der aktuellen Version bereitzustellen, die auf die archivierten Inhalte verweisen. ## Implementierung ### 1. Archivierung von Legacy-Inhalten Verschieben Sie bei der Veröffentlichung einer neuen Hauptversion (z. B. v2.0) Ihre bestehende Dokumentation in ein Archivverzeichnis (z. B. `docs-v1/`). Dies stellt sicher, dass der vollständige Kontext der vorherigen Version für Benutzer erhalten bleibt, die noch nicht migriert sind. ### 2. Kontextbezogene Migrations-Callouts Verwenden Sie in Ihrer neuesten Dokumentation `warning`- oder `important`-Callouts am Anfang von Seiten, auf denen signifikante Änderungen vorgenommen wurden. Dies bietet Benutzern, die versuchen, Legacy-Muster zu verwenden, einen sofortigen Mehrwert. ```markdown # Konfigurations-API ::: callout warning "Migration: Breaking Change in v2.0" Die Eigenschaft `siteTitle` wurde entfernt. Sie wurde durch die globale Eigenschaft `title` ersetzt. * **Migration von v1.x?** Bitte aktualisieren Sie Ihre `docmd.config.js`. * **Benötigen Sie v1.x-Docs?** Siehe [Legacy-Konfigurationsanleitung](../../configuration/overview.md). ::: ``` ### 3. Aufrechterhaltung der AI-Genauigkeit Durch die strikte Trennung von veralteten Inhalten von der aktiven Version verbessern Sie die Genauigkeit von KI-Tools erheblich. Das [LLMs-Plugin](../../plugins/llms.md) von `docmd` generiert Kontextdateien basierend auf der aktiven Version. Die Archivierung von Legacy-Inhalten verhindert, dass KI-Modelle "halluzinieren" und Benutzern, die nach modernen Lösungen suchen, veraltete APIs empfehlen. ## Abwägungen Das aktive Verwalten von Migrations-Callouts bedeutet zusätzlichen Wartungsaufwand. Wenn sie unbefristet stehen bleiben, können Seiten mit alten Warnungen überladen werden. Wir empfehlen eine Richtlinie, Migrations-Callouts zu entfernen, sobald die Legacy-Version ihr Lebensende (EOL) erreicht hat oder nach einem vollständigen Hauptversionszyklus, um die Dokumentation schlank und fokussiert zu halten. --- ## [Zusammenarbeit mehrerer Teams](https://docs.docmd.io/de/guides/scaling-architecture/multi-team-collaboration/) --- title: "Zusammenarbeit mehrerer Teams" description: "So nutzen Sie dezentrale Navigation und globale Menüleisten, um mehreren Teams die Zusammenarbeit an einem einheitlichen Dokumentationsprojekt ohne Reibungsverluste zu ermöglichen." --- ## Problem Wenn mehrere unabhängige Teams (z. B. Frontend, Backend, DevOps und Produkt) zu einem einzigen Dokumentations-Repository beitragen, entstehen oft organisatorische Reibungsverluste. Teams könnten versehentlich globale Navigationseinstellungen überschreiben, widersprüchliche Design-Paradigmen erstellen oder bei gleichzeitigen Updates Links über Domänengrenzen hinweg beschädigen. ## Warum es wichtig ist Reibung im Authoring-Prozess führt zu "Dokumentations-Silos", in denen Teams unabhängige, isolierte Wikis erstellen, um der Komplexität eines gemeinsamen Repositorys zu entgehen. Dies zerstört die einheitliche User Experience eines zentralen Dokumentationsportals und macht es für Benutzer erheblich schwerer, umfassende Informationen über das gesamte System zu finden. ## Ansatz Nutzen Sie das dezentrale [Auflösungsprioritätssystem](../../configuration/navigation#navigation-resolution-priority) von `docmd`. Dies ermöglicht es einzelnen Teams, mithilfe lokaler `navigation.json`-Dateien die volle Autonomie über ihre spezifischen Domänen zu behalten, während ein zentrales Team die globale [Menüleiste](../../configuration/menubar) und das visuelle Designsystem verwaltet. ## Implementierung ### 1. Domänenbasierte Verantwortlichkeit Unterteilen Sie Ihre Dokumentation in Top-Level-Verzeichnisse, die spezifischen Teams zugewiesen sind. Jedes Team ist vollständig für den Inhalt und die interne Struktur seines zugewiesenen Ordners verantwortlich. ```text mein-projekt/ ├── docs/ │ ├── frontend/ # Gehört dem UI-Team │ │ ├── navigation.json # Teamspezifische Sidebar │ │ └── komponenten.md │ ├── backend/ # Gehört dem API-Team │ │ ├── navigation.json │ │ └── datenbank.md │ └── docmd.config.json # Gehört dem Plattform-/Core-Team ``` ### 2. Globaler Kontextwechsel (Die Menüleiste) Das zentrale Plattform-Team steuert die [Menüleiste](../../configuration/menubar), die als primäre Navigationsebene dient, um zwischen den verschiedenen Team-Domänen zu wechseln. ```json { "menubar": { "enabled": true, "items": [ { "text": "Frontend", "url": "/frontend/komponenten" }, { "text": "Backend", "url": "/backend/datenbank" }, { "text": "Infrastruktur", "url": "/devops/setup" } ] } } ``` ### 3. Lokale Autonomie mit navigation.json Wenn ein Benutzer Inhalte innerhalb des `/frontend/`-Verzeichnisses durchsucht, priorisiert `docmd` automatisch die Datei `frontend/navigation.json`. Die Sidebar wird dynamisch aktualisiert und spiegelt nur die frontend-spezifische Hierarchie wider, wodurch verhindert wird, dass die Navigation durch unzusammenhängende Informationen anderer Teams überladen wird. ```json // docs/frontend/navigation.json [ { "title": "Design System", "path": "/frontend/design-system" }, { "title": "Komponenten-Bibliothek", "path": "/frontend/komponenten" } ] ``` ## Abwägungen Dezentrale Navigation erfordert von den Teams Sorgfalt bei domänenübergreifenden Links. Während `docmd` relative Links effektiv verarbeitet, bricht das Verschieben eines kompletten Team-Verzeichnisses die Links in den Dateien anderer Teams. Wir empfehlen die Verwendung von pfad-relativen Pfaden (beginnend mit `/`) für Links zwischen verschiedenen Team-Domänen, um Stabilität zu gewährleisten. --- ## [Verwalten von mehrversionigen Dokumentationen](https://docs.docmd.io/de/guides/scaling-architecture/multi-version-documentation/) --- title: "Verwalten von mehrversionigen Dokumentationen" description: "So pflegen Sie mehrere Versionen Ihrer Dokumentation (v1, v2, Legacy) mit einem einheitlichen Switcher und Pfaderhaltung." --- ## Problem Softwareprodukte entwickeln sich weiter, aber Unternehmenskunden bleiben oft bei älteren LTS-Versionen (Long Term Support). Wenn die Dokumentation für v1 bei der Veröffentlichung von v2 eingestellt wird, lässt man diese Benutzer im Stich. Gleichzeitig führt das Pflegen komplett separater Websites für jede Version zu einer fragmentierten User Experience und einer Schwächung der SEO. ## Warum es wichtig ist Ohne eine nahtlose Möglichkeit zum Wechseln zwischen Versionen wenden Entwickler fälschlicherweise Anweisungen aus der neuesten Dokumentation auf Legacy-Umgebungen an, was zu Fehlern und erhöhtem Supportaufwand führt. Ein einheitliches Versionierungssystem stellt sicher, dass Benutzer immer wissen, in welchem Kontext sie sich befinden, und einfach zwischen den Versionen derselben Seite springen können. ## Ansatz `docmd` verfügt über eine native [Versioning Engine](../../configuration/versioning), die Versionen als erstklassige Bestandteile behandelt. Sie isoliert Builds in Verzeichnisse mit Versionspräfix, bietet einen "Sticky Switching"-Mechanismus, der den aktuellen Seitenpfad beibehält, und beschränkt Suchergebnisse korrekt auf den aktiven Versionskontext. ## Implementierung ### 1. Quellverzeichnisse organisieren Bewahren Sie Ihre aktuellste Dokumentation in einem Standardverzeichnis (z. B. `docs/`) auf und platzieren Sie Legacy-Versionen in Geschwisterverzeichnissen (z. B. `docs-v1/`). ```text mein-projekt/ ├── docs/ # v2.x (Aktuell) ├── docs-v1/ # v1.x (Legacy LTS) └── docmd.config.json ``` ### 2. Versions-Map konfigurieren Definieren Sie Ihre Versionsstruktur in der `docmd.config.json`. Die `current`-Version wird unter der Root-URL bereitgestellt, während andere unter `/{id}/` erreichbar sind. ```json { "versions": { "current": "v2", "position": "sidebar-top", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (Aktuell)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x (LTS)" } ] } } ``` ### 3. Navigation pro Version Wenn sich die Navigationsstruktur zwischen den Versionen unterscheidet, können Sie eine `navigation.json`-Datei in das Quellverzeichnis der jeweiligen Version legen. `docmd` erkennt diese automatisch und verwendet sie für diese spezifische Version. ```json // docs-v1/navigation.json [ { "title": "Legacy Setup", "path": "/legacy-setup" }, { "title": "Migration zu v2", "path": "/migration" } ] ``` ### 4. Pfaderhaltung (Sticky Switching) `docmd` versucht automatisch, den aktuellen Pfad des Benutzers beizubehalten, wenn dieser die Version wechselt. Wenn sich ein Benutzer auf der `v2`-Seite unter `/api/auth` befindet und zu `v1` wechselt, versucht die Engine, ihn zu `/v1/api/auth` zu leiten. Wenn die Seite in der Zielversion nicht existiert, erfolgt ein Fallback auf die Startseite dieser Version. ## Abwägungen Das Speichern mehrerer Versionen in einem einzigen Repository erhöht die Größe des Repositorys im Laufe der Zeit. Bei sehr großen Dokumentationsmengen sollten Sie in Erwägung ziehen, Legacy-Verzeichnisse während des Build-Prozesses dynamisch über CI/CD einzubinden, anstatt sie fest in den Haupt-Branch einzuchecken. --- ## [Organisation großer Repositories](https://docs.docmd.io/de/guides/scaling-architecture/organising-large-repositories/) --- title: "Organisation großer Repositories" description: "So bewahren Sie Navigationsklarheit und Benutzerfreundlichkeit in komplexen Dokumentationsstrukturen durch Hub-Pages und hierarchische Navigation." --- ## Problem Wenn ein Dokumentations-Repository auf Hunderte von Seiten anwächst, macht die Anzeige jedes Themas in einer einzigen, riesigen Sidebar die Website unbrauchbar. Benutzer leiden unter "Entscheidungsparalyse", wenn das Finden eines bestimmten Moduls das Scrollen durch Dutzende irrelevanter, ausgeklappter Kategorien erfordert. ## Warum es wichtig ist Navigation ist eine kritische Komponente der User Experience. Ein überladenes Interface mindert die wahrgenommene Qualität Ihres Produkts und erschwert es Entwicklern, die benötigten Antworten zu finden. Wenn sich die Navigation chaotisch anfühlt, gehen Benutzer oft davon aus, dass die Software selbst ebenso schwierig zu bedienen ist. ## Ansatz Implementieren Sie eine hierarchische Gruppierungsstrategie mit der [Navigations-Konfiguration](../../configuration/navigation.md) von `docmd`. Das Grundprinzip besteht darin, Komplexität zu verbergen, bis sie benötigt wird. Verwenden Sie ausklappbare Gruppen und "Hub-Pages", um eine übersichtliche Sidebar zu erhalten und sicherzustellen, dass sich Benutzer auf ihre aktuelle Aufgabe konzentrieren können, ohne überfordert zu werden. ## Implementierung ### 1. Hierarchische Gruppierung Verwenden Sie die Eigenschaft `collapsible` in Ihrer `navigation.json` oder Konfigurationsdatei, um verwandte Seiten zu gruppieren. Dies hält die Sidebar übersichtlich und ermöglicht es Benutzern, nur die Abschnitte auszuklappen, die sie interessieren. ```json // docs/navigation.json [ { "title": "Advanced API", "icon": "braces", "collapsible": true, "children": [ { "title": "Authentifizierung", "path": "/api/auth" }, { "title": "Webhooks", "path": "/api/webhooks" }, { "title": "Rate Limiting", "path": "/api/rate-limiting" } ] } ] ``` ### 2. Implementierung von Hub-Pages Anstatt jede einzelne Seite in der Sidebar anzuzeigen, erstellen Sie zentrale "Hub-Pages", die als Verzeichnisse für bestimmte Teilsysteme dienen. Verwenden Sie [Grids und Cards](../../content/containers/grids.md) um eine visuelle, übergeordnete Übersicht über die verfügbaren Inhalte zu geben. ```markdown # Integrations-Hub ::: grids ::: grid ::: card "Datenbank-Integrationen" icon:database Verbinden Sie Ihre Anwendung mit populären Datenbanken wie Postgres und MongoDB. [Datenbank-Anleitungen ansehen](../integrations/openapi-generation.md) ::: ::: ::: grid ::: card "Payment Gateways" icon:credit-card Erfahren Sie, wie Sie Stripe, PayPal und mehr implementieren. [Payment-Anleitungen ansehen](../integrations/alongside-other-tools.md) ::: ::: ::: ``` ### 3. Nutzung von Breadcrumbs `docmd` generiert automatisch [Breadcrumbs](../../content/syntax/advanced.md#breadcrumbs) für jede Seite, basierend auf Ihrer Ordnerstruktur und Navigationshierarchie. Durch die Verwendung von Hub-Pages können Sie die Sidebar fokussiert halten, während Breadcrumbs den notwendigen Kontext und eine einfache Möglichkeit für Benutzer bieten, in der Hierarchie zurückzunavigieren. ## Abwägungen Die Verwendung von Hub-Pages kann einen zusätzlichen "Klick" erfordern, um tiefergehende Inhalte zu erreichen. Dies ist jedoch in der Regel einem überladenen Seitenmenü vorzuziehen, das das Auffinden von Informationen erschwert. Das Ergebnis ist ein saubereres, professionelleres Interface, das die allgemeine Durchsuchbarkeit und den Fokus Ihrer Dokumentation erheblich verbessert. --- ## [Skalierbare Ordnerstruktur](https://docs.docmd.io/de/guides/scaling-architecture/scalable-folder-structure/) --- title: "Skalierbare Ordnerstruktur" description: "So organisieren Sie umfangreiche Dokumentationsprojekte unter Verwendung des Diátaxis-Frameworks und des Auflösungssystems von docmd." --- ## Problem Kleine Dokumentations-Websites beginnen oft mit einem flachen `docs/`-Ordner. Wenn das Projekt jedoch wächst und mehrere Module, Tutorials, APIs und konzeptionelle Vertiefungen umfasst, wird eine ungeordnete Ordnerstruktur zu einer erheblichen Wartungslast. Dateien sind schwer zu finden, und die Navigations-Seitenleiste wird zu einer überwältigenden "Wand aus Links". ## Warum es wichtig ist Eine ungeordnete Ordnerstruktur führt direkt zu einer verwirrenden Benutzererfahrung, da das Routing und die Standardnavigation von `docmd` von Ihrem Dateisystem abgeleitet werden. Für Autoren führt das Fehlen einer klaren Struktur zu Inhaltsduplikaten und inkonsistenten Benennungen, was die Verwaltung der Dokumentation erschwert, je mehr Mitwirkende dem Projekt beitreten. ## Ansatz Wir empfehlen die Einführung eines Frameworks für Informationsarchitektur wie [Diátaxis](external:https://diataxis.fr/), das Inhalte in vier verschiedene Kategorien unterteilt: Tutorials, How-To Guides (Anleitungen), Reference (Referenz) und Explanation (Erklärung). Die strikte Abbildung dieser Kategorien auf Ihr physisches Dateisystem bietet einen klaren Fahrplan sowohl für Leser als auch für Autoren. ## Implementierung ### 1. Die Diátaxis-Hierarchie Organisieren Sie Ihr Quellverzeichnis in semantische Unterordner. Diese physische Isolierung erleichtert die Verwaltung großer Dateisätze und gewährleistet eine saubere URL-Struktur. ```text my-project/ ├── docs/ │ ├── tutorials/ (Lernorientiert: Schritt-für-Schritt-Lektionen) │ │ └── getting-started.md │ ├── guides/ (Aufgabenorientiert: Lösung spezifischer Probleme) │ │ └── deployment.md │ ├── reference/ (Informationsorientiert: technische Beschreibungen) │ │ └── api-spec.md │ ├── explanation/ (Verständnisorientiert: theoretischer Hintergrund) │ │ └── architecture.md │ └── navigation.json (Definition der Hauptnavigation) └── docmd.config.js ``` ### 2. Strategische Nutzung von navigation.json Anstatt einen massiven Navigationsbaum in Ihrer globalen Konfiguration zu definieren, verwenden Sie `navigation.json`-Dateien in Ihren Quellverzeichnissen. `docmd` folgt einem [Auflösungsprioritätssystem](../../configuration/navigation#navigation-resolution-priority), das es Ihnen ermöglicht, unterschiedliche Seitenleisten-Hierarchien für verschiedene Abschnitte Ihrer Website zu definieren. ```json // docs/navigation.json [ { "title": "Tutorials", "icon": "book-open", "children": [ { "title": "Erste Schritte", "path": "/tutorials/getting-started" } ] }, { "title": "Referenz", "icon": "braces", "children": [ { "title": "API-Spezifikation", "path": "/reference/api-spec" } ] } ] ``` ### 3. Datei-basiertes Routing Denken Sie daran, dass der Speicherort jeder Markdown-Datei in der Ordnerstruktur ihre endgültige URL bestimmt. Beispielsweise wird `docs/guides/auth.md` zu `ihre-seite.com/guides/auth`. Nutzen Sie dies zu Ihrem Vorteil, um intuitive, einprägsame URLs für Ihre Benutzer zu erstellen. ## Abwägungen Strenge Organisations-Frameworks wie Diátaxis erfordern ein klares Verständnis der Inhaltstypen. Technische Redakteure können es gelegentlich als schwierig empfinden, ein bestimmtes Dokument zu kategorisieren (z. B. "Ist dies ein Guide oder ein Tutorial?"). Die Festlegung klarer interner Richtlinien für Beiträge ist unerlässlich, um die Konsistenz zu wahren, während Ihr Team und Ihre Dokumentation wachsen. --- ## [Skalierung auf 1000+ Seiten](https://docs.docmd.io/de/guides/scaling-architecture/scaling/) --- title: "Skalierung auf 1000+ Seiten" description: "So bewahren Sie mit docmd auch in riesigen Dokumentationsprojekten eine hohe Performance und Benutzerfreundlichkeit." --- ## Problem Mit zunehmender Reife eines Softwareprodukts wächst natürlich auch dessen Dokumentation. Wenn ein Projekt auf Hunderte oder Tausende von Markdown-Dateien anwächst, leiden viele Dokumentationsgeneratoren unter trägen Build-Zeiten, langsamen Hot-Reloads des Dev-Servers und Navigationsstrukturen, die sowohl Maintainer als auch Benutzer überfordern. ## Warum es wichtig ist Wenn die Generierung der Dokumentation Minuten statt Sekunden dauert, werden Autoren davon abgehalten, kleine Korrekturen vorzunehmen, was zu veralteten und ungenauen Inhalten führt. Für Benutzer macht ein riesiges, unorganisiertes Sidebar-Menü das Finden von Informationen frustrierend, was zu mehr Support-Anfragen und einer schlechten Developer Experience führt. ## Ansatz `docmd` ist auf Geschwindigkeit und Skalierbarkeit ausgelegt. Durch die Verwendung einer Hochleistungs-Parsing-Engine und einer granularen, dateibasierten Build-Strategie kann es Tausende von Seiten in Sekunden verarbeiten. Die optimierte SPA-Auslieferung (Single Page Application) stellt sicher, dass die Navigation durch eine große Website für den Endbenutzer verzögerungsfrei bleibt. ## Implementierung ### 1. Granulare Projektstruktur Vermeiden Sie es, alle Dateien in einem einzigen flachen Verzeichnis abzulegen. Verwenden Sie eine tief verschachtelte Ordnerstruktur, die die Architektur Ihres Produkts widerspiegelt. Dies macht das Projekt wartungsfreundlicher und ermöglicht es `docmd`, Änderungen während der Entwicklung effizient zu verfolgen. ### 2. Optimierte Suchindexierung Für große Websites ist das [Search-Plugin](../../plugins/search) unerlässlich. `docmd` generiert einen hochkomprimierten Suchindex, der bei Bedarf geladen wird. Dies stellt sicher, dass selbst bei Tausenden von Seiten das erste Laden der Seite schnell bleibt, während gleichzeitig eine Volltextsuche über die gesamte Website ermöglicht wird. ### 3. Versionierung und Archivierung Nutzen Sie die [Versioning Engine](../../configuration/versioning), um Legacy-Inhalte von der aktiven Dokumentation zu trennen. Durch die Isolierung älterer Versionen in eigene Build-Kontexte reduzieren Sie die Anzahl der Seiten, die bei täglichen Updates neu verarbeitet werden müssen, was die Entwicklungsgeschwindigkeit erheblich verbessert. ```json { "versions": { "current": "v3", "all": [ { "id": "v3", "dir": "docs/current", "label": "v3.x (Aktuell)" }, { "id": "v2", "dir": "docs/v2", "label": "v2.x (Legacy)" } ] } } ``` ### 4. Komponentenbasierte Navigation Unterteilen Sie Ihre Navigation mithilfe von `navigation.json`-Dateien in logische Segmente. Dies ermöglicht es Ihnen, separate Sidebar-Hierarchien für verschiedene Abschnitte Ihrer Website zu definieren und so zu verhindern, dass die Hauptnavigation unübersichtlich wird. ## Abwägungen Eine große Website verbraucht während des Build-Prozesses naturgemäß mehr Speicherplatz und RAM. Um auch bei extremen Skalierungen (10.000+ Seiten) Build-Zeiten im Sub-Sekunden-Bereich beizubehalten, sollten Sie eine leistungsstarke CI/CD-Umgebung mit SSD-Speicher und ausreichend RAM in Betracht ziehen, um die parallele Verarbeitung der Dateien zu bewältigen. --- ## [Workspace- & Monorepo-Architektur](https://docs.docmd.io/de/guides/scaling-architecture/workspace-monorepo/) --- title: "Workspace- & Monorepo-Architektur" description: "So nutzen Sie den Workspace-Modus von docmd, um mehrere unabhängige Dokumentationsprojekte aus einem einzigen Repository ohne Redundanz zu verwalten." --- ## Das Problem Große Organisationen pflegen Dokumentationen für mehrere unabhängige Produkte – z. B. ein SDK, ein CLI-Tool und eine Hauptplattform –, die jeweils eigene Versionierungen, Navigationsstrukturen und Release-Zyklen haben. Das Betreiben separater Dokumentations-Websites für jedes Produkt führt zu Redundanz: separate CI-Pipelines, separate Theme-Konfigurationen und separate Deployment-Jobs. ## Warum es wichtig ist Fragmentierte Dokumentation ist schwer zu pflegen und verwirrt die Benutzer. Wenn die SDK-Dokumentation anders aussieht als die Plattform-Dokumentation, verlieren Benutzer das Vertrauen. Wenn jedes Projekt einen eigenen CI-Job benötigt, steigt Ihr Entwicklungsaufwand mit der Anzahl der Produkte. Ein einheitlicher Workspace löst beide Probleme mit einer einzigen Konfigurationsdatei. ## Der Ansatz Verwenden Sie den **Workspace-Modus** von docmd. Definieren Sie alle Projekte in einer einzigen Root-Datei `docmd.config.json`. Legen Sie globale Standardwerte (Theme, Menüleiste, Logo) einmalig fest. Jedes Projekt erbt diese und kann bei Bedarf Werte überschreiben. Ein einziger Build-Befehl erzeugt ein einziges, direkt bereitstellbares Verzeichnis. ## Implementierung ### 1. Repository-Struktur ```text my-org-docs/ ├── assets/ ← Gemeinsames Logo, Favicon, globales CSS ├── main-docs/ ← prefix: / │ ├── docmd.config.json │ └── docs/ ├── sdk-docs/ ← prefix: /sdk │ ├── docmd.config.json │ └── docs/ ├── cli-docs/ ← prefix: /cli │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← Workspace-Root └── package.json ``` ### 2. Root-Workspace-Konfiguration Definieren Sie globale Einstellungen einmal. Alle Projekte erben diese automatisch. ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Plattform-Doku" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK-Referenz" }, { "prefix": "/cli", "src": "cli-docs", "title": "CLI-Referenz" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg", "alt": "My Org" }, "menubar": [ { "text": "Plattform", "url": "/" }, { "text": "SDK", "url": "/sdk" }, { "text": "CLI", "url": "/cli" } ] } ``` ### 3. Projekt-spezifische Konfiguration Jedes Projekt gibt nur das an, was vom Root abweicht. Dieses Beispiel für das SDK-Projekt fügt OpenAPI-Unterstützung hinzu und legt einen eigenen `title` fest: ```json { "title": "SDK-Referenz", "src": "docs", "plugins": { "search": {}, "openapi": {}, "git": { "repo": "https://github.com/my-org/sdk" } }, "versions": { "current": "v2", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (Stabil)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x (Legacy)" } ] } } ``` Das globale `theme`, das `logo` und die `menubar` aus der Root-Konfiguration werden weiterhin angewendet. Das SDK-Projekt fügt lediglich seine eigenen Plugins und Versionen hinzu. ### 4. Build & CI Bauen Sie den gesamten Workspace mit einem einzigen Befehl: ```bash npx @docmd/core build ``` Ein minimaler GitHub Actions-Workflow für CI/CD: ```yaml name: Deploy Docs on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: path: site/ deploy: needs: build runs-on: ubuntu-latest environment: name: github-pages steps: - uses: actions/deploy-pages@v4 ``` Oder generieren Sie den Workflow automatisch: ```bash npx @docmd/core deploy --github-pages ``` ### 5. Projekt-spezifische Entwicklungs-Rebuilds Während der Entwicklung lösen Dateiänderungen gezielte Rebuilds nur für das betroffene Projekt aus: ```bash npx @docmd/core dev ``` - Das Ändern einer Datei in `sdk-docs/docs/` baut nur das SDK-Projekt neu. - Das Ändern der Root-Datei `docmd.config.json` löst einen vollständigen Workspace-Rebuild aus. - Das Ändern einer gemeinsamen `assets/`-Datei baut alle Projekte neu auf. ### 6. Projekt-Switcher Der integrierte Projekt-Switcher ermöglicht es Benutzern, zwischen Projekten zu navigieren, ohne die Dokumentations-Website verlassen zu müssen. Er wird automatisch aus dem `projects`-Array in der Root-Konfiguration befüllt. Das Feld `title` jedes Eintrags wird als Anzeigename verwendet. ```json "switcher": { "enabled": true, "position": "sidebar-top" } ``` Verfügbare Positionen: `sidebar-top` (Standard), `sidebar-bottom`, `options-menu`. ## Abwägungen ### Build-Dauer Das Bauen von 3 Projekten dauert ungefähr dreimal so lange wie das eines einzelnen Projekts. Erwägen Sie bei sehr großen Workspaces (mehr als 10 Projekte), diese in separate CI-Jobs aufzuteilen, die auf einen gemeinsamen CDN-Pfad veröffentlichen. ### Präfixkonflikte Wenn Ihr Root-Projekt einen Ordner namens `sdk/` hat und Sie außerdem ein Projekt mit `prefix: "/sdk"` definieren, gewinnt das präfigierte Projekt. Die Engine gibt eine Warnung aus. Überprüfen Sie Ihre Verzeichnisstruktur, bevor Sie neue Präfixe hinzufügen. ### Gemeinsame Navigation Ein globales `navigation`-Array in der Root-Konfiguration ist als Fallback nützlich. Jedes Projekt sollte jedoch im Idealfall seine eigene `navigation.json` für eine präzise Steuerung verwalten. Siehe [Navigationskonfiguration](../../configuration/navigation.md). --- ## [Schnelle & präzise Suche](https://docs.docmd.io/de/guides/search/fast-accurate-search/) --- title: "Schnelle & präzise Suche" description: "Wie docmd die Suchindexierung für Geschwindigkeit und Genauigkeit optimiert, selbst in großen Dokumentationsprojekten." --- ## Problem Wenn eine Dokumentation auf Hunderte oder Tausende von Seiten anwächst, kann der kompilierte Suchindex sehr groß werden. Eine monolithische Indexdatei kann den Hauptthread des Browsers während des Downloads und Parsens blockieren, was die "Time to Interactive" verzögert und dazu führt, dass sich die Suchoberfläche träge oder nicht reaktionsfähig anfühlt. ## Warum es wichtig ist Das primäre Ziel der Dokumentationssuche ist die "Time to Answer". Wenn ein Benutzer das Suchmodal aufruft und mehrere Sekunden warten muss, bis der Index geladen ist, geht der Nutzen des Suchwerkzeugs verloren. Schnelle, präzise Suchergebnisse sind essenziell, um eine professionelle Developer Experience zu bieten und Benutzern zu helfen, Informationen reibungslos zu finden. ## Ansatz `docmd` verwendet eine optimierte Indexierungsstrategie, die von einer leistungsstarken Suchbibliothek angetrieben wird. Es setzt auf **Scoping**, **inkrementelles Laden** und **Feldoptimierung**, um sicherzustellen, dass Suchergebnisse fast augenblicklich geliefert werden, unabhängig von der Größe der Dokumentations-Website. ## Implementierung ### 1. Gescopte Suchindizes `docmd` generiert automatisch separate Suchindizes für jedes [Locale](../../configuration/localisation/index.md) und jede [Version](../../configuration/versioning.md). Dies stellt sicher, dass ein Benutzer nur den für seinen aktuellen Kontext relevanten Index herunterlädt. Beispielsweise lädt ein Benutzer, der die deutsche Version Ihrer Dokumentation durchsucht, nur den deutschen Suchindex herunter, was die Payload-Größe erheblich reduziert. ### 2. Intelligentes Field-Stripping Das [Search-Plugin](../../plugins/search.md) ermöglicht es Ihnen zu steuern, welche Inhalte genau indexiert werden. Standardmäßig werden Überschriften und Frontmatter-Metadaten priorisiert, während gängige "Stoppwörter" und unnötige Codesymbole, die den Index ohne Mehrwert aufblähen würden, entfernt werden. Sie können auch spezifische Seiten über die Eigenschaft `search` in Ihrem [Frontmatter](../../content/frontmatter.md) vom Index ausschließen. ```yaml --- title: "Interner Entwickler-Leitfaden" search: false # Diese Seite erscheint nicht in den Suchergebnissen --- ``` ### 3. Lazy Loading & Prefetching Um das erste Laden der Seite schnell zu halten, lädt `docmd` den Suchindex nicht sofort. Stattdessen wird er verzögert im Hintergrund abgerufen oder in dem Moment ausgelöst, in dem ein Benutzer mit der Such-UI interagiert (z. B. durch Klicken auf die Suchleiste oder Verwenden des Tastenkürzels `Cmd+K` / `Ctrl+K`). ### 4. Ranking der Ergebnisse Ergebnisse werden basierend auf einem gewichteten Bewertungssystem eingestuft. Schlüsselwörter, die im Seiten-`title` oder in `h1`-Überschriften gefunden werden, werden deutlich höher gewichtet als solche im Textkörper. Dies stellt sicher, dass die relevantesten Seiten ganz oben in der Ergebnisliste erscheinen. ## Abwägungen Das Ausschließen von Hilfs- oder internen Seiten vom Suchindex erschwert deren Auffindbarkeit. Sie sollten die Eigenschaft `search: false` sparsam einsetzen, um sicherzustellen, dass wertvolle Informationen auffindbar bleiben. Während Lazy Loading die Performance verbessert, können Benutzer mit extrem langsamen Verbindungen eine kurze Verzögerung bemerken, wenn sie zum ersten Mal eine Suche auslösen. --- ## [Suchrelevanz & Struktur](https://docs.docmd.io/de/guides/search/improving-search-relevance/) --- title: "Suchrelevanz & Struktur" description: "So strukturieren Sie Ihre Markdown-Inhalte, um die Suchrelevanz zu verbessern und Benutzern zu helfen, Informationen schneller zu finden." --- ## Problem Suchmaschinen priorisieren Inhalte basierend auf ihrer Struktur. Wenn eine hochwertige Anleitung generische Überschriften wie "Einleitung" oder "Schritt 1" verwendet, weist die Suchmaschine den Kern-Keywords, die in den Absätzen vergraben sind, möglicherweise nicht genügend Gewicht zu. Dies führt dazu, dass relevante Seiten tief in den Suchergebnissen vergraben werden, was Benutzer frustriert, die sofortige Antworten erwarten. ## Warum es wichtig ist Benutzer suchen typischerweise nach spezifischen technischen Begriffen (z. B. "Authentifizierungs-Token" oder "Deployment-Limit") statt nach vollständigen Sätzen. Wenn Ihre Dokumentationsstruktur diese Begriffe nicht hervorhebt, kann die Suchmaschine Ihre Inhalte nicht sicher ranken. Eine hohe Suchrelevanz ist der entscheidende Unterschied zwischen einem Self-Service-Dokumentationsportal und einem hohen Aufkommen an Support-Tickets. ## Ansatz Strukturieren Sie Ihr Markdown so, dass der Suchindexer Kernkonzepte automatisch identifizieren und priorisieren kann. Die Suchmaschine von `docmd` weist dem Seiten-`title`, der `description` und den `headers` ein höheres Gewicht zu als dem Textkörper. Durch die Optimierung dieser strukturellen Elemente verbessern Sie die Auffindbarkeit Ihrer Inhalte erheblich. ## Implementierung ### 1. Frontmatter-Metadaten optimieren Verwenden Sie den [Frontmatter](../../content/frontmatter)-Block, um explizite Schlüsselwörter und eine aussagekräftige Zusammenfassung bereitzustellen. Das [Search-Plugin](../../plugins/search) indexiert diese Felder, um bessere Ergebnisse und nützlichere Snippets in der Such-UI anzuzeigen. ```yaml --- title: "AWS S3 Speicher-Konfiguration" description: "So konfigurieren Sie IAM-Rollen und Bucket-Berechtigungen für die AWS S3-Integration." keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. Semantische Überschriften verwenden Vermeiden Sie generische Überschriften. Fügen Sie stattdessen relevante Schlüsselwörter in Ihre Überschriften ein, um sowohl dem Benutzer als auch der Suchmaschine Kontext zu bieten. * **Niedrige Relevanz:** `## Schritt 1: Konfiguration` * **Hohe Relevanz:** `## Schritt 1: Konfigurieren von AWS IAM-Rollen` ### 3. Callouts für Schlüsselinformationen nutzen Die Verwendung von [Callout-Containern](../../content/containers/callouts) für kritische Warnungen oder "Pro-Tipps" kann ebenfalls die Suchrelevanz verbessern. Inhalte innerhalb von Callouts sind oft semantisch isoliert und können vom Indexer anders gewichtet werden, um wichtige Schritte zur Fehlerbehebung hervorzuheben. ## Abwägungen Die Optimierung der Suchrelevanz erfordert diszipliniertes Schreiben. Wenn sich Ihr Produkt weiterentwickelt, können Schlüsselwörter im Frontmatter veralten, wenn sie nicht regelmäßig überprüft werden. Darüber hinaus kann das Einfügen zu vieler Schlüsselwörter in Überschriften (Keyword-Stuffing) dazu führen, dass sich die Dokumentation repetitiv und weniger natürlich liest. Streben Sie ein Gleichgewicht zwischen SEO und Lesbarkeit an. --- ## [Local-First Suchoptimierung](https://docs.docmd.io/de/guides/search/local-first-search/) --- title: "Local-First Suchoptimierung" description: "So optimieren Sie Ihre Dokumentationsinhalte für die leistungsstarke, clientseitige Suchmaschine von docmd." --- ## Problem Local-First-Suchmaschinen laufen vollständig im Browser und liefern sofortige Ergebnisse ohne Server-Umweg. Das bedeutet jedoch auch, dass sie durch den Speicher und die Rechenleistung des Browsers begrenzt sind. Wenn ein Suchindex nicht ordnungsgemäß optimiert ist, kann er übermäßig viel RAM verbrauchen, was dazu führt, dass der Browser-Tab ruckelt oder sogar abstürzt , besonders auf mobilen Geräten. ## Warum es wichtig ist Eine nahtlose Sucherfahrung ist essenziell für die Produktivität von Entwicklern. Wenn das Suchwerkzeug Performance-Probleme verursacht oder zu viel Speicher verbraucht, werden Benutzer es meiden. Die Optimierung Ihrer Inhalte für die Local-First-Suche stellt sicher, dass Ihre Dokumentation auf allen Geräten und unter allen Netzwerkbedingungen schnell, reaktionsschnell und zuverlässig bleibt. ## Ansatz Das [Search-Plugin](../../plugins/search) von `docmd` verwendet während des Builds eine Extraktions-Pipeline, um einen hochoptimierten Index zu erstellen. Durch das Entfernen unnötiger Daten und die Konzentration auf hochwertige semantische Felder wird sichergestellt, dass der resultierende Index sowohl umfassend als auch leichtgewichtig ist. ## Implementierung ### 1. Extraktion während des Build-Prozesses Während des Builds verarbeitet `docmd` Ihre Markdown-Dateien, um nur den relevantesten Text für die Indexierung zu extrahieren. Dabei werden automatisch entfernt: * HTML-Tags und struktureller Boilerplate-Code. * Markdown-Syntaxzeichen, die keinen semantischen Mehrwert bieten. * Reine Formatierungselemente, die den Index unnötig aufblähen würden. Dies stellt sicher, dass der Indexer nur sauberen, aussagekräftigen Text erhält, was die finale Indexgröße erheblich reduziert. ### 2. Strategische Indexierung mit Frontmatter Sie können [Frontmatter](../../content/frontmatter) verwenden, um explizit zu steuern, wie eine Seite indexiert wird. Wenn eine Seite beispielsweise große Mengen an repetitiven Daten enthält (wie rohe JSON-Logs), die für die Suche nicht nützlich sind, können Sie festlegen, dass nur die Überschriften und Metadaten indexiert werden. ```yaml --- title: "API Log Referenz" search: indexBody: false # Nur Titel und Überschriften indexieren --- ``` ### 3. Clientseitiges Speichermanagement `docmd` verwaltet den Lebenszyklus des Suchindex im Browser sorgfältig. Es verwendet eine On-Demand-Ladestrategie, was bedeutet, dass die Suchmaschine erst initialisiert wird, wenn der Benutzer zum ersten Mal damit interagiert. Dies hält den Footprint beim ersten Laden der Seite gering und stellt sicher, dass Systemressourcen nur bei Bedarf verbraucht werden. ## Abwägungen Das aggressive Entfernen von Inhalten aus dem Suchindex (z. B. das Ausschließen großer Codeblöcke) kann manchmal dazu führen, dass sehr spezifische Ergebnisse fehlen. Sie müssen die Notwendigkeit eines leichtgewichtigen, schnellen Index gegen die Anforderung an eine gründliche Suchabdeckung abwägen. Wir empfehlen, Überschriften und konzeptionelle Beschreibungen zu priorisieren, da dies die häufigsten Suchziele für Entwickler sind. --- ## [Semantische Suche integrieren](https://docs.docmd.io/de/guides/search/semantic-search/) --- title: "Semantische Suche integrieren" description: "So konfigurieren und deployen Sie die clientseitige hybride semantische Suche in docmd unter Verwendung lokaler Vektoreinbettungen." --- ## Das Problem Die traditionelle Volltextsuche stützt sich vollständig auf exakte Keyword-Übereinstimmungen. Wenn ein Benutzer nach "Authentifizierung" sucht, die Seite jedoch nur Begriffe wie "OAuth2" oder "Login" verwendet, findet eine Standard-Suchmaschine den Inhalt nicht. Dies zwingt Autoren zu unnatürlichem Keyword-Stuffing und frustriert Leser, die die benötigten Informationen nicht finden. ## Warum es wichtig ist Moderne Entwickler erwarten intuitive, kontextbezogene Suchfunktionen, die Absichten und Synonyme verstehen. Die Implementierung einer serverseitigen semantischen Suche erfordert in der Regel eine komplexe Infrastruktur wie Vektordatenbanken (z. B. Pinecone oder pgvector), das Hosten von Modellen und das Erstellen von APIs, was den Wartungsaufwand und die monatlichen Hostingkosten erhöht und Sicherheits- sowie Datenschutzbedenken aufwirft. ## Der Ansatz Verwenden Sie das native **Semantische Such-Plugin** von docmd. Es arbeitet vollständig clientseitig in einer hochoptimierten Browser-Laufzeit. Es generiert strukturierte Vektorchunks zum Build-Zeitpunkt über lokale Hugging Face-Modellpipelines und führt ein Reranking unter Verwendung einer hybriden BM25-Keyword-Frequenz und einer Vektor-Kosinus-Ähnlichkeit durch. Es werden niemals Daten an Drittanbieter-APIs gesendet. ## Implementierung ### 1. Semantische Suche in der Konfiguration aktivieren Fügen Sie die Optionen für das `search`-Plugin in Ihre `docmd.config.json` ein. Setzen Sie `semantic` auf `true` und aktivieren Sie `showConfidence`, um semantische Übereinstimmungen in den Suchergebnissen visuell zu kennzeichnen: ```json { "plugins": { "search": { "semantic": true, "showConfidence": true } } } ``` ### 2. Das passende Einbettungsmodell wählen docmd unterstützt sowohl leichtgewichtige, rein englische Modelle als auch umfassende mehrsprachige Modelle. Aktualisieren Sie Ihr Modellprofil über `docmd-search --settings` or definieren Sie es explizit: | Modell-ID | Dimensionen | Größe | Sprachen | Bestens geeignet für | | :--- | :---: | :---: | :--- | :--- | | `Xenova/all-MiniLM-L6-v2` | 384 | ~90 MB | Nur Englisch | Schnelle, präzise englische Dokumentation | | `Xenova/LaBSE` | 768 | ~470 MB | 100+ Sprachen | Absolute beste mehrsprachige Qualität | | `Xenova/paraphrase-multilingual-MiniLM-L12-v2` | 384 | ~220 MB | 50+ Sprachen | Hervorragende Balance für Mehrsprachigkeit | ### 3. Index in CI/CD vorbauen Um Overhead im Browser beim ersten Laden zu vermeiden, generieren Sie die Vektorchunks während Ihres Builds oder in Ihrer CI/CD-Pipeline vorab mit der CLI: ```bash # Bauen Sie den semantischen Suchindex vorab npx docmd-search --build # Führen Sie anschließend den docmd-Build aus npx @docmd/core build ``` Dies erzeugt hochoptimierte statische Vektor-JSON-Chunks in `.docmd-search/`. Wenn ein Benutzer eine Suche durchführt, lädt der Client diese Chunks progressiv im Hintergrund, wodurch die Benutzeroberfläche sofort interaktiv bleibt. ## Abwägungen ### Initiale Asset-Größe Clientseitige Vektoreinbettungen erfordern, dass der Browser beim ersten Suchvorgang eine WebAssembly-Laufzeitumgebung und die vorkompilierte ONNX-Modelldatei herunterlädt. Obwohl diese Assets dauerhaft im Cache-Speicher des Browsers gespeichert werden, kann die Latenz beim ersten Suchvorgang auf langsameren Verbindungen etwas höher sein (~1-2 Sekunden Verzögerung). ### Suchqualität vs. Payload-Größe Die Wahl größerer Modelle wie `LaBSE` bietet eine außergewöhnliche mehrsprachige Qualität, führt jedoch zu größeren Downloads. Für standardmäßige internationale Dokumentations-Websites ist das Modell `paraphrase-multilingual-MiniLM-L12-v2` die empfohlene goldene Mitte zwischen Genauigkeit und Netzwerklast. --- ## [Git-basierte Workflows](https://docs.docmd.io/de/guides/workflows-teams/git-based-workflows/) --- title: "Git-basierte Workflows" description: "So verwalten Sie Dokumentationsbeiträge effektiv mit Git, Pull Requests und automatisierten CI/CD-Checks." --- ## Problem Direkte Pushes in den Hauptzweig der Dokumentation führen oft zu fehlerhaften Links, inkonsistenter Formatierung und ungeprüften technischen Informationen. Gleichzeitig schreckt zu viel Reibung , etwa die Anforderung separater CMS-Accounts , Community-Mitglieder und interne Entwickler davon ab, wertvolle Updates beizusteuern. ## Warum es wichtig ist Zusammenarbeit ist das Lebenselixier großartiger Dokumentation. Wenn ein Entwickler einen Tippfehler oder ein veraltetes Beispiel findet, sollte er in der Lage sein, innerhalb von Minuten eine Korrektur einzureichen. Ein Git-basierter Workflow bietet eine vertraute, transparente und sichere Umgebung für Beiträge und stellt sicher, dass jede Änderung vor der Veröffentlichung geprüft und validiert wird. ## Ansatz Implementieren Sie ein "Pull Request" (PR)-Modell, das durch automatisierte Validierung und Preview-Umgebungen unterstützt wird. `docmd` ist für diesen Workflow konzipiert, da es auf Standard-Markdown-Dateien basiert, die mit vertrauten Git-Tools einfach verglichen (diff), geprüft und gemergt werden können. ## Implementierung ### 1. "Diese Seite bearbeiten"-Links aktivieren Sie können `docmd` so konfigurieren, dass automatisch "Diese Seite bearbeiten"-Links über das [Git-Plugin](../../plugins/git.md) generiert werden. Dies ermöglicht es Benutzern, direkt von einer Dokumentationsseite zur entsprechenden Quelldatei in Ihrem Repository zu springen. ```json { "plugins": { "git": { "repo": "https://github.com/my-org/my-repo", "branch": "main", "editLink": true } } } ``` ### 2. Kontextbezogene Reviews mit Threads Verwenden Sie für komplexe Updates, die detailliertes Feedback erfordern, das [Threads-Plugin](../../plugins/threads.md). Dies ermöglicht es Autoren und Reviewern, während der Review-Phase Inline-Kommentare direkt im Markdown-Inhalt zu hinterlassen, wodurch Diskussionen kontextbezogen bleiben. ```markdown ::: thread "Name des Reviewers" Sollten wir hier ein Code-Beispiel für den neuen Authentifizierungs-Flow einfügen? ::: ``` ### 3. Automatisierte Validierung in der CI Integrieren Sie `docmd` in Ihre CI/CD-Pipeline (z. B. [GitHub Actions](../integrations/github-actions-cicd.md)), um jeden PR zu validieren. Ihre Pipeline sollte mindestens den Build-Befehl ausführen, um sicherzustellen, dass keine Syntaxfehler oder fehlerhafte Konfigurationen eingeführt werden. ```bash # In Ihrer CI-Pipeline npm install npx @docmd/core build ``` ## Abwägungen Strikte Git-Workflows können gelegentlich kleinere Updates verlangsamen, wie das Beheben eines kritischen Tippfehlers oder das Aktualisieren einer Servicestatus-Meldung. Für Teams mit hoher Geschwindigkeit empfehlen wir die Benennung von "Documentation Owners", die die Befugnis haben, kleine Änderungen schnell durchzuwinken, während sie bei signifikanten technischen Updates strenge Review-Standards einhalten. --- ## [Konsistenz wahren](https://docs.docmd.io/de/guides/workflows-teams/maintaining-consistency/) --- title: "Konsistenz wahren" description: "So gewährleisten Sie eine einheitliche Stimme und professionelle Qualität in großen Dokumentationsteams durch Linting und standardisierte Muster." --- ## Problem In großen Teams hat jeder technische Redakteur einen anderen Stil und eigene Vorlieben. Einige verwenden Fettdruck zur Hervorhebung, andere Kursivschrift. Einige bevorzugen "Klicken Sie auf die Schaltfläche", während andere "Wählen Sie die Option" verwenden. Mit der Zeit kann Ihre Dokumentation zu einem "Flickenteppich" aus widersprüchlichen Stilen werden, was es für Benutzer erschwert, Informationen schnell zu erfassen, und das professionelle Vertrauen in Ihr Produkt mindert. ## Warum es wichtig ist Konsistenz schafft Vertrautheit. Wenn Benutzer komplexe APIs oder Workflows erlernen, verlassen sie sich auf ein konsistentes Vokabular und strukturelle Muster, um effektiv durch die Inhalte zu navigieren. Eine einheitliche Stimme sorgt dafür, dass sich Ihre Dokumentation wie ein zusammenhängendes, hochwertiges Produkt anfühlt, was wiederum das Vertrauen in die Software selbst stärkt. ## Ansatz Setzen Sie Konsistenz mechanisch durch [standardisierte Container](../../content/containers) und automatisierte Linting-Tools durch. Indem Sie Low-Level-Stil- und Syntaxprüfungen automatisieren, geben Sie Ihren Redakteuren den Freiraum, sich auf die High-Level-Qualität, Genauigkeit und Klarheit der Inhalte zu konzentrieren. ## Implementierung ### 1. Standardisierte docmd-Muster nutzen Ermutigen Sie alle Mitwirkenden, die integrierten thematischen Container von `docmd` zu verwenden, anstatt mit manueller Markdown-Formatierung zu improvisieren. Dies stellt sicher, dass jede Warnung, jeder Tipp oder Hinweis auf der gesamten Website identisch aussieht und funktioniert. ```markdown <!-- ❌ Vermeiden: inkonsistent und ohne Styling --> **Hinweis:** Bitte starten Sie den Dienst neu. <!-- ✅ Empfohlen: konsistent, barrierefrei und thematisch passend --> ::: callout info Bitte starten Sie den Dienst neu. ::: ``` Die Verwendung von [Callouts](../../content/containers/callouts) stellt sicher, dass Ihre Dokumentation ein professionelles Erscheinungsbild behält und Barrierefreiheitsstandards erfüllt, ohne dass der Autor zusätzlichen Aufwand betreiben muss. ### 2. Prose-Linting implementieren Integrieren Sie Tools wie **Vale** oder **Markdownlint**, um Markenterminologie, Tonfall und Grammatik durchzusetzen. Diese Tools können so konfiguriert werden, dass sie automatisch auf Passiv, voreingenommene Sprache oder falsche Schreibweisen von Produktnamen prüfen. ```ini # Beispiel für .vale.ini MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. Automatisierte Durchsetzung in der CI/CD Integrieren Sie Konsistenzprüfungen in Ihre [GitHub Actions](../../guides/integrations/github-actions-cicd) oder andere CI/CD-Pipelines. Dies stellt sicher, dass jeder Pull Request automatisch auf Stil- und Strukturkonsistenz geprüft wird, bevor er gemergt werden kann. ```bash # Beispiel für einen CI-Schritt zum Linting - name: Dokumentation prüfen run: vale docs/ ``` ## Abwägungen Striktes Linting kann Community-Mitglieder entmutigen, wenn sie bei einer einfachen Tippfehler-Korrektur mit mehreren "Stilfehlern" konfrontiert werden. Wir empfehlen, die Empfindlichkeit Ihres Linters für externe Beiträge auf `warning` zu stellen und den `error`-Status für interne Team-Updates zu reservieren, um ein Gleichgewicht zwischen Konsistenz und Inklusivität zu finden. --- ## [Änderungen vorschauen](https://docs.docmd.io/de/guides/workflows-teams/previewing-changes/) --- title: "Änderungen vorschauen" description: "So richten Sie lokale und cloudbasierte Preview-Umgebungen ein, um sicherzustellen, dass Ihre Dokumentation vor der Veröffentlichung perfekt gerendert wird." --- ## Problem Das Schreiben von Markdown ohne Live-Vorschau führt häufig zu Formatierungsfehlern, fehlerhaften Containern und falschen Bildpfaden, die erst sichtbar werden, wenn der Inhalt bereits live ist. Dies führt zu einer frustrierenden Erfahrung für Benutzer und zu Mehrarbeit für Maintainer, die ständig Hotfixes für einfache Rendering-Probleme nachschieben müssen. ## Warum es wichtig ist Eine qualitativ hochwertige Dokumentation ist essenziell für das Vertrauen der Entwickler. Eine fehlerhafte Warnbox oder nicht gerenderte Syntax wirkt unprofessionell und kann Benutzer sogar über die Funktionsweise Ihrer Software irreführen. Die Dokumentation so zu sehen, wie sie später tatsächlich aussieht, ist der effektivste Weg, um Fehler abzufangen, die Lesbarkeit zu verbessern und eine nahtlose User Experience zu gewährleisten. ## Ansatz Implementieren Sie eine mehrstufige Preview-Strategie: Nutzen Sie den [lokalen Entwicklungsserver](../../getting-started/quick-start#local-development) von `docmd` für sofortiges Feedback während des Schreibens und setzen Sie kurzlebige Cloud-Umgebungen (wie Vercel oder Cloudflare Pages) für finale Reviews innerhalb Ihrer Pull Requests ein. ## Implementierung ### 1. Sofortige lokale Vorschau Der schnellste Weg, Ihre Änderungen zu sehen, ist der Befehl `docmd dev`. Er bietet Hot Module Replacement (HMR), wodurch Ihr Browser automatisch aktualisiert wird, sobald Sie eine Markdown-Datei speichern. ```bash # Lokalen Entwicklungsserver starten npx @docmd/core dev ``` ### 2. Cloudbasierte Preview-Umgebungen Konfigurieren Sie für die gemeinsame Review-Arbeit Ihre CI/CD-Plattform so, dass für jeden Pull Request eindeutige "Preview-URLs" generiert werden. Da `docmd` standardmäßige statische Dateien ausgibt, ist es mit allen gängigen Hosting-Anbietern kompatibel. * **Build-Befehl**: `npx @docmd/core build` * **Output-Verzeichnis**: `site` Dies ermöglicht es Reviewern, genau zu sehen, wie die Änderungen in einer produktionsnahen Umgebung aussehen und funktionieren, bevor sie in den Hauptzweig gemergt werden. ### 3. Gemeinsame Reviews mit Threads Kombinieren Sie Ihre Cloud-Previews mit dem [Threads-Plugin](../../plugins/usage). Dies ermöglicht es Teammitgliedern, Feedback direkt auf der gerenderten Vorschauseite zu hinterlassen, wodurch die Lücke zwischen dem Markdown-Quellcode und der finalen User Experience geschlossen wird. ## Abwägungen Das Erstellen einer vollständigen statischen Website bei jedem Commit in einem riesigen Repository (Tausende von Seiten) kann zeitaufwendig sein und CI/CD-Ressourcen kosten. Um dies zu optimieren, konfigurieren Sie Ihre CI-Pipeline so, dass ein Dokumentations-Build nur dann ausgelöst wird, wenn Dateien innerhalb Ihres Quellverzeichnisses (z. B. `/docs`) geändert wurden. --- ## [Workflow einrichten](https://docs.docmd.io/de/guides/workflows-teams/setting-up-workflow/) --- title: "Workflow einrichten" description: "So etablieren Sie einen hocheffizienten Dokumentations-Workflow für mehrere Autoren unter Verwendung von docmd und Docs-as-Code-Prinzipien." --- ## Problem Wenn Teams kein strukturiertes Dokumentations-Workflow haben, werden Aktualisierungen oft verzögert, vergessen oder nur über Ad-hoc-Nachrichten geteilt. Ohne einen klaren Prozess werden Inhalte fragmentiert, die Formatierung wird inkonsistent und technische Redakteure verbringen mehr Zeit damit, Merge-Konflikte zu lösen, als hochwertige Inhalte zu schreiben. ## Warum es wichtig ist Ohne einen formalen Prozess veraltet die Dokumentation schnell und verliert ihren Wert. Wenn die Aktualisierung der Dokumentation das Warten auf einen langsamen Software-Release-Zyklus erfordert, bleiben Ihre Anleitungen permanent asynchron zu den tatsächlichen Produktfunktionen, was zu Frustration bei den Benutzern und einem erhöhten Supportaufkommen führt. ## Ansatz Entkoppeln Sie das Deployment der Dokumentation von den Software-Release-Zyklen und übernehmen Sie gleichzeitig dieselben robusten Prozesse, die in der Softwareentwicklung verwendet werden (Branches → Pull Requests → CI/CD-Previews). Die Leichtigkeit von `docmd` ermöglicht es Teams, "Documentation as Code" mit minimalem Overhead zu praktizieren und sicherzustellen, dass Ihre Anleitungen so zuverlässig und aktuell sind wie Ihre Software. ## Implementierung ### 1. Repository-Strategie Wählen Sie die Strategie, die am besten zu Ihrer Organisationsstruktur passt: * **Monorepo-Strategie**: Behalten Sie einen `/docs`-Ordner innerhalb Ihres Haupt-Anwendungs-Repositorys. Dies ist ideal, um sicherzustellen, dass Dokumentationsänderungen im selben Pull Request wie der beschriebene Code gemergt werden, was eine perfekte Synchronisation gewährleistet. * **Separate Repository-Strategie**: Am besten geeignet für große Organisationen oder Open-Source-Projekte, bei denen ein dediziertes Team die Dokumentation unabhängig von der Build-Pipeline der Hauptanwendung verwaltet. ### 2. Validierung mit CI/CD Integrieren Sie `docmd` in Ihre CI/CD-Pipeline, um sicherzustellen, dass jedes Update technisch einwandfrei ist. Ihre Pipeline sollte mindestens den Build-Befehl ausführen, um auf Syntaxfehler und Konfigurationsprobleme zu prüfen. ```bash # Beispiel für einen Validierungsschritt in GitHub Actions - name: Dokumentation validieren run: npm install && npx @docmd/core build ``` Detaillierte Setup-Anweisungen finden Sie im [GitHub Actions Leitfaden](../../guides/integrations/github-actions-cicd). ### 3. Kollaborativer Review-Prozess Etablieren Sie eine Kultur des Peer-Reviews für alle Dokumentations-Updates. Nutzen Sie Pull Requests, um Änderungen zu diskutieren, die Formatierung zu überprüfen und die technische Genauigkeit sicherzustellen. Sie können das [Threads-Plugin](../../plugins/usage) nutzen, um detaillierte Diskussionen direkt am gerenderten Inhalt zu führen. ## Abwägungen Die Einführung eines "Docs-as-Code"-Workflows kann eine Hürde für nicht-technische Mitarbeiter (z. B. Produktmanager oder Rechtsabteilung) darstellen, die Git und Markdown möglicherweise einschüchternd finden. Um dies abzumildern, sollten Sie den integrierten Web-Editor von GitHub für kleinere Korrekturen in Betracht ziehen oder die [Live-Preview](../../content/live-preview)-Funktion nutzen, um ein visuelles und intuitiveres Authoring-Erlebnis zu bieten. --- ## [Versionierungs-Workflows](https://docs.docmd.io/de/guides/workflows-teams/versioning-release-workflows/) --- title: "Versionierungs-Workflows" description: "So synchronisieren Sie Dokumentations-Releases mit Software-Deployments unter Verwendung der Versionierungs-Engine und der Promotions-Strategien von docmd." --- ## Problem Die Synchronisierung von Software-Releases mit den entsprechenden Dokumentations-Updates ist eine erhebliche Koordinationsherausforderung. Häufig wird die Dokumentation auf der Live-Site aktualisiert, bevor der neue Code bereitgestellt wurde (was aktuelle Benutzer verwirrt), oder sie wird erst Tage nach dem Release veröffentlicht (was Early Adopters frustriert). ## Warum es wichtig ist Eine Desynchronisierung zwischen dem Verhalten der Software und ihrer Dokumentation ist eine Hauptursache für Frustration bei Entwicklern. Damit Dokumentation effektiv ist, muss sie strikt der spezifischen Version der Software entsprechen, die der Benutzer gerade verwendet. Die Bereitstellung des korrekten Kontextes für jede Version gewährleistet ein reibungsloses Onboarding- und Troubleshooting-Erlebnis. ## Ansatz Isolieren Sie die Dokumentation für die aktive Entwicklung mithilfe der [Versionierungs-Engine](../../configuration/versioning) von `docmd`. Dies ermöglicht es Ihrem Team, Inhalte für kommende Funktionen asynchron in einem separaten Verzeichnis (z. B. `docs-next/`) zu entwerfen und sie erst dann in den Status "Stabil" oder "Aktuell" zu befördern, wenn das offizielle Software-Release erfolgt. ## Implementierung ### 1. Verzeichnisstruktur organisieren Behalten Sie Ihre stabile Dokumentation im primären `docs/`-Ordner bei und erstellen Sie ein dediziertes Verzeichnis für das kommende Release. ```text projekt-root/ ├── docs/ # Aktuell Stabil (v1.x) ├── docs-v2/ # Kommendes Release (v2.0) └── docmd.config.json ``` ### 2. Versionen konfigurieren Registrieren Sie beide Versionen in Ihrer Konfiguration. Sie können die kommende Version als "Beta" oder "Next" kennzeichnen, um den Benutzern über den Versions-Switcher den Status zu signalisieren. ```json { "versions": { "current": "v1.0", "all": [ { "id": "v1.0", "dir": "docs", "label": "v1.x (Stabil)" }, { "id": "v2.0", "dir": "docs-v2", "label": "v2.0 (Beta)" } ] } } ``` ### 3. Der Promotions-Prozess Wenn Sie bereit sind, die neue Version offiziell zu veröffentlichen: 1. **Konfiguration aktualisieren**: Ändern Sie die `current` Versions-ID in `docmd.config.json` auf `v2.0`. 2. **Labels aktualisieren**: Entfernen Sie den "(Beta)"-Tag vom `label` im `all`-Array. 3. **Alte Dokumentation archivieren**: Behalten Sie den `v1.0`-Eintrag im `all`-Array bei, damit Benutzer älterer Versionen weiterhin auf die für sie relevante Dokumentation zugreifen können. ## Abwägungen ### Wartungsaufwand Die Pflege mehrerer Dokumentationsversionen erfordert Disziplin. Wenn ein kritischer Tippfehler oder eine Sicherheitswarnung in der stabilen Version korrigiert wird, stellen Sie sicher, dass dies auch auf das Verzeichnis der kommenden Version angewendet wird, um "Regressionen" in der Klarheit zu vermeiden. ### SEO und Suche Mehrere Versionen können gelegentlich dazu führen, dass Suchergebnisse auf ältere Dokumentationen verweisen. Verwenden Sie das `seo`-Plugin und korrekte Canonical-Tags, um sicherzustellen, dass die "Aktuelle" Version von Suchmaschinen immer priorisiert wird. Weitere Informationen zum Verwalten von Übergängen finden Sie unter [Umgang mit Breaking Changes](../scaling-architecture/breaking-changes-deprecations). --- ## [docmd Dokumentation: Produktionsreife Docs aus Markdown](https://docs.docmd.io/de/) --- title: "docmd Dokumentation: Produktionsreife Docs aus Markdown" description: "Erstellen Sie in Sekundenschnelle produktionsreife Dokumentationen aus Markdown. Zero Setup, standardmäßig schnell, SEO-freundlich und KI-bereit." titleAppend: false --- ::: hero # docmd Von Markdown zu produktionsreifen Dokumenten mit einem einzigen Befehl. Statisches HTML für SEO. SPA für Geschwindigkeit. Standardmäßig KI-bereit. ::: button "Erste Schritte" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#24292e icon:github ::: ## Übersicht docmd ist ein Zero-Config-Dokumentationsgenerator. Er erstellt hochperformante statische Websites direkt aus Ihren Markdown-Dateien. ```bash npx @docmd/core dev ``` Ein einzelner Befehl. Die Engine erstellt automatisch Ihre Website, generiert Navigation und aktiviert die sofortige Suche. ## Kernfunktionen Alles, was für weltklasse Dokumentation benötigt wird, ist bereits enthalten. Keine komplexen Plugins für die Essentials erforderlich. ::: grids ::: grid ::: card "Sofortiges Setup" icon:rocket Ohne Boilerplate-Code sofort anfangen. Die Engine erkennt Dateien automatisch und erstellt in Sekunden die Navigationsstruktur. ::: ::: ::: grid ::: card "KI-optimiert" icon:brain-circuit Generiert automatisch `llms.txt` und `llms-full.txt`. Halten Sie Ihre Dokumentation für KI-Modelle verdaubar. ::: ::: ::: grid ::: card "Lokale Suche" icon:search Schnelle clientseitige Volltextsuche mit MiniSearch. Funktioniert sofort über Versionen und Sprachen hinweg. ::: ::: ::: grid ::: card "Live-Vorschau" icon:monitor Betten Sie interaktive, editierbare Code-Sandboxes direkt in Ihre Seiten ein für sofortige Experimente. ::: ::: ::: grid ::: card "Flexible Themes" icon:palette Wechseln Sie zwischen integrierten Themes oder wenden Sie benutzerdefiniertes Styling an. Vollständige Unterstützung für dunklen Modus und Systemvoreinstellungen. ::: ::: ::: grid ::: card "Native Internationalisierung" icon:globe Erstklassige i18n-Unterstützung. Beinhaltet sprachpriorisiertes Routing, eigenständige Suchindizes und übersetzte UI-Strings. ::: ::: ::: ::: callout info "Umfangreiche Content-Container" Gehen Sie über Standard-Markdown hinaus. Verwenden Sie strukturierte visuelle Muster wie Schritte, Tabs, Karten, Raster und Callouts direkt in Ihrem Text. ::: button "Container erkunden" ./content/containers/index.md icon:blocks ::: --- ## [Migration von Docusaurus](https://docs.docmd.io/de/migration/docusaurus/) --- title: "Migration von Docusaurus" description: "Ein umfassender Leitfaden zum Umzug Ihres Docusaurus v2/v3-Projekts zu docmd." --- # Migration von Docusaurus zu docmd Docusaurus ist ein beliebtes Dokumentations-Framework, das auf React basiert. `docmd` bietet eine schnelle, konfigurationsfreie Alternative, die deutlich schneller kompiliert und keine React-Komponenten benötigt, um umfangreiche Funktionen zu rendern. ## Schritt 1: Ausführen der Migration-Engine Führen Sie den folgenden Befehl im Root-Verzeichnis Ihres bestehenden Docusaurus-Projekts aus (dort, wo sich Ihre `docusaurus.config.js` oder `docusaurus.config.ts` befindet): ```bash npx @docmd/core migrate --docusaurus ``` ### Was automatisch passiert 1. **Backup**: Ihr gesamtes Projekt (außer `node_modules` und `.git`) wird sicher in ein neues Verzeichnis `docusaurus-backup/` verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Root-Verzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. 3. **Konfigurationserstellung**: Eine `docmd.config.js` wird generiert, wobei der Seitentitel (`title`) aus Ihrer Docusaurus-Konfiguration extrahiert wird. ## Schritt 2: Testen des Setups Sobald der Befehl abgeschlossen ist, können Sie Ihre Markdown-Inhalte sofort in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Seitenleiste wird leer sein. ## Schritt 3: Manuelle Konfiguration Docusaurus verfügt über komplexe programmatische Konfigurationen, die `docmd` nicht zu erraten versucht. Diese müssen Sie manuell zuordnen. ### 1. Navigations-Setup Docusaurus-Seitenleisten werden oft automatisch generiert oder in `sidebars.js` konfiguriert. **Erforderliche Aktion:** Erstellen Sie eine `navigation.json` in Ihrem neuen `docs/`-Verzeichnis, um Ihre `docmd`-Seitenleiste zu strukturieren. Siehe den [Leitfaden zur Navigation](../configuration/navigation.md). ### 2. Ersetzen von MDX-Komponenten Docusaurus stützt sich stark auf MDX (`.mdx`), um benutzerdefinierte React-Komponenten (wie Tabs, Admonitions oder benutzerdefinierte UI-Elemente) zu rendern. `docmd` wird rein über Markdown gesteuert und verwendet kein React. **Erforderliche Aktion:** Sie müssen alle benutzerdefinierten `<MyReactComponent />`-Tags in Standard-Markdown umwandeln oder die nativen [Container](../content/containers/callouts.md) von `docmd` verwenden. #### Beispiel: Umwandeln von Admonitions (Hinweisen) **Docusaurus:** ```markdown :::tip Mein Tipp Dies ist ein hilfreicher Tipp. ::: ``` **docmd:** (Die Lernkurve ist fast bei Null, außer einigen geänderten Schlüsselwörtern für eine bessere Benutzererfahrung. `docmd` unterstützt nativ Admonitions im Docusaurus-Stil als Callouts). ```markdown ::: callout tip "Mein Tipp" Dies ist ein hilfreicher Tipp. ::: ``` #### Beispiel: Umwandeln von Tabs **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> Dies ist ein Apfel. </TabItem> <TabItem value="orange" label="Orange"> Dies ist eine Orange. </TabItem> </Tabs> ``` **docmd:** (Umwandlung in die native `docmd`-Tabs-Container-Syntax) ```markdown ::: tabs == tab "Apple" Dies ist ein Apfel. == tab "Orange" Dies ist eine Orange. ::: ``` ### 3. Lokalisierung (i18n) Wenn Sie die `i18n`-Funktionen von Docusaurus verwendet haben, befanden sich Ihre übersetzten Dateien wahrscheinlich in `i18n/locale/docusaurus-plugin-content-docs/current/`. **Erforderliche Aktion:** Verschieben Sie diese Dateien in die Verzeichnisstruktur von `docmd` (`docs/en/`, `docs/de/` usw.) und konfigurieren Sie die Locales in der `docmd.config.js`. Siehe den [Leitfaden zur Lokalisierung](../configuration/localisation/index.md). ## Nächste Schritte - Entdecken Sie die Einstellungen für [Layout & UI](../configuration/layout-ui.md), um Ihr Docusaurus-Theme anzupassen. - Wandeln Sie React-basierte Hero-Header in `docmd` [Hero-Container](../content/containers/hero.md) um. --- ## [Migration von MkDocs](https://docs.docmd.io/de/migration/mkdocs/) --- title: "Migration von MkDocs" description: "Ein umfassender Leitfaden zum Umzug Ihres MkDocs- (oder Material for MkDocs-) Projekts zu docmd." --- # Migration von MkDocs zu docmd MkDocs, insbesondere mit dem Material-Theme, ist ein beliebter Python-basierter Dokumentationsgenerator. `docmd` bietet eine ähnliche Markdown-First-Erfahrung, setzt jedoch auf Node.js/Bun für unglaublich schnelle Builds und reichhaltige interaktive Funktionen, ohne dass komplexe Python-Erweiterungen erforderlich sind. ## Schritt 1: Ausführen der Migration-Engine Führen Sie den folgenden Befehl im Root-Verzeichnis Ihres bestehenden MkDocs-Projekts aus (dort, wo sich Ihre `mkdocs.yml` befindet): ```bash npx @docmd/core migrate --mkdocs ``` ### Was automatisch passiert 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues Verzeichnis `mkdocs-backup/` verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Root-Verzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. 3. **Konfigurationserstellung**: Eine `docmd.config.js` wird generiert, wobei der Projektname (`site_name`) aus Ihrer `mkdocs.yml` extrahiert wird. ## Schritt 2: Testen des Setups Sobald der Befehl abgeschlossen ist, zeigen Sie Ihre Inhalte in `docmd` in der Vorschau an: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Seitenleiste wird leer sein. ## Schritt 3: Manuelle Konfiguration MkDocs verwendet die `mkdocs.yml`, um die Navigation und Erweiterungen der Website zu definieren. Sie müssen dieses Setup auf `docmd` übertragen. ### 1. Navigations-Setup In MkDocs wird die Navigation strikt im Schlüssel `nav` der `mkdocs.yml` definiert. **Erforderliche Aktion:** Sie müssen eine `navigation.json` in Ihrem `docs/`-Ordner erstellen. **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "Startseite", "path": "/" }, { "title": "Leitfaden", "collapsible": true, "children": [ { "title": "Einrichtung", "path": "/setup" }, { "title": "Nutzung", "path": "/usage" } ] } ] ``` ### 2. Ersetzen von Python-Markdown-Erweiterungen Wenn Sie "Material for MkDocs" verwendet haben, haben Sie sich wahrscheinlich auf Python-Markdown-Erweiterungen wie PyMdown Extensions für Tabs, Admonitions oder Aufgabenlisten verlassen. **Erforderliche Aktion:** Wandeln Sie die MkDocs-spezifische Erweiterungssyntax in die nativen [Container](../content/containers/callouts.md) von `docmd` um. #### Beispiel: Umwandeln von Admonitions (Hinweisen) **MkDocs (PyMdown):** ```markdown !!! note "Optionaler Titel" Dies ist ein Inhaltsblock für einen Hinweis. ``` **docmd:** ```markdown ::: callout info "Optionaler Titel" Dies ist ein Inhaltsblock für einen Hinweis. ::: ``` #### Beispiel: Umwandeln von Tabs **MkDocs (SuperFences):** ```markdown === "Tab 1" Inhalt für Tab 1. === "Tab 2" Inhalt für Tab 2. ``` **docmd:** ```markdown ::: tabs == tab "Tab 1" Inhalt für Tab 1. == tab "Tab 2" Inhalt für Tab 2. ::: ``` ## Nächste Schritte - `docmd` verfügt über eine integrierte Suche. Sie müssen kein Such-Plugin konfigurieren. - Entdecken Sie die [Theme-Optionen](../theming/customisation.md), um die Farben Ihrer Website an Ihr altes Material-Theme anzupassen. --- ## [Migrationsübersicht](https://docs.docmd.io/de/migration/overview/) --- title: "Migrationsübersicht" description: "Erfahren Sie, wie Sie Ihre bestehende Dokumentation einfach auf docmd migrieren können." --- # Migration zu docmd `docmd` bietet eine vollautomatische **Migrations-Engine**, mit der Sie mit nur einem einzigen Befehl von alten oder konkurrierenden Dokumentationsplattformen wechseln können. Das Ziel der Migrations-Engine ist es, Ihnen die mühsame Arbeit des Verschiebens von Markdown-Dateien und der Umstrukturierung Ihres Projektverzeichnisses abzunehmen. ## Wie es funktioniert Der Migrationsbefehl führt Folgendes aus: 1. **Erkennt** Ihre bestehende Konfigurationsdatei (z.B. `docusaurus.config.js`, `mkdocs.yml`). 2. **Extrahiert** grundlegende Metadaten wie den `title` Ihrer Website. 3. **Sichert** Ihre bestehenden Dateien und Verzeichnisse sicher in einem `*-backup/`-Verzeichnis (z.B. `docusaurus-backup/`). 4. **Kopiert** Ihre Markdown-Inhalte in das standardmäßige `docmd` `docs/`-Verzeichnis. 5. **Erzeugt** eine neue, speziell auf Ihre Inhalte zugeschnittene `docmd.config.js`. Anschließend können Sie direkt `npx @docmd/core dev` ausführen, um Ihre Inhalte sofort in der `docmd`-Engine zu sehen. ## Was wird migriert? | Funktion | Automatisch migriert? | | :--- | :--- | | **Markdown-Dateien** | ✅ Ja, alle `.md` und `.mdx` Dateien werden nach `docs/` verschoben | | **Verzeichnisstruktur** | ✅ Ja, Ihre Ordner-Verschachtelung bleibt erhalten | | **Website-Titel** | ✅ Ja, aus Ihrer Konfiguration extrahiert | | **Container-Syntax** | ✅ Ja, VitePress/Docusaurus-Container funktionieren ohne Änderungen | | **Navigation / Sidebar** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Lokalisierung (i18n)** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Versionierung** | ⚠️ **Nein**, erfordert eine manuelle Zuordnung | | **Eigene React/Vue-Komponenten** | ❌ Nein, diese müssen durch `docmd` Container ersetzt werden | ::: callout success "Container-Syntax-Kompatibilität" Ab `docmd` 0.7.8 funktioniert die Container-Syntax von **VitePress** (`:::tip`, `:::warning`, `:::danger`, `:::info`, `:::details`) und **Docusaurus** (`:::note`, `:::caution`) ohne Änderung. Ihre bestehenden Admonitions und ausklappbaren Abschnitte werden in `docmd` korrekt gerendert. **MkDocs** verwendet `!!!`-Syntax, die eine manuelle Konvertierung in das `:::`-Format erfordert. ::: ## Warum Navigation und i18n nicht automatisch migriert werden Jede Dokumentationsplattform behandelt Navigations-Sidebars, Übersetzungen und Multi-Versionierung unterschiedlich. Beispielsweise verwendet Docusaurus komplexe JavaScript-Objekte oder automatisch generierte Sidebars, während MkDocs auf strikt eingerückte YAML-Strukturen setzt. Um fehlerhafte Migrationen durch das Erraten komplexer Konfigurationen zu vermeiden, verschiebt `docmd` Ihre Inhalte sicher und bittet Sie darum, die Navigation, Lokalisierung und Versionierung mithilfe der einfachen JSON-basierten APIs von `docmd` nativ zu konfigurieren. - **Navigation:** Erfahren Sie unter [Navigations-Setup](../configuration/navigation.md), wie Sie eine `navigation.json` erstellen. - **Lokalisierung:** Lesen Sie den [Leitfaden zur Lokalisierung](../configuration/localisation/index.md), um mehrsprachige Dokumentationen einzurichten. - **Versionierung:** Beziehen Sie sich auf das [Versions-Setup](../configuration/versioning.md). ## Unterstützte Plattformen Wählen Sie Ihre aktuelle Plattform für spezifische Migrationsanweisungen aus: - [Von Docusaurus migrieren](./docusaurus.md) - [Von MkDocs migrieren](./mkdocs.md) - [Von VitePress migrieren](./vitepress.md) - [Von Astro Starlight migrieren](./starlight.md) --- ## [Von Astro Starlight migrieren](https://docs.docmd.io/de/migration/starlight/) --- title: "Von Astro Starlight migrieren" description: "Ein umfassender Leitfaden zur Migration Ihres Astro Starlight-Projekts zu docmd." --- # Von Astro Starlight migrieren zu docmd Starlight ist ein hervorragendes Dokumentations-Theme, das auf dem Astro-Framework basiert. `docmd` bietet eine ähnliche Standarderfahrung ohne JavaScript, macht jedoch die Konfiguration eines vollständigen Web-Frameworks (Astro) überflüssig, was die Lernkurve für technische Redakteure drastisch reduziert. ## Schritt 1: Führen Sie die Migrations-Engine aus Führen Sie den folgenden Befehl im Hauptverzeichnis Ihres bestehenden Starlight-Projekts aus (dort, wo sich Ihre `astro.config.mjs` befindet): ```bash npx @docmd/core migrate --starlight ``` ### Was passiert automatisch 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues `starlight-backup/`-Verzeichnis verschoben. 2. **Inhaltsmigration**: Starlight speichert die Dokumentation in `src/content/docs/`. Die Migrations-Engine extrahiert dieses spezifische Verzeichnis automatisch und verschiebt seinen Inhalt zur Nutzung durch `docmd` in den Stammordner `docs/`. 3. **Konfigurationsgenerierung**: Eine `docmd.config.js` wird generiert, die Ihren Website-`title` aus der Starlight-Integration innerhalb der `astro.config.mjs` extrahiert. ## Schritt 2: Testen Sie das Setup Sobald der Befehl abgeschlossen ist, können Sie Ihre Inhalte in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Sidebar bleibt zunächst leer. ## Schritt 3: Manuelle Konfiguration ### 1. Navigations-Setup Starlight definiert die Navigation in der `astro.config.mjs` über das Array `sidebar`. **Aktion erforderlich:** Sie müssen eine `navigation.json` in Ihrem neuen `docs/`-Ordner erstellen. **Starlight (`astro.config.mjs`):** ```js sidebar: [ { label: 'Guides', items: [ { label: 'Setup', link: '/guides/setup/' } ], }, ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. Astro-Komponenten ersetzen (MDX/Markdoc) Starlight verwendet Astro-Komponenten (`<Tabs>`, `<Card>` usw.), die über MDX oder Markdoc eingebettet sind. Da sich `docmd` auf reine Markdown-Syntax anstelle von UI-Komponenten verlässt, müssen diese konvertiert werden. **Aktion erforderlich:** Ersetzen Sie Astro-Komponenten durch `docmd` [Container](../content/containers/callouts.md). #### Beispiel: Tabs konvertieren **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### Beispiel: Admonitions (Asides) konvertieren **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter-Zuordnung Starlight verfügt über eine strikte Frontmatter-Typisierung über Astro Content Collections. Das Frontmatter von `docmd` ist einfacher gehalten. Wenn Sie in Starlight `hero`- oder `banner`-Frontmatter-Eigenschaften für Landingpages verwendet haben, müssen Sie diese durch [Hero-Bereiche](../content/containers/hero.md) von `docmd` ersetzen, die direkt in den Markdown-Text geschrieben werden. ## Nächste Schritte - Entdecken Sie das integrierte [Such-Plugin](../plugins/search.md) von `docmd` (Starlight verwendet Pagefind, während `docmd` nativ einen hochoptimierten lokalen Suchindexer mitliefert). --- ## [Von VitePress migrieren](https://docs.docmd.io/de/migration/vitepress/) --- title: "Von VitePress migrieren" description: "Ein umfassender Leitfaden zur Migration Ihres VitePress-Projekts zu docmd." --- # Von VitePress migrieren zu docmd VitePress ist ein schnelles, Vue-basiertes SSG-Framework. Genau wie VitePress ist `docmd` außergewöhnlich schnell, erreicht dies jedoch, indem absolut keine JavaScript-Framework-Logik an den Client ausgeliefert wird (kein Overhead durch Vue-Hydration). ## Schritt 1: Führen Sie die Migrations-Engine aus Führen Sie den folgenden Befehl im Hauptverzeichnis Ihres bestehenden VitePress-Projekts aus: ```bash npx @docmd/core migrate --vitepress ``` ### Was passiert automatisch 1. **Backup**: Ihr gesamtes Projekt wird sicher in ein neues `vitepress-backup/`-Verzeichnis verschoben. 2. **Inhaltsmigration**: Ihr `docs/`-Ordner wird im Stammverzeichnis wiederhergestellt, damit `docmd` ihn verwenden kann. Der versteckte `.vitepress`-Konfigurationsordner wird vollständig aus dem neuen `docs/`-Verzeichnis entfernt, um Konflikte zu vermeiden. 3. **Konfigurationsgenerierung**: Eine `docmd.config.js` wird generiert, die Ihren Website-`title` aus Ihrer `.vitepress/config.js` oder `.ts` extrahiert. ## Schritt 2: Testen Sie das Setup Sobald der Befehl abgeschlossen ist, können Sie Ihre Inhalte in `docmd` in der Vorschau anzeigen: ```bash npx @docmd/core dev ``` Ihre Markdown-Dateien werden kompiliert, aber Ihre Navigations-Sidebar bleibt zunächst leer. ## Schritt 3: Manuelle Konfiguration VitePress konfiguriert die Navigation in seiner Konfigurationsdatei und verwendet Vue-Komponenten innerhalb von Markdown. Sie müssen diese auf `docmd` umstellen. ### 1. Navigations-Setup VitePress verwendet ein Array von Objekten unter `themeConfig.sidebar`. **Aktion erforderlich:** Erstellen Sie eine `navigation.json` in Ihrem `docs/`-Verzeichnis. **VitePress (`.vitepress/config.js`):** ```js themeConfig: { sidebar: [ { text: 'Guide', items: [ { text: 'Introduction', link: '/introduction' }, { text: 'Getting Started', link: '/getting-started' } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. Vue-Komponenten ersetzen VitePress erlaubt es Autoren, Vue-Komponenten (z. B. `<MyComponent />`) direkt in Markdown-Dateien einzubetten. Da `docmd` Vue nicht auf dem Client ausführt, müssen Sie diese benutzerdefinierten Komponenten entfernen oder durch natives Markdown ersetzen. **Aktion erforderlich:** Ersetzen Sie Vue-spezifische UI-Komponenten durch `docmd` [Container](../content/containers/callouts.md). #### Beispiel: Admonitions (Benutzerdefinierte Container) VitePress verwendet eine benutzerdefinierte Block-Syntax für markdown-it, die der von `docmd` sehr ähnlich sieht. **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` *Hinweis: VitePress verwendet `info`, `tip`, `warning`, `danger`, `details`. `docmd` unterstützt diese direkt, aber Sie möchten sich möglicherweise die vollständige Liste der [docmd Callouts](../content/containers/callouts.md) ansehen.* ## Nächste Schritte - Entdecken Sie den `docmd`-Leitfaden [Bauen & Bereitstellen](../deployment/index.md), da `docmd` nicht auf die Build-Pipeline von Vite angewiesen ist. --- ## [Analytics-Plugin](https://docs.docmd.io/de/plugins/analytics/) --- title: "Analytics-Plugin" description: "Integrieren Sie Google Analytics 4 oder Legacy Universal Analytics und verfolgen Sie Benutzerinteraktionen automatisch." --- Das Plugin `@docmd/plugin-analytics` ermöglicht es Ihnen, Google Analytics nahtlos in Ihre Dokumentation zu integrieren. Es unterstützt den modernen Google Analytics 4 (GA4) Standard, das ältere Universal Analytics (UA) und beinhaltet natives Event-Tracking für interaktionsreiche Dokumentationsseiten. ## Konfiguration Aktivieren Sie Analytics, indem Sie Ihre Tracking-Anmeldedaten zum Abschnitt `plugins` der `docmd.config.js` hinzufügen. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { analytics: { // 1. Google Analytics 4 (Empfohlen) googleV4: { measurementId: 'G-XXXXXXX' }, // 2. Älteres Universal Analytics googleUA: { trackingId: 'UA-XXXXXXX-X' }, // 3. Einstellungen für Verhaltens-Tracking autoEvents: true, // Klicks, Downloads und TOC-Interaktionen verfolgen trackSearch: true // Von Lesern verwendete Suchbegriffe verfolgen } } }); ``` ## Verfolgte Ereignisse (Events) Wenn `autoEvents` aktiviert ist, erfasst das Plugin automatisch die folgenden Benutzerinteraktionen und sendet sie an Ihren Analytics-Anbieter: * **Externe Links**: Verfolgen, wann Benutzer die Seite für externe Ressourcen verlassen. * **Datei-Downloads**: Automatisches Protokollieren von Klicks auf Links mit dem `download`-Attribut oder gängigen Dateiendungen (`.pdf`, `.zip`, `.tar` etc.). * **Inhaltsverzeichnis (TOC)**: Überwachen, welche Abschnitte am interessantesten sind, indem Klicks in der rechten Seitennavigation verfolgt werden. * **Überschrift-Anker**: Protokollieren, wenn Benutzer auf „Permalinks“ (Anker von Überschriften) klicken, um spezifische Abschnitte zu teilen. * **Suchanfragen**: Wenn `trackSearch` aktiv ist, werden Suchbegriffe erfasst (mit einer Verzögerung von 1 Sekunde), um Ihnen zu helfen zu verstehen, wonach Ihre Benutzer suchen. ## Technische Details Das Plugin fügt die erforderlichen Tracking-Skripte in den `<head>` jeder Seite ein. Event-Listener werden unter Verwendung einer effizienten Ereignisdelegation an das `<body>`-Element angehängt, um sicherzustellen, dass keine Auswirkungen auf die Ladeleistung der Seite oder die Übergänge der Single Page Application (SPA) entstehen. ::: callout info "Datenschutz & DSGVO" Standardmäßig anonymisiert dieses Plugin IP-Adressen nicht, da dies nun nativ von GA4 gehandhabt wird. Wenn Sie ein erweitertes Cookie-Einwilligungsmanagement benötigen, können Sie Ihre Skripte für den Consent-Manager manuell über `customCss` oder einen benutzerdefinierten Plugin-Hook einbinden. ::: --- ## [Plugins entwickeln](https://docs.docmd.io/de/plugins/building-plugins/) --- title: "Plugins entwickeln" description: "Ein umfassender Leitfaden zur Erweiterung von docmd mit benutzerdefinierter Logik, Dateneinfügung und interaktiven Funktionen." --- Plugins sind der primäre Erweiterungsmechanismus für `docmd`. Sie ermöglichen das Einfügen von benutzerdefiniertem HTML, das Ändern der Markdown-Parslogik, das Einschleusen von Build-Zeit-Daten vor dem Template-Rendering und die Automatisierung von Post-Build-Aufgaben. Dieser Leitfaden beschreibt die Plugin-API und Best Practices für die Erstellung wiederverwendbarer Komponenten. ## Plugin-Deskriptor Jedes Plugin sollte einen `plugin`-Deskriptor exportieren, der seine Identität und Fähigkeiten deklariert. Dies ermöglicht der Engine, Fähigkeitsgrenzen beim Laden zu validieren, zu isolieren und durchzusetzen. ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` > **Hinweis:** Der Deskriptor ist derzeit optional (Soft-Deprecation-Warnung). Er wird **ab 0.8.0 erforderlich sein**. ## Kern-Fähigkeiten Das `capabilities`-Array bestimmt, welche Hooks Ihr Plugin verwenden darf. | Fähigkeit | Erlaubte Hooks | Phase | | :--- | :--- | :--- | | `init` | `onConfigResolved` | Init | | `markdown` | `markdownSetup` | Setup | | `head` | `generateMetaTags`, `generateScripts` (head) | Rendering | | `body` | `generateScripts` (body) | Rendering | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeRender`, `onPageReady` | Build | | `post-build`| `onPostBuild` | Post-Build | | `dev` | `onDevServerReady` | Dev-Server | | `assets` | `getAssets` | Ausgabe | | `actions` | `actions` | Interaktiv | | `events` | `events` | Interaktiv | | `translations`| `translations` | i18n | Legacy-Plugins ohne Deskriptor erhalten vollen Zugriff auf alle Hooks, sodass während der Übergangsphase nichts abbricht. ## Plugin-API-Referenz Ein `docmd`-Plugin ist ein Standard-JavaScript-Objekt (oder ein Modul, das eines als Standard exportiert), das einen oder mehrere der folgenden Hooks implementiert. | Hook | Beschreibung | | :--- | :--- | | `markdownSetup(md, opts)` | Erweitert die `markdown-it`-Instanz. Synchron. | | `generateMetaTags(config, page, root)` | Fügt `<meta>`- oder `<link>`-Tags in den `<head>` ein. | | `generateScripts(config, opts)` | Gibt ein Objekt mit `headScriptsHtml` und `bodyScriptsHtml` zurück. | | `getAssets(opts)` | Definiert externe Dateien oder CDN-Skripte zum Einbinden. | | `onPostBuild(ctx)` | Führt Logik nach der Generierung aller HTML-Dateien aus. | | `translations(localeId)` | Gibt ein Objekt mit übersetzten Strings für das angegebene Gebietsschema zurück. | | `actions` | Objekt mit benannten Aktions-Handlern für WebSocket-RPC-Aufrufe vom Browser. | | `events` | Objekt mit benannten Event-Handlern für Fire-and-Forget-Nachrichten vom Browser. | ## Ein lokales Plugin erstellen Ein Plugin zu erstellen ist so einfach wie das Definieren einer JavaScript-Datei. Zum Beispiel `my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, markdownSetup: (md, options) => { // Beispiel: Regel hinzufügen oder markdown-it-Plugin verwenden }, generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`Benutzerdefiniertes Plugin: ${pages.length} Seiten überprüft.`); } }; ``` Verweisen Sie in Ihrer `docmd.config.js` über den **vollständigen Paketnamen** auf Ihr Plugin: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { 'my-awesome-plugin': { // Ihre benutzerdefinierten Optionen hier } } }); ``` > **Hinweis:** Kurzformen (z.B. `math`, `search`) sind ausschließlich für offizielle `@docmd/plugin-*`-Pakete reserviert. Drittanbieter-Plugins müssen immer mit ihrem vollständigen npm-Paketnamen referenziert werden. ### Plugin-Isolierung Jeder Hook-Aufruf ist in eine try/catch-Grenze eingebettet. Ein defektes Plugin kann den Build nicht zum Absturz bringen oder andere Plugins stören. Fehler werden protokolliert und am Ende des Builds in einer Zusammenfassung gesammelt. ## Lebenszyklus-Hooks docmd bietet tiefe Integrations-Hooks, die es Plugins ermöglichen, Konfiguration, Rohquellen und Seitendaten während der gesamten Build-Pipeline zu manipulieren. | Hook | Beschreibung | Erwarteter Rückgabewert | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | Liest oder modifiziert die aktive normalisierte Konfiguration direkt nach der Initialisierung. | `void` oder `Promise<void>` | | **`onDevServerReady(server, wss)`** | Gibt den rohen Node.js `http.Server` und `WebSocketServer` im Entwicklungsmodus frei. | `void` oder `Promise<void>` | | **`onBeforeParse(src, frontmatter)`** | Vorverarbeitet rohe Markdown-Zeichenkettendaten unmittelbar bevor sie zur Analyse übergeben werden. | `string` oder `Promise<string>` | | **`onAfterParse(html, frontmatter)`** | Nachverarbeitet den generierten HTML-Code, der das Markdown-Body-Segment darstellt. | `string` oder `Promise<string>` | | **`onBeforeRender(page)`** | Wird vor dem Template-Rendering aufgerufen. Empfängt den vollständigen `PageContext`. Änderungen an `frontmatter` und `html` werden in der gerenderten Ausgabe widergespiegelt. | `void` oder `Promise<void>` | | **`onPageReady(page)`** | Greift auf die vollständig zusammengestellten Seitenmetadaten zu, kurz bevor die Seite in die Zieldatei geschrieben wird. | `void` oder `Promise<void>` | ### Multi-Threaded Hintergrundaufgaben (`runWorkerTask`) Ab Version 0.8.0 verarbeitet docmd Markdown in einem persistenten, mehrfädigen `WorkerPool`. Plugins können ihre eigenen I/O- oder CPU-intensiven Aufgaben auf diese Threads auslagern, anstatt den Haupt-Build-Thread zu blockieren. Die Methode `runWorkerTask` wird in `PageContext`, `PostBuildContext` und `ActionContext` injiziert. ```javascript export default { plugin: { name: "my-plugin", version: "1.0.0", capabilities: ["post-build"] }, onPostBuild: async (ctx) => { // Übergeben Sie den absoluten Pfad zu Ihrem Worker-Skript, den exportierten Funktionsnamen und ein Array von Argumenten const result = await ctx.runWorkerTask('/absolute/path/to/worker.js', 'parseData', [ctx.outputDir]); } } ``` ### `onBeforeRender` und `PageContext` Der `onBeforeRender`-Hook ist der richtige Ort für Plugins, die Build-Zeit-Daten aus der Quelldatei einschleusen müssen - Datei-Metadaten lesen, benutzerdefinierte Frontmatter-Felder berechnen oder Daten aus externen Quellen laden. ```typescript interface PageContext { sourcePath: string; // Absoluter Pfad zur .md-Quelldatei. Immer gesetzt. frontmatter: Record<string, any>; // Veränderbar - Änderungen in der Template-Ausgabe widergespiegelt html: string; // Veränderbar - gerenderter Markdown-Body localeId?: string; versionId?: string; relativePathToRoot?: string; } ``` ```javascript export default { plugin: { name: 'my-metadata-plugin', version: '1.0.0', capabilities: ['build'] }, onBeforeRender: async (page) => { // sourcePath ist immer verfügbar - kein Raten oder Pfadkonstruktion nötig const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } }; ``` ## Vertiefung: Asset-Einbindung Der `getAssets()`-Hook ermöglicht es Ihrem Plugin, clientseitige Logik sicher zu bündeln. ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), dest: 'assets/js/plugin-init.js', type: 'js', location: 'body' } ]; } ``` ## Plugins übersetzen (i18n) Plugins, die clientseitige UI rendern, sollten übersetzbare Strings über den `translations(localeId)`-Hook bereitstellen. ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['translations', 'body'] }, translations: (localeId) => { try { const p = path.join(__dirname, 'i18n', `${localeId}.json`); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } try { const p = path.join(__dirname, 'i18n', 'en.json'); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } return {}; } } ``` ## WebSocket-RPC-Aktionen Plugins können **Aktions-Handler** und **Event-Handler** registrieren, die auf dem Dev-Server laufen und über die `window.docmd`-API vom Browser aufrufbar sind. ```javascript export default { plugin: { name: 'my-live-plugin', version: '1.0.0', capabilities: ['actions', 'events'] }, actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`Seite aufgerufen: ${data.path}`); } } }; ``` Das `ctx`-Objekt (ActionContext) bietet: | Methode | Beschreibung | | :--- | :--- | | `ctx.readFile(path)` | Liest eine Datei relativ zum Projektstamm. | | `ctx.writeFile(path, content)` | Schreibt eine Datei (löst Rebuild + Reload aus). | | `ctx.readFileLines(path)` | Liest eine Datei als Zeilenarray. | | `ctx.broadcast(event, data)` | Sendet ein Event an alle verbundenen Browser. | | `ctx.source` | Quellbearbeitungswerkzeuge für blockbasierte Markdown-Manipulation. | | `ctx.projectRoot` | Absoluter Pfad zum Projektstamm. | | `ctx.config` | Aktuelle docmd-Seitenkonfiguration. | ::: callout info "Nur Entwicklungsmodus 🛡️" Das WebSocket-RPC-System ist nur während `docmd dev` aktiv. Produktions-Builds enthalten weder den API-Client noch serverseitige Aktionsverarbeitung. ::: ## Best Practices 1. **Fähigkeiten deklarieren**: Exportieren Sie immer einen `plugin`-Deskriptor mit Ihren deklarierten Fähigkeiten. Ab `0.8.0` wird dies erforderlich sein. 2. **`onBeforeRender` für Dateneinfügung verwenden**: Wenn Ihr Plugin die Quelldatei liest oder Frontmatter-Felder berechnet, verwenden Sie `onBeforeRender` - nicht `generateMetaTags`. `sourcePath` ist im `PageContext` immer verfügbar. 3. **Async/Await**: Verwenden Sie immer `async`-Funktionen für `onPostBuild`, `onBeforeRender` und Aktions-Handler. 4. **Zustandslosigkeit**: Vermeiden Sie die Beibehaltung von Zustand im Plugin-Objekt, da `docmd` Plugins während Entwicklungs-Rebuilds neu initialisieren kann. 5. **Namenskonvention**: Für Community-Plugins, stellen Sie `docmd-plugin-` voran (z.B. `docmd-plugin-analytics`). 6. **Aktions-Namensräume**: Stellen Sie Ihren Plugin-Namen voran (z.B. `my-plugin:save-note`) um Kollisionen zu vermeiden. 7. **Aktionsvalidierung**: Definieren Sie immer ein explizites Payload-Schema in Ihren Aktionen. 8. **Logging**: Verwenden Sie den bereitgestellten `log()`-Helfer in `onPostBuild`. ::: callout tip "KI-optimiertes Design 🤖" Die `docmd`-Plugin-API ist **LLM-optimal** gestaltet. Da die Hooks Standard-JavaScript-Objekte und -Typen ohne versteckte komplexe Klassenhierarchien verwenden, können KI-Agenten fehlerfreie benutzerdefinierte Plugins mit minimaler Anleitung generieren. ::: --- ## [Git-Plugin](https://docs.docmd.io/de/plugins/git/) --- title: "Git-Plugin" description: "Zeigt Zeitstempel der letzten Aktualisierung und Commit-Verlauf direkt aus Ihrem Git-Repository an." --- Das **Git-Plugin** fügt Ihren Dokumentationsseiten Repository-basierte Metadaten hinzu. Es zeigt an, wann jede Seite zuletzt geändert wurde, wer beigetragen hat, und bietet optional einen "Diese Seite bearbeiten"-Link - alles direkt aus Ihrem Git-Verlauf ohne Konfiguration. ::: callout info "Core-Plugin" Das Git-Plugin ist in `@docmd/core` enthalten und standardmäßig aktiviert. Es erkennt automatisch, ob sich Ihr Projekt in einem Git-Repository befindet, und deaktiviert sich selbst, wenn nicht. Für die Grundfunktionalität ist keine Installation oder Konfiguration erforderlich. ::: ## Funktionen ### Zeitstempel der letzten Aktualisierung Jede Seite zeigt automatisch an, wann sie zuletzt geändert wurde. Der Zeitstempel wird aus dem letzten Git-Commit abgeleitet, der die Quelldatei betrifft. Zeitstempel verwenden relative Formatierung für aktuelle Änderungen ("vor 2 Std.", "vor 3 T.") und wechseln zu absoluten Daten für ältere Inhalte ("15. März 2026"). ### Commit-Verlauf-Tooltip Bewegen Sie den Mauszeiger über den Text "Zuletzt aktualisiert", um einen Tooltip mit den letzten Commits für diese Seite anzuzeigen. Jeder Eintrag zeigt die Commit-Nachricht, den Autor (mit Gravatar-Avatar) und den relativen Zeitstempel. Dies bietet schnellen Kontext über aktuelle Änderungen, ohne die Seite zu verlassen - nützlich, um zu verstehen, was aktualisiert wurde und von wem. ### Bearbeitungslinks Bei Konfiguration mit einer Repository-URL zeigt das Plugin einen "Diese Seite bearbeiten"-Link an, der die Quelldatei direkt im Web-Editor Ihres Git-Anbieters öffnet. ```javascript plugins: { git: { repo: 'https://github.com/ihre-org/ihre-docs', branch: 'main' } } ``` Das Plugin erkennt automatisch GitHub-, GitLab- und Bitbucket-URLs und erstellt das korrekte Bearbeitungslink-Format für jeden Anbieter. ## Konfiguration | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | Repository-URL (z.B. `https://github.com/org/repo`). Erforderlich für Bearbeitungslinks. | | `branch` | `string` | `'main'` | Branch-Name für Bearbeitungslinks. | | `editLink` | `boolean` | `true` | "Diese Seite bearbeiten"-Link anzeigen, wenn `repo` gesetzt ist. | | `lastUpdated` | `boolean` | `true` | Zeitstempel der letzten Aktualisierung anzeigen. | | `commitHistory` | `boolean` | `true` | Commit-Verlauf-Tooltip beim Hovern anzeigen. | | `maxCommits` | `number` | `6` | Maximale Anzahl der Commits im Tooltip (nur anwendbar, wenn `commitHistory` `true` ist). | | `dateFormat` | `string` | `'relative'` | Zeitstempel-Format: `relative` (relativ), `iso` (ISO-Format) oder `locale-aware` (lokalisiertes Format). | ### Vollständiges Beispiel ```json { "plugins": { "git": { "repo": "https://github.com/docmd-io/docs", "branch": "main", "editLink": true, "lastUpdated": true, "commitHistory": true, "maxCommits": 5 } } } ``` ## Seitenspezifische Steuerung Deaktivieren Sie das Git-Plugin für bestimmte Seiten über Frontmatter: ```markdown --- title: "Interne Notizen" plugins: git: false --- Diese Seite zeigt keine Zeitstempel oder Bearbeitungslinks an. ``` ## Funktionsweise Das Plugin liest den Git-Verlauf zur Build-Zeit mit Standard-Git-Befehlen. Für jede Markdown-Datei: 1. Führt `git log` aus, um den Commit-Verlauf abzurufen 2. Extrahiert Zeitstempel, Autoren und Commit-Nachrichten 3. Fügt die Daten in den Seitenkontext ein 4. Client-seitiges JavaScript rendert die UI-Komponenten ::: callout tip "Performance" Git-Daten werden während des Build-Prozesses gecacht. Der Verlauf jeder Datei wird nur einmal abgefragt, unabhängig davon, wie oft die Seite gerendert wird (z.B. über mehrere Sprachen hinweg). ::: ## Anforderungen - Die Dokumentationsquelle muss sich in einem Git-Repository befinden - Git muss in der Build-Umgebung verfügbar sein - Dateien müssen mindestens einen Commit in ihrem Verlauf haben Seiten ohne Git-Verlauf (neue, noch nicht committete Dateien) zeigen keine Zeitstempel oder Commit-Verlauf an. ## Migration von editLink Wenn Sie zuvor die `editLink`-Konfigurationsoption verwendet haben, bietet das Git-Plugin dieselbe Funktionalität mit zusätzlichen Features: **Vorher (editLink-Konfiguration):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs', text: 'Diese Seite bearbeiten' } }); ``` **Nachher (Git-Plugin):** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', branch: 'main' } } }); ``` Das Git-Plugin erstellt automatisch die Bearbeitungs-URL aus Repository und Branch, sodass Sie den vollständigen Bearbeitungspfad nicht mehr manuell angeben müssen. ::: callout warning "Hinweis zur Veraltung" Die eigenständige `editLink`-Konfigurationsoption ist veraltet und wird in einer zukünftigen Version entfernt. Bitte migrieren Sie zum Git-Plugin für die Bearbeitungslink-Funktionalität. ::: ## Lokalisierung Das Plugin enthält Übersetzungen für alle UI-Strings. Unterstützte Sprachen: - Englisch (en) - Deutsch (de) - Chinesisch (zh) Benutzerdefinierte Übersetzungen können über das Standard-[UI-Strings](../configuration/localisation/ui-strings.md)-System bereitgestellt werden. --- ## [LLM Context Plugin](https://docs.docmd.io/de/plugins/llms/) --- title: "LLM Context Plugin" description: "Optimieren Sie Ihre Dokumentation für den KI-Konsum mit automatisierter Generierung von llms.txt und llms-full.txt." --- Das `@docmd/plugin-llms`-Plugin stellt sicher, dass Ihre Dokumentation perfekt für Large Language Models (LLMs) und KI-Agenten optimiert ist. Es folgt dem wachsenden Industriestandard, eine übergeordnete Zusammenfassung und eine umfassende Kontextdatei bereitzustellen, die KI-Tools einlesen können, um Ihr Projekt mit minimalen Halluzinationen zu verstehen. ## Konfiguration Das LLM-Plugin ist standardmäßig aktiviert. Damit es korrekt funktioniert, müssen Sie eine `url` in Ihrer `docmd.config.js` angeben. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ url: 'https://docs.example.com', plugins: { llms: { fullContext: true // Generiert llms-full.txt } } }); ``` ### Eine Seite ausschließen Wenn eine Seite sensible Informationen oder interne Notizen enthält, die KI-Modelle nicht lernen sollen, verwenden Sie das Flag `llms: false` in Ihrem Frontmatter: ```yaml --- title: "Interne Entwicklergeheimnisse" llms: false --- ``` ::: callout tip "Maximierung der KI-Genauigkeit :robot:" Detaillierte Best Practices zur Strukturierung Ihres Markdowns (semantische Überschriften, Alt-Text usw.) finden Sie in unserem Leitfaden [Optimierung für KI-Agenten](../guides/ai-optimisation/generating-ai-ready-docs.md). ::: --- ## [Math-Plugin](https://docs.docmd.io/de/plugins/math/) --- title: "Math-Plugin" description: "Native KaTeX/LaTeX-Mathematik-Integration für docmd." --- Das **Math-Plugin** fügt Ihren docmd-Websites native Unterstützung für LaTeX und KaTeX hinzu. Es nutzt `markdown-it-texmath` in sicherer Integration mit der `katex`-Engine, um sowohl Inline-Mathematik als auch mathematische Blöcke reibungslos zu rendern, ohne dass komplexe clientseitige JavaScript-Bibliotheken erforderlich sind. ## Setup ```bash docmd add math ``` ```javascript plugins: { math: {} } ``` ## Funktionsweise 1. Aktivieren Sie das Plugin über Ihre `docmd.config.js`. 2. Umschließen Sie Ihre Standard-LaTeX-Mathematik mit `$` (inline) oder `$$` (Block). 3. Der Server verarbeitet diese mathematischen Regeln während des Static-Site-Builds intelligent als reine statische HTML-Tags. 4. Minimal eingefügtes CSS übernimmt das Styling dieser Klassen automatisch, was zu einer sofortigen Visualisierung führt, sobald der Benutzer die Seite aufruft! ## Verwendung ### Inline-Mathematik Sie können Standard-Gleichungen mithilfe von einfachen Dollarzeichen `$` nahtlos in einen Textabschnitt einfügen: ```markdown Hier ist eine Inline-Gleichung: $E = mc^2$ ``` Hier ist eine Inline-Gleichung: $E = mc^2$ ### Mathematische Blöcke Verwenden Sie für umfangreichere mathematische Beweise oder eigenständige Formeln doppelte Dollarzeichen `$$` für die Blockformatierung: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid-Diagramme](https://docs.docmd.io/de/plugins/mermaid/) --- title: "Mermaid-Diagramme" description: "Erstellen Sie professionelle Architekturdiagramme, Flussdiagramme und Sequenzdiagramme direkt in Ihren Markdown-Dateien mithilfe der Mermaid.js-Syntax." --- Das `@docmd/plugin-mermaid`-Plugin integriert die leistungsstarke [Mermaid.js](external:https://mermaid.js.org/)-Engine in Ihre Dokumentations-Pipeline. Es ermöglicht Ihnen, reine Textbeschreibungen in hochauflösende, interaktive Diagramme zu verwandeln, ohne jemals Ihre Markdown-Umgebung verlassen zu müssen. ## Hauptmerkmale - **Zero Scripting**: Es ist nicht erforderlich, externe Skripte oder CDN-Links manuell einzubinden. `docmd` erkennt die Verwendung und injiziert die Rendering-Engine nur dort, wo sie benötigt wird. - **Theme-Bewusstsein**: Diagramme passen ihre Farbschemata automatisch an den Wechsel zwischen **Light**- und **Dark**-Mode Ihrer Website an. - **Isomorphes Lazy Loading**: Für optimale Performance werden Diagramme erst initialisiert und gerendert, wenn sie in das Sichtfeld des Benutzers gelangen. - **Interaktive Steuerung**: Jedes Diagramm verfügt über integrierte Funktionen für **Pan** (Schwenken), **Zoom** und **Vollbild**, um sicherzustellen, dass auch große Architekturdiagramme auf allen Bildschirmgrößen lesbar bleiben. - **Icon-Integration**: Umfassende Unterstützung für das Icon-Paket, sodass Sie die Syntax `icon:name` innerhalb von Architekturdiagrammen verwenden können. - **Technische Lesbarkeit**: Diagramme bleiben in Ihrem Quellcode reiner Text, was sie leicht versionierbar und für KI-Agenten lesbar macht. ## Konfiguration Um die Diagramm-Unterstützung zu aktivieren, fügen Sie das `mermaid`-Plugin zu Ihrer `docmd.config.js` hinzu: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { mermaid: {} // Aktiviert mit Zero-Config } }); ``` ## Implementierungsgalerie Um ein Diagramm zu rendern, platzieren Sie Ihre Mermaid-Syntax in einem Fenced Code Block mit der Sprachkennung `mermaid`. ### 1. Sequenzdiagramme Ideal zur Veranschaulichung von Interaktionen zwischen mehreren Systemkomponenten. ::: tabs == tab "Vorschau" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Gibt URL ein Browser->>Server: HTTP-Anfrage Server-->>Browser: HTTP-Antwort Browser-->>User: Zeigt Seite an ``` == tab "Markdown-Quelle" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Gibt URL ein Browser->>Server: HTTP-Anfrage Server-->>Browser: HTTP-Antwort Browser-->>User: Zeigt Seite an ``` ```` ::: ### 2. Analytische Diagramme Visualisieren Sie Daten mit integrierten Diagrammtypen wie Torten- oder Balkendiagrammen. ::: tabs == tab "Vorschau" ```mermaid pie title Projektzusammensetzung "Dokumentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI-Komponenten" : 10 ``` == tab "Markdown-Quelle" ````markdown ```mermaid pie title Projektzusammensetzung "Dokumentation" : 45 "Core Engine" : 30 "Plugins" : 15 "UI-Komponenten" : 10 ``` ```` ::: ### 3. Git-Workflows Visualisieren Sie Branching- und Merging-Strategien für Ihre Entwickler-Leitfäden. ::: tabs == tab "Vorschau" ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` == tab "Markdown-Quelle" ````markdown ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` ```` ::: ### 4. Architektur & Icons Verwenden Sie das integrierte **Lucide**-Icon-Paket, um detailreiche Architekturdiagramme zu erstellen, die zum visuellen Stil Ihrer Website passen. ::: tabs == tab "Vorschau" ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Datenbank] in api service disk(icon:hard-drive)[Speicher] in api db:L -- R:disk ``` == tab "Markdown-Quelle" ````markdown ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Datenbank] in api service disk(icon:hard-drive)[Speicher] in api db:L -- R:disk ``` ```` ::: ## Technische Implementierung Das Mermaid-Plugin fängt `mermaid`-Codeblöcke während der Parsing-Phase ab und hüllt sie in einen speziellen `<div class="mermaid">`-Container. 1. **Erkennung**: Die Engine scannt das gerenderte HTML nach dem Vorhandensein von Mermaid-Containern. 2. **Asset-Injektion**: Wenn Container gefunden werden, injiziert `docmd` ein leichtgewichtiges `init-mermaid.js`-Modul. 3. **Rendering**: Die Mermaid-Bibliothek wird asynchron geladen und rendert die Diagramme clientseitig. So bleibt Ihr initiales HTML-Paket klein und schnell. ::: callout tip "Diagramme für KI-Agenten" Während Diagramme für Menschen visuell hilfreich sind, sind sie für KIs technisch transparent. Da die Quelle reiner Text ist, können Modelle wie GPT-4 oder Claude Ihre Systemarchitektur oder Logikflüsse über den `llms-full.txt`-Stream "sehen". Dies ermöglicht es der KI, komplexe architektonische Beziehungen basierend auf Ihren Diagrammen zu erklären. ::: --- ## [OpenAPI-Plugin](https://docs.docmd.io/de/plugins/openapi/) --- title: "OpenAPI-Plugin" description: "Rendert OpenAPI 3.x API-Referenzdokumentation direkt aus JSON- oder YAML-Spezifikationsdateien in Ihren Markdown-Seiten." --- Das **OpenAPI-Plugin** wandelt OpenAPI 3.x Spezifikationsdateien in strukturierte API-Referenzseiten um - zur Build-Zeit gerendert, ohne clientseitiges JavaScript und ohne Drittanbieter-Abhängigkeiten. Jeder Endpunkt, Parameter, Request-Body und jede Response wird in semantische HTML-Tabellen konvertiert. ::: callout info "Kern-Plugin" Das OpenAPI-Plugin ist jetzt standardmäßig in `@docmd/core` **enthalten**. Eine separate Installation ist nicht erforderlich. Es folgt der Docmd-Philosophie des Build-Zeit-Renderings - das Plugin liest Ihre Spezifikation und gibt saubere, zugängliche HTML-Tabellen ohne clientseitiges JavaScript aus. ::: ## Installation ```bash docmd add openapi # oder manuell: npm install @docmd/plugin-openapi ``` In Ihrer Konfiguration aktivieren: ```javascript export default defineConfig({ plugins: { openapi: {} } }); ``` ## Verwendung Betten Sie eine OpenAPI-Spezifikation in jede Markdown-Seite ein, indem Sie einen umzäunten Codeblock mit dem `openapi`-Sprach-Tag verwenden: ````markdown ### Live-Beispiel ```openapi assets/docmd-api.json ``` ```` ### Ergebnis ```openapi assets/docmd-api.json ``` Der Pfad wird relativ zu Ihrem `src`-Verzeichnis aufgelöst. Sowohl **JSON** als auch **YAML**-Formate werden unterstützt. YAML erfordert die Installation von `js-yaml`: ```bash npm install js-yaml ``` ## Was gerendert wird Für jeden Pfad und jede HTTP-Methode in der Spezifikation rendert das Plugin: - **Methoden-Badge** - farbkodiert (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`) - **Pfad** - der vollständige Endpunkt-Pfad - **Zusammenfassung und Beschreibung** - aus dem Operationsobjekt - **Parameter-Tabelle** - Name, Position (`path`, `query`, `header`, `cookie`), Typ, Pflichtfeld, Beschreibung - **Request-Body-Tabelle** - Schema-Eigenschaften mit Typen und Standardwerten - **Response-Tabelle** - Status-Codes mit Beschreibungen und Response-Schema-Typen - **Veraltungshinweis** - als `deprecated: true` markierte Operationen werden inline gekennzeichnet ::: callout tip "Build-Zeit-Rendering" Alles Rendering erfolgt zur Build-Zeit. Die generierten Seiten sind vollständig statisch - kein JavaScript ist erforderlich, um die API-Dokumentation anzuzeigen, was schnelle Seitenladevorgänge und vollständige Suchindexierung bedeutet. ::: ## Unterstützte OpenAPI-Funktionen | Funktion | Unterstützung | | :--- | :--- | | OpenAPI 3.x | ✓ | | Swagger 2.x | ✗ (zuerst in 3.x konvertieren) | | JSON-Format | ✓ | | YAML-Format | ✓ (erfordert `js-yaml`) | | `$ref`-Auflösung | ✓ (interne `#/components/schemas/`-Refs) | | `oneOf` / `anyOf`-Typen | ✓ (als Union-Type-Strings angezeigt) | | Verschachtelte Schema-Tabellen | ✓ | | `deprecated`-Flag | ✓ | | Externe `$ref` (Remote-URLs) | ✗ (nur lokale Refs) | ## Konfiguration Das OpenAPI-Plugin kann in Ihrer `docmd.config.js` konfiguriert werden: ```javascript export default defineConfig({ plugins: { openapi: { info: true, // API-Titel und Versions-Header anzeigen download: true, // 'Download JSON/YAML'-Link in der Benutzeroberfläche bereitstellen summaryOnly: false, // Nur Zusammenfassungen anzeigen, Parameter/Antworten ausblenden allowRawHtml: false // HTML in Beschreibungen zulassen (mit Vorsicht verwenden) } } }); ``` | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `info` | `boolean` | `true` | Zeigt API-Titel, Version und Beschreibung aus dem `info`-Objekt der Spezifikation an. | | `download` | `boolean` | `false` | Wenn wahr, wird ein Link im Header der Spezifikation hinzugefügt, um die rohe JSON/YAML-Datei herunterzuladen/anzusehen. **Empfohlen für KI-Barrierefreiheit.** | | `summaryOnly` | `boolean` | `false` | Wenn wahr, werden nur Methode, Pfad und Zusammenfassung gerendert. Nützlich für große API-Indizes. | | `allowRawHtml` | `boolean` | `false` | Wenn wahr, wird das Escaping von HTML-Tags in Beschreibungen verhindert. | ## Seitenspezifische Steuerung Plugin für bestimmte Seiten über Frontmatter deaktivieren: ```markdown --- title: "Interne Notizen" plugins: openapi: false --- ``` --- ## [PWA & Offline-Support](https://docs.docmd.io/de/plugins/pwa/) --- title: "PWA & Offline-Support" description: "Verwandeln Sie Ihre Dokumentation in eine progressive Webanwendung mit Offline-Caching und mobil-optimierten Funktionen." --- Das `@docmd/plugin-pwa`-Plugin verwandelt Ihre Dokumentation in eine Progressive Web App (PWA). Es fügt ein Web-Manifest für die mobile Installation hinzu und registriert einen Service Worker für das intelligente Offline-Caching. So bleibt Ihre technische Dokumentation auch in Umgebungen mit schlechter Internetverbindung zugänglich. ## Konfiguration Passen Sie Ihre App-Branding-Einstellungen innerhalb des `plugins`-Abschnitts Ihrer `docmd.config.json` an. | Option | Typ | Standardwert | Beschreibung | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Aktiviert oder deaktiviert die Generierung des PWA-Manifests und Service Workers. | | `themeColor` | `string` | `'#1e293b'` | Die Primärfarbe der mobilen Benutzeroberfläche des Browsers. | | `bgColor` | `string` | `'#ffffff'` | Hintergrundfarbe für den Startbildschirm (Splash Screen) während der Installation. | | `logo` | `string` | `null` | Pfad zum App-Icon (relativ zur Projektquelle). | ### Beispiel ```json { "plugins": { "pwa": { "themeColor": "#1e293b", "bgColor": "#ffffff", "logo": "assets/app-icon.png" } } } ``` ## Funktionen - **Offline-Caching**: Verwendet eine „Stale-While-Revalidate“-Strategie. Seiten werden sofort aus dem Cache geladen, während im Hintergrund nach Updates gesucht wird. - **Mobile Installation**: Generiert eine `manifest.webmanifest`-Datei, die es Benutzern unter iOS und Android ermöglicht, die App nativ „Zum Home-Bildschirm hinzuzufügen“. - **Intelligente Asset-Auflösung**: Erstellt App-Icons automatisch aus dem Logo oder Favicon Ihres Projekts, falls kein explizites Icon angegeben ist. - **SPA-Kompatibel**: Vollständig kompatibel mit Single-Page-Application-Übergängen und Standard-Verzeichnis-Routing. ## Priorität der Icon-Auflösung Das Plugin löst Ihre PWA-Icons anhand der folgenden Rangfolge auf: 1. `pwa.icons` - Explizites Array in der Konfiguration. 2. `pwa.logo` - Pfad relativ zur Quelle. 3. `config.logo` - Globales Website-Logo. 4. `config.favicon` - Globales Favicon. ::: callout tip "Testen von PWA-Funktionen" Service Worker werden in `npx @docmd/core dev` umgangen, um Caching-Probleme während der Bearbeitung zu vermeiden. Um PWA-Funktionen zu testen, führen Sie `npx @docmd/core build` aus und stellen Sie das `site/`-Verzeichnis über einen statischen Host bereit. ::: --- ## [Such-Plugin](https://docs.docmd.io/de/plugins/search/) --- title: "Such-Plugin" description: "Aktivieren Sie eine extrem schnelle, Offline-first Volltextsuche für Ihre Dokumentation mit MiniSearch." --- Das `@docmd/plugin-search`-Plugin bietet ein leistungsstarkes, clientseitiges Sucherlebnis für Ihre Dokumentation. Es verwendet [MiniSearch](external:https://github.com/lucaong/minisearch), um während des Build-Prozesses einen leichtgewichtigen Index zu erstellen, der es Benutzern ermöglicht, technische Informationen sofort und ohne serverseitige Datenbank zu finden. ## Konfiguration Die Suche ist in den meisten `docmd`-Templates standardmäßig aktiviert. Sie können ihre Sichtbarkeit und Platzierung über die `layout`-Konfiguration steuern. | Option | Typ | Standardwert | Beschreibung | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `true` | Aktiviert oder deaktiviert den Volltext-Suchindexer. | | `placeholder` | `String` | `'Search...'` | Benutzerdefinierter Platzhaltertext für das Sucheingabefeld. | | `maxResults` | `Number` | `10` | Maximale Anzahl an Suchergebnissen, die im Modal angezeigt werden. | ### Beispiel ```json { "layout": { "optionsMenu": { "position": "header", "components": { "search": true } } } } ``` ## Funktionsweise <img width="720" class="with-border" src="/assets/previews/search-ui-default.webp"> ### 1. Indizierung (Build-Zeit) Während des `docmd build`-Prozesses iteriert das Such-Plugin über jede Seite Ihrer Website. Es extrahiert den Titel, Überschriften und den Fließtext und komprimiert diese Daten dann in eine `search-index.json`-Datei. * **Deep Linking**: Der Indexer registriert automatisch jede Überschrift (`#`, `##` etc.) als suchbares Ziel. * **Relevanz-Gewichtung**: Titel erhalten das höchste Gewicht, gefolgt von Überschriften und schließlich dem Seiteninhalt. ### 2. Abruf (Client-seitig) Wenn ein Benutzer das Suchmodal öffnet (normalerweise über `/` oder `Strg+K`), wird die `search-index.json` vom Browser geladen. Suchen werden lokal mit Fuzzy-Matching (erlaubt kleine Tippfehler) und sofortigem Präfix-Matching durchgeführt. ## Suchverhalten anpassen Obwohl das Such-Plugin auf Einfachheit ohne Konfiguration ausgelegt ist, können Sie bestimmte Seiten vom Index ausschließen, indem Sie das `noindex`-Flag in deren Frontmatter verwenden: ```yaml --- title: "Interne Spezifikation" noindex: true # Diese Seite wird nicht in den Suchergebnissen oder Sitemaps erscheinen --- ``` ## Technische Implementierung Das Plugin injiziert ein leichtgewichtiges Suchmodal in den `<body>` Ihrer Website. Es ist vollständig barrierefrei (ARIA-konform) und unterstützt die Tastaturnavigation für ein Erlebnis, das sich wie eine native App anfühlt. ::: callout tip "Such-Analyse" Wenn Sie das [Analytics-Plugin](./analytics.md) aktiviert haben, werden die von Ihren Lesern verwendeten Suchbegriffe automatisch erfasst und an Ihren Analytics-Anbieter gesendet. So erhalten Sie Einblicke, welche Informationen fehlen oder am schwersten zu finden sind. ::: Da die Suche vollständig auf dem Client stattfindet, werden niemals Daten - nicht einmal Tastaturanschläge - an einen Server gesendet. Dies macht `docmd` zum Goldstandard für die Dokumentationssuche in datenschutzsensiblen Branchen (Gesundheitswesen, Finanzen, Sicherheit). ## Vergleich Viele Dokumentationsgeneratoren (wie Docusaurus) verlassen sich auf **Algolia DocSearch**. Obwohl Algolia leistungsstark ist, bringt es Hürden mit sich: | Feature | docmd Suche | Algolia / Extern | | :--- | :--- | :--- | | **Einrichtung** | **Zero Config** (Automatisch) | Komplex (API-Keys, CI/CD Crawling) | | **Datenschutz** | **100% Privat** (Client-seitig) | Daten werden an Drittserver gesendet | | **Offline** | **Ja** | Nein | | **Kosten** | **Kostenlos** | Kostenloses Kontingent oder kostenpflichtig | | **Geschwindigkeit** | **Sofort** (In-Memory) | Schnell (Abhängig von Netzwerklatenz) | ## Semantische Suche (Alpha-Vorschau) ::: callout tip "Neu: docmd-search" Wir haben etwas gebaut, auf das wir ziemlich stolz sind. **`docmd-search`** ist nach unserem Wissen die erste vollständig offline-fähige semantische Suchmaschine für Dokumentationen - und sie ist nicht an docmd gebunden. Sie läuft vollständig im Browser, benötigt weder Server noch API-Schlüssel, und keine Nutzerdaten verlassen das Gerät. Integrierbar in jede Dokumentations-Engine, jede statische Website oder jede beliebige Webseite. Einfach einstecken und loslegen. Dies ist eine frühe Alpha-Version. Vieles wird sich verbessern und weiterentwickeln. Doch das Fundament - private, offline und wirklich intelligente Suche - steht bereits. [→ Auf GitHub ansehen](https://github.com/docmd-io/docmd-search) ::: > **Experimentelles Feature** - Die semantische Suche befindet sich derzeit in der Alpha-Vorschau. Die standardmäßige keyword-basierte Suche bleibt die empfohlene Option für den produktiven Einsatz. <img width="720" class="with-border" src="/assets/previews/search-ui-semantic.webp"> Die semantische Suche verwendet lokale Embeddings, um die Bedeutung hinter Suchanfragen zu verstehen. Dies ermöglicht intelligentere Ergebnisse über einfache Keyword-Treffer hinaus. ### Semantische Suche aktivieren Installieren Sie zuerst das Paket `docmd-search`: ```bash npm install docmd-search ``` Aktivieren Sie es dann in Ihrer Konfiguration: ```json { "plugins": { "search": { "semantic": true } } } ``` ### Wie die semantische Suche funktioniert Im Gegensatz zur Keyword-Suche, die exakte Begriffe abgleicht, bietet die semantische Suche: * **Kontextverständnis** - Eine Anfrage nach „Authentifizierung“ findet relevante Seiten, selbst wenn dort Begriffe wie „Anmeldung“ oder „Login“ verwendet werden. * **Natürliche Fehlertoleranz** - Keine Notwendigkeit für klassische Fuzzy-Logik; das Modell versteht die Absicht. * **Erkennung verwandter Konzepte** - Die Suche nach „API“ gibt relevante Endpoint-Dokumentationen zurück, nicht nur Seiten, die das Wort „API“ enthalten. ### Konfigurationsoptionen | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `semantic` | `boolean` | `false` | Semantische Suche aktivieren (erfordert das Paket `docmd-search`) | | `showConfidence` | `boolean` | `false` | Ähnlichkeits-Konfidenz-Badges (Übereinstimmungs-Scores) in den semantischen Suchergebnissen anzeigen | | `showFilters` | `boolean` | `true` | Versionsfilter-Leiste über den Suchergebnissen anzeigen (auf `false` setzen, um sie auszublenden) | | `model` | `string` | `'Xenova/all-MiniLM-L6-v2'` | Zu verwendendes Embedding-Modell | | `chunkSize` | `number` | `512` | Maximale Chunk-Größe in Zeichen | | `chunkOverlap` | `number` | `50` | Überlappung zwischen Chunks in Zeichen | | `indexDir` | `string` | - | Pfad zum vorgefertigten semantischen Index | ### Vergleich: Semantisch vs. Keyword | Feature | Semantische Suche | Keyword-Suche | | :--- | :--- | :--- | | **Verständnis** | Kontextsensitiv | Nur exakte Treffer | | **Fehlertoleranz** | Hoch | Begrenzt (Fuzzy-Matching) | | **Synonyme** | Ja | Nein | | **Einrichtung** | Erfordert `docmd-search` | Integriert | | **Indexgröße** | Größer (1–2 MB pro 100 Dateien) | Kleiner | | **Datenschutz** | 100 % privat (clientseitig) | 100 % privat (clientseitig) | | **Offline** | Ja | Ja | ### Fallback-Verhalten Wenn die semantische Suche aktiviert ist, das Paket `docmd-search` jedoch nicht installiert ist, fällt das Plugin automatisch auf die Keyword-Suche zurück. Dadurch bleibt Ihre Dokumentation in jedem Fall suchbar. ::: callout warning "Alpha-Einschränkungen" Die semantische Suche ist experimentell. Zu den aktuellen Einschränkungen gehören: * Modelle nur für Englisch (mehrsprachige Modelle verfügbar, aber weniger getestet) * Keine inkrementellen Updates (vollständiger Rebuild erforderlich) * Höhere Speichernutzung (~50–100 MB im Browser) * Das erste Laden kann langsamer sein, da die Embeddings geladen werden müssen ::: ### Best Practices Für optimale Leistung der semantischen Suche: 1. **Rauschen ausschließen** - Indizieren Sie keine Changelogs oder Entwürfe: ```json { "plugins": { "search": { "semantic": true, "exclude": ["**/release-notes/**", "**/drafts/**"] } } } ``` 2. **Für CI/CD vorbauen** - Nutzen Sie die Option `indexDir`, um Indizes vorab zu generieren: ```bash npx docmd-search --ui ``` 3. **Indexgröße überwachen** - Überprüfen Sie regelmäßig die Größe des Ordners `.docmd-search/` 4. **Gründlich testen** - Überprüfen Sie die Qualität der Suchergebnisse, bevor Sie sie in der Produktion bereitstellen --- ## [SEO-Plugin](https://docs.docmd.io/de/plugins/seo/) --- title: "SEO-Plugin" description: "Optimieren Sie Ihre Dokumentation für Suchmaschinen und steuern Sie den Zugriff von KI-Crawlern mit nativer Meta-Tag-Generierung." --- Das `@docmd/plugin-seo`-Plugin ist für die Generierung hochwertiger Metadaten für jede Seite verantwortlich. Es stellt sicher, dass Ihre Dokumentation nicht nur von menschlichen Lesern in Suchmaschinen gefunden wird, sondern auch von KI-Modellen und Social-Media-Plattformen korrekt interpretiert wird. ## Globale Konfiguration Konfigurieren Sie projektweite SEO-Standardwerte in Ihrer `docmd.config.js`. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { seo: { defaultDescription: 'Umfassende Dokumentation für das docmd-Ökosystem.', aiBots: false, // Auf false setzen, um gängige KI-Crawler (GPTBot etc.) zu blockieren openGraph: { defaultImage: '/assets/og-image.png' }, twitter: { siteUsername: '@docmd_io', cardType: 'summary_large_image' } } } }); ``` ## Überschreibungen auf Seitenebene Sie können SEO-Einstellungen für einzelne Seiten über das Frontmatter feinabstimmen. Einstellungen auf Seitenebene haben immer Vorrang vor globalen Standardwerten. ```yaml --- title: "Erweiterte Konfiguration" description: "Lernen Sie, wie Sie die interne Engine von docmd meistern." noindex: true # Diese spezifische Seite vor allen Suchmaschinen verbergen seo: keywords: ["docmd", "javascript", "ssg"] ogType: "article" canonicalUrl: "https://meineseite.de/kanonischer-pfad" aiBots: true # Globalen Block überschreiben, um KI-Zugriff auf diese Seite zu erlauben --- ``` ## Kernfunktionen ### 1. Intelligenter Beschreibungs-Fallback Wenn im Frontmatter oder in der globalen Konfiguration keine Beschreibung angegeben ist, extrahiert das Plugin automatisch die ersten 150 Zeichen des Fließtexts der Seite, um sie als `<meta name="description">` zu verwenden. So wird sichergestellt, dass jede Seite über grundlegende Metadaten für Suchergebnisse verfügt. ### 2. KI-Bot-Steuerung Durch das Setzen von `aiBots: false` injiziert das Plugin `noindex`-Anweisungen speziell für große KI-Crawler (einschließlich `GPTBot`, `Claude-Web` und `Google-Extended`). Dies ermöglicht es Ihnen, zwischen herkömmlicher Suchmaschinenindizierung und LLM-Trainingssitzungen zu unterscheiden. ### 3. Kanonische Auflösung Das Plugin generiert automatisch `<link rel="canonical">`-Tags basierend auf Ihrer `siteUrl`. Es verarbeitet Verzeichnisindizes intelligent und konvertiert `guide/index.html` in eine saubere kanonische `/guide/`-URL, um Probleme mit doppeltem Inhalt zu vermeiden. ### 4. Ansprechende Social-Media-Vorschauen Die native Unterstützung für Open Graph und Twitter Cards stellt sicher, dass Links zu Ihrer Dokumentation professionell aussehen, wenn sie auf Plattformen wie X (Twitter), LinkedIn und Discord geteilt werden. ::: callout tip "Sichtbarkeit in der Suche" Für die besten SEO-Ergebnisse stellen Sie sicher, dass Ihre `siteUrl` im Root Ihrer Konfiguration definiert ist. Ohne eine Basis-URL kann das Plugin keine absoluten kanonischen Links oder Pfade für Open-Graph-Bilder generieren. ::: ## Strukturierte Daten (LD+JSON) `docmd` kann automatisch das [Article Schema](external:https://developers.google.com/search/docs/appearance/structured-data/article) generieren, um Suchmaschinen bei der Anzeige von Rich Snippets zu unterstützen. ```yaml --- title: "Wie man ein docmd-Plugin erstellt" seo: ldJson: true --- ``` ::: callout tip "Strukturierte Daten" Ein gut konfiguriertes SEO-Plugin hilft KI-gestützten Suchmaschinen (wie SearchGPT oder Perplexity), Ihre Website genau zusammenzufassen. Durch die Bereitstellung klarer Beschreibungen und das Blockieren von Bots steuern Sie genau, wie KI-Modelle Ihre Inhalte online wahrnehmen und als Quelle verwenden. ::: --- ## [Sitemap-Plugin](https://docs.docmd.io/de/plugins/sitemap/) --- title: "Sitemap-Plugin" description: "Generieren Sie automatisch eine standardkonforme sitemap.xml für eine bessere Sichtbarkeit in Suchmaschinen." --- Das Plugin `@docmd/plugin-sitemap` generiert automatisch eine `sitemap.xml`-Datei im Stammverzeichnis Ihres Build-Ordners. Diese Datei bietet Suchmaschinen wie Google und Bing eine umfassende Karte der Architektur Ihrer Website und stellt sicher, dass alle Seiten - einschließlich Deep-Links innerhalb versionierter Dokumentationen - gecrawlt und indexiert werden. ## Konfiguration Aktivieren Sie die Sitemap-Generierung, indem Sie Ihre `siteUrl` in der Hauptkonfiguration angeben. Sie können die Crawling-Gewichtung verschiedener Abschnitte innerhalb des `plugins`-Objekts anpassen. ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ siteUrl: 'https://docs.beispiel.de', // Erforderlich für die Sitemap-Generierung plugins: { sitemap: { defaultChangefreq: 'weekly', // 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never' defaultPriority: 0.8, // Standardgewichtung für normale Seiten rootPriority: 1.0 // Gewichtung für die Startseite (index.md) } } }); ``` ## Steuerungen auf Seitenebene Sie können das Sitemap-Verhalten für spezifische Seiten über das Frontmatter überschreiben. ```yaml --- title: "Archiv-Seite" priority: 0.3 # Niedrigere Gewichtung für alte Inhalte changefreq: "monthly" # Hinweis an Crawler, dass sich diese Seite selten ändert lastmod: "2024-03-15" # Explizites Setzen des letzten Änderungsdatums sitemap: false # Diese spezifische Seite aus der sitemap.xml ausschließen --- ``` ## Kernfunktionen ### 1. Automatische URL-Konstruktion Das Plugin löst Seitenpfade intelligent in ihre kanonischen öffentlichen URLs auf. Es verarbeitet Verzeichnis-Indizes automatisch und stellt sicher, dass `guide/index.html` als `https://meineseite.de/guide/` aufgeführt wird, um eine saubere URL-Struktur beizubehalten. ### 2. Entdeckung von Versionen Wenn Ihr Projekt [Versionierung](../configuration/versioning) verwendet, schließt das Sitemap-Plugin automatisch alle Seiten aus allen Versionen ein (z. B. `/v1/erste-schritte`, `/v2/erste-schritte`). Dies ermöglicht es Suchmaschinen, Ihre archivierten Dokumentationen ohne manuelle Konfiguration zu entdecken. ### 3. Intelligente Ausschlüsse Seiten, die in ihrem Frontmatter mit `noindex: true` oder `sitemap: false` markiert sind, werden automatisch von der generierten `sitemap.xml` ausgeschlossen. Dies gibt Ihnen eine granulare Kontrolle darüber, was den Suchmaschinen präsentiert wird. ::: callout tip "Validierung" Nach dem Build Ihrer Website finden Sie die Sitemap normalerweise unter `ihr-ausgabe-ordner/sitemap.xml`. Die meisten Search-Engine-Konsolen ermöglichen es Ihnen, diese Datei direkt einzureichen, um die Indexierung zu beschleunigen. ::: --- ## [Threads-Plugin](https://docs.docmd.io/de/plugins/threads/) --- title: "Threads-Plugin" description: "Fügen Sie Ihrer Dokumentation Inline-Diskussionsstränge hinzu - direkt in Ihren Markdown-Dateien gespeichert." --- Das **Threads-Plugin** bringt kollaborative Inline-Kommentare in Ihre Dokumentation. Wählen Sie einen beliebigen Text auf der Seite aus, hinterlassen Sie einen Kommentar, starten Sie eine Diskussion - alles wird direkt in Ihren Markdown-Quelldateien gespeichert, ganz ohne Datenbank. Originalautor: [@svallory](external:https://github.com/svallory) ::: callout info "Alpha-Release" Dieses Plugin befindet sich in der Alpha-Phase. Die API und das Speicherformat sind stabil, aber die Benutzeroberfläche wird aktiv weiterentwickelt. ::: ## Einrichtung ```bash docmd add threads ``` ```javascript plugins: { threads: {} } ``` ### Konfigurationsoptionen | Option | Typ | Standard | Beschreibung | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | Wenn `true`, bleiben Threads am Ende der Seite gruppiert. Wenn `false` (Standard), werden Threads inline neben dem markierten Text positioniert. | ```javascript // Threads am Ende der Seite behalten statt inline plugins: { threads: { sidebar: true } } ``` ## Funktionsweise 1. **Text markieren** auf einer beliebigen Dokumentationsseite während `docmd dev`. 2. Ein **Kommentar-Popover** erscheint - schreiben Sie Ihren Kommentar und senden Sie ihn ab. 3. Der ausgewählte Text wird mit einem Thread-Marker **hervorgehoben**. 4. Threads werden als `::: threads`-Blöcke am Ende der Markdown-Datei gespeichert. 5. **Keine Datenbank** - Ihre Markdown-Dateien sind die "Source of Truth". ## Vorschau So sehen Threads auf einer Live-Seite aus. Text mit Diskussionen wird <span class="threads-preview-highlight">so hervorgehoben</span> und Thread-Karten erscheinen darunter. <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 2 T.</div> <div class="threads-preview-body">Dieser Abschnitt könnte ein Diagramm vertragen, um die Architektur zu erklären. Was denkst du?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · vor 1 T.</div> <div class="threads-preview-body">Gute Idee - ich füge ein Mermaid-Flowchart hinzu. Funktioniert <code>sequenceDiagram</code> hier?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 12 Std.</div> <div class="threads-preview-body">Perfekt. Ein einfaches Flowchart wäre ideal.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Und hier ist eine <span class="threads-preview-highlight-blue">zweite Hervorhebung mit einer anderen Farbe</span> - Threads durchlaufen automatisch eine Farbpalette. <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · vor 3 T.</div> <div class="threads-preview-body">Sollten wir hier die Abwärtskompatibilität erwähnen?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Erledigte Threads erscheinen ausgegraut: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · vor 5 T.  <span class="threads-preview-resolved-badge">✓ Erledigt</span></div> <div class="threads-preview-body">Tippfehler im Konfigurationsbeispiel behoben.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ Neuer Kommentar</div> </div> </div> Ein schwebender **Diskussions-Button** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span> erscheint in der unteren rechten Ecke und zeigt die Anzahl der offenen Threads an. Klicken Sie darauf, um zum ersten Thread auf der Seite zu springen. ## Speicherformat Threads werden unter Verwendung der Container-Syntax von docmd in Ihr Markdown eingebettet: ```markdown # Meine Dokumentationsseite Inhalt mit ==markiertem Text=={t-a1b2c3d4}, der einen Thread hat. ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" Dieser Text muss klargestellt werden. ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 Habe es aktualisiert - passt das so? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` Die Syntax `==Text=={threadId}` verknüpft markierten Text im Dokumentenkörper mit einem spezifischen Thread. ## Features | Feature | Beschreibung | | :--- | :--- | | **Textauswahl** | Markieren Sie beliebigen Text, um einen neuen Thread zu starten | | **Antworten** | Verschachtelte Antwortketten innerhalb jedes Threads | | **Reaktionen** | Emoji-Reaktionen auf einzelne Kommentare | | **Bearbeiten / Löschen** | Ändern oder entfernen Sie Ihre Kommentare | | **Erledigen** | Markieren Sie Threads als erledigt mit Autor + Zeitstempel | | **Autorenprofile** | Git-basierte Autorenerkennung mit Gravatar-Unterstützung | | **Highlight-Marker** | Visuelle Indikatoren auf der Seite, die zeigen, wo Threads verankert sind | | **Schwebender Button** | Schnellzugriff-FAB mit Anzahl der offenen Threads | | **Scroll-Erhaltung** | Die Seite bleibt nach dem Hinzufügen von Kommentaren an derselben Position | ## Actions API Das Threads-Plugin macht die folgenden Aktionen über das WebSocket-RPC-System verfügbar. Diese können von Browser-Plugins über `docmd.call()` aufgerufen werden: | Aktion | Beschreibung | | :--- | :--- | | `threads:get-threads` | Parst und gibt alle Threads aus einer Datei zurück | | `threads:add-thread` | Erstellt einen neuen Thread mit seinem ersten Kommentar | | `threads:add-comment` | Fügt einen Kommentar zu einem bestehenden Thread hinzu | | `threads:edit-comment` | Bearbeitet den Inhalt eines bestehenden Kommentars | | `threads:delete-comment` | Entfernt einen Kommentar aus einem Thread | | `threads:delete-thread` | Entfernt einen kompletten Thread und bereinigt die Highlights | | `threads:resolve-thread` | Schaltet den Status zwischen erledigt/offen um | | `threads:toggle-reaction` | Schaltet eine Emoji-Reaktion auf einen Kommentar um | | `threads:get-authors` | Liest die Autorenprofil-Map aus | | `threads:upsert-author` | Erstellt oder aktualisiert ein Autorenprofil | ## Autorenprofile Autoreninformationen werden in `<docsRoot>/.threads/authors.json` gespeichert: ```javascript "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } ``` Während der Entwicklung erkennt das Plugin automatisch Ihren Git-Benutzernamen und Ihre E-Mail zur Autorenidentifikation. ::: callout tip "Versionskontrollfreundlich" Da Threads in Ihren Markdown-Dateien gespeichert werden, unterliegen sie automatisch der Versionskontrolle mit Git. Überprüfen Sie Kommentare in PRs, verfolgen Sie die Diskussionshistorie und arbeiten Sie über Ihren bestehenden Workflow zusammen. ::: --- ## [Plugin-Mechanismus & Verwendung](https://docs.docmd.io/de/plugins/usage/) --- title: "Plugin-Mechanismus & Verwendung" description: "Erfahren Sie mehr über die Lifecycle-Hooks von docmd, den Plugin-Sicherheitsmechanismus und wie Sie die Funktionen der Engine erweitern können." --- `docmd` folgt einer steckbaren Architektur. Fast alle Kernfunktionen - von der Suche über SEO bis hin zur Live-Vorschau - sind als Plugins implementiert. Dieses Design stellt sicher, dass die Engine leichtgewichtig bleibt, während Entwickler Funktionen selektiv basierend auf ihren spezifischen Projektanforderungen aktivieren können. ## Plugin-Übersicht | Plugin | Funktion | | :--- | :--- | | **[Suche (Search)](search.md)** | Bietet eine leistungsstarke, Offline-first Volltextsuche. | | **[SEO](seo.md)** | Generiert automatisch Meta-Tags, Sitemaps und steuert den Zugriff von KI-Crawlern. | | **[Mermaid](mermaid.md)** | Rendert Flussdiagramme, Sequenzdiagramme und Gantt-Charts. | | **[LLMs](llms.md)** | Generiert einen maschinenlesbaren Stream der gesamten Dokumentation für KI-Training oder Suche. | | **[Live-Vorschau (Live)](../content/live-preview.md)** | Stellt eine im Browser laufende Rendering-Engine für benutzerdefinierte Editoren bereit. | ## Lifecycle-Hooks Plugins können in den Build-Prozess eingreifen, indem sie sich in die folgenden Lifecycle-Hooks einklinken: | Hook | Beschreibung | | :--- | :--- | | `onInit(ctx)` | Wird sofort nach dem Start der Engine und dem Laden der Konfiguration ausgeführt | | `onPostBuild(ctx)` | Ausführung von Logik nach der Generierung aller HTML-Dateien | | `translations(localeId)` | Gibt übersetzte UI-Strings für ein Locale zurück | | `actions` | Serverseitige Handler, die über WebSocket-RPC vom Browser aus aufrufbar sind | | `events` | "Fire-and-Forget"-Handler für vom Browser gepushte Events | ## Plugin-Sicherheit Das Plugin-System bietet integrierte Sicherheitsgarantien: - **Validierung**: Plugins können einen `plugin`-Deskriptor mit `name`, `version` und `capabilities` deklarieren. Ungültige Deskriptoren werden zum Ladezeitpunkt abgelehnt. - **Isolierung**: Jeder Hook-Aufruf ist in einen Try/Catch-Block gehüllt. Ein fehlerhaftes Plugin kann weder den Build zum Absturz bringen noch andere Plugins beeinflussen. - **Erzwingung von Fähigkeiten**: Plugins, die Fähigkeiten (Capabilities) deklarieren, können sich nur für Hooks registrieren, die sie explizit deklariert haben. Nicht deklarierte Hooks werden mit einer Warnung übersprungen. Siehe [Plugins erstellen](building-plugins.md) für die vollständige API-Referenz. ::: callout tip "KI-transparente Architektur :robot:" Die Plugin-Architektur ist auf **Determinismus** ausgelegt. Jeder von einem Plugin injizierte Meta-Tag und jedes Skript ist rückverfolgbar, was es KI-Agenten (und menschlichen Entwicklern) ermöglicht, genau zu verstehen, wie sich die Website verhält, ohne versteckte Nebeneffekte. ::: --- ## [Versionshinweise - 0.8.0](https://docs.docmd.io/de/release-notes/0-8-0/) --- title: "Versionshinweise - 0.8.0" description: "Leistungsstarke Multi-Thread-Architektur, generische Worker-Plugin-APIs und massive Leistungsschübe." --- Die `docmd` 0.8.0 Version stellt ein monumentales Architektur-Upgrade dar - sie führt einen nativen Multi-Threaded Worker-Pool ein, der Seiten parallel verarbeitet, wodurch die Build-Zeiten für große Dokumentations-Websites drastisch verkürzt werden, zusammen mit einer leistungsstarken neuen Plugin-Worker-API. ## ✨ Highlights ### ⚡ Multi-Threaded Build-Architektur docmd baut Ihre Dokumentation jetzt parallel auf, indem ein hochoptimierter `WorkerPool` verwendet wird. Indem der schwerste Teil der Pipeline - das Parsing des Markdown-AST und die Prozessor-Hooks - in isolierte Hintergrund-Threads verlagert wird, kann docmd nun alle verfügbaren CPU-Kerne vollständig ausnutzen. Für große Workspaces (z.B. mehr als 1000 Seiten) führt dies zu **massiven Leistungsschüben**, wodurch Kaltstart-Build-Zeiten drastisch verkürzt und die Entwicklererfahrung beim Hot-Reload flüssiger wird. Der Thread-Pool wird intelligent begrenzt (`os.cpus().length - 1`), um sicherzustellen, dass Ihr Hauptsystem bei schweren Builds reaktionsfähig bleibt. ### 🔌 Plugin Worker API Wir haben docmd nicht nur multi-threaded gemacht, wir haben das Multi-Threading auch für das gesamte Ökosystem zugänglich gemacht. Plugins können nun ihre eigenen rechenintensiven oder synchronen Aufgaben an den docmd-Worker-Pool auslagern, ohne die Thread-Erstellung selbst verwalten zu müssen. Eine neue `runWorkerTask`-API wird in `ActionContext`, `PageContext` und `PostBuildContext` injiziert. ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['post-build'] }, async onPostBuild(ctx) { // Senden Sie schwere Vorgänge (wie das Parsen des Git-Verlaufs) an einen Hintergrund-Thread const result = await ctx.runWorkerTask( '/absolute/path/to/my-worker-script.js', 'parseGitHistory', [ctx.outputDir] ); } } ``` ### 🧩 Gemeinsamer modularer Kern Wir haben formell ein neues Paket extrahiert: `@docmd/utils`, eine abhängigkeitsfreie Bibliothek für gemeinsam genutzte Dienstprogramme. Dieses Paket zentralisiert Dateisystem-Wrapper, Pfad-Normalisierung, Hashing-Mechanismen und den eigentlichen `WorkerPool`, verhindert zirkuläre Abhängigkeiten und ermöglicht es Plugins, robuste Hilfsmittel direkt aus dem docmd-Ökosystem zu importieren. ## 📝 Vollständiges Änderungsprotokoll ### 🚀 Engine & Architektur - **Worker-Parser-Pipeline**: Der Markdown-Kernprozessor wird nun dynamisch in Hintergrund-Threads rehydriert. Dateien werden gleichzeitig gelesen und chargenweise an die Worker verteilt. - **AST Caching Engine**: Eine MD5-basierte Caching-Ebene fängt unveränderte Dateien ab. Wenn sich der rohe Inhalts-Hash einer Datei seit dem letzten Durchlauf nicht geändert hat, wird das AST-Parsing komplett übersprungen. - **Persistente Dev-Worker**: Während `docmd dev` bleibt der Worker-Pool über Dateispeicherungen hinweg persistent. Dies eliminiert die typische Node.js-Thread-Startlatenz von 200-500 ms und führt zu nahezu sofortigen inkrementellen Rebuilds. - **Worker CPU Throttling**: Der Thread-Pool berechnet die exakte Anzahl der Threads basierend auf der Systemarchitektur und reserviert einen CPU-Kern, um I/O-Aushungerung und Betriebssystem-Sperren zu verhindern. ### 🔌 Plugin System - **`runWorkerTask` API**: Wird direkt in den Plugin-Kontexten (`onBeforeRender`, `onPostBuild`, `actions`, `events`) für die generische Skriptausführung im Hintergrund offengelegt. - **Git Plugin Persistenter Cache**: Das Git-Plugin nutzt nun einen robusten persistenten Festplatten-Cache (`.docmd/cache/git-history.json`), der über die Datei-Änderungszeit (`mtimeMs`) invalidiert wird. Dadurch werden redundante `git log` Shell-Subprozesse bei Folge-Builds vollständig eliminiert, was die Build-Zeit großer Repositories (800+ Seiten) von ~18 Sekunden auf nur noch ~3,5 Sekunden senkt. - **Entkoppelte API-Importe**: Plugins können nun `fsUtils`, `WorkerPool` und `getGitRoot` direkt von `@docmd/utils` importieren. ### ⚙️ Infrastruktur & Tools - **Zentralisierter Git-Kontext**: Die interne Git-Zweig-Erkennung und das Parsen des Repository-Stammverzeichnisses (`getGitRoot`) wurden in einen sicheren Hilfsbereich extrahiert. - **JSON-serialisierbare Konfigurationen**: Kontinuierlicher Übergang zur Zero-Config-Architektur durch Sicherstellung, dass das aufgelöste Konfigurationsobjekt vollständig JSON-serialisierbar ist, sodass es sicher in die Worker-Threads übertragen werden kann. ## ⚠️ Wichtige (Breaking) Änderungen - **Kern-Modul-Importe**: Wenn sich Ihre benutzerdefinierten Plugins auf tiefe relative Importe von `@docmd/core/src/utils/fs-utils` verlassen haben, müssen Sie diese Importe auf `@docmd/utils` aktualisieren. - **Worker-Ausführungskontext**: Plugins, die sich in das `markdownSetup` einklinken, müssen sicherstellen, dass ihre Erweiterungen vollständig serialisierbar sind, da Markdown-it-Prozessoren jetzt über Thread-Grenzen hinweg instanziiert werden. ## Upgrade-Anleitung Führen Sie ein Upgrade durch, indem Sie `npm install docmd@latest` ausführen. Dann: 1. **Testen Sie Ihre benutzerdefinierten Plugins**: Wenn Sie ein benutzerdefiniertes docmd-Plugin pflegen, das AST manipuliert oder viel CPU-Zeit benötigt, prüfen Sie, ob Sie die neue `runWorkerTask` nutzen können, um die Build-Schleife schnell zu halten. 2. **Entfernen Sie manuelle Kern-Importe**: Ersetzen Sie `import { fsUtils } from '@docmd/core/dist/utils/fs-utils'` durch `import { fsUtils } from '@docmd/utils'`. Eine vollständige Anleitung finden Sie unter [Erste Schritte - Installation](../getting-started/installation). --- ## [docmd v0.8.1 - Engine-Architektur & Git-Cache-Fixes](https://docs.docmd.io/de/release-notes/0-8-1/) --- title: "docmd v0.8.1 - Engine-Architektur & Git-Cache-Fixes" description: "Steckbare Engine-Architektur (Vorschau), persistente Git-Indizierung, Navigations-Fixes und Standardisierung der JSON-Konfiguration." --- ::: callout danger **Diese Version ist veraltet.** Version 0.8.1 enthält einen Paketierungsfehler, der dazu führt, dass `npm install` mit einem `EUNSUPPORTEDPROTOCOL`-Fehler fehlschlägt. Alle Änderungen und Fixes wurden in [v0.8.2](./0-8-2.md) übernommen. Bitte aktualisieren Sie sofort. ::: docmd v0.8.1 führt eine steckbare Engine-Architektur, wesentliche Verbesserungen bei der Performance der Git-Indizierung und wichtige Fixes für das SPA-Routing ein. ## ✨ Highlights ### Steckbare Engine-Architektur (Vorschau) docmd unterstützt jetzt ein steckbares Engine-System. Das neue Paket `@docmd/engine-rust` bietet die Grundlage für beschleunigte I/O-Operationen und ist so konzipiert, dass es reibungslos mit vorhandenen Plugins zusammenarbeitet. ```json { "engine": "rust" } ``` Die Engine ist **optional** – die standardmäßige JavaScript-Engine verarbeitet weiterhin alle Workloads. Die Rust-Engine bietet spürbare Vorteile bei großen Repositories (mehr als 1.000 Dateien), bei denen die Git-Indizierung und Batch-Dateioperationen die Build-Zeit dominieren. **Architektur-Highlights:** - **Steckbares Design**: Engines sind Pakete unter `@docmd/engine-*` und folgen demselben Muster wie Plugins. - **Integrierte vorkompilierte Binärdateien**: Alle unterstützten Plattform-Binärdateien werden nun über ein einziges, zentralisiertes Paket `@docmd/engine-rust-binaries` bereitgestellt. - **Lazy Loading**: Native Binärdateien werden erst geladen, wenn die Engine explizit ausgewählt wird. - **Plugin-kompatibel**: Plugins können die Engine-API für beschleunigte I/O-Operationen nutzen. - **Automatischer Fallback**: Wenn die native Binärdatei nicht verfügbar ist, übernimmt die JS-Engine transparent. **Verfügbare Engine-Pakete:** | Paket | Beschreibung | | :--- | :--- | | `@docmd/engine-js` | Standard-JavaScript-Engine (immer verfügbar) | | `@docmd/engine-rust` | Rust-Engine-Loader (orcheststriert native Beschleunigung) | | `@docmd/engine-rust-binaries` | Zentralisierte native Binärdateien für alle Plattformen | ::: callout info "Vorschau-Status & Plattform-Unterstützung" Die Rust-Engine befindet sich in der Vorschau. Bei der ersten **Einführung in v0.8.1** sind vorkompilierte native Binärdateien im Binärpaket exklusiv für **macOS-ARM64 (Apple Silicon)**-Plattformen enthalten. Builds auf anderen Architekturen weichen automatisch auf die hochperformante JS-Engine aus. Interne Benchmarks zeigen eine **Verbesserung von ca. 25 % bei Kaltstarts** und **ca. 17 % bei Warmstarts** für ein 886-seitiges Workspace-Projekt. ::: ### Git-Indizierung: Persistenter Festplatten-Cache Das Git-Plugin **speichert Indizierungsergebnisse nun über Builds hinweg auf der Festplatte**. Zuvor wurden Git-Metadaten bei jedem Build von Grund auf neu indiziert – selbst wenn sich keine Dateien geändert hatten. Das neue Cache-System: - Leitet die Cache-Speicherung sauber in das isolierte temporäre Verzeichnis Ihres Betriebssystems (`os.tmpdir()`) um, um eine Überfrachtung des Projektverzeichnisses zu verhindern. - Sichert den Cache-Abruf über Verzeichnisumbenennungen oder -verschiebungen hinweg, indem ein zuverlässiger Hash generiert wird, der an die Git-Tracking-URL Ihres Repositories oder eindeutige OS-Inode-Identifikatoren gebunden ist. - Unterstützt konfigurierbare Speicherpfade über den neuen Konfigurationsparameter `tmp`. - Funktioniert mit **beiden** Engine-Pfaden (Rust und JS) und dem `execFile`-Fallback. - Bietet **ca. 45 % schnellere Warmstarts** auf der offiziellen Dokumentations-Website (886 Seiten). ### Konfigurierbares `tmp`-Verzeichnis Standardmäßig leitet docmd den internen Zustand und Build-Caches in den isolierten temporären Ordner Ihres Systems um, um Ihr Projektverzeichnis sauber zu halten. Für Umgebungen, die ein persistentes Caching an bestimmten Orten erfordern (z. B. CI/CD-Pipelines mit Cache-Key-Anforderungen), können Sie den Pfad nun mit dem Schlüssel `tmp` konfigurieren: ```json { "src": ".", "out": "site", "tmp": ".docmd-cache" } ``` Dadurch können Sie den `.docmd/`-Zustandsordner in jedem beliebigen Verzeichnis verankern, sodass er über Build-Sitzungen hinweg problemlos gecached und wiederhergestellt werden kann. ### JSON-Konfigurationsstandard Beginnend mit v0.8.0 ist `docmd.config.json` das empfohlene Konfigurationsformat. Alle Dokumentationen der v0.8 wurden auf JSON-Beispiele aktualisiert. Die Formate `.js` und `.ts` werden weiterhin als Fallbacks für dynamische Konfigurationslogiken vollständig unterstützt. ## 🐛 Fehlerbehebungen ### Externe Links in der SPA-Navigation Es wurde ein Problem behoben, bei dem externe Links in der `navigation.json` mit `external: true` fälschlicherweise als relative Pfade aufgelöst wurden, nachdem über den SPA-Router auf eine andere interne Seite navigiert wurde. Die Links behalten nun ihre absoluten URLs bei. ### Kurzschreibweise für externe Navigationslinks Das Präfix `external:`, das zuvor nur in Markdown-Inhalten verfügbar war, funktioniert nun auch in der `navigation.json` als praktische Kurzschreibweise: ```json [ { "title": "GitHub", "path": "external:https://github.com/docmd-io/docmd" } ] ``` Dies entspricht: ```json [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ### Git-Cache-Verzeichnis-Stabilität & -Verlagerung Es wurde ein Fehler behoben, bei dem der Cache des Git-Plugins während Workspace-Builds in wechselnde Verzeichnisse geschrieben wurde. Der Cache wurde sauber aus dem Projektverzeichnis direkt in `os.tmpdir()` verlagert. Er verwendet nun einen persistenten Repository-Identifikator und unterstützt den benutzerdefinierten Parameter `tmp`. ### Engine-Konfiguration wird beachtet Das Git-Plugin beachtet nun den Konfigurationsschlüssel `engine`. Zuvor wurde unabhängig von der Konfiguration immer versucht, zuerst die Rust-Engine zu laden. Das Setzen von `"engine": "js"` erzwingt nun korrekt die JavaScript-Engine. ## 📝 Vollständiger Changelog ### 🚀 Engine & Architektur - **Steckbares Engine-System**: Neues `Engine`-Interface in `@docmd/api` zur Build-Beschleunigung. - **JS-Engine-Paket**: Standard-Engine ausgelagert in das Paket `@docmd/engine-js`. - **Rust-Engine-Ecosystem**: Native Rust-Beschleunigung mit zentraler Binärverteilung über `@docmd/engine-rust-binaries`. - **Engine-Loader-API**: `loadEngine()` und `registerEngine()` für die Registrierung benutzerdefinierter Engines. - **Engine-Konfigurationsschlüssel**: Neuer Schlüssel `engine` in der `docmd.config.json` zur Auswahl der Build-Engine. - **Engine-Hervorhebung**: Erhöhte Protokollierungshervorhebung für benutzerdefinierte Build-Engines in TUI-Layouts. ### ⚡ Performance - **Git-Festplatten-Cache**: Ergebnisse werden für Warmstarts auf der Festplatte gespeichert. - **Persistente Identifikation**: Dual-Mode-Cache-Identifikation über Git-Remote-URL-Hashing und OS-Inode-Fallback. - **Konfigurierbarer Speicher**: Unterstützung für das Überschreiben des Cache-Ziels über den Parameter `tmp`. - **Konfigurations-Resolver**: Automatische Erkennungsunterstützung für Standard-JSON-Konfigurationsdateien in Workspace-Subprojekten. - **Festplatten-Cache-Vorwärmung**: Build-Pipeline liest den Festplatten-Cache vor Engine- oder Subprozessaufrufen. ### 🐛 Fehlerbehebungen - **SPA-Router**: Externe Links in der Seitenleiste bleiben bei clientseitiger Navigation korrekt erhalten. - **Navigationskonfiguration**: Das Präfix `external:` wird nun als Kurzschreibweise in der `navigation.json` unterstützt. - **Linkauflösung**: URL-Auflösungsfehler für protokollrelative URLs behoben. - **Git-Plugin**: Beachtet nun den Konfigurationsschlüssel `engine` statt standardmäßig immer Rust zu laden. - **Workspace-Cache**: Zustandsordner in deterministische temporäre OS-Strukturen verlagert, um Verluste zu vermeiden. --- ## [docmd v0.8.2 - Patch-Release](https://docs.docmd.io/de/release-notes/0-8-2/) --- title: "docmd v0.8.2 - Patch-Release" description: "Fehlerhafte Protokollabhängigkeiten behoben und Release-Automatisierung aktualisiert." --- Dies ist ein kritisches Patch-Release, das Installationsprobleme für Benutzer von `npm` behebt und die interne Abhängigkeitsauflösung des Monorepos standardisiert. ### 🚀 Highlights #### Kompatibilität von `npm install` behoben Es wurde ein kritisches Problem behoben, bei dem auf der NPM-Registry veröffentlichte Pakete unaufgelöste `workspace:`-Protokollreferenzen in ihren `optionalDependencies` enthielten. Dies führte dazu, dass `npm install` mit einem `EUNSUPPORTEDPROTOCOL`-Fehler fehlschlug. Die Publishing-Pipeline wurde aktualisiert, um sicherzustellen, dass alle Abhängigkeitstypen korrekt in SemVer-Bereiche aufgelöst werden. ### 🛠 Verbesserungen & Fixes - **Publishing-Pipeline**: `scripts/resolve-ws-deps.js` wurde korrigiert, um `optionalDependencies` während des Release-Prozesses korrekt zu transformieren. - **Standardisierung der Abhängigkeiten**: Alle internen Paket-Referenzen wurden aktualisiert, um Konsistenz im gesamten Ökosystem sicherzustellen. - **Workflow-Optimierung**: GitHub Actions wurden aktualisiert, um stabile Runner-Konfigurationen für eine zuverlässige Binärgenerierung zu verwenden. ### 📦 Paket-Updates Alle Pakete im `@docmd`-Ökosystem wurden auf `v0.8.2` angehoben, um vollständige Kompatibilität und eine einheitliche Versionierung zu gewährleisten. Für eine vollständige Liste der in der v0.8-Serie eingeführten architektonischen Änderungen verweisen wir auf die [v0.8.1 Release Notes](./0-8-1.md). --- ## [docmd v0.8.3 - Workspaces & Erhöhte Sicherheit](https://docs.docmd.io/de/release-notes/0-8-3/) --- title: "docmd v0.8.3 - Workspaces & Erhöhte Sicherheit" description: "Einführung der neuen Workspace-Architektur mit Konfigurationsvererbung, einem erstklassigen Projekt-Switcher und erheblicher Sicherheitsoptimierung." --- docmd v0.8.3 ist ein umfassendes architektonisches Update, das **Workspaces** einführt und so die zentralisierte Verwaltung mehrerer Dokumentationsprojekte ermöglicht. Dieses Release setzt außerdem Prioritäten bei **Sicherheit & Stabilität** mit einem gehärteten Rendering im gesamten Ökosystem und verbesserter Routing-Zuverlässigkeit. ### ✨ Highlights #### 🚀 Workspaces-Architektur Das Multi-Projekt-System wurde als **Workspaces** völlig neu konzipiert. Sie können nun mehrere unabhängige Dokumentationsprojekte aus einer einzigen Root-Konfiguration mit leistungsstarken neuen Funktionen verwalten: - **Globale Konfigurationsvererbung**: Definieren Sie Ihr `theme`, Ihre `menubar`, Ihre `navigation` und Ihr `logo` im Root, um sie automatisch auf alle Projekte anzuwenden. - **Premium Projekt-Switcher**: Eine neue, schlanke UI-Komponente zur nahtlosen Navigation zwischen Projekten mit Unterstützung für mehrere Positionen (`sidebar-top`, `sidebar-bottom` und `options-menu`). - **Flexible Overrides**: Projekte können globale Standardwerte in ihrer lokalen Konfiguration selektiv überschreiben. - **Abwärtskompatibilität**: Bestehende Multi-Projekt-Konfigurationen werden automatisch in das neue Workspace-Schema überführt. #### 🛡️ Erhöhte Sicherheit & Stabilität Dieses Release führt eine Reihe interner Verbesserungen ein, um die Dokumentations-Engine und ihre Plugins gegen Rendering-Probleme in Grenzfällen zu härten: - **Gehärtetes Rendering**: Die Verwendung von `innerHTML` wurde im Core und in den Plugins systematisch durch sichere DOM-APIs (`createElement`, `DOMParser`) ersetzt. - **Universeller Sicherheitsaudit**: Die Monorepo-Failsafe-Pipeline enthält nun ein spezielles, AST-basiertes Sicherheitsaudit, um unsichere DOM-Muster (`innerHTML`, `outerHTML`, `document.write`) vor jeder Veröffentlichung zu erkennen und zu blockieren. - **Erhöhte Suchsicherheit**: Suchergebnisse verwenden nun eine zuverlässigere Rendering-Pipeline, um sicherzustellen, dass Inhalte immer sicher verarbeitet werden. - **Dev-Server-Isolation**: Verbesserter Verzeichnisdurchquerungsschutz im lokalen Entwicklungsserver für eine bessere Isolierung der Umgebung. ### 🛠 Verbesserungen & Fixes #### Normalisierung der automatisch zugewiesenen Indizes Es wurde ein Fehler im Zero-Config Auto-Router behoben, bei dem als Verzeichnisindizes zugewiesene Dateien (wenn keine `index.md` vorhanden ist) aufgrund einer Abweichung beim abschließenden Schrägstrich (Trailing Slash) nicht korrekt gerendert wurden. Die Engine normalisiert diese Pfade nun korrekt und stellt ein stabiles Routing und eine korrekte `index.html`-Generierung für alle automatisch indizierten Verzeichnisse sicher. #### Routing-Stabilität Verbesserte Pfadvorhersagbarkeit im Auto-Router, um Unstimmigkeiten bei abschließenden Schrägstrichen in Verzeichnissen ohne dedizierte Indexdatei zu beheben. #### TUI-Pipeline & Klarheit bei Workspace-Builds Verfeinerung der Terminalausgabe (TUI) für Multi-Projekt-Workspace-Builds. Build-Protokolle sind nun sowohl bei Standalone- als auch bei Workspace-Builds konsistent in strikte Abschnitte (`Data Indexing`, `Publishing` usw.) gegliedert, was überlappenden Text, endlose Ladeanimationen und unzusammenhängende Statusmeldungen verhindert. #### Anpassungen an der UI-Seitenleiste Es wurde ein Layoutfehler behoben, bei dem Dropdown-Menüs (Versions-, Sprach- und Projekt-Switcher) innerhalb der Seitenleiste durch den Begrenzungsrahmen der Seitenleiste abgeschnitten wurden. Diese Menüs werden nun sicher über dem Hauptinhaltsbereich gerendert und richten sich dynamisch an der Breite der Seitenleiste aus. ### 📦 Paket-Updates - **Node.js-Typen**: `@types/node` auf `v25.8.0` aktualisiert. - **GitHub Actions**: CI/CD-Workflows auf die neuesten stabilen Versionen aktualisiert. ### 📝 Vollständiger Changelog #### 🚀 Neue Funktionen - **Core-Engine**: `workspace`-Schema für zentralisiertes Projektmanagement eingeführt. - **UI-Komponenten**: Teilkomponente `project-switcher` und Event-Delegationslogik hinzugefügt. - **Config-Loader**: Globale Standardwertzusammenführung und Aliasing für `menubar`-Einträge (`title`/`path`) implementiert. - **Pipeline**: Statisch analysierendes Sicherheitsaudit in Universal Failsafe V5.0 integriert, um strikte DOM-Sicherheitsstandards in allen Paketen durchzusetzen. #### 🐛 Fehlerbehebungen - **Threads-Plugin**: Kommentar-Rendering und Metadaten-Escaping durch Umstellung auf DOMParser gehärtet. - **Search-Plugin**: Ergebnis-Rendering und Datenattributsicherheit verbessert, innerHTML ersetzt. - **Icon-Renderer**: Attribut-Rendering für SVG-Icons gehärtet. - **Tabs-Komponente**: Attributsicherheit in Tab-Navigationsschaltflächen verbessert. - **Core-Engine**: Pfadnormalisierung für automatisch zugewiesene Indexdateien im Generator behoben. - **Routing**: Implizite Indexzuweisung im Auto-Router entfernt, um die Pfadvorhersagbarkeit zu verbessern. - **Dev-Server**: Pfadvalidierung für statiche Dateibereitstellung verbessert. - **UI-Assets**: `overflow: hidden` aus der Seitenleiste entfernt und Positionierungskontexte überarbeitet, um abgeschnittene Dropdown-Menüs zu verhindern. - **CLI / TUI**: Hängende Statusmeldungen und ungeschlossene UI-Abschnitte bei Workspace- und Dev-Builds behoben. #### 🚀 Infrastruktur - **Refactoring**: Workspace-Engine in `workspace.ts` umbenannt und Terminologie im Monorepo vereinheitlicht. - **Abhängigkeiten**: `@types/node` von 25.7.0 auf 25.8.0 angehoben. - **Workflows**: GitHub Actions-Gruppe auf die neuesten Versionen aktualisiert. --- ## [v0.8.4 - Deployer & Sicherheit](https://docs.docmd.io/de/release-notes/0-8-4/) --- title: "v0.8.4 - Deployer & Sicherheit" description: "Release Notes für docmd v0.8.4 – modulares Deployer-Paket, Steuerung von Markdown-Zeilenumbrüchen, Sicherheitsoptimierung und Stabilitäts-Fixes." date: "2026-05-18" --- ### ✨ Highlights Diese Version führt das neue Deployer V2-System ein, zusammen mit Verbesserungen bei der Plugin-Sicherheit, der Build-Zuverlässigkeit und den Entwicklungs-Workflows. ### Bereitstellungsziele (Deployment Targets) Die Deployment-Engine wurde in ein eigenes Paket `@docmd/deployer` mit anbieterspezifischen Bereitstellungszielen ausgelagert. Sie können nun Bereitstellungsdateien direkt für GitHub Pages, Vercel und Netlify generieren: ```bash docmd deploy --github-pages docmd deploy --vercel docmd deploy --netlify ``` Generierte Dateien übernehmen automatisch Werte aus Ihrer `docmd.config.json`, einschließlich des Ausgabeverzeichnisses, der Website-URL, des SPA-Routings und der Node.js-Version. Bestehende Bereitstellungsziele für Docker, Nginx und Caddy funktionieren weiterhin unverändert. ### Markdown-Zeilenumbrüche Eine neue Option `markdown.breaks` wurde in der `docmd.config.json` hinzugefügt. Setzen Sie diese auf `false`, um automatische Zeilenumbrüche in Markdown zu deaktivieren und die Formatierung von umbrochenem Markdown beizubehalten. ```json { "markdown": { "breaks": false } } ``` ### Changelog 1. **Deployer**: Auslagerung der Deployment-Engine in `@docmd/deployer` mit nativer Unterstützung für GitHub Pages, Vercel und Netlify. 2. **Markdown-Formatierung**: Konfigurationsoption `markdown.breaks` zur Steuerung von Zeilenumbrüchen bei automatischem Zeilenumbruch (Soft-wrap) hinzugefügt (#137, #127). 3. **Sicherheit des Installers**: Plugin-Installationen wurden auf die offizielle npm-Registry beschränkt und unsichere Shell-basierte Ausführungspfade wurden ersetzt. 4. **Threads-Plugin**: Deaktivierung des rohen HTML-Renderings in Thread-Kommentaren unter Beibehaltung der standardmäßigen Markdown-Formatierung (#136). 5. **Build-Zuverlässigkeit**: Der Parser und der Build-Lebenszyklus enden nun bei Plugin-Fehlern mit Nicht-Null-Statuscodes, was das Verhalten in CI-Pipelines verbessert (#134). 6. **Entwicklererlebnis**: Reduzierung des Protokollaufkommens des Entwicklungsservers bei Hot-Reloads und Hinzufügung von `filePath`-Argumenten zu Parser-Lebenszyklus-Hooks (#135). 7. **UI-Updates**: Der Versions-Switcher wurde mit Lucide-Icons verfeinert und die Dropdown-Stile des Projekt-Switchers wurden an die Standard-Themenmenüs angepasst. 8. **Fehlerbehebungen**: Fehler bei Cache-Überlappungen beim Projektwechsel, Übersetzungsprobleme auf `noStyle`-Seiten und Hover-Zustände für das Kopieren von Code-Icons wurden behoben. ### Danke 💖 Vielen Dank an alle Mitwirkenden, Tester und Fehlerberichterstatter, die zur Verbesserung dieser Version beigetragen haben. Besonderer Dank gilt den Sicherheitsforschern für die Koordinierung verantwortungsvoller Offenlegungen. Dokumentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [v0.8.5 - Semantische Suche Alpha & SEO-Verbesserungen](https://docs.docmd.io/de/release-notes/0-8-5/) --- title: "v0.8.5 - Semantische Suche Alpha & SEO-Verbesserungen" description: "Versionshinweise für docmd v0.8.5 - Semantische Suche Alpha-Vorschau, SEO-Plugin robots.txt Auto-Generierung, Mermaid C4Context-Korrektur und Config-Upgrade-CLI." date: "2026-05-31" --- ### ✨ Highlights Dieses Release führt die semantische Suche als Alpha-Vorschau ein, fügt die automatische `robots.txt`-Generierung im SEO-Plugin hinzu, behebt das Mermaid C4Context-Rendering und enthält einen neuen Config-Upgrade-Befehl zur Modernisierung bestehender Projekte. ### Semantische Suche (Alpha-Vorschau) docmd unterstützt jetzt semantische Suche basierend auf lokalen Embeddings, die kontextbezogene Suchergebnisse über einfache Schlüsselwortsuche hinaus ermöglicht. **Funktionen** - Kontextbezogene Suche über exakte Schlüsselwortübereinstimmungen hinaus - Natürliche Fehlertoleranz bei Tippfehlern - Findet verwandte Inhalte auch bei unterschiedlicher Terminologie - Vollständig lokale Verarbeitung ohne externe Dienste oder API-Aufrufe Aktivieren Sie die semantische Suche, indem Sie `semantic: true` zu Ihrer Konfiguration hinzufügen: ```json { "plugins": { "search": { "semantic": true } } } ``` Das Search-Plugin installiert automatisch `docmd-search` und lädt erforderliche Modelle herunter. Falls dies fehlschlägt, fällt es auf die Schlüsselwortsuche zurück. **Dokumentation** - https://docs.docmd.io/plugins/search/#semantic-search-alpha-preview > **Hinweis:** Dies ist eine Alpha-Vorschau. Mehrsprachige Modelle sind verfügbar, aber umfassendere Tests und Optimierungen sind noch in Arbeit. ## Einführung der Offline-Suchmaschine (docmd-search) Wir freuen uns, **docmd-search** vorzustellen. ```bash npm install docmd-search ``` docmd-search ist eine semantische Suchmaschine für Dokumentationsseiten. Sie läuft vollständig im Browser oder CLI, erfordert keine Server oder API-Schlüssel und hält alle Verarbeitung lokal. Obwohl für docmd entwickelt, kann sie in andere Dokumentationsplattformen, Websites und Webanwendungen integriert werden. Dies ist eine frühe Alpha-Version und wird sich weiterentwickeln, aber die Grundlage ist bereits gelegt. **GitHub:** https://github.com/docmd-io/docmd-search **Dokumentation:** https://docs.docmd.io/search/ ## SEO-Plugin: robots.txt Auto-Generierung Das SEO-Plugin generiert jetzt automatisch eine `robots.txt`-Datei während des Build-Prozesses, falls noch keine existiert. **Funktionen** - Intelligente Standardwerte mit `User-agent: *` und `Allow: /` - Automatische sitemap-Referenzen wenn `config.url` konfiguriert ist - Optionale AI-Crawler-Kontrollen - Bestehende `robots.txt`-Dateien werden niemals überschrieben ```json { "plugins": { "seo": { "aiBots": false } } } ``` Standardmäßig sind AI-Crawler erlaubt. Das Setzen von `aiBots: false` fügt Direktiven für GPTBot, ChatGPT-User, Google-Extended, CCBot und andere unterstützte AI-Crawler hinzu. ## Mermaid C4Context Korrektur C4Context-Diagramme werden jetzt korrekt gerendert anstatt als leere weiße Boxen angezeigt. Das Problem wurde durch einen fehlenden SVG-Namespace verursacht, der von Mermaid beim Rendern von C4Context-Diagrammen generiert wird. docmd injiziert jetzt automatisch den erforderlichen Namespace vor dem Parsen, wodurch diese Diagramme korrekt gerendert werden. Danke an @sinsombat für die Korrektur und die begleitende Test-Suite. ## Config-Upgrade-Befehl Ein neues `--upgrade`-Flag wurde zum `docmd migrate`-Befehl hinzugefügt. ```bash npx @docmd/core migrate --upgrade ``` Das Ausführen des Befehls aktualisiert automatisch ältere Konfigurationsdateien auf das moderne Schema. Die folgenden Legacy-Schlüssel werden automatisch migriert: | Legacy-Schlüssel | Moderner Schlüssel | |------------------|---------------------| | `projects` | `workspace.projects` | | `siteTitle` | `title` | | `siteUrl` / `baseUrl` | `url` | | `srcDir` / `source` | `src` | | `outputDir` | `out` | | `defaultLocale` | `i18n.default` | Bestehende Werte werden während der Migration beibehalten. ## TOC-HTML-Entitätsdekodierung Überschriftentexte mit Sonderzeichen wie `<`, `>`, `&` und intelligenten Anführungszeichen werden jetzt in der Inhaltsverzeichnis-Seitenleiste korrekt angezeigt. Zunächst wurden diese Zeichen als rohe HTML-Entitäten statt ihrer beabsichtigten Darstellung angezeigt. ## Änderungsprotokoll ### Neue Funktionen 1. Alpha-Vorschau-Unterstützung für semantische Suche via `docmd-search` hinzugefügt. 2. Automatische `robots.txt`-Generierung zum SEO-Plugin hinzugefügt. 3. `search.showFilters` hinzugefügt, um die Versionsfilterleiste über den Suchergebnissen auszublenden. 4. `search.showConfidence` hinzugefügt, um semantische Suchkonfidenz-Prozentwerte anzuzeigen. 5. Rechtsbündige Metadaten für Suchergebnisse für Versionen und Konfidenz-Badges hinzugefügt. ### Fehlerkorrekturen 1. Mermaid C4Context-Diagramme, die als leere weiße Boxen gerendert wurden, behoben. 2. Live-Editor-Template-Rendering-Absturz verursacht durch frühzeitigen `workspace`-Zugriff behoben. 3. HTML-Entitätsdekodierung im Inhaltsverzeichnis behoben. 4. Übermäßige Dev-Server-Neuladungen durch doppelte `fs.watch`-Ereignisse auf macOS behoben. ### Verbesserungen 1. `docmd migrate --upgrade` für automatisierte Konfigurationsmodernisierung hinzugefügt. 2. Projekt-Switcher umgestaltet, um mit dem Erscheinungsbild und den Sprachsteuerungen übereinzustimmen. 3. Konfigurations- und `navigation.json`-Änderungen lösen jetzt schnelle gezielte Rebuilds statt vollständige Neustarts aus. 4. Der Dev-Server öffnet jetzt automatisch die Dokumentations-URL im Standardbrowser beim Start. ### Danke 💖 Danke an alle Mitwirkenden, Tester und Problem-Reporter, die diesen Release verbessert haben. Dokumentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [v0.8.6 - KI-First-Integration, MCP & Docker](https://docs.docmd.io/de/release-notes/0-8-6/) --- title: "v0.8.6 - KI-First-Integration, MCP & Docker" description: "Versionshinweise für docmd v0.8.6 - nativer MCP-Server, modulare Agent Skills, offizielles Docker-Image, CJK-Suche-Tokenisierung, Kopier-Widgets und TOC-Verbesserungen." date: "2026-06-05" --- ### ✨ Highlights Dieses Release etabliert docmd offiziell als erste Adresse für "KI-First"-Dokumentations-Engines. Im Mittelpunkt steht ein **nativer Model Context Protocol (MCP) Server**, der KI-Agenten die Interaktion mit Dokumentations-Arbeitsbereichen über `docmd mcp` ermöglicht. Darüber hinaus liefert diese Version ein **modulares Agenten-Skill-Set** (`docmd-skills`), ein **offizielles Docker-Image** mit Multi-Architektur-Unterstützung, clientseitige "Kopieren"-Aktionen für Markdown und strukturierte Kontexte für LLMs, eine überarbeitete Suchtokenisierung für CJK und Sprachen ohne Wort-Leerzeichen sowie wichtige Verbesserungen am Inhaltsverzeichnis (TOC). ### 🔌 Nativer Model Context Protocol (MCP) Server Sie können jetzt einen nativen MCP-Server direkt aus Ihrem Workspace heraus starten: ```bash docmd mcp ``` Der Server läuft lokal im `stdio`-Modus (Protokollversion `2025-03-26`) und ermöglicht es KI-Agenten (wie Claude Desktop, Cursor oder Windsurf), sicher auf Ihren Dokumentations-Arbeitsbereich zuzugreifen, um: - Volltext- und semantische Suchen durchzuführen (`search_docs`) - Markdown-Dateien und Konfigurationen einzulesen (`read_doc`) - Hyperlinks und relative Pfade zu validieren (`validate_docs`) - Den vereinheitlichten Repository-Kontext abzurufen (`get_llms_context`) Vollständige Protokollkonformität einschließlich `ping`-Health-Checks und `notifications/initialized`-Lebenszyklus. ### 📖 Modulares Agenten-Skill-Set (`docmd-skills`) Bei der Ausführung von `docmd init` wird eine versionskontrollierte `SKILL.md`-Datei im Projektstammverzeichnis erstellt. Das vollständige Skill-Set wird als modulare Sammlung im [`docmd-skills`](https://github.com/docmd-io/docmd-skills) Repository gepflegt: - **`cli.md`**: Einrichtung, alle CLI-Befehle mit Flags und Optionen. - **`config.md`**: Vollständiges `docmd.config.json`-Schema mit Standardwerten und Inline-Kommentaren. - **`plugins.md`**: Jedes integrierte Plugin mit allen Konfigurationsschlüsseln, Standardwerten und Verhalten. - **`plugin-development.md`**: Hook-Signaturen, Lebenszyklus, ActionContext, Anleitung zur Plugin-Erstellung. - **`formatting.md`**: Container-Syntax, Frontmatter-Referenz, Regeln für selbstschließende Elemente. - **`api.md`**: Node.js-Build-API, Browser-API, MCP-Server, URL-Hilfsfunktionen, clientseitige Events. - **`validation.md`**: Link-Prüfung und CI/CD-Integration. Alle Skill-Dateien enthalten Inline-Kommentare mit Standardwerten, Referenzlinks zur vollständigen Dokumentation und Hinweise zur `llms-full.txt`-Auffindbarkeit. ### 🐳 Offizielles Docker-Image docmd ist jetzt als offizielles Docker-Image mit Multi-Architektur-Unterstützung (`linux/amd64` und `linux/arm64`) verfügbar: ```bash docker pull ghcr.io/docmd-io/docmd:latest docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` Enthält Docker-Compose- und Kubernetes-Deployment-Beispiele, Non-Root-Sicherheit, Alpine-Linux-Basis, Health-Checks und GitHub-Actions-CI/CD-Integration. ### 🧠 KI-First-Kontext-Kopierwidgets Um das Einlesen von Dokumentationen durch KI-Assistenten zu vereinfachen, haben wir zwei neue, lokalisierte Schaltflächen neben den Breadcrumbs eingeführt: - **Markdown kopieren**: Kopiert den reinen Inhalt des Dokuments und entfernt automatisch YAML-Frontmatter-Metadaten. - **Kontext kopieren**: Kopiert strukturierten Kontext mit Seiten-URL, Titel, Tags, Version und Text. - **Lokalisierung**: Unterstützt alle 7 Hauptsprachen (`en`, `de`, `es`, `fr`, `hi`, `ja`, `zh`). ### 🔍 Suchtokenisierung für Sprachen ohne Leerzeichen (CJK, Thailändisch, Laotisch usw.) Wir haben eine Einschränkung bei der Suchindizierung in `MiniSearch` für Sprachen behoben, die keine Leerzeichen zwischen Wörtern verwenden. Ein einheitlicher `CJK_AND_SPACELESS_REGEX`-Tokenizer teilt zeichenbasierte Schriften in einzelne Zeichentoken auf und läuft symmetrisch auf dem Build-Zeit-Indexgenerator, dem Multithread-Build-Worker und dem clientseitigen Browser-Abfrage-Parser. ### 🔢 docmd-search 0.1.0-alpha.1 Dieses Release enthält docmd-search 0.1.0-alpha.1, das einen kritischen Fehler behebt, bei dem die Konfidenzprozente in den Suchergebnissen in bestimmten Grenzfällen 100% überschreiten konnten. ### 📚 Verbesserungen am Inhaltsverzeichnis (TOC) Die TOC-Komponente hat in diesem Release erhebliche Verbesserungen erhalten: H1-Überschriften werden nun ordnungsgemäß im Inhaltsverzeichnis berücksichtigt. Die TOC-Seitenleiste scrollt nun unabhängig mit automatischer Zentrierung aktiver Elemente und debounctem Smooth-Scrolling. ### Änderungsprotokoll 1. **MCP**: Native `docmd mcp`-Serverfunktionen auf Basis von lokalem stdio implementiert. 2. **MCP**: Protokoll auf `2025-03-26` aktualisiert — `ping`-Handler und `notifications/initialized`-Lebenszyklus korrigiert. 3. **MCP**: `readline`-Ausgabe-Verschmutzung behoben, die den JSON-RPC-Stream beschädigte. 4. **MCP**: Dedizierte MCP-Server-Dokumentationsseite hinzugefügt. 5. **Skills**: Agenten-Handbücher in 7 Skill-Dateien unter `docmd-skills/` modularisiert. 6. **Skills**: `api.md` und `plugin-development.md` Module hinzugefügt. 7. **Skills**: `llms-full.txt`-Auffindbarkeitshinweise und Agenten-Nutzungsanweisungen hinzugefügt. 8. **Docker**: Offizielles Docker-Image mit Multi-Architektur-Unterstützung (amd64/arm64) hinzugefügt. 9. **Docker**: Docker-Compose-, Kubernetes- und GitHub-Actions-Deployment-Beispiele hinzugefügt. 10. **Docker**: Non-Root-Sicherheit, Alpine-Basis, Health-Checks, SBOM-Attestierung. 11. **KI**: Widgets "Markdown kopieren" und "Kontext kopieren" inklusive Übersetzungen für 7 Sprachen hinzugefügt. 12. **Suche**: Einheitlicher Tokenizer für CJK, Thailändisch, Laotisch, Khmer, Burmesisch und Tibetisch in MiniSearch hinzugefügt. 13. **TOC**: Unterstützung für H1-Überschriften im Inhaltsverzeichnis hinzugefügt. 14. **TOC**: Unabhängiges Scrollen für die TOC-Seitenleiste mit `max-height`-Einschränkungen implementiert. 15. **TOC**: Automatische Zentrierung aktiver TOC-Elemente mit debounctem Smooth-Scrolling hinzugefügt. 16. **TOC**: Scroll-Spy erweitert, um H1-Überschriften neben H2-H4 zu beobachten. 17. **Parser**: Anker-Injektion für H1-Überschriften mit Permalink-Icons aktualisiert. 18. **UI**: Rendering-Probleme in der Fußzeile behoben, die durch TOC-Überlauf verursacht wurden. 19. **Suche**: Berechnung der Konfidenzprozente in docmd-search 0.1.0-alpha.1 korrigiert. 20. **UI**: Die Steps-Komponente mit präziser Ausrichtung, Hover-Effekten und leuchtenden Marken-Nodes aufgewertet. 21. **UI**: Die Changelog-Timeline für die Verwendung einer durchgehenden Rasterachse mit interaktiven, erweiterbaren Markierungen überarbeitet. 22. **UI**: Ein moderner, adaptiver radialer Halo-Effekt am oberen Rand der Inhaltsseite hinzugefügt (Hell- und Dunkelmodus). 23. **UI**: Kopier-Widgets als einheitliche, elegante segmentierte Schaltflächengruppe neu gestaltet. 24. **UI**: Ein kritischer SPA-Routing-Fehler wurde behoben, bei dem Head-Assets (Stylesheets und Symbole) bei der clientseitigen Navigation aufgrund von Verschiebungen bei der relativen Pfadauflösung dupliziert wurden. ### Danke 💖 Danke an alle Mitwirkenden und Community-Mitglieder, die Probleme gemeldet und Feedback gegeben haben. Dokumentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [Asset-Management](https://docs.docmd.io/de/theming/assets-management/) --- title: "Asset-Management" description: "Wie docmd CSS-, JavaScript- und Bild-Assets während des Build-Prozesses verarbeitet." --- `docmd` verfolgt einen "Mirror & Map"-Ansatz für Assets. Dies stellt sicher, dass Ihre lokalen Entwicklungspfade konsistent mit Ihrem Produktions-Build bleiben. ## Verzeichnisstruktur Standardmäßig sucht `docmd` nach einem `assets/`-Ordner in Ihrem Projekt-Root. ```bash my-docs/ ├── assets/ # Quell-Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Inhalt ├── docmd.config.json └── site/ # Build-Output (automatisch gespiegelt) ``` ## Automatisches Kopieren Wenn Sie `docmd build` oder `docmd dev` ausführen: 1. **Die Spiegelungs-Logik**: Der gesamte Inhalt Ihres `assets/`-Ordners wird rekursiv nach `site/assets/` kopiert. 2. **Stabilität**: Wir verwenden eine gehärtete Kopier-Engine mit automatischen Wiederholungsversuchen, um "File Busy"- oder "ENOENT"-Fehler auf macOS und modernen SSDs zu vermeiden. 3. **Referenzierung**: Sie sollten Assets in Ihrem Markdown oder in der Konfiguration immer über den **root-relativen** Pfad referenzieren: ```markdown ![Logo](/assets/images/logo.png) ``` ## Integration von benutzerdefiniertem CSS & JS Um Ihre Assets auf jeder Seite einzubinden, fügen Sie sie Ihrer Theme-Konfiguration hinzu: ```json { "theme": { "customCss": ["/assets/css/branding.css"] }, "customJs": ["/assets/js/utils.js"] } ``` ::: callout info "KI-Erkennungsstrategie :robot:" * **Nach Typ organisieren**: Halten Sie `/css`, `/js` und `/images` getrennt. Dies hilft KI-Agenten, relevante Stile oder Skripte sofort zu finden, wenn Sie sie bitten, "die Farbe des Headers zu ändern". * **Beschreibende Dateinamen verwenden**: Die Benennung eines Bildes als `authentication-flow-diagram.png` bietet dem `llms.txt`-Crawler viel mehr Kontext als `img_01.png`. ::: --- ## [Verfügbare Themes](https://docs.docmd.io/de/theming/available-themes/) --- title: "Verfügbare Themes" description: "Entdecken Sie die integrierten Themes von docmd, darunter Sky, Ruby und Retro. Erfahren Sie, wie Sie Themes mit einer einzigen Konfigurationszeile wechseln." --- `docmd` bietet eine Reihe von professionell gestalteten Themes mit responsivem Light/Dark-Mode. Sie können die gesamte Ästhetik Ihrer Website durch Ändern eines einzigen Schlüssels in der `docmd.config.json` anpassen. ## So wechseln Sie Themes ```json { "theme": { "name": "sky", "appearance": "system" } } ``` ## Galerie der integrierten Themes | Theme | Bestens geeignet für | Vibe | | :--- | :--- | :--- | | `default` | Schlichte Dokumentation | Sauber, leichtgewichtig, neutral | | `sky` | Produktdokumentation | Modern, hochwertig, Standard | | `ruby` | Markenidentität | Anspruchsvoll, Serif-Header, lebendig | | `retro` | Entwickler-Tools | 80er-Jahre-Terminals, Monospace, Neon-Akzente | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` Genau das Theme, das für diese Dokumentationsseite verwendet wird. Nutzen Sie dieses, wenn Sie umfangreiches benutzerdefiniertes CSS hinzufügen möchten und keine störenden integrierten Designschichten wünschen. ### 2. `sky` Der Goldstandard für moderne Dokumentation. Es bietet klare Typografie, subtile Übergänge und kontrastreiche Light/Dark-Modi, die zu modernen SaaS-Plattformen passen. ### 3. `ruby` Ein hochelegantes Theme mit Serif-Typografie für Überschriften und einer tiefen, juwelenfarbenen Farbpalette. Perfekt für Dokumentationen, die autoritär und hochwertig wirken sollen. ### 4. `retro` Ein von Nostalgie geprägtes Theme, inspiriert von klassischem Computing. Zu den Merkmalen gehören phosphorgrüner Text auf schwarzem Hintergrund (im Dark Mode), Scanline-Effekte und Monospace-Schriftarten wie Fira Code als Standard. ## Theme-Architektur 1. **CSS-Layering**: Themes sind additiv. Die Wahl von `sky` lädt tatsächlich die Basisstile von `default` und legt dann die `sky`-Ästhetik darüber. 2. **Nativer Dark-Mode**: Jedes Theme enthält eine erstklassige Dark-Mode-Implementierung. 3. **Kein Refresh**: Wenn Benutzer Themes über die UI wechseln, aktualisiert die SPA-Engine die `--docmd-primary`-Variablen sofort ohne Neuladen der Seite. ::: callout tip Wenn Sie Ihr Dokumentationslayout einem KI-Entwickler-Tool beschreiben, hilft die Erwähnung Ihres Themes (z. B. "Ich verwende das `retro`-Theme") dem Modell, benutzerdefinierte CSS-Überschreibungen vorzuschlagen, die zum Variablenschema dieses spezifischen Themes passen. ::: --- ## [Eigene Styles & Skripte](https://docs.docmd.io/de/theming/custom-css-js/) --- title: "Eigene Styles & Skripte" description: "Fügen Sie Ihre eigenen CSS- und JS-Dateien hinzu, um die Funktionalität und das Branding von docmd zu erweitern." --- Obwohl `docmd`-Themes hochflexibel sind, möchten Sie möglicherweise Ihre eigenen Stylesheets oder interaktiven Skripte einbinden. Dies geschieht über die Arrays `theme.customCss` und `customJs` in Ihrer Konfiguration. ## Eigenes CSS Verwenden Sie `theme.customCss`, um bestehende Styles zu überschreiben oder neue hinzuzufügen. ```json { "theme": { "customCss": [ "/assets/css/branding.css" ] } } ``` ### Funktionsweise 1. Platzieren Sie Ihre CSS-Datei in den Assets-Ordner Ihres Projekts (z. B. `docs/assets/css/branding.css`). 2. `docmd` kopiert diese automatisch in den Build-Ordner und fügt ein `<link>`-Tag in jede Seite ein. 3. Eigenes CSS wird **nach** den Theme-Styles geladen, wodurch Ihre Überschreibungen Vorrang haben. ## Eigenes JavaScript Verwenden Sie das übergeordnete `customJs`-Array für Skripte, die Verhalten hinzufügen oder Dienste von Drittanbietern integrieren. ```json { "customJs": [ "/assets/js/feedback-widget.js" ] } ``` ### Beachtung des Lebenszyklus Skripte werden am Ende des `<body>`-Tags eingefügt. Da `docmd` eine **Single Page Application (SPA)** ist, denken Sie daran: * Die Seite wird beim Navigieren zwischen Links nicht vollständig neu geladen. * Möglicherweise müssen Sie auf benutzerdefinierte Lebenszyklus-Ereignisse hören, um Ihre Skripte auf neuen Seiten neu zu initialisieren. Die vollständige Liste der Ereignisse und Anwendungsbeispiele finden Sie unter [Client-Side Events](../api/client-side-events). ::: callout tip Das Hinzufügen von eigenem CSS und JS ermöglicht es KI-Modellen (wie ChatGPT), maßgeschneiderte UI-Verbesserungen vorzuschlagen. Wenn Sie erwähnen: „Ich habe eine eigene `branding.css`-Datei“, kann das Modell spezifische Selektoren liefern, die nicht mit der `docmd`-Kern-Engine kollidieren. ::: --- ## [Anpassung & Variablen](https://docs.docmd.io/de/theming/customisation/) --- title: "Anpassung & Variablen" description: "Eine vollständige Referenz der CSS-Variablen und Komponentonklassen von docmd für fortgeschrittenes Styling." --- `docmd` basiert auf einer CSS-Variablen-Architektur. Das bedeutet, dass Sie Ihre gesamte Website neu gestalten können, indem Sie einfach ein paar Schlüssel in einem `:root`-Block überschreiben, ohne komplexe CSS-Selektoren schreiben zu müssen. ## Referenz der globalen Variablen | Variable | Standard (Hell) | Standard (Dunkel) | Beschreibung | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | Hintergrund der Hauptseite. | | `--text-color` | `#3f3f46` | `#a1a1aa` | Standardfließtext. | | `--text-heading` | `#09090b` | `#fafafa` | Farben für Titel und Überschriften. | | `--link-color` | `#068ad5` | `#068ad5` | Primäre Akzentfarbe / Links. | | `--border-color` | `#e4e4e7` | `#27272a` | Trennlinien und Rahmen. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Hintergrund der Navigation. | | `--ui-border-radius` | `6px` | `6px` | Rundung für alle UI-Elemente. | | `--sidebar-width` | `260px` | `260px` | Breite der Seitenleiste. | ## Beispiel für eine Überschreibung Um die primäre Akzentfarbe Ihrer Website zu ändern, fügen Sie dies zu Ihrem `customCss` hinzu: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Ansprechen von Komponenten Wenn Sie bestimmte Komponenten stylen möchten, verwenden Sie diese übergeordneten Klassen: * `.main-content`: Der Wrapper für alle Markdown-Inhalte. * `.sidebar-nav`: Die interne Navigationsliste. * `.page-header`: Die obere Navigationsleiste. * `.docmd-search-modal`: Das Such-Overlay. * `.docmd-tabs`: Komponenten des Tab-Containers. * `.callout`: Die Hinweis- und Warnungsboxen. ## Fehlerbehebung bei der Selektivität (Specificity) Die meisten `docmd`-Styles verwenden eine niedrige Selektivität. Wenn Ihre Überschreibungen nicht übernommen werden, stellen Sie sicher, dass Ihr `customCss` korrekt registriert ist und prüfen Sie, ob das Hinzufügen eines `body`-Präfixes (z. B. `body .main-content`) hilft. ::: callout tip Da `docmd` Standard-CSS-Variablen verwendet, können Sie eine KI fragen: *"Gib mir eine professionelle Farbpalette mit --link-color und --bg-color für docmd"*. Das Modell wird in der Lage sein, sofort kopierbares CSS bereitzustellen, das sich perfekt in die integrierten Themes integriert. ::: --- ## [Icons](https://docs.docmd.io/de/theming/icons/) --- title: "Icons" description: "So verwenden und passen Sie Lucide-Icons in Ihrer Dokumentation an." --- `docmd` verfügt über integrierte Unterstützung für die [Lucide](external:https://lucide.dev/)-Icon-Bibliothek. Icons können in Ihrer Navigations-Seitenleiste, in Buttons und in benutzerdefinierten Komponenten verwendet werden, um visuelle Hinweise zu geben und die Scannbarkeit zu verbessern. ## Navigations-Icons Weisen Sie jedem Navigationselement in Ihrer `docmd.config.json` ein Icon zu. Verwenden Sie den Kebab-Case-Namen eines beliebigen Icons, das Sie auf der Lucide-Website finden. ```json { "navigation": [ { "title": "Home", "path": "/", "icon": "home" }, { "title": "Setup", "path": "/setup", "icon": "settings" } ] } ``` ## Icons in Containern Sie können Icons auch innerhalb Ihrer Buttons, Tags, Tabs und anderen Containern verwenden, indem Sie den rohen HTML-Code einbinden oder das standardmäßige `icon:`-Präfix in docmd nutzen. ```markdown ::: button "Download" /download icon:download ``` ## CSS-Styling Alle Icons werden als Inline-SVGs mit der Klasse `.lucide-icon` gerendert. Sie können deren Größe oder Linienstärke global in Ihrem `customCss` ändern: ```css .lucide-icon { stroke-width: 1.5px; /* Dünnere Icons für einen modernen Look */ width: 1.2rem; height: 1.2rem; } /* Gezielte Anpassung eines Icons */ .icon-rocket { color: #ff5733; } ``` ## Icon-Referenz Wir unterstützen die gesamte Lucide-Bibliothek. Sie können die Tausenden von verfügbaren Icons hier durchsuchen: ::: button "Lucide-Icons durchsuchen" external:https://lucide.dev/icons icon:globe --- ## [Hell- & Dunkelmodus](https://docs.docmd.io/de/theming/light-dark-mode/) --- title: "Hell- & Dunkelmodus" description: "So konfigurieren Sie den Standard-Ansichtsmodus und verwalten den Theme-Umschalter für die beste Benutzererfahrung." --- `docmd` bietet integrierte Unterstützung für helle und dunkle Farbschemata. Es erkennt automatisch die Systemeinstellungen der Benutzer und ermöglicht manuelle Überschreibungen über einen UI-Umschalter. ## Standard-Ansichtsmodus Sie legen den Anfangszustand Ihrer Dokumentation in der `docmd.config.json` fest. ```json { "theme": { "name": "sky", "appearance": "system" } } ``` * **`system`**: Entspricht der Betriebssystem-Präferenz des Benutzers (Empfohlen). * **`light`**: Erzwingt den Hellmodus beim ersten Laden. * **`dark`**: Erzwingt den Dunkelmodus beim ersten Laden. ## Konfiguration der Umschalt-Schaltfläche Der Theme-Umschalter ist Teil des **Optionsmenüs**. Sie können dessen Sichtbarkeit und Position innerhalb des `layout`-Objekts steuern. ```json { "layout": { "optionsMenu": { "position": "header", "components": { "themeSwitch": true } } } } ``` ## Funktionsweise (Technisch) Die Theme-Engine wendet ein `data-theme`-Attribut auf das `<body>`-Tag an: * `<body data-theme="light">` * `<body data-theme="dark">` Wenn Sie ein themenbasiertes Design wie `sky` verwenden, lautet das Attribut `sky-light` oder `sky-dark`. ### CSS-Variablen `docmd`-Themes verwenden CSS-Variablen für alle Farben. Sie können diese Variablen in Ihrem eigenen CSS überschreiben, um das Aussehen beider Modi anzupassen. ```css /* Benutzerdefinierte CSS-Überschreibung */ :root { --docmd-primary: #4f46e5; /* Primärer Akzent für Hellmodus */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* Primärer Akzent für Dunkelmodus */ } ``` ## Benutzer-Persistenz Wenn ein Benutzer den Modus manuell umschaltet, wird seine Präferenz im `localStorage` gespeichert. `docmd` liest diesen Wert bei jedem Seitenladen sofort aus, um "Theme-Flackern" (FOUC) zu verhindern. ::: callout tip Bei der Generierung von Inhalten bevorzugen LLMs kontrastreiche Strukturen. `docmd` stellt sicher, dass Code-Snippets und Callouts in beiden Modi barrierefrei bleiben. Dies gewährleistet, dass `llms-full.txt`-Payloads als semantische Blöcke korrekt verstanden werden, unabhängig davon, welcher Modus während des Builds aktiv war. ::: --- ## [Caddy](https://docs.docmd.io/deployment/caddy/) --- title: "Caddy" description: "Deploy docmd with a production-ready Caddyfile." --- [Caddy](https://caddyserver.com/) is a modern web server that handles HTTPS provisioning and certificate renewals automatically. ## Generate a Caddyfile ```bash npx @docmd/core deploy --caddy ``` This generates a `Caddyfile` personalised to your project: - **Site address** is set to the hostname from your `url` config. Caddy automatically provisions an SSL certificate for it. It falls back to `:80` if no URL is configured. - **Root directory** uses your configured `out` directory (not hardcoded). - **SPA fallback** is only included when `layout.spa` is `true` in your config. ### What Gets Generated ```caddy docs.example.com { root * ./site file_server # SPA Routing Fallback (only when layout.spa is true) try_files {path} {path}/ /index.html # Security Headers header { X-Content-Type-Options "nosniff" X-Frame-Options "SAMEORIGIN" -Server } # Custom 404 handle_errors { rewrite * /404.html file_server } # Cache Static Assets (6 months) @static { file path *.ico *.css *.js *.gif *.jpg *.jpeg *.png *.webp *.avif *.svg *.woff *.woff2 *.eot *.ttf *.otf } header @static Cache-Control "public, max-age=15552000, immutable" } ``` When you use a real domain as the site address (e.g., `docs.example.com` instead of `:80`), Caddy automatically provisions a free SSL certificate via Let's Encrypt. Zero HTTPS configuration is needed. ## Deployment Steps 1. Build your site: `npx @docmd/core build` 2. Transfer your output folder and the generated `Caddyfile` to your server. 3. Run `caddy start` or `caddy run` in the directory containing your Caddyfile. ### Re-Generating Changed your site URL or output directory? Run `npx @docmd/core deploy --caddy` again. The engine regenerates the Caddyfile to match your current `docmd.config.json`. --- ## [Cloudflare Pages](https://docs.docmd.io/deployment/cloudflare-pages/) --- title: "Cloudflare Pages" description: "Deploy your docmd documentation to Cloudflare Pages using its global edge network. CI/CD-ready with automatic builds." --- [Cloudflare Pages](https://pages.cloudflare.com/) hosts your docmd site on Cloudflare's global edge network with zero-configuration CI/CD. Connect your repository, and every push triggers an automatic build and deployment. ## Dashboard Setup 1. Go to the [Cloudflare Dashboard](https://dash.cloudflare.com/) and navigate to **Workers & Pages → Create → Pages**. 2. Connect your git provider (GitHub or GitLab) and select your repository. 3. Configure the build settings: | Setting | Value | |---------|-------| | Framework preset | `None` | | Build command | `npx @docmd/core build` | | Build output directory | `site` | 4. Click **Save and Deploy**. Cloudflare Pages detects the static output and distributes it across its edge network automatically. ## Custom Domain Add a custom domain under **Pages → your project → Custom domains**. Cloudflare provisions an SSL certificate automatically. Set the `url` field in `docmd.config.json` to match your domain. This ensures canonical tags, sitemaps, and the LLMs plugin generate correct absolute URLs. ## CI/CD Notes Cloudflare Pages runs a fresh CI/CD build on every commit pushed to the connected branch. You do not need a separate GitHub Actions workflow. Cloudflare manages the build pipeline. ::: callout info "Why `npx @docmd/core`?" In CI/CD environments where docmd is not globally installed, `npx @docmd/core` fetches and runs the package directly. If your project lists `@docmd/core` as a `devDependency`, running `npx @docmd/core build` after `npm install` works perfectly. ::: ## SPA Routing docmd generates each page as its own `index.html`. Direct URL access works without any rewrite rules. No additional Cloudflare configuration is needed. --- ## [Deployer](https://docs.docmd.io/deployment/deployer/) --- title: "Deployer" description: "Generate provider-specific deployment configuration files from your docmd project config with a single command." --- The `deploy` command reads your `docmd.config.json` and generates deployment configuration files tailored to your exact project — output directory, site URL, SPA routing, and Node.js version are all reflected automatically. No generic templates. ## Supported Providers | Provider | Flag | Files Generated | | :------- | :--- | :-------------- | | Docker + Nginx | `--docker` | `Dockerfile`, `.dockerignore` | | Nginx | `--nginx` | `nginx.conf` | | Caddy | `--caddy` | `Caddyfile` | | GitHub Pages | `--github-pages` | `.github/workflows/deploy.yml` | | Vercel | `--vercel` | `vercel.json` | | Netlify | `--netlify` | `netlify.toml` | ## Usage Run from your project root (where `docmd.config.json` lives): ```bash # Single provider npx @docmd/core deploy --github-pages # Multiple providers at once npx @docmd/core deploy --docker --nginx # Overwrite existing files npx @docmd/core deploy --vercel --force ``` ## What Gets Personalised The deploy command reads your configuration (or zero-config defaults) and injects: | Config Field | Used In | |:--|:--| | `title` | Comment headers in every generated file | | `out` | `COPY` paths in Dockerfile, `root` directives in Nginx/Caddy | | `url` | `server_name` in Nginx, site address in Caddy | | `layout.spa` | Controls whether SPA routing fallback is included | | Config path | Dockerfile build step uses `--config` when non-default | No `docmd.config.json`? No problem. The command uses the same zero-config defaults as `npx @docmd/core dev` and `npx @docmd/core build`. ## Always In Sync Every run regenerates your deployment files to match your current config. Changed your site URL or output directory? Just re-run the deploy command. Use `--force` to overwrite existing files without prompts. ## Provider Details ### GitHub Pages ```bash npx @docmd/core deploy --github-pages ``` Generates `.github/workflows/deploy.yml` with a complete build-and-deploy pipeline. The workflow checks out your repository, installs Node.js, runs `npx @docmd/core build`, and uploads the output to GitHub Pages. ::: callout tip "Using the GitHub Action instead?" If you want to deploy to GitHub Pages without generating a workflow file yourself, use the [GitHub Action](./github-action) directly — it handles everything in one composable step. ::: ### Docker ```bash npx @docmd/core deploy --docker ``` Generates a `Dockerfile` using a multi-stage build: 1. **Build stage** — installs your exact pinned `@docmd/core` version and runs the build. 2. **Serve stage** — copies the output into a minimal `nginx:alpine` image. If an `nginx.conf` already exists in your project root, the Dockerfile automatically copies it into the container. ```bash # Generate Docker and Nginx configs together npx @docmd/core deploy --docker --nginx ``` ::: callout tip "Official Docker Image" Looking to run docmd in a container without building a custom image? See the [Docker Image](./docker) page for the official pre-built image. ::: ### Nginx ```bash npx @docmd/core deploy --nginx ``` Generates `nginx.conf` with SPA routing, gzip compression, and correct `root` path for your output directory. See the [NGINX](./nginx) page for the full generated config. ### Caddy ```bash npx @docmd/core deploy --caddy ``` Generates a `Caddyfile` with automatic HTTPS, SPA routing, and file serving from your output directory. See the [Caddy](./caddy) page for the full generated config. ### Vercel ```bash npx @docmd/core deploy --vercel ``` Generates `vercel.json` with SPA routing rules and your configured output directory. See the [Vercel](./vercel) page for deployment steps. ### Netlify ```bash npx @docmd/core deploy --netlify ``` Generates `netlify.toml` with your build command, publish directory, and SPA redirect rules. See the [Netlify](./netlify) page for deployment steps. ## Trade-offs Generated configs are opinionated starting points. They are correct for the majority of docmd deployments but may require adjustments for advanced scenarios such as custom domains, CDN rewrites, or multi-region deployments. Always review generated files before deploying to production. --- ## [Docker](https://docs.docmd.io/deployment/docker/) --- title: "Docker" description: "Run docmd in a Docker container — use the official pre-built image or generate a custom Dockerfile from your project config." --- docmd generates static HTML, making it ideal for lightweight, reproducible Docker containers. There are two distinct approaches depending on your use case. ## Official Docker Image The official image lets you build and serve your documentation without installing anything locally. It supports multiple architectures (`linux/amd64` and `linux/arm64`). ### Quick Start ```bash # Pull the latest image docker pull ghcr.io/docmd-io/docmd:latest # Build your documentation (mounts local docs and outputs to ./site) docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build # Run the built-in demo site docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest ``` ### Docker Compose Use Docker Compose to build and serve in a single workflow: ```yaml version: '3.8' services: docs: image: ghcr.io/docmd-io/docmd:latest command: build volumes: - ./docs:/docs - ./site:/site - ./docmd.config.json:/docmd.config.json:ro serve: image: nginx:alpine ports: - "8080:80" volumes: - ./site:/usr/share/nginx/html:ro depends_on: - docs ``` ### Image Details | Property | Value | |:--|:--| | Base | Alpine Linux (minimal footprint) | | Security | Runs as non-root user | | Health checks | Built-in container health monitoring | | SBOM | Software Bill of Materials attestation included | | Architectures | `linux/amd64`, `linux/arm64` | ## Custom Dockerfile (via Deployer) For production self-hosting, generate a `Dockerfile` tailored to your project configuration using the [Deployer](./deployer): ```bash npx @docmd/core deploy --docker ``` This generates a `Dockerfile` using a multi-stage build: 1. **Build stage** — installs your exact pinned `@docmd/core` version and runs the build. 2. **Serve stage** — copies the output into a minimal `nginx:alpine` image. Generate both Docker and Nginx configs together for a complete self-hosted setup: ```bash npx @docmd/core deploy --docker --nginx ``` ### Build and Run ```bash docker build -t my-docs . docker run -p 8080:80 my-docs ``` Your documentation will be live at `http://localhost:8080`. ::: callout tip "Re-generating" Changed your config? Re-run `npx @docmd/core deploy --docker` to regenerate. Use `--force` to overwrite existing files. ::: --- ## [Firebase Hosting](https://docs.docmd.io/deployment/firebase/) --- title: "Firebase Hosting" description: "Deploy your docmd documentation to Firebase Hosting. Works manually or via GitHub Actions." --- [Firebase Hosting](https://firebase.google.com/products/hosting) delivers your docmd static site over a global CDN with SSL included. It integrates cleanly into CI/CD pipelines via the Firebase CLI or GitHub Actions. ## Prerequisites Install the Firebase CLI: ```bash npm install -g firebase-tools firebase login ``` ## Setup 1. Build your site: ```bash npx @docmd/core build ``` 2. Initialise Firebase Hosting in your project root: ```bash firebase init hosting ``` When prompted: - Select your Firebase project (or create a new one). - Set the **public directory** to `site`. - Configure as a single-page app: **No** (docmd generates individual `index.html` files per page. No catch-all rewrite is needed). - Do not overwrite `site/index.html`. 3. Deploy: ```bash firebase deploy --only hosting ``` ## CI/CD with GitHub Actions To deploy automatically on every push, create `.github/workflows/firebase.yml`: ```yaml name: Deploy to Firebase Hosting on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: "20" - run: npm install - run: npx @docmd/core build - uses: FirebaseExtended/action-hosting-deploy@v0 with: repoToken: ${{ secrets.GITHUB_TOKEN }} firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} channelId: live ``` Set `FIREBASE_SERVICE_ACCOUNT` in your repository's **Settings → Secrets** using a Firebase service account JSON key. ::: callout info "Why `npx @docmd/core`?" In CI/CD environments where docmd is not globally installed, `npx @docmd/core` fetches and runs the package directly. If your project lists `@docmd/core` as a `devDependency`, running `npx @docmd/core build` after `npm install` works perfectly. ::: ## Custom Domain Add a custom domain in the Firebase Console under **Hosting → Add custom domain**. Firebase provisions SSL automatically. Set the `url` field in `docmd.config.json` to match your domain. This ensures canonical tags and sitemaps generate correct absolute URLs. --- ## [GitHub Action](https://docs.docmd.io/deployment/github-action/) --- title: "GitHub Action" description: "Use the official docmd GitHub Action to build and deploy your documentation to GitHub Pages — zero config, one composable step." --- The `docmd-io/deploy` action builds your documentation site and outputs the path to the compiled assets, ready for upload to GitHub Pages or any other hosting target. It handles Node.js setup, config detection, dependency installation, and the build step in a single composable action. ::: button "View on GitHub Marketplace" external:https://github.com/marketplace/actions/build-and-deploy-documentation-with-docmd icon:github ::: button "Source Code" external:https://github.com/docmd-io/deploy icon:code ::: callout tip "Starting a new project?" Use the [Starter Template](./starter-template) — it includes a pre-configured workflow file and a ready-to-go repository structure. The GitHub Action is best for adding docmd deployment to an **existing** repository. ::: ## Quick Start Add the action to any workflow file in your repository: ```yaml # .github/workflows/docs.yml name: Deploy Docs on: push: branches: [main] permissions: contents: write pages: write id-token: write jobs: docs: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deploy.outputs.page_url }} steps: - uses: actions/checkout@v4 - uses: docmd-io/deploy@v1 id: build - uses: actions/upload-pages-artifact@v3 with: path: ${{ steps.build.outputs.site-dir }} - uses: actions/deploy-pages@v4 id: deploy ``` ## Reusable Workflow For the absolute minimum boilerplate, use the hosted reusable workflow. It handles permissions, checkout, build, upload, and deploy in one call: ```yaml # .github/workflows/docs.yml on: push: branches: [main] jobs: docs: uses: docmd-io/deploy/.github/workflows/deploy.yml@v1 ``` ## Inputs | Input | Default | Description | |-------|---------|-------------| | `node` | `20` | Node.js version to use during the build | ## Outputs | Output | Description | |--------|-------------| | `site-dir` | Relative path to the compiled site directory (e.g. `site/`) | ## What the Action Does The action runs the following steps internally: 1. **Sets up Node.js** using the specified version. 2. **Detects your config** — searches the repository tree (up to two levels deep) for `docmd.config.json`, `docmd.config.js`, or `docmd.config.ts`. Subdirectory configs are fully supported. 3. **Initialises docmd** — if no config is found, runs `npx @docmd/core init` to scaffold one automatically. 4. **Installs dependencies** — runs `npm ci` if a `package.json` is present, otherwise installs `@docmd/core` directly. 5. **Builds the site** — runs `npx @docmd/core build` and reads the output directory from your config. 6. **Outputs the path** — exposes `site-dir` so the upload step knows where to find the compiled assets. ## First-Time Setup GitHub Pages must be configured to deploy from **GitHub Actions** (not from a branch). This is a one-time step per repository: 1. Go to your repository on GitHub. 2. Navigate to **Settings → Pages**. 3. Under **Source**, select **GitHub Actions**. 4. Save. After this, every push to `main` triggers a deployment automatically. ## Nested Config Support If your `docmd.config.json` lives in a subdirectory — for example, `packages/docs/docmd.config.json` in a monorepo — the action detects it and passes `--cwd` to docmd automatically. No manual path configuration is required. ## Custom Domain To use a custom domain: 1. Add a `CNAME` file to your `docs/` directory (or your configured assets folder) containing your domain, e.g. `docs.example.com`. 2. Set the `url` field in `docmd.config.json` to your custom domain so sitemaps and canonical tags are correct. 3. Configure the domain in **Settings → Pages → Custom domain**. ## Pinning the Action Version For production documentation sites, pin to a specific release tag rather than `@v1`: ```yaml - uses: docmd-io/deploy@v1.0.0 id: build ``` This prevents unexpected behaviour from future minor updates. ## Troubleshooting **`Error: Dependencies lock file is not found`** This occurs when `actions/setup-node` is configured with `cache: 'npm'` but no `package-lock.json` exists. The `docmd-io/deploy` action handles caching internally — do not add a separate `actions/setup-node` step with `cache: 'npm'` when using this action. **Build succeeds but the site is not live** Ensure GitHub Pages is set to deploy from **GitHub Actions**, not from a branch. See [First-Time Setup](#first-time-setup) above. **Config not detected** The action searches up to two directory levels. If your config is deeper, pass `--cwd` manually in a custom workflow step or use the [Deployer](./deployer) to generate a tailored workflow file. --- ## [Deployment Overview](https://docs.docmd.io/deployment/) --- title: "Deployment Overview" description: "Choose how to deploy your docmd documentation site — from zero-config templates to self-hosted servers and cloud platforms." --- docmd builds a fully static site. The output is a self-contained folder (default: `site/`) that can be hosted anywhere — no server-side runtime required. ```bash npx @docmd/core build ``` ## Choosing a Deployment Method There are three main paths depending on your situation: | Method | Best For | |:--|:--| | [Starter Template](./starter-template) | Starting a new project from scratch | | [GitHub Action](./github-action) | Adding automated deployment to an existing repository | | [Deployer](./deployer) | Generating server configs (Docker, Nginx, Caddy, Vercel, Netlify) | ## Starter Template The fastest way to get started. Clone the official template repository — it includes a `docmd.config.json`, a sample page, and a pre-configured GitHub Actions workflow that deploys to GitHub Pages on every push. → [Starter Template](./starter-template) ## GitHub Action The `docmd-io/deploy` action builds your site and outputs the compiled path, ready for upload to GitHub Pages or any other target. Use this to add docmd deployment to an existing repository without changing your project structure. → [GitHub Action](./github-action) ## Deployer The `deploy` command reads your `docmd.config.json` and generates provider-specific configuration files tailored to your project. No generic templates — every file reflects your actual output directory, site URL, and SPA settings. ```bash # Self-hosted npx @docmd/core deploy --docker # Dockerfile + .dockerignore npx @docmd/core deploy --nginx # Production nginx.conf npx @docmd/core deploy --caddy # Production Caddyfile # Cloud / CI npx @docmd/core deploy --github-pages # GitHub Actions workflow npx @docmd/core deploy --vercel # vercel.json npx @docmd/core deploy --netlify # netlify.toml ``` → [Deployer Reference](./deployer) ## Cloud Platforms For managed hosting without running your own server: - [Docker Image](./docker) — Official multi-arch image for containerised deployments - [NGINX](./nginx) — Self-hosted with generated config - [Caddy](./caddy) — Self-hosted with automatic HTTPS - [Vercel](./vercel) — Zero-config cloud deployment - [Netlify](./netlify) — Git-connected continuous deployment - [Cloudflare Pages](./cloudflare-pages) — Edge-native hosting with built-in CI/CD - [Firebase Hosting](./firebase) — Google CDN with GitHub Actions integration ## Production Checklist 1. **Site URL** — Set `url` in `docmd.config.json`. This drives canonical tags, sitemaps, social previews, and generated deployment files. 2. **Redirects** — Migrating from another tool? Use the `redirects` config to preserve SEO rankings. 3. **Analytics** — Enable the `analytics` plugin to track engagement and search queries. 4. **AI Context** — Enable the `llms` plugin to generate `llms.txt` for AI agent ingestion. ::: callout tip "Custom 404 Pages" docmd generates a `404.html` in your output directory. Most hosting providers serve it automatically for missing routes. ::: --- ## [Netlify](https://docs.docmd.io/deployment/netlify/) --- title: "Netlify" description: "Deploy your docmd documentation to Netlify using a generated netlify.toml." --- `npx @docmd/core deploy --netlify` generates a `netlify.toml` file at the root of your project. It is pre-configured with the correct build command, publish directory, cache headers, and SPA redirects. ```bash npx @docmd/core deploy --netlify ``` ## What Gets Generated The `netlify.toml` configures: - **Build command** - installs `@docmd/core` and runs `npx @docmd/core build`. - **Publish directory** - set to your configured `out` directory. - **Node version** - pinned to Node 20. - **Cache headers** - immutable for assets, no-cache for HTML pages. - **SPA redirects** - a `/*` → `/index.html` rewrite when `layout.spa` is enabled. ## Deploying Connect your repository to Netlify from the [Netlify dashboard](external:https://app.netlify.com). It detects the `netlify.toml` automatically and deploys on every push. Alternatively, use the [Netlify CLI](external:https://docs.netlify.com/cli/get-started/): ```bash npm install -g netlify-cli netlify deploy --prod ``` ## Re-generating Re-run `npx @docmd/core deploy --netlify` any time you change `out` or other config fields. This keeps `netlify.toml` in sync. --- ## [NGINX](https://docs.docmd.io/deployment/nginx/) --- title: "NGINX" description: "Deploy docmd with a production-ready NGINX configuration." --- NGINX is one of the most reliable web servers available. Because docmd output is entirely static, NGINX can serve it with near-zero latency. ## Generate nginx.conf ```bash npx @docmd/core deploy --nginx ``` This generates an `nginx.conf` personalised to your project: - **`server_name`** is set to the hostname extracted from your `url` config. It falls back to `localhost` if not set. - **SPA fallback** (`try_files ... /index.html`) is only included when `layout.spa` is `true` in your config. - **Security headers**, GZIP compression, and immutable asset caching are included by default. ### What Gets Generated ```nginx server { listen 80; server_name docs.example.com; root /usr/share/nginx/html; index index.html; # Security server_tokens off; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; # GZIP Compression gzip on; gzip_vary on; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml; # SPA Routing Fallback (only when layout.spa is true) location / { try_files $uri $uri/ /index.html; } # Custom 404 error_page 404 /404.html; # Cache Static Assets (6 months, immutable) location ~* \.(?:ico|css|js|gif|jpe?g|png|webp|avif|woff2?|eot|ttf|otf|svg)$ { expires 6M; access_log off; add_header Cache-Control "public, immutable"; } } ``` ## Deployment Steps 1. Build your site: `npx @docmd/core build` 2. Upload the contents of your output directory to your server's web root (e.g., `/var/www/html/` or `/usr/share/nginx/html/`). 3. Place the generated `nginx.conf` into your server's configuration (e.g., `/etc/nginx/conf.d/default.conf`). 4. Restart NGINX: `sudo systemctl restart nginx` ### Re-Generating Changed your site URL or switched off SPA mode? Just run `npx @docmd/core deploy --nginx` again. The config file automatically regenerates to match your current `docmd.config.json`. --- ## [Starter Template](https://docs.docmd.io/deployment/starter-template/) --- title: "Starter Template" description: "Use the official docmd starter template to create a pre-configured documentation site with GitHub Pages deployment in under a minute." --- # docmd Starter Template The `docmd-template` repository is the fastest way to start a new documentation site. It includes a working `docmd.config.json`, a sample page, a `package.json` for local development, and a pre-configured GitHub Actions workflow that deploys to GitHub Pages automatically on every push. ::: button "Use this Template" external:https://github.com/docmd-io/docmd-template/generate icon:github color:#2ea44f ::: button "View Repository" external:https://github.com/docmd-io/docmd-template icon:external-link ## Getting Started ### 1. Create Your Repository Click **[Use this template](https://github.com/docmd-io/docmd-template/generate)** on GitHub. Give your repository a name and click **Create repository**. You do not need to fork it — the template creates a clean, independent copy. ### 2. Configure Your Site Open `docmd.config.json` in your new repository and update the `title` and `url` fields: ```json { "title": "My Docs", "url": "https://username.github.io/repo-name" } ``` Replace `username` and `repo-name` with your GitHub username and repository name. ### 3. Enable GitHub Pages This is a one-time step per repository: 1. Go to **Settings → Pages**. 2. Under **Source**, select **GitHub Actions**. 3. Save. ### 4. Push and Deploy Push any change to `main`. The included workflow builds your site and deploys it to GitHub Pages automatically. Your documentation will be live at: ``` https://<username>.github.io/<repo-name>/ ``` ## What's Included ``` .github/ workflows/ docs.yml # Automated build and deploy on push to main docmd.config.json # Site title, URL, and output directory docs/ index.md # Your first documentation page package.json # Local development scripts ``` ## Local Development Clone your repository and run the development server: ```bash npm install npm run dev ``` The site is available at `http://localhost:3000` with live reload. Changes to Markdown files are reflected immediately. To build a production copy locally: ```bash npm run build ``` The compiled site is written to `site/` by default. ## Included Workflow The template ships with `.github/workflows/docs.yml`: ```yaml name: Docs on: push: branches: [main, master] workflow_dispatch: permissions: contents: write pages: write id-token: write concurrency: group: docs cancel-in-progress: false jobs: deploy: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deploy.outputs.page_url }} steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/setup-node@v4 with: node-version: 20 - name: Install run: npm install @docmd/core - name: Build run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: path: ./site - name: Deploy id: deploy uses: actions/deploy-pages@v4 ``` The workflow installs `@docmd/core` directly without a lock file, which is intentional — the template has no committed `package-lock.json` so `actions/setup-node` caching is not used. This keeps the template dependency-free whilst still deploying reliably. ## Adding Your First Page Create a new Markdown file in `docs/`: ```bash docs/ index.md # Home page getting-started.md api-reference.md ``` Add a `navigation.json` to control the sidebar: ```json [ { "title": "Home", "path": "/" }, { "title": "Getting Started", "path": "/getting-started" }, { "title": "API Reference", "path": "/api-reference" } ] ``` See [Navigation Configuration](../configuration/navigation.md) for the full navigation schema. ## Custom Domain To use a custom domain (e.g. `docs.example.com`): 1. Update the `url` field in `docmd.config.json`: ```json { "url": "https://docs.example.com" } ``` 2. Add a `CNAME` file to your `docs/` directory containing your domain. 3. Configure the domain in **Settings → Pages → Custom domain**. ## Starter Template vs GitHub Action The template gives you full ownership of the workflow file and config from the start. The [GitHub Action](./github-action) is better suited for adding docmd deployment to an existing repository without restructuring it. | | Starter Template | GitHub Action | |---|---|---| | Starting point | New repository | Existing repository | | Workflow file | Included, yours to edit | You write it, action handles build | | Config | Pre-configured | Detected or scaffolded automatically | | Best for | New projects | Adding docs to existing repos | --- ## [Vercel](https://docs.docmd.io/deployment/vercel/) --- title: "Vercel" description: "Deploy your docmd documentation to Vercel using a generated vercel.json." --- `npx @docmd/core deploy --vercel` generates a `vercel.json` file at the root of your project. It is automatically configured for your site's output directory and SPA routing settings. ```bash npx @docmd/core deploy --vercel ``` ## What Gets Generated The `vercel.json` configures: - **Build command** - runs `npx @docmd/core build`. - **Output directory** - set to the `out` property in your config. - **Install command** - installs the exact `@docmd/core` version used. - **Cache headers** - immutable caching for assets, no-cache for HTML. - **SPA routing** - a catch-all route to `index.html` when `layout.spa` is enabled. ## Deploying After generating the file, deploy using the [Vercel CLI](external:https://vercel.com/docs/cli): ```bash npm install -g vercel vercel ``` Alternatively, connect your repository to Vercel from the dashboard. It detects the `vercel.json` automatically. ## Re-generating If you change your `out` directory or `url` in `docmd.config.json`, re-run the command to regenerate the file. This keeps the configuration in sync. --- ## [JavaScript Engine](https://docs.docmd.io/engines/js/) --- title: "JavaScript Engine" description: "Deep explore docmd's native JavaScript execution engine: use cases, portability, capabilities, and limits." --- The **JavaScript Engine** is the foundational execution engine bundled into docmd. It runs easily on modern JavaScript runtimes. It delivers excellent performance without external dependencies or complex compilers. By default, every docmd repository relies on the JavaScript engine. It provides highly reliable file traversal, metadata indexing, and build generation. ## Configuration To explicitly instruct docmd to utilise the JavaScript backend, define the `engine` property as `"js"` inside `docmd.config.json`. ```json { "title": "Developer Handbook", "engine": "js", "src": "docs", "out": "site" } ``` ## Ideal Use Cases & Where It Shines The JavaScript engine is exceptionally versatile. It shines under the following conditions: - **Standard Repositories**: Sites containing up to several hundred pages build extremely fast. It leverages optimised JIT compilation and native JSON parsing. - **Maximum Portability**: If your team uses diverse operating systems or restricted enterprise networks, the JavaScript engine guarantees flawless builds everywhere. - **Rapid Prototyping**: Local development builds benefit from instantaneous hot-reloading (`npx @docmd/core dev`) with low initialisation latency. - **Custom Scripting**: Configuration fallbacks and plugin integrations execute naturally within JavaScript. Standard string parsing avoids cross-boundary serialisation costs. ## Available Devices & Host Compatibility Because it operates entirely within native runtime environments, the JavaScript engine supports an exhaustive array of target platforms: - **Operating Systems**: macOS, Linux, Windows, FreeBSD, and OpenBSD. - **Hardware Architectures**: x64, ARM64 (Apple Silicon, AWS Graviton), ARMv7, and RISC-V. - **Container Environments**: Alpine Linux, standard Debian/Ubuntu, serverless build runners (Vercel, Netlify), and embedded CI pipelines. ## Capabilities & Limitations | Dimension | JavaScript Engine Profile | Operational Impact | | :--- | :--- | :--- | | **Concurrency Model** | Node.js Event Loop + Native Worker Threads | Excellent asynchronous scheduling for network responses. Disk-heavy blocks operate smoothly. | | **Git Metadata Handling** | Subprocess Orchestration (`child_process.execFile`) | Safely spawns native Git binaries to harvest commit histories. Includes persistent disk caching. | | **Setup & Initialisation** | Zero-Configuration | Boots instantaneously. No package postinstall compilation required. | | **Scalability Ceiling** | Highly Performant up to ~1,000 documents | On monolithic repositories exceeding a thousand complex files, sequential subprocess overhead may introduce minor latencies. | ## Feature Completeness The JavaScript engine is **exclusive in its universal feature support**. Every core feature, advanced syntax, templating zone, and official plugin is engineered to run easily here. Whether compiling mathematical formulas, rendering live search indices, or generating static site maps, the JavaScript engine guarantees deterministic builds. --- ## [Engines Overview](https://docs.docmd.io/engines/overview/) --- title: "Engines Overview" description: "Understand the pluggable build engine architecture and select the best processing backend." --- The compiler features a highly modular, multi-threaded **Pluggable Engine Architecture**. It decouples orchestration from computational tasks to execute heavy workloads efficiently. Choose between the zero-configuration **JavaScript Engine** and the accelerated **Rust Engine**. Select the engine based on your repository size, platform, and performance needs. ## Available Engines | Engine | Identifier | Default | Target Use Case | Key Strength | | :--- | :--- | :---: | :--- | :--- | | **JavaScript Engine** | `"js"` | ✅ Yes | Standard websites, rapid local prototyping, portability. | Runs universally on any device supporting Node.js. | | **Rust Engine (Preview)** | `"rust"` | ❌ No | Massive repositories (1,000+ files), enterprise CI/CD builds. | Maximises parallel file I/O via Tokio. | ## Configuration Options Configure your build engine in the `docmd.config.json` file. Set the `engine` parameter directly. ```json { "title": "Enterprise Reference", "engine": "js", "src": "docs", "out": "site" } ``` ### Complete Options Reference | Key | Supported Values | Default | Description | | :--- | :--- | :--- | :--- | | `engine` | `"js"`, `"rust"` | `"js"` | The execution layer processing file discovery and batch reads. | ## High-Level Capabilities & Limitations Both engines share a rigorous execution boundary. The core API layer enforces uniform security and deterministic output. ### Shared Capabilities - **Thread Isolation**: Engines execute asynchronous tasks securely inside isolated worker threads. This prevents blocking the primary server loop. - **Task Verification**: Strict allowlists prevent unauthorised disk access or unverified execution patterns. - **Seamless Interoperability**: Plugins request data via standardised interfaces (`runWorkerTask`). They remain unaware of the underlying backend. ### Architectural Limitations - **Serialisation Overhead**: Data crosses native runtime boundaries (N-API). Highly iterative tasks passing large JSON objects incur a small serialisation penalty. - **Binary Compatibility**: The JavaScript engine runs natively everywhere. The Rust engine relies on OS-specific platform binaries distributed via npm. ## How the Engine Loader Works When `@docmd/core` boots, the internal loader inspects your active configuration: 1. **Resolution**: If configured for `"rust"`, the engine lazy-loads the architecture-specific native package (e.g., `@docmd/engine-rust-darwin-arm64`). 2. **Graceful Fallback**: If the binary is missing or unsupported, the engine logs an advisory notice. It then transparently falls back to the JavaScript engine. Your build always succeeds. Explore the deep-dive documentation for each engine: - [JavaScript Engine Reference](js.md) - [Rust Engine Reference](rust.md) --- ## [Rust Engine](https://docs.docmd.io/engines/rust/) --- title: "Rust Engine" description: "Explore the optional native Rust engine: use cases, file I/O capabilities, supported packages, and limitations." --- The **Rust Engine** is an optional, high-performance execution engine. It accelerates heavy I/O workloads in massive documentation projects. By using native binaries through N-API, it bypasses standard event-loop constraints to deliver multi-threaded file reading and subprocess orchestration. Available as an **experimental preview**, the Rust engine targets enterprise scale. It shines where thousands of markdown files and exhaustive Git logs introduce compilation bottlenecks. ## Configuration To activate native Rust acceleration, configure the `engine` directive to `"rust"` within your `docmd.config.json` file. ```json { "title": "Global API Registry", "engine": "rust", "src": "docs", "out": "site" } ``` ## Ideal Use Cases & Where It Shines The Rust engine solves specific compilation bottlenecks. It provides excellent efficiency gains under the following scenarios: - **Massive Repositories (1,000+ Files)**: Monolithic projects benefit immensely from asynchronous, parallel file system access orchestrated via Tokio. - **Intensive Git Metadata Harvesting**: Extracting deep commit logs across hundreds of pages requires heavy subprocess spawning. The Rust engine processes `git:log` tasks up to **1.24× faster** than JavaScript. - **Cold Build Acceleration in CI/CD**: In environments where warm disk caches are unavailable, raw file read throughput reduces total processing time. Real-world benchmarks demonstrate a **~25% speedup during cold builds** and a **~17% improvement on warm builds**. ## Supported Devices & Platform Packages The engine executes pre-compiled machine code. It requires dedicated native binaries tailored to your target host architecture. The foundational `@docmd/engine-rust` package automatically lazy-loads the correct platform binary during startup. The following platform packages are currently distributed: | Platform Package | Target Architecture | Host Operating System | | :--- | :--- | :--- | | `@docmd/engine-rust-darwin-arm64` | ARM64 (Apple Silicon) | macOS | | `@docmd/engine-rust-darwin-x64` | x64 (Intel) | macOS | | `@docmd/engine-rust-linux-x64-gnu` | x64 | Linux (glibc environments) | | `@docmd/engine-rust-linux-arm64-gnu` | ARM64 | Linux (glibc environments) | | `@docmd/engine-rust-win32-x64-msvc` | x64 | Windows | ::: callout info "Transparent Graceful Fallback" If your environment lacks an available pre-built binary, the engine logs a non-fatal notification and **automatically falls back** to the high-performance JavaScript engine. Your builds remain fully deterministic. ::: ## Capabilities & Strategic Limitations To achieve maximum utility, you must understand its architectural trade-offs. The engine excels at I/O-bound operations but incurs overhead during cross-boundary serialisation. | Capability / Task | Rust Engine Performance Profile | Architectural Verdict | | :--- | :--- | :--- | | **Batch File Discovery & Reads** | Accelerated via parallel Tokio workers. | ✅ Highly Effective for massive directories. | | **Git Commit Log Harvest** | Fast subprocess orchestration bypassing Node event loops. | ✅ Excellent for cold-start Git metadata extraction. | | **Persistent Disk Caching** | Native support for anchored disk caches to eliminate redundant reads. | ✅ Highly Effective for warm builds. | | **CPU-Bound Search Indexing** | **Slower than native JavaScript JIT**. | ❌ Inefficient due to double serialisation overhead. | ### The Double-Serialisation Tax Explained Communication between docmd's core orchestrator and the native Rust engine relies on stringified JSON passing across the N-API runtime boundary: ```text JS Worker → JSON.stringify() → NAPI Boundary → Serde Deserialisation → [Rust Task] → Serde Serialisation → NAPI Boundary → JSON.parse() ``` For I/O-heavy operations like querying Git histories or reading disk buffers, the processing time saved vastly outweighs the string conversion cost. However, for highly iterative, CPU-bound tasks like full-text search indexing (`search:index`), **the serialisation round-trip consumes more CPU resources than the underlying task itself**. Serialising large arrays of content back and forth causes the Rust implementation to run slower than Node's native JIT string manipulation. As a result, **the JavaScript engine remains the recommended runtime for semantic search pipelines**. Enable the Rust engine selectively for large-scale Git and file management workloads. --- ## [Installation](https://docs.docmd.io/getting-started/installation/) --- title: "Installation" description: "Install @docmd/core globally, locally within a project, or run containerised via the official Docker image. Requires Node.js 18+." --- Choose the installation method that fits your workflow. Node.js 18 or higher is required for local builds. ## 1. Local Installation (Recommended) Running `docmd` locally keeps your documentation configuration versioned with your source code. ::: tabs == tab "npm" icon:box ```bash # Install as a development dependency npm install -D @docmd/core # Initialise a new project npx docmd init ``` == tab "pnpm" icon:boxes ```bash # Install as a development dependency pnpm add -D @docmd/core # Initialise a new project pnpm dlx docmd init ``` == tab "yarn" icon:scroll ```bash # Install as a development dependency yarn add -D @docmd/core # Initialise a new project yarn dlx docmd init ``` == tab "Bun" icon:zap ```bash # Install as a development dependency bun add -D @docmd/core # Initialise a new project bunx docmd init ``` == tab "Docker" icon:container ```bash # Pull the official multi-architecture image docker pull ghcr.io/docmd-io/docmd:latest # Build documentation from local docs/ to site/ docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` See the [Docker Deployment Guide](../deployment/docker.md) for Docker Compose and Kubernetes configurations. ::: <img width="500" class="with-border" src="/assets/previews/terminal-npx-init.webp"> ::: callout tip "Shorthand Scripts" icon:sparkles Once installed locally, you can use `npx docmd dev` to start the live preview server, or add scripts directly to your `package.json`. ::: ## 2. Global Installation Install the package globally to create or preview sites anywhere on your system without creating a local project. ::: tabs == tab "npm" icon:box ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: Once installed, the `docmd` binary is available everywhere: ```bash docmd dev # Start a dev server locally docmd build # Build static output ``` ## 3. Browser-Only Integration Embed the engine directly inside an existing web application via CDN. ::: callout info "Specialised Library Integration" icon:help-circle This bypasses the CLI and loads the parsing engine in the reader's browser. Use this for dynamic portals, not static SEO websites. ::: Add the stylesheet and JavaScript engine to your HTML. ```html <!-- Core Stylesheet --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- Isomorphic Rendering Engine --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` See the [Browser API Guide](../api/browser-api.md) for full integration details. ## 4. Troubleshooting ### Permission Denied (`EACCES` Errors) Do not use `sudo` for global installs on macOS or Linux. Fix permission conflicts using a Node.js version manager like [nvm](external:https://github.com/nvm-sh/nvm) or [fnm](external:https://github.com/Schniz/fnm). ### PowerShell Execution Policies (Windows) If Windows blocks execution, open PowerShell as administrator and enable current-user script execution. ```powershell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser ``` --- ## [Project Structure](https://docs.docmd.io/getting-started/project-structure/) --- title: "Project Structure" description: "Learn how `@docmd/core` maps physical folders and Markdown files to dynamic URLs and clean navigation." --- The compiler uses your local filesystem as the source of truth. Folders become navigation sections. Markdown files become content pages. Your directory hierarchy translates directly into web URLs. ## 1. Standard Project Scaffold Run `npx @docmd/core init` to establish a minimal workspace layout. This structure keeps source content separated from assets and production builds. ```text my-docs/ ├── docs/ ← Source directory containing your Markdown (.md) pages │ └── index.md ← The landing page (resolves to /) ├── assets/ ← Static web assets loaded directly by the engine │ ├── css/ ← Custom stylesheets for customising page layout │ ├── js/ ← Custom scripts to extend browser-side logic │ └── images/ ← Brand logos, icons, and inline illustrations ├── docmd.config.json ← Central configuration schema ├── package.json ← Node dependency manifest and scripts └── site/ ← Optimised production build output folder ``` ::: callout info "Configuration File Resolution" icon:settings `docmd.config.json` (or `docmd.config.ts`) is the recommended, primary configuration format. The legacy `docmd.config.js` format remains supported but acts strictly as a fallback when `.json` or `.ts` configuration files are missing. ::: ## 2. Directory and URL Mapping The compiler maps files within your source folder directly to public URLs. There are no trailing `.html` extensions or complex routing rules. | Source File | Resolved URL Path | Purpose | | :--- | :--- | :--- | | `docs/index.md` | `/` | Home Landing Page | | `docs/api.md` | `/api` | Main API Reference | | `docs/guides/setup.md` | `/guides/setup` | Sub-section Technical Guide | | `docs/getting-started/quick-start.md` | `/getting-started/quick-start` | Multi-level deep page | ::: callout tip "Automatic Header Parsing" icon:info If a file lacks a `title` in its YAML frontmatter, the engine extracts the first `H1` tag (`# Heading`). This title represents the page in breadcrumbs and search. ::: ## 3. Workspace Monorepo Structure For complex layouts or large projects with multiple distinct products (such as a core platform, an SDK, and a CLI tool), `docmd` natively supports a **Workspace Monorepo** directory structure. This allows you to manage multiple independent documentation sites from a single root repository while maintaining unified branding. ```text my-docs-monorepo/ ├── docmd.config.json ← Root configuration (defines global settings) ├── assets/ ← Shared global assets (inherited by all projects) │ ├── css/ ← Shared global stylesheets │ └── images/ ← Shared logos and icons ├── package.json ← Root dependency manifest ├── main-site/ ← Root project directory │ ├── docmd.config.json ← Project-specific config overrides │ └── docs/ ← Content for main-site (resolves to /) │ └── index.md └── sdk-reference/ ← Secondary project directory ├── docmd.config.json ← Project-specific config overrides └── docs/ ← Content for sdk-reference (resolves to /sdk) └── index.md ``` ### Key Workspace Directory Patterns * **Global Configuration Cascading:** Any configuration defined in the root `docmd.config.json` (such as `theme` or `menubar`) acts as a fallback default. Individual projects can selectively override these defaults in their own local config files. * **Asset Sharing and Priority:** Shared logos, global custom styles, and common scripts are placed in the root `assets/` directory. Projects can also define their own local `assets/` directories; in the event of filename conflicts, project-specific assets always take precedence. * **Output Consolidation:** During the build process (`npx @docmd/core build`), the engine automatically merges all projects into a single consolidated production output directory (e.g. `./site/` and `./site/sdk/`), negating the need for complex reverse proxy setups or isolated build pipeline configuration. For complete setup steps and advanced cascading rules, refer to the [Workspaces Configuration Guide](../configuration/workspaces.md). --- ## [Quick Start](https://docs.docmd.io/getting-started/quick-start/) --- title: "Quick Start" description: "Go from an empty folder to a running documentation site in under a minute." --- Run docmd inside any folder with Markdown files. No config file, setup, or framework knowledge required. ## 1. Start a dev server ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: This opens `http://localhost:3000`. Your documentation is live. <img width="500" class="with-border" src="/assets/previews/terminal-npx-dev.webp"> ::: callout tip "Automatic Port Failover" icon:info If port `3000` is in use, docmd automatically finds the next available port (e.g., `3001`). ::: ## 2. Automatic features The engine sets up everything automatically: 1. **Directory Detection**: Scans for `docs/`, `src/docs/`, `documentation/`, or `.md` files. 2. **Navigation Structuring**: Builds a nested sidebar from your folder tree. 3. **Title Resolution**: Extracts page titles from the first `H1` tag automatically. 4. **Search Indexing**: Enables built-in full-text search immediately. 5. **Smart Caching**: Triggers sub-200ms rebuilds instantly on file save. No `docmd.config.json` is required. Add one later to customise layouts, plugins, or versions. ## 3. Build for production Compile your Markdown files into a static, production-ready site. ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: The compiler outputs a static site to `./site/`. Host this static output anywhere. Deploy to GitHub Pages, Vercel, Netlify, or any static host. --- ## [Context Preservation for AI-Friendly Documentation](https://docs.docmd.io/guides/ai-optimisation/context-preservation/) --- title: "Context Preservation for AI-Friendly Documentation" description: "How to ensure that AI models can understand and utilise the relationships between different parts of your documentation." --- ## Problem Human readers can click hyperlinks to learn more. AI models often process documentation in isolated "chunks". When an AI encounters a hyperlink, it cannot "click" it to fetch context. If critical information is hidden behind a link, the AI may fail to provide accurate answers. This leads to hallucinations. ## Why it matters AI models rely on immediate surrounding text to determine meaning. If your documentation is highly fragmented with poor context preservation, AI-driven search tools (like RAG systems) will struggle to provide high-quality responses. ## Approach Use **Inline Context Unrolling** to provide the minimum viable context alongside every major link. Use docmd's [LLMs Plugin](../../plugins/llms.md) to provide a unified, machine-readable view of your entire documentation set. ## Implementation ### 1. Descriptive Linking and Summaries Avoid generic link text. Provide a brief, one-sentence summary of the linked concept alongside the link. - **❌ Poor (Context Lost)**: To configure the timeout, refer to the [General Configuration](../../configuration/overview.md). - **✅ Better (Context Preserved)**: You can configure the `timeoutMs` parameter within the [General Configuration](../../configuration/overview.md), which defines how long the engine waits before failing a network request. ### 2. Using Collapsible Sections for Detail [Collapsible Containers](../../content/containers/collapsible.md) are excellent for AI optimisation. The content remains part of the raw Markdown source for the AI, but it is visually tucked away for human readers. ```markdown ### Database Connection Connect using the primary URI. ::: collapsible "What is the URI format?" The URI follows the standard PostgreSQL format: `postgresql://user:password@host:port/database`. ::: ``` ### 3. Enabling the LLMs Plugin Enable the [LLMs Plugin](../../plugins/llms.md) in your `docmd.config.json`. This plugin generates a `llms-full.txt` file after every build. It concatenates your entire documentation set into a single, high-context file that LLMs consume easily. ## Trade-offs Inline context unrolling makes documentation slightly more verbose and introduces minor redundancy. However, this is a small price to ensure your documentation is "AI-ready" and capable of powering high-quality automated support. --- ## [Creating Deterministic and Chunkable Documentation](https://docs.docmd.io/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "Creating Deterministic and Chunkable Documentation" description: "How to structure your documentation to optimise it for Retrieval-Augmented Generation (RAG) and AI ingestion." --- ## Problem When AI pipelines ingest documentation, they slice the Markdown into smaller "chunks". If a document consists of long paragraphs with unclear boundaries, the algorithm splits context mid-thought. This destroys the chunk's utility and leads to incorrect AI responses. ## Why it matters If an AI retrieves a code block but misses the preceding paragraph explaining *when* to use it, the answer lacks conditionality. Structuring your documentation for chunkability ensures each segment contains enough context to be useful on its own. ## Approach Structure your pages as a hierarchy of deterministic, atomic blocks. Use Markdown headers to clearly delineate concepts. Ensure related information (like a warning and the code it applies to) is kept physically close together in the source file. ## Implementation ### 1. Atomic Header Sections Ensure every `##` or `###` header encapsulates a single, atomic concept. A well-structured section should stand alone as a useful chunk for an AI model. - **✅ Good**: A header "Authentication via OAuth" followed by a brief explanation and a code example. - **❌ Poor**: A massive "Getting Started" page with 15 different concepts and no sub-headers. ### 2. Tight Proximity for Critical Information Do not separate a critical warning from the code it applies to with long paragraphs. Use [Callouts](../../content/containers/callouts.md) to bind them together vertically. This increases the probability that they remain in the same vector chunk during ingestion. ```markdown ::: callout warning "Destructive Action" Running this command will permanently delete all logs. ::: `npx @docmd/core logs --clear` ``` ### 3. Automated Concatenation The [LLMs Plugin](../../plugins/llms.md) facilitates chunking by generating a `llms-full.txt` file. This uses standard separators (`---`) between pages. It helps ingestion pipelines recognise natural document boundaries while preserving global context. ## Trade-offs This approach favours a modular, segmented writing style over long, flowing narratives. While it may feel repetitive to a human reader, it significantly improves the performance of AI-powered search and automated support agents. --- ## [Generating AI-Ready Documentation with docmd](https://docs.docmd.io/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "Generating AI-Ready Documentation with docmd" description: "How to use the llms.txt standard and docmd's built-in tools to provide optimised context for AI assistants." --- ## Problem Developers increasingly rely on AI coding assistants to read and interpret documentation. If your documentation is only accessible via a web browser - cluttered with navigation elements, trackers, and complex HTML - AI agents consume excessive tokens on irrelevant data. This quickly exhausts their context windows. ## Why it matters Providing a clean, token-optimised text version of your documentation is the modern equivalent of providing a high-quality REST API. It ensures AI agents can quickly ingest your entire documentation set. This results in more accurate code suggestions and better support. ## Approach Use docmd's built-in **LLMs Plugin**. This plugin natively implements the emerging `llms.txt` standard. It automatically generates token-optimised summaries and full-context files during every build process. ## Implementation Configure the `llms` plugin in your [Plugin Configuration](../../plugins/llms.md). ### 1. Configure the Site URL Ensure the `url` property is correctly set in your `docmd.config.json`. This allows the plugin to generate absolute URLs for all pages in the `llms.txt` file. ```json { "title": "My Project Docs", "url": "https://docs.example.com", "plugins": { "llms": {} } } ``` ### 2. Output Files During the build process, docmd generates two key files in your site root: - **`llms.txt`**: A concise, structured Markdown summary of all your pages, including their titles, descriptions, and full URLs. - **`llms-full.txt`**: A comprehensive file containing the raw Markdown content of your entire site, concatenated with standard separators (`---`). This provides the ultimate "source of truth" for AI models. ### 3. Controlling Ingestion You can exclude specific pages from the AI-ready output using the `llms` property in the [Page Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Internal Debugging Guide" llms: false --- ``` ## Trade-offs Generating `llms-full.txt` creates a large single file. For exceptionally large documentation sites, this file could exceed several megabytes. While ideal for modern LLMs with large context windows (like Gemini 1.5 Pro or Claude 3.5 Sonnet), it may be too large for smaller models. Ensure you organise your [Navigation](../../configuration/navigation.md) logically so the AI can prioritise important sections. --- ## [MCP & Agent Skills](https://docs.docmd.io/guides/ai-optimisation/mcp-and-agent-skills/) --- title: "MCP & Agent Skills" description: "Optimise your documentation workspace for AI development agents using the Model Context Protocol and custom Skills." --- Integrating AI development agents into your workflow requires structured interfaces that allow models to query, read, and write documentation context efficiently. `docmd` satisfies this need via a native **Model Context Protocol (MCP)** server and an extensible **Agent Skills** database. ## Model Context Protocol (MCP) Setup The Model Context Protocol connects LLM environments directly to your local workspace tools. ### 1. Claude Desktop Integration Add the following to your desktop configuration file (typically at `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows): ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/path/to/your/docs/project" } } } ``` ### 2. IDE Integration (Cursor / Windsurf) In your editor's MCP settings panel, add a new server using the `stdio` transport: - **Command**: `npx @docmd/core mcp` - **Transport**: `stdio` ## Available MCP Tools Once connected, the following tools become available to the agent: 1. `search_docs(query)`: Performs a workspace-wide full-text search. 2. `read_doc(route)`: Retrieves the raw Markdown contents of a specific route. 3. `validate_docs()`: Lints the entire documentation and returns validation errors (e.g., broken links). 4. `get_llms_context()`: Fetches the consolidated `llms-full.txt` context file. ## Leveraging Agent Skills (`SKILL.md`) When you run `docmd init` in your project, the engine automatically generates a `SKILL.md` file in your root workspace. This file serves as a prompt instruction card for any AI agent working on your repository. ### Best Practices for AI Agents 1. **Read SKILL.md First**: Instruct your agents to read the `SKILL.md` file at the start of a coding session. This teaches the model about custom Callouts, OpenAPI markup, and file structures. 2. **Validate After Edits**: Whenever an agent modifies Markdown files, it should call the `validate_docs` tool (or run `npx @docmd/core validate`) to verify that no relative links or anchor paths are broken. 3. **Synchronize Locales**: If the project uses versioning or multiple languages, agents should use the comparison matrix to ensure all translations stay in sync. --- ## [Minimising AI Hallucinations via Documentation](https://docs.docmd.io/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "Minimising AI Hallucinations via Documentation" description: "How to write explicit, self-contained documentation that prevents AI models from inventing incorrect information." --- ## Problem AI models are predictive engines, not reasoning engines. If an API usage example is incomplete, uses ambiguous placeholders, or relies on implicit knowledge, the AI will "hallucinate". It invents missing pieces based on general training patterns. These inventions are frequently incorrect, leading to developer frustration. ## Why it matters Hallucinated code destroys user trust. When a developer asks an AI for help and receives broken code, they blame the software for being "buggy" or "poorly documented". Minimising hallucinations is critical for maintaining your project's professional reputation. ## Approach Practice **Defensive Documentation**. Write extremely explicit, fully instantiated code blocks that leave no room for ambiguity. Never assume the reader (or the AI) knows the necessary imports, environment variables, or prerequisite configurations. ## Implementation ### 1. Fully-Qualified Code Blocks Always include the necessary imports or setup code in every snippet. This ensures that when an AI chunks your documentation, the code block remains a self-contained unit of truth. - **❌ Hallucination Risk**: ```javascript const config = loadConfig(); ``` - **✅ Hallucination Proof**: ```javascript import { loadConfig } from "@docmd/core"; const config = loadConfig(); ``` ### 2. Concrete Examples Over Placeholders Avoid using vague placeholders like `your-api-key` or `env-name`. Provide concrete, valid examples or use comments to specify strict enum requirements. ```javascript // Valid environments: "development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. Inline Code Comments Place critical requirements *inside* the code block as comments, rather than only in surrounding paragraphs. AI models weigh comments within code highly when generating similar snippets. ```javascript // REQUIRED: Must be an absolute path outputPath: "/var/www/html/docs" ``` ### 4. Categorised Warnings Use [Callouts](../../content/containers/callouts.md) to clearly mark deprecated features or breaking changes. AI models are more likely to respect a `::: callout warning` block than a simple sentence in a paragraph. ## Trade-offs Defensive documentation makes code blocks longer and more repetitive. Human readers may find seeing the same `import` statements tedious. However, the benefit of having "AI-proof" documentation that reduces support tickets far outweighs the minor cost of verbosity. --- ## [Designing for Semantic Search and RAG](https://docs.docmd.io/guides/ai-optimisation/semantic-search-design/) --- title: "Designing for Semantic Search and RAG" description: "How to structure your documentation to optimise it for vector-based search and Retrieval-Augmented Generation." --- ## Problem Traditional keyword search relies on exact text matches. If a user searches for "authentication", a basic keyword engine fails to find "Integrating OAuth2" if the exact word is absent. Semantic search uses vector embeddings to understand query meaning. It solves this problem but requires specific documentation structures. ## Why it matters Modern developers expect intuitive, intent-based search. If documentation fails to surface relevant content because of terminology differences, users abandon your site. Designing for semantic search ensures documentation remains discoverable regardless of the vocabulary used. ## Approach Structure your documentation to be easily consumed by Retrieval-Augmented Generation (RAG) pipelines. Create "semantically dense" content where concepts are clearly defined. Replace pronouns with explicit entities to preserve context during chunking and vectorisation. ## Implementation ### 1. Rich Frontmatter Metadata Use [Frontmatter](../../content/frontmatter.md) to provide explicit keywords and descriptions that might not appear naturally in the body text. This gives the search engine extra "hooks" into your content. ```yaml --- title: "Integrating OAuth2" description: "Learn how to implement secure user authentication and SSO." keywords: ["login", "authentication", "sso", "security", "identity"] --- ``` ### 2. The "Semantic Density" Strategy RAG systems slice documents into small vector chunks. The first paragraph of every section should contain the highest density of relevant nouns and verbs related to that topic. This ensures the section's primary "meaning" is captured in the initial vector. - **✅ Good**: "This guide explains how to implement **OAuth2 Single Sign-On (SSO)** to provide secure **authentication** for your documentation site." - **❌ Poor**: "In this section, we'll talk about how it works and how you can set it up easily." ### 3. Avoiding Pronoun Ambiguity In a chunked database, a sentence like "It works with any provider" is useless if the preceding paragraph defining "It" was sliced into a different chunk. Be explicit. - **❌ Ambiguous**: "It is highly scalable." - **✅ Explicit**: "The **docmd Search Engine** is designed to be highly scalable." ## Trade-offs Writing for semantic density can feel more formal or repetitive than traditional narrative writing. However, the resulting improvement in discoverability and AI response accuracy makes this a vital practice for enterprise-grade documentation. --- ## [Structuring Documentation for AI Agents](https://docs.docmd.io/guides/ai-optimisation/structure-for-llms/) --- title: "Structuring Documentation for AI Agents" description: "How to move from visual formatting to semantic structuring to improve the accuracy of AI coding assistants." --- ## Problem Human readers rely on visual cues and inferred context. AI agents consume raw text streams. Without rigorous semantic structure, models struggle to map relationships between concepts. This leads to poor reasoning and inaccurate coding suggestions. ## Why it matters If your documentation is not optimised for LLMs, developers using tools like GitHub Copilot or Cursor face more hallucinations. This degrades the developer experience. Users often blame your product for errors generated by their AI assistants. ## Approach Transition from a "visual-first" to a **"semantic-first"** mindset. Use standard Markdown features - strict header hierarchies, explicit code block tags, and descriptive alt text - to provide a machine-readable roadmap. docmd processes this structure into optimised outputs via the [LLMs Plugin](../../plugins/llms.md). ## Implementation ### 1. Strict Header Hierarchy Avoid skipping header levels for visual effects. A consistent hierarchy allows LLMs to understand the scope and relationships of different sections. - **`#` Title**: The primary subject of the page. - **`##` Major Concept**: An atomic, high-level topic. - **`###` Detail**: A specific sub-task or property. * **❌ Poor**: Using `###` immediately after `#` for a smaller font size. * **✅ Good**: `# Installation` followed by `## Prerequisites` and `### System Requirements`. ### 2. Descriptive Metadata for Media LLMs cannot "see" images or diagrams. Provide architectural context in the alternative text or an adjacent paragraph. ```markdown ![System Architecture: The frontend React app communicates with the Node.js API via REST, which queries a Redis cache and a PostgreSQL database.](../../static/img/architecture.png) ``` ### 3. Explicit Code Block Labelling Specify the language for every fenced code block using [Syntax Highlighting](../../content/syntax/index.md). This allows LLMs to parse the Abstract Syntax Tree (AST) correctly. ```json "plugins": { "llms": {} } ``` ### 4. Semantic Containers Use [Callouts](../../content/containers/callouts.md) rather than generic blockquotes to provide intent. docmd's semantic containers help AI models distinguish core instructions from supplementary warnings. ## Trade-offs Semantic rigour requires discipline. You cannot use Markdown features purely as decorative elements. However, this discipline produces documentation that is significantly more accessible to both AI agents and human readers using assistive technologies. --- ## [Avoiding Anti-Patterns](https://docs.docmd.io/guides/content-ux/avoiding-anti-patterns/) --- title: "Avoiding Anti-Patterns" description: "How to identify and eliminate common documentation mistakes that degrade the user experience and increase content debt." --- ## Problem Documentation repositories accumulate "quick fixes" that inadvertently erode the user experience. Anti-patterns - such as vague link text or bloated code samples - become entrenched. This makes documentation harder to maintain and less useful for developers. ## Why it matters Anti-patterns contribute to "content debt". They degrade search engine rankings (SEO), reduce accessibility, and increase cognitive load on readers trying to find quick solutions. High-quality documentation requires constant vigilance to keep it clean, concise, and professional. ## Approach Identify and ruthlessly eliminate common anti-patterns during the [Peer Review process](../workflows-teams/git-based-workflows.md). Use automated prose linters like Vale and manual reviews to ensure content remains high-quality, accessible, and consistent. ## Implementation ### 1. Non-Descriptive Hyperlinks Avoid generic text like "click here" or "read more" for links. This harms SEO and makes documentation inaccessible for screen reader users who navigate by skipping between links. * **❌ Bad**: To configure your server, [click here](../../configuration/overview.md). * **✅ Good**: Review the [General Configuration](../../configuration/overview.md) to set up your production server. ### 2. The "Wall of Boilerplate" In code examples, dozens of lines of standard imports and boilerplate distract the reader from the core logic. * **Solution**: Focus on the relevant code snippet. If boilerplate is necessary, use comments to indicate omissions or use [Callouts](../../content/containers/callouts.md) to explain the required setup. ### 3. Using FAQs as "Dumping Grounds" "Frequently Asked Questions" (FAQ) pages often become a repository for information that failed to integrate into main guides. If a question is truly "frequently asked," it indicates your core documentation failed to explain the concept effectively. * **Solution**: Instead of adding to an FAQ, refactor the relevant tutorial or conceptual guide to address the confusion where the user first encounters it. Use an [Important Callout](../../content/containers/callouts.md) if the information is critical. ## Trade-offs Eliminating FAQs requires writers to refactor and improve existing documentation hierarchies constantly. While this adds initial maintenance overhead, it results in a significantly more cohesive, professional, and useful documentation site. --- ## [Improving Readability](https://docs.docmd.io/guides/content-ux/improving-readability/) --- title: "Improving Readability" description: "How to use visual rhythm, information hierarchy, and docmd's structural tools to create highly readable documentation." --- ## Problem Technical documentation is often dense, jargon-heavy, and difficult to scan. When readers encounter "walls of text" without visual relief, they skim over important details. Dense formatting increases cognitive friction, leading to user frustration and potential errors. ## Why it matters Readability is a functional requirement. If a developer misses a warning buried in a long paragraph, the consequences can be severe. A clear information hierarchy ensures users find information quickly, understand it accurately, and act safely. ## Approach Establish a predictable visual rhythm by breaking up long sections of text. Use [Thematic Containers](../../content/containers/index.md) to highlight critical information. By utilising docmd's built-in structural tools, you create a hierarchy that guides the reader's eye naturally toward the most important parts of the page. ## Implementation ### 1. The "Power of Brevity" Limit paragraphs to three or four sentences. Shorter paragraphs are easier to digest on screens and provide "breathing room" for complex technical concepts. If a paragraph feels too long, break it into a list or use a sub-heading. ### 2. Categorising with Callouts Use [Callouts](../../content/containers/callouts.md) consistently to categorise information. This allows skimming users to recognise the intent of a block based on its visual style: * **Info**: Background context or supplementary details. * **Tip**: Best practices, shortcuts, and "pro-tips". * **Warning/Danger**: Critical actions that could lead to errors, data loss, or security vulnerabilities. ```markdown ::: callout warning "Production Safety" Never execute this command on a live database without verifying backups first. ::: ``` ### 3. Sequential Instruction with Steps For tutorials, avoid narrative descriptions of actions. Instead, use the [Steps Container](../../content/containers/steps.md) to create a clear, numbered progression. ```markdown ::: steps 1. **Initialise**: Run `npx @docmd/core init` in your project root. 2. **Configure**: Update your `docmd.config.json` with your site title and navigation. 3. **Build**: Run `npx @docmd/core build` to generate your production-ready static files. ::: ``` ## Trade-offs Using specialised containers like `::: steps` or `::: callout` requires contributors to learn docmd-specific Markdown extensions. While this adds a small learning curve, the significant improvement in information density and clarity far outweighs the minimal effort required. --- ## [Navigation for Large Sites](https://docs.docmd.io/guides/content-ux/navigation-large-sites/) --- title: "Navigation for Large Sites" description: "How to organise complex documentation sets into an intuitive, scalable navigation structure using docmd's layout tools." --- ## Problem As a site grows to hundreds of pages, a simple sidebar often transforms into a labyrinth of deeply nested folders. When users must expand multiple levels to find a reference, they lose context. Frustrated users abandon documentation in favour of trial-and-error. ## Why it matters Navigation is the "map" of your product's capabilities. If navigation is difficult, users rely exclusively on the search bar, leading to fragmented knowledge. A well-structured navigation system teaches users the taxonomy of your product, helping them become self-sufficient over time. ## Approach Prioritise **Top-Level Context Switching** over deep nesting. Keep your left sidebar limited to two or three levels of depth. Use the horizontal [Menubar](../../configuration/menubar.md) to separate distinct documentation "domains" (e.g., Guides, API Reference, Community). This allows each sidebar to remain focused and manageable. ## Implementation ### 1. Domain-Based Separation In your `docmd.config.json`, use the [Menubar](../../configuration/menubar.md) to divide your content into high-level categories. This approach allows you to present a completely different sidebar for each domain, preventing a single navigation tree from becoming overwhelming. ### 2. Flattening the Hierarchy Instead of splitting a single concept across many tiny pages, consolidate related information into comprehensive parent pages. Use clear [Heading Hierarchy](../../content/syntax/index.md) to allow users to navigate within the page using the auto-generated right-side Table of Contents (TOC). * **❌ Poor IA**: A folder named "Security" containing ten separate, one-paragraph files for different protocols. * **✅ Better IA**: A single, well-structured "Security Overview" page that covers all protocols, using headings to provide a clean TOC. ### 3. Using Collapsible Sections For large groups of related content accessed infrequently, use the `collapsible` property in your [Navigation Configuration](../../configuration/navigation.md). This keeps the interface clean by hiding secondary information until explicitly requested by the user. ```json // navigation.json { "title": "API Reference", "collapsible": true, "collapsed": true, "children": [ { "title": "Authentication", "path": "api/auth" }, { "title": "Endpoints", "path": "api/endpoints" } ] } ``` ## Trade-offs Consolidating content into fewer, longer pages requires authors to be disciplined about structural clarity and heading use. If a page becomes too long without proper internal navigation, it becomes its own "wall of text." However, the significant reduction in "click-fatigue" and improved discovery make a flatter, domain-based hierarchy better for large documentation sets. --- ## [Scalable Technical Writing](https://docs.docmd.io/guides/content-ux/scalable-technical-writing/) --- title: "Scalable Technical Writing" description: "How to use Progressive Disclosure and structural containers to manage growing documentation complexity without overwhelming your users." --- ## Problem In the early stages, documenting a feature takes a few paragraphs. As the product evolves, those paragraphs explode into a sea of edge cases, platform variations, and complex options. This results in "vertical bloat," where a page becomes an unreadable wall of text. ## Why it matters Vertical bloat destroys comprehension and increases cognitive load. When users scroll through pages of irrelevant content, they become overwhelmed. They often assume the product is more complex than it actually is. Scalable writing ensures users only see the information they need at any given moment. ## Approach Implement **Progressive Disclosure**. This technique involves presenting only the most critical information upfront (the "Happy Path"). You hide complex, technical, or specific details behind interactive UI structures. docmd provides built-in containers specifically designed to manage this complexity effectively. ## Implementation ### 1. Handling Variations with Tabs Instead of listing instructions sequentially for multiple package managers, use the [Tabs Container](../../content/containers/tabs.md). This allows the user to select their specific environment. It instantly hides irrelevant commands and reduces visual noise. ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. Managing Edge Cases with Collapsibles If a troubleshooting step only applies to a small percentage of users, do not let it interrupt the main tutorial's logical flow. Use the [Collapsible Container](../../content/containers/collapsible.md) to bury these details while keeping them accessible. ```markdown 1. Start the development server by running `npx @docmd/core dev`. ::: collapsible "Troubleshooting: Port already in use" If you receive an `EADDRINUSE` error, you can specify a custom port using the `--port` flag: `npx @docmd/core dev --port 4000`. ::: ``` ### 3. Progressive Detail with Callouts Use [Callouts](../../content/containers/callouts.md) to provide supplementary information that isn't required for the primary task but offers valuable context for advanced users. ## Trade-offs Hiding content inside tabs or collapsibles can occasionally make it harder for users to find information using the browser's native `Ctrl+F` search. However, docmd's integrated [Search Engine](../../plugins/search.md) indexes all content within these containers. This ensures users can still find exactly what they need while enjoying a cleaner reading experience. --- ## [Task vs. Concept](https://docs.docmd.io/guides/content-ux/task-vs-concept/) --- title: "Task vs. Concept" description: "How to apply the Diátaxis framework to separate 'How-To' guides from conceptual explanations for a more effective documentation structure." --- ## Problem A frequent mistake in technical writing is mixing the *Why* something works with the *How* to do it. A tutorial on "Configuring SSO", for example, can become bogged down with pages explaining the SAML protocol's history. This distracts the user from their immediate goal of getting the feature running. ## Why it matters User intent varies significantly. An engineer fixing a production issue at 2 AM needs specific, actionable steps - not architectural philosophy. Conversely, a technical leader evaluating your platform needs to understand the underlying logic before committing. Separating these concerns ensures both personas find the information they need without unnecessary friction. ## Approach Adopt the **Diátaxis framework**, which categorises documentation into four quadrants: Tutorials, How-to Guides, Explanation (Concepts), and Technical Reference. For this guide, we focus on the critical separation between **Task-oriented content** (actionable steps) and **Concept-oriented content** (deeper understanding). ## Implementation ### 1. The Task-Oriented Guide (How-To) Focus entirely on a specific, narrow objective. Strip out lengthy theoretical explanations and focus on the minimum steps required to achieve the goal. Use the [Steps Container](../../content/containers/steps.md) to provide a clear, unambiguous path forward. * **Title Example**: "How to Configure Webhooks" * **Structure**: * Prerequisites * Direct, actionable instructions * Verification steps (how to know it worked) ### 2. The Concept-Oriented Guide (Explanation) Focus on the "Big Picture", including architecture, design philosophy, and the "why" behind specific decisions. Avoid giving direct instructions or commands in these sections. * **Title Example**: "Understanding Webhook Delivery Architecture" * **Structure**: * High-level architecture diagrams * Retry logic and reliability philosophy * Security considerations ### 3. Effective Cross-Referencing Instead of merging the two types of content, use docmd's linking tools to provide a bridge for users who need more context or are ready to implement. * **In a How-To guide**: "For a deeper explore our retry logic, see [Webhook Architecture](../../guides/performance-delivery/caching-strategies.md)." * **In a Conceptual guide**: "Ready to get started? Follow our [Webhook Configuration Guide](../../guides/integrations/alongside-other-tools.md)." ## Trade-offs Separating tasks and concepts increases the number of pages in your navigation and requires rigorous cross-linking. However, this modular structure significantly improves the long-term maintainability, searchability, and overall professionalism of your documentation suite. --- ## [Customising Favicons and Metadata](https://docs.docmd.io/guides/customisation/custom-favicons-metadata/) --- title: "Customising Favicons and Metadata" description: "How to configure your site's visual identity in the browser and optimise social media previews." --- ## Problem A default documentation site often lacks a distinct visual identity in the browser. It uses generic favicons and provides poor previews when links are shared on social media or communication tools. This reduces brand recognition and click-through rates. ## Why it matters Your favicon is the primary visual anchor in a crowded browser window. High-quality OpenGraph and Twitter metadata ensure your documentation looks professional and trustworthy when shared. This provides context through titles, descriptions, and hero images. ## Approach docmd provides a built-in `favicon` property for easy icon configuration. For advanced SEO and social metadata, use the [SEO Plugin](../../plugins/seo.md). This automates the generation of meta tags based on your project configuration and page frontmatter. ## Implementation ### 1. Configuring the Favicon Place your favicon file (e.g., `favicon.svg` or `favicon.ico`) in your source directory and reference it in your `docmd.config.json`. docmd will automatically handle the relative pathing and cache-busting. ```json "title": "My Project", "favicon": "/favicon.svg" ``` ### 2. Global SEO Configuration Enable and configure the [SEO Plugin](../../plugins/seo.md) to set default social media previews for your entire site. ```json "url": "https://docs.example.com", "plugins": { "seo": { "defaultDescription": "The ultimate guide to our amazing software.", "openGraph": { "defaultImage": "/static/og-banner.png" }, "twitter": { "siteUsername": "@myproject", "cardType": "summary_large_image" } } } ``` ### 3. Page-Specific Overrides You can override SEO settings for individual pages using the `seo` property in the [Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Major Release v2.0" description: "Everything you need to know about our new engine." seo: image: "/assets/v2-hero-banner.png" keywords: ["release", "v2", "update", "performance"] --- ``` ## Trade-offs While the `favicon` property is convenient, it only supports a single file. For complex multi-size favicon sets (Apple Touch Icons, Android manifests, etc.), you may need to use a custom plugin to inject additional `<link>` tags into the `<head>`. --- ## [Custom Fonts and Branding](https://docs.docmd.io/guides/customisation/custom-fonts-branding/) --- title: "Custom Fonts and Branding" description: "How to match your documentation's appearance to your corporate identity using CSS variables." --- ## Problem Ensuring your documentation platform easily matches your corporate identity is critical for a professional appearance. The default font stack and colour palette ensure general readability but may not reflect your brand personality. ## Why it matters Documentation is a key brand touchpoint. If your product uses a specific typography (like "Outfit") and a distinct primary colour, your documentation should reflect those choices. Consistency across web properties builds trust and provides a cohesive user experience. ## Approach docmd uses a system of CSS custom properties (variables) that define the layout's visual tokens. You can easily override these variables in a custom stylesheet without modifying the core engine. ## Implementation ### 1. Create a Custom Stylesheet Create a file named `custom.css` in your source directory and override the `:root` variables. ```css /* Import your brand font */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* Brand Typography */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* Brand Colours (Light Mode) */ --link-color: #8a2be2; /* Your primary brand colour */ --link-colour-hover: #7b1fa2; --bg-color: #fcfcfd; /* Subtle background tint */ } /* Dark Mode Overrides */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. Register the Stylesheet Add your custom CSS file to the `theme.customCss` array in your `docmd.config.json`. ```json "theme": { "customCss": ["/custom.css"] } ``` ## Trade-offs Importing external fonts (like Google Fonts) adds latency to the initial page load. To optimise performance, consider hosting your font files locally. Use `font-display: swap` to prevent a "Flash of Unstyled Text" (FOUT) while the custom font loads. --- ## [Designing Custom Landing Pages](https://docs.docmd.io/guides/customisation/custom-landing-pages/) --- title: "Designing Custom Landing Pages" description: "How to use docmd's hero and grid containers to create premium landing pages for your documentation." --- ## Problem By default, the `index.md` file in most documentation generators looks like a standard technical page. Creating a high-impact, marketing-grade landing page usually requires a separate web framework (like Next.js or Astro). This adds complexity to your documentation workflow. ## Why it matters Your documentation homepage is often the first interaction a developer has with your product. A generic Markdown-parsed page may fail to inspire confidence in your project's quality. A custom landing page guides users to important sections while reinforcing your brand's visual identity. ## Approach docmd provides specialised [Hero](../../content/containers/hero.md) and [Grids](../../content/containers/grids.md) containers designed specifically for building premium landing pages. For total creative freedom, use the `noStyle` frontmatter property to take complete control over a page's HTML and styling. ## Implementation ### 1. Using the Hero Container The `hero` container supports several layouts, including `split` (for side-by-side content) and `glow` (for a modern aesthetic). ```markdown ::: hero layout:split glow:true # Build Faster with docmd The zero-config documentation engine for modern developer teams. [Get Started](/docs/start) [View on GitHub](https://github.com/docmd-io/docmd) == side ![Dashboard Preview](../../static/img/hero-preview.png) ::: ``` ### 2. Organising Content with Grids Use [Grids and Cards](../../content/containers/grids.md) to create high-level navigation sections that help users find what they need quickly. ```markdown ::: grids ::: grid ::: card "Quick Start" icon:rocket Get up and running in less than 5 minutes. [Learn More](/docs/start.md) ::: ::: ::: grid ::: card "API Reference" icon:code Comprehensive documentation for all our endpoints. [Explore API](/api) ::: ::: ::: ``` ### 3. Full Customisation with noStyle If you need a completely custom design that ignores the standard documentation layout (no sidebar or header), use the `noStyle` property in the [Page Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Custom Dashboard" noStyle: true --- ``` When `noStyle: true` is set, docmd renders only the raw HTML/Markdown content you provide. This allows you to inject your own CSS and JavaScript for a pixel-perfect experience. ## Trade-offs Using `noStyle: true` means you forfeit the native navigation, search, and theme-switching features provided by docmd. You are responsible for ensuring the custom page is mobile-responsive and accessible. For most use cases, combining the `hero` and `grid` containers provides the best balance of aesthetics and functionality. --- ## [Extending docmd with Custom Plugins](https://docs.docmd.io/guides/customisation/extending-custom-plugins/) --- title: "Extending docmd with Custom Plugins" description: "How to use docmd's lifecycle hooks to build custom functionality and extend the documentation engine." --- ## Problem Sometimes you have specific requirements not covered by built-in features. For example, you might need to fetch data from an internal API during the build process or perform complex transformations on the generated HTML. ## Why it matters Extensibility separates a static tool from a professional documentation framework. Without a clean way to inject custom logic, teams maintain fragile shell scripts or post-processing wrappers. This makes the build process difficult to manage and debug. ## Approach docmd features a reliable, hook-based [Plugin API](../../plugins/building-plugins.md). Write simple Node.js modules that intercept the documentation lifecycle at various stages. This allows you to arbitrarily modify content and behaviour from initial configuration to final HTML generation. ## Implementation ### 1. Create a Local Plugin A plugin is a standard JavaScript module that exports a descriptor and lifecycle hooks. ```javascript // plugins/version-injector.js let latestVersion = "0.0.0"; export default { // Plugin Descriptor plugin: { "name": "version-injector", "version": "1.0.0", "capabilities": ["init", "build"] }, // Lifecycle Hooks async onConfigResolved(config) { // Fetch external data once during initialisation const response = await fetch("https://api.example.com/version"); latestVersion = await response.text(); console.log(`[Plugin] Fetched version: ${latestVersion}`); }, // Modify HTML before writing async onBeforeRender(page) { if (!page.html) return; page.html = page.html.replace(/\{\{VERSION\}\}/g, latestVersion); page.frontmatter.computedVersion = latestVersion; } }; ``` ### 2. Register the Plugin Register your local plugin by importing it into your `docmd.config.js` (or `docmd.config.ts`). JSON config files cannot use imports - use the `.js` or `.ts` format for plugin registration. ```javascript import VersionInjector from "./plugins/version-injector.js"; export default { "title": "My Project Docs", "plugins": { // Inject the local plugin object "version-injector": VersionInjector } }; ``` ## Trade-offs Custom plugins run in the Node.js environment during build time. While powerful, they can impact build performance if unoptimised. Any logic in hooks like `onAfterParse` or `onPageReady` runs for *every* page in your site. Ensure your transformations are efficient (e.g., using optimised Regex) to keep build times fast. --- ## [Alongside Other Tools](https://docs.docmd.io/guides/integrations/alongside-other-tools/) --- title: "Alongside Other Tools" description: "Strategies for integrating docmd into a multi-tool documentation ecosystem to create a seamless user experience." --- ## Problem Large organisations rarely use a single tool for documentation. You might use Confluence for internal specs, Stoplight for APIs, and GitHub for code. Integrating disparate sources into a unified user journey is a challenge. Users often jump between disconnected portals with different styles and navigation. ## Why it matters A fragmented documentation experience ruins developer trust and increases cognitive load. If a user switches between completely different interfaces to follow a tutorial, they lose context or abandon your product. Unifying your tools ensures a professional, cohesive experience that encourages exploration. ## Approach Use docmd as your primary documentation hub. By using the [Menubar](../../configuration/menubar.md) for unified navigation and [Embed Containers](../../content/containers/embed.md) for third-party content, you can create a seamless interface that hides multi-tool complexity. ## Implementation ### 1. Unified Global Navigation Use the `menubar` configuration to link your various documentation portals together. This ensures users can always find their way back to the main guides, regardless of which subdomain they are on. ```json "layout": { "menubar": { "left": [ { "text": "Guides", "url": "/" }, { "text": "API Reference", "url": "https://api.example.com" }, { "text": "Community", "url": "https://forum.example.com" } ] } } ``` ### 2. Seamless Embedding For tools that provide a web interface (like interactive API explorers or dashboard previews), use the `::: embed` container. This displays them directly within your docmd pages, keeping users within your branded environment. ```markdown # Interactive API Explorer ::: embed "https://api.example.com/v1/explorer" ::: ``` For more information, see the [Embed Reference](../../content/containers/embed.md). ### 3. Content Aggregation For external content that must be searchable alongside core documentation, consider a build step that fetches data from other sources and converts it into Markdown. This allows docmd to index all information in a single, unified [Search Index](../../plugins/search.md). ## Trade-offs While embedding provides a unified look, it can introduce performance overhead or "scroll-nesting" issues on mobile devices. Content within an iframe is not natively indexed by docmd's search engine. If search parity is critical, prioritising [OpenAPI Generation](openapi-generation.md) or other Markdown-based ingestion methods is recommended. --- ## [Choosing Your Deployment Method](https://docs.docmd.io/guides/integrations/choosing-deployment-method/) --- title: "Choosing Your Deployment Method" description: "A practical guide to choosing between the docmd GitHub App, GitHub Action, Starter Template, and Deployer Package — with a decision matrix and real-world scenarios." --- # Choosing Your Deployment Method docmd offers four ways to get your documentation live. They all produce the same output — a static site deployed to GitHub Pages or a hosting provider of your choice — but they differ in how much control you want and where you are starting from. ## Quick Decision Matrix | | [GitHub App](../../integrations/github-app.md) | [Starter Template](../../integrations/starter-template.md) | [GitHub Action](../../integrations/github-action.md) | [Deployer Package](../../deployment/deployer-package.md) | |---|---|---|---|---| | **Starting point** | Existing repo | New repo | Any | Any | | **Setup effort** | One click | Two clicks | Write YAML | Run a command | | **Workflow file** | Auto-generated | Included | You write it | Auto-generated | | **Customisable** | After generation | From the start | Fully | Fully | | **Hosting target** | GitHub Pages | GitHub Pages | GitHub Pages | Any provider | | **Monorepo support** | ✓ Auto-detected | — | Manual `--cwd` | ✓ | | **Non-GitHub hosting** | ✗ | ✗ | Adaptable | ✓ Docker, Nginx, Vercel, Netlify… | ## Scenario Guide ### "I want docs live in under two minutes with zero setup" Use the **[GitHub App](../../integrations/github-app.md)**. Install it, select your repository, done. It detects your config, generates the workflow, enables GitHub Pages, and deploys — without you touching a single file. ::: button "Install GitHub App" external:https://github.com/apps/docmd/installations/new icon:github color:#2ea44f --- ### "I'm starting a brand-new documentation site" Use the **[Starter Template](../../integrations/starter-template.md)**. Click "Use this template" on GitHub, update `docmd.config.json` with your title and URL, enable GitHub Pages once, and push. Everything is pre-wired. ::: button "Use Starter Template" external:https://github.com/docmd-io/docmd-template/generate icon:github --- ### "I have an existing CI/CD pipeline and want to add docs to it" Use the **[GitHub Action](../../integrations/github-action.md)**. Drop `docmd-io/deploy@v1` into your existing workflow. It composes cleanly with other steps — run tests, build your app, then build docs, all in one job. --- ### "I'm deploying to Vercel, Netlify, Docker, or my own server" Use the **[Deployer Package](../../deployment/deployer-package.md)**. Run `npx @docmd/core deploy --vercel` (or `--netlify`, `--docker`, `--nginx`) to generate provider-specific config files tailored to your `docmd.config.json`. --- ### "I'm in a monorepo with docs in a subdirectory" Both the **GitHub App** and the **Deployer Package** handle this automatically. The App detects configs anywhere in the repository tree and injects the correct `--cwd` flag. The Deployer Package reads your config from the current working directory. If you prefer the GitHub Action, pass `--cwd` manually: ```yaml - run: npx @docmd/core build --cwd packages/docs ``` --- ### "I want to preview docs on every pull request" Use the **GitHub Action** combined with a PR preview service (e.g. Cloudflare Pages preview deployments or a self-hosted preview environment). See [Previewing Changes](../workflows-teams/previewing-changes.md) for a full walkthrough. --- ## How They Fit Together These methods are not mutually exclusive. A common progression looks like this: ``` Start with the GitHub App (fastest path to live) ↓ Customise the generated workflow file as your needs grow ↓ Add the Deployer Package to generate Nginx/Docker configs for self-hosting ↓ Integrate the Action into a broader CI/CD pipeline ``` You can also mix them: use the Starter Template for a new project, then add the Deployer Package later to generate a Docker image for your staging environment. ## Comparing Build Triggers | Method | Triggers on push | Manual trigger | PR preview | |---|---|---|---| | GitHub App | ✓ (auto-configured) | ✓ `workflow_dispatch` | Requires extra step | | Starter Template | ✓ `main` / `master` | ✓ `workflow_dispatch` | Requires extra step | | GitHub Action | You configure | You configure | You configure | | Deployer Package | Generates the file; triggers depend on your workflow | — | — | ## Further Reading - [GitHub Action reference](../../integrations/github-action.md) - [GitHub App reference](../../integrations/github-app.md) - [Starter Template reference](../../integrations/starter-template.md) - [Deployer Package reference](../../deployment/deployer-package.md) - [GitHub Actions CI/CD guide](./github-actions-cicd.md) - [Previewing Changes](../workflows-teams/previewing-changes.md) --- ## [Existing Markdown Repos](https://docs.docmd.io/guides/integrations/existing-markdown-repos/) --- title: "Existing Markdown Repos" description: "How to instantly generate a professional documentation site from your existing Markdown files with zero configuration." --- ## Problem You have an established repository with hundreds of raw Markdown files - perhaps a legacy wiki, an Obsidian vault, or technical notes. Manually converting frontmatter, fixing broken links, and restructuring files for a new engine is a difficult task that often prevents modernisation. ## Why it matters Your content should remain portable and tool-agnostic. A high-quality documentation engine adapts to your existing files, rather than forcing files to adapt to the engine. Avoiding vendor lock-in ensures your intellectual property remains standard, readable, and future-proof. ## Approach docmd adheres to strict CommonMark specifications and is designed to be **zero-config** by default. Point the docmd CLI at any directory containing Markdown files, and it intelligently bootstraps a full-featured documentation site without modifying a single line of source content. ## Implementation ### 1. Instant Bootstrapping Navigate to your existing Markdown folder and run the development server. docmd scans your directory structure and builds a functional site in memory instantly. ```bash cd my-existing-docs/ npx @docmd/core dev ``` ### 2. Automatic Navigation (Auto-Router) If no `navigation.json` or `docmd.config.json` is found, docmd triggers its [Auto-Router](../../configuration/navigation.md#automatic-sidebar-generation). It recursively maps your folder structure, prettifies directory names (e.g., `getting-started` becomes `Getting Started`), and generates a logical sidebar taxonomy automatically. ### 3. Intelligent Title Inference You don't need to add `title` frontmatter to every file. docmd uses a cascading resolution strategy to determine page titles: 1. **Frontmatter**: Checks for a `title` or `h1` key. 2. **First Heading**: Extracts the first `# Heading` found in the file content. 3. **Filename**: Prettifies the filename as a fallback (e.g., `install-guide.md` becomes `Install Guide`). ### 4. Resilient Syntax Handling docmd is built to be resilient. If existing files contain proprietary syntax or legacy shortcodes from other engines, they render safely as raw text or are skipped. This ensures your build never fails due to unmigrated content. ## Trade-offs Automatic sidebars are typically sorted alphabetically by filename. While naming files like `01-intro.md` and `02-setup.md` works well, descriptive filenames may appear in an unintuitive order. For production-ready sites, we recommend transitioning to manual [Navigation Configuration](../../configuration/navigation.md) for full control over the user journey. --- ## [GitHub Actions CI/CD](https://docs.docmd.io/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "How to automate your documentation builds and deployments using GitHub Actions and docmd for a high-velocity workflow." --- ## Problem Building and deploying documentation manually from a local machine is prone to errors, environment inconsistencies, and security risks. It creates a bottleneck, as deployments depend on a single individual's availability. ## Why it matters Continuous Deployment (CD) ensures your documentation is always in sync with your software. When a technical update is merged, it should reach users within minutes. Automation guarantees every build happens in a clean, reproducible environment, maintaining quality and reliability. ## Approach Use GitHub Actions to run the docmd build pipeline on every push or Pull Request. The resulting static assets can be automatically deployed to hosting providers like GitHub Pages, Cloudflare Pages, or containerised environments using Docker. ## Implementation ### 1. Standard GitHub Pages Workflow Create `.github/workflows/docs.yml` to automate the build and deployment process. ```yaml name: Deploy Docs on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # Build the site into the 'site/' directory - run: npx @docmd/core build - name: Upload Artifact uses: actions/upload-pages-artifact@v3 with: path: site/ - name: Deploy to GitHub Pages uses: actions/deploy-pages@v4 ``` ### 2. Containerised Deployment (Docker) If you host your own documentation, use the [Deploy Command](../../deployment/index.md) to generate a production-ready `Dockerfile` and server configurations. ```bash # Generate Docker and Nginx configs locally npx @docmd/core deploy --docker --nginx ``` You can update your GitHub Action to build and push this Docker image to a registry (like Docker Hub or GitHub Container Registry) whenever you release a new version. ### 3. Pull Request Previews Enhance your workflow by generating ephemeral preview environments for every Pull Request. This allows reviewers to see the rendered documentation before merging it into the main branch. See the [Previewing Changes Guide](../workflows-teams/previewing-changes.md) for more details. ## Trade-offs Automated CI/CD requires initial setup time and management of secrets (e.g., API tokens). However, the long-term benefits of a "hands-off" deployment process - including reduced human error and faster update cycles - far outweigh the initial investment. For large sites, ensure your workflow only triggers when files in your documentation directory change to save CI minutes. --- ## [OpenAPI Generation](https://docs.docmd.io/guides/integrations/openapi-generation/) --- title: "OpenAPI Generation" description: "How to integrate OpenAPI/Swagger schemas into your docmd workflow for automated and synchronised API reference documentation." --- ## Problem Manually maintaining REST API documentation is an operational risk. When an engineer modifies an endpoint or updates a schema in code, documentation becomes obsolete. Keeping these in sync manually is tedious, error-prone, and frequently leads to integration failures for consumers. ## Why it matters Inaccurate API references cause developer frustration and increase support tickets. Automation ensures your documentation remains the "source of truth", reflecting the actual state of your API at every build. This allows engineers to focus on building features rather than updating tables manually. ## Approach Implement an asynchronous build pipeline that converts your `openapi.json` or `swagger.yaml` schema into standard Markdown files. Because docmd excels at rendering Markdown with complex [Containers](../../content/containers/index.md), the resulting API reference feels integrated and visually consistent with the rest of your documentation. ## Implementation ### 1. Build Pipeline Integration Use a tool like `widdershins` or a custom script to generate Markdown from your OpenAPI schema as a pre-build step in your CI/CD pipeline. ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. Optimising API Layouts API references are often content-dense, with large tables for parameters and nested schemas. Use [Frontmatter](../../content/frontmatter.md) to optimise the page layout for readability. ```markdown --- title: "REST API Reference" layout: "full" # Maximises horizontal space for dense tables --- ``` Setting `layout: "full"` removes the right-hand Table of Contents sidebar, providing more room for wide code blocks and response examples. ### 3. Enhancing with docmd Containers Post-process the generated Markdown to inject docmd features like [Tabs](../../content/containers/tabs.md) for multi-language code samples or [Callouts](../../content/containers/callouts.md) for authentication warnings. ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## Trade-offs Machine-generated documentation is excellent for technical accuracy but lacks the "human touch" required for effective learning. We recommend using OpenAPI generation for the **Technical Reference** (endpoints, parameters, schemas) while providing handwritten **Tutorials** and **Conceptual Guides** to explain the context and use cases. --- ## [Caching Strategies](https://docs.docmd.io/guides/performance-delivery/caching-strategies/) --- title: "Caching Strategies" description: "How to optimise your documentation site's performance using immutable caching, Etag revalidation, and production-ready server configurations." --- ## Problem When a documentation site is served without proper cache-control headers, browsers unnecessarily re-download images, CSS, and JavaScript bundles. This results in visual stuttering, increased bandwidth consumption, and a poor experience for returning users. ## Why it matters Effective caching is highly impactful for improving perceived performance. Storing static assets locally in the user's browser eliminates the latency of repeated network requests. This makes navigation feel fluid and reliable, even on unstable connections. ## Approach Implement a two-tier caching strategy: **Immutable Caching** for static assets (CSS, JS, images) and **Etag Revalidation** for dynamic content (HTML, JSON). docmd facilitates this by generating production-ready configurations that handle cache-busting automatically. ## Implementation ### 1. Production-Ready Server Configs The easiest way to implement optimal caching is by using the [Deploy Command](../../deployment/index.md) to generate your server configuration. ```bash # Generate an optimised Nginx configuration npx @docmd/core deploy --nginx ``` ### 2. Immutable Assets For assets that don't change frequently (like theme styles and core scripts), use long-term caching. docmd appends version hashes to these assets to ensure users only download new versions when you update your documentation. ```nginx # Example Nginx rule for immutable assets location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML & Navigation Revalidation Your HTML files and `navigation.json` should always be checked for updates. This ensures users see the latest content immediately. Use the `no-cache` directive to force the browser to revalidate with the server using Etags. ```nginx # Example Nginx rule for HTML files location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## Trade-offs ### Stale Content vs. Performance Setting long cache times for assets is highly performant but requires a reliable "cache-busting" strategy. docmd handles this automatically for core files. If you manually add assets to your `static/` directory, you must update their references (e.g., by changing the filename or adding a query parameter) when content changes. ### CDN Integration If you use a CDN (like Cloudflare or AWS CloudFront), ensure it honours your server's `Cache-Control` headers. Most modern CDNs provide "instant purge" capabilities. We recommend triggering this as part of your CI/CD pipeline whenever you deploy a new version. --- ## [CDN & Edge Deployment](https://docs.docmd.io/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN & Edge Deployment" description: "How to minimise global latency by deploying your static documentation to a Content Delivery Network (CDN) or Edge Network." --- ## Problem Hosting documentation on a single server in one geographic region (e.g., US-East) creates significant network latency for users elsewhere. Every page load, image, and script travels thousands of miles. This makes your documentation feel sluggish for a global audience. ## Why it matters High latency directly harms the developer experience. Even if your documentation is well-written and lightweight, the "Time to First Byte" (TTFB) is limited by physics. If your site feels slow, developers lose focus or abandon your tool in favour of faster alternatives. ## Approach The optimal solution is to deploy your site to an Edge CDN. docmd generates pure static assets (HTML, CSS, JS), making it perfectly suited for edge distribution. CDNs replicate files across globally distributed "Edge Nodes" to serve users from the closest data centre. ## Implementation ### 1. Choose a Platform docmd natively supports all modern static hosting and edge platforms. We recommend the following for their global performance and ease of use: * **Cloudflare Pages**: Extremely fast global edge network with built-in DDoS protection. * **Vercel**: Optimised for performance with excellent developer workflow integration. * **Netlify**: Powerful automation features and a reliable global CDN. ### 2. Automate the Build Use a CI/CD pipeline to build and deploy your site automatically whenever you push changes. See the [GitHub Actions Guide](../../guides/integrations/github-actions-cicd.md) for detailed examples. ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # Build the site into the default 'site/' directory - run: npm install && npx @docmd/core build # Example: Deploying to Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: my-docs directory: site ``` ### 3. Verification Once deployed, verify global performance using tools like PageSpeed Insights or global ping tests. You should see sub-100ms response times from almost any worldwide location. ## Trade-offs Global edge networks abstract away server management, which benefits documentation teams. However, debugging regional caching issues can occasionally be more complex than reviewing a single server log. Using platforms with reliable "instant cache invalidation" ensures users always see the latest version immediately after a deployment. --- ## [Low-End Device Optimisation](https://docs.docmd.io/guides/performance-delivery/low-end-devices/) --- title: "Low-End Device Optimisation" description: "How to build high-performance, accessible documentation that works easily on low-powered hardware and slow network connections." --- ## Problem Modern documentation sites often rely on heavy JavaScript runtimes to display static text. For users on older mobile phones or slow connections, these sites take several seconds to load. The processor struggles to parse large JS bundles, resulting in "input lag" and a poor reading experience. ## Why it matters Technical documentation should be universally accessible. Forcing users on constrained hardware to download a heavy framework creates an unnecessary barrier to learning. A lightweight site ensures product information is available to everyone, regardless of hardware or internet speed. ## Approach Adopt an **HTML-First** strategy. docmd uses a zero-framework architecture. The primary content is rendered into standard HTML during the build process. This keeps the browser's main thread unblocked, ensuring smooth scrolling and snappy navigation even on budget devices. ## Implementation ### 1. Minimal Runtime Footprint By default, docmd does not use React or Vue for its core UI. This pre-rendered approach ensures the initial "First Contentful Paint" happens almost immediately. To maintain this performance: * **Limit Custom Scripts**: Avoid adding large third-party libraries to your `customJs` configuration. * **Use Native Browser Features**: Rely on standard CSS and HTML5 elements. ### 2. Strategic Plugin Management While [Plugins](../../plugins/usage.md) add powerful features, they introduce performance overhead. For example, the [Mermaid Plugin](../../plugins/mermaid.md) requires a large engine to render diagrams. If your users are on low-end devices, use static images instead of client-side rendering. ### 3. Responsive and Optimised Media Avoid serving oversized images to mobile users. Use modern formats like WebP and consider the `<picture>` tag for granular control over responsive assets. ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="Feature Overview" loading="lazy"> </picture> ``` Using the `loading="lazy"` attribute ensures images are only downloaded as they enter the user's viewport, saving bandwidth. ### 4. Efficient Search Indexing docmd generates scoped search indices to keep the memory footprint low. However, for extremely large sites, the [Search Plugin](../../plugins/search.md) can still be memory-intensive. Optimise your index as described in the [Local-First Search Guide](../search/local-first-search.md). ## Trade-offs Prioritising performance for low-end devices means avoiding "heavy" interactive features like complex 3D visualisations. This is a deliberate design choice that values inclusivity and speed over visual complexity. It ensures your documentation remains useful for the widest audience possible. --- ## [Reducing JS Payload](https://docs.docmd.io/guides/performance-delivery/reducing-javascript-payload/) --- title: "Reducing JS Payload" description: "How to maintain a high-performance documentation site by optimising your JavaScript dependencies and using docmd's zero-framework architecture." --- ## Problem Many modern documentation tools rely on heavy JavaScript frameworks (like React or Vue) to render static text. These frameworks add several hundred kilobytes to the initial page load. The browser must download, parse, and execute large amounts of code before the site becomes fully interactive. This leads to slow loading times and "ghost clicks" on low-end devices. ## Why it matters A large JavaScript payload directly impacts "Time to Interactive" (TTI). In technical documentation, users need answers quickly. Any delay caused by heavy framework initialisation is a significant usability barrier. Keeping your payload small ensures that search, navigation, and theme switching are instantaneous. ## Approach docmd uses a **zero-framework** architecture for its core client-side logic. By utilising Vanilla JavaScript and native browser APIs instead of a heavy Virtual DOM, we keep the total JS payload for a standard site under **20KB**. This lightweight foundation ensures maximum performance across all devices. ## Implementation ### 1. Use Native Browser APIs Avoid importing heavy libraries like jQuery or Lodash for simple tasks. Modern browsers have reliable native APIs that handle almost any documentation-related requirement with zero overhead. ```javascript // Add custom scripts in docmd.config.json customJs: ["/static/js/my-custom-logic.js"] ``` ### 2. Strategic Plugin Management While [Plugins](../../plugins/usage.md) add powerful features, some significantly increase your JavaScript payload. For example, the [Mermaid Plugin](../../plugins/mermaid.md) requires a large client-side library to render diagrams. Only enable heavy plugins if they are essential to your content. ### 3. Defer Non-Critical Scripts If you include third-party services like analytics or feedback widgets, ensure they load asynchronously or are deferred. This prevents them from blocking the rendering of your documentation. ```html <!-- In your custom head injection --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. Optimise Assets Ensure any custom JavaScript you provide is minified and compressed. docmd handles the minification of its core assets, but you are responsible for optimising any files you add to your `static/` directory. ## Trade-offs Building complex interactive features with Vanilla JavaScript requires more manual effort than using a declarative framework. However, for documentation - where 95% of the content is static text and images - the performance gains of a zero-framework approach far outweigh the convenience of a heavy framework. --- ## [Sub-100ms Navigation](https://docs.docmd.io/guides/performance-delivery/sub-100ms-navigation/) --- title: "Sub-100ms Navigation" description: "How docmd's native SPA router and intent-based prefetching deliver instant page transitions for an optimal reading experience." --- ## Problem Traditional multi-page navigation triggers a full browser reload on every click. This creates a disruptive "white flash" and breaks the reader's flow. The browser discards the current state, requests new HTML, and re-parses CSS and JavaScript - even if only the central content area changes. ## Why it matters Users frequently jump between tutorials, API references, and conceptual guides. If transitions take seconds, cognitive friction discourages exploration. Instant navigation makes documentation feel like a native application, significantly improving user satisfaction and engagement. ## Approach docmd utilises a high-performance **Single Page Application (SPA) Router** built on pre-generated static files. The browser intercepts link clicks, fetches only necessary content in the background, and updates the page dynamically without a full reload. This preserves the state of the sidebar, table of contents, and theme settings for near-instant transitions. ## Implementation The docmd SPA router uses advanced techniques to achieve sub-100ms navigation speeds: ### 1. Intent-Based Prefetching When a user hovers over a navigation link, docmd detects the intent and initiates a background fetch for the target page. By the time the user clicks, the data is often already in the browser's cache. Transitions feel instantaneous. ### 2. Partial DOM Updates Instead of re-rendering the entire page, docmd intelligently updates only necessary functional zones: * **Main Content**: The primary Markdown-rendered body. * **Table of Contents**: Refreshed to match new headers. * **Navigation State**: Updates active and expanded sidebar states. ### 3. Lifecycle Events for Custom Logic Because the browser avoids full reloads, standard events like `DOMContentLoaded` only fire once. To execute custom JavaScript after every navigation, listen for the `docmd:page-mounted` event. ```javascript document.addEventListener("docmd:page-mounted", (event) => { const currentPath = event.detail.path; console.log(`Successfully navigated to: ${currentPath}`); if (currentPath.includes("/api/")) { initApiConsole(); } }); ``` For more details, see the [Client-Side Events](../../api/client-side-events.md) documentation. ## Trade-offs ### Script Execution The SPA router automatically re-executes `<script>` tags found within the Markdown body of the new page. However, global scripts defined in your theme only run once during the initial load. Use the `docmd:page-mounted` event for logic that must execute on every page. ### SEO and Accessibility Despite SPA-like behaviour, docmd generates a complete `.html` file for every page. This ensures search engine crawlers see full content and the site remains functional for users with JavaScript disabled. This maintains excellent SEO and accessibility standards. --- ## [Breaking Changes & Deprecations](https://docs.docmd.io/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "Breaking Changes & Deprecations" description: "How to communicate API changes and migration paths effectively using versioned documentation and contextual callouts." --- ## Problem When a product introduces a major version change, APIs or configurations are inevitably deprecated. Users browsing the latest docs must be warned if they use outdated patterns. However, the documentation should remain focused on the modern implementation. ## Why it matters Failure to surface breaking changes leads to developers debugging code the engine no longer supports. Contextual warnings and clear migration paths maintain user trust, reduce support requests, and ensure a smooth transition. ## Approach Combine docmd's [Versioning Engine](../../configuration/versioning.md) with [Callout Containers](../../content/containers/callouts.md). This creates a clear distinction between legacy and modern content. Move full legacy documentation to an archived version while providing "migration anchors" in the current version. ## Implementation ### 1. Archiving Legacy Content When releasing a new major version, move existing documentation to an archived directory (e.g., `docs-v1/`). This preserves the context of the previous version for users who haven't migrated. ### 2. Contextual Migration Callouts In your latest documentation, use `warning` or `important` callouts where significant changes occurred. This provides immediate value to users attempting to use legacy patterns. ```markdown # Configuration API ::: callout warning "Migration: Breaking Change in v2.0" The `siteTitle` property has been removed. It has been replaced by the global `title` property. * **Migrating from v1.x?** Please update your `docmd.config.json`. * **Need latest docs?** Refer to the [Configuration Guide](../../configuration/overview.md). ::: ``` ### 3. Maintaining AI Accuracy Separating deprecated content from the active version improves the accuracy of AI tools. docmd's [LLMs Plugin](../../plugins/llms.md) generates context files based on the active version. Archiving legacy content prevents AI models from recommending outdated APIs. ## Trade-offs Actively managing migration callouts adds maintenance overhead. If left indefinitely, pages become cluttered with old warnings. Remove migration callouts once the legacy version reaches End-of-Life (EOL) or after one full major release cycle. This keeps documentation lean and focused. --- ## [Multi-Team Collaboration](https://docs.docmd.io/guides/scaling-architecture/multi-team-collaboration/) --- title: "Multi-Team Collaboration" description: "How to use decentralised navigation and global menubars to allow multiple teams to contribute without friction." --- ## Problem When multiple independent teams (e.g., Frontend, Backend, DevOps, and Product) contribute to a single documentation repository, organisational friction occurs. Teams may overwrite global navigation settings, create conflicting styling paradigms, or break links across boundaries during concurrent updates. ## Why it matters Friction in the authoring experience leads to "documentation silos". Teams create isolated wikis to avoid the complexity of a shared repository. This destroys the unified user experience of a single portal and makes it significantly harder for users to find comprehensive information. ## Approach Use docmd's decentralised [Navigation Resolution](../../configuration/navigation.md#navigation-resolution-priority) system. This allows individual teams to have full autonomy over their specific domains using local `navigation.json` files. A central team governs the global [Menubar](../../configuration/menubar.md) and visual design system. ## Implementation ### 1. Domain-Based Ownership Divide your documentation into top-level directories assigned to specific teams. Each team completely owns the content and internal structure of their assigned folder. ```text my-project/ ├── docs/ │ ├── frontend/ # Owned by the UI Team │ │ ├── navigation.json # Team-specific sidebar │ │ └── components.md │ ├── backend/ # Owned by the API Team │ │ ├── navigation.json │ │ └── database.md │ └── docmd.config.json # Owned by the Platform/Core Team ``` ### 2. Global Context Switching (The Menubar) The central platform team controls the [Menubar](../../configuration/menubar.md). This serves as the primary navigation layer to switch between different team domains. ```json "menubar": { "enabled": true, "items": [ { "text": "Frontend", "url": "/frontend/components" }, { "text": "Backend", "url": "/backend/database" }, { "text": "Infrastructure", "url": "/devops/setup" } ] } ``` ### 3. Local Autonomy with navigation.json When a user browses content within the `/frontend/` directory, docmd automatically prioritises the `frontend/navigation.json` file. The sidebar updates dynamically to reflect only the frontend-specific hierarchy. This prevents navigation clutter. ```json // docs/frontend/navigation.json [ { "title": "Design System", "path": "/frontend/design-system" }, { "title": "Component Library", "path": "/frontend/components" } ] ``` ## Trade-offs Decentralised navigation requires teams to be mindful of cross-domain links. While docmd handles relative links effectively, moving an entire team directory breaks links in other teams' files. Use root-relative paths (starting with `/`) for links between different team domains to ensure stability. --- ## [Managing Multi-Version Documentation](https://docs.docmd.io/guides/scaling-architecture/multi-version-documentation/) --- title: "Managing Multi-Version Documentation" description: "How to maintain multiple versions of your documentation with a unified switcher and path preservation." --- ## Problem As software products evolve, users often remain on older LTS versions. Dropping documentation for v1 when v2 releases leaves users stranded. Maintaining separate sites for each version fragments the user experience and cannibalises SEO. ## Why it matters Without a seamless way to switch versions, developers mistakenly apply instructions from the latest docs to legacy environments. This causes errors and increases support overhead. A unified versioning system ensures users know their context and can jump between versions easily. ## Approach docmd features a native [Versioning Engine](../../configuration/versioning.md) that treats versions as first-class citizens. It isolates builds into version-prefixed directories, provides "Sticky Switching" to preserve paths, and scopes search results to the active version. ## Implementation ### 1. Organise Source Directories Keep your latest documentation in a standard directory (e.g., `docs/`). Place legacy versions in sibling directories (e.g., `docs-v1/`). ```text my-project/ ├── docs/ # v2.x (Current) ├── docs-v1/ # v1.x (Legacy LTS) └── docmd.config.json ``` ### 2. Configure the Version Map Define your version structure in `docmd.config.json`. The `current` version is served at the root URL. Others are served at `/{id}/`. ```json "versions": { "current": "v2", "position": "sidebar-top", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (Latest)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x (LTS)" } ] } ``` ### 3. Per-Version Navigation If the navigation structure differs between versions, place a `navigation.json` file inside each version's source directory. docmd will detect and use it for that specific version. ```json // docs-v1/navigation.json [ { "title": "Legacy Setup", "path": "/legacy-setup" }, { "title": "Migration to v2", "path": "/migration" } ] ``` ### 4. Path Preservation (Sticky Switching) docmd attempts to preserve the user's current path when they switch versions. If a user is at `/api/auth` on the `v2` site and switches to `v1`, the engine routes them to `/v1/api/auth`. If the page doesn't exist, it falls back to the version's homepage. ## Trade-offs Storing multiple versions in a single repository increases repository size over time. For massive documentation sets, consider using CI/CD to pull legacy directories dynamically during the build process instead of committing them to the main branch. --- ## [Organising Large Repositories](https://docs.docmd.io/guides/scaling-architecture/organising-large-repositories/) --- title: "Organising Large Repositories" description: "How to maintain navigation clarity and usability in complex documentation structures using hub pages and hierarchical navigation." --- ## Problem As a documentation repository grows to hundreds of pages, displaying every topic in a single sidebar makes the site unusable. Users suffer from "choice paralysis" where finding a specific module requires scrolling through dozens of irrelevant categories. ## Why it matters Navigation is a critical component of user experience. A cluttered interface diminishes the perceived quality of your product and makes it harder for developers to find answers. If navigation feels chaotic, users often assume the software itself is difficult to use. ## Approach Implement a hierarchical grouping strategy using docmd's [Navigation Configuration](../../configuration/navigation.md). Hide complexity until it is needed. Use collapsible groups and "Hub Pages" to maintain a clean sidebar, ensuring users can focus on their current task. ## Implementation ### 1. Hierarchical Grouping Use the `collapsible` property in your `navigation.json` or config file to group related pages. This keeps the sidebar clean and allows users to expand only the sections they need. ```json // docs/navigation.json [ { "title": "Advanced API", "icon": "braces", "collapsible": true, "children": [ { "title": "Authentication", "path": "/api/auth" }, { "title": "Webhooks", "path": "/api/webhooks" }, { "title": "Rate Limiting", "path": "/api/rate-limiting" } ] } ] ``` ### 2. Implementing Hub Pages Instead of exposing every individual page in the sidebar, create central "Hub Pages" that act as directories for specific sub-systems. Use [Grids and Cards](../../content/containers/grids.md) to provide a visual, high-level overview of the available content. ```markdown # Integrations Hub ::: grids ::: grid ::: card "Database Integrations" icon:database Connect your application to popular databases like Postgres and MongoDB. [View Database Guides](/integrations/databases) ::: ::: ::: grid ::: card "Payment Gateways" icon:credit-card Learn how to implement Stripe, PayPal, and more. [View Payment Guides](/integrations/payments) ::: ::: ::: ``` ### 3. Using Breadcrumbs docmd automatically generates [Breadcrumbs](../../content/syntax/advanced.md#breadcrumbs) for every page based on your folder structure and navigation hierarchy. By using Hub Pages, you keep the sidebar focused while breadcrumbs provide context and an easy way to navigate back up the hierarchy. ## Trade-offs Using Hub Pages can add an extra "click" for users to reach deep content. However, this is usually preferable to a cluttered sidebar that makes discovery difficult. The trade-off is a cleaner, more professional interface that improves overall searchability and focus. --- ## [Scalable Folder Structure](https://docs.docmd.io/guides/scaling-architecture/scalable-folder-structure/) --- title: "Scalable Folder Structure" description: "How to organise large-scale documentation projects using the Diátaxis framework and docmd's resolution system." --- ## Problem Small documentation sites often start with a flat `docs/` folder. As projects grow to include multiple modules, APIs, and conceptual deep-dives, a disorganised folder structure becomes a significant maintenance burden. Files become difficult to locate, and the navigation sidebar becomes an overwhelming "wall of links." ## Why it matters A disorganised folder structure creates a confusing user experience, since docmd's routing and default navigation are derived from your file system. For authors, a lack of clear structure leads to content duplication and inconsistent naming. This makes documentation harder to manage as more contributors join. ## Approach We recommend adopting an information architecture framework like [Diátaxis](external:https://diataxis.fr/). It separates content into four distinct categories: Tutorials, How-To Guides, Reference, and Explanation. Mapping these categories strictly to your physical file system provides a clear roadmap for both readers and authors. ## Implementation ### 1. The Diátaxis Hierarchy Organise your source directory into semantic subfolders. This physical isolation makes it easier to manage large sets of files and ensures a clean URL structure. ```text my-project/ ├── docs/ │ ├── tutorials/ (Learning-oriented: step-by-step lessons) │ │ └── getting-started.md │ ├── guides/ (Task-oriented: solving specific problems) │ │ └── deployment.md │ ├── reference/ (Information-oriented: technical descriptions) │ │ └── api-spec.md │ ├── explanation/ (Understanding-oriented: theoretical background) │ │ └── architecture.md │ └── navigation.json (Main navigation definition) └── docmd.config.json ``` ### 2. Strategic Use of navigation.json Instead of defining a massive navigation tree in your global configuration, use `navigation.json` files within your source directories. docmd follows a [Resolution Priority](../../configuration/navigation#navigation-resolution-priority) system. This allows you to define distinct sidebar hierarchies for different sections of your site. ```json // docs/navigation.json [ { "title": "Tutorials", "icon": "book-open", "children": [ { "title": "Get Started", "path": "/tutorials/getting-started" } ] }, { "title": "Reference", "icon": "braces", "children": [ { "title": "API Specification", "path": "/reference/api-spec" } ] } ] ``` ### 3. File-Based Routing Every Markdown file's location in the folder structure determines its final URL. For example, `docs/guides/auth.md` becomes `your-site.com/guides/auth`. Use this to your advantage to create intuitive, memorable URLs. ## Trade-offs Strict organisational frameworks like Diátaxis require a clear understanding of content types. Technical writers may occasionally find it difficult to categorise a specific document. Establishing clear internal contribution guidelines is essential to maintain consistency as your team grows. --- ## [Scaling to 1000+ Pages](https://docs.docmd.io/guides/scaling-architecture/scaling/) --- title: "Scaling to 1000+ Pages" description: "How to maintain high performance and usability in massive documentation projects with docmd." --- ## Problem Documentation naturally expands as software matures. When projects grow to thousands of Markdown files, traditional generators suffer. Build times drag, hot-reloading slows, and navigation structures overwhelm maintainers and users alike. ## Why it matters If builds take minutes, authors avoid making small corrections. Content becomes stale and inaccurate. For users, a massive, unorganised sidebar menu makes finding information frustrating. This increases support tickets and degrades the developer experience. ## Approach docmd is built for speed and scalability. By using a high-performance parsing engine and a granular file-based strategy, it processes thousands of pages in seconds. Its optimised SPA delivery ensures navigation remains instantaneous for end users. ## Implementation ### 1. Granular Project Structure Avoid flat directories. Use a deeply nested folder structure that mirrors your product's architecture. This eases maintenance and allows docmd to track changes efficiently during development. ### 2. Optimised Search Indexing For large sites, the [Search Plugin](../../plugins/search.md) is essential. docmd generates a highly compressed search index loaded on demand. This keeps the initial page load fast while providing full-text search across thousands of pages. ### 3. Versioning and Archiving Use the [Versioning Engine](../../configuration/versioning.md) to separate legacy content. Isolating older versions into distinct build contexts reduces the number of pages processed during daily updates. This improves development velocity. ```json "versions": { "current": "v3", "all": [ { "id": "v3", "dir": "docs/current", "label": "v3.x (Latest)" }, { "id": "v2", "dir": "docs/v2", "label": "v2.x (Legacy)" } ] } ``` ### 4. Component-Based Navigation Break navigation into logical segments using `navigation.json` files. This lets you define distinct sidebar hierarchies for different sections, preventing main navigation clutter. ## Trade-offs A massive site naturally consumes more disk space and memory during builds. To maintain sub-second build times at extreme scales (10,000+ pages), use a high-performance CI/CD environment with SSD storage and ample RAM to handle parallel file processing. --- ## [Workspace & Monorepo Architecture](https://docs.docmd.io/guides/scaling-architecture/workspace-monorepo/) --- title: "Workspace & Monorepo Architecture" description: "How to use docmd's Workspace mode to manage multiple independent documentation projects from a single repository with zero duplication." --- ## Problem Large organisations maintain documentation for multiple independent products - an SDK, a CLI tool, and a main platform - each with its own versioning, navigation, and release cycle. Running separate documentation sites for each product creates duplication: separate CI pipelines, separate theme configs, separate deployment jobs. ## Why it matters Fragmented documentation is hard to maintain and confusing for users. If the SDK docs look different from the platform docs, users lose confidence. If every project needs its own CI job, your engineering overhead scales with the number of products. A unified workspace solves both problems with a single config file. ## Approach Use docmd's **Workspace mode**. Define all projects in a single root `docmd.config.json`. Set global defaults (theme, menubar, logo) once. Each project inherits them and may override what it needs. One build command produces a single deployable directory. ## Implementation ### 1. Repository Structure ```text my-org-docs/ ├── assets/ ← shared logo, favicon, global CSS ├── main-docs/ ← prefix: / │ ├── docmd.config.json │ └── docs/ ├── sdk-docs/ ← prefix: /sdk │ ├── docmd.config.json │ └── docs/ ├── cli-docs/ ← prefix: /cli │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← workspace root └── package.json ``` ### 2. Root Workspace Config Define global settings once. All projects inherit these automatically. ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Platform Docs" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK Reference" }, { "prefix": "/cli", "src": "cli-docs", "title": "CLI Reference" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg", "alt": "My Org" }, "menubar": [ { "text": "Platform", "url": "/" }, { "text": "SDK", "url": "/sdk" }, { "text": "CLI", "url": "/cli" } ] } ``` ### 3. Per-Project Config Each project only specifies what differs from the root. This example for the SDK project adds OpenAPI support and sets its own `title`: ```json { "title": "SDK Reference", "src": "docs", "plugins": { "search": {}, "openapi": {}, "git": { "repo": "https://github.com/my-org/sdk" } }, "versions": { "current": "v2", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (Stable)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x (Legacy)" } ] } } ``` The global `theme`, `logo`, and `menubar` from the root config are still applied. The SDK project just adds its own plugins and versions on top. ### 4. Build & CI Build the entire workspace with a single command: ```bash npx @docmd/core build ``` For CI/CD, a minimal GitHub Actions workflow: ```yaml name: Deploy Docs on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: path: site/ deploy: needs: build runs-on: ubuntu-latest environment: name: github-pages steps: - uses: actions/deploy-pages@v4 ``` Or generate the workflow automatically: ```bash npx @docmd/core deploy --github-pages ``` ### 5. Per-Project Targeted Dev Rebuilds During development, file changes trigger targeted rebuilds for the affected project only: ```bash npx @docmd/core dev ``` - Changing a file in `sdk-docs/docs/` only rebuilds the SDK project. - Changing the root `docmd.config.json` triggers a full workspace rebuild. - Changing a shared `assets/` file rebuilds all projects. ### 6. Project Switcher The built-in Project Switcher lets users navigate between projects without leaving the documentation site. It is automatically populated from the `projects` array in the root config. Each entry's `title` field is used as the display label. ```json "switcher": { "enabled": true, "position": "sidebar-top" } ``` Available positions: `sidebar-top` (default), `sidebar-bottom`, `options-menu`. ## Trade-offs ### Build Time Building 3 projects takes roughly 3× the time of a single project. For very large workspaces (10+ projects), consider splitting into separate CI jobs that publish to a shared CDN path. ### Prefix Conflicts If your root project has a folder named `sdk/` and you also define a project with `prefix: "/sdk"`, the prefixed project wins. The engine emits a warning. Review your directory structure before adding new prefixes. ### Shared Navigation A global `navigation` array in the root config is useful as a fallback. However, each project should ideally maintain its own `navigation.json` for precise control. See [Navigation Configuration](../../configuration/navigation.md). --- ## [Fast & Accurate Search](https://docs.docmd.io/guides/search/fast-accurate-search/) --- title: "Fast & Accurate Search" description: "How docmd optimises search indexing for speed and accuracy, even in large-scale documentation projects." --- ## Problem As documentation grows, the compiled search index can become large. A monolithic index file blocks the browser's main thread during download and parsing. This delays the "Time to Interactive" and causes the search interface to feel sluggish. ## Why it matters The primary goal of documentation search is "Time to Answer". If a user waits several seconds for the index to load, the tool's utility is lost. Fast, accurate search results are essential for providing a professional developer experience. ## Approach docmd utilises an optimised indexing strategy powered by a high-performance search library. It employs **Scoping**, **Incremental Loading**, and **Field Optimisation** to ensure search results are delivered instantaneously, regardless of site size. ## Implementation ### 1. Scoped Search Indices docmd automatically generates separate search indices for every [Locale](../../configuration/localisation/index.md) and [Version](../../configuration/versioning.md). Users only download the index relevant to their current context. For example, a user browsing the Chinese version only downloads the Chinese search index, significantly reducing payload size. ### 2. Intelligent Field Stripping The [Search Plugin](../../plugins/search.md) lets you control exactly what content is indexed. By default, it prioritises headers and frontmatter metadata while stripping common "stop words". You can exclude specific pages from the index using the `search` property in your [Frontmatter](../../content/frontmatter.md). ```yaml --- title: "Internal Developer Guide" search: false # This page will not appear in search results --- ``` ### 3. Lazy Loading & Prefetching To keep initial page loads fast, docmd fetches the search index lazily in the background. It also triggers immediately when a user interacts with the search UI (e.g., clicking the search bar or using the `Cmd+K` / `Ctrl+K` shortcut). ### 4. Result Ranking Results are ranked based on a weighted scoring system. Keywords found in the page `title` or `h1` headers are weighted significantly higher than those in body text. This ensures the most relevant pages appear at the top. ## Trade-offs Excluding utility or internal pages from the search index makes them harder to discover. Use the `search: false` property sparingly to ensure valuable information remains findable. While lazy loading improves initial performance, users on slow connections may experience a brief delay the first time they trigger a search. --- ## [Search Relevance & Structure](https://docs.docmd.io/guides/search/improving-search-relevance/) --- title: "Search Relevance & Structure" description: "How to structure your Markdown content to improve search relevance and help users find information faster." --- ## Problem Search engines prioritise content based on structure. If a high-quality guide uses generic headers like "Introduction" or "Step 1", the search engine may not assign enough weight to core keywords. Relevant pages get buried in search results, frustrating users who expect instant answers. ## Why it matters Users typically search for specific technical terms (e.g., "authentication token" or "deployment limit") rather than full sentences. If your documentation structure doesn't emphasise these terms, the search engine cannot confidently rank your content. High search relevance prevents a high volume of support tickets. ## Approach Structure your Markdown so the search indexer automatically identifies and prioritises core concepts. docmd's search engine assigns higher weights to the page `title`, `description`, and `headers` compared to the body text. Optimising these structural elements significantly improves discoverability. ## Implementation ### 1. Optimise Frontmatter Metadata Use the [Frontmatter](../../content/frontmatter.md) block to provide explicit keywords and a descriptive summary. The [Search Plugin](../../plugins/search.md) indexes these fields to provide better results and useful snippets in the search UI. ```yaml --- title: "AWS S3 Storage Configuration" description: "How to configure IAM roles and bucket permissions for AWS S3 integration." keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. Use Semantic Headers Avoid generic header names. Include relevant keywords in your headers to provide context for both the user and the search engine. * **Low Relevance:** `## Step 1: Configuration` * **High Relevance:** `## Step 1: Configuring AWS IAM Roles` ### 3. Use Callouts for Key Information Using [Callout Containers](../../content/containers/callouts.md) for critical warnings or "Pro Tips" improves search relevance. Content within callouts is semantically isolated and weighted differently by the indexer to highlight important troubleshooting steps. ## Trade-offs Optimising for search relevance requires disciplined writing. As your product evolves, keywords in frontmatter become outdated if not reviewed regularly. In addition, including too many keywords in headers (keyword stuffing) makes documentation feel repetitive and unnatural. Aim for a balance between SEO and readability. --- ## [Local-First Search Optimisation](https://docs.docmd.io/guides/search/local-first-search/) --- title: "Local-First Search Optimisation" description: "How to optimise your documentation content for docmd's high-performance, client-side search engine." --- ## Problem Local-first search engines run entirely in the browser. They provide instant results without a server round-trip. However, they are constrained by browser memory and processing limits. An unoptimised search index consumes excessive RAM. This causes the browser tab to stutter or crash, especially on mobile devices. ## Why it matters A seamless search experience is essential for productivity. If the search tool causes performance issues or memory bloat, users abandon it. Optimising content for local-first search ensures documentation remains fast, responsive, and reliable across all devices and network conditions. ## Approach docmd's [Search Plugin](../../plugins/search.md) uses a build-time extraction pipeline to create an optimised index. By pruning unnecessary data and focusing on high-value semantic fields, the resulting index is comprehensive and lightweight. ## Implementation ### 1. Build-Time Extraction During the build process, docmd processes Markdown files to extract relevant text for indexing. It automatically strips out: * HTML tags and structural boilerplate. * Markdown syntax characters that lack semantic value. * Formatting-only elements that bloat the index. This ensures the indexer only receives clean, meaningful text, reducing the final index size significantly. ### 2. Strategic Indexing with Frontmatter Use [Frontmatter](../../content/frontmatter.md) to explicitly control how a page is indexed. If a page contains repetitive data (like raw JSON logs) that aren't useful for search, index only the headers and metadata. ```yaml --- title: "API Log Reference" search: indexBody: false # Only index the title and headers --- ``` ### 3. Client-Side Memory Management docmd manages the search index lifecycle carefully in the browser. It uses an on-demand loading strategy. The search engine is only initialised when the user first interacts with it. This keeps the initial page load footprint small and conserves system resources. ## Trade-offs Aggressively pruning content from the search index (e.g., excluding large code blocks) can cause missing niche results. You must balance the need for a lightweight index with thorough search coverage. We recommend prioritising headers and conceptual descriptions, as these are the most common search targets. --- ## [Semantic Search Integration](https://docs.docmd.io/guides/search/semantic-search/) --- title: "Semantic Search Integration" description: "How to configure and deploy client-side hybrid semantic search in docmd using local vector embeddings." --- ## Problem Traditional full-text search relies entirely on exact keyword matches. If a user searches for "authentication" but the page only uses terms like "OAuth2" or "login", a standard keyword search engine will fail to find it. This forces writers to perform unnatural keyword-stuffing and leaves readers frustrated when they cannot find what they need. ## Why it matters Modern developers expect natural language interfaces that understand intent, synonyms, and context. Implementing server-side semantic search typically requires setting up complex infrastructure like vector databases (e.g., Pinecone or pgvector), hosting models, and building APIs, which increases maintenance overhead, monthly hosting costs, and introduces security and privacy concerns. ## Approach Use docmd's native **Semantic Search Plugin**. It operates entirely client-side using a highly optimised browser runtime. It generates structured vector chunk indices at build time using local Hugging Face model pipelines, then re-ranks matches using hybrid BM25 keyword frequency and vector cosine similarity. No data is ever sent to third-party APIs. ## Implementation ### 1. Enable Semantic Search in Configuration Add the `search` plugin options within your `docmd.config.json`. Configure `semantic` to `true` and enable `showConfidence` to visually identify semantic matching in search results: ```json { "plugins": { "search": { "semantic": true, "showConfidence": true } } } ``` ### 2. Choose the Right Embedding Model docmd supports both lightweight English-only models and comprehensive multilingual models. Update your model profile using `docmd-search --settings` or define it explicitly: | Model ID | Dimensions | Size | Languages | Best For | | :--- | :---: | :---: | :--- | :--- | | `Xenova/all-MiniLM-L6-v2` | 384 | ~90 MB | English only | Fast, high-accuracy English docs | | `Xenova/LaBSE` | 768 | ~470 MB | 100+ languages | Absolute best multilingual quality | | `Xenova/paraphrase-multilingual-MiniLM-L12-v2` | 384 | ~220 MB | 50+ languages | Excellent multi-language balance | ### 3. Pre-Building Index in CI/CD To prevent overhead in the browser during first-load, pre-generate the search chunks during your build or CI/CD pipeline using the CLI: ```bash # Build the semantic search index npx docmd-search --build # Run docmd build afterwards npx @docmd/core build ``` This generates highly optimised static Vecto-JSON chunks in `.docmd-search/`. When a user performs a search, the client progressively loads these chunks in the background, keeping the UI instantly interactive. ## Trade-offs ### Initial Asset Size Client-side vector embeddings require the browser to download a WebAssembly runtime and the pre-trained ONNX model file on the first search. Although these assets are persistently cached in the browser's Cache Storage, the first-load search latency may be slightly higher on slower connections (~1-2 seconds delay). ### Search Quality vs Payload Size Choosing larger models like `LaBSE` offers exceptional multilingual quality but results in larger downloads. For standard international documentation websites, the `paraphrase-multilingual-MiniLM-L12-v2` model is the recommended sweet spot between accuracy and network payload. --- ## [Git-Based Workflows](https://docs.docmd.io/guides/workflows-teams/git-based-workflows/) --- title: "Git-Based Workflows" description: "How to manage documentation contributions effectively using Git, Pull Requests, and automated CI/CD checks." --- ## Problem Allowing direct pushes to the main branch leads to broken links and unverified information. However, imposing too much friction - like requiring separate CMS accounts - discourages community members and internal developers from contributing. ## Why it matters Collaboration is the lifeblood of great documentation. If a developer finds a typo, they should be able to submit a fix in minutes. A Git-based workflow provides a familiar, transparent, and secure environment for contributions. It ensures every change is reviewed and validated before it goes live. ## Approach Implement a "Pull Request" (PR) model supported by automated validation and preview environments. docmd is designed for this workflow. It operates on standard Markdown files that are easy to diff, review, and merge using familiar Git tools. ## Implementation ### 1. Enable "Edit this Page" Links You can configure docmd to generate "Edit this page" links via the [Git Plugin](../../plugins/git.md). This allows users to jump directly from a documentation page to the corresponding source file in your repository. ```json "plugins": { "git": { "repo": "https://github.com/my-org/my-repo", "branch": "main", "editLink": true } } ``` ### 2. Contextual Reviews with Threads For complex updates requiring detailed feedback, use the [Threads Plugin](../../plugins/threads.md). This allows authors and reviewers to leave inline comments directly within the Markdown content during the review phase, keeping discussions contextualised. ```markdown ::: thread "Reviewer Name" Should we include a code example for the new authentication flow here? ::: ``` ### 3. Automated Validation in CI Integrate docmd into your CI/CD pipeline (e.g., [GitHub Actions](../../guides/integrations/github-actions-cicd.md)) to validate every PR. At a minimum, your pipeline should run the build command to ensure no syntax errors or broken configurations are introduced. ```bash # In your CI pipeline npm install npx @docmd/core build ``` ## Trade-offs Strict Git workflows can occasionally slow down minor updates, such as fixing a typo or updating a service status notice. For high-velocity teams, we recommend designating "Documentation Owners" who have authority to fast-track small changes while maintaining rigorous review standards for significant updates. --- ## [Maintaining Consistency](https://docs.docmd.io/guides/workflows-teams/maintaining-consistency/) --- title: "Maintaining Consistency" description: "How to ensure a unified voice and professional quality across large documentation teams using linting and standardised patterns." --- ## Problem In large teams, every technical writer has a different style. Some use bold text for emphasis; others use italics. Some prefer "Click the button"; others use "Select the option". Over time, documentation becomes a patchwork quilt of conflicting styles. This makes it harder for users to parse information and reduces professional trust. ## Why it matters Consistency breeds familiarity. When users learn complex APIs or workflows, they rely on consistent vocabulary and structural patterns to navigate effectively. A unified voice makes documentation feel like a cohesive, high-quality product, building confidence in the software itself. ## Approach Enforce consistency mechanically using [Standardised Containers](../../content/containers/index.md) and automated linting tools. Automating low-level style and syntax checks frees human editors to focus on the high-level quality, accuracy, and clarity of the content. ## Implementation ### 1. Use Standardised docmd Patterns Encourage all contributors to use docmd's built-in thematic containers instead of manual Markdown formatting. This ensures every warning, tip, or note looks and behaves identically across the entire site. ```markdown <!-- ❌ Avoid: inconsistent and unstyled --> **Note:** Please restart the service. <!-- ✅ Use: consistent, accessible, and thematic --> ::: callout info Please restart the service. ::: ``` Using [Callouts](../../content/containers/callouts.md) ensures your documentation maintains a professional appearance and meets accessibility standards without extra effort. ### 2. Implement Prose Linting Integrate tools like **Vale** or **Markdownlint** to enforce brand terminology, tone, and grammar. These tools automatically check for passive voice, biased language, or incorrect product spelling. ```ini # .vale.ini example MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. Automated Enforcement in CI/CD Include consistency checks in your [GitHub Actions](../../guides/integrations/github-actions-cicd.md) or other CI/CD pipelines. This ensures every Pull Request is audited for style and structural consistency before it can be merged. ```bash # Example CI step for linting - name: Lint Documentation run: vale docs/ ``` ## Trade-offs Strict linting can discourage community contributors if they face multiple "style errors" for a simple typo fix. We recommend setting your linter's sensitivity to `warning` for external contributions and reserving `error` status for internal team updates. This balances consistency with inclusivity. --- ## [Previewing Changes](https://docs.docmd.io/guides/workflows-teams/previewing-changes/) --- title: "Previewing Changes" description: "How to set up local and cloud-based preview environments to ensure your documentation renders perfectly before it goes live." --- ## Problem Writing Markdown without a live preview leads to formatting errors, broken containers, and incorrect image paths. These only become visible once the content is in production. This results in a frustrating user experience and forces maintainers to push hotfixes for rendering issues. ## Why it matters High-quality documentation is essential for developer trust. A broken warning box or unrendered syntax looks unprofessional and misleads users. Seeing the "real" documentation before it goes live is the best way to catch errors, improve readability, and ensure a seamless user experience. ## Approach Implement a multi-stage preview strategy: use docmd's [Local Development](../../getting-started/quick-start.md#local-development) server for immediate feedback while writing, and use ephemeral cloud environments (like Vercel or Cloudflare Pages) for final reviews within your Pull Requests. ## Implementation ### 1. Instant Local Previews The fastest way to see your changes is by running the `npx @docmd/core dev` server. It features Hot Module Replacement (HMR). This automatically refreshes your browser the moment you save a Markdown file. ```bash # Start the local development server npx @docmd/core dev ``` ### 2. Cloud-Based Preview Environments For collaborative reviews, configure your CI/CD platform to generate unique "Preview URLs" for every Pull Request. Since docmd outputs standard static files, it is compatible with all major hosting providers. * **Build Command**: `npx @docmd/core build` * **Output Directory**: `site` This allows reviewers to see exactly how changes look and behave in a production-like environment before merging them into the main branch. ### 3. Collaborative Reviews with Threads Combine your cloud previews with the [Threads Plugin](../../plugins/threads.md). This allows team members to leave feedback directly on the rendered preview page. It bridges the gap between the source Markdown and the final user experience. ## Trade-offs Building a full static site for every commit in a massive repository can be time-consuming and costly in terms of CI/CD resources. To optimise this, configure your CI pipeline to only trigger a documentation build when files within your source directory (e.g., `/docs`) have been modified. --- ## [Setting Up a Workflow](https://docs.docmd.io/guides/workflows-teams/setting-up-workflow/) --- title: "Setting Up a Workflow" description: "How to establish a high-velocity, multi-author documentation workflow using docmd and docs-as-code principles." --- ## Problem When teams lack a structured workflow, updates are delayed or forgotten. Without a clear process, content becomes fragmented and formatting becomes inconsistent. Technical writers spend more time resolving merge conflicts than writing high-quality content. ## Why it matters Without a formal process, documentation quickly becomes outdated. If updating documentation requires waiting on a slow software release cycle, guides will remain out of sync with product features. This leads to user frustration and increased support volume. ## Approach Decouple documentation deployments from software release cycles. Adopt the same reliable processes used in software engineering (Branches → Pull Requests → CI/CD Previews). docmd's lightweight nature allows teams to treat "documentation as code" with minimal overhead. ## Implementation ### 1. Repository Strategy Choose the strategy that best fits your organisational structure: * **Monorepo Strategy**: Keep a `/docs` folder within your main application repository. This ensures documentation changes merge in the same Pull Request as the code they describe. * **Separate Repository Strategy**: Best for large organisations or open-source projects where a dedicated team manages documentation independently. ### 2. Validation with CI/CD Integrate docmd into your CI/CD pipeline to ensure every update is technically sound. At a minimum, your pipeline should run the build command to check for syntax errors and configuration issues. ```bash # Example validation step in GitHub Actions - name: Validate Documentation run: npm install && npx @docmd/core build ``` See the [GitHub Actions Guide](../../guides/integrations/github-actions-cicd.md) for detailed setup instructions. ### 3. Collaborative Review Process Establish a culture of peer review for all documentation updates. Use Pull Requests to discuss changes, verify formatting, and ensure technical accuracy. Use the [Threads Plugin](../../plugins/threads.md) to facilitate discussions directly on the rendered content. ## Trade-offs Adopting a "docs-as-code" workflow can create a barrier for non-technical contributors who may find Git and Markdown intimidating. To mitigate this, consider using GitHub's built-in web editor for minor fixes. Alternatively, use the [Live Preview](../../content/live-preview.md) feature to provide a visual and intuitive authoring experience. --- ## [Versioning Workflows](https://docs.docmd.io/guides/workflows-teams/versioning-release-workflows/) --- title: "Versioning Workflows" description: "How to synchronise documentation releases with software deployment using docmd's versioning engine and promotion strategies." --- ## Problem Synchronising software releases with corresponding documentation updates is a coordination challenge. Frequently, documentation updates on the live site before new code deploys (confusing current users) or delays several days (frustrating early adopters). ## Why it matters Desynchronisation between software behaviour and its documentation causes developer friction. For documentation to be effective, it must strictly map to the software version the user is running. Providing correct context for every version ensures smooth onboarding and troubleshooting. ## Approach Isolate active development documentation using docmd's [Versioning Engine](../../configuration/versioning.md). This allows your team to draft content for upcoming features asynchronously in a separate directory (e.g., `docs-next/`). Promote it to "Stable" status only when the official software release occurs. ## Implementation ### 1. Structure Your Directories Maintain your stable documentation in the primary `docs/` folder. Create a dedicated directory for the upcoming release. ```text project-root/ ├── docs/ # Current Stable (v1.x) ├── docs-v2/ # Upcoming Release (v2.0) └── docmd.config.json ``` ### 2. Configure Versions Register both versions in your configuration. Label the upcoming version as "Beta" or "Next" to signal its status to users through the version switcher. ```json "versions": { "current": "v1.0", "all": [ { "id": "v1.0", "dir": "docs", "label": "v1.x (Stable)" }, { "id": "v2.0", "dir": "docs-v2", "label": "v2.0 (Beta)" } ] } ``` ### 3. The Promotion Process When you are ready to officially release the new version: 1. **Update Config**: Change the `current` version ID in `docmd.config.json` to `v2.0`. 2. **Update Labels**: Remove the "(Beta)" tag from the `label` in the `all` array. 3. **Archive Old Docs**: Keep the `v1.0` entry in the `all` array so users on older versions can still access relevant documentation. ## Trade-offs ### Maintenance Overhead Maintaining multiple versions of documentation requires discipline. If a critical typo or security warning is fixed in the stable version, ensure it is also applied to the upcoming version directory to prevent regressions. ### SEO and Search Multiple versions can occasionally lead to search results pointing to older documentation. Use the `seo` plugin and proper canonical tags to ensure the "Current" version is always prioritised by search engines. See [Handling Breaking Changes](../scaling-architecture/breaking-changes-deprecations.md) for more details. --- ## [docmd docs: deploy production-ready docs from Markdown](https://docs.docmd.io/) --- title: "docmd docs: deploy production-ready docs from Markdown" description: "Build production-ready documentation from Markdown in seconds. Zero setup, fast by default, SEO-friendly, and AI-ready." titleAppend: false --- ::: hero # docmd Markdown to production docs in one command. Static HTML for SEO. SPA for speed. AI-ready by default. ::: button "Get Started" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#24292e icon:github ::: ## Overview docmd is a zero-configuration documentation generator. It creates premium, high-performance static websites directly from your Markdown files. ```bash npx @docmd/core dev ``` Run this single command. The engine automatically builds your site, generates navigation, and enables instant search. ## Core Capabilities Everything needed for world-class documentation ships built-in. No complex plugins required for the essentials. ::: grids ::: grid ::: card "Instant Setup" icon:rocket Start immediately without boilerplate. The engine auto-detects files and structures navigation in seconds. ::: ::: ::: grid ::: card "AI Optimised" icon:brain-circuit Generates `llms.txt` and `llms-full.txt` automatically. Keep your documentation digestible for AI models. ::: ::: ::: grid ::: card "Local-First Search" icon:search Fast, client-side full-text search powered by MiniSearch. Works out of the box across versions and locales. ::: ::: ::: grid ::: card "Live Previews" icon:monitor Embed interactive, editable code sandboxes directly into your pages for real-time experimentation. ::: ::: ::: grid ::: card "Flexible Theming" icon:palette Switch between built-in themes or apply custom styling. Fully supports dark mode and system preferences. ::: ::: ::: grid ::: card "Native Translation" icon:globe First-class i18n support. Features locale-first routing, individual search indexes, and translated UI strings. ::: ::: ::: ::: callout info "Rich Content Containers" icon:info Go beyond standard Markdown. Use structured visual patterns like steps, tabs, cards, grids, and callouts directly in your text. ::: button "Explore Containers" ./content/containers/index.md icon:blocks ::: --- ## [Migrating from Docusaurus](https://docs.docmd.io/migration/docusaurus/) --- title: "Migrating from Docusaurus" description: "A comprehensive guide on moving your Docusaurus v2/v3 project to docmd." --- # Migrating from Docusaurus to docmd Docusaurus is a popular React-based documentation framework. docmd provides a fast, zero-config alternative. It compiles significantly faster and doesn't require React components to render rich features. ## Step 1: Run the Migration Engine Run the following command at the root of your existing Docusaurus project: ```bash npx @docmd/core migrate --docusaurus ``` ### What Happens Automatically 1. **Backup**: Your entire project (excluding `node_modules` and `.git`) is safely moved into a new `docusaurus-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for docmd to use. 3. **Config Generation**: A `docmd.config.json` is generated, extracting your site `title` from your Docusaurus configuration. ## Step 2: Test the Setup Once the command finishes, you can immediately preview your Markdown content in docmd: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration Docusaurus has complex programmatic configurations that docmd does not try to guess. You must map these manually. ### 1. Navigation Setup Docusaurus sidebars are often auto-generated or configured in `sidebars.js`. **Action required:** Create a `navigation.json` inside your new `docs/` directory to structure your docmd sidebar. See the [Navigation Guide](../configuration/navigation.md). ### 2. Replacing MDX Components Docusaurus relies heavily on MDX (`.mdx`) to render custom React components. docmd is purely Markdown-driven and does not use React. **Action required:** Convert any custom `<MyReactComponent />` tags into standard Markdown or use docmd's native [Containers](../content/containers/callouts.md). #### Example: Converting Admonitions **Docusaurus:** ```markdown :::tip My Tip This is a helpful tip. ::: ``` ::: callout success "Zero Changes Required" Docusaurus admonition syntax works **without any modification**. The following aliases are fully supported: - `:::note` → renders as `callout info` - `:::tip` → renders as `callout tip` - `:::info` → renders as `callout info` - `:::caution` → renders as `callout warning` - `:::danger` → renders as `callout danger` Spaceless syntax is also supported. Your existing Docusaurus admonitions will render correctly in docmd without changes. ::: **docmd native syntax** (optional, provides more features like custom icons): ```markdown ::: callout tip "My Tip" This is a helpful tip. ::: ``` #### Example: Converting Tabs **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> This is an apple. </TabItem> <TabItem value="orange" label="Orange"> This is an orange. </TabItem> </Tabs> ``` **docmd:** (Convert to the native docmd tabs container syntax) ```markdown ::: tabs == tab "Apple" This is an apple. == tab "Orange" This is an orange. ::: ``` ### 3. Localisation (i18n) If you used Docusaurus's `i18n` features, your translated files were likely in `i18n/locale/docusaurus-plugin-content-docs/current/`. **Action required:** Move these files into docmd's directory structure (`docs/en/`, `docs/es/`, etc.) and configure the locales in `docmd.config.json`. See the [Localisation Guide](../configuration/localisation/index.md). ## Next Steps - Explore the [Layout & UI](../configuration/layout-ui.md) settings to match your Docusaurus theme. - Convert React-based hero headers into docmd [Hero Containers](../content/containers/hero.md). --- ## [Migrating from MkDocs](https://docs.docmd.io/migration/mkdocs/) --- title: "Migrating from MkDocs" description: "A comprehensive guide on moving your MkDocs (or Material for MkDocs) project to docmd." --- # Migrating from MkDocs to docmd MkDocs is a popular Python-based generator. docmd provides a similar Markdown-first experience. It relies on Node.js/Bun for incredibly fast builds without complex Python extensions. ## Step 1: Run the Migration Engine Run the following command at the root of your existing MkDocs project: ```bash npx @docmd/core migrate --mkdocs ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `mkdocs-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for docmd to use. 3. **Config Generation**: A `docmd.config.json` is generated, extracting your `site_name` from `mkdocs.yml`. ## Step 2: Test the Setup Once the command finishes, preview your content in docmd: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration MkDocs uses `mkdocs.yml` to define site navigation and extensions. You must translate this setup to docmd manually. ### 1. Navigation Setup In MkDocs, navigation is strictly defined in the `nav` key of `mkdocs.yml`. **Action required:** Create a `navigation.json` inside your `docs/` folder. **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "Home", "path": "/" }, { "title": "Guide", "collapsible": true, "children": [ { "title": "Setup", "path": "/setup" }, { "title": "Usage", "path": "/usage" } ] } ] ``` ### 2. Replacing Python Markdown Extensions If you used "Material for MkDocs", you likely relied on Python Markdown extensions for tabs or admonitions. **Action required:** Convert MkDocs-specific extension syntax to docmd's native [Containers](../content/containers/callouts.md). #### Example: Converting Admonitions **MkDocs (PyMdown):** ```markdown !!! note "Optional Title" This is an admonition content block. ``` ::: callout warning "Manual Conversion Required" MkDocs uses `!!!` syntax for admonitions, which differs from docmd's `:::` syntax. You must convert these manually or use a find-and-replace tool. **Mapping:** - `!!! note` → `::: callout info` or `:::note` - `!!! tip` → `::: callout tip` or `:::tip` - `!!! warning` → `::: callout warning` or `:::warning` - `!!! danger` → `::: callout danger` or `:::danger` - `!!! example` → `::: callout info` ::: **docmd:** ```markdown ::: callout info "Optional Title" This is an admonition content block. ::: ``` #### Example: Converting Tabs **MkDocs (SuperFences):** ```markdown === "Tab 1" Content for tab 1. === "Tab 2" Content for tab 2. ``` **docmd:** ```markdown ::: tabs == tab "Tab 1" Content for tab 1. == tab "Tab 2" Content for tab 2. ::: ``` ## Next Steps - docmd has native search. You do not need to configure a search plugin. - Explore the [Theming options](../theming/customisation.md) to customise colours to match your old Material theme. --- ## [Migration Overview](https://docs.docmd.io/migration/overview/) --- title: "Migration Overview" description: "Learn how to easily migrate your existing documentation to docmd." --- # Migrating to docmd docmd provides a fully automated **migration engine**. Transition from legacy platforms with a single command. The engine eliminates the tedious work of moving Markdown files and restructuring directories. ## How It Works The migration command will: 1. **Detect** your existing configuration file (e.g., `docusaurus.config.js`, `mkdocs.yml`). 2. **Extract** core metadata like your site's `title`. 3. **Backup** your existing files and directories safely into a `*-backup/` directory. 4. **Copy** your Markdown content into the standard docmd `docs/` directory. 5. **Generate** a fresh `docmd.config.json` tailored for your content. You can then run `npx @docmd/core dev` immediately to see your content rendered. ## What is Migrated | Feature | Migrated Automatically? | | :--- | :--- | | **Markdown Files** | ✅ Yes, all `.md` and `.mdx` files are moved to `docs/` | | **Directory Structure** | ✅ Yes, your folder nesting is preserved | | **Site Title** | ✅ Yes, extracted from your config | | **Container Syntax** | ✅ Yes, VitePress/Docusaurus containers work without changes | | **Navigation / Sidebar** | ⚠️ **No**, requires manual mapping | | **Localisation (i18n)** | ⚠️ **No**, requires manual mapping | | **Versioning** | ⚠️ **No**, requires manual mapping | | **Custom React/Vue Components** | ❌ No, these must be replaced with docmd Containers | ::: callout success "Container Syntax Compatibility" Container syntax from **VitePress** (`:::tip`, `:::warning`, `:::danger`, `:::info`, `:::details`) and **Docusaurus** (`:::note`, `:::caution`) works without modification. Your existing admonitions and collapsible sections render correctly in docmd. **MkDocs** uses `!!!` syntax, which requires manual conversion to `:::` format. ::: ## Why Navigation and i18n Aren't Automatically Migrated Every platform handles navigation sidebars, translations, and multi-versioning differently. For example, Docusaurus uses complex JavaScript objects. MkDocs relies on strictly indented YAML structures. Rather than risking a broken migration by guessing complex configurations, docmd moves your content safely. You must configure navigation, localisation, and versioning natively using docmd's JSON-based APIs. - **Navigation:** Learn how to create a `navigation.json` in the [Navigation Setup](../configuration/navigation.md). - **Localisation:** See the [Localisation Guide](../configuration/localisation/index.md) for setting up multi-language docs. - **Versioning:** Refer to the [Versioning Setup](../configuration/versioning.md). ## Supported Platforms Select your current platform for specific migration instructions: - [Migrating from Docusaurus](./docusaurus.md) - [Migrating from MkDocs](./mkdocs.md) - [Migrating from VitePress](./vitepress.md) - [Migrating from Astro Starlight](./starlight.md) --- ## [Migrating from Astro Starlight](https://docs.docmd.io/migration/starlight/) --- title: "Migrating from Astro Starlight" description: "A comprehensive guide on moving your Astro Starlight project to docmd." --- # Migrating from Astro Starlight to docmd Starlight is a documentation theme built on Astro. docmd provides a similar zero-JavaScript-by-default experience. It eliminates the need to configure a full web framework, reducing the learning curve. ## Step 1: Run the Migration Engine Run the following command at the root of your existing Starlight project: ```bash npx @docmd/core migrate --starlight ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `starlight-backup/` directory. 2. **Content Migration**: Starlight keeps documentation in `src/content/docs/`. The migration engine extracts this directory and moves its contents to the root `docs/` folder. 3. **Config Generation**: A `docmd.config.json` is generated, extracting your site `title` from the Starlight integration inside `astro.config.mjs`. ## Step 2: Test the Setup Once the command finishes, preview your content in docmd: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration ### 1. Navigation Setup Starlight defines navigation in `astro.config.mjs` via the `sidebar` array. **Action required:** Create a `navigation.json` inside your new `docs/` folder. **Starlight (`astro.config.mjs`):** ```javascript sidebar: [ { "label": "Guides", "items": [ { "label": "Setup", "link": "/guides/setup/" } ] } ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. Replacing Astro Components (MDX/Markdoc) Starlight uses Astro components embedded via MDX or Markdoc. Because docmd relies on pure Markdown syntax, these must be converted. **Action required:** Replace Astro components with docmd [Containers](../content/containers/callouts.md). #### Example: Converting Tabs **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### Example: Converting Asides (Admonitions) **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter Mapping Starlight has strict frontmatter typing via Astro content collections. docmd frontmatter is simpler. If you used `hero` or `banner` frontmatter properties in Starlight for landing pages, replace them with docmd's [Hero Sections](../content/containers/hero.md) written directly in the Markdown body. ## Next Steps - Explore docmd's built-in [Search plugin](../plugins/search.md). Starlight uses Pagefind, while docmd ships with a highly optimised local search indexer natively. --- ## [Migrating from VitePress](https://docs.docmd.io/migration/vitepress/) --- title: "Migrating from VitePress" description: "A comprehensive guide on moving your VitePress project to docmd." --- # Migrating from VitePress to docmd VitePress is a fast Vue-powered SSG framework. docmd is equally fast, but it ships zero JavaScript framework logic to the client. This eliminates Vue hydration overhead. ## Step 1: Run the Migration Engine Run the following command at the root of your existing VitePress project: ```bash npx @docmd/core migrate --vitepress ``` ### What Happens Automatically 1. **Backup**: Your entire project is safely moved into a new `vitepress-backup/` directory. 2. **Content Migration**: Your `docs/` folder is restored to the root directory for docmd to use. The `.vitepress` hidden configuration folder is completely stripped to prevent conflicts. 3. **Config Generation**: A `docmd.config.json` is generated, extracting your site `title` from `.vitepress/config.js` or `.ts`. ## Step 2: Test the Setup Once the command finishes, preview your content in docmd: ```bash npx @docmd/core dev ``` Your Markdown files will compile, but your navigation sidebar will be empty. ## Step 3: Manual Configuration VitePress configures navigation in its config file and uses Vue components inside Markdown. You must translate these to docmd. ### 1. Navigation Setup VitePress uses an array of objects in `themeConfig.sidebar`. **Action required:** Create a `navigation.json` inside your `docs/` directory. **VitePress (`.vitepress/config.js`):** ```javascript themeConfig: { "sidebar": [ { "text": "Guide", "items": [ { "text": "Introduction", "link": "/introduction" }, { "text": "Getting Started", "link": "/getting-started" } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. Replacing Vue Components VitePress allows authors to embed Vue components directly in Markdown files. Because docmd does not run Vue on the client, you must remove custom components or replace them with native Markdown. **Action required:** Replace Vue-specific UI components with docmd [Containers](../content/containers/callouts.md). #### Example: Admonitions (Custom Containers) VitePress uses a markdown-it custom block syntax that looks similar to docmd. **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` ::: callout success "Zero Changes Required" VitePress container syntax works **without any modification**. The following aliases are fully supported: - `:::tip` → renders as `callout tip` - `:::warning` → renders as `callout warning` - `:::danger` → renders as `callout danger` - `:::info` → renders as `callout info` - `:::details` → renders as `collapsible` Spaceless syntax is also supported. Your existing VitePress content will render correctly in docmd without changes. ::: ## Next Steps - Explore docmd's [Build & Deploy](../deployment/index.md) guide. docmd does not rely on Vite's build pipeline. - Review the full list of [docmd Containers](../content/containers/index.md) for additional UI components. --- ## [Analytics Plugin](https://docs.docmd.io/plugins/analytics/) --- title: "Analytics Plugin" description: "Integrate Google Analytics 4 or legacy Universal Analytics and track user interactions automatically." --- The `@docmd/plugin-analytics` plugin allows you to easily integrate Google Analytics into your documentation. It supports the modern Google Analytics 4 (GA4) standard, legacy Universal Analytics (UA), and includes native event tracking for interaction-heavy documentation sites. ## Configuration Enable analytics by adding your tracking credentials to the `plugins` section of your `docmd.config.json`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `googleV4` | `object` | `null` | Google Analytics 4 configuration (requires `measurementId`). | | `googleUA` | `object` | `null` | Universal Analytics configuration (requires `trackingId`). | | `autoEvents` | `boolean` | `true` | Automatically track clicks, downloads, and TOC interactions. | | `trackSearch` | `boolean` | `true` | Track search keywords used by readers. | ### Example ```json { "plugins": { "analytics": { "googleV4": { "measurementId": "G-XXXXXXX" }, "autoEvents": true, "trackSearch": true } } } ``` ## Tracked Events When `autoEvents` is enabled, the plugin automatically captures the following user interactions: - **External Links**: Track when users depart for external resources. - **File Downloads**: Log clicks on links with the `download` attribute or common file extensions. - **Table of Contents (TOC)**: Monitor section engagement by tracking clicks in the right-hand navigation. - **Heading Anchors**: Log when users click on "permalinks" to share specific sections. - **Search Queries**: Capture keywords used in the search bar (with a 1-second debounce). ::: callout info "Privacy & GDPR" By default, this plugin does not anonymise IP addresses as that is now handled natively by GA4. If you require advanced cookie consent management, you can manually inject scripts using a custom plugin hook. ::: --- ## [Building Plugins](https://docs.docmd.io/plugins/building-plugins/) --- title: "Building Plugins" description: "A comprehensive guide to extending docmd with custom logic, data injection, and interactive features." --- Plugins are the primary extension mechanism for docmd. They allow you to inject HTML, modify Markdown parsing, inject build-time data, and automate post-build tasks. This guide outlines the plugin API. ## Plugin Descriptor Every plugin must export a `plugin` descriptor declaring its identity and capabilities. This enables the engine to validate and isolate boundaries at load time. ```javascript "plugin": { "name": "my-analytics", "version": "1.0.0", "capabilities": ["head", "body", "post-build"] }, "generateScripts": (config, opts) => { ... }, "onPostBuild": async (ctx) => { ... } ``` > **Note:** The descriptor is strictly required. Plugins without it will fail to load. ## Core Capabilities The `capabilities` array dictates which hooks your plugin is allowed to use. | Capability | Allowed Hooks | Phase | | :--- | :--- | :--- | | `init` | `onConfigResolved` | Init | | `markdown` | `markdownSetup` | Setup | | `head` | `generateMetaTags`, `generateScripts` (head) | Render | | `body` | `generateScripts` (body) | Render | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeBuild`, `onBeforeRender`, `onPageReady` | Build | | `post-build`| `onPostBuild` | Post-Build | | `dev` | `onDevServerReady` | Dev Server | | `assets` | `getAssets` | Output | | `actions` | `actions` | Interactive | | `events` | `events` | Interactive | | `translations`| `translations` | i18n | ## Plugin API Reference A docmd plugin is a standard JavaScript object that implements one or more of the following hooks. | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the `markdown-it` instance. Synchronous. | | `generateMetaTags(config, page, root)` | Inject `<meta>` or `<link>` tags into the `<head>`. | | `generateScripts(config, opts)` | Return an object containing `headScriptsHtml` and `bodyScriptsHtml`. | | `getAssets(opts)` | Define external files or CDN scripts to be injected. | | `onPostBuild(ctx)` | Run logic after the generation of all HTML files. | | `translations(localeId)` | Return an object of translated strings for the given locale. | | `actions` | An object of named action handlers for WebSocket RPC calls. | | `events` | An object of named event handlers for browser messages. | ## Creating a Local Plugin Creating a plugin is as simple as defining a JavaScript file. For example, `my-plugin.js`: ```javascript import path from "path"; export default { plugin: { "name": "my-plugin", "version": "1.0.0", "capabilities": ["head", "post-build"] }, markdownSetup: (md, options) => { // Add custom parser rules }, generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`Custom Plugin: Verified ${pages.length} pages.`); } }; ``` To enable your plugin, reference its **full package name** in your `docmd.config.json`: ```json "plugins": { "my-awesome-plugin": {} } ``` > **Note:** Shorthand names (e.g. `math`, `search`) are reserved for official `@docmd/plugin-*` packages. Third-party plugins must always use their full npm package name. ### Plugin Resolution The docmd engine resolves plugin names as follows: - **Official shorthands** (`math`, `search`) expand to `@docmd/plugin-<name>`. Only official packages can exist under the `@docmd` scope. - **Third-party plugins** must use their full package name (e.g. `my-awesome-plugin`, `@myorg/docmd-extras`). There is no alias system for external plugins. This eliminates supply-chain attack vectors. ### Plugin Isolation Every hook invocation is wrapped in a try/catch block. A broken plugin cannot crash the build or interfere with other plugins. Errors are logged and collected into a summary. ### Scoping Plugins (`noStyle`) Plugins inject their CSS/JS universally by default. Developers can explicitly prevent their plugin from rendering on `noStyle` pages by exporting a `noStyle` boolean: ```javascript export default { noStyle: false, generateScripts: () => { ... } } ``` Users can override this via configuration (`plugins: { math: { noStyle: false } }`) or dynamically via Markdown frontmatter (`plugins: { math: true }`). ## Lifecycle Hooks Docmd provides deep integration hooks. They allow plugins to manipulate configuration, raw sources, and page data. | Hook | Description | Expected Return | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | Reads or modifies the active config right after initialisation. | `void` or `Promise<void>` | | **`onDevServerReady(server, wss)`** | Exposes the raw Node.js server during `npx @docmd/core dev`. | `void` or `Promise<void>` | | **`onBeforeParse(src, frontmatter, filePath?)`** | Pre-processes raw markdown string data immediately before parsing. | `string` or `Promise<string>` | | **`onAfterParse(html, frontmatter, filePath?)`** | Post-processes generated HTML representing the markdown body. | `string` or `Promise<string>` | | **`onBeforeBuild(ctx)`** | Called after all markdown is parsed but before HTML generation. Used for heavy pre-computation. | `void` or `Promise<void>` | | **`onBeforeRender(page)`** | Called before template rendering. Mutations to `frontmatter` and `html` are reflected in output. | `void` or `Promise<void>` | | **`onPageReady(page)`** | Accesses fully assembled page metadata just before it is written to the destination file. | `void` or `Promise<void>` | ### Engine Acceleration & Background Tasks (`runWorkerTask`) docmd executes intensive operations via a **Pluggable Engine Architecture**. Plugins can easily offload custom heavy I/O or CPU-bound subroutines through the configured build engine (e.g., JavaScript or native Rust workers). The `runWorkerTask` method is injected transparently into `PageContext`, `PostBuildContext`, and `ActionContext`. ```javascript { "plugin": { "name": "my-plugin", "version": "1.0.0", "capabilities": ["post-build"] }, "onPostBuild": async (ctx) => { // Pass a registered engine action name or absolute script path const result = await ctx.runWorkerTask('/path/to/worker.js', 'parseData', [ctx.outputDir]); } } ``` ### Data Fetching and Indexing (`onBeforeBuild`) The `onBeforeBuild` hook runs *after* markdown parsing but *before* the HTML rendering loop begins. It is optimal for heavy data indexing or API calls. It receives the `BeforeBuildContext`, containing all `pages` and the `tui` instance. This allows plugins to show isolated progress bars. ```typescript export async function onBeforeBuild({ pages, tui }) { tui.step('Fetching remote plugin data', 'WAIT'); let processed = 0; for (const page of pages) { if (page.sourcePath) { page.frontmatter.remoteData = await fetchHeavyData(page.sourcePath); } processed++; if (processed % 10 === 0 || processed === pages.length) { tui.progress('Fetching remote plugin data', processed, pages.length); } } tui.step('Fetching remote plugin data', 'DONE'); } ``` ### `onBeforeRender` and `PageContext` Use `onBeforeRender` to inject build-time data derived from the source file. ```typescript interface PageContext { sourcePath: string; frontmatter: Record<string, any>; html: string; localeId?: string; versionId?: string; relativePathToRoot?: string; runWorkerTask<T = any>(modulePath: string, functionName: string, args: any[]): Promise<T>; } ``` ```javascript export default { plugin: { name: "my-metadata-plugin", version: "1.0.0", capabilities: ["build"] }, onBeforeRender: async (page) => { const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } } ``` ## Deep Dive: Asset Injection The `getAssets()` hook allows your plugin to bundle client-side logic securely. ```javascript export default { getAssets: (options) => { return [ { url: "https://example.com/script.js", type: "js", location: "head" }, { src: path.join(__dirname, "plugin-init.js"), dest: "assets/js/plugin-init.js", type: "js", location: "body" } ]; } } ``` ## Translating Plugins (i18n) Plugins rendering client-side UI should expose strings via the `translations(localeId)` hook. The engine merges these with core strings automatically. The standard pattern stores a JSON file for each language in an `i18n/` directory: ```javascript import fs from "fs"; import path from "path"; export default { plugin: { name: "my-plugin", version: "1.0.0", capabilities: ["translations", "body"] }, translations: (localeId) => { try { const p = path.join(__dirname, "i18n", `${localeId}.json`); return JSON.parse(fs.readFileSync(p, "utf8")); } catch { } return {}; } } ``` ## WebSocket RPC Actions Plugins can register **action handlers** and **event handlers** that run on the dev server. They are callable from the browser via the `window.docmd` API. ```javascript export default { plugin: { name: "my-live-plugin", version: "1.0.0", capabilities: ["actions", "events"] }, actions: { "my-plugin:save-note": async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + "\n\n> " + payload.note; await ctx.writeFile(payload.file, updated); return { "saved": true }; } }, events: { "my-plugin:page-viewed": (data, ctx) => { console.log(`Page viewed: ${data.path}`); } } }; ``` The `ctx` (ActionContext) provides: | Method | Description | | :--- | :--- | | `ctx.readFile(path)` | Read a file relative to the project root. | | `ctx.writeFile(path, content)` | Write a file (triggers rebuild + reload). | | `ctx.readFileLines(path)` | Read a file as an array of lines. | | `ctx.broadcast(event, data)` | Push an event to all connected browsers. | | `ctx.runWorkerTask(module, fn, args)` | Offload heavy CPU tasks to the worker pool. | | `ctx.source` | Source editing tools for block-level markdown manipulation. | | `ctx.projectRoot` | Absolute path to the project root. | | `ctx.config` | Current docmd site configuration. | All file operations are sandboxed to the project root. ::: callout info "Dev Mode Only 🛡️" The WebSocket RPC system is only active during `npx @docmd/core dev`. Production builds do not include the API client or server-side action handling. ::: ## Best Practices 1. **Declare Capabilities**: Always export a `plugin` descriptor with declared capabilities. 2. **Use `onBeforeRender` for data injection**: If your plugin computes frontmatter fields, use `onBeforeRender`. 3. **Async/Await**: Always use `async` functions for `onPostBuild`, `onBeforeRender`, and action handlers. 4. **Statelessness**: Avoid maintaining state within the plugin object. The engine may re-initialise plugins dynamically. 5. **Naming Convention**: Prefix community package names with `docmd-plugin-`. 6. **Action Namespacing**: Prefix action names with your plugin name (e.g., `my-plugin:save-note`). 7. **Action Validation**: Define and require an explicit payload schema in your actions. 8. **Logging**: Use the provided `log()` helper in `onPostBuild` to respect user verbosity settings. ::: callout tip "AI-Ready Design 🤖" The docmd plugin API is **LLM-Optimal**. Because the hooks use standard JavaScript objects, AI agents can generate bug-free plugins with minimal instruction. ::: --- ## [Git Plugin](https://docs.docmd.io/plugins/git/) --- title: "Git Plugin" description: "Repository-aware metadata, last-updated timestamps, and automated edit links derived from Git history." --- The `@docmd/plugin-git` plugin adds repository intelligence to your documentation. It extracts data directly from Git history at build time. It displays when a page was last modified, who contributed, and provides an optional "Edit this page" link. ## Configuration | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | Repository URL (e.g. `https://github.com/org/repo`). Required for edit links. | | `branch` | `string` | `'main'` | Branch name for edit links. | | `editLink` | `boolean` | `true` | Show "Edit this page" link when `repo` is set. | | `lastUpdated` | `boolean` | `true` | Show last updated timestamp. | | `commitHistory` | `boolean` | `true` | Show commit history tooltip on hover. | | `maxCommits` | `number` | `6` | Maximum commits to show in the tooltip (if `commitHistory` is true). | | `dateFormat` | `string` | `'relative'` | Timestamp format: `relative` (default), `iso`, or `locale-aware`. | ### Example ```json { "plugins": { "git": { "repo": "https://github.com/org/repo", "branch": "main", "editLink": true, "lastUpdated": true, "commitHistory": true, "maxCommits": 5 } } } ``` ## Features - **Last Updated Timestamps**: Automatically shows when a page was last modified in the footer. - **Commit History Tooltip**: Hovering over the timestamp reveals recent commits for that specific page. - **Automated Edit Links**: Provides a link to edit the source file on GitHub, GitLab, or Bitbucket. - **Performance-First**: Git history is queried once and cached at build time. This ensures zero impact on site performance. ## Behaviour Once configured, the plugin works automatically. Timestamps and edit links appear in the page footer. ### Footer Example ::: callout info "Rendering Result" The footer of this page is rendered by the Git plugin. Scroll to the bottom to see it in action. Hover over the **Last updated** date to see the commit history. ::: ## Per-Page Control Disable Git features for specific pages via frontmatter: ```markdown --- title: "Internal Notes" plugins: git: false --- ``` ## CI/CD Integration The Git plugin reads your repository history at build time using local Git commands. Many CI/CD providers use "shallow clones" by default (fetching only the last commit). This causes the plugin to show only the most recent change across all pages. To ensure accurate timestamps and history, configure your CI environment to perform a full fetch. ::: tabs == tab "GitHub Actions" Add `fetch-depth: 0` to your checkout step: ```yaml - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 ``` == tab "GitLab CI" Set the `GIT_DEPTH` variable to `0`: ```yaml variables: GIT_DEPTH: 0 ``` == tab "Netlify" Netlify fetches the full history by default. If you encounter issues, ensure your build command has access to the `.git` directory. ::: ::: callout warning "Git Data Requirement" The `.git` directory must be present in the build environment. If building inside a Docker container or restricted CI environment, ensure Git history is preserved and the `git` binary is installed. ::: ## Localisation The plugin includes built-in translations for English, German, and Chinese. Custom strings can be provided through the [UI Localisation](../configuration/localisation/ui-strings.md) system. --- ## [LLM Context Plugin](https://docs.docmd.io/plugins/llms/) --- title: "LLM Context Plugin" description: "Optimise your documentation for AI consumption with automated llms.txt and llms-full.txt generation." --- The `@docmd/plugin-llms` plugin ensures your documentation is perfectly optimised for Large Language Models (LLMs) and AI Agents. It follows the growing industry standard of providing a high-level summary and a comprehensive context file that AI tools can ingest to understand your project with minimal hallucination. ## Configuration The LLM plugin is enabled by default. To function correctly, you must provide a `url` in your `docmd.config.json`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable the LLM context generation. | | `fullContext` | `boolean` | `true` | If true, generates a `llms-full.txt` file containing the content of all pages. | | `maxTokenLimit` | `number` | `null` | Optional limit on the total characters/tokens for context files. | ### Example ```json { "url": "https://docs.example.com", "plugins": { "llms": { "fullContext": true } } } ``` ## Generated Output Once configured, the plugin automatically generates `llms.txt` and `llms-full.txt` in your site root during every build. These files are linked in the page `<head>` for automatic discovery by AI tools. ### Excluding a Page If a page contains sensitive information or internal notes you don't want AI models to learn, use the `llms: false` flag in your frontmatter: ```markdown --- title: "Internal Dev Secrets" llms: false --- ``` ::: callout tip "Maximising AI Accuracy" For detailed best practices on structuring your markdown (semantic headings, alt-text, etc.), see our [Optimising for AI Agents](../guides/ai-optimisation/generating-ai-ready-docs.md) guide. ::: --- ## [Math Plugin](https://docs.docmd.io/plugins/math/) --- title: "Math Plugin" description: "Native KaTeX/LaTeX mathematics integration for docmd." --- The **Math plugin** adds native LaTeX and KaTeX support to your docmd sites. It uses `markdown-it-texmath` integrated with the `katex` computation engine. This renders inline and block-level equations smoothly without complex client-side javascript libraries. ## Configuration The Math plugin is an optional plugin. Install it via the CLI: ```bash npx @docmd/core add math ``` Enable it in your `docmd.config.json`: ### Example ```json { "plugins": { "math": {} } } ``` ## How It Works 1. Enable the plugin via your `docmd.config.json`. 2. Wrap your standard LaTeX mathematics in `$` (inline) or `$$` (block) indicators. 3. The engine processes these rules during the build exactly as raw static HTML tags. 4. Minimal injected CSS styles the classes automatically. This yields immediate visualisation on page load. ## Usage ### Inline Mathematics Inject standard equations within a paragraph using single dollar signs `$`: ```markdown Here is an inline equation: $E = mc^2$ ``` Here is an inline equation: $E = mc^2$ ### Block Mathematics For wider mathematical proofs or distinct formulations, use double dollar signs `$$` for block level formatting: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid Diagrams](https://docs.docmd.io/plugins/mermaid/) --- title: "Mermaid Diagrams" description: "Create professional architectural diagrams, flowcharts, and sequence diagrams directly in your Markdown files using Mermaid.js syntax." --- The `@docmd/plugin-mermaid` plugin integrates the powerful [Mermaid.js](external:https://mermaid.js.org/) engine into your documentation pipeline. It allows you to transform plain-text descriptions into high-fidelity, interactive diagrams with built-in support for themes, panning, and zooming. ## Configuration The Mermaid plugin is bundled with `@docmd/core` and enabled by default. No mandatory configuration is required. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable Mermaid diagram rendering globally. | ### Example ```json { "plugins": { "mermaid": {} } } ``` ## Features - **Theme Awareness**: Diagrams automatically adapt to **Light** or **Dark** mode transitions. - **Interactive Controls**: Built-in **Pan**, **Zoom**, and **Fullscreen** buttons for every diagram. - **Lazy Loading**: Diagrams are initialised only as they enter the user's viewport for optimum performance. - **Icon Support**: Deep integration with the **Lucide** icon pack (use `icon:name` syntax). ## Usage Embed diagrams using a fenced code block with the `mermaid` language identifier. ### Sequence Diagram Example ::: tabs == tab "Preview" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` == tab "Source" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: Enters URL Browser->>Server: HTTP Request Server-->>Browser: HTTP Response Browser-->>User: Displays Page ``` ```` ::: ### Architecture Example ```mermaid architecture-beta group api(icon:cloud)[API Service] service db(icon:database)[Database] in api service disk(icon:hard-drive)[Storage] in api db:L -- R:disk ``` ::: callout tip "AI Readability" Because Mermaid diagrams are defined as pure text in your Markdown, they are fully readable by AI agents. This allows LLMs to understand and explain your system architecture directly from your documentation source. ::: --- ## [OpenAPI Plugin](https://docs.docmd.io/plugins/openapi/) --- title: "OpenAPI Plugin" description: "Static API reference documentation rendered directly from OpenAPI 3.x specifications at build-time." --- The `@docmd/plugin-openapi` plugin converts OpenAPI 3.x specification files into structured, searchable API reference pages. It follows the Docmd "Zero-JS" philosophy - rendering every endpoint, parameter, and response into semantic HTML tables during the build process, ensuring maximum performance and SEO. ## Configuration The OpenAPI plugin is included by default in `@docmd/core`. You can configure global rendering options in your `docmd.config.json`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `info` | `boolean` | `true` | Display the API title, version, and description from the spec's `info` object. | | `download` | `boolean` | `false` | If true, adds a link to the header of the spec to download the raw JSON/YAML file. | | `summaryOnly` | `boolean` | `false` | If true, only renders the method, path, and summary. Useful for large API indexes. | | `allowRawHtml` | `boolean` | `false` | If true, prevents escaping of HTML tags in descriptions. | ### Example ```json { "plugins": { "openapi": { "info": true, "download": true, "summaryOnly": false } } } ``` ## Usage Embed an OpenAPI specification anywhere in your Markdown using a fenced code block with the `openapi` tag. The path is resolved relative to your project source. ````markdown ```openapi assets/openapi.json ``` ```` ### Rendering Result ```openapi assets/docmd-api.json ``` ## What Gets Rendered For each path and HTTP method in the spec, the plugin renders: - **Method badge** - colour-coded (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`) - **Path** - the full endpoint path with parameters highlighted - **Summary and description** - from the operation object - **Parameters table** - name, location (`path`, `query`, `header`, `cookie`), type, required flag, description - **Request body table** - schema properties with types and defaults - **Responses table** - status codes with descriptions and response schema types - **Deprecated notice** - operations marked `deprecated: true` are flagged inline ::: callout tip "Build-Time Rendering" All rendering happens at build time. The generated pages are fully static - no JavaScript is needed to display the API docs, which means fast page loads and full search indexation. This approach ensures zero-JS performance and SEO-friendliness. ::: ## Capability Support | Feature | Support | | :--- | :--- | | OpenAPI 3.x | ✓ (JSON & YAML*) | | Swagger 2.x | ✗ (Convert to 3.x first) | | `$ref` Resolution | ✓ (Internal schemas) | | `oneOf` / `anyOf` | ✓ (Shown as union types) | | `deprecated` flag | ✓ | *\*YAML support requires the `js-yaml` package to be installed in your project.* --- ## [PWA & Offline Support](https://docs.docmd.io/plugins/pwa/) --- title: "PWA & Offline Support" description: "Transform your documentation into a progressive web application with offline caching and mobile-first features." --- The `@docmd/plugin-pwa` plugin transforms your documentation into a Progressive Web App (PWA). It adds a web manifest for mobile installation and registers a service worker for intelligent offline caching. Your technical manuals remain accessible even in low-connectivity environments. ## Configuration Customise your app branding within the `plugins` section of your `docmd.config.json`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable PWA manifest and service worker generation. | | `themeColor` | `string` | `'#1e293b'` | The primary colour of the mobile UI browser chrome. | | `bgColor` | `string` | `'#ffffff'` | Background colour for the splash screen during installation. | | `logo` | `string` | `null` | Path to the app icon (relative to project source). | ### Example ```json { "plugins": { "pwa": { "themeColor": "#1e293b", "bgColor": "#ffffff", "logo": "assets/app-icon.png" } } } ``` ## Features - **Offline Caching**: Uses a "Stale-While-Revalidate" strategy. Pages serve instantly from the cache while updating in the background. - **Mobile Installation**: Generates a `manifest.webmanifest` allowing users to "Add to Home Screen" natively on iOS and Android. - **Smart Asset Resolution**: Automatically generates app icons from your project logo or favicon if no explicit icon is provided. - **SPA Compatible**: Fully compatible with Single Page Application transitions and standard directory routing. ## Icon Resolution Priority The plugin resolves your PWA icons based on the following priority: 1. `pwa.icons` - Explicit array in config. 2. `pwa.logo` - Path relative to source. 3. `config.logo` - Global site logo. 4. `config.favicon` - Global favicon. ::: callout tip "Testing PWA Features" Service workers are bypassed in `npx @docmd/core dev` to prevent caching issues during editing. To test PWA features, run `npx @docmd/core build` and serve the `site/` directory using a static host. ::: --- ## [Search Plugin](https://docs.docmd.io/plugins/search/) --- title: "Search Plugin" description: "Enable high-speed, offline-first full-text search for your documentation using MiniSearch." --- The `@docmd/plugin-search` plugin provides a powerful, client-side search experience for your documentation. It uses [MiniSearch](external:https://github.com/lucaong/minisearch) to build a lightweight index during the build process, allowing users to find technical information instantly without a server-side database. ## Configuration Search is enabled by default in most `docmd` templates. You can control its visibility and placement via the `layout` configuration. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable the full-text search indexer. | | `placeholder` | `string` | `'Search...'` | Custom placeholder text for the search input. | | `maxResults` | `number` | `10` | Maximum number of results to display in the modal. | ### Example ```json { "layout": { "optionsMenu": { "position": "header", "components": { "search": true } } } } ``` ## How It Works <img width="720" class="with-border" src="/assets/previews/search-ui-default.webp"> ### 1. Indexing (Build-time) During the `npx @docmd/core build` process, the search plugin iterates through every page on your site. It extracts the title, headings, and plain-text prose, then compiles this data into a compressed `search-index.json` file. * **Deep Linking**: The indexer automatically registers every heading (`#`, `##`, etc.) as a searchable target. * **Relevancy Boosting**: Titles are given the highest weight, followed by headings, then page content. ### 2. Retrieval (Client-side) When a user opens the search modal (usually via `/` or `Ctrl+K`), the `search-index.json` is fetched by the browser. Searches are performed locally using fuzzy matching (allowing for small typos) and instant prefix matching. ## Customising Search Behaviour Whilst the search plugin is designed for zero-config simplicity, you can exclude specific pages from the index by using the `noindex` flag in their frontmatter: ```yaml --- title: "Internal Specification" noindex: true # This page will not appear in search results or sitemaps --- ``` ## Technical Implementation The plugin injects a lightweight search modal into the `<body>` of your site. It is fully accessible (ARIA compliant) and supports keyboard navigation for a native app-like experience. ::: callout tip "Search Analytics" If you have the [Analytics Plugin](./analytics.md) enabled, search keywords used by your readers are automatically captured and sent to your analytics provider, giving you insights into what information is missing or hardest to find. ::: Because the search happens entirely on the client, no data - not even keystrokes - is ever sent to a server. This makes `docmd` the Gold Standard for documentation search in privacy-sensitive industries (Healthcare, Finance, Security). ## Comparison Many documentation generators (like Docusaurus) rely on **Algolia DocSearch**. Whilst Algolia is powerful, it introduces friction: | Feature | docmd Search | Algolia / External | | :--- | :--- | :--- | | **Setup** | **Zero Config** (Automatic) | Complex (API Keys, CI/CD crawling) | | **Privacy** | **100% Private** (Client-side) | Data sent to 3rd party servers | | **Offline** | **Yes** | No | | **Cost** | **Free** | Free tier limits or Paid | | **Speed** | **Instant** (In-memory) | Fast (Network latency dependent) | ## Semantic Search (Alpha Preview) ::: callout tip "Introducing docmd-search" We built something we're rather proud of. **`docmd-search`** is, to our knowledge, the first fully offline semantic search engine designed for documentation - and it isn't tied to docmd at all. It runs entirely in the browser, requires no server, no API keys, and sends nothing to anyone. Plug it into any documentation engine, any static site, or any webpage. It just works. This is an early alpha. Things will change, improve, and grow. But the foundation - private, offline, genuinely intelligent search - is already here. [→ View on GitHub](https://github.com/docmd-io/docmd-search) ::: > **Experimental Feature** - Semantic search is currently in alpha preview. The default keyword-based search remains the recommended option for production use. <img width="720" class="with-border" src="/assets/previews/search-ui-semantic.webp"> Semantic search uses local embeddings to understand the meaning behind queries, enabling more intelligent results beyond simple keyword matching. ### Enabling Semantic Search First, install the `docmd-search` package: ```bash npm install docmd-search ``` Then enable it in your configuration: ```json { "plugins": { "search": { "semantic": true } } } ``` ### How Semantic Search Works Unlike keyword search which matches exact terms, semantic search: * **Understands context** - A query for "authentication" finds relevant pages even if they use different terminology like "login" or "sign-in" * **Handles typos naturally** - No need for fuzzy matching; the model understands intent * **Finds related concepts** - Searching "API" returns relevant endpoint documentation, not just pages containing "API" ### Configuration Options | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `semantic` | `boolean` | `false` | Enable semantic search (requires `docmd-search` package) | | `showConfidence` | `boolean` | `false` | Display similarity confidence score badges in semantic search results | | `showFilters` | `boolean` | `true` | Show the version filter bar above search results (set `false` to hide it) | | `model` | `string` | `'Xenova/all-MiniLM-L6-v2'` | Embedding model to use | | `chunkSize` | `number` | `512` | Maximum chunk size in characters | | `chunkOverlap` | `number` | `50` | Overlap between chunks in characters | | `indexDir` | `string` | - | Path to pre-built semantic index | ### Comparison: Semantic vs Keyword | Feature | Semantic Search | Keyword Search | | :--- | :--- | :--- | | **Understanding** | Context-aware | Exact match only | | **Typo tolerance** | High | Limited (fuzzy matching) | | **Synonyms** | Yes | No | | **Setup** | Requires `docmd-search` | Built-in | | **Index size** | Larger (1–2 MB per 100 files) | Smaller | | **Privacy** | 100% Private (client-side) | 100% Private (client-side) | | **Offline** | Yes | Yes | ### Automatic Installation When `semantic: true` is enabled, the plugin automatically installs `docmd-search` and its peer dependencies (`@huggingface/transformers`, `onnxruntime-node`) if they're not already available. This works with npm, pnpm, yarn, and bun — detecting your project's package manager automatically. If the automatic installation fails (e.g., in restricted CI environments), the plugin gracefully falls back to keyword search. ### Available Models The `model` option lets you choose an embedding model. Models are downloaded once and cached locally. | Model | Size | Languages | Best For | | :---- | :--- | :-------- | :------- | | `Xenova/all-MiniLM-L6-v2` *(default)* | ~23 MB | English only | Fast, English-only documentation | | `Xenova/paraphrase-multilingual-MiniLM-L12-v2` | ~118 MB | 50+ languages | **i18n docs** (Chinese, German, French, etc.) | | `Xenova/multilingual-e5-small` | ~118 MB | 100+ languages | Wide language coverage | | `Xenova/paraphrase-multilingual-mpnet-base-v2` | ~270 MB | 50+ languages | Best multilingual quality | ::: callout info "Custom models" You can use any HuggingFace model compatible with Transformers.js. Browse at [huggingface.co/models](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) and filter by `transformers.js` library. ::: ### Fallback Behaviour If semantic search is enabled but `docmd-search` cannot be installed or found, the plugin automatically falls back to keyword search. This ensures your documentation remains searchable regardless of configuration. ::: callout warning "Alpha Limitations" Semantic search is experimental. Current limitations include: * English-only models (multilingual model available but less tested) * No incremental updates (full rebuild required) * Higher memory usage (~50–100 MB in browser) * First load may be slower as embeddings are fetched ::: ### Best Practices For optimal semantic search performance: 1. **Exclude noise** - Don't index changelogs or draft content: ```json { "plugins": { "search": { "semantic": true, "exclude": ["**/release-notes/**", "**/drafts/**"] } } } ``` 2. **Pre-build for CI/CD** - Use the `indexDir` option to pre-generate indexes: ```bash npx docmd-search --ui ``` 3. **Monitor index size** - Check the `.docmd-search/` directory size regularly 4. **Test thoroughly** - Verify search results quality before deploying to production --- ## [SEO Plugin](https://docs.docmd.io/plugins/seo/) --- title: "SEO Plugin" description: "Optimise your documentation for search engines and control AI crawler access with native meta tag generation." --- The `@docmd/plugin-seo` plugin generates high-quality metadata for every page. It ensures your documentation is not only discoverable by human readers on search engines but also correctly interpreted by AI models and social media platforms. ## Configuration Configure site-wide SEO defaults in your `docmd.config.json`. Page-level settings always take precedence over global defaults. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `defaultDescription` | `string` | `null` | Fallback description for pages without frontmatter descriptions. | | `aiBots` | `boolean` | `true` | Allow (`true`) or block (`false`) AI training bots. When `false`, blocks GPTBot, ChatGPT-User, Google-Extended, CCBot, and other AI crawlers. | | `openGraph` | `object` | `null` | Open Graph settings for social media (Facebook, LinkedIn). | | `twitter` | `object` | `null` | Twitter (X) Card settings including username and card type. | ### Example ```json { "plugins": { "seo": { "defaultDescription": "Comprehensive documentation for the docmd ecosystem.", "aiBots": false, "twitter": { "siteUsername": "@docmd_io", "cardType": "summary_large_image" } } } } ``` ## Features - **Automatic robots.txt**: Generates `robots.txt` if missing, with sitemap reference and AI bot directives. - **Smart Fallbacks**: Automatically extracts the first 150 characters of prose if no description is provided. - **AI Bot Governance**: By default, AI bots are allowed to index content. Set `aiBots: false` to block AI training bots whilst still allowing traditional search engines. - **Canonical Resolution**: Automatically generates `<link rel="canonical">` tags to prevent duplicate content issues. - **Rich Social Previews**: Native support for Open Graph and Twitter Cards for professional link sharing. - **Structured Data**: Supports LD+JSON Article Schema for rich search snippets. ## robots.txt Auto-Generation The plugin automatically generates a `robots.txt` file during the build process if one doesn't exist in your output directory. **Generated content includes:** ```txt User-agent: * Allow: / # Sitemap Sitemap: https://your-domain.com/sitemap.xml ``` **Blocking AI Training Bots:** When `aiBots: false` is set, the generated `robots.txt` includes: ```txt # Block AI training bots User-agent: GPTBot Disallow: / User-agent: ChatGPT-User Disallow: / User-agent: Google-Extended Disallow: / # ... (additional AI crawlers) ``` ### robots.txt Location Strategy The plugin intelligently handles `robots.txt` across multiple locations: **Priority Order:** 1. **Site root** (`site/robots.txt`) - Checked first, highest priority 2. **Assets folder** (`site/assets/robots.txt`) - Copied to site root if found **Behaviour:** - If `robots.txt` exists in **site root**: Preserved, no action taken - If `robots.txt` exists in **assets folder**: Automatically copied to site root (recommended location for SEO) - If `robots.txt` not found: Auto-generated based on SEO configuration **Recommended Practice:** Place your custom `robots.txt` in the `assets/` folder of your documentation source. The plugin will copy it to the site root during build: ``` your-docs/ ├── assets/ │ └── robots.txt ← Place here ├── index.md └── docmd.config.json ``` After build, it appears at the correct location: ``` site/ ├── robots.txt ← Copied here (SEO standard location) ├── assets/ │ └── robots.txt ← Also preserved here └── index.html ``` ::: callout tip "Why Site Root?" Search engines expect `robots.txt` at the domain root (`https://example.com/robots.txt`). The plugin ensures your file is always in the correct location, whether you provide a custom one or let it auto-generate. ::: ## Page-Level Overrides Fine-tune settings for individual pages using frontmatter: ```markdown --- title: "Advanced Configuration" noindex: true # Hide from all search engines seo: keywords: ["docmd", "javascript", "ssg"] aiBots: true # Override global block for this page ldJson: true # Enable Article Schema --- ``` ::: callout tip "Search Discovery" For best results, ensure your `url` is defined in the root of your configuration. Without a base URL, the plugin cannot generate absolute canonical links or social image paths. ::: --- ## [Sitemap Plugin](https://docs.docmd.io/plugins/sitemap/) --- title: "Sitemap Plugin" description: "Automatically generate a standard-compliant sitemap.xml for better search engine discovery." --- The `@docmd/plugin-sitemap` plugin generates a `sitemap.xml` file at the root of your build directory. This provides search engines with a comprehensive map of your site's architecture, ensuring that all pages - including versioned documentation - are crawled and indexed. ## Configuration Enable sitemap generation by providing your `siteUrl` in the root configuration. You can customise the crawl weight within the `plugins` object. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | Enable or disable sitemap generation. | | `defaultChangefreq` | `string` | `'weekly'` | Hint to crawlers on how often pages change. | | `defaultPriority` | `number` | `0.8` | Default weight for standard pages (0.0 to 1.0). | | `rootPriority` | `number` | `1.0` | Weight for the homepage (`index.md`). | ### Example ```json { "url": "https://docs.example.com", "plugins": { "sitemap": { "defaultChangefreq": "weekly", "defaultPriority": 0.8 } } } ``` ## Features - **Automatic URL Construction**: Intelligently resolves page paths to their canonical public URLs with clean directory structure. - **Versioned Discovery**: Automatically includes all pages from all versions (e.g. `/v1/`, `/v2/`) without manual configuration. - **Granular Exclusions**: Exclude specific pages from the sitemap using frontmatter. - **SEO Ready**: Follows standard XML sitemap protocols compatible with all major search engines. ## Page-Level Controls Override sitemap behaviour for specific pages using frontmatter: ```markdown --- title: "Archive Page" priority: 0.3 # Lower weight for legacy content changefreq: "monthly" # Hint to crawlers sitemap: false # Exclude this specific page --- ``` ::: callout tip "Validation" After building your site, you can find the sitemap at `site/sitemap.xml`. You can submit this URL directly to search engine consoles to accelerate indexing. ::: --- ## [Threads Plugin](https://docs.docmd.io/plugins/threads/) --- title: "Threads Plugin" description: "Add inline discussion threads to your documentation - stored directly in your markdown files." --- The **Threads plugin** brings collaborative inline comments to your documentation. Select text, leave a comment, and start a discussion. All threads are stored directly in your markdown source files. No database is required. Original Author: [@svallory](external:https://github.com/svallory) ::: callout info "Alpha Release" This plugin is in alpha. The API and storage format are stable. The UI remains under active development. ::: ## Configuration The Threads plugin is an optional plugin. Install it via the CLI: ```bash npx @docmd/core add threads ``` Enable it in your `docmd.config.json`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | When `true`, threads stay grouped at the bottom of the page. When `false`, threads appear inline next to highlighted text. | ### Example ```json { "plugins": { "threads": { "sidebar": true } } } ``` ## How It Works 1. **Select text** on any documentation page during `npx @docmd/core dev`. 2. A **comment popover** appears. Write your comment and submit. 3. The selected text gets **highlighted** with a thread marker. 4. Threads store as `::: threads` blocks at the bottom of the markdown file. 5. **No database** is needed. Your markdown files remain the single source of truth. ## Preview Here is what threads look like on a live page. Text with discussions gets <span class="threads-preview-highlight">highlighted like this</span>. Thread cards appear below. <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 2d ago</div> <div class="threads-preview-body">This section could use a diagram to explain the architecture. What do you think?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · 1d ago</div> <div class="threads-preview-body">Good idea - I'll add a Mermaid flowchart. Does <code>sequenceDiagram</code> work here?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 12h ago</div> <div class="threads-preview-body">Perfect. A simple flowchart would be ideal.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> Here is a <span class="threads-preview-highlight-blue">second highlight with a different colour</span>. Threads cycle through a palette of colours automatically. <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · 3d ago</div> <div class="threads-preview-body">Should we mention backward compatibility here?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> Resolved threads appear dimmed: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 5d ago  <span class="threads-preview-resolved-badge">✓ Resolved</span></div> <div class="threads-preview-body">Fixed the typo in the config example.</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ New Comment</div> </div> </div> A floating **discussion button** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span> appears in the bottom-right corner. It shows the count of open threads. Click it to jump to the first thread on the page. ## Storage Format Threads embed in your markdown using docmd's container syntax: ```markdown # My Documentation Page Some content with ==highlighted text=={t-a1b2c3d4} that has a thread. ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" This text needs clarification. ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 Updated it - does this work? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` The `==text=={threadId}` syntax links highlighted text in the document body to a specific thread. ## Features | Feature | Description | | :--- | :--- | | **Text Selection** | Select any text to start a new thread. | | **Replies** | Nested reply chains within each thread. | | **Reactions** | Emoji reactions on individual comments. | | **Edit / Delete** | Modify or remove your comments. | | **Resolve** | Mark threads as resolved with author and timestamp. | | **Author Profiles** | Git-based author detection with Gravatar support. | | **Highlight Markers** | Visual indicators showing where threads anchor. | | **Floating Button** | Quick-access FAB with open thread count. | | **Scroll Preservation** | Page stays in place after adding comments. | ## Actions API The threads plugin exposes the following actions via the WebSocket RPC system. Call these from browser plugins using `docmd.call()`: | Action | Description | | :--- | :--- | | `threads:get-threads` | Parse and return all threads from a file. | | `threads:add-thread` | Create a new thread with its first comment. | | `threads:add-comment` | Add a comment to an existing thread. | | `threads:edit-comment` | Edit an existing comment's body. | | `threads:delete-comment` | Remove a comment from a thread. | | `threads:delete-thread` | Remove an entire thread and cleanup highlights. | | `threads:resolve-thread` | Toggle resolved/unresolved status. | | `threads:toggle-reaction` | Toggle an emoji reaction on a comment. | | `threads:get-authors` | Read the author profile map. | | `threads:upsert-author` | Create or update an author profile. | ## Author Profiles Author information is stored in `<docsRoot>/.threads/authors.json`: ```json { "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } } ``` During development, the plugin automatically detects your Git username and email for author identification. ::: callout tip "Version Control Friendly" Since threads are stored in your markdown files, they are automatically version-controlled with Git. Review comments in PRs, track discussion history, and collaborate through your existing workflow. ::: --- ## [Using Plugins](https://docs.docmd.io/plugins/usage/) --- title: "Using Plugins" description: "Install, configure, and manage docmd plugins - from required defaults to optional add-ons." --- docmd features a modular plugin architecture. Required plugins ship with the core and need no installation. Optional plugins can be installed with a single CLI command. ## Installing Plugins Use the docmd CLI to install and remove plugins: ```bash # Install a plugin npx @docmd/core add <plugin-name> # Remove a plugin npx @docmd/core remove <plugin-name> ``` The installer detects your package manager (npm, pnpm, yarn, or bun). It resolves short names to full package names and injects the config into your `docmd.config.json`. Use `--verbose` (or `-V`) for full installer output: ```bash npx @docmd/core add <plugin-name> -V ``` ## Required Plugins These plugins are bundled with `@docmd/core`. No installation is needed. Enable them in your `docmd.config.json`: ```json "plugins": { "search": {}, "seo": { "aiBots": false }, "sitemap": {}, "analytics": {}, "llms": {}, "mermaid": {}, "openapi": {}, "git": {} } ``` ::: callout tip "Git Plugin" The Git plugin detects if your project is a Git repository. If not, it disables itself automatically. No configuration is required for last-updated timestamps. ::: ## Optional Plugins Optional plugins require installation before enabling. | Plugin | Install Command | Description | | :--- | :--- | :--- | | [PWA](pwa.md) | `npx @docmd/core add pwa` | Progressive Web App support with offline caching | | [Threads](threads.md) | `npx @docmd/core add threads` | Inline discussion comments stored in Markdown | | [Math](math.md) | `npx @docmd/core add math` | Native KaTeX and LaTeX mathematics rendering | ## Auto-Installation When you add an official plugin to your `docmd.config.json` without installing it, docmd automatically downloads and installs it on the next build. This works for all plugins in the official registry. ```json { "plugins": { "pwa": {} } } ``` The auto-installer: - Only targets official `@docmd/plugin-*` packages. - Installs the exact version matching your `@docmd/core` installation. - Uses your project's active package manager. - Displays progress directly in the terminal. ## Third-Party & Custom Plugins For security, the installer enforces an official registry allowlist. Third-party plugins must be installed natively using your package manager: ```bash npm install my-custom-plugin # or pnpm add, yarn add, bun add ``` After installation, add the plugin to your `docmd.config.json` using its exact package name: ```json { "plugins": { "my-custom-plugin": { "someOption": true } } } ``` If the plugin meets docmd's requirements, it activates automatically during the build. Otherwise, the engine reports an error. ## Plugin Scopes and `noStyle` Overrides Plugins inject CSS and behaviour globally. However, you can configure them to bypass specific pages or entirely disable their execution on unstyled landing pages (`noStyle: true`). ### Global Config Extent Instruct any plugin to automatically skip `noStyle` pages via your `docmd.config.json`: ```json { "plugins": { "math": { "noStyle": false } } } ``` ### Page Local Scope (Frontmatter) You can definitively enable or disable any plugin per-document via markdown frontmatter. ```markdown --- noStyle: true plugins: math: true threads: false --- # Only Math renders here, Threads are completely blocked ``` ## Plugin Lifecycle Plugins hook into different stages of the build and development process: | Hook | Description | | :--- | :--- | | `markdownSetup(md, opts)` | Extend the Markdown parser with custom rules. | | `generateMetaTags(config, page, root)` | Inject `<meta>` and `<link>` tags into the `<head>`. | | `generateScripts(config, opts)` | Inject scripts into `<head>` or `</body>`. | | `getAssets(opts)` | Define external files or CDN scripts to inject. | | `onPostBuild(ctx)` | Run logic after all HTML files finish generating. | | `translations(localeId)` | Return translated UI strings for a locale. | | `actions` | Server-side handlers callable via WebSocket RPC. | | `events` | Fire-and-forget handlers for browser-pushed events. | ## Plugin Safety The plugin system guarantees build safety: - **Validation**: Invalid plugin descriptors are rejected instantly at load time. - **Isolation**: Every hook invocation is wrapped in a try/catch block. A broken plugin cannot crash the build. - **Capability Enforcement**: Plugins can only register for explicitly declared hooks. See [Building Plugins](building-plugins.md) for the full API reference. ::: callout tip "AI-Transparent Architecture :robot:" The architecture is **deterministic**. Every meta-tag and script is traceable. AI agents can understand exactly how the site behaves without hidden side effects. ::: --- ## [docmd v0.8.0 - The Parallel Engine Era](https://docs.docmd.io/release-notes/0-8-0/) --- title: "docmd v0.8.0 - The Parallel Engine Era" description: "High-performance multi-threaded architecture, workspace support, and massive performance boosts." --- The `docmd` 0.8.0 release is a monumental architectural upgrade. We have moved from a single-threaded sequential engine to a native multi-threaded worker pool that processes pages in parallel. This release also introduces first-class **workspace support**, allowing you to manage complex documentation ecosystems under a single domain with near-instant build times. ## ✨ Highlights ### ⚡ Parallel Build Engine docmd now builds your documentation in parallel using a highly optimised `WorkerPool`. By offloading Markdown AST parsing and processor hooks into background threads, docmd fully utilises all available CPU cores. For large sites (1000+ pages), this results in **up to 10x faster builds**. ### 🏢 workspace Support You can now build multiple independent documentation projects into a single site. This is perfect for monorepos or large organisations that need to unify multiple documentation sources under one domain (e.g., `docmd.io` and `docmd.io/search`). - **Unified Output**: Each project has its own config but shares a single output directory. - **Independent Context**: Each sub-project maintains its own versioning, i18n, and plugin configurations. ### 🔌 Plugin Worker API We have exposed the internal `WorkerPool` to the entire plugin ecosystem. Plugins can now offload computationally heavy tasks (like image processing, remote indexing, or data parsing) to background threads using the new `ctx.runWorkerTask()` API. ### 📜 Persistent Git Indexing The Git plugin has been redesigned for speed. It now features a **Persistent Disk Cache** and parallel I/O processing. - **Massive Speedup**: Indexing 800+ pages now takes ~3.5s instead of ~18s on subsequent builds. - **Smart Pruning**: The cache automatically manages entries for deleted or renamed files. ### 🏠 SEO-Friendly README Routes docmd now automatically treats `README.md` as a directory index, ensuring that links like `[Guide](./guide/README.md)` resolve correctly to `/guide/`. - **Intelligent Fallback**: `index.md` is always prioritised, with `README.md` serving as a fallback if no index is present. - **Clean URLs**: Automatically strips `README` and `index` from URLs for a professional look. ### ⚙️ Modern Configuration You can now write your configuration in TypeScript or JSON. - **TypeScript Support**: Use `docmd.config.ts` with full autocompletion and type safety via `defineConfig`. - **JSON Support**: Lightweight `docmd.config.json` for environments where JavaScript execution is restricted. ### 🧜 Better Mermaid Diagrams The Mermaid plugin now features an improved UI for large diagrams. - **Refined Controls**: Zoom and pan controls have been moved to the bottom-left to prevent overlapping with content. - **Fullscreen Experience**: Fullscreen mode now includes full access to all navigation and zoom controls. ## 📝 Complete Changelog ### 🚀 Engine & Architecture - **Worker-Parser Pipeline**: The core markdown processor is now re-hydrated dynamically inside background threads. Files are read concurrently and farmed out to the workers in batches. - **AST Caching Engine**: An MD5-based caching layer intercepts unmodified files. If a file's raw content hash hasn't changed since the previous pass, the AST parsing is skipped entirely. - **Persistent Dev Workers**: During `npx @docmd/core dev`, the worker pool remains persistent across file saves. This eliminates the 200-500ms thread-startup latency commonly associated with Node.js workers, resulting in near-instant incremental rebuilds. - **Worker CPU Throttling**: The thread pool calculates the exact number of threads based on system architecture, reserving one CPU core to prevent I/O starvation and OS lockups. - **WorkerPool MaxListeners Guard**: The EventEmitter listener cap is dynamically scaled (`poolSize * 4 + 50`) to prevent spurious Node.js warnings on high-throughput builds with 900+ pages. ### 🔌 Plugin System - **`onBeforeBuild` Lifecycle Hook**: A new dedicated "Data Indexing" phase allows plugins to fetch heavy data (like Git logs or remote APIs) and display a progress bar *before* HTML generation begins. This guarantees the core render loop remains purely synchronous and lightning-fast. - **`runWorkerTask` API**: Exposed directly on the plugin contexts (`onBeforeBuild`, `onBeforeRender`, `onPostBuild`, `actions`, `events`) for generic script execution in the background. - **Git Plugin Persistent Cache**: The Git plugin now runs in the new `onBeforeBuild` hook and utilises a reliable persistent disk cache (`.docmd/cache/git-history.json`). This completely eliminates redundant `git log` shell subprocesses on subsequent builds, dropping the build time of large repositories (800+ pages) from ~18 seconds down to just ~3.5 seconds. - **Git Plugin Parallel I/O**: Git metadata syncing now processes pages in parallel batches (concurrency of 10). Since `git log` is async I/O, this yields ~5-10x faster cold-start indexing on large sites compared to sequential processing. - **Git Cache Auto-Pruning**: The disk cache automatically removes stale entries for deleted or renamed files during each save, preventing unbounded cache growth over time. - **Search Index Worker Offload**: When a WorkerPool is available, the CPU-intensive MiniSearch tokenization and indexing is offloaded to a worker thread via `runWorkerTask`, keeping the main thread free for other post-build tasks. - **Decoupled API Imports**: Plugins can now import `fsUtils`, `WorkerPool`, and `getGitRoot` directly from `@docmd/utils`. ### 🖥️ Terminal Interface - **TUI Progress Bars**: Exposing the `@docmd/tui` engine directly to plugin contexts. The Git and Search plugins now render highly stable, in-place progress bars during their indexing phases to clearly separate data-fetching latency from raw build speed. ### ⚙️ Infrastructure & Tooling - **Centralised Git Context**: Internal Git branch detection and repository root parsing (`getGitRoot`) have been extracted into the safe utilities boundary. - **Modern Config Candidates**: Added `docmd.config.ts` and `docmd.config.json` to the default configuration search path. - **JSON-serialisable Configs**: Continued transition towards zero-config architecture by ensuring the resolved config object is fully JSON-serialisable. ## ⚠️ Breaking Changes - **Utility Imports**: Custom plugins relying on core relative imports must migrate to `@docmd/utils`. - **Serialisable Hooks**: `markdownSetup` hooks must be serialisable for cross-thread instantiation. ## Migration Guide Upgrade by running `npm install @docmd/core@latest`. Most sites will see immediate performance gains without any configuration changes. See [Installation](../getting-started/installation) for a full walkthrough. --- ## [docmd v0.8.1 - Engine Architecture & Git Cache Fixes](https://docs.docmd.io/release-notes/0-8-1/) --- title: "docmd v0.8.1 - Engine Architecture & Git Cache Fixes" description: "Pluggable engine architecture (preview), persistent git indexing, navigation fixes, and JSON config standardisation." --- ::: callout danger **This release is deprecated.** Version 0.8.1 contains a packaging defect that causes `npm install` to fail with an `EUNSUPPORTEDPROTOCOL` error. All changes and fixes have been carried forward to [v0.8.2](./0-8-2.md). Please upgrade immediately. ::: docmd v0.8.1 introduces a pluggable engine architecture, major improvements to git indexing performance, and important fixes for SPA navigation. ## ✨ Highlights ### Pluggable Engine Architecture (Preview) docmd now supports a pluggable engine system. The new `@docmd/engine-rust` package provides a foundation for accelerated I/O operations, designed to work easily with existing plugins. ```json { "engine": "rust" } ``` The engine is **optional** - the default JavaScript engine handles all workloads. The Rust engine provides measurable gains for large repositories (1000+ files) where git indexing and batch file operations dominate build time. **Architecture highlights:** - **Pluggable design**: Engines are packages under `@docmd/engine-*`, following the same pattern as plugins - **Bundled pre-built binaries**: All supported platform binaries are now delivered via a single centralised `@docmd/engine-rust-binaries` package - **Lazy loading**: Native binaries are only loaded when the engine is explicitly selected - **Plugin-compatible**: Plugins can use the engine API for accelerated I/O - **Automatic fallback**: If the native binary isn't available, the JS engine takes over transparently **Available engine packages:** | Package | Description | |---------|-------------| | `@docmd/engine-js` | Default JavaScript engine (always available) | | `@docmd/engine-rust` | Rust engine loader (orchestrates native acceleration) | | `@docmd/engine-rust-binaries` | Centralised native binary distribution for all platforms | ::: callout info "Preview Status & Platform Support" The Rust engine is in preview. In the initial **v0.8.1 rollout**, pre-compiled native binaries are exclusively published for **macOS ARM64 (Apple Silicon)** platforms within the binaries package. Builds executed on other architectures automatically and transparently fallback to the high-performance JS engine. Internal benchmarks show a **~25% improvement on cold builds** and **~17% on warm builds** for an 886-page workspace site. ::: ### Git Indexing: Persistent Disk Cache The git plugin now **persists indexing results to disk** across builds. Previously, git metadata was re-indexed from scratch on every build - even when no files had changed. The new cache system: - Routes cache storage cleanly to your operating system's isolated temporary directory (`os.tmpdir()`), preventing top-level directory clutter. - Secures cache retrieval persistently across directory renames or moves by generating a reliable hash anchored to your repository's Git tracking URL or unique OS inode identifiers. - Supports configurable storage paths via the new `tmp` configuration parameter. - Works with **both** engine paths (Rust and JS) and the `execFile` fallback. - Provides **~45% faster warm builds** on the official documentation site (886 pages). ### Configurable `tmp` Directory By default, docmd now routes internal state and build caches to your system's isolated temporary folder to keep your project root clean. For environments that require persistent caching in specific locations (e.g., CI/CD pipelines with cache-key requirements), you can now configure the full storage path using the new `tmp` key: ```json { "src": ".", "out": "site", "tmp": ".docmd-cache" } ``` This allows you to anchor the `.docmd/` state folder to any directory, ensuring it can be easily cached and restored across build sessions. ### JSON Configuration Standard Starting with v0.8.0, `docmd.config.json` is the recommended configuration format. All v0.8 documentation has been updated to use JSON examples. The `.js` and `.ts` formats remain fully supported as fallbacks for dynamic configuration logic. ## 🐛 Bug Fixes ### External Links in SPA Navigation Fixed an issue where external links defined in `navigation.json` with `external: true` were incorrectly resolved as relative paths after navigating to another internal page via the SPA router. The links now correctly preserve their absolute URLs during client-side navigation. ### Navigation External Link Shorthand The `external:` prefix, previously available only in Markdown content, now works in `navigation.json` as a convenient shorthand: ```json [ { "title": "GitHub", "path": "external:https://github.com/docmd-io/docmd" } ] ``` This is equivalent to: ```json [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ### Git Cache Directory Stability & Relocation Fixed a bug where the git plugin's disk cache was written to shifting directories during workspace builds. The cache has been cleanly relocated out of the project root directory directly into `os.tmpdir()` using a persistent repository identifier, fully supporting the custom `tmp` override path parameter. ### Engine Configuration Respected The git plugin now respects the `engine` configuration key. Previously, it always attempted to load the Rust engine first regardless of configuration. Setting `"engine": "js"` now correctly forces the JavaScript engine. ## 📝 Complete Changelog ### 🚀 Engine & Architecture - **Pluggable Engine System**: New `Engine` interface in `@docmd/api` for build acceleration - **JS Engine Package**: Default engine extracted to `@docmd/engine-js` - **Rust Engine Ecosystem**: Native Rust acceleration with centralised binary distribution via `@docmd/engine-rust-binaries` - **Engine Loader API**: `loadEngine()` and `registerEngine()` for custom engine registration - **Engine Config Key**: New `engine` key in `docmd.config.json` to select build engine - **Engine Prominence**: Elevated top-level logging prominence for custom build engines inside TUI layouts ### ⚡ Performance - **Git Disk Cache**: Engine-path results now persisted to disk for warm builds - **Persistent Identification**: Dual-mode cache identification using Git remote URL hashing and OS inode fallback - **Configurable Storage**: Added support for overriding cache destination via the `tmp` config parameter - **Config Resolvers**: Added seamless detection support for standard JSON config files in workspace sub-project loops - **Disk Cache Pre-warming**: Build pipeline reads disk cache before engine/subprocess calls ### 🐛 Bug Fixes - **SPA Router**: External links in sidebar navigation now correctly preserved during client-side navigation - **Navigation Config**: `external:` prefix now supported as shorthand in `navigation.json` - **Link Resolution**: Fixed URL resolution edge case for protocol-relative URLs - **Git Plugin**: Now respects the `engine` configuration key instead of always defaulting to Rust - **workspace Cache**: Relocated state storage to deterministic temporary OS structures to prevent loss between loop boundaries --- ## [docmd v0.8.2 - Patch Release](https://docs.docmd.io/release-notes/0-8-2/) --- title: "docmd v0.8.2 - Patch Release" description: "Patched dependency protocol errors and updated release automation." --- This is a critical patch release that resolves installation issues for users using `npm` and standardises the monorepo's internal dependency resolution. ### 🚀 Highlights #### Fixed `npm install` Compatibility Resolved a critical issue where packages published to the NPM registry contained unresolved `workspace:` protocol references in their `optionalDependencies`. This caused `npm install` to fail with an `EUNSUPPORTEDPROTOCOL` error. The publishing pipeline has been updated to ensure all dependency types are correctly resolved to semver ranges. ### 🛠 Improvements & Fixes - **Publishing Pipeline**: Fixed `scripts/resolve-ws-deps.js` to correctly transform `optionalDependencies` during the release process. - **Dependency Standardisation**: Updated all internal package references to ensure consistency across the ecosystem. - **Workflow Optimisation**: Updated GitHub Actions to use stable runner configurations for reliable binary generation. ### 📦 Package Updates All packages in the `@docmd` ecosystem have been bumped to `v0.8.2` to ensure full compatibility and lock-step versioning. For a full list of architectural changes introduced in the v0.8 series, please refer to the [v0.8.1 Release Notes](./0-8-1.md). --- ## [docmd v0.8.3 - Workspaces & Enhanced Security](https://docs.docmd.io/release-notes/0-8-3/) --- title: "docmd v0.8.3 - Workspaces & Enhanced Security" description: "Introduced the new Workspace architecture with configuration cascading, a premium Project Switcher, and major security hardening." --- docmd v0.8.3 is a major architectural update that introduces **Workspaces**, enabling centralised management of multiple documentation projects. This release also prioritises **Security & Stability** with hardened rendering across the ecosystem and improved routing reliability. ### ✨ Highlights #### 🚀 Workspaces Architecture The multi-project system has been completely reimagined as **Workspaces**. You can now manage multiple independent documentation projects from a single root configuration with powerful new capabilities: - **Global Configuration Cascading**: Define your `theme`, `menubar`, `navigation`, and `logo` at the root to apply them across all projects automatically. - **Premium Project Switcher**: A new slim UI component for seamless navigation between projects, supporting multiple positions (`sidebar-top`, `sidebar-bottom`, and `options-menu`). - **Flexible Overrides**: Projects can selectively override global defaults in their own local configuration. - **Backward Compatibility**: Existing multi-project configurations are automatically normalised to the new workspace schema. #### 🛡️ Enhanced Security & Stability This release introduces a series of internal improvements to harden the documentation engine and its plugins against edge-case rendering issues: - **Hardened Rendering**: Systematically replaced `innerHTML` usage with secure DOM APIs (`createElement`, `DOMParser`) across the core and plugins. - **Universal Security Audit**: The monorepo Failsafe pipeline now includes a specialised, AST-based security audit to detect and block unsafe DOM patterns (`innerHTML`, `outerHTML`, `document.write`) before any release. - **Improved Search Safety**: Search results now use a more reliable rendering pipeline to ensure content is always handled securely. - **Dev Server Isolation**: Enhanced directory traversal protection in the local development server for improved environment isolation. ### 🛠 Improvements & Fixes #### Auto-Designated Index Normalisation Fixed a bug in the Zero-Config auto-router where files designated as directory indexes (when no `index.md` is present) failed to render correctly due to a trailing slash mismatch. The engine now correctly normalises these paths, ensuring stable routing and correct `index.html` generation for all auto-indexed directories. #### Routing Stability Improved path predictability in the Auto-Router to resolve trailing slash inconsistencies in directories without a dedicated index file. #### TUI Pipeline & Workspace Build Clarity Refined the terminal output (TUI) for multi-project Workspace builds. Build logs are now consistently structured into strict sections (`Data Indexing`, `Publishing`, etc.) across both standalone and workspace builds, preventing overlapping text, looping spinners, and disconnected status messages. #### UI Sidebar Adjustments Fixed a layout bug where dropdown menus (Version, Language, and Project Switchers) inside the sidebar would get cropped by the sidebar's bounding box. These menus now securely render over the main content area and dynamically align to the sidebar width, preventing them from overflowing the browser viewport. ### 📦 Package Updates - **Node.js Types**: Updated `@types/node` to `v25.8.0`. - **GitHub Actions**: Updated CI/CD workflows to latest stable versions for improved reliability. ### 📝 Complete Changelog #### 🚀 New Features - **Core Engine**: Introduced `workspace` schema for centralised project management. - **UI Components**: Added `project-switcher` partial and event delegation logic. - **Config Loader**: Implemented global default merging and `menubar` item aliasing (`title`/`path`). - **Pipeline**: Integrated a static-analysis Security Audit into the Universal Failsafe V5.0 to enforce strict DOM safety standards across all packages. #### 🐛 Bug Fixes - **Threads Plugin**: Hardened comment rendering and metadata escaping by moving to DOMParser. - **Search Plugin**: Improved results rendering and data attribute safety, replacing innerHTML. - **Icon Renderer**: Hardened icon attribute rendering for SVG icons. - **Tabs Component**: Improved attribute safety in tab navigation items. - **Core Engine**: Fixed path normalisation for auto-designated index files in the generator. - **Routing**: Removed implicit index designation in the Auto-Router to improve path predictability. - **Dev Server**: Enhanced path validation for static file serving. - **UI Assets**: Removed `overflow: hidden` from sidebar and refactored positioning contexts to prevent cropped dropdown menus. - **CLI / TUI**: Fixed dangling status messages and unclosed UI sections during workspace and dev builds. #### 🚀 Infrastructure - **Refactoring**: Renamed workspace engine to `workspace.ts` and refactored terminology across the monorepo. - **Dependencies**: Bumped `@types/node` from 25.7.0 to 25.8.0. - **Workflows**: Updated GitHub Actions group to latest versions. --- ## [v0.8.4 - Deployer & Security](https://docs.docmd.io/release-notes/0-8-4/) --- title: "v0.8.4 - Deployer & Security" description: "Release notes for docmd v0.8.4 - modular deployer package, markdown line break control, security hardening, and stability fixes." date: "2026-05-18" --- ### ✨ Highlights This release introduces the new Deployer V2 system, alongside improvements to plugin safety, build reliability, and development workflows. ### Deployment targets The deployment engine has been extracted into a dedicated `@docmd/deployer` package with provider-based deployment targets. You can now generate deployment files directly for GitHub Pages, Vercel, and Netlify: ```bash docmd deploy --github-pages docmd deploy --vercel docmd deploy --netlify ``` Generated files automatically inherit values from your `docmd.config.json`, including the output directory, site URL, SPA routing, and Node.js version. Existing deployment targets for Docker, Nginx, and Caddy continue to work unchanged. ### Markdown line breaks A new `markdown.breaks` option has been added to `docmd.config.json`. Set this to `false` to disable automatic markdown line breaks and preserve wrapped markdown formatting. ```json { "markdown": { "breaks": false } } ``` ### Changelog 1. **Deployer**: Extracted the deployment engine into `@docmd/deployer` with native support for GitHub Pages, Vercel, and Netlify targets. 2. **Markdown formatting**: Added the `markdown.breaks` configuration option to control automatic soft-wrap line breaks (#137, #127). 3. **Installer security**: Restricted plugin installs to the official npm registry and replaced unsafe shell-based execution paths. 4. **Threads plugin**: Disabled raw HTML rendering inside thread comments whilst preserving standard markdown formatting (#136). 5. **Build reliability**: The parser and build lifecycle now exit with non-zero status codes on plugin failures, improving CI pipeline behaviour (#134). 6. **Developer experience**: Reduced development server noise during hot reloads and added `filePath` arguments to parser lifecycle hooks (#135). 7. **UI updates**: Refined the version switcher with Lucide icons and aligned Project Switcher dropdown styles with the standard theme menus. 8. **Bug fixes**: Fixed project-switching cache overlaps, translation fetch issues on `noStyle` pages, and copy-code icon hover states. ### Thanks 💖 Thanks to all contributors, testers, and issue reporters who helped improve this release. Special thanks to security researchers for coordinating responsible disclosures. Documentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [v0.8.5 - Semantic Search Alpha & SEO Enhancements](https://docs.docmd.io/release-notes/0-8-5/) --- title: "v0.8.5 - Semantic Search Alpha & SEO Enhancements" description: "Release notes for docmd v0.8.5 - semantic search alpha preview, SEO plugin robots.txt auto-generation, Mermaid C4Context fix, and config upgrade CLI." date: "2026-05-31" --- ### ✨ Highlights This release introduces semantic search as an alpha preview, adds automatic `robots.txt` generation in the SEO plugin, fixes Mermaid C4Context rendering, and includes a new config upgrade command for modernising existing projects. ### Semantic Search (Alpha Preview) docmd now supports semantic search powered by local embeddings, enabling context-aware search results beyond simple keyword matching. **Features** - Context-aware search beyond exact keyword matches - Natural typo tolerance - Finds related content even when different terminology is used - Fully local processing with no external services or API calls Enable semantic search by adding `semantic: true` to your configuration: ```json { "plugins": { "search": { "semantic": true } } } ``` The search plugin automatically installs `docmd-search` and downloads required models, if failed to do so, it falls back to keyword search. **Documentation** - https://docs.docmd.io/plugins/search/#semantic-search-alpha-preview > **Note:** This is an alpha preview. Multilingual models are available, but broader testing and optimisation are still ongoing. ## Introducing Offline Semantic Search Engine (docmd-search) We're excited to introduce **docmd-search**. ```bash npm install docmd-search ``` docmd-search is a semantic search engine built for documentation sites. It runs entirely in the browser or CLI, requires no servers or API keys, and keeps all processing local. Although created for docmd, it can be integrated into other documentation platforms, websites, and web applications. This is an early alpha release and will continue to evolve, but the foundation is already in place. **GitHub:** https://github.com/docmd-io/docmd-search **Documentation:** https://docs.docmd.io/search/ ## SEO Plugin: robots.txt Auto-Generation The SEO plugin now automatically generates a `robots.txt` file during the build process if one does not already exist. **Features** - Smart defaults with `User-agent: *` and `Allow: /` - Automatic sitemap references when `config.url` is configured - Optional AI crawler controls - Existing `robots.txt` files are never overwritten ```json { "plugins": { "seo": { "aiBots": false } } } ``` By default AI crawlers are allowed. Setting `aiBots: false` adds directives for GPTBot, ChatGPT-User, Google-Extended, CCBot and other supported AI crawlers. ## Mermaid C4Context Fix C4Context diagrams now render correctly instead of appearing as blank white boxes. The issue was caused by a missing SVG namespace generated by Mermaid when rendering C4Context diagrams. docmd now automatically injects the required namespace before parsing, ensuring these diagrams render correctly. Thanks to @sinsombat for the fix and accompanying test suite. ## Config Upgrade Command A new `--upgrade` flag has been added to the `docmd migrate` command. ```bash npx @docmd/core migrate --upgrade ``` Running the command automatically updates older configuration files to the modern schema. The following legacy keys are migrated automatically: | Legacy Key | Modern Key | |------------|------------| | `projects` | `workspace.projects` | | `siteTitle` | `title` | | `siteUrl` / `baseUrl` | `url` | | `srcDir` / `source` | `src` | | `outputDir` | `out` | | `defaultLocale` | `i18n.default` | Existing values are preserved during migration. ## TOC HTML Entity Decoding Heading text containing special characters such as `<`, `>`, `&`, and smart quotes now displays correctly in the Table of Contents sidebar. Previously, these characters appeared as raw HTML entities instead of their intended representation. ## Changelog ### New Features 1. Added alpha preview support for semantic search via `docmd-search`. 2. Added automatic `robots.txt` generation to the SEO plugin. 3. Added `search.showFilters` to hide the version filter bar above search results. 4. Added `search.showConfidence` to display semantic search confidence percentages. 5. Added right-aligned search result metadata for versions and confidence badges. ### Bug Fixes 1. Fixed Mermaid C4Context diagrams rendering as blank white boxes. 2. Fixed Live Editor template rendering crash caused by early `workspace` access. 3. Fixed HTML entity decoding in the Table of Contents. 4. Fixed excessive dev server reloads caused by duplicate `fs.watch` events on macOS. ### Improvements 1. Added `docmd migrate --upgrade` for automated configuration modernisation. 2. Restyled the Project Switcher to align with the appearance and language controls. 3. Config and `navigation.json` changes now trigger fast targeted rebuilds instead of full restarts. 4. The dev server now automatically opens the documentation URL in the default browser on startup. ### Thanks 💖 Thanks to all contributors, testers, and issue reporters who helped improve this release. Documentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [v0.8.6 - AI-First Integration, MCP & Docker](https://docs.docmd.io/release-notes/0-8-6/) --- title: "v0.8.6 - AI-First Integration, MCP & Docker" description: "Release notes for docmd v0.8.6 - native MCP Server, modular Agent Skills, official Docker image, CJK search tokenization, Copy Context widgets, and TOC improvements." date: "2026-06-05" --- ### ✨ Highlights This release officially establishes docmd as the premier "AI-First" documentation engine. The centrepiece is a **native Model Context Protocol (MCP) server** enabling AI agents to interact with documentation workspaces via `docmd mcp`. Alongside this, the release delivers a **modular agent instruction set** (`docmd-skills`), an **official Docker image** with multi-architecture support, client-side "Copy Markdown" and "Copy Context" widgets for LLMs, a search tokenizer overhaul supporting CJK and spaceless languages, critical enhancements to the Table of Contents layout, and a visual overhaul of the UI featuring radial top glows, a continuous changelog timeline, and upgraded steps components. ### 🔌 Native Model Context Protocol (MCP) Server You can now start a native MCP server directly from your workspace: ```bash docmd mcp ``` The server runs in local `stdio` mode (protocol version `2025-03-26`), allowing AI developer agents (like Claude Desktop, Cursor, or Windsurf) to securely interface with your documentation workspace to: - Perform full-text and semantic documentation searches (`search_docs`) - Read markdown files and configurations (`read_doc`) - Run hyperlink and relative path validations (`validate_docs`) - Retrieve the unified repository context (`get_llms_context`) Full protocol compliance including `ping` health checks and `notifications/initialized` lifecycle. ### 📖 Modular Agent Instruction Set (`docmd-skills`) When running `docmd init`, a version-controlled `SKILL.md` is generated in the project root. The full instruction set is maintained as a modular collection in the [`docmd-skills`](https://github.com/docmd-io/docmd-skills) repository: - **`cli.md`**: Setup, all CLI commands with flags and per-command options. - **`config.md`**: Complete `docmd.config.json` schema with defaults and inline comments. - **`plugins.md`**: Every built-in plugin with all config keys, defaults, and behaviour. - **`plugin-development.md`**: Hook signatures, lifecycle, ActionContext, custom plugin creation guide. - **`formatting.md`**: Container syntax, frontmatter reference, self-closing rules. - **`api.md`**: Node.js build API, browser API, MCP server, URL utilities, client-side events. - **`validation.md`**: Link checking and CI/CD integration. All skill files include inline comments explaining defaults, reference links to full documentation, and `llms-full.txt` discoverability guidance. ### 🐳 Official Docker Image docmd is now available as an official Docker image with multi-architecture support (`linux/amd64` and `linux/arm64`): ```bash # Pull and run with demo site docker pull ghcr.io/docmd-io/docmd:latest docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest # Build your docs docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` Features include Docker Compose and Kubernetes deployment examples, non-root security, Alpine Linux base, health checks, and GitHub Actions CI/CD integration. ### 🧠 AI-First Context Extraction Widgets To enable seamless documentation ingestion by AI assistants, we have introduced two new localised buttons next to page breadcrumbs: - **Copy Markdown**: Copies the clean body content of the document, automatically stripping YAML frontmatter metadata so LLMs ingest pure content. - **Copy Context**: Copies structured context containing the page URL, title, tags, version, and text, optimised for direct copy-pasting into AI chat windows. - **Localisation**: Supports translations and copied confirmations for all 7 primary languages (`en`, `de`, `es`, `fr`, `hi`, `ja`, `zh`). ### 🔍 Spaceless Script Search Tokenization (CJK, Thai, Lao, etc.) We have resolved a search indexing limitation in `MiniSearch` for languages that do not use spaces between words. Previously, continuous character blocks (such as Chinese, Japanese, Korean, Thai, Lao, Khmer, Burmese, or Tibetan text) were indexed as single giant tokens, causing partial/sub-word matches to fail. A unified `CJK_AND_SPACELESS_REGEX` tokenizer has been added. It splits spaceless character scripts into individual character tokens while preserving default space-based tokenization for English and other languages. This tokenizer runs symmetrically on: - The build-time offline index generator. - The multi-threaded background build worker. - The client-side browser query parser. ### 🔢 docmd-search 0.1.0-alpha.1 This release includes docmd-search 0.1.0-alpha.1, which fixes a critical bug where confidence percentages in search results could exceed 100% in certain edge cases. The scoring algorithm has been corrected to properly normalise relevance scores within the expected 0-100% range. ### 📚 Table of Contents Enhancements The table of contents (TOC) component has received significant improvements in this release, addressing long-standing issues with scrolling behaviour and heading coverage. **H1 Heading Support** H1 headings (`# Heading`) are now properly included in the table of contents. Previously, only H2-H4 headings were displayed in the TOC, which meant important top-level headings were missing from the navigation sidebar. **Improved Scrolling Behaviour** The TOC sidebar now scrolls independently when it contains many items, preventing it from overlapping or interfering with the page footer. The active heading is automatically centred in the TOC view as you scroll through the content, making it easier to track your position in long documents. Smooth scrolling has been optimised with debouncing to prevent jittery or jarring movements, providing a more polished reading experience. ### Changelog 1. **MCP**: Implemented native `docmd mcp` server capabilities running on local stdio. 2. **MCP**: Updated protocol to `2025-03-26` — added `ping` handler, fixed `notifications/initialized` lifecycle. 3. **MCP**: Fixed `readline` output pollution that corrupted the JSON-RPC stream. 4. **MCP**: Added dedicated MCP Server documentation page. 5. **Skills**: Modularized agent manuals into 7 skill files under `docmd-skills/` with inline defaults and doc references. 6. **Skills**: Added `api.md` (Node.js, browser, MCP, URL utilities) and `plugin-development.md` (hooks, lifecycle) modules. 7. **Skills**: Added `llms-full.txt` discoverability guidance and agent usage instructions. 8. **Docker**: Added official Docker image with multi-architecture support (amd64/arm64). 9. **Docker**: Added Docker Compose, Kubernetes, and GitHub Actions deployment examples. 10. **Docker**: Non-root security, Alpine base, health checks, SBOM attestation. 11. **AI**: Added "Copy Markdown" and "Copy Context" UI widgets with translations for 7 languages. 12. **Search**: Added a unified tokenizer for CJK, Thai, Lao, Khmer, Burmese, and Tibetan scripts in MiniSearch. 13. **TOC**: Added support for H1 headings in the table of contents with proper anchor links and styling. 14. **TOC**: Implemented independent scrolling for the TOC sidebar with `max-height` constraints to prevent footer overlap. 15. **TOC**: Added automatic centring of active TOC items during page scroll with debounced smooth scrolling. 16. **TOC**: Extended scroll spy to observe H1 headings alongside H2-H4. 17. **Parser**: Updated heading anchor injection to include H1 headings for permalink icons. 18. **UI**: Fixed footer rendering issues caused by TOC overflow on pages with many headings. 19. **Search**: Fixed confidence percentage calculation in docmd-search 0.1.0-alpha.1 to prevent scores exceeding 100%. 20. **UI**: Upgraded steps component with precise alignments, hover states, and glowing brand nodes. 21. **UI**: Refactored changelog timeline to utilize a continuous grid axis with interactive expandable markers. 22. **UI**: Added a modern adaptive radial halo glow at the top of the content page (light and dark modes). 23. **UI**: Redesigned copy widgets as a unified, sleek segmented control button group. 24. **UI**: Fixed a critical SPA routing bug where head assets (stylesheets and icons) were duplicated during client-side navigation due to relative path resolution shifts. ### Thanks 💖 Thanks to all contributors and community members who reported issues and provided feedback on TOC behaviour and AI integrations. Documentation: https://docs.docmd.io/ GitHub: https://github.com/docmd-io/docmd --- ## [Assets Management](https://docs.docmd.io/theming/assets-management/) --- title: "Assets Management" description: "How docmd handles CSS, JavaScript, and Image assets during the build process." --- `docmd` takes a "Mirror & Map" approach to assets. This ensures that your local development paths stay consistent with your production build. ## Directory Structure By default, `docmd` looks for an `assets/` folder in your project root. ```bash my-docs/ ├── assets/ # Source Assets │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # Content ├── docmd.config.json └── site/ # Build Output (Automatically mirrored) ``` ## Automatic Copying When you run `npx @docmd/core build` or `npx @docmd/core dev`: 1. **The Mirroring Logic**: The entire contents of your `assets/` folder are recursively copied to `site/assets/`. 2. **Stability**: We use a hardened copy engine with automatic retries to prevent "File Busy" or "ENOENT" errors on macOS and modern SSDs. 3. **Referencing**: You should always reference assets from your Markdown or Config using the **root-relative** path: ```markdown ![Logo](/assets/images/logo.png) ``` ## Custom CSS & JS Integration To link your assets to every page, add them to your theme configuration: ```json { "theme": { "customCss": ["/assets/css/branding.css"] }, "customJs": ["/assets/js/utils.js"] } ``` ::: callout info "AI Recognition Strategy :robot:" * **Organise by type**: Keep `/css`, `/js`, and `/images` separate. This helps AI agents locate relevant styles or scripts instantly when you ask them to "edit the header colour". * **Use Descriptive Filenames**: Naming an image `authentication-flow-diagram.png` provides much more context to the `llms.txt` crawler than `img_01.png`. ::: --- ## [Available Themes](https://docs.docmd.io/theming/available-themes/) --- title: "Available Themes" description: "Explore docmd's built-in themes including Sky, Ruby, and Retro. Learn how to switch themes with a single config line." --- `docmd` provides a set of professionally designed, light/dark responsive themes. You can switch your entire site's aesthetic by changing a single key in `docmd.config.json`. <!-- SCREENSHOT: Gallery grid showing all available themes - each theme rendered as a small preview card with the theme name below. Show at least the default, minimal, and docs themes in both light and dark variants. --> ## How to Switch Themes ```json { "theme": { "name": "sky", "appearance": "system" } } ``` ## Built-in Theme Gallery | Theme | Best For | Vibes | | :--- | :--- | :--- | | `default` | Low-profile docs | Clean, lightweight, neutral | | `sky` | Product Docs | Modern, premium, standard-issue | | `ruby` | Brand Identity | Sophisticated, serif headers, vibrant | | `retro` | Dev Tools | 80s Terminals, monospace, neon accents | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` The very theme used for this documentation site. Use this if you plan on adding extensive custom CSS and don't want any built-in design layers interfering. ### 2. `sky` The gold standard for modern documentation. It features crisp typography, subtle transitions, and high-contrast light/dark modes that match modern SaaS platforms. ### 3. `ruby` A high-elegance theme using serif typography for headers and a deep, jewel-toned colour palette. Perfect for documentation that needs to feel authoritative and premium. ### 4. `retro` A nostalgia-fueled theme inspired by vintage computing. Features include phosphor-green text on black backgrounds (in dark mode), scanline effects, and monospace fonts like Fira Code by default. ## Theming Architecture 1. **CSS Layering**: Themes are additive. Choosing `sky` actually loads the base `default` styles and then overlays the `sky` aesthetic on top. 2. **Native dark-mode**: Every theme includes a first-class dark mode implementation. 3. **No Refresh**: When users switch themes via the UI, the SPA engine updates the `--docmd-primary` variables instantly without a page reload. ::: callout tip When describing your documentation layout to an AI developer tool, mentioning your theme (e.g., "I'm using the `retro` theme") helps the model suggest custom CSS overrides that align with that specific theme's variable schema. ::: --- ## [Custom Styles & Scripts](https://docs.docmd.io/theming/custom-css-js/) --- title: "Custom Styles & Scripts" description: "Inject your own CSS and JS files to extend docmd's functionality and branding." --- While `docmd` themes are highly flexible, you may want to inject your own stylesheets or interactive scripts. This is done via the `theme.customCss` and `customJs` arrays in your configuration. ## Custom CSS Use `theme.customCss` to override existing styles or add new ones. ```json { "theme": { "customCss": [ "/assets/css/branding.css" ] } } ``` ### How it Works 1. Place your CSS file inside your project’s assets folder (e.g., `docs/assets/css/branding.css`). 2. `docmd` will automatically copy it to the build folder and inject a `<link>` tag into every page. 3. Custom CSS is loaded **after** the theme styles, ensuring your overrides take priority. ## Custom JavaScript Use the top-level `customJs` array for scripts that add behaviour or integrate 3rd-party services. ```json { "customJs": [ "/assets/js/feedback-widget.js" ] } ``` ### Life-cycle Awareness Scripts are injected at the bottom of the `<body>` tag. Since `docmd` is a **Single Page Application (SPA)**, remember that: * The page does not fully reload when navigating between links. * You may need to listen for custom lifecycle events to re-initialise your scripts on new pages. For the full event list and usage examples, see [Client-Side Events](../api/client-side-events.md). ::: callout tip Adding custom CSS and JS allows AI models (like ChatGPT) to suggest much more tailored UI improvements. If you mention "I have a custom `branding.css` file", the model can provide specific selectors that won't conflict with the core `docmd` engine. ::: --- ## [Customisation & Variables](https://docs.docmd.io/theming/customisation/) --- title: "Customisation & Variables" description: "A complete reference of docmd's CSS variables and component classes for advanced styling." --- `docmd` is built using a CSS variable-first architecture. This means you can restyle your entire site by simply overriding a few keys in a `:root` block without writing complex CSS selectors. ## Global Variable Reference | Variable | Default (Light) | Default (Dark) | Description | | :--- | :--- | :--- | :--- | | `--bg-colour` | `#ffffff` | `#09090b` | Main page background. | | `--text-colour` | `#3f3f46` | `#a1a1aa` | Standard body text. | | `--text-heading` | `#09090b` | `#fafafa` | Title and Header colours. | | `--link-colour` | `#068ad5` | `#068ad5` | Primary accent / links. | | `--border-colour` | `#e4e4e7` | `#27272a` | Dividers and borders. | | `--sidebar-bg` | `#fafafa` | `#09090b` | Navigation background. | | `--ui-border-radius` | `6px` | `6px` | Rounding for all UI items. | | `--sidebar-width` | `260px` | `260px` | Sidebar column width. | ## Example Override To change your site's primary accent colour, add this to your `customCss`: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## Component Targeting If you need to style specific components, use these top-level classes: * `.main-content`: The wrapper for all Markdown content. * `.sidebar-nav`: The internal navigation list. * `.page-header`: The top navigation bar. * `.docmd-search-modal`: The search overlay. * `.docmd-tabs`: Tab container components. * `.callout`: The alert/note boxes. ## Troubleshooting specificity Most `docmd` styles use low specificity. If your overrides aren't applying, ensure your `customCss` is registered correctly and check if adding a `body` prefix (e.g., `body .main-content`) helps. ::: callout tip Because `docmd` uses standard CSS variables, you can ask an AI: *"Give me a professional colour palette using --link-colour and --bg-colour for docmd"*. The model will be able to provide ready-to-paste CSS that integrates perfectly with the built-in themes. ::: --- ## [Icons](https://docs.docmd.io/theming/icons/) --- title: "Icons" description: "How to use and customise Lucide icons in your documentation." --- `docmd` comes with built-in support for the [Lucide](external:https://lucide.dev/) icon library. Icons can be used in your navigation sidebar, buttons, and custom components to provide visual cues and improve scannability. ## Navigation Icons Assign an icon to any navigation item in your `docmd.config.json`. Use the kebab-case name of any icon found on the Lucide website. ```json { "navigation": [ { "title": "Home", "path": "/", "icon": "home" }, { "title": "Setup", "path": "/setup", "icon": "settings" } ] } ``` ## Icons in Containers You can also use icons inside your buttons, tags, tabs, and other containers by including the raw HTML or using standard `icon:` prefix across docmd. ```markdown ::: button "Download" /download icon:download ``` ## CSS Styling All icons are rendered as inline SVGs with the class `.lucide-icon`. You can globally change their size or stroke weight in your `customCss`: ```css .lucide-icon { stroke-width: 1.5px; /* Thinner icons for a modern look */ width: 1.2rem; height: 1.2rem; } /* Target a specific icon */ .icon-rocket { color: #ff5733; } ``` ## Icon Reference We support the entire Lucide library. You can browse the thousands of available icons here: ::: button "Browse Lucide Icons" external:https://lucide.dev/icons icon:globe --- ## [Light & Dark Mode](https://docs.docmd.io/theming/light-dark-mode/) --- title: "Light & Dark Mode" description: "How to configure the default viewing mode and manage the theme switcher for the best user experience." --- `docmd` provides built-in support for light and dark colour schemes. It detects user system preferences automatically and allows manual overrides via a UI toggle. ## Default Viewing Mode You specify the starting state of your documentation in `docmd.config.json`. ```json { "theme": { "name": "sky", "appearance": "system" } } ``` * **`system`**: Matches the user's OS preference (Recommended). * **`light`**: Force light mode on initial load. * **`dark`**: Force dark mode on initial load. ## Configuring the Toggle Button The theme switcher is part of the **Options Menu**. You can control its visibility and position within the `layout` object. ```json { "layout": { "optionsMenu": { "position": "header", "components": { "themeSwitch": true } } } } ``` ## How it works (Technical) The theme engine applies a `data-theme` attribute to the `<body>` tag: * `<body data-theme="light">` * `<body data-theme="dark">` If you are using a themed design like `sky`, the attribute will be `sky-light` or `sky-dark`. ### CSS Variables `docmd` themes use CSS variables for all colours. You can override these variables in your own CSS to customise the look of either mode. ```css /* Custom CSS override */ :root { --docmd-primary: #4f46e5; /* Primary accent for light mode */ } html[data-theme="dark"] { --docmd-primary: #818cf8; /* Primary accent for dark mode */ } ``` ## User Persistence When a user manually toggles the mode, their preference is stored in `localStorage`. `docmd` instantly reads this value on every page load to prevent "theme flickering" (FOUC). ::: callout tip When generating content, LLMs prefer high-contrast structures. `docmd` ensures that code snippets and callouts remain accessible in both modes, ensuring that `llms-full.txt` payloads are correctly understood as semantic blocks regardless of which mode was active during the build. ::: --- ## [浏览器 API(客户端)](https://docs.docmd.io/zh/07/api/browser-api/) --- title: "浏览器 API(客户端)" description: "在浏览器中与 docmd 交互 - - 实时编译与开发模式插件通信。" --- `docmd` 提供两类浏览器 API:用于在浏览器中渲染 Markdown 的**同构编译引擎**,以及用于与开发服务器实时通信的**开发模式插件 API**。 ## 同构编译引擎 在 Node.js 中生成静态站点的同一引擎可完全在浏览器中运行。非常适合构建 CMS 预览、交互式演示场,或将文档嵌入现有 Web 应用。 ### 通过 CDN 安装 ```html <!-- 核心样式 --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 同构引擎 --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` 使用默认的 `docmd` 布局将原始 Markdown 编译为完整的 HTML 文档字符串。 **参数:** - `markdown`(String):原始 Markdown 内容。 - `config`(Object):配置覆盖(与 `docmd.config.js` 使用相同的 schema)。 **返回值:** `Promise<String>`:完整的 HTML 文档。 ### 示例:实时预览 为确保样式隔离,建议通过 `srcdoc` 属性在 `<iframe>` 内渲染输出。 ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: '预览', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## 开发模式插件 API 在 `docmd dev` 运行期间,`window.docmd` 全局对象会自动注入每个页面。该 API 通过 WebSocket RPC 实现浏览器端插件代码与服务器端动作处理程序的实时通信。 ::: callout info "仅限开发模式" 以下插件 API 方法仅在 `docmd dev` 期间可用,不包含在生产构建中。 ::: ### `docmd.call(action, payload)` 调用插件注册的服务器端动作处理程序。返回一个 Promise,其值为处理程序的返回值。 ```javascript // 调用插件动作并获取结果 const threads = await docmd.call('threads:get-threads', { file: 'docs/getting-started.md' }); console.log(threads); // 线程对象数组 ``` 如果动作修改了源文件,Promise 完成后页面将自动重载。 ### `docmd.send(name, data)` 向服务器发送即发即忘事件,不返回响应。 ```javascript // 通知服务器页面浏览(不期待响应) docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` 订阅服务器推送事件。返回取消订阅函数。 ```javascript // 监听服务器广播事件 const unsub = docmd.on('threads:updated', (data) => { console.log('线程已更新:', data); }); // 稍后取消订阅 unsub(); ``` ### `docmd.afterReload(name, callback)` 声明页面重载后运行的处理程序。如果使用 `scheduleReload` 存储了上下文,回调将接收到该上下文。 ```javascript // 在实时重载后恢复滚动位置 docmd.afterReload('scroll-restore', (ctx) => { window.scrollTo(0, ctx.scrollY); }); ``` ### `docmd.scheduleReload(name, context)` 将上下文存储到 `sessionStorage` 中,供命名的 `afterReload` 处理程序使用。在下次页面重载后,匹配的处理程序将以此上下文触发。 ```javascript // 在文件编辑触发重载之前,保存状态 docmd.scheduleReload('scroll-restore', { scrollY: window.scrollY }); ``` ## 注意事项 - **WebSocket 连接**:开发模式 API 需要与开发服务器保持活跃的 WebSocket 连接。如果连接断开,将以指数退避方式自动重连。 --- ## [CLI 命令](https://docs.docmd.io/zh/07/api/cli-commands/) --- title: "CLI 命令" description: "docmd 的命令行参考 - - 所有可用的命令和选项。" --- ## 命令概览 | 命令 | 描述 | |:--------|:------------| | [`docmd init`](#docmd-init) | 初始化一个新的文档项目 | | [`docmd dev`](#docmd-dev) | 启动带有热重载的开发服务器 | | [`docmd build`](#docmd-build) | 生成生产环境静态网站 | | [`docmd live`](#docmd-live) | 启动基于浏览器的实时编辑器 | | [`docmd stop`](#docmd-stop) | 停止正在运行的开发服务器 | | [`docmd deploy`](#docmd-deploy) | 生成部署配置(Docker、Nginx、Caddy) | | [`docmd migrate`](#docmd-migrate) | 将旧版配置升级到 V2 架构 | | [`docmd add <plugin>`](#docmd-add-plugin) | 安装并配置插件 | | [`docmd remove <plugin>`](#docmd-remove-plugin) | 移除插件及其配置 | ## 全局选项 | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--config <path>` | `-c` | 配置文件路径(默认:`docmd.config.js`) | | `--verbose` | `-V` | 显示详细的构建日志 | | `--version` | `-v` | 输出安装的版本号 | | `--help` | `-h` | 显示帮助菜单 | | `--cwd <path>` | - | 覆盖当前工作目录(适用于 monorepos) | ## `docmd init` 在当前目录中初始化一个新的文档项目。 ```bash docmd init ``` 创建内容: - `docs/index.md` - - 示例主页 - `docmd.config.js` - - 推荐的默认配置 - 更新 `package.json` 并添加构建脚本 ## `docmd dev` 启动一个带有即时热重载的开发服务器。 ```bash docmd dev [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--port <number>` | `-p` | 服务器端口(默认:`3000`) | | `--config <path>` | `-c` | 配置文件路径 | ## `docmd build` 在 `site/` 目录中生成生产就绪的静态网站。 ```bash docmd build [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--offline` | - | 将链接重写为 `.html` 以进行 `file://` 浏览 | | `--config <path>` | `-c` | 配置文件路径 | ## `docmd live` 启动基于浏览器的实时编辑器。 ```bash docmd live [options] ``` | 选项 | 描述 | |:-------|:------------| | `--build-only` | 仅生成编辑器捆绑包而不启动服务器 | ## `docmd stop` 停止正在运行的 docmd 开发服务器。 ```bash docmd stop [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--port <number>` | `-p` | 仅停止该端口上的服务器 | | `--force` | `-f` | 同时强制停止端口 3000、3001、8080、8081 上的服务进程 | ## `docmd deploy` 生成部署配置文件。 ```bash docmd deploy [options] ``` | 选项 | 描述 | |:-------|:------------| | `--docker` | 生成 `Dockerfile` | | `--nginx` | 生成 `nginx.conf` | | `--caddy` | 生成 `Caddyfile` | | `--force` | 覆盖现有的部署文件 | ## `docmd migrate` 将旧版 docmd V1 配置升级到 V2 架构。 ```bash docmd migrate ``` 自动重新映射已弃用的键(例如,`siteTitle` → `title`)并重构配置对象。 ## `docmd add <plugin>` 安装并配置官方或社区插件。 ```bash docmd add <plugin-name> ``` | 示例 | 描述 | |:--------|:------------| | `docmd add analytics` | 安装 `@docmd/plugin-analytics` | | `docmd add search` | 安装 `@docmd/plugin-search` | CLI 会自动检测你的包管理器(npm、pnpm、yarn 或 bun),并将推荐的默认设置注入到 `docmd.config.js` 中。 ## `docmd remove <plugin>` 安全地卸载插件并清理其配置。 ```bash docmd remove <plugin-name> ``` 移除: - npm 软件包 - `docmd.config.js` 中的插件配置 ::: callout tip "代理兼容的日志记录 :robot:" `docmd` 使用结构化的终端日志记录。AI 代理可以精确解析输出,以便进行错误检测和自动化维护。 ::: --- ## [客户端事件](https://docs.docmd.io/zh/07/api/client-side-events/) --- title: "客户端事件" description: "接入 docmd SPA 生命周期,添加交互式功能。" --- `docmd` 使用轻量级单页应用(SPA)路由器,提供即时页面切换。由于浏览器在导航时不执行完整刷新,依赖 `DOMContentLoaded` 的脚本将不会重新执行。 为此,`docmd` 分发自定义生命周期事件,你可以在 `customJs` 文件中监听这些事件。 ## `docmd:page-mounted` 每当新页面成功获取并注入到 DOM 时,此事件就会被分发。 ### 用法 在 `document` 对象上添加监听器,以重新初始化第三方库或触发自定义动画。 ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`已导航至:${url}`); // 重新初始化组件 // 示例:Prism.highlightAll(); }); ``` ### 事件详情(`event.detail`) | 属性 | 类型 | 说明 | | :--- | :--- | :--- | | `url` | `String` | 刚刚挂载的页面的绝对 URL。 | ## 最佳实践 1. **幂等性**:确保你的初始化逻辑可以在同一页面上安全多次调用,或在下次导航前妥善清理。 2. **全局作用域**:通过 `customJs` 添加的脚本在全局作用域中执行。使用 IIFE(立即调用函数表达式)避免污染 `window` 对象。 3. **清理**:如果脚本添加了全局事件监听器(如 `window.onresize`),考虑追踪当前路径,以便用户离开时将其移除。 --- ## [实时编辑器](https://docs.docmd.io/zh/07/api/live-api/) --- title: "实时编辑器" description: "了解 docmd 实时编辑器及其基于浏览器的创作工作流。" --- `docmd` 实时编辑器是专为实时文档创作而设计的专用环境。它使用 `docmd` 的同构核心,无需后端构建流程,即可即时并排预览 Markdown 内容。 ## 启动编辑器 运行以下命令启动本地实时编辑器: ```bash docmd live ``` 编辑器通常可在 `http://localhost:3000` 访问。 ## 架构 与标准 `dev` 服务器(在磁盘上重新构建文件)不同,实时编辑器直接在浏览器中运行 `docmd` 引擎。这实现了: 1. **即时反馈**:内容在输入时即时重新渲染。 2. **可移植沙盒**:编辑器可以打包成静态站点,托管在 GitHub Pages 等平台上。 3. **跨平台一致性**:预览使用与生产构建完全相同的渲染逻辑。 ## 静态部署 生成一个可共享的独立编辑器版本: ```bash docmd live --build-only ``` 这会创建一个包含编辑器 HTML 和打包同构引擎的 `dist/` 目录。 --- ## [Node.js API](https://docs.docmd.io/zh/07/api/node-api/) --- title: "Node.js API" description: "将 docmd 的构建引擎集成到你的自定义 Node.js 脚本和自动化流水线中。" --- 对于高级工作流,你可以直接在自己的 Node.js 应用程序中导入并使用 `docmd` 构建引擎。这对于自定义 CI/CD 流水线、自动化文档生成或为特定环境扩展 `docmd` 非常理想。 ## 安装 确保你的项目中安装了 `@docmd/core`: ```bash npm install @docmd/core ``` ## 核心函数 ### `buildSite(configPath, options)` 主要的构建函数。它处理配置加载、Markdown 解析和资源生成。 ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.js', { isDev: false, // 设置为 true 以启用监视模式逻辑 offline: false, // 设置为 true 以优化 file:// 访问 zeroConfig: false // 设置为 true 以跳过配置文件检测 }); } ``` ### `buildLive(options)` 生成基于浏览器的 **实时编辑器 (Live Editor)** 捆绑包。 ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true 启动本地服务器;false 生成静态文件 port: 3000 // 如果 serve 为 true,则指定自定义端口 }); } ``` ## 示例:自定义流水线 你可以封装 `docmd` 来创建复杂的文档工作流。 ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. 生成动态内容 await fs.writeFile('./docs/dynamic.md', '# Generated Content'); // 2. 执行 docmd 构建 await buildSite('./docmd.config.js'); // 3. 移动输出结果 await fs.move('./site', './public/docs'); } ``` ::: callout tip 编程式 API 与 **AI 驱动的文档** 高度兼容。代理可以在内容更新后触发构建以验证完整性,并自主管理部署。 ::: ## 插件 API (`@docmd/api`) `@docmd/api` 软件包是插件系统的专属家园。它提供钩子注册、WebSocket RPC 调度、源码编辑工具以及 **集中式 URL 实用程序**。 ```bash npm install @docmd/api ``` ### URL 实用程序 插件应使用这些集中式实用程序,而不是编写自己的 URL 逻辑。 #### `outputPathToSlug(outputPath)` 将构建引擎输出路径转换为干净的目录样式 slug。 ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` 转换为根相对路径名。 ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` 构建完整的规范 URL。 ```javascript import { outputPathToCanonical } from '@docmd/api'; outputPathToCanonical('guide/index.html', 'https://example.com'); // → 'https://example.com/guide/' ``` #### `sanitizeUrl(url)` 折叠双斜杠(协议之后的除外)。 ```javascript import { sanitizeUrl } from '@docmd/api'; sanitizeUrl('https://example.com//path/'); // → 'https://example.com/path/' sanitizeUrl('/foo//bar/'); // → '/foo/bar/' ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` 构建带有语言环境和版本前缀的绝对 URL。 ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` 将用户编写的 href 规范化为干净的 URL。处理 `.md` 剥离、尾随斜杠、`external:` 和 `raw:` 前缀。 ```javascript import { resolveHref } from '@docmd/api'; resolveHref('overview.md'); // → { href: 'overview/', isExternal: false, isRaw: false } resolveHref('external:https://github.com/docmd-io/docmd'); // → { href: 'https://github.com/docmd-io/docmd', isExternal: true, isRaw: false } resolveHref('raw:docs/readme.md'); // → { href: 'docs/readme.md', isExternal: false, isRaw: true } ``` ### 预计算的页面 URL 每个页面对象都包含预计算的 URL 数据。插件可以直接读取这些数据 - - 无需计算。 ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); // "guide/" console.log(page.urls.canonical); // "https://example.com/guide/" console.log(page.urls.pathname); // "/guide/" } } ``` | 属性 | 类型 | 描述 | |:---------|:-----|:------------| | `slug` | `string` | 干净的目录样式 slug (例如, `guide/` 或 `/`) | | `canonical` | `string` | 完整规范 URL (仅当设置了 `config.url` 时) | | `pathname` | `string` | 根相对路径 (例如, `/guide/`) | > **向后兼容性:** `@docmd/api` 中的所有导出也从 `@docmd/core` 中重新导出,因此现有代码可以继续运行而无需更改。建议新项目直接从 `@docmd/api` 导入。 ### `createActionDispatcher(hooks, options)` 创建一个调度程序,将 WebSocket RPC 消息路由到插件动作/事件处理程序。 ```javascript import { createActionDispatcher } from '@docmd/api'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` 创建用于操作 markdown 文件的源编辑实用程序。 ```javascript import { createSourceTools } from '@docmd/api'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // 获取特定行范围的块信息 const block = await source.getBlockAt('docs/page.md', [10, 12]); // 使用语法标记包装文本 await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### `loadPlugins(config, options)` 加载、验证并注册配置中声明的所有插件。返回填充好的钩子注册表。 ```javascript import { loadPlugins, hooks } from '@docmd/api'; const registeredHooks = await loadPlugins(config, { resolvePaths: [__dirname] // 帮助解析 pnpm 工作区中的插件 }); ``` ### 类型导出 对于 TypeScript 插件作者,可以使用以下类型: ```typescript import type { PluginModule, // 完整插件合约接口 PluginDescriptor, // 插件元数据(名称、版本、能力) PluginHooks, // 钩子注册表形状 PageContext, // 传递给构建钩子的上下文(sourcePath、html 等) Capability, // 钩子类别声明(init、body、actions 等) ActionContext, // 传递给动作/事件处理程序的上下文 ActionHandler, // 动作处理程序签名 EventHandler, // 事件处理程序签名 SourceTools, // 源编辑工具接口 BlockInfo, // getBlockAt 返回的块信息 TextLocation, // findText 返回的文本位置 } from '@docmd/api'; ``` --- ## [对比 (Comparison)](https://docs.docmd.io/zh/07/comparison/) --- title: "对比 (Comparison)" description: "为什么选择 docmd?了解它与 Docusaurus、VitePress、MkDocs 和其他工具的对比情况。" --- 你以前选择过文档工具,以后也会再次选择。这里是真正重要的东西 - - 以及 docmd 的优势所在。 ## 3 秒钟开始编写,而不是 30 分钟 ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` 搞定。你的文档已经上线。无需配置文件,无需项目脚手架,无需陷入依赖迷宫。 == tab "Docusaurus" ```bash npx create-docusaurus@latest my-site classic cd my-site npm install npm start ``` 四个命令,一个在 `node_modules` 中占用约 250MB 空间的生成项目,以及一个在你做任何有用的事情之前需要编辑的 `docusaurus.config.js`。 == tab "VitePress" ```bash npx vitepress init ``` 问你 5 个问题,生成一个配置文件,然后你运行 `vitepress dev`。很整洁 - - 但仍然需要脚手架。 == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new my-site && cd my-site mkdocs serve ``` Python 生态。在渲染第一页之前,你需要 `pip`、虚拟环境和一个 `mkdocs.yml`。 ::: ## 载荷差距是真实的 你的读者不应该为了读一个段落而下载整个 React 应用。以下是在一个有 50 个页面的网站上,浏览器实际接收到的数据: | 生成器 | 总初始加载量 | JS 载荷 | CSS 载荷 | |:----------|:------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "为什么这很重要" 在中端手机上,每 100 KB 的 JavaScript 都会耗费约 50ms 的解析时间。docmd 仅 12 KB 的 JS 意味着你的文档可以瞬间加载,即使在 3G 网络下也是如此。Docusaurus 为同样的内容传输了 16 倍以上的 JavaScript。 ::: ## 构建速度 在 M1 MacBook Air 上构建同一个拥有 50 个页面的网站: | 生成器 | 冷启动构建 | 热重载 (dev) | |:----------|:----------:|:-----------------:| | **docmd** | **~1.2s** | **~80ms** | | VitePress | ~2.5s | ~150ms | | MkDocs Material | ~3.0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd 的重新构建非常快,在你切换窗口之前页面就已经刷新了。 ## 真正可用的多语言支持 (i18n) 这是大多数工具折戟的地方。你添加了 6 种语言,翻译了 3 个印地语页面,突然间你的用户在每个未翻译的页面上都会遇到 404 错误。 | 能力 | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | 每页可回退到默认语言环境 | ✅ | ❌ (404) | ❌ (404) | ✅ | | 本地化的“未翻译”警告 | ✅ | ❌ | ❌ | ✅ | | 在切换器中自动禁用缺失的语言 | ✅ | ❌ | ❌ | ❌ | | 瞬时页面存在检查 (无需网络) | ✅ | ❌ | ❌ | ❌ | | 版本控制 + i18n 组合 | ✅ | ❌ | ❌ | ❌ | | 零配置 (无需自定义 React/Vue) | ✅ | 部分 | ❌ | ✅ | ::: callout warning "在 VitePress 和 Docusaurus 中会发生什么" 如果读者切换到印地语且该页面尚未翻译,他们将看到 **404 错误**。唯一的解决方法是服务器端重定向或编写自定义 React/Vue 组件。docmd 在构建时处理此问题 - - 不可用的语言环境会显示“N/A”徽章,而未翻译的页面会静默回退并带有一个本地化的警告标注。 ::: ## 完整功能矩阵 | 特性 | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **零配置启动** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **需要配置** | 无 | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **SPA 导航** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **原生版本控制** | ✅ | ✅ | ❌ | 插件 | ❌ | ✅ | | **原生多语言 (i18n)** | ✅ | ✅ | 手动 | 插件 | ✅ | ✅ | | **内置搜索** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | 云端 | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **行内讨论** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA 支持** | ✅ | 社区 | ❌ | ❌ | ❌ | ❌ | | **私有化部署** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **部署配置生成器** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## 配置负担 对于一个包含版本控制、多语言、搜索和站点地图的网站,所需的配置行数: | 生成器 | 配置行数 | 所需文件 | |:----------|:------------:|:--------------:| | **docmd** | **~15 行** | 1 (`docmd.config.js`) | | MkDocs Material | ~50 行 | 1 + 插件 | | VitePress | ~80 行 | 1 + 主题目录 | | Docusaurus | ~120 行 | 3+ 配置文件 | ## 质量保证 docmd 附带了一套暴力测试套件,通过 **85 项断言** 验证 **25 个不同的场景** - - 覆盖了每个功能的独立运行以及组合运行的情况。每个版本在发布前必须通过所有 85 项断言和 13 项内部故障安全检查。 ::: callout tip "亲自运行测试" ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: 同类文档生成器中,没有任何一个会在其源码中发布如此规模的端到端功能测试套件。 --- ## [布局与界面分区](https://docs.docmd.io/zh/07/configuration/layout-ui/) --- title: "布局与界面分区" description: "通过管理头部、侧边栏和功能插槽来控制界面结构。" --- 一个标准的 `docmd` 页面分为六个主要功能分区: 1. **菜单栏**:全宽顶部导航栏,用于全局站点链接。 2. **头部**:含页面标题和工具按鈕的固定导航栏。 3. **侧边栏**:主要导航树(通常在左侧)。 4. **内容区**:中心 Markdown 渲染区,包含**面包屑**。 5. **目录(TOC)**:当前页面的右侧标题导航。 6. **页脚**:底部版权、品牌和全局链接區域。 ## 全局组件 大多数 UI 分区通过 `docmd.config.js` 的 `layout` 属性选来配置。 ### 菜单栏 菜单栏在文档上方提供高层跟踪导航。 ```javascript layout: { menubar: { enabled: true, position: 'top', // 'top'(固定) 或 'header'(随内容流) left: [ { type: 'title', text: '品牌', url: '/', icon: 'home' }, { text: '功能特性', url: '/features' } ], right: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', icon: 'github' } ] } } ``` ### 页面头部 头部默认开启。可全局关闭,也可在页面层级的 frontmatter 中隐藏特定元素。 ```javascript // docmd.config.js layout: { header: { enabled: true // 设为 false 则全局隐藏顶部头部 }, breadcrumbs: true // 设为 false 则全局隐藏面包屑 } ``` **页面级覆盖(Frontmatter):** ```yaml --- title: "特殊页面" hideTitle: true # 隐藏该页固定头部中的标题 --- ``` ## 工具菜单(选项菜单) `optionsMenu` 将搜索、主题切换和赞助等实用功能整合在一起。 ```javascript layout: { optionsMenu: { position: 'header', // 可选值:'header'、'sidebar-top'、'sidebar-bottom'、'menubar' components: { search: true, // 启用全文搜索 themeSwitch: true, // 启用明暗模式切换 sponsor: 'https://github.com/sponsors/your-profile' } } } ``` ::: callout info "容器回退" 如果所选位置对应的容器已禁用,`docmd` 将自动将选项菜单渲染到 `sidebar-top` 插槽,确保实用功能持续可用。 ::: ## 侧边栏与页脚控制 ### 侧边栏行为 ```javascript layout: { sidebar: { enabled: true, collapsible: true, // 启用展开/折叠动画 defaultCollapsed: false, // 设置侧边栏初始状态 position: 'left' } } ``` ### 页脚品牌 `docmd` 提供了两种页脚样式:**minimal**(简洁)和 **complete**(完整)。 ```javascript layout: { footer: { style: 'complete', description: '本文档由 docmd 构建。', branding: true, // 控制 "Built with docmd" 徽标的显示 columns: [ { title: '社区', links: [{ text: 'GitHub', url: '...' }] } ] } } ``` ::: callout tip "AI 优化界面" 在设计自定义布局时,建议将**搜索**组件放在 `optionsMenu` 的显著位置。AI 模型在浏览文档时经常把搜索作为定位特定技术上下文的主要入口。 ::: --- ## [国际化](https://docs.docmd.io/zh/07/configuration/localisation/) --- title: "国际化" description: "通过语言区域优先路由、翻译导航和自动降级回退,以多种语言提供文档服务。" --- 为你的文档站点添加多语言支持。docmd 以各自的 URL 前缀提供每种语言区域的内容,翻译系统 UI 字符串,并在缺少翻译时优雅地回退。 ## 在配置中添加语言 ```js // docmd.config.js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }, { id: 'zh', label: '中文' } ] } } ``` `default` 语言区域在站点根路径(`/`)渲染。其他所有区域在 `/{id}/` 渲染。你可以自由选择 ID、标签以及哪个区域为默认值 - - 没有任何硬编码假设。如果想以印地语为默认语言,设置 `default: 'hi'`,印地语将在 `/` 渲染,英语在 `/en/` 渲染。 | 键 | 类型 | 说明 | |:----|:-----|:------------| | `default` | `string` | 在 `/` 渲染的区域 ID。省略时默认为第一个区域。 | | `locales` | `array` | 区域对象列表。每个对象必须包含 `id`。 | | `position` | `string` | 语言切换器的显示位置。`options-menu`(默认)、`sidebar-top` 或 `sidebar-bottom`。 | 每个区域对象可包含以下字段: | 键 | 类型 | 默认值 | 说明 | |:----|:-----|:--------|:------------| | `id` | `string` | - | 你选择的任意标识符(如 `en`、`hi`、`fr-ca`)。用作文件夹名称和 URL 前缀。必填。 | | `label` | `string` | 同 `id` | 语言切换器中显示的名称。 | | `dir` | `string` | `ltr` | 文字方向。阿拉伯语、希伯来语等设为 `rtl`。 | | `translations` | `object` | `{}` | 自定义 UI 字符串覆盖(参见 [自定义 UI 字符串](./ui-strings))。 | ## URL 结构 默认区域没有 URL 前缀。非默认区域嵌套在 `/{id}/` 下。与[版本控制](../versioning)结合使用时,URL 格式为 `/{locale}/{version}/page`。 ``` / ← 默认区域,当前版本 /getting-started ← 默认区域页面 /05/ ← 默认区域,旧版本 /hi/ ← 非默认区域,当前版本 /hi/getting-started ← 非默认区域页面 /hi/05/ ← 非默认区域,旧版本 ``` 切换语言时,语言切换器会保留当前页面和版本。版本切换器会保留当前语言区域。 ## 缺失的语言区域目录 如果在 `locales` 中声明了某个语言区域,但其源目录不存在(例如没有 `docs/hi/` 文件夹),docmd 会自动在语言切换器中**禁用**该语言区域。该语言区域仍会出现在下拉菜单中 - 带有"N/A"标记和灰色样式 - 但点击不会产生任何效果。 这可以防止在您列出计划中的语言但内容尚未准备好时出现 404 错误。 ## 语言切换器位置 使用 `position` 选项控制语言切换器的显示位置: ```js i18n: { position: 'options-menu', // 默认 // ... } ``` | 位置 | 行为 | |:---------|:----------| | `options-menu` | 紧凑的地球仪图标,与主题切换和搜索并排。默认。 | | `sidebar-top` | 带标签的完整下拉菜单,位于侧边栏顶部。 | | `sidebar-bottom` | 带标签的完整下拉菜单,位于侧边栏底部。 | ## 后续步骤 - [翻译内容](./translated-content) - 目录结构、编写翻译、导航 - [UI 字符串与 SEO](./ui-strings) - 自定义系统文本、hreflang 标签 --- ## [翻译内容](https://docs.docmd.io/zh/07/configuration/localisation/translated-content/) --- title: "翻译内容" description: "在语言区域子目录中组织翻译内容,支持逐文件降级回退和各区域独立导航。" --- ## 目录结构 每种语言区域(包括默认区域)在源目录中都有自己的子目录。文件夹名称与配置中的区域 `id` 匹配。 ``` docs/ ├── en/ ← 默认区域内容 │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← 第二语言区域 │ ├── index.md ← 翻译后的首页 │ ├── navigation.json ← 翻译后的导航标签 │ └── getting-started/ │ └── installation.md ← 翻译后的页面 └── zh/ ← 第三语言区域 └── index.md ← 仅翻译了首页 ``` 源目录是纯净的容器 - - 启用 i18n 后,根目录下不放任何内容文件,只放语言区域文件夹。 ::: callout info "文件夹名称由你决定" 文件夹名称直接来自配置中的 `id` 值。如果配置中写的是 `{ id: 'fr-ca' }`,文件夹就是 `docs/fr-ca/`。如果印地语是默认区域(`default: 'hi'`),则 `docs/hi/` 就是规范内容目录。 ::: ## 逐文件回退 无需翻译每一个页面。docmd 以**默认区域的目录**为页面规范列表。对于其他区域,会检查每个页面是否存在翻译版本: - 如果 `docs/hi/getting-started/installation.md` 存在 → 提供印地语翻译 - 如果不存在 → 提供该页面的默认区域版本 当页面发生回退时,docmd 可以显示一个翻译后的提示框,告知用户当前页面以默认语言展示。该消息可通过[UI 字符串](./ui-strings)配置自定义。 ## 仅限该区域的页面 非默认区域也可以拥有默认区域中不存在的页面。这些页面仅为该区域渲染,不会出现在其他区域中。 ## 翻译导航 每个区域目录都可以有自己的 `navigation.json`。`docmd` 使用级联优先级系统来解析侧边栏。 有关解析层级结构和视觉示例的详细信息,请参阅 [导航解析优先级](../navigation#daohang-jiexi-youxianji)。 区域的 `navigation.json` 使用相同格式: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "部分导航" 只有在需要翻译标签时才需要创建区域 `navigation.json`。如果缺少该文件,将使用默认区域的导航 - - 页面仍正常渲染,只是标签未翻译。 ::: ## 版本控制与 i18n 结合使用 同时配置版本控制和 i18n 时,源目录结构如下: ``` docs/ ← 当前版本(容器) en/ ← 当前版本,默认区域 hi/ ← 当前版本,翻译区域 docs-v1/ ← 旧版本 index.md ← 旧版本内容(无区域结构) navigation.json ``` 早于 i18n 的旧版本可自动工作 - - 当没有区域子目录时,docmd 直接读取。只有默认区域渲染旧版本。如需为旧版本添加翻译,在旧版本目录中创建区域子目录: ``` docs-v1/ hi/ ← v1 的印地语翻译 index.md navigation.json ``` 输出 URL 按区域优先、版本其次的顺序嵌套: ``` / ← 默认区域,当前版本 /hi/ ← 翻译区域,当前版本 /v1/ ← 默认区域,旧版本 /hi/v1/ ← 翻译区域,旧版本 ``` --- ## [UI 字符串翻译](https://docs.docmd.io/zh/07/configuration/localisation/ui-strings/) --- title: "UI 字符串翻译" description: "通过配置自定义翻译来自定义 docmd 用户界面中显示的文本(搜索占位符、导航标签等)。" --- 虽然 `docmd` 对常见语言有内置的翻译,但你可能希望为特定项目自定义 UI 文本(例如,将“Search”更改为“Find in Docs”)。 ## 全局配置 你可以在 `docmd.config.js` 中直接定义特定语言环境的翻译。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ locales: { en: { title: 'English', label: 'English' }, zh: { title: 'Chinese', label: '简体中文' } }, plugins: { localisation: { translations: { zh: { 'search.placeholder': '搜索文档...', 'nav.next': '下一篇', 'nav.prev': '上一篇', 'toc.title': '本页目录' } } } } }); ``` ## 可用的 UI 键名 以下是你可以覆盖的最常用 UI 字符串: | 键名 | 默认值 (EN) | 描述 | | :--- | :--- | :--- | | `search.placeholder` | `Search...` | 搜索输入框中的占位符。 | | `search.noResults` | `No results found` | 未找到匹配项时显示的文本。 | | `nav.next` | `Next` | 分页器中“下一页”按钮的文本。 | | `nav.prev` | `Previous` | 分页器中“上一页”按钮的文本。 | | `toc.title` | `On this page` | 目录侧边栏顶部的标题。 | | `theme.light` | `Light` | 主题切换器中“浅色”的标签。 | | `theme.dark` | `Dark` | 主题切换器中“深色”的标签。 | | `theme.system` | `System` | 主题切换器中“系统同步”的标签。 | ## 插件贡献 如果你正在 [开发插件](../../plugins/building-plugins.md),你也可以通过 `translations` 钩子提供新的翻译键: ```javascript export default { name: 'my-plugin', translations(localeId) { if (localeId === 'zh') { return { 'myplugin.status': '状态' }; } return { 'myplugin.status': 'Status' }; } }; ``` ::: callout tip "AI 翻译建议" 当要求 AI 助手为你的网站添加新语言时,请提供上述 UI 键名列表。这可确保 AI 不仅翻译你的内容,还为你的 `.config.js` 文件提供一套匹配的本地化 UI 字符串。 ::: --- ## [菜单栏](https://docs.docmd.io/zh/07/configuration/menubar/) --- title: "菜单栏" description: "配置菜单栏结构、链接和下拉菜单。" --- `menubar` 是一个高级导航层,可在整个文档网站中提供全局上下文。它可以固定在视口顶部,也可以作为相对定位组件置于页面头部上方。 ## 配置 菜单栏在 `docmd.config.js` 的 `layout` 部分中进行配置。 ```javascript export default defineConfig({ layout: { menubar: { enabled: true, position: 'top', // 'top'(固定)或 'header'(内联) left: [ { type: 'title', text: '品牌', url: '/', icon: 'home' }, { text: '文档', url: '/docs' }, { type: 'dropdown', text: '生态', items: [ { text: 'GitHub', url: 'https://github.com/docmd-io/docmd', external: true }, { text: '实时编辑器', url: 'https://live.docmd.io' } ] } ], right: [ { text: '支持', url: '/support', icon: 'help-circle' } ] } } }); ``` ### 选项 | 选项 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | 切换菜单栏的显示状态 | | `position` | `String` | `'top'` | `'top'`(绝对固定在顶部)或 `'header'`(位于页面标题上方) | | `left` | `Array` | `[]` | 左侧对齐的导航项 | | `right` | `Array` | `[]` | 右侧对齐的导航项 | ## 项目类型 `left` 和 `right` 数组支持多种项目类型,以便更好地组织导航结构: ### 1. 标准链接 最常见的项目类型。 - `text`:显示标签。 - `url`:路径或外部 URL。 - `icon`:可选的 Lucide 图标名称。 - `external`:设为 `true` 则在新标签页打开。 ### 2. 标题(品牌) 设置 `type: 'title'` 可为链接应用品牌样式(通常为粗体或特定字重)。 ### 3. 下拉菜单 设置 `type: 'dropdown'` 并提供 `items` 数组即可创建嵌套菜单。 ## 工具集成 通过将 `optionsMenu.position` 设为 `'menubar'`,可以将全局搜索和主题切换集成到菜单栏中。 ```javascript layout: { optionsMenu: { position: 'menubar' } } ``` 集成后,选项菜单将自动对齐到菜单栏的**右侧区域**,显示在 `right` 数组中定义的链接之后。 ::: callout info 如果 `menubar` 被禁用,分配到该位置的工具组件将自动回退到 `sidebar-top` 位置。 ::: ## 自定义样式 可在 `customCss` 文件中使用 CSS 变量精细调整菜单栏的外观: ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-color); --menubar-text: var(--docmd-text-primary); } ``` --- ## [多项目配置](https://docs.docmd.io/zh/07/configuration/multi-project/) --- title: "多项目配置" description: "从单个 docmd 实例构建多个独立文档站点。共享资源、独立版本、统一部署。" --- 从单个仓库构建和部署多个文档项目。每个项目维护独立的配置、版本和导航,同时共享通用的主题和资源管道。 ## 概览 多项目模式专为在一个域名下维护多个工具、库或产品的组织设计。无需在反向代理后运行多个 docmd 实例,一条 `docmd build` 命令即可生成统一的 `site/` 目录。 ``` docs.example.com/ → 主文档 docs.example.com/sdk/ → SDK 参考 docs.example.com/cli/ → CLI 文档 ``` ## 配置 ### 1. 目录结构 按照每个项目一个目录的方式组织仓库: ``` my-docs/ ├── assets/ ← 共享资源(所有项目) ├── main-docs/ │ ├── docmd.config.js ← 项目配置 │ └── v01/ ← 版本化内容 │ └── en/ ├── sdk-docs/ │ ├── docmd.config.js ← 项目配置 │ └── docs/ ← 非版本化内容 ├── docmd.config.js ← 根多项目配置 └── package.json ``` ### 2. 根配置 根 `docmd.config.js` **仅包含** `projects` 数组: ```javascript module.exports = defineConfig({ projects: [ { prefix: '/', src: 'main-docs' }, { prefix: '/sdk', src: 'sdk-docs' } ] }); ``` | 键 | 说明 | | :-- | :---------- | | `prefix` | 此项目的 URL 前缀。根项目使用 `'/'`。 | | `src` | 包含此项目 `docmd.config.js` 和内容的目录。 | ::: callout warning 每个多项目配置**必须**包含一个 `prefix: '/'` 的根项目。 ::: ### 3. 项目配置 每个项目目录有自己的 `docmd.config.js`,包含完全独立的配置。**不要**包含 `src` 或 `out` 键 - - 父配置会自动提供这些值。 每个项目可以拥有完全独立的: - **i18n** - 不同的语言环境、不同的默认语言 - **版本控制** - 不同的版本号和结构 - **插件** - 仅启用每个项目需要的插件 - **导航** - 每个项目的自定义侧边栏 ## 资源 ### 共享资源 将共享资源(logo、favicon、全局 CSS)放在根 `assets/` 目录中,它们会自动复制到每个项目的输出中。 ### 项目专属资源 每个项目可以拥有自己的 `assets/` 目录。当文件名重复时,项目资源优先于共享资源。 ``` my-docs/ ├── assets/ │ └── images/ │ └── logo.png ← 所有项目使用 ├── sdk-docs/ │ └── assets/ │ └── images/ │ └── logo.png ← 仅覆盖 SDK 的 logo ``` ## 开发 启动多项目开发服务器: ```bash docmd dev ``` 服务器构建所有项目并通过单个端口提供服务: ``` ┌─ DEV SERVER │ │ Local http://127.0.0.1:3000 │ Network http://192.168.1.5:3000 │ │ Project http://127.0.0.1:3000/ │ Project http://127.0.0.1:3000/sdk └────────────────────────────────────────────────────────── ``` 任何项目中的文件更改都会触发针对性重建和实时刷新。仅重建受影响的项目 - - 其他项目保持不变以实现快速迭代。共享资源的更改会重建所有项目。 ## 构建与部署 ```bash docmd build ``` 输出为单个静态目录: ``` site/ ├── index.html ← main-docs 根目录 ├── sdk/ │ └── index.html ← sdk-docs 根目录 ├── assets/ ← 合并后的资源 ├── 404.html └── sitemap.xml ``` 可直接部署到任何静态托管服务(GitHub Pages、Netlify、Vercel、Cloudflare Pages),无需额外配置。无需 nginx 或代理规则。 ## 规则与约束 1. **必须有根项目** - - 一个项目必须使用 `prefix: '/'` 2. **前缀不可重复** - - 每个项目需要唯一的 URL 前缀 3. **子配置无需 `src`/`out`** - - 父配置提供这些值 4. **完全独立** - - 每个项目拥有独立的标题、版本、国际化、插件和导航 5. **根配置精简** - - 根 `docmd.config.js` 中应仅包含 `projects` --- ## [导航设置 (Navigation)](https://docs.docmd.io/zh/07/configuration/navigation/) --- title: "导航设置 (Navigation)" description: "通过全局配置、目录级 navigation.json 或自动文件扫描来定义网站的侧边栏结构。" --- `docmd` 提供了一个极其灵活的导航系统,可以从简单的单文件夹项目扩展到复杂的多版本、多语言文档中心。 ## 导航定义方式 你可以通过三种方式定义导航。如果同时使用多种方式,`docmd` 会按照以下优先级进行解析: ### 1. 全局配置 (`docmd.config.js`) 适用于小型项目。所有导航逻辑都保存在主配置文件中。 ```javascript export default { navigation: [ { title: '开始使用', path: '/intro' }, { title: 'API 参考', path: '/api', children: [...] } ] } ``` ### 2. 目录级配置 (`navigation.json`) 这是处理大规模文档的 **推荐方式**。在你的 `docs/` 目录(或任何子目录)中放置一个 `navigation.json` 文件。 ```json [ { "title": "概览", "path": "overview.md" }, { "title": "高级话题", "children": [...] } ] ``` ### 3. 自动文件扫描 (降级方案) 如果既没有定义全局配置也没有 `navigation.json`,`docmd` 会自动扫描你的文件系统并按照字母顺序构建侧边栏。 ## 侧边栏对象属性 每个导航项都支持以下属性: | 属性 | 类型 | 描述 | | :--- | :--- | :--- | | `title` | `string` | 侧边栏中显示的标签文本。 | | `path` | `string` | 相对于当前目录的源文件路径(如 `intro.md`)。 | | `icon` | `string` | 来自 Lucide 库的图标名称(如 `home`)。 | | `collapsible` | `boolean` | 是否允许该分组在侧边栏中折叠(默认为 `true`)。 | | `collapsed` | `boolean` | 初始加载时该分组是否处于折叠状态。 | | `external` | `boolean` | 是否在新标签页中打开链接。 | | `children` | `array` | 子导航项的嵌套列表。 | ## 导航解析优先级 当用户访问一个页面时,侧边栏是根据该页面所在的目录深度动态计算的: 1. **最近邻匹配**: 引擎首先在当前页面所在的文件夹中查找 `navigation.json`。 2. **向上递归**: 如果未找到,它会向父目录查找,直到到达根目录。 3. **全局降级**: 如果整个文件系统中都没有 `navigation.json`,则使用 `docmd.config.js` 中的定义。 ::: callout tip "基于上下文的导航" 这种解析逻辑允许你为网站的不同部分定义 **完全不同** 的侧边栏。例如,你的 `/api/` 目录可以有一套专注于技术定义的侧边栏,而你的 `/guides/` 目录则可以显示一套专注于教程的侧边栏。 ::: ## 自动排序与隐藏 * **排除文件**: 如果你不想让某个文件出现在自动生成的侧边栏中,但仍希望它能被访问,请在 Frontmatter 中设置 `unlisted: true`。 * **排序**: `navigation.json` 中的顺序即为最终渲染的顺序。 ::: callout warning "路径规范化" 在 `navigation.json` 中,你可以编写 `overview.md`、`overview` 或 `./overview`。构建引擎会自动将这些格式规范化为干净的生产环境 URL。详见 [链接与引用](../content/syntax/linking.md)。 ::: --- ## [配置概览](https://docs.docmd.io/zh/07/configuration/overview/) --- title: "配置概览" description: "配置 docmd.config.js 的架构、品牌、布局与引擎功能。" --- `docmd.config.js` 文件是你文档项目的核心配置中心,控制网站结构、品牌呈现、界面行为以及引擎级蓉处理规则。 ## 配置文件 推荐使用 `@docmd/core` 提供的 `defineConfig` 辅助函数,它将提供完整的 IDE 自动补全和类型检查功能,让你轻松了解所有可用配置项。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ title: 'My Project', url: 'https://docs.myproject.com', // ... 配置项 }); ``` ## 核心配置项 `docmd` 采用简洁的配置架构。下表列出了主要顶层配置项: | 键名 | 说明 | 默认值 | | :--- | :--- | :--- | | `title` | 文档网站名称,显示在头部和浏览器标题中 | `Documentation` | | `url` | 生产环境基础 URL,对 SEO、站点地图和 OpenGraph 至关重要 | `null` | | `src` | Markdown 文件目录的相对路径 | `docs` | | `out` | 静态网站输出目录的相对路径 | `site` | | `base` | 如果托管在子目录下的基础路径(如 `/docs/`) | `/` | | `i18n` | [多语言支持](./localisation.md)配置 | `null` | | `plugins` | 标准或自定义[插件](../plugins/usage.md)配置 | `{}` | ## 品牌与身份 配置导航头部和浏览器标签页的品牌展示方式。 ```javascript logo: { light: 'assets/images/logo-dark.png', // 浅色模式下显示的 Logo dark: 'assets/images/logo-light.png', // 深色模式下显示的 Logo href: '/', // 点击 Logo 时跳转的链接 alt: 'Company Logo', // 无障碍文字 height: '32px' // 可选:Logo 高度 }, favicon: 'assets/favicon.ico', // 网站图标路径 ``` ## 布局架构 `docmd` 拥有模块化布局系统。你可以通过 `layout` 对象切换 UI 组件并配置导航行为。 | 分区 | 键名 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | **全局** | `spa` | `true` | 启用 SPA 无刷新跟踪导航 | | **头部** | `header` | `{ enabled: true }` | 切换顶部导航栏的显示 | | **侧边栏** | `sidebar` | `{ enabled: true, collapsible: true }` | 控制侧边栏导航树及其行为 | | **页脚** | `footer` | `{ style: 'minimal' }` | 支持 `'minimal'` 或 `'complete'` 页脚样式 | ### 工具菜单(选项菜单) 选项菜单将全局搜索、主题切换、赞助链接等实用功能整合在一起。 ```javascript layout: { optionsMenu: { position: 'header', // 可选值:'header'、'sidebar-top'、'sidebar-bottom'、'menubar' components: { search: true, // 启用内置全文搜索 themeSwitch: true, // 启用明暗模式切换 sponsor: 'https://github.com/sponsors/your-profile' // 可选的赞助链接 } } } ``` ::: callout info 如果 `optionsMenu.position` 设置为 `header` 或 `menubar`,但对应容器已禁用,菜单将自动回退到 `sidebar-top`。 ::: ## 核心引擎功能 细化调整 `docmd` 处理和渲染文档内容的方式。 ```javascript minify: true, // 压缩生产资源(CSS/JS) autoTitleFromH1: true, // 如果 frontmatter 未设置 title,自动提取第一个 H1 作为页面标题 copyCode: true, // 自动为所有代码块添加“复制”按鈕 pageNavigation: true, // 在页面底部添加上一页/下一页导航链接 ``` ## 兖容旧版本 如果你将旧版 `docmd` 升级,以下键名会自动映射到新架构,保证向后兼容: * `siteTitle` → `title` * `siteUrl` / `baseUrl` → `url` * `srcDir` / `source` → `src` * `outDir` / `outputDir` → `out` ::: callout tip 运行 `docmd migrate` 可自动将配置文件升级到最新架构,同时自动备份原始配置。 ::: --- ## [重定向与 404](https://docs.docmd.io/zh/07/configuration/redirects/) --- title: "重定向与 404" description: "为静态部署配置基于元数据的重定向和自定义品牌化 404 错误页面。" --- 在静态托管环境中,没有服务端逻辑(如 Nginx 规则或 `.htaccess` 文件)来处理动态路由。`docmd` 通过自动生成原生 HTML 回退机制来解决重定向和错误状态问题。 ## 无服务器重定向 在 `redirects` 对象中定义映射规则,即可将旧 URL 的流量转发到新目标地址。 ```javascript export default defineConfig({ redirects: { '/setup': '/getting-started/installation', // 短 URL 跳转到深层链接 '/v1/api': '/api-reference' // 旧版本路径映射到新路径 } }); ``` ### 技术实现 定义重定向后,`docmd` 会在旧路径下创建一个包含 `<meta http-equiv="refresh">` 标签的 `index.html` 文件。这种方式可确保: 1. **无缝跳转**:页面加载后立即将用户转发到新目标地址。 2. **SEO 保护**:搜索引擎识别跳转关系,有助于保留链接权重。 3. **统计追踪**:在跳转发生前完成页面浏览统计,保留流量数据。 ## 品牌化 404 页面 当用户访问不存在的 URL 时,大多数静态托管服务(Netlify、Vercel、GitHub Pages)都会自动查找根目录下的 `404.html` 文件。`docmd` 默认生成该文件,并继承网站的主题、侧边栏和 SPA 功能。 ### 自定义错误页面内容 可在配置中自定义 404 错误信息: ```javascript export default defineConfig({ notFound: { title: '404:页面不存在', content: '找不到您请求的页面,请使用侧边栏导航返回。' } }); ``` ::: callout tip "本地开发调试" `docmd dev` 服务器会在找不到请求文件时自动提供自定义 404 页面,方便你在本地测试错误页面的效果。 ::: --- ## [版本管理](https://docs.docmd.io/zh/07/configuration/versioning/) --- title: "版本管理" description: "启用多版本文档管理,支持无缝切换、路径保留和独立构建目录。" --- `docmd` 内置了原生版本管理引擎,可同时管理和提供多个版本的项目文档(如 `v1.x`、`v2.x`)。引擎自动处理 URL 路由、侧边栏更新和版本切换逻辑。 ## 目录组织 启用版本管理前,需将文档组织到各版本的源文件夹中。常见做法是将最新版本保存在 `docs/`,旧版本存放在以 `docs-` 为前缀的目录中。 ```text my-project/ ├── docs/ # 最新版本(主版本) ├── docs-v1/ # 旧版本 ├── docmd.config.js ``` ## 配置 在 `versions` 对象中定义所有版本: ```javascript export default defineConfig({ versions: { current: 'v2', // 构建到根目录(/)的版本 ID position: 'sidebar-top', // 切换器位置:'sidebar-top' 或 'sidebar-bottom' all: [ { id: 'v2', dir: 'docs', label: 'v2.x(最新)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x' } ] } }); ``` ## 核心特性 ### 1. 根目录 SEO(「当前」版本) `current` 指定的版本将直接生成到输出根目录(如 `mysite.com/`),确保搜索流量始终落在最新文档上。 ### 2. 独立子目录 非当前版本将自动构建到以其 `id` 命名的子文件夹中: * `v2(当前)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. 粘性切换(路径保留) `docmd` 在用户切换版本时会保留相对路径。例如用户正在阅读 `mysite.com/getting-started`,切换到 **v1** 后将自动跳转到 `mysite.com/v1/getting-started`(如果该页面存在),而不是回到首页。 ### 4. 资源隔离 每个版本继承全局 `assets/` 目录,但 `docmd` 在构建过程中会对其进行隔离,防止样式泄露或版本冲突。 ### 5. 版本级导航 每个版本都可以维护自身独立的导航结构。`docmd` 使用级联优先级系统来解析侧边栏,允许你使用中央配置或特定版本/语言的 `navigation.json` 文件。 有关解析层级结构和视觉示例的详细信息,请参阅 [导航解析优先级](./navigation#daohang-jiexi-youxianji)。 ## 最佳实践 1. **语义化 ID**:使用简洁、URL 友好的 ID,如 `v1`、`v2` 或 `beta`。 2. **导航结构保持一致**:各版本之间保持一致的文件夹结构,以最大化「粘性切换」的效果。 3. **统一配置文件**:无需为每个版本单独准备配置文件,`docmd` 在一次构建过程中处理所有版本。 --- ## [按钮 (Buttons)](https://docs.docmd.io/zh/07/content/containers/buttons/) --- title: "按钮 (Buttons)" description: "通过单行语法注入用于内部路由或外部资源的呼吁操作按钮。" --- 按钮是用于突出导航的高影响力 UI 元素。与块容器不同,`button` 是 **自闭合的** - - 它定义在单行上,不需要结束标签 `:::`。 ## 语法 ```markdown ::: button "标签" 路径 [选项] ``` ### 选项参考 | 属性 | 格式 | 描述 | | :--- | :--- | :--- | | **路径 (Path)** | `/path/` | 相对项目 URL(会自动解析以用于 SPA 导航)。 | | **外部 (External)** | `external:URL`| 在新的浏览器标签页中打开目标 URL (`target="_blank"`)。 | | **颜色 (Color)** | `color:VALUE` | 应用背景颜色(支持 CSS 名称或十六进制代码)。 | | **图标 (Icon)** | `icon:NAME` | 在按钮标签前添加 [Lucide](external:https://lucide.dev/icons) 图标。 | ## 使用示例 ### 1. 内部导航 使用相对路径以确保在 `docmd` SPA 中实现无缝、零刷新的切换。 ```markdown ::: button "安装 docmd" /getting-started/installation ``` ::: button "安装 docmd" /getting-started/installation ### 2. 外部资源链接 在 URL 前面加上 `external:` 以确保安全的外部链接。 ```markdown ::: button "查看 GitHub 仓库" external:https://github.com/docmd-io/docmd ``` ::: button "查看 GitHub 仓库" external:https://github.com/docmd-io/docmd ### 3. 语义与品牌样式 使用颜色覆盖来使按钮符合你的品牌标识或语义优先级。 ```markdown ::: button "危险操作" /delete color:crimson ::: button "成功确认" /success color:#228B22 ``` ::: button "危险操作" ./#delete color:crimson ::: button "成功确认" ./#success color:#228B22 ### 4. 带有图标的按钮 添加 Lucide 图标以增强视觉清晰度。 ```markdown ::: button "开始使用" /getting-started/installation icon:arrow-right ::: button "查看源码" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "开始使用" /getting-started/installation icon:arrow-right ::: button "查看源码" external:https://github.com/docmd-io/docmd icon:github ## 关键提示:自闭合逻辑 由于按钮是自闭合的,添加结尾的 `:::` 行将终止按钮所在的 **父容器**(例如 Card 或 Tab),这可能会破坏你的布局。 **不正确的序列:** ```markdown ::: card "设置" ::: button "开始" /setup ::: <-- 错误:这将提前关闭 Card。 ::: ``` **正确的序列:** ```markdown ::: card "设置" ::: button "开始" /setup ::: <-- 正确:这将关闭 Card。 ``` --- ## [标注 (Callouts)](https://docs.docmd.io/zh/07/content/containers/callouts/) --- title: "标注 (Callouts)" description: "使用语义化的视觉区块突出显示关键警告、专业技巧和背景信息。" --- 标注用于隔离那些需要读者立即注意的信息。`docmd` 提供了五种语义类型,每种都具有独特的视觉样式和主题图标。 ::: callout info "迁移友好的别名" 如果您从 **VitePress** 或 **Docusaurus** 迁移,可以直接使用它们的原生语法: - `:::tip`、`:::warning`、`:::danger`、`:::info`(VitePress) - `:::note`、`:::caution`(Docusaurus) 这些别名的渲染效果与 `docmd` 等效语法完全相同。无空格语法如 `:::callout` 也同样支持。 ::: ## 语法参考 ```markdown ::: callout 类型 "可选标题" 技术内容或警告放在这里。 ::: ``` 添加可选的 `icon:` 参数,可以用任何 [Lucide](external:https://lucide.dev/icons) 图标覆盖默认的类型图标: ```markdown ::: callout info "自定义图标" icon:sparkles 此标注使用自定义图标而不是默认的 info 图标。 ::: ``` ### 支持的语义类型 | 类型 | 意图 | 视觉信号 | | :--- | :--- | :--- | | `info` | **通用数据** | 上下文背景或有用的非关键信息。 | | `tip` | **优化** | 性能捷径或“专业技巧”。 | | `warning`| **警告** | 潜在问题或需要关注的弃用功能。 | | `danger` | **危险** | 数据丢失风险、破坏性变更或系统故障。 | | `success`| **成功** | 成功配置或构建的确认。 | ## 实现展示 ### 1. 极简信息说明 ```markdown ::: callout info 旧版配置架构仍然受支持,但不再推荐使用。 ::: ``` ::: callout info 旧版配置架构仍然受支持,但不再推荐使用。 ::: ### 2. 带有自定义标题的高优先级警报 ```markdown ::: callout warning "破坏性变更目标" 自 `v0.7.0` 起,内部 WebSocket RPC 系统将正式弃用。 ::: ``` ::: callout warning "破坏性变更目标" 自 `v0.7.0` 起,内部 WebSocket RPC 系统将正式弃用。 ::: ### 3. 丰富内容组合 标注支持全方位的 Markdown,允许你在警报中嵌入按钮和代码块。 ````markdown ::: callout tip "优化的本地测试" icon:command 在开发过程中使用 preserve 标志来保留构建文件: ```bash docmd dev --preserve ``` ::: button "CLI 标志参考" /cli-commands ::: ```` ::: callout info "优化的本地测试" icon:command 使用 preserve 标志来保留构建文件: ```bash docmd dev --preserve ``` ::: button "CLI 标志参考" ./#cli-commands ::: ::: callout tip "AI 的优先逻辑" 对于 LLM,标注充当 **高优先级锚点 (High-Priority Anchors)**。通过使用 `::: callout danger` 来记录破坏性变更或系统限制,你可以提供一个清晰的信号,即 AI 模型在推理和生成过程中必须优先处理此信息。 ::: --- ## [Untitled](https://docs.docmd.io/zh/07/content/containers/cards/) --- ## [更新日志](https://docs.docmd.io/zh/07/content/containers/changelogs/) --- title: "更新日志" description: "生成结构化、基于时间线的版本历史记录和发布说明。" --- The `changelog` container provides a specialised layout for documenting project evolution. It automatically parses date or version headers into a vertical timeline, ensuring historical updates are easily scannable. ## 语法 使用专用的 `==` 分隔符定义条目。`==` 行上的文本渲染为左侧的时间线徽章,后续内容填充相邻的时间槽。 ```markdown ::: changelog == v2.0.0 重大功能发布说明。 == v1.5.0 维护更新和安全补丁说明。 ::: ``` ## 详细示例:发布历史 更新日志在每个条目中支持丰富的 Markdown,包括列表、提示框和代码块。 ```markdown ::: changelog == v2.0.0 (2026-03-15) ### 重大系统重构 核心引擎已针对同构执行进行重新架构。 * 实现了**SPA 路由器**,实现零刷新导航。 * 引入了**同构插件**系统。 ::: callout success 此版本初始构建速度提升 40%。 ::: == v1.5.1 (2025-12-10) ### 安全补丁 * 修复了内部解析器中的高危漏洞。 * 将依赖 `flatted` 升级至 `v3.3.2`。 == v1.0.0 (2024-05-01) 首次公开发布。 ::: ``` ::: changelog == v2.0.0 (2026-03-15) ### 重大系统重构 核心引擎已针对同构执行进行重新架构。 * 实现了**SPA 路由器**,实现零刷新导航。 * 引入了**同构插件**系统。 ::: callout success 此版本初始构建速度提升 40%。 ::: == v1.5.1 (2025-12-10) ### 安全补丁 * 修复了内部解析器中的高危漏洞。 * 将依赖 `flatted` 升级至 `v3.3.2`。 == v1.0.0 (2024-05-01) 首次公开发布。 ::: ::: callout tip "为 AI 提供历史上下文" 更新日志为 AI Agent 提供时间映射。当 LLM 解析 `llms-full.txt` 上下文时,`::: changelog` 结构使其能够准确识别特定功能、破坏性变更或安全修复的引入时间,从而提高开发建议的准确性。 ::: --- ## [折叠区块 (Collapsible Sections)](https://docs.docmd.io/zh/07/content/containers/collapsible/) --- title: "折叠区块 (Collapsible Sections)" description: "为常见问题、深度内容和剧透内容嵌入交互式手风琴式切换按钮。" --- `collapsible` 容器创建一个交互式的、可切换的区域(手风琴)。这种模式非常适合常见问题 (FAQ)、详细的技术配置,或任何应该在不干扰主要文档流程的情况下可以访问的次要信息。 ::: callout info "VitePress 别名" 如果您从 **VitePress** 迁移,可以使用 `:::details` 作为 `:::collapsible` 的别名。无空格语法如 `:::collapsible` 也同样支持。 ::: ## 语法 ```markdown ::: collapsible [open] "标题文本" 主要内容放在这里。 ::: ``` ### 选项参考 - **`open`**: (可选) 如果指定,该区域初始化时处于展开状态。 - **`"标题"`**: 渲染在交互式切换栏上的文本。如果省略,默认显示为 "点击以展开"。 - **`icon:NAME`**: (可选) 在标题文本前添加一个 [Lucide](external:https://lucide.dev/icons) 图标。 ## 详细实现示例 ### 标准用法 (初始状态:关闭) 主要用于常见问题或降低技术页面的视觉密度。 ```markdown ::: collapsible "如何升级 docmd?" 运行 `npm update -g @docmd/core` 来获取最新的稳定引擎。 ::: ``` ::: collapsible "如何升级 docmd?" 运行 `npm update -g @docmd/core` 来获取最新的稳定引擎。 ::: ### 选择性可见 (初始状态:打开) 非常适合那些默认应该可见,但允许用户将其最小化以获得更整洁视图的区域。 ```markdown ::: collapsible open "环境先决条件" 1. Node.js v18+ (推荐 LTS) 2. PNPM 包管理器 ::: ``` ::: collapsible open "环境先决条件" 1. Node.js v18+ (推荐 LTS) 2. PNPM 包管理器 ::: ### 嵌套技术数据 折叠区块可以包含复杂的 Markdown 元素,包括语法高亮的代码块。 ````markdown ::: collapsible "分析示例 JSON 响应" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "分析示例 JSON 响应" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ::: callout tip 虽然 `collapsible` 内部的内容可能对人类用户隐藏,但它对 `docmd` 搜索索引保持完全可见,并包含在统一的 `llms-full.txt` 流中。这确保了 AI 代理可以根据隐藏的技术细节提供全面的答案,同时人类界面保持整洁并具有优先级。 ::: --- ## [URL 嵌入 (Embeds)](https://docs.docmd.io/zh/07/content/containers/embed/) --- title: URL 嵌入 (Embeds) description: 如何安全地将动态组件、视频和社交媒体直接嵌入到你的文档中。 --- `docmd` 原生搭载了高度优化的 **[embed-lite](external:https://github.com/mgks/embed-lite)** 解析器生态系统。这允许你将原始外部 URL 严格映射到页面上,并瞬间将它们精美地转换为完全安全、零延迟的 UI 组件! ## 支持的平台 集成引擎原生公开了针对以下网络的结构化格式化程序: * **视频生态系统:** YouTube (包括原生 9:16 Shorts 支持), Vimeo, Dailymotion, TikTok * **社交连接:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **代码与原型:** GitHub Gists, CodePen, Figma, Google Maps * **音乐服务:** Spotify, SoundCloud ## 使用语法 你只需使用 `::: embed` 容器,后跟任何目标 URL。以下三种封闭格式是等效的: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### 标准结果示例 渲染引擎会在后台严格解析该 URL,检查验证矩阵,并将原生 HTML 节点直接结构化地注入到你的页面输出中: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## 降级安全 不用担心生成损坏的屏幕。如果内部解析器扫描到未经验证或严格不可用的域名配置映射,`docmd` 会优雅地降级为生成一个简单的、实心的 `<a>` 超链接按钮,明确指向目标: ```md ::: embed "https://docs.docmd.io/zh/content/containers/embed/" ``` *(接下来会生成你下面看到的内容)* ::: embed "https://docs.docmd.io/zh/content/containers/embed/" --- ## [网格 (Grids)](https://docs.docmd.io/zh/07/content/containers/grids/) --- title: "网格 (Grids)" description: "使用原生 markdown 容器,通过自动调整的响应式列无缝组织布局。" --- 网格在 `docmd` 中提供了一个原生的、由 markdown 驱动的布局系统。你可以利用 `grids` 容器来并排构建元素,而无需编写手动的 HTML 包装器。 列会自动调整宽度以填满可用空间,并在较小屏幕(移动设备)上逻辑地堆叠成垂直行。 ## 语法参考 ```markdown ::: grids ::: grid #### 组件 A 左侧的内容。 ::: ::: grid #### 组件 B 右侧的内容。 ::: ::: ``` ## 实际应用示例 ### 1. 并排展示功能 使用网格将关键功能并排展示,例如将结构化卡片与信息块结合。 ```markdown ::: grids ::: grid ::: card "速度 :rocket:" 建立在非阻塞 I/O 流水线上,以获得最高性能。 ::: ::: ::: grid ::: card "可扩展性 :zap:" 专为大规模 monorepos 和广泛的项目结构而设计。 ::: ::: ::: ``` ::: grids ::: grid ::: card "速度 :rocket:" 建立在非阻塞 I/O 流水线上,以获得最高性能。 ::: ::: ::: grid ::: card "可扩展性 :zap:" 专为大规模 monorepos 和广泛的项目结构而设计。 ::: ::: ::: ### 2. 布局平衡 网格将根据可用内容自动计算每列的最佳宽度(超宽屏幕上每行最多 4 个项目),并在窄视口上无缝分组行。 ::: callout tip "语义化布局" 使用 `grids` 容器可以使你的文档结构纯粹用 Markdown 编写,从而产生更整洁的源文件,并确保 LLM 完美地解释你的结构关系! ::: --- ## [英雄区块 (Hero Sections)](https://docs.docmd.io/zh/07/content/containers/hero/) --- title: "英雄区块 (Hero Sections)" description: "纯粹用 Markdown 构建高影响力的落地页页眉和营销亮点。" --- `hero` 容器可以创建专业且视觉冲击力强的落地页页眉。它可以处理复杂的 CSS 需求,如 **分割布局 (Split Layouts)**、**发光效果 (Glow Effects)** 和 **滑块 (Sliders)**,同时保持简洁的编写体验。 ## 基本语法 默认情况下,`hero` 会将其内容居中,非常适合横幅和简单的标题。 ```markdown ::: hero # 构建更快。 一行命令,从 Markdown 到生产文档。 ::: button "开始使用" /intro color:blue ::: ``` ## 高级布局 `hero` 容器支持专门的标志来控制其结构行为。 | 标志 | 效果 | | :--- | :--- | | `layout:split` | 将 hero 分为文本区域(左侧)和媒体区域(右侧)。在移动端垂直堆叠。 | | `layout:slider` | 将 hero 转换为具有滚动捕捉行为的水平滑块。 | | `glow:true` | 在背景中注入微妙的径向渐变发光。 | ### 分割布局 (`== side`) 使用 `== side` 分隔符来定义哪些内容放入主文本区域,哪些内容放入次要的“侧边”区域(通常是图像或视频嵌入)。 ```markdown ::: hero layout:split glow:true # docmd 2.0 同构执行。针对 AI 优化。 ::: button "快速开始" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 同构执行。针对 AI 优化。 ::: button "快速开始" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### 滑块布局 (`== slide`) 通过在不同的内容节点之间使用 `== slide` 分隔符来创建交互式 hero 滑块。 ```markdown ::: hero layout:slider == slide # 同构核心 引擎可在任何地方渲染。 == slide # AI 优化 为 LLM 时代而生。 ::: ``` ::: hero layout:slider == slide # 同构核心 引擎可在任何地方渲染。 == slide # AI 优化 为 LLM 时代而生。 ::: ## 响应式行为 `hero` 容器默认完全响应: - 在 **桌面端**,`layout:split` 并排显示。 - 在 **移动端**,它会自动转换为居中的垂直堆叠,以确保最佳的可读性。 ## 最佳实践 1. **发光效果**:在暗黑模式网站上谨慎使用 `glow:true`,以获得高级的“霓虹灯”感。 2. **媒体类型**:分割布局的“侧边”内容非常适合 `::: embed` 组件、高质量 PNG 或原始 `<video>` 标签。 3. **CTA 放置**:始终将 `::: button` 元素放置在主“Hero 副本”部分(在 `== side` 分隔符之前),以确保它们是用户在移动端看到的第一件东西。 --- ## [容器概览 (Containers Overview)](https://docs.docmd.io/zh/07/content/containers/) --- title: "容器概览 (Containers Overview)" description: "使用内置的交互式组件扩展标准的 Markdown,使你的文档从静态页面转变为功能丰富的应用。" --- `docmd` 容器允许你在不编写任何 HTML 或 CSS 的情况下,将复杂的 UI 元素(如按钮、卡片、折叠区块和选项卡)直接注入到你的文档源文件中。 ::: callout tip "从其他文档引擎迁移?" `docmd` 开箱即支持 **VitePress** 和 **Docusaurus** 的语法别名。`:::tip`、`:::warning`、`:::note`、`:::details` 和 `:::caution` 等容器无需修改即可工作。所有容器也支持无空格语法(例如 `:::tabs` 而不是 `::: tabs`)。 ::: ## 块语法参考 所有容器都使用一致的块语法,确保在整个项目中拥有可预测的编写体验。 ```markdown ::: 类型 "可选页眉标题" 这是主要内容区域。 它支持 **Markdown**、图像和深层组件嵌套。 ::: ``` | 组件 | 关键字 | 主要用例 | | :--- | :--- | :--- | | **[标注 (Callouts)](callouts.md)** | `callout` | 用于技巧、警告和警报的语义化突出显示。 | | **[卡片 (Cards)](cards.md)** | `card` | 用于功能网格和布局控制的有框结构块。 | | **[网格 (Grids)](grids.md)** | `grids` | 自动调整的多列结构组。 | | **[选项卡 (Tabs)](tabs.md)** | `tabs` | 用于替代平台说明的交互式可切换面板。 | | **[步骤 (Steps)](steps.md)** | `steps` | 用于“如何操作”指南和教程的视觉数字时间线。 | | **[标签 (Tags)](tags.md)** | `tag` | 用于版本、状态或突出的自闭合彩色标签。 | | **[按钮 (Buttons)](buttons.md)** | `button` | 自闭合、突出的呼吁操作导航链接。 | | **[折叠区块 (Collapsibles)](collapsible.md)**| `collapsible`| 用于 FAQ 和深度技术数据的交互式手风琴切换。 | | **[变更日志 (Changelogs)](changelogs.md)** | `changelog` | 结构化、基于时间线的版本历史和发布说明。 | | **[英雄区块 (Hero)](hero.md)** | `hero` | 具有布局和滑块支持的高影响力落地页部分。 | ## 容器的战略重要性 容器的作用不仅仅是视觉上的点缀;它们向 `docmd` 引擎和下游 AI 代理提供高保真的 **语义信号 (Semantic Signals)**: 1. **AI 上下文映射**:将一个块标记为 `callout warning` 会明确告诉 LLM 在其推理和生成阶段优先考虑该信息。 2. **结构完整性**:将 `cards` 与标准 CSS 结合使用,可以在不离开 Markdown 环境的情况下创建复杂的落地页。 3. **源码可维护性**:消除文档源码中的“HTML 臃肿”,保持 `.md` 文件整洁且机器可读。 ## 递归组合 `docmd` 支持 **无限嵌套深度**。你可以在一个容器内组合任何其他容器,纯粹用 Markdown 构建复杂的交互式文档节点。 ```markdown ::: card "架构概览" ::: callout info 此模块利用异步 I/O 流水线。 ::: ::: button "深入核心引擎" /advanced/developer-guide ::: ``` --- ## [嵌套容器](https://docs.docmd.io/zh/07/content/containers/nested-containers/) --- title: "嵌套容器" description: "利用 docmd 的递归解析器将卡片、标签页和提示框组合成高保真页面布局。" --- One of `docmd`’s most powerful technical capabilities is its **Recursive Parsing Engine**. You can nest components within each other infinitely to synthesize complex, interactive documentation blocks that would otherwise require deep HTML knowledge or custom templates. ## 架构规则 虽然嵌套在数学上无限,但请始终遵循**自闭合组件规则**: ::: callout warning "自闭合按钮" 由于 `::: button` 组件是自闭合的(单行),绝不要在其后添加终止 `:::` 行。否则会意外关闭容纳按钮的**父容器**,导致布局断裂。 ::: ## 技术组合示例 ### 1. 交互式资源块 将**卡片**用于结构框架,**标签页**用于特定环境的说明,**提示框**用于高亮关键信息。 ````markdown ::: card "Monorepo 快速开始" 选择你偏好的初始化方式: ::: tabs == tab "自动化" ```bash pnpm onboard ``` ::: callout success 此脚本自动处理所有包安装和构建任务。 ::: == tab "手动" 手动获取并链接核心引擎。 ::: button "前往开发者指南" /advanced/developer-guide ::: ::: ```` ### 2. 多平台教程 将**标签页**嵌套在**步骤**中是标准教程序列中提供平台特定说明的专业模式。 ```markdown ::: steps 1. **环境设置** 配置本地操作系统。 ::: tabs == tab "macOS" 确保 Homebrew 已安装并为最新版本。 == tab "Linux" 验证 `curl` 和 `bash` 是否存在。 ::: 2. **核心验证** 执行版本检查以确认连接性。 ::: ``` ::: steps 1. **环境设置** 配置本地操作系统。 ::: tabs == tab "macOS" 确保 Homebrew 已安装并为最新版本。 == tab "Linux" 验证 `curl` 和 `bash` 是否存在。 ::: 2. **核心验证** 执行版本检查以确认连接性。 ::: ## 设计约束 为保持性能和移动端响应性,请遵守以下约束: * **递归标签页**:在标签页中嵌套标签页在技术上受支持,但强烈不建议。在小视口上会造成混乱的导航"循环"。 * **顺序冲突**:如果需要在标签页内使用编号步骤,请使用标准有序列表(`1. 步骤内容`)而非 `::: steps` 容器,以避免布局冲突。 * **可读性**:虽然 `docmd` 不严格要求嵌套块的缩进,但使用 2 或 4 个空格的缩进可显著提高 Markdown 源码的可读性。 ::: callout tip "为 AI 提供知识分割" 嵌套提供清晰的**语义边界**。当 AI Agent 解析 `llms-full.txt` 流时,嵌套在 `card` 中的 `callout` 明确告知模型该提示的范围限定于该卡片的特定主题,防止上下文泄漏并提高生成响应的技术准确性。 ::: --- ## [步骤](https://docs.docmd.io/zh/07/content/containers/steps/) --- title: "步骤" description: "将标准有序列表转化为高冲击力的可视化时间线和教程。" --- The `steps` container is designed specifically for "How-to" guides and technical tutorials. It transforms a standard Markdown ordered list into a polished, numbered vertical timeline with automatic spacing and visual emphasis. ## 语法 将任意标准有序列表包裹在 `::: steps` 块中。 ```markdown ::: steps 1. **初始化项目** 运行 `docmd init` 命令搭建目录结构。 2. **编写内容** 使用标准 Markdown 文件编写文档。 3. **构建与部署** 使用 `docmd build` 生成静态资源。 ::: ``` ## 详细实现 `steps` 组件支持在每个条目中使用丰富的 Markdown 内容,包括代码块、图片和嵌套容器。 ```markdown ::: steps 1. **生成生产构建** 执行构建命令以生成高度优化的静态站点。 ```bash docmd build ``` 2. **验证资源完整性** 检查 `site/` 目录,确保所有资源均已正确编译。 3. **部署到基础设施** 将 `site/` 目录同步到你的主要托管提供商(如 S3、Cloudflare Pages 或 Vercel)。 ::: ``` ::: steps 1. **生成生产构建** 执行构建命令以生成高度优化的静态站点。 ```bash docmd build ``` 2. **验证资源完整性** 检查 `site/` 目录,确保所有资源均已正确编译。 3. **部署到基础设施** 将 `site/` 目录同步到你的主要托管提供商(如 S3、Cloudflare Pages 或 Vercel)。 ::: ## 高级嵌套 你可以在步骤内嵌套其他文档组件(如**提示框**或**按钮**),而不会中断序列的时间流。 ```markdown ::: steps 1. **配置环境** 在 `docmd.config.js` 中定义项目特定变量。 ::: callout tip 使用 `defineConfig` 可为配置键启用 IDE 自动补全。 ::: 2. **验证架构** 运行 `docmd verify` 确保配置结构正确。 ::: ``` ::: callout tip "工作流优化" 现代 AI 模型将 `steps` 容器解读为**顺序工作流**的高保真信号。为最大化 `llms-full.txt` 上下文中的 AI 准确性,请始终以**加粗标题**开头每个列表项。这允许 Agent 在处理实现细节之前可靠地解析每个步骤的目标。 ::: --- ## [选项卡 (Tabs)](https://docs.docmd.io/zh/07/content/containers/tabs/) --- title: "选项卡 (Tabs)" description: "将密集、替代或多语言信息组织到可切换的交互式面板中。" --- 选项卡是在紧凑、交互式的格式中展示互斥或相关数据集(例如,“通过 NPM 与 Yarn 安装”或“macOS 与 Windows”指令)的最佳 UI 模式。 ## 语法参考 `tabs` 容器使用专门的子分隔符 `== tab "标签"`。你可以选择使用 `icon:name` 语法添加图标。 ```markdown ::: tabs == tab "标签 1" icon:rocket 第一个选项卡的内容。 == tab "标签 2" icon:settings 第二个选项卡的内容。 ::: ``` ## 实现展示 ### 1. 包管理 选项卡最常用于在单个视图中显示不同包管理器的安装说明。 ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. 多语言代码片段 通过分离不同的编程语言或环境来保持逻辑整洁。 ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.js'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.js'); ``` ::: ## 核心能力 ### 同构延迟渲染 `docmd` 实现了 **条件资源延迟 (Conditional Resource Laziness)**。如果选项卡包含计算密集型元素(例如 **Mermaid.js** 图表或高分辨率图像),则仅在用户激活该特定选项卡时才初始化并渲染这些资源。这确保了初始页面的快速加载。 ### 状态持久化 默认的 SPA 路由器会在类似的文档页面之间跟踪活动选项卡的索引。如果用户在某一页选择了“pnpm”,并导航到另一页具有匹配选项卡结构的页面,则“pnpm”选项卡将自动保持活动状态。 ## 技术约束 | 约束 | 说明 | | :--- | :--- | | **嵌套深度** | 为了保持布局完整性,选项卡不能嵌套在其他选项卡组件内。 | | **交互冲突**| 高冲突语法:要在选项卡内嵌套“步骤”,请使用标准有序列表 (`1. 第一步`) 而不是 `::: steps` 容器。 | | **响应限制** | 建议将每个区块的选项卡数量限制在 6 个以内,以确保移动设备兼容性。 | ::: callout tip "AI 上下文映射" 在将选项卡用于代码片段时,始终直接在选项卡标签中包含目标语言(例如 `== tab "TypeScript"`)。这允许 LLM 从 `llms-full.txt` 上下文流中立即识别并提取技术相关的部分。 ::: --- ## [标签 (Tags)](https://docs.docmd.io/zh/07/content/containers/tags/) --- title: "标签 (Tags)" description: "使用标签容器在行内无缝标注版本、状态或突出显示短文本片段。" --- `tag` 容器是一个自闭合组件,用于直接在文本中插入小巧的药丸状徽章。与块容器不同,标签不会继承父元素(如标题)的巨大尺寸,无论放置在哪里,它们都会保留紧凑、整洁的比例。 ## 基本用法 要创建一个基本标签,只需提供你想要显示的文本: ::: tabs == tab "预览" 此功能已在 ::: tag "v0.7.4" color:blue 中添加,且运行完美。 == tab "Markdown 源码" ```markdown 此功能已在 ::: tag "v0.7.4" 中添加,且运行完美。 ``` ::: ## 自定义颜色 你可以通过提供任何有效的 CSS 颜色字符串(例如 `#ff0000`、`blue` 或 `hsl(...)`),使用 `color:` 属性来覆盖默认的标签样式。`docmd` 会自动计算出精美的淡色背景,并配以对比完美的文本和边框! ::: tabs == tab "预览" ::: tag "已弃用" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "稳定版" color:#22c55e == tab "Markdown 源码" ````markdown ::: tag "已弃用" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "稳定版" color:#22c55e ```` ::: ## 添加图标 就像按钮和标注一样,你可以使用 `icon:` 属性轻松附加来自 `docmd` 图标库的图标。 ::: tabs == tab "预览" ::: tag "已验证" icon:check-circle color:#10b981 == tab "Markdown 源码" ````markdown ::: tag "已验证" icon:check-circle color:#10b981 ```` ::: ## 链接标签 如果你需要标签充当超链接(例如,将版本标签直接链接到其发布说明),可以使用 `link:` 属性。外部链接会被自动检测并在新标签页中打开。 ::: tabs == tab "预览" 查看最新的 ::: tag "发行说明" icon:external-link link:/release-notes/0-7-4 == tab "Markdown 源码" ````markdown 查看最新的 ::: tag "发行说明" icon:external-link link:/release-notes/0-7-4 ```` ::: ## 在标题中使用标签 因为标签是真正的行内元素,所以当用于标记主标题时,它们看起来非常华丽。它们会自动对齐到基线,而不会继承标题巨大的字体大小。 ::: tabs == tab "预览" # 搜索过滤 ::: tag "新" color:#8b5cf6 == tab "Markdown 源码" ````bash # 搜索过滤 ::: tag "新" color:#8b5cf6 ```` ::: --- ## [Frontmatter 参考](https://docs.docmd.io/zh/07/content/frontmatter/) --- title: "Frontmatter 参考" description: "docmd 中页面级元数据与配置的完整指南。" --- Frontmatter 允许你在单个页面上覆盖全局设置。它心须写在 Markdown 文件最顶部,以 YAML 格式编写。 ## 核心元数据 | 键名 | 类型 | 说明 | | :--- | :--- | :--- | | `title` | `String` | **必填。** 设置 HTML `<title>` 和页面主标题。 | | `description` | `String` | SEO 和搜索结果的元描述。 | | `keywords` | `Array` | `<meta name="keywords">` 标签的关键词列表。 | ::: callout warning "标题很重要" 虽然并非必填,但强烈建议填写 `title`。如果缺失,docmd 会回退到第一个 `# H1` 标题或文件名作为标题,可能产生不理想的 `<title>` 标签和搜索结果。 ::: ## 显示与索引 | 键名 | 类型 | 说明 | | :--- | :--- | :--- | | `noindex` | `Boolean` | 将该页面排除在内部搜索索引之外。 | | `llms` | `Boolean` | 设为 `false` 可将该页面排除在 AI 上下文文件(`llms.txt`)之外。 | | `hideTitle` | `Boolean` | 隐藏固定头部中的标题(当使用自定义 H1 时很有用)。 | | `bodyClass` | `String` | 为该页面的 `<body>` 标签添加自定义 CSS 类。 | ## 布局控制 | 键 | 类型 | 说明 | | :--- | :--- | :--- | | `layout` | `String` | 设为 `full` 使用主内容宽度并隐藏目录侧边栏。 | | `toc` | `Boolean` | 设为 `false` 完全禁用目录。 | | `noStyle` | `Boolean` | 为自定义页面禁用整个 `docmd` UI(侧边栏、Header、Footer)。 | | `titleAppend` | `Boolean` | 设为 `false` 可防止将站点标题附加到 `<title>`、OpenGraph (`og:title`) 和 Twitter 元数据标签。默认值:`true`。 | ### `noStyle` 组件控制 `noStyle: true` 启用时,必须显式选择要保留的组件: ```yaml --- noStyle: true components: meta: true # 注入 SEO 元数据 favicon: true # 注入站点 favicon css: true # 注入 docmd-main.css theme: true # 注入主题特定样式 highlight: true # 注入语法高亮 scripts: true # 注入 SPA 路由器逻辑 sidebar: true # 注入导航侧边栏 footer: true # 注入站点页脚 --- ``` ## 插件覆盖 ### SEO(`seo`) * `image`:页面的自定义社交分享图片 URL。 * `aiBots`:设为 `false` 可阻止 AI 爬虫访问此页面。 * `canonicalUrl`:为 SEO 设置自定义规范链接。 --- ## [实时预览 (Live Preview)](https://docs.docmd.io/zh/07/content/live-preview/) --- title: "实时预览 (Live Preview)" description: "将 docmd 渲染引擎集成到你自己的 Web 界面中,以实现即时、在浏览器中进行的文档预览。" --- `docmd` 实时预览架构允许你将生产级的 Markdown 渲染引擎直接引入到自定义编辑器、CMS 仪表板或基于 Web 的 IDE 中。 ### 1. 资源集成 从你的资源目录或 CDN 中包含所需的 CSS 和 JavaScript 捆绑包: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. 同构 API 全局 `docmd` 对象提供了用于瞬时渲染的 `compile` 方法。 ```javascript const html = await docmd.compile(markdown, { siteTitle: 'Dynamic Preview', theme: { appearance: 'dark' } }); // 注入到 iframe 中以实现样式隔离 document.getElementById('preview-frame').srcdoc = html; ``` ::: callout tip "AI 反馈循环" 实时架构是构建 **AI 代理沙箱 (AI-Agent Sandboxes)** 的理想选择。你可以将 AI 建议的文档更改通过管道传输到实时编译缓冲区,而不是直接授予代理文件系统写入权限。这允许你在将更改提交到存储库之前,在“影子”环境中直观地验证 AI 的建议。 ::: --- ## [docmd : Bespoke No-Style Page Demo](https://docs.docmd.io/zh/07/content/no-style-example/) --- title: "docmd : Bespoke No-Style Page Demo" description: "noStyle 架构功能的实际演示。" noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: center; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-color); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>定制页面架构</h1> <p>演示通过 <code>noStyle: true</code> 实现的绝对布局控制。</p> </div> <div class="demo-card"> <h2>逻辑基础</h2> <p> 本演示使用 <code>noStyle: true</code> frontmatter 指令绕过全局文档布局(侧边栏、Header 和目录)。这提供了一个"零阻力"画布,用于创建营销落地页或自定义产品仪表盘。 </p> <h3>已启用的系统组件</h3> <p>在 No-Style 模式下,你需要明确选择文档引擎的核心功能:</p> <ul> <li><strong>SEO 元引擎</strong>:结构化标签和社交图谱数据被保留。</li> <li><strong>项目品牌</strong>:全局 favicon 注入保持活跃。</li> <li><strong>基础排版</strong>:处理后的 <code>docmd-main.css</code> 提供基础样式。</li> <li><strong>主题同步</strong>:浅色/深色模式状态完全保留。</li> <li><strong>交互能力</strong>:SPA 路由器和组件逻辑保持可用。</li> </ul> <h3>技术实现</h3> <p> 此页面的布局使用标准 HTML 包装器和在 <code>customHead</code> frontmatter 字段中定义的作用域 CSS 编写。这确保了零 CSS 泄漏到文档站点的其余部分。 </p> <a href="/content/no-style-pages/" class="demo-button">分析实现指南 →</a> </div> </div> --- ## [无样式页面](https://docs.docmd.io/zh/07/content/no-style-pages/) --- title: "无样式页面" description: "通过禁用默认 docmd 主题创建自定义落地页和独特布局。" --- `docmd` 允许你在单个页面上跳过标准文档布局(侧边栏、头部和页脚)。这非常适合创建产品落地页、自定义仪表盘或运营起始页,同时沉淦使用文档引擎的各种组件。 ## 启用无样式模式 在页面的 frontmatter 中添加 `noStyle: true` 即可禁用全局 UI。 ```yaml --- title: "产品展示" noStyle: true components: meta: true # 保留 SEO 和 OpenGraph 标签 favicon: true # 保留网站图标 css: true # 注入 docmd-main.css 用于排版 --- <!-- 原生 HTML 或特殊 Markdown 放在这里 --> <div class="hero"> <h1>下一代文档</h1> <p>零配置。同构。AI 就绪。</p> </div> ::: callout info "无限层级嵌套" 即使开启 `noStyle: true`,所有标准 `docmd` 容器(如 `::: card`、`::: tabs`、`::: hero`)仍完全可用,并可以无限深度嵌套。 ::: ``` ## 组件单独启用 开启 `noStyle` 后,页面从空白画布开始。根据需要选择性地开启核心组件: | 组件 | 说明 | | :--- | :--- | | `meta` | 注入 `<title>`、SEO 元标签和 OpenGraph 结构化数据。 | | `favicon` | 注入项目全局网站图标。 | | `css` | 注入 `docmd-main.css`。强烈建议开启,提供基础网格和排版。 | | `menubar` | 注入网站顶部菜单栏。 | | `theme` | 注入当前主题的 CSS 变量和外观覆盖。 | | `scripts` | 注入交互组件逻辑(需要 `mainScripts: true`)。 | | `spa` | 启用单页应用路由(需要 `scripts: true`)。 | ## 组合式落地页 `noStyle` 的核心优势在于:它允许你将所有 `docmd` 组件使用为在空白画布上的高价值“小插件”。你不局限于原始 HTML,可以纯簹用 Markdown 构建复杂的结构化设计。 ### 打造现代入口页 ```yaml --- title: "欢迎使用" noStyle: true components: meta: true css: true menubar: true # 使用网站顶部导航 scripts: true spa: true --- ::: hero # 下一代文档 沈浸式, 18kb, AI 就绪. ::: button "立马开始" /getting-started/quick-start ::: ``` ::: callout tip "AI 辅助布局设计" `noStyle` 页面同时支持原生 HTML 和 `docmd` 容器,因此非常适合 **AI 驱动的 UI 设计**。你可以提示 AI:*"使用 Tailwind 风格的工具类和 docmd 按钮设计一个现代 hero 区块,封装在 noStyle: true 容器中。"* AI 即可在你的静态网站流水线中快速迭代设计,无需任何额外配置。 ::: --- ## [高级 Markdown 语法](https://docs.docmd.io/zh/07/content/syntax/advanced/) --- title: "高级 Markdown 语法" description: "充分利用 docmd 的扩展功能:自定义属性、GFM 扩展与语义定义。" --- 除标准 Markdown 外,`docmd` 还支持多种源自 GitHub Flavored Markdown (GFM) 和自定义属性插件的高保真扩展。这些工具可让你完全掌控文档的结构与样式。 ## GFM 扩展 ### 任务列表 创建可交互或只读的检查列表,适用于路线跟踪。 ```markdown - [x] 引擎优化完成 - [ ] 插件 API 内容确定 ``` - [x] 引擎优化完成 - [ ] 插件 API 内容确定 ### 自动链接识别 标准 URL 和电子邮件地址会被自动识别并转化为链接,无需额外标记:`https://docmd.io` ### 短代码 Emoji `docmd` 支持标准短代码,可为文档增添视觉趣味。 > 我们 :heart: 高性能文档!:rocket: :smile: ## 自定义元素属性 使用花括号 `{}` 语法可为标题、图片和链接添加唯一 ID 和 CSS 类。这是应用 [自定义 CSS 样式](../../theming/custom-css-js.md) 的主要方式。 ### 唯一语义 ID 用于直接定位到技术子章节的深层链接。 ```markdown ## 性能基准测试 {#benchmarks-2026} ``` ### CSS 功能类 为特定元素应用样式工具。 ```markdown ## 居中对齐章节 {.text-center .text-blue} ``` ### 按鈕链接 将任意标准 Markdown 链接转化为样式化的行动履用按鈕。 ```markdown [下载最新版本](#download){.docmd-button} ``` ## 引用与定义 ### 脚注引用 添加引用或技术深层内容[^1],自动收集并在页跟渲染。 ```markdown 架构决策记录在 RFC[^1] 中。 [^1]: RFC-42: 同构渲染流水线。 ``` ### 定义列表 非常适合 API 参数说明和词汇表。 ```markdown PropName : 该配置项的唯一标识符。 ``` PropName : 该配置项的唯一标识符。 ### 节略词生成 在页面中全局定义节略词,悬停时显示完整定义。 ```markdown *[SPA]: Single Page Application docmd 路由器带来流畅的 SPA 体验。 ``` *[SPA]: Single Page Application docmd 路由器带来流畅的 SPA 体验。 ::: callout tip "AI 上下文精确性" 使用**定义**和**节略词**可为 AI Agent 提供高质量的技术信号。当 AI 处理你的 `llms-full.txt` 上下文时,这些明确的定义可防止词义模糊,确保模型为项目特定术语生成逻辑正确的解释。 ::: --- ## [代码块](https://docs.docmd.io/zh/07/content/syntax/code/) --- title: "代码块" description: "高保真语法高亮与一键复制按钮,清晰呈现技术实现细节。" --- `docmd` 使用超快速的 `lite-hl` 引擎,为数百种编程语言和配置格式提供自动、上下文感知的语法高亮。 ## 语法高亮 使用标准 Markdown 代码围斜线语法编写技术示例。始终指定语言标识符,确保高亮引擎应用正确的词法规则。 ````markdown ```javascript function initialize() { console.log("docmd engine active."); } ``` ```` **Rendered Result:** ```javascript function initialize() { console.log("docmd engine active."); } ``` ::: callout tip "一键复制" 开启配置中的 `copyCode: true`(默认开启)后,每个代码块右上角悬停时会自动显示复制按鈕,方便用户将代码片段直接复制到 IDE。 ::: ## AI 上下文策略 编写面向 LLM 和 AI Agent 的代码文档时,建议遵循以下最佳实践: 1. **严格语言标注**:明确标注为 `typescript`、`bash` 或 `json`,确保 AI 解析器在 `llms-full.txt` 流中准确解析代码块的语法。 2. **嵌入意图**:在代码块中使用内联注释解释复杂逻辑背后的原因。这为 AI 提供了关键的推理上下文,而这是代码块外的简单文本难以传达的。 ## 支持的语言 `docmd` 开筱即用地支持最常用的技术生态系统,包括: * **逻辑语言**:`javascript`、`typescript`、`python`、`rust`、`go`、`ruby`、`csharp`。 * **Web**:`html`、`css`、`markdown`。 * **数据与 Shell**:`json`、`yaml`、`bash`、`powershell`、`dockerfile`。 * **文档**:`mermaid`、`changelog`。 --- ## [图片与视觉媒体](https://docs.docmd.io/zh/07/content/syntax/images/) --- title: "图片与视觉媒体" description: "掌握媒体管理:响应式图片、样式属性与自动 Lightbox 效果。" --- `docmd` 使用标准 Markdown 语法集成媒体资源。建议将媒体资源集中存放在项目源目录的 `assets/images/` 文件夹中。 ```markdown ![技术架构图](/assets/images/architecture.png "可选提示标题") ``` ## 样式属性参考 使用 `{ .class }` 属性语法可直接为图片添加 CSS 类。 ### 动态缩放 ```markdown ![小尺寸](/assets/icon.png){ .size-small } ![标准视图](/assets/preview.png){ .size-medium } ![全尺寸](/assets/banner.png){ .size-large } ``` ### 对齐与布局 ```markdown ![居中](/assets/img.png){ .align-center } ![右对齐](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![高级样式示例](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-center} ## 结构化媒体元素 ### 图片标题 对于精确的可访问性媒体标注,建议使用标准 HTML5 `<figure>` 元素。 ```html <figure> <img src="/assets/diagram.png" alt="云基础架构图"> <figcaption>图 1.1:核心系统基础架构。</figcaption> </figure> ``` ### 图片画廊 使用 `image-gallery` 类将多张图片整理到响应式均衡网格中。 ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="用户仪表盘视图"> <figcaption>应用性能监控</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="配置面板视图"> <figcaption>项目全局设置</figcaption> </figure> </div> ``` ## 交互式 Lightbox 缩放 开启 `mainScripts` 组件(默认开启)后,`docmd` 会自动为画廊内的图片或带有 `.lightbox` 类的图片应用全屏缩放效果。 ```markdown ![深层纹理分析](/assets/sample.png){ .lightbox } ``` ::: callout tip "AI 上下文与可访问性" 媒体内容始终要提供全面的 **Alt 文本**。虽然高级 AI 模型具备视觉能力,但 Markdown 源文件中的描述性文本为模型推理引擎提供了直接、高保真的信号,有助于增强 `llms-full.txt` 流中的架构分析和功能理解。 ::: --- ## [Markdown 语法基础](https://docs.docmd.io/zh/07/content/syntax/) --- title: "Markdown 语法基础" description: "掌握 docmd 的基础格式规则:标题、排版样式和技术块。" --- `docmd` 遵循标准 **GitHub Flavored Markdown (GFM)** 规范。本指南建立了在整个文档网站中编写核心内容的基准标准。 ## 排版样式 | 属性 | Markdown 语法 | 视觉效果 | | :--- | :--- | :--- | | **强调** | `**Text**` | **粗体技术术语** | | **斜体** | `*Text*` | *斜体变量* | | **删除线** | `~~Text~~` | ~~已废弃逻辑~~ | | **内联代码** | `` `code` `` | `engine.initialize()` | ## 结构元素 ### 语义化标题层次 ```markdown # 一级标题(通过 Frontmatter 自动生成) ## 二级标题(主要章节) ### 三级标题(功能细节) ``` ::: callout tip "AI 逻辑完整性" 高级 AI 模型和搜索索引器依靠严格的标题层次结构来建立对项目的精确理解。避免"跳级标题"(如从 H2 直接跳到 H4),可确保 `llms-full.txt` 上下文流在时序和逻辑上保持连贯。 ::: ### 导航与引用 内部文档节点和外部资源均使用标准链接语法。 ```markdown [外部资源](https://docmd.io) [内部模块](../api/node-api.md) ``` ### 枚举与列表 * **无序列表**:使用 `*` 或 `-` 创建易于扫描的项目符号。 * **有序逻辑**:使用 `1.`、`2.` 等表示有序步骤。(对于教程,建议使用高级**[步骤容器](../containers/steps)**。) ## 技术块级元素 ### 引用块 标准 `>` 语法非常适合突出显示外部引用或背景上下文。 > docmd 引擎重新定义了静态站点生成与动态应用交付之间的边界。 ### 数据表格 | 属性 | 数据类型 | 默认值 | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## 原生 HTML 支持 `docmd` 启用了原生 HTML 解析,你可以直接在 Markdown 文件中嵌入复杂布局或特殊样式,满足个性化 UI 需求。 ```html <div style="padding: 2rem; border: 1px solid var(--border-color); border-radius: 12px; text-align: center;"> 自定义 UI 元素放在这里。 </div> ``` --- ## [链接与引用 (Linking & Referencing)](https://docs.docmd.io/zh/07/content/syntax/linking/) --- title: "链接与引用 (Linking & Referencing)" description: "通过 docmd 的自动 URL 规范化功能,掌握内部交叉链接、外部资源和可靠的资源引用。" --- `docmd` 提供了一个强大的、具有文件系统感知能力的链接系统。你可以自然地编写指向源 `.md` 文件的链接 - - 使用你喜欢的任何格式 - - 引擎会自动将它们规范化为干净、经过 SEO 优化的生产环境 URL。 ::: callout info "自然编写,完美交付" 你不需要遵循任何特殊的链接约定。无论你写的是 `overview.md`、`overview/` 还是仅仅是 `overview`,构建引擎都会生成相同的干净、带有尾随斜杠的 URL。每个内部链接在构建时都会自动规范化,因此你可以专注于内容,而不是 URL 格式。 ::: ## URL 规范化是如何工作的 在构建过程中,引擎会对每一个内部链接(包括 Markdown 文本、按钮容器、标签和导航配置中的链接)应用一套一致的规则: | 你编写的内容 | 渲染后的内容 | 原因 | | :--- | :--- | :--- | | `overview.md` | `overview/` | 剥离 `.md` 扩展名,添加尾随 `/` | | `overview` | `overview/` | 自动添加尾随 `/` | | `overview/` | `overview/` | 已经正确 - - 无需更改 | | `api/commands.md` | `api/commands/` | 规范化子目录链接 | | `localisation/index.md` | `localisation/` | 剥离 `index` - - 文件夹是规范 URL | | `../index.md` | `../` | 清洁地解析父目录索引 | | `overview.md#settings` | `overview/#settings` | 在规范化过程中保留哈希片段 | | `./guide.md` | `./guide/` | 保留相对前缀 | | `https://example.com` | `https://example.com` | 外部链接保持不变 | ::: callout tip "SEO 最佳实践" 所有内部页面都作为以尾随斜杠结尾的目录样式 URL 提供(例如,`/configuration/overview/`)。这是静态网站的行业标准,可以防止 301 重定向链,并确保搜索引擎索引的一致规范 URL。 ::: ## 内部链接解析 使用指向源 `.md` 文件的相对路径来链接到文档中的其他页面。无论目录深度如何,引擎都能正确解析它们。 | 目标策略 | Markdown 语法 | | :--- | :--- | | **同级页面** | `[系统概览](overview.md)` | | **子目录** | `[API 参考](api/node-api.md)` | | **子目录索引** | `[本地化](localisation/index.md)` | | **父目录** | `[回到首页](../index.md)` | ## 章节锚点 (深层链接) 使用标准的 URL 哈希片段直接导航到特定标题。 * **页内锚点**: `[跳转到路线图](#project-roadmap)` * **跨页锚点**: `[查看 CLI 标志](../cli-commands.md#available-flags)` 哈希片段在规范化过程中会被保留。上面的链接在生产环境中渲染为 `../cli-commands/#available-flags`。 ## 在新标签页中打开链接 在任何链接上使用 `external:` 前缀强制其在新标签页中打开。这在标准 Markdown 链接、按钮容器、标签以及任何可以编写 URL 的地方都是通用的。 ```markdown <!-- 强制任何链接在新标签页中打开 --> [在新标签页中打开](external:./configuration/overview.md) <!-- 指向 GitHub 的外部链接 --> [GitHub](external:https://github.com/docmd-io/docmd) ``` 默认情况下,所有链接(包括 HTTP/HTTPS)都在同一个窗口中打开。仅当你想要一个新标签页时才使用 `external:` 前缀。 `external:` 前缀会从渲染后的 URL 中 **剥离** - - 它纯粹是一个构建时信号。 ## 链接到原始文件 默认情况下,引擎会剥离 `.md` 扩展名并规范化路径。如果你确实需要链接到原始 `.md` 文件(例如,可下载的源文件),请使用 `raw:` 前缀: ```markdown [查看原始源码](raw:docs/readme.md) ``` `raw:` 前缀会绕过所有规范化 - - 扩展名和路径将完全按照编写的方式保留。与 `external:` 一样,前缀本身会从渲染后的 URL 中剥离。 ## 按钮容器 (Button Containers) `::: button` 容器支持与标准 Markdown 链接相同的链接约定 - - 包括 `external:` 和 `raw:` 前缀: ```markdown ::: button "开始使用" ./getting-started/quick-start.md icon:rocket ::: button "在 GitHub 上查看" https://github.com/docmd-io/docmd icon:github ::: button "下载源码" raw:docs/readme.md icon:download ``` ## 标签链接 (Tag Links) 带有 `link:` 值的标签也受益于统一规范化器: ```markdown ::: tag "v0.7.6" link:release-notes/0-7-6.md icon:tag color:#22c55e ::: tag "GitHub" link:https://github.com/docmd-io/docmd icon:github ::: tag "从外部打开" link:external:./configuration/overview.md icon:external-link ``` ## 导航配置 在 `navigation.json` 和 `docmd.config.js` 中定义的路径也会在构建时进行规范化。你可以使用任何格式编写它们: ```json "navigation.json" [ { "title": "Overview", "path": "configuration/overview" }, { "title": "Overview", "path": "configuration/overview.md" }, { "title": "Overview", "path": "configuration/overview/" } ] ``` 上面的三个条目都会生成相同的规范 URL:`/configuration/overview/`。 对于应该在新标签页中打开的导航项目,请使用 `external` 标志: ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "导航中的索引页" 在链接到目录的索引页时,请使用文件夹路径,而不是显式引用 `index.md`。两者工作方式相同,但文件夹路径更整洁: ```markdown <!-- 推荐 --> [本地化](localisation/) <!-- 同样有效(自动规范化) --> [本地化](localisation/index.md) ``` ::: ## 协议与外部资源 引擎尊重标准浏览器的外部资源协议。这些链接永远不会被修改。 * **全局 HTTPS**: `[docmd 主页](https://docmd.io)` - - 在同一个标签页中打开(使用 `external:` 前缀以在新标签页中打开) * **邮件协议**: `[支持渠道](mailto:help@docmd.io)` - - 不在新标签页中打开 * **资源协议**: `[下载 CLI 二进制文件](/assets/bin/docmd-mac.zip)` - - 不进行规范化 ## 静态资源引用 要提供下载或引用原始源文件,请将它们放在项目的 `assets/` 目录中。`docmd` 构建器确保这些文件被移动到生产根目录,且不修改路径。 ```markdown [下载文档 PDF](/assets/pdf/handbook.pdf) [查看原始全局配置](/assets/config/docmd.config.js) ``` ::: callout tip "针对 AI 的语义链接" 在交叉链接技术模块时,优先使用 **描述性锚点**(例如,`[优化 PWA 缓存](../plugins/pwa.md)`)而不是通用文本(例如,`[阅读更多](../plugins/pwa.md)`)。详细的链接标签为 AI 代理提供了 `llms-full.txt` 上下文中不同文档节点之间语义关系的高保真地图。 ::: --- ## [参与贡献](https://docs.docmd.io/zh/07/contributing/) --- title: "参与贡献" description: "参与 docmd 项目贡献的指南和环境设置说明。" --- 感谢您对 `docmd` 项目的关注。我们非常欢迎各种形式的贡献,包括修复错误、改进文档、开发新功能以及提出设计建议。 ## 开发环境 `docmd` 是一个使用 [pnpm](https://pnpm.io/) 管理的 Monorepo 项目。 ### 前提条件 - **Node.js**: v22.x 或更高版本 (推荐 LTS) - **pnpm**: v10.x 或更高版本 ### 项目设置 克隆仓库并运行初始设置以安装依赖并构建项目: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` 要在全局范围内链接本地 `docmd` 命令以便在其他项目中进行测试: ```bash pnpm verify --link ``` ### 本地开发 我们提供了一个主代理命令,可以直接针对内部的 `_playground` 目录运行任何 `docmd` 命令。这使得开发体验与用户 CLI 完全一致: ```bash pnpm docmd dev # 启动 Playground 开发服务器 (也可直接运行 pnpm dev) pnpm docmd build # 构建 Playground 文档 ``` 如需开启热重载监控内部源码文件(引擎、模板和插件),请设置 `DOCMD_DEV` 环境变量: ```bash DOCMD_DEV=true pnpm dev ``` ## 质量标准 ### 代码检查 (Linting) 确保您的代码符合我们的 ESLint 配置。要自动修复格式问题,请运行: ```bash pnpm lint --fix ``` ### 验证 在提交 Pull Request 之前,您 **必须** 确保整个 Monorepo 通过我们的强化验证流水线。该流水线会模拟一个全新的发布环境,审核安全漏洞,并验证 Monorepo 的完整性: ```bash pnpm prep ``` *(该命令会链式执行 `pnpm reset`、依赖安装、代码检查、7 项端到端测试,以及最终的发布预演。)* ## GitHub 工作流 1. **Fork 和 分支**: 从最新的 `main` 分支创建一个特性分支。 2. **验证**: 确保 `pnpm prep` 返回 `🛡️ docmd is ready for production!`。 3. **提交 PR**: 提交预览时请清晰地描述所解决的问题或新增的功能。 ### 提交规范 (Commit Guidelines) 我们遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范。请为您的提交消息添加以下前缀: - `feat:` (新增功能) - `fix:` (错误修复) - `docs:` (文档更改) - `refactor:` (内部重构) ### 源码头部 (Source Headers) 所有在 `packages/` 目录下的新文件必须包含标准的项目版权声明头部: ```javascript /** * -------------------------------------------------------------------- * docmd : the zero-config documentation engine. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @license MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` --- ## [Caddy](https://docs.docmd.io/zh/07/deployment/caddy/) --- title: "Caddy" description: "使用生产级 Caddyfile 部署 docmd。" --- [Caddy](https://caddyserver.com/) 是一个现代 Web 服务器,能自动处理 HTTPS 证书配置和续期。 ## 生成 Caddyfile ```bash docmd deploy --caddy ``` 这会生成针对你项目定制的 `Caddyfile`: - **站点地址**设置为从 `url` 配置中提取的主机名 - - Caddy 会自动为其签发 SSL 证书。如果未配置 URL 则回退到 `:80`。 - **根目录**使用你配置的 `out` 目录(不是硬编码的值) - **SPA 回退**仅在配置中 `layout.spa` 为 `true` 时包含 使用真实域名作为站点地址时(如 `docs.example.com` 而不是 `:80`),Caddy 会通过 Let's Encrypt 自动签发免费 SSL 证书 - - 无需任何 HTTPS 配置。 ## 部署步骤 1. 构建站点:`docmd build` 2. 将输出文件夹和生成的 `Caddyfile` 传输到服务器。 3. 在包含 Caddyfile 的目录中运行 `caddy start` 或 `caddy run`。 ### 重新生成 修改了站点 URL 或输出目录?重新运行 `docmd deploy --caddy` - - Caddyfile 会根据当前 `docmd.config.js` 重新生成。 --- ## [CI/CD 流水线](https://docs.docmd.io/zh/07/deployment/ci-cd/) --- title: "CI/CD 流水线" description: "通过 GitHub Pages、Vercel、Netlify 等 CI/CD 流水线自动化文档的构建与部署。" --- 使用 CI/CD 工作流,在每次推送更改时自动构建并部署你的 `docmd` 站点。以下是常用云平台的即插即用配置。 ## 云平台 ::: tabs == tab "GitHub Pages" 推荐的方法是使用 **GitHub Actions** 在每次推送时自动化部署。 **创建 `.github/workflows/deploy.yml`:** ```yaml name: 部署 docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22' } - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. 将你的存储库连接到 Vercel。 2. 在项目 **Build Settings** 中: - **Framework Preset**: `Other` - **Build Command**: `npx @docmd/core build` - **Output Directory**: `site` 3. 部署。Vercel 会自动检测静态输出并进行全球分发。 == tab "Netlify" 1. 从 GitHub/GitLab/Bitbucket 导入你的项目。 2. 配置构建设置: - **Build command**: `npx @docmd/core build` - **Publish directory**: `site` 3. 点击 **Deploy site**。Netlify 的 CDN 将处理路由和资源分发。 == tab "Cloudflare Pages" 1. 在 Cloudflare 控制面板的 **Pages** 下创建一个新项目。 2. 连接你的 git 提供商并选择你的存储库。 3. 配置构建设置: - **Framework preset**: `None` - **Build command**: `npx @docmd/core build` - **Build output directory**: `site` 4. 保存并部署。 == tab "Firebase" 1. 安装 Firebase CLI: `npm install -g firebase-tools`。 2. 构建你的站点: `npx @docmd/core build`。 3. 运行 `firebase init hosting` 并选择你的项目。 4. 将公共目录设置为 `site`。 5. 配置为单页面应用: `Yes`(这会处理 404 行为)。 6. 使用 `firebase deploy` 进行部署。 ::: ::: callout info "为什么使用 npx @docmd/core?" 在未全局安装 `docmd` 的 CI/CD 环境中,使用 `npx @docmd/core` 直接运行作用域包。如果你的项目已将 `@docmd/core` 列为 `devDependency`,那么在 `npm install` 之后直接使用 `docmd build` 同样有效。 ::: ## 手动 / 静态服务器 对于传统的 Web 服务器(Apache、IIS 等): 1. 生成站点: `npx @docmd/core build`。 2. 通过 SFTP、SCP 或你喜欢的部署工具将 `site/` 文件夹的内容上传到你的服务器。 3. 确保你的服务器配置为对目录提供 `index.html`(大多数服务器的默认设置)。 --- ## [Docker](https://docs.docmd.io/zh/07/deployment/docker/) --- title: "Docker" description: "通过一条命令将 docmd 部署到 Docker 容器中。" --- `docmd` 生成静态 HTML - - 非常适合轻量级、可复现的 Docker 容器。 ## 生成 Dockerfile ```bash docmd deploy --docker ``` 这会在项目根目录创建针对你配置定制的 `Dockerfile` 和 `.dockerignore`: - **你的输出目录**用于 `COPY` 路径(不是硬编码的 `site/`) - **你当前的 `@docmd/core` 版本**固定在安装步骤中,确保可复现构建 - **你的配置文件**在使用非默认名称时会传递给 `docmd build` ### 生成内容 Dockerfile 采用优化的多阶段构建: 1. **阶段 1 - 构建**:通过层缓存安装依赖(先复制 `package.json`),安装固定版本的 `@docmd/core`,执行 `docmd build`。 2. **阶段 2 - 服务**:将构建产物复制到精简的 `nginx:alpine` 容器中。 ::: callout tip "Docker 中使用自定义 Nginx" 如果你在生成 Dockerfile 之前先生成了 `nginx.conf`(通过 `docmd deploy --nginx`),它会被自动检测并配置到容器中。 ::: ## 构建和运行 ```bash docker build -t my-docs . docker run -p 8080:80 my-docs ``` 你的文档现在可以在 `http://localhost:8080` 访问。 ### 重新生成 修改了配置?直接重新运行 `docmd deploy --docker` - - 文件始终根据当前 `docmd.config.js` 重新生成。 --- ## [部署](https://docs.docmd.io/zh/07/deployment/) --- title: "部署" description: "通过一条命令将 docmd 文档部署到 Docker、Nginx、Caddy 或任何云平台。" --- `docmd` 生成高性能静态网站。运行构建命令生成输出目录: ```bash docmd build ``` 输出是一个独立的 `site/` 文件夹(或你在配置中设定的 `out` 目录),可以托管在任何地方。 ## 一键部署 ::: callout tip "v0.7.2 新功能" `docmd deploy` 会读取你的 `docmd.config.js`,生成针对你项目定制的部署文件 - - 不是通用模板。 ::: 无需手动编写 Dockerfile 和服务器配置,让 docmd 为你自动生成: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # 生产级 nginx.conf docmd deploy --caddy # 生产级 Caddyfile ``` ### 自动定制的内容 deploy 命令会读取你的配置(或零配置默认值)并注入: | 配置字段 | 用于 | |:--|:--| | `title` | 每个生成文件的注释头 | | `out` | Dockerfile 中的 `COPY` 路径、Nginx/Caddy 的 `root` 指令 | | `url` | Nginx 的 `server_name`、Caddy 的站点地址 | | `layout.spa` | 控制是否包含 SPA 路由回退 | | 配置文件路径 | 非默认配置名时,Dockerfile 构建步骤使用 `--config` | 没有 `docmd.config.js`?没问题 - - 命令会使用与 `docmd dev` 和 `docmd build` 相同的零配置默认值。 ### 始终同步 每次运行都会重新生成部署文件以匹配你当前的配置。修改了站点 URL 或输出目录?直接重新运行 deploy 命令即可。 ### 支持的目标 * [`docmd deploy --docker`](./docker) - 优化的多阶段 Dockerfile,具有层缓存和版本锁定。 * [`docmd deploy --nginx`](./nginx) - 安全加固的 nginx.conf,包含 GZIP 和不可变资产缓存。 * [`docmd deploy --caddy`](./caddy) - 支持 HTTPS 的 Caddyfile,带自动路由。 点击各目标查看详细的服务专用文档。 *(云部署目标如 `--vercel` 和 `--netlify` 计划在未来版本中推出。)* ## 云托管与 CI/CD 如果你更倾向于托管服务而非自托管,可以将输出文件夹直接部署到 GitHub Pages、Vercel、Netlify 或 Cloudflare Pages。 参见 [CI/CD 部署指南](./ci-cd) 了解自动化工作流。 ## SPA 路由 `docmd` 实现了微型 SPA 路由器以实现平滑的内部导航。每个页面都生成为独立的 `index.html` 文件: - **无需重写规则** - 直接访问 URL 即可,因为 `/guide/setup` 会解析为 `/guide/setup/index.html`。 - **深层链接开箱即用** - 在所有托管平台上均可正常工作。 当配置中 `layout.spa` 设为 `false` 时,deploy 命令会在生成的服务器配置中省略 SPA 回退路由。 ## 生产部署检查清单 1. **站点 URL**:在 `docmd.config.js` 中设置 `url` 属性 - - 这将驱动规范标签、站点地图、社交预览和部署文件生成。 2. **重定向**:从其他工具迁移?使用 `redirects` 配置保持 SEO 排名。 3. **统计分析**:启用 `analytics` 插件追踪用户行为和搜索查询。 4. **AI 上下文**:启用 `llms` 插件生成 `llms.txt`,供 AI Agent 高效摄取文档内容。 ::: callout tip "自定义 404 页面" `docmd` 会在输出目录中自动生成 `404.html`。大多数托管服务会在用户访问缺失路由时自动使用该文件。 ::: --- ## [NGINX](https://docs.docmd.io/zh/07/deployment/nginx/) --- title: "NGINX" description: "使用生产级 NGINX 配置部署 docmd。" --- NGINX 是最可靠的 Web 服务器之一。由于 `docmd` 输出完全是静态的,NGINX 可以以接近零延迟的速度提供服务。 ## 生成 nginx.conf ```bash docmd deploy --nginx ``` 这会生成针对你项目定制的 `nginx.conf`: - **`server_name`** 设置为从 `url` 配置中提取的主机名(如果未设置则回退到 `localhost`) - **SPA 回退**(`try_files ... /index.html`)仅在配置中 `layout.spa` 为 `true` 时包含 - **安全头**、GZIP 压缩和不可变资产缓存默认包含 ## 部署步骤 1. 构建站点:`docmd build` 2. 将输出目录的内容上传到服务器的 Web 根目录(如 `/usr/share/nginx/html/`)。 3. 将生成的 `nginx.conf` 放入服务器配置中(如 `/etc/nginx/conf.d/default.conf`)。 4. 重启 NGINX:`sudo systemctl restart nginx` ### 重新生成 修改了站点 URL 或关闭了 SPA 模式?重新运行 `docmd deploy --nginx` - - 配置文件会根据当前 `docmd.config.js` 重新生成。 --- ## [安装](https://docs.docmd.io/zh/07/getting-started/installation/) --- title: "安装" description: "全局安装、本地安装或直接用 npx 运行 docmd。需要 Node.js 18+。" --- 根据你的工作流选择合适的安装方式。 ## 即时运行 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: 无需安装。可在任意包含 Markdown 文件的目录中直接运行 docmd。 ::: tabs == tab "npm" icon:box ```bash # 构建生产版本静态网站 npx @docmd/core build ``` == tab "Bun" icon:zap ```bash # 构建生产版本静态网站 bunx @docmd/core build ``` ::: ## 安装为项目依赖(推荐) ::: tabs == tab "npm" icon:package ```bash npm install -D @docmd/core npx @docmd/core init npx @docmd/core dev ``` == tab "pnpm" icon:boxes ```bash pnpm add -D @docmd/core pnpm dlx docmd init pnpm dlx docmd dev ``` == tab "yarn" icon:scroll ```bash yarn add -D @docmd/core yarn docmd init yarn docmd dev ``` == tab "Bun" icon:zap ```bash bun add -D @docmd/core bunx docmd init bunx docmd dev ``` ::: 这种方式可以锁定版本,方便团队和 CI/CD 流水线保持一致。 ::: callout tip "本地安装后" 将 `@docmd/core` 安装为项目依赖后,所有命令改用 `docmd` (或 `npm docmd`, `yarn docmd`, `bun docmd`) 替代 `npx @docmd/core`。 ::: ## 全局安装 ::: tabs == tab "npm" icon:package ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: ```bash # 在任意目录使用 docmd 命令 docmd dev docmd build ``` ## 仅浏览器集成 ::: callout info "仅限库集成模式" 此方式将 docmd 渲染引擎嵌入到其他 Web 应用中,不适用于标准文档网站的构建方式。 ::: ```html <!-- 核心样式 --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 处理引擎 --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` 具体采用方式请参阅 [浏览器 API](../api/browser-api.md) 指南。 ## 常见问题 ::: callout warning "权限拒绝(EACCES)" 如果在 macOS 或 Linux 上全局安装时遇到 `EACCES` 错误,请改用 [nvm](https://github.com/nvm-sh/nvm) 或 [fnm](https://github.com/Schniz/fnm) 等 Node 版本管理器,而不要使用 `sudo`。 ::: ::: callout info "PowerShell 脚本执行策略(Windows)" 如果 PowerShell 阻止脚本执行,请以管理员身份运行: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser` ::: --- ## [项目结构](https://docs.docmd.io/zh/07/getting-started/project-structure/) --- title: "项目结构" description: "docmd 如何将文件和文件夹映射为页面、URL 和导航。" --- docmd 以文件系统作为唯一数据来源。文件夹对应文档章节,Markdown 文件对应页面,目录层级决定 URL 路由。 ## 初始化项目 ::: tabs == tab "npm" icon:box ```bash mkdir my-docs && cd my-docs npx @docmd/core init ``` == tab "Bun" icon:zap ```bash mkdir my-docs && cd my-docs bunx @docmd/core init ``` ::: 这将创建标准项目脚手架: ```text my-docs/ ├── docs/ ← 源目录,.md 文件放这里 │ └── index.md ← 首页 (/) ├── assets/ ← 静态资源(图片、自定义 CSS/JS) │ ├── css/ │ ├── js/ │ └── images/ ├── docmd.config.js ← 配置文件 ├── package.json ← 项目元数据与脚本 └── site/ ← 构建输出目录 ``` ## 文件到 URL 的映射 docmd 将 `docs/` 目录结构直接映射为 URL: | 文件 | URL | |:-----|:----| | `docs/index.md` | `/` | | `docs/api.md` | `/api` | | `docs/guides/setup.md` | `/guides/setup` | ::: callout tip "自动标题" 如果页面未在 frontmatter 中定义标题,docmd 会自动提取第一个 `H1` 标题作为页面标题。 ::: ## 启动开发服务器 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: 访问 `http://localhost:3000` 即可查看带热重载的文档。对 `.md` 文件或 `docmd.config.js` 的更改会即时反映。 ## 构建生产版本 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: 输出静态网站到 `./site/`,出品为纯静态 HTML - - 可部署到 GitHub Pages、Vercel、Netlify 或任意静态托管服务。 部署前可在本地预览: ::: tabs == tab "npm" icon:box ```bash npx serve site ``` == tab "Bun" icon:zap ```bash bunx serve site ``` ::: --- ## [快速开始](https://docs.docmd.io/zh/07/getting-started/quick-start/) --- title: "快速开始" description: "从空文件夹到运行中的文档网站,不到一分钟。" --- 在任意包含 Markdown 文件的文件夹中运行 docmd,无需配置文件,无需安装框架,即刻启动。 ## 启动开发服务器 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: 访问 `http://localhost:3000`,文档网站即刻上线。 ## 自动完成的事项 docmd 会自动扫描项目并完成以下配置: 1. **目录检测** - 自动寻找 `docs/`、`src/docs/`、`documentation/` 或任意 `.md` 文件 2. **导航生成** - 根据文件夹结构自动构建侧边栏导航 3. **元数据提取** - 从 `package.json` 读取网站标题(如有) 4. **主题激活** - 应用默认主题,支持跟随系统自动切换明暗模式 5. **搜索索引** - 启用内置全文搜索 无需 `docmd.config.js`。如后续需要版本管理、插件或自定义导航,再添加配置文件即可。 ## 构建生产版本 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: 生成的静态网站输出至 `./site/`,可部署到任意静态托管服务。 --- ## [AI 友好型文档的上下文保留 (Context Preservation)](https://docs.docmd.io/zh/07/guides/ai-optimisation/context-preservation/) --- title: "AI 友好型文档的上下文保留 (Context Preservation)" description: "如何确保 AI 模型能够理解并利用文档不同部分之间的关系。" --- ## 问题 虽然人类读者可以轻松点击超链接来了解更多关于某个术语的信息,但 AI 模型通常以孤立的“块”形式处理文档。当 AI 遇到超链接时,它无法通过“点击”来获取更多上下文。如果关键信息隐藏在链接后面而不是在上下文中解释,AI 可能会无法提供准确的答案,从而导致幻觉。 ## 为什么这很重要 AI 模型依赖于紧邻的周围文本来确定信息的含义和相关性。如果你的文档高度碎片化且上下文保留较差,AI 驱动的搜索工具(如那些由 RAG 驱动的工具)将难以提供高质量的响应。 ## 方法 使用 **行内上下文展开 (Inline Context Unrolling)**,在每个主要链接旁边提供最小可行上下文。此外,利用 `docmd` 的特定功能,例如 [LLMs 插件](../../plugins/llms.md),来提供整个文档集的统一、机器可读视图。 ## 实现 ### 1. 描述性链接和摘要 避免使用通用的链接文本。相反,在链接本身之前或之后提供所链接概念的一句话简短摘要。 - **❌ 较差 (上下文丢失)**:要配置超时,请参考 [常规配置](../../configuration/overview.md)。 - **✅ 较好 (上下文保留)**:你可以在 [常规配置](../../configuration/overview.md) 中配置 `timeoutMs` 参数,该参数定义了引擎在网络请求失败前等待的时间。 ### 2. 使用折叠区块展示细节 [折叠容器](../../content/containers/collapsible.md) 非常适合 AI 优化。内容仍然是原始 Markdown 源码的一部分(AI 可以阅读),但它被视觉化地收纳起来以方便人类读者。 ```markdown ### 数据库连接 使用主 URI 进行连接。 ::: collapsible "URI 格式是什么?" URI 遵循标准的 PostgreSQL 格式:`postgresql://user:password@host:port/database`。 ::: ``` ### 3. 启用 LLMs 插件 在你的 `docmd.config.js` 中启用 [LLMs 插件](../../plugins/llms.md)。此插件会在每次构建后自动生成一个 `llms-full.txt` 文件,它将你的整个文档集连接成一个单一的、高上下文的文件,该文件可以轻松地被大型语言模型消费。 ## 权衡 行内上下文展开会使你的文档稍微冗长一些,并引入少量的冗余。然而,为了确保你的文档是“AI 就绪”的,并且能够支持高质量的自动化支持和搜索体验,这种冗余是一个很小的代价。 --- ## [创建确定性且可分块的文档](https://docs.docmd.io/zh/07/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "创建确定性且可分块的文档" description: "如何组织您的文档结构,以优化其在检索增强生成 (RAG) 和 AI 摄取中的表现。" --- ## 问题 当 AI 流水线(例如 RAG 架构)摄取文档时,它们会将 Markdown 源码切分成更小的“块”(例如每个块 500 个 token)。如果文档由冗长、杂乱且边界不明的段落组成,切分算法可能会在思绪中途切断上下文,从而破坏该块的效用,并导致 AI 的回答不完整或不正确。 ## 为什么重要 如果 AI 检索到的一个块包含代码示例,但遗漏了前面解释 *何时* 使用该代码的段落,那么生成的答案将缺乏必要的条件说明。为“可分块性”组织您的文档可确保每个文本段落都包含足够的上下文,从而能够独立发挥作用。 ## 方法 将您的页面组织成确定性的、原子化的块层级结构。使用 Markdown 标题清晰地描绘概念,并确保相关信息(如警告及其适用的代码)在源文件中物理位置紧密相连。 ## 实施 ### 1. 原子化标题部分 确保每个 `##` 或 `###` 标题都封装了一个单一的、原子化的概念。一个结构良好的部分应该能够作为一个有用的块独立存在,供 AI 模型使用。 - **✅ 正确**:标题为“通过 OAuth 进行身份验证”,后跟简短解释和代码示例。 - **❌ 糟糕**:一个庞大的“入门”页面,包含 15 个不同的概念且没有子标题。 ### 2. 关键信息的紧密排列 不要用长段落将关键警告与其适用的代码分开。使用 [标注 (Callouts)](../../content/containers/callouts) 将它们在纵向上绑定在一起。这增加了它们在摄取过程中保留在同一个向量块中的概率。 ```markdown ::: callout warning "破坏性操作" 运行此命令将永久删除所有日志。 ::: `docmd logs --clear` ``` ### 3. 自动化串联 [LLMs 插件](../../plugins/usage) 通过生成 `llms-full.txt` 文件来促进分块。该文件在页面之间使用标准分隔符 (`---`),帮助摄取流水线识别自然的文档边界,同时保留项目的全局上下文。 ## 权衡 这种方法更倾向于模块化、分段式的写作风格,而不是长篇大论。虽然这对人类读者来说可能感觉更具重复性,但它能显著提高依赖于您文档的 AI 驱动搜索和自动化支持代理的性能。 --- ## [使用 docmd 生成 AI 就绪的文档](https://docs.docmd.io/zh/07/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "使用 docmd 生成 AI 就绪的文档" description: "如何使用 llms.txt 标准和 docmd 的内置工具为 AI 助手提供优化的上下文。" --- ## 问题 开发者越来越依赖 AI 编程助手(如 Cursor、GitHub Copilot 和 ChatGPT)来代表他们阅读和解释文档。如果您的文档只能通过浏览器访问,并且充斥着导航元素、追踪器和复杂的 HTML,AI 代理将在无关数据上消耗过多的 token,从而迅速耗尽其上下文窗口。 ## 为什么重要 提供文档的纯净、经过 token 优化的文本版本,相当于现代的提供高质量 REST API。它确保 AI 代理可以快速摄取您的整个文档集,从而提供更准确的代码建议,并为使用您产品的开发者提供更好的支持。 ## 方法 利用 `docmd` 内置的 **LLMs 插件**。该插件原生支持新兴的 `llms.txt` 标准,在每次构建过程中自动生成经过 token 优化的摘要文件和全上下文文件。 ## 实施 `llms` 插件可在 `docmd >= 0.7.0` 中使用,并可以在您的 [插件配置](../../plugins/usage) 中进行配置。 ### 1. 配置网站 URL 确保在 `docmd.config.js` 中正确设置了 `url` 属性。这允许插件为 `llms.txt` 文件中的所有页面生成绝对 URL。 ```javascript // docmd.config.js export default { title: '我的项目文档', url: 'https://docs.example.com', plugins: ['llms'] }; ``` ### 2. 输出文件 在构建过程中,`docmd` 会在您的网站根目录下生成两个关键文件: - **`llms.txt`**:所有页面的简明、结构化的 Markdown 摘要,包括标题、描述和完整 URL。 - **`llms-full.txt`**:包含整个网站原始 Markdown 内容的综合文件,使用标准分隔符 (`---`) 进行串联。这为 AI 模型提供了终极的“事实来源”。 ### 3. 控制摄取 您可以使用 [页面 Frontmatter](../../content/frontmatter) 中的 `llms` 属性将特定页面排除在 AI 就绪输出之外。 ```yaml --- title: "内部调试指南" llms: false --- ``` ## 权衡 生成 `llms-full.txt` 会创建一个巨大的单一文件。对于异常庞大的文档网站,该文件可能会超过几兆字节。虽然这对于具有大上下文窗口的现代 LLM(如 Gemini 1.5 Pro 或 Claude 3.5 Sonnet)来说是理想的,但对于较小的模型来说可能过大。请确保逻辑清晰地组织您的 [导航](../../configuration/navigation),以便 AI 可以优先处理最重要的部分。 --- ## [通过文档减少 AI 幻觉](https://docs.docmd.io/zh/07/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "通过文档减少 AI 幻觉" description: "如何编写显式的、自包含的文档,以防止 AI 模型臆造错误信息。" --- ## 问题 AI 模型是预测引擎,而不是推理引擎。如果一个 API 使用示例不完整、使用了模糊的占位符或依赖于隐含知识,AI 通常会产生“幻觉” - - 它会根据在训练期间学到的通用模式来臆造缺失的部分。这些臆造的内容对于您的特定软件来说往往是错误的,会导致开发者的挫败感。 ## 为什么重要 幻觉代码会破坏用户信任。当开发者向 AI 寻求帮助并收到抛出语法错误或使用不存在参数的代码时,他们往往会归咎于软件本身“有缺陷”或“文档太烂”。减少幻觉对于维护项目的专业声誉至关重要。 ## 方法 实践 **防御性文档 (Defensive Documentation)**。这涉及编写极其显式、完全实例化的代码块,不留任何歧义空间。切勿假设读者(或 AI)了解必要的导入、环境变量或先决配置。 ## 实施 ### 1. 全限定代码块 始终在每个代码片段中包含必要的导入或设置代码。这确保了当 AI 对您的文档进行分块时,代码块仍然是一个自包含的事实单元。 - **❌ 存在幻觉风险**: ```javascript const config = loadConfig(); // loadConfig 是从哪里来的? ``` - **✅ 防御幻觉**: ```javascript import { loadConfig } from '@docmd/core'; const config = loadConfig(); ``` ### 2. 使用具体示例而非占位符 避免使用像 `your-api-key` 或 `env-name` 这样模糊的占位符。相反,提供具体的、有效的示例,或使用注释来指定严格的枚举要求。 ```javascript // 有效的环境:"development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. 内联代码注释 将关键要求作为注释放在代码块 *内部*,而不仅仅是在周围的 Markdown 文本中。AI 模型在生成类似片段时,会非常重视代码内部的注释。 ```javascript export default { // 关键:outputPath 必须是一个绝对文件系统路径。 outputPath: '/var/www/html/docs' }; ``` ### 4. 分类的警告 使用 [标注 (Callouts)](../../content/containers/callouts) 来清晰地标记弃用的功能或破坏性变更。AI 模型比段落中的简单句子更有可能尊重 `::: callout warning` 块。 ## 权衡 防御性文档会使代码块变得更长且更具重复性。人类读者可能会觉得在每个片段中看到相同的 `import` 语句稍微有些乏味。然而,拥有能够显著减少支持工单和用户错误的“防 AI (AI-proof)”文档所带来的好处,远超其冗长带来的微小代价。 --- ## [为语义搜索和 RAG 设计文档](https://docs.docmd.io/zh/07/guides/ai-optimisation/semantic-search-design/) --- title: "为语义搜索和 RAG 设计文档" description: "如何组织文档结构,以优化其在基于向量的搜索和检索增强生成中的表现。" --- ## 问题 传统的关键字搜索(如 [docmd 的内置搜索](../../plugins/search))依赖于精确的文本匹配。如果用户搜索“身份验证”,基本的关键字引擎可能会因为页面标题为“集成 OAuth2”且该词出现频率不够而无法找到该页面。语义搜索使用向量嵌入来理解查询的 *含义*,解决了这个问题,但需要特定的文档结构才能有效。 ## 为什么重要 现代开发者期望直观、基于意图的搜索体验。如果您的文档由于微小的术语差异而无法显示相关内容,用户将很快放弃您的网站并寻求其他帮助。为语义搜索进行设计可以确保您的文档在用户使用不同术语时仍具有可发现性。 ## 方法 组织您的文档,使其易于被检索增强生成 (RAG) 流水线消费。这涉及创建“语义密集型”内容,其中概念被清晰定义,并且代词被显式实体替换,以便在分块和向量化过程中保留上下文。 ## 实施 ### 1. 丰富的 Frontmatter 元数据 使用 [Frontmatter](../../content/frontmatter) 提供在正文中可能不会自然使用的显式关键字和描述。这为搜索引擎提供了额外的内容“挂钩”。 ```yaml --- title: "集成 OAuth2" description: "了解如何实现安全的身份验证和单点登录 (SSO)。" keywords: ["login", "authentication", "sso", "security", "identity"] --- ``` ### 2. “语义密度”策略 RAG 系统将文档切分为小块(向量)。每个章节的第一段应该包含与该主题相关的、密度最高的名词和动词。这确保了该章节的主要“含义”被捕获在初始向量中。 - **✅ 正确**:“本指南解释了如何实施 **OAuth2 单点登录 (SSO)**,为您的文档网站提供安全的 **身份验证**。” - **❌ 糟糕**:“在本节中,我们将讨论它是如何工作的,以及您如何轻松地设置它。” ### 3. 避免代词歧义 在分块数据库中,如果定义“它”的前一个段落被切分到了不同的块中,那么像“它适用于任何提供商”这样的句子就是无用的。请务必显式表达。 - **❌ 歧义**:“它具有高度的可扩展性。” - **✅ 显式**:“**docmd 搜索引擎** 旨在具有高度的可扩展性。” ## 权衡 为语义密度而写作有时会比传统的叙述性写作感觉稍微正式或具有重复性。然而,由此带来的可发现性的提高以及 AI 生成回答的准确性,使得这成为现代企业级文档的重要实践。 --- ## [为 AI 代理构建文档结构](https://docs.docmd.io/zh/07/guides/ai-optimisation/structure-for-llms/) --- title: "为 AI 代理构建文档结构" description: "如何从视觉格式转向语义化结构,以提高 AI 编码助手的准确性。" --- ## 问题 人类读者依靠视觉线索、侧边栏导航和推断上下文来理解文档。然而,AI 代理和大型语言模型 (LLMs) 主要消费原始文本流。当文档缺乏严格的语义结构时,这些模型难以映射概念之间的关系,从而导致推理较差和不准确的编码建议。 ## 为什么这很重要 如果你的文档未针对 LLM 进行优化,那么使用 GitHub Copilot、Cursor 或 ChatGPT 等工具的开发人员在处理你的软件时将会遇到更多的幻觉。这直接降低了开发人员的体验,因为用户通常会因为 AI 助手生成的错误而归咎于产品本身。 ## 方法 从“视觉优先”的心态转变为 **“语义优先”** 的心态。使用标准的 Markdown 功能 - - 例如严格的标题层次结构、明确的代码块语言标签和描述性的替代文本 - - 为你的内容提供清晰、机器可读的路线图。`docmd` 通过 [LLMs 插件](../../plugins/llms.md) 将这种结构处理成优化的输出。 ## 实现 ### 1. 严格的标题层次结构 避免为了纯粹的视觉效果而跳过标题级别。一致的层次结构允许 LLM 理解不同章节的范围和关系。 - **`#` 标题**: 页面的主要主题。 - **`##` 主要概念**: 一个原子的、高层的话题。 - **`###` 细节**: 该概念的一个特定子任务或属性。 * **❌ 较差**: 在 `#` 之后立即使用 `###`,只是因为你喜欢较小的字体。 * **✅ 较好**: `# 安装` 之后是 `## 前提条件`,然后是 `### 系统要求`。 ### 2. 媒体的描述性元数据 由于 LLM 无法“看到”图像或图表,你必须在替代文本或相邻段落中提供架构上下文。 ```markdown ![系统架构:前端 React 应用程序通过 REST 与 Node.js API 通信,后者随后查询 Redis 缓存和 PostgreSQL 数据库。](../../static/img/architecture.png) ``` ### 3. 明确的代码块标签 始终使用 [语法高亮](../../content/syntax/index.md) 为每个围栏代码块指定语言。这允许 LLM 正确解析代码的抽象语法树 (AST)。 ```javascript // docmd.config.js export default { plugins: ['llms'] }; ``` ### 4. 语义化容器 使用 [标注](../../content/containers/callouts.md) 而不是通用的块引用来提供意图。`docmd` 的语义容器帮助 AI 模型区分核心指令与补充技巧或警告。 ## 权衡 语义上的严谨要求作者具有自律性。你不能再将 Markdown 功能(如块引用或标题)纯粹用作装饰元素。然而,这种自律产生的文档对于 AI 代理和使用辅助技术的人类读者来说,其可访问性都将显著提高。 --- ## [避免反模式](https://docs.docmd.io/zh/07/guides/content-ux/avoiding-anti-patterns/) --- title: "避免反模式" description: "如何识别并消除常见的文档错误,这些错误会降低用户体验并增加内容债务。" --- ## 问题 随着时间的推移,文档存储库往往会积累一些针对内容问题的“快速修复”,这些修复会无意中侵蚀用户体验。这些反模式 - - 例如模糊的链接文本或臃肿的代码示例 - - 在项目中根深蒂固,使得文档难以维护,对开发者的价值也随之降低。 ## 为什么重要 反模式会导致“内容债务”。它们会降低搜索引擎排名 (SEO),降低残障人士的可访问性,并显著增加读者的认知负荷,而读者仅仅是想快速找到技术问题的解决方案。高质量的文档需要不断的警惕,以保持其整洁、简练且专业。 ## 方法 在 [同行评审流程](../workflows-teams/git-based-workflows.md) 中识别并无情地消除常见的反模式。使用 Vale 等自动化的散文检查工具以及人工审核,确保您的内容在所有页面上保持高质量、易于访问且一致。 ## 实施 ### 1. 非描述性超链接 避免在链接中使用“点击这里”或“阅读更多”等通用文本。这不仅对 SEO 有害,还会导致使用屏幕阅读器的用户无法访问文档,因为他们通常通过在链接之间跳转来浏览页面。 * **❌ 错误示例**:要配置您的服务器,请 [点击这里](../../configuration/overview.md)。 * **✅ 正确示例**:查看 [全局配置](../../configuration/overview.md) 以设置您的生产服务器。 ### 2. “样板代码墙” 在代码示例中,如果核心逻辑之前包含数十行标准导入和样板配置,会分散读者对示例实际重点的注意力。 * **解决方案**:专注于相关的代码片段。如果为了提供上下文而必须包含样板代码,请使用注释说明为了简洁而省略了标准导入,或者使用 [标注](../../content/containers/callouts.md) 来解释所需的设置。 ### 3. 将 FAQ 视为“垃圾场” “常见问题解答”(FAQ) 页面往往成为了难以整合进主指南的信息库。如果一个问题确实是“经常被问到”的,这清楚地表明您的核心文档未能有效地解释该概念。 * **解决方案**:不要将其添加到 FAQ,而是重构相关的教程或概念指南,在用户首次遇到困惑的地方直接解决它。如果信息对操作成功至关重要,请使用 [重要标注](../../content/containers/callouts.md)。 ## 权衡 消除 FAQ 要求作者在发现新的支持问题时不断重构和改进现有的文档层级。虽然这比简单地在 FAQ 列表末尾添加一个要点增加了更多的初始维护开销,但它会为您的用户带来一个更加连贯、专业且实用的文档网站。 --- ## [提高可读性 (Improving Readability)](https://docs.docmd.io/zh/07/guides/content-ux/improving-readability/) --- title: "提高可读性 (Improving Readability)" description: "如何利用视觉节奏、信息层次结构和 docmd 的结构化工具来创建高度可读的文档。" --- ## 问题 技术文档通常内容密集、术语繁多且难以扫描。当读者遇到没有任何视觉缓冲的“文字墙”时,他们往往会跳过重要细节,或者完全错过关键的安全警告。密集的格式增加了认知摩擦,导致用户产生挫败感并可能引发错误。 ## 为什么这很重要 可读性不仅仅是一种美学选择 - - 它是一项功能要求。如果一个开发人员因为警告被埋没在长篇大论中而错过了它,后果可能会非常严重。清晰的信息层次结构可确保用户能够快速找到所需信息,准确理解并安全地采取行动。 ## 方法 通过打破长段落并使用 [主题容器](../../content/containers/index.md) 突出显示关键信息,建立一种可预测的视觉节奏。利用 `docmd` 内置的结构化工具,你可以创建一个自然引导读者视线看向页面最重要部分的层次结构。 ## 实现 ### 1. “简洁的力量” 尽量将段落限制在三或四句话以内。短段落更易于在屏幕上消化,并为复杂的技术概念提供了自然的“喘息空间”。如果一个段落感觉太长,请考虑将其拆分为列表或使用子标题对信息进行重新分类。 ### 2. 使用标注进行分类 一致地使用 [标注](../../content/containers/callouts.md) 对信息进行分类。这允许正在扫视的用户根据块的视觉样式立即识别其意图: * **Info (信息)**:背景上下文或补充细节,提供更深入的理解。 * **Tip (技巧)**:最佳实践、快捷方式和提高效率的“专业技巧”。 * **Warning/Danger (警告/危险)**:可能导致错误、数据丢失或安全漏洞的关键操作。 ```markdown ::: callout warning "生产环境安全" 在未先核实备份的情况下,切勿在实时数据库上执行此命令。 ::: ``` ### 3. 使用步骤进行顺序说明 对于教程和分步指南,请避免对操作进行叙述性描述。相反,使用 [步骤容器](../../content/containers/steps.md) 创建一个清晰、带编号的进程,使其易于遵循。 ```markdown ::: steps 1. **初始化**: 在项目根目录下运行 `npx @docmd/core init`。 2. **配置**: 更新你的 `docmd.config.js`,包含你的站点标题和导航。 3. **构建**: 运行 `npx @docmd/core build` 生成生产就绪的静态文件。 ::: ``` ## 权衡 使用 `::: steps` 或 `::: callout` 等专门的容器要求贡献者学习 `docmd` 特有的 Markdown 扩展。虽然这增加了一点学习曲线,但信息密度、清晰度和专业呈现方面的显著提升,远远超过了学习这些强大结构化标签所付出的微小努力。 --- ## [大型站点的导航设计](https://docs.docmd.io/zh/07/guides/content-ux/navigation-large-sites/) --- title: "大型站点的导航设计" description: "如何使用 docmd 的布局工具,将复杂的文档集组织成直观、可扩展的导航结构。" --- ## 问题 随着文档站点从几十页增长到几百或几千页,简单的侧边栏往往会变成深层嵌套文件夹的混乱迷宫。当用户被迫展开多层级目录仅仅为了寻找一个特定的参考信息时,他们会丢失上下文,感到挫败,并往往会放弃文档而转向“试错法”。 ## 为什么重要 导航是您产品功能的“地图”。如果导航难以使用,用户将完全依赖搜索栏,这可能导致知识的碎片化。一个结构良好的导航系统可以在用户浏览时向其传授产品的逻辑和分类,帮助他们随着时间的推移变得更加熟练和自给自足。 ## 方法 优先考虑 **顶级上下文切换 (Top-Level Context Switching)** 而不是深层嵌套。目标是将左侧边栏限制在不超过两到三个层级的深度。使用水平 [菜单栏 (Menubar)](../../configuration/menubar) 分隔不同的文档“领域”(例如:指南、API 参考和社区),这允许每个单独的侧边栏保持聚焦、相关且易于管理。 ## 实施 ### 1. 基于领域的划分 在您的 `docmd.config.js` 中,使用 [菜单栏 (Menubar)](../../configuration/menubar) 将您的内容划分为高级类别。这种方法允许您为每个领域呈现完全不同的侧边栏,防止单一导航树变得过于臃肿。 ### 2. 扁平化层级结构 与其将一个单一的概念拆分为许多零散的 Markdown 页面,不如将相关信息整合到综合性的父页面中。使用清晰的 [标题层级](../../content/syntax),允许用户使用自动生成的右侧目录 (TOC) 在页面内进行导航。 * **❌ 糟糕的信息架构 (IA)**:一个名为“安全”的文件夹,包含十个独立的、只有一个段落的各种协议文件。 * **✅ 更好的信息架构 (IA)**:一个结构良好的“安全概述”页面,涵盖所有协议,并使用标题提供整洁的目录 (TOC)。 ### 3. 利用可折叠部分 对于不经常访问的大组相关内容,在您的 [导航配置](../../configuration/navigation) 中使用 `collapsible` 属性。这通过隐藏次要信息直到用户明确请求,来保持界面的整洁。 ```json // navigation.json { "title": "API 参考", "collapsible": true, "collapsed": true, "children": [ { "title": "身份验证", "path": "api/auth" }, { "title": "端点", "path": "api/endpoints" } ] } ``` ## 权衡 将内容整合到更少、更长的页面中,要求作者在结构清晰度和标题使用方面保持严谨。如果一个页面太长而没有适当的内部导航 (TOC),它本身可能变成一面“文字墙”。然而,对于大型文档集来说,显著减少“点击疲劳”和改进相关内容的发现,使得扁平的、基于领域的层级结构更具优势。 --- ## [可扩展的技术写作 (Scalable Technical Writing)](https://docs.docmd.io/zh/07/guides/content-ux/scalable-technical-writing/) --- title: "可扩展的技术写作 (Scalable Technical Writing)" description: "如何使用渐进式披露和结构化容器来管理不断增长的文档复杂性,而不让用户感到不知所措。" --- ## 问题 在产品的早期阶段,记录一个功能可能只需要几个段落。然而,随着产品演变为企业平台,这些段落可能会激增,变成充斥着边缘案例、平台特定变体(Docker、Kubernetes、Cloud)以及复杂配置选项的海洋。这会导致“垂直膨胀”,即单页面变成难以阅读、难以导航且难以维护的文字墙。 ## 为什么这很重要 垂直膨胀会破坏理解并增加认知负荷。当用户被迫滚动浏览大量与其特定环境或用例无关的内容时,他们会感到不知所措,并往往认为产品比实际情况更复杂。可扩展的写作可确保用户在任何特定时刻只看到他们需要的信息,从而保持一条清晰的成功之路。 ## 方法 实施 **渐进式披露 (Progressive Disclosure)**。这种技术涉及预先仅呈现最关键的信息(“快乐路径”),并将更复杂、技术性更强或更具体的细节隐藏在交互式 UI 结构后面。`docmd` 提供了几种专门设计的内置容器,可帮助你有效且优雅地管理这种复杂性。 ## 实现 ### 1. 使用选项卡处理变体 与其按顺序罗列多个包管理器、操作系统或云提供商的说明,不如使用 [选项卡容器](../../content/containers/tabs.md)。这允许用户选择他们的特定环境,即时隐藏无关的命令并减少视觉噪音。 ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. 使用折叠区块管理边缘案例 如果一个故障排除步骤或特定的边缘案例仅适用于极少数用户,请不要让它中断主教程的逻辑流程。使用 [折叠容器](../../content/containers/collapsible.md) 来埋没这些细节,同时在需要时保持它们易于访问。 ```markdown 1. 通过运行 `npx @docmd/core dev` 启动开发服务器。 ::: collapsible "故障排除:端口已被占用" 如果你收到 `EADDRINUSE` 错误,可以使用 `--port` 标志指定自定义端口:`npx @docmd/core dev --port 4000`。 ::: ``` ### 3. 使用标注提供渐进式细节 使用 [标注](../../content/containers/callouts.md) 提供补充信息,这些信息虽然不是主要任务所必需的,但能为高级用户提供有价值的上下文。 ## 权衡 将内容隐藏在选项卡或折叠区块中偶尔会使用户更难使用浏览器的原生 `Ctrl+F` 搜索来查找信息。然而,`docmd` 集成的 [搜索引擎](../../plugins/search.md) 会对这些容器内的所有内容进行索引,从而确保用户在享受更整洁的阅读体验的同时,仍能通过网站的主搜索界面准确找到他们需要的内容。 --- ## [任务 vs 概念](https://docs.docmd.io/zh/07/guides/content-ux/task-vs-concept/) --- title: "任务 vs 概念" description: "如何应用 Diátaxis 框架,将“操作指南”与“概念解释”分离开来,以构建更有效的文档结构。" --- ## 问题 技术写作中常见的一个错误是将“为什么要这样做”与“如何具体操作”混为一谈。例如,一个关于“配置 SSO”的教程,很容易因为大篇幅解释 SAML 协议的历史而变得冗长乏味,分散了用户实现功能这一首要目标的注意力。 ## 为什么重要 用户的意图会根据其当前所处的上下文而有很大差异。凌晨 2 点试图修复生产问题的工程师寻找的是具体、可操作的步骤,而不是架构哲学。相反,正在评估您平台的技术负责人则需要在投入实施之前理解其背后的逻辑。分离这些关注点可以确保这两类角色都能在没有不必要干扰的情况下找到所需的信息。 ## 方法 采用 **Diátaxis 框架**,它将文档分为四个不同的象限:教程 (Tutorials)、操作指南 (How-to Guides)、解释 (Explanation/Concepts) 和技术参考 (Technical Reference)。在本指南中,我们专注于**任务导向型内容**(可操作步骤)与**概念导向型内容**(深入理解)之间的关键分离。 ## 实施 ### 1. 任务导向型指南 (How-To) 完全专注于一个具体、明确的目标。删掉冗长的理论解释,专注于实现该目标所需的最少步骤。使用 [步骤容器 (Steps Container)](../../content/containers/steps) 提供清晰、无歧义的路径。 * **标题示例**:“如何配置 Webhook” * **结构**: * 前提条件 * 直接、可操作的说明 * 验证步骤(如何知道操作已成功) ### 2. 概念导向型指南 (Explanation) 专注于“大局”,包括架构、设计哲学以及特定决策背后的“原因”。在这些部分中,避免提供直接的指令或命令。 * **标题示例**:“理解 Webhook 交付架构” * **结构**: * 高层架构图 * 重试逻辑与可靠性哲学 * 安全注意事项 ### 3. 有效的交叉引用 不要合并这两类内容,而是使用 `docmd` 的链接工具为需要更多上下文或准备实施的用户提供桥梁。 * **在操作指南中**:“有关我们重试逻辑的深入探讨,请参阅 [Webhook 架构](../../guides/performance-delivery/caching-strategies)。” * **在概念指南中**:“准备好开始了吗?请遵循我们的 [Webhook 配置指南](../../guides/integrations/alongside-other-tools)。” ## 权衡 将任务与概念分离开来会增加导航中的页面数量,并需要更严格的交叉引用规范。然而,这种模块化结构显著提高了文档套件的长期可维护性、可搜索性以及整体专业性。 --- ## [自定义 Favicon 和元数据](https://docs.docmd.io/zh/07/guides/customisation/custom-favicons-metadata/) --- title: "自定义 Favicon 和元数据" description: "如何配置您网站在浏览器中的视觉标识并优化社交媒体预览。" --- ## 问题 默认的文档网站在浏览器中往往缺乏独特的视觉标识(使用通用的 favicon),并且在链接被分享到社交媒体或 Slack、Discord 等沟通工具时,提供的预览效果较差。这会降低品牌识别度和点击率。 ## 为什么重要 Favicon 是浏览器窗口中主要的视觉锚点。高质量的 OpenGraph 和 Twitter 元数据可以确保您的文档在分享时看起来专业且值得信赖,通过标题、描述和英雄图提供必要的上下文。 ## 方法 `docmd` 提供了一个内置的 `favicon` 属性,用于轻松配置图标。对于高级 SEO 和社交元数据,请利用 [SEO 插件](../../plugins/seo),它可以根据您的项目配置和页面 Frontmatter 自动生成元标签。 ## 实施 ### 1. 配置 Favicon 将您的 Favicon 文件(例如 `favicon.svg` 或 `favicon.ico`)放在源目录中,并在 `docmd.config.js` 中引用它。`docmd` 会自动处理相对路径和缓存失效。 ```javascript // docmd.config.js export default { title: '我的项目', favicon: '/favicon.svg' // 相对于源目录 }; ``` ### 2. 全局 SEO 配置 启用并配置 [SEO 插件](../../plugins/seo),为整个网站设置默认的社交媒体预览。 ```javascript // docmd.config.js export default { url: 'https://docs.example.com', plugins: { seo: { defaultDescription: '关于我们神奇软件的终极指南。', openGraph: { defaultImage: '/static/og-banner.png' }, twitter: { siteUsername: '@myproject', cardType: 'summary_large_image' } } } }; ``` ### 3. 页面级覆盖 您可以使用 [Frontmatter](../../content/frontmatter) 中的 `seo` 属性覆盖单个页面的 SEO 设置。 ```yaml --- title: "重大发布 v2.0" description: "关于我们新引擎您需要了解的一切。" seo: image: "/assets/v2-hero-banner.png" keywords: ["发布", "v2", "更新", "性能"] --- ``` ## 权衡 虽然 `favicon` 属性很方便,但它仅支持单个文件。对于复杂的多尺寸 Favicon 集(Apple Touch 图标、Android manifest 等),您可能需要使用自定义插件将额外的 `<link>` 标签注入 `<head>` 中。 --- ## [自定义字体和品牌](https://docs.docmd.io/zh/07/guides/customisation/custom-fonts-branding/) --- title: "自定义字体和品牌" description: "如何使用 CSS 变量使您的文档外观与企业形象保持一致。" --- ## 问题 确保您的文档平台与企业形象无缝匹配,对于维护专业外观至关重要。默认的字体堆栈和配色方案旨在提供通用可读性,但可能无法反映您的特定品牌个性。 ## 为什么重要 文档是一个关键的品牌触点。如果您的主产品使用了特定的字体(如 "Outfit")和独特的颜色,您的文档也应该反映这些相同的选择。所有 Web 资产的一致性可以建立信任,并提供更具凝聚力的用户体验。 ## 方法 `docmd` 使用一套 CSS 自定义属性(变量),这些属性定义了布局的视觉标记。您可以轻松地在自定义样式表中覆盖这些变量,而无需修改核心引擎。 ## 实施 ### 1. 创建自定义样式表 在您的源目录(或任何子目录)中创建一个名为 `custom.css` 的文件,并覆盖 `:root` 变量。 ```css /* 导入您的品牌字体 */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* 品牌字体 */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* 品牌颜色 (浅色模式) */ --link-color: #8a2be2; /* 您的主品牌颜色 */ --link-color-hover: #7b1fa2; --bg-color: #fcfcfd; /* 细微的背景底色 */ } /* 深色模式覆盖 */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. 注册样式表 将您的自定义 CSS 文件添加到 `docmd.config.js` 中的 `theme.customCss` 数组中。 ```javascript // docmd.config.js export default { theme: { customCss: ['/custom.css'] } }; ``` ## 权衡 导入外部字体(如 Google Fonts)会为初始页面加载增加少量的延迟。为了优化性能,请考虑将字体文件本地托管在您的项目中,并使用 `font-display: swap` 来防止自定义字体加载时的“无样式文本闪烁 (FOUT)”。 --- ## [设计自定义落地页](https://docs.docmd.io/zh/07/guides/customisation/custom-landing-pages/) --- title: "设计自定义落地页" description: "如何使用 docmd 的 hero 和 grid 容器为您的文档创建高级落地页。" --- ## 问题 默认情况下,大多数文档生成器中的 `index.md` 文件看起来都像一个标准的页面。创建一个具有高冲击力的、营销级的落地页通常需要使用单独的 Web 框架(如 Next.js 或 Astro),这增加了文档工作流的复杂性。 ## 为什么重要 您的文档首页通常是开发者与您产品的第一次互动。一个通俗的 Markdown 解析页面可能无法激发用户对您产品精致程度和专业质量的信心。自定义落地页可以更好地引导用户访问最重要的章节,同时强化您品牌的视觉身份。 ## 方法 `docmd` 提供了专门的 [Hero](../../content/containers/hero) 和 [网格 (Grid)](../../content/containers/grids-cards) 容器,专门用于构建高级落地页。为了获得完全的创作自由,您还可以使用 `noStyle` Frontmatter 属性来完全控制页面的 HTML 和样式。 ## 实施 ### 1. 使用 Hero 容器 `hero` 容器支持多种布局,包括 `split`(用于并排内容)和 `glow`(用于现代美学效果)。 ```markdown ::: hero layout:split glow:true # 使用 docmd 更快地构建 面向现代开发团队的零配置文档引擎。 [开始使用](../../getting-started/quick-start.md) [在 GitHub 上查看](https://github.com/docmd-io/docmd) == side ![仪表板预览](../../static/img/hero-preview.png) ::: ``` ### 2. 使用网格组织内容 使用 [网格和卡片](../../content/containers/grids.md) 创建高层级的导航区域,帮助用户快速找到所需内容。 ```markdown ::: grids ::: grid ::: card "快速入门" icon:rocket 在不到 5 分钟的时间内启动并运行。 [了解更多](../../getting-started/quick-start.md) ::: ::: ::: grid ::: card "API 参考" icon:code 我们所有端点的全面文档。 [探索 API](../../api/node-api.md) ::: ::: ::: ``` ### 3. 使用 noStyle 进行完全自定义 如果您需要一个完全自定义的设计,且忽略标准的文档布局(无侧边栏或页眉),请在 [页面 Frontmatter](../../content/frontmatter) 中使用 `noStyle` 属性。 ```yaml --- title: "自定义仪表板" noStyle: true --- ``` 设置 `noStyle: true` 后,`docmd` 将仅渲染您提供的原始 HTML/Markdown 内容,允许您注入自己的 CSS 和 JavaScript,以实现像素级的完美体验。 ## 权衡 使用 `noStyle: true` 意味着您放弃了 `docmd` 提供的原生导航、搜索和主题切换功能。您负责确保自定义页面是移动端自适应且符合无障碍要求的。对于大多数用例,在标准布局中结合使用 `hero` 和 `grid` 容器可以在美观和功能之间提供最佳平衡。 --- ## [使用自定义插件扩展 docmd](https://docs.docmd.io/zh/07/guides/customisation/extending-custom-plugins/) --- title: "使用自定义插件扩展 docmd" description: "如何使用 docmd 的生命周期钩子构建自定义功能并扩展文档引擎。" --- ## 问题 有时您有一些非常具体的需求,内置功能或现有插件无法满足。例如,您可能需要在构建过程中从内部 API 获取数据,或者对生成的 HTML 进行超出简单 CSS 范畴的复杂转换。 ## 为什么重要 可扩展性是静态工具与专业文档框架的区别所在。如果没有一种清晰的方式来注入自定义逻辑,团队往往不得不维护脆弱的 shell 脚本或后处理封装程序,这使得构建过程难以管理和调试。 ## 方法 `docmd` 具有强大的基于钩子的 [Plugin API](../../plugins/api)。您可以编写简单的 Node.js 模块,在文档生命周期的各个阶段(从初始配置到最终 HTML 生成)进行拦截,从而允许您任意修改内容和行为。 ## 实施 ### 1. 创建本地插件 插件是一个标准的 JavaScript 模块,它导出一个描述符和若干生命周期钩子。 ```javascript // plugins/version-injector.js export default { // 插件元数据 plugin: { name: 'version-injector', version: '1.0.0', capabilities: ['build'] // 使用 'build' 钩子所必需的 }, // 在钩子之间共享的状态 latestVersion: '0.0.0', // 在配置解析完成后运行 async onConfigResolved(config) { // 从内部 API 获取数据 const response = await fetch('https://api.internal.com/version'); this.latestVersion = await response.text(); console.log(`[插件] 已获取版本:${this.latestVersion}`); }, // 在模板渲染前拦截页面上下文 async onBeforeRender(page) { if (!page.html) return; // 在 HTML 和 frontmatter 中用动态数据替换占位符 page.html = page.html.replace(/\{\{VERSION\}\}/g, this.latestVersion); page.frontmatter.computedVersion = this.latestVersion; } }; ``` ### 2. 注册插件 您可以通过将本地插件导入到 `docmd.config.js` 中来注册它。 ```javascript // docmd.config.js import VersionInjector from './plugins/version-injector.js'; export default { title: '我的项目文档', plugins: { // 通过提供导入的模块进行注册 'version-injector': VersionInjector } }; ``` ## 权衡 自定义插件在构建时的 Node.js 环境中运行。虽然功能强大,但如果不进行优化,可能会影响构建性能。像 `onAfterParse` 或 `onPageReady` 这样的钩子逻辑会为网站中的 *每一页* 运行。请确保您的转换是高效的(例如使用优化的正则表达式),以保持快速的构建速度。 --- ## [与其他工具并存](https://docs.docmd.io/zh/07/guides/integrations/alongside-other-tools/) --- title: "与其他工具并存" description: "如何将 docmd 集成到多工具文档生态系统中,以创建无缝的用户体验。" --- ## 问题 大型组织很少仅使用单一工具来满足其所有文档需求。您的公司可能使用 Confluence 编写内部规范,使用 Stoplight 进行 API 设计,使用 GitHub 存放代码示例。将这些分散的来源整合到一个统一的用户旅程中是一项重大挑战,因为用户经常发现自己在风格和导航完全不同的断开门户之间跳转。 ## 为什么重要 碎片化的文档体验会破坏开发者的信任并增加认知负荷。如果用户为了完成一个教程而被迫在完全不同的界面之间切换,他们更有可能丢失上下文或放弃您的产品。统一您的工具可确保专业、连贯的体验,鼓励用户进行探索和学习。 ## 方法 将 `docmd` 用作您的主要文档中心或“单一窗口 (Single Pane of Glass)”。通过利用 [菜单栏 (Menubar)](../../configuration/menubar) 实现统一导航,并利用 [嵌入容器 (Embed Containers)](../../content/containers/embed) 引入第三方内容,您可以创建一个无缝的界面,隐藏多工具基础设施的复杂性。 ## 实施 ### 1. 统一的全局导航 使用 `menubar` 配置将您的各个文档门户链接在一起。这可确保用户始终能找到返回主指南的路径,无论他们当前处于哪个子域名。 ```javascript // docmd.config.js export default { layout: { menubar: { left: [ { text: '指南', url: '/' }, // docmd 站点 { text: 'API 参考', url: 'https://api.example.com' }, // 外部工具 { text: '社区', url: 'https://forum.example.com', external: true } ] } } }; ``` ### 2. 无缝嵌入 对于提供 Web 界面(如交互式 API 资源管理器或仪表板预览)的工具,使用 `::: embed` 容器直接在您的 `docmd` 页面中显示它们。这可以将用户留在您的品牌环境中。 ```markdown # 交互式 API 资源管理器 ::: embed "https://api.example.com/v1/explorer" ::: ``` 有关更多信息,请参阅 [嵌入参考](../../content/containers/embed)。 ### 3. 内容聚合 对于必须与您的核心文档一起被搜索的外部内容,考虑建立一个构建步骤,从其他来源获取数据并将其转换为 Markdown。这允许 `docmd` 在单一、统一的 [搜索索引](../../plugins/search) 中索引您的所有信息。 ## 权衡 虽然嵌入提供了统一的外观,但它偶尔会引入性能开销或在移动设备上出现“滚动嵌套”问题。此外,iframe 内的内容不会原生被 `docmd` 的搜索引擎索引。如果搜索一致性至关重要,建议优先考虑 [OpenAPI 生成](./openapi-generation) 或其他基于 Markdown 的摄取方法。 --- ## [现有的 Markdown 存储库](https://docs.docmd.io/zh/07/guides/integrations/existing-markdown-repos/) --- title: "现有的 Markdown 存储库" description: "如何从现有的 Markdown 文件中即时生成专业的文档网站,且无需任何配置。" --- ## 问题 您可能有一个已经建立的存储库,其中包含数百或数千个原始 Markdown 文件 - - 例如旧的 Wiki、Obsidian 库或技术笔记集。手动转换 Frontmatter、修复失效链接以及重组文件以适应新引擎是一项艰巨的任务,这往往阻碍了团队对文档进行现代化改造。 ## 为什么重要 您的内容应该保持可移植性且与工具无关。高质量的文档引擎应该适应您现有的文件,而不是强迫您的文件适应引擎。避免厂商锁定可确保您的知识资产保持标准、可读且面向未来。 ## 方法 `docmd` 遵循严格的 CommonMark 规范,并且默认设计为 **零配置 (zero-config)**。您可以将 `docmd` CLI 指向任何包含 Markdown 文件的目录,它将智能地引导生成一个功能齐全的文档网站,而无需修改源内容的任何一行。 ## 实施 ### 1. 即时引导 导航到您现有的 Markdown 文件夹并运行开发服务器。`docmd` 将扫描您的目录结构并立即在内存中构建一个功能完善的站点。 ```bash cd my-existing-docs/ npx @docmd/core dev ``` ### 2. 自动导航 (Auto-Router) 如果没有找到 `navigation.json` 或 `docmd.config.js`,`docmd` 将触发其 [自动路由 (Auto-Router)](../../configuration/navigation#automatic-sidebar-generation)。它会递归映射您的文件夹结构,美化目录名称(例如,`getting-started` 变为 `Getting Started`),并自动生成逻辑侧边栏分类。 ### 3. 智能标题推断 您不需要为每个文件都添加 `title` Frontmatter。`docmd` 采用级联解析策略来确定页面标题: 1. **Frontmatter**:检查 `title` 或 `h1` 键。 2. **第一个标题**:提取文件内容中发现的第一个 `# 标题`。 3. **文件名**:作为备选方案,美化文件名(例如,`install-guide.md` 变为 `Install Guide`)。 ### 4. 弹性的语法处理 `docmd` 的设计具有很强的弹性。如果您现有的文件中包含来自其他引擎的专有语法或旧的短代码,它们将被安全地渲染为原始文本或被跳过,从而确保您的构建永远不会因为尚未迁移的内容而失败。 ## 权衡 自动生成的侧边栏通常按文件名的字母顺序排序。虽然像 `01-intro.md` 和 `02-setup.md` 这样的命名方式效果很好,但更具描述性的文件名可能会以不直观的顺序出现。对于生产级站点,我们建议过渡到手动 [导航配置](../../configuration/navigation),以获得对用户旅程的完全控制。 --- ## [GitHub Actions CI/CD](https://docs.docmd.io/zh/07/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "如何使用 GitHub Actions 和 docmd 自动化您的文档构建和部署,以实现高效的文档工作流。" --- ## 问题 从本地机器手动构建和部署文档容易出错,且存在环境不一致(例如 Node.js 版本不同)和安全风险。此外,这还会造成瓶颈,因为部署取决于单个人员的可用性和本地设置。 ## 为什么重要 持续部署 (CD) 可确保您的文档始终与软件同步。当技术更新被合并时,它应该在几分钟内(而不是几天)到达用户手中。自动化保证了每次构建都在干净、可重复的环境中进行,从而保持了高质量和高可靠性的标准。 ## 方法 利用 GitHub Actions 在每次推送或拉取请求 (Pull Request) 时运行 `docmd` 构建流水线。生成的静态资产随后可以自动部署到 GitHub Pages、Cloudflare Pages 等托管提供商,或使用 Docker 部署到容器化环境中。 ## 实施 ### 1. 标准 GitHub Pages 工作流 创建 `.github/workflows/docs.yml` 以自动化构建和部署过程。 ```yaml name: 部署文档 on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # 将站点构建到 'site/' 目录中 - run: npx @docmd/core build - name: 上传产物 uses: actions/upload-pages-artifact@v3 with: path: site/ - name: 部署到 GitHub Pages uses: actions/deploy-pages@v4 ``` ### 2. 容器化部署 (Docker) 如果您自行托管文档,请使用 [部署命令](../../deployment) 生成生产级 `Dockerfile` 和服务器配置。 ```bash # 在本地生成 Docker 和 Nginx 配置 npx @docmd/core deploy --docker --nginx ``` 随后,您可以更新 GitHub Action,以便在发布新版本时构建此 Docker 镜像并将其推送到注册表(如 Docker Hub 或 GitHub Container Registry)。 ### 3. 拉取请求预览 通过为每个拉取请求生成临时的预览环境来增强您的工作流。这允许审查人员在更改合并到主分支之前查看渲染后的文档。有关更多详细信息,请参阅 [预览更改指南](../workflows-teams/previewing-changes)。 ## 权衡 自动化的 CI/CD 需要初始设置时间并需要管理机密(如 API 令牌)。然而,从长远来看,“无需干预”的部署过程带来的好处 - - 包括减少人为错误和缩短更新周期 - - 远超初始投入。对于大型站点,请确保您的工作流仅在文档目录中的文件发生更改时才触发,以节省 CI 额度。 --- ## [OpenAPI 生成](https://docs.docmd.io/zh/07/guides/integrations/openapi-generation/) --- title: "OpenAPI 生成" description: "如何将 OpenAPI/Swagger 架构集成到你的 docmd 工作流中,以实现自动化且同步的 API 参考文档。" --- ## 问题 手动维护 REST API 文档是一项重大的运营风险。一旦工程师修改了端点或更新了代码中的架构,文档就会过时。手动保持这些内容的同步既枯燥又容易出错,并且经常导致 API 使用者的集成失败。 ## 为什么这很重要 不准确的 API 参考是导致开发人员沮丧和支持工单增加的主要原因。自动化可确保你的文档保持为“事实来源”,实时(或在每次构建时)反映 API 的实际状态。这使工程师能够专注于构建功能,而不是手动更新文档表格。 ## 方法 实施一个异步构建流水线,将你的 `openapi.json` 或 `swagger.yaml` 架构转换为标准的 Markdown 文件。由于 `docmd` 擅长渲染带有复杂 [容器](../../content/containers/index.md) 的 Markdown,因此生成的 API 参考将与文档的其余部分在视觉上保持一致且融为一体。 ## 实现 ### 1. 构建流水线集成 你可以使用 `widdershins` 等工具或自定义脚本,在 CI/CD 流水线中作为一个预构建步骤从 OpenAPI 架构生成 Markdown。 ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. 优化 API 布局 API 参考通常内容密集,具有用于参数的大型表格和嵌套架构。使用 [Frontmatter](../../content/frontmatter.md) 优化页面布局以提高可读性。 ```markdown --- title: "REST API 参考" layout: "full" # 为密集表格最大化水平空间 --- ``` 设置 `layout: "full"` 会移除右侧的目录侧边栏,从而为宽代码块和响应示例提供更多空间。 ### 3. 使用 docmd 容器进行增强 你可以对生成的 Markdown 进行后处理,以注入 `docmd` 功能,例如用于多语言代码示例的 [选项卡 (Tabs)](../../content/containers/tabs.md) 或用于身份验证警告的 [标注 (Callouts)](../../content/containers/callouts.md)。 ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## 权衡 机器生成的文档在技术准确性方面非常出色,但往往缺乏有效学习所需的“人文关怀”。我们建议将 OpenAPI 生成用于 **技术参考 (Technical Reference)**(端点、参数、架构),同时提供手写的 **教程 (Tutorials)** 和 **概念指南 (Conceptual Guides)** 来解释 API 的背景和用例。 --- ## [缓存策略](https://docs.docmd.io/zh/07/guides/performance-delivery/caching-strategies/) --- title: "缓存策略" description: "如何使用不可变缓存、Etag 重新验证和生产级服务器配置来优化您的文档网站性能。" --- ## 问题 如果文档网站在提供服务时没有适当的缓存控制 (cache-control) 响应头,浏览器将在每次访问时非必要地重新下载图像、CSS 和 JavaScript 包。这会导致视觉卡顿、带宽消耗增加,并给期望文档能瞬间加载的重复访问用户带来糟糕的体验。 ## 为什么重要 有效的缓存是提高网站“感知性能”最有效的方法之一。通过确保静态资产存储在用户的浏览器本地,您可以消除重复网络请求带来的延迟。这使您的文档导航感觉更加流畅和可靠,即使在不稳定的网络连接下也是如此。 ## 方法 实施两级缓存策略:针对静态资产(CSS、JS、图像)的 **不可变缓存 (Immutable Caching)**,以及针对动态内容(HTML、JSON)的 **Etag 重新验证**。`docmd` 通过生成生产级配置来简化此过程,这些配置通过版本哈希自动处理缓存失效。 ## 实施 ### 1. 生产级服务器配置 实施最佳缓存的最简单方法是使用 [部署命令](../../deployment) 生成您的服务器配置。 ```bash # 生成经过优化的 Nginx 配置 npx @docmd/core deploy --nginx ``` ### 2. 不可变资产 对于不经常更改的资产(如主题样式和核心脚本),请使用长期缓存。`docmd` 会为这些资产附加版本哈希,以确保用户仅在您更新文档时才下载新版本。 ```nginx # 不可变资产的 Nginx 规则示例 location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML 与导航重新验证 您的 HTML 文件和 `navigation.json` 应始终检查更新,以确保用户能立即看到最新的内容和结构。使用 `no-cache` 指令强制浏览器使用 Etag 与服务器进行重新验证。 ```nginx # HTML 文件的 Nginx 规则示例 location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## 权衡 ### 过时内容 vs 性能 为资产设置较长的缓存时间可以获得极高的性能,但需要稳健的“缓存失效”策略。`docmd` 会为其核心文件自动处理此问题,但如果您手动向 `static/` 目录添加资产,则必须确保在内容更改时更新其引用(例如通过更改文件名或添加查询参数)。 ### CDN 集成 如果您正在使用 CDN(如 Cloudflare 或 AWS CloudFront),请确保其配置为遵循服务器的 `Cache-Control` 响应头。大多数现代 CDN 提供“即时刷新”功能,我们建议将其作为 CI/CD 流水线的一部分,在每次部署新版本文档时触发。 --- ## [CDN 与边缘网络部署](https://docs.docmd.io/zh/07/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN 与边缘网络部署" description: "如何通过将您的静态文档部署到内容分发网络 (CDN) 或边缘网络来最小化全球延迟。" --- ## 问题 将您的文档托管在一个地理区域(例如美国东部)的单一服务器上,意味着世界其他地区(例如欧洲或亚洲)的用户将体验到显著的网络延迟。每次页面加载、图像和脚本都必须跨越数千英里,这使您的文档在全球观众看来显得迟钝且无响应。 ## 为什么重要 高延迟直接损害开发者体验。即使您的文档写得很好且很轻量,“首字节时间 (TTFB)”也会受到物理定律的限制。如果您的网站感觉很慢,开发者更有可能失去焦点,或者完全放弃您的工具,转而使用文档更快速、更易于访问的工具。 ## 方法 最佳解决方案是将您的网站部署到边缘 CDN。由于 `docmd` 生成的是纯静态资产(HTML、CSS、JS),它非常适合边缘分发。CDN 会将您的文件复制到数百个全球分布的“边缘节点”,从距离用户最近的数据中心为他们提供服务。 ## 实施 ### 1. 选择平台 `docmd` 原生兼容所有现代静态托管和边缘平台。我们推荐以下平台,因为它们具有出色的全球性能和易用性: * **Cloudflare Pages**:极速的全球边缘网络,内置 DDoS 防护。 * **Vercel**:针对性能进行了优化,具有出色的开发工作流集成。 * **Netlify**:强大的自动化功能和稳健的全球 CDN。 ### 2. 自动化构建 使用 CI/CD 流水线,在您推送更改时自动构建并部署您的网站。有关详细示例,请参阅 [GitHub Actions 指南](../../guides/integrations/github-actions-cicd)。 ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # 将站点构建到默认的 'site/' 目录中 - run: npm install && npx @docmd/core build # 示例:部署到 Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: my-docs directory: site ``` ### 3. 验证 部署完成后,您可以使用 PageSpeed Insights 或全球 Ping 测试等工具验证您的全球性能。您应该会看到来自世界各地几乎任何位置的亚秒级响应时间。 ## 权衡 全球边缘网络抽象了服务器管理,这对于文档团队来说是一个主要优势。然而,调试区域性缓存问题偶尔会比查看单一服务器日志更复杂。使用具有强大“即时缓存失效”功能的平台,可确保您的用户在部署后立即看到文档的最新版本。 --- ## [低端设备优化](https://docs.docmd.io/zh/07/guides/performance-delivery/low-end-devices/) --- title: "低端设备优化" description: "如何构建高性能、无障碍的文档,使其在低配置硬件和慢速网络连接上也能无缝运行。" --- ## 问题 现代文档网站通常依赖沉重的 JavaScript 运行时来显示静态文本。对于使用旧款手机、廉价笔记本电脑或处于 3G/4G 慢速连接的用户,这些网站可能需要几秒钟才能加载完成。设备的处理器在解析大型 JS 包时会感到吃力,导致“输入延迟”、动画卡顿以及糟糕的整体阅读体验。 ## 为什么重要 技术文档应该是普遍可访问的。迫使处于新兴市场或硬件受限的用户下载并执行沉重的框架来阅读教程,会为学习制造不必要的障碍。轻量级的网站可确保您的产品信息可供所有人使用,无论其硬件配置或互联网速度如何。 ## 方法 采用 **HTML 优先** 策略。`docmd` 采用零框架架构设计,确保在构建过程中将主要内容渲染为标准 HTML。这使浏览器的主要线程保持畅通,从而确保即使在廉价设备上也能实现平滑滚动和快速度的导航。 ## 实施 ### 1. 极简的运行时足迹 默认情况下,`docmd` 的核心 UI 不使用 React、Vue 或任何其他沉重的客户端框架。这种预渲染方法确保了初始“首次内容绘制 (First Contentful Paint)”几乎立即发生。为了保持这种性能: * **限制自定义脚本**:避免在 `customJs` 配置中添加大型第三方库。 * **使用原生浏览器功能**:依靠标准 CSS 和 HTML5 元素,这些元素经过所有现代浏览器的高度优化。 ### 2. 战略性插件管理 虽然 [插件](../../plugins/usage) 增加了强大的功能,但它们可能会引入显著的性能开销。例如,[Mermaid 插件](../../plugins/mermaid) 需要大型引擎来渲染图表。如果您的用户主要使用低端设备,请考虑使用静态图像代替客户端渲染的图表。 ### 3. 响应式与优化的媒体 避免向移动用户发送尺寸过大的图像。使用 WebP 等现代格式,并考虑使用 `<picture>` 标签来更精细地控制响应式资产。 ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="功能概览" loading="lazy"> </picture> ``` 使用 `loading="lazy"` 属性可确保仅在图像进入用户视口时才下载,从而节省慢速连接下的带宽。 ### 4. 高效的搜索索引 `docmd` 生成限定范围的搜索索引,以保持较低的内存占用。然而,对于极大型站点,[搜索插件](../../plugins/search) 仍可能消耗大量内存。鼓励移动设备用户仅在必要时使用搜索栏,或按照 [本地优先搜索指南](../search/local-first-search) 中的说明优化您的索引。 ## 权衡 优先考虑低端设备的性能通常意味着避免使用“沉重”的交互功能,如复杂的 3D 可视化或大型客户端数据处理。这是一种刻意的设计选择,它重视 **包容性和速度** 超过视觉复杂性,确保您的文档对于尽可能广泛的受众来说始终是一个有用的资源。 --- ## [减少 JS 有效载荷](https://docs.docmd.io/zh/07/guides/performance-delivery/reducing-javascript-payload/) --- title: "减少 JS 有效载荷" description: "如何通过优化 JavaScript 依赖项并利用 docmd 的零框架架构来维护高性能文档网站。" --- ## 问题 许多现代文档工具依赖于沉重的 JavaScript 框架(如 React 或 Vue)来渲染静态文本。这些框架会为您的初始页面加载增加数百 KB 的体积,迫使浏览器在网站变得完全可交互之前下载、解析并执行大量代码。这导致了加载速度缓慢,并在低端设备上出现“点击无效(ghost clicks)”的情况。 ## 为什么重要 大型 JavaScript 有效载荷直接影响“可交互时间 (TTI)”。在技术文档中,用户需要快速获得答案,任何由沉重的框架初始化引起的延迟都是显著的可用性障碍。保持有效载荷较小,可确保搜索、导航和主题切换从页面出现的那一刻起就是瞬时的。 ## 方法 `docmd` 的核心客户端逻辑采用 **零框架 (Zero-Framework)** 架构。通过利用原生 JavaScript 和浏览器 API 而不是沉重的虚拟 DOM,我们将标准站点的总 JS 有效载荷保持在 **20KB** 以下。这种轻量级的基石确保了在所有设备和网络条件下都能获得最佳性能。 ## 实施 ### 1. 利用原生浏览器 API 避免为简单任务导入 jQuery 或 Lodash 等沉重的库。现代浏览器拥有强大的原生 API,几乎可以处理任何与文档相关的需求,且开销为零。 ```javascript // docmd.config.js export default { // ✅ 使用小巧、专用的脚本,而不是沉重的库 customJs: ['/static/js/my-custom-logic.js'] }; ``` ### 2. 战略性插件管理 虽然 [插件](../../plugins/usage) 增加了强大的功能,但某些插件会显著增加您的 JavaScript 有效载荷。例如,[Mermaid 插件](../../plugins/mermaid) 需要大型客户端库来渲染图表。仅在对您的内容至关重要时才启用沉重的插件,并考虑它们对整体页面重量的影响。 ### 3. 延迟加载非关键脚本 如果您需要包含第三方服务(如分析或反馈组件),请确保它们异步加载或延迟加载,以免阻塞文档的渲染。 ```html <!-- 在您的自定义 head 注入中 --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. 优化资源 确保您提供的任何自定义 JavaScript 都经过压缩。`docmd` 处理其核心资产的压缩,但您需要负责优化添加到 `static/` 目录中的任何文件。 ## 权衡 使用原生 JavaScript 构建复杂的交互功能可能比使用声明式框架需要更多的手动工作。然而,对于文档而言 - - 其中 95% 的内容是静态文本和图像 - - 零框架方法带来的性能收益远超沉重框架带来的开发便利性。 --- ## [亚秒级(Sub-100ms)导航](https://docs.docmd.io/zh/07/guides/performance-delivery/sub-100ms-navigation/) --- title: "亚秒级(Sub-100ms)导航" description: "docmd 的原生 SPA 路由和基于意图的预取功能如何提供即时页面切换,从而实现最佳阅读体验。" --- ## 问题 传统的单页导航中,每次点击链接都会触发完整的浏览器重新加载,这会产生令人不适的“白屏闪烁”并打断读者的思路。浏览器必须丢弃当前状态,请求新的 HTML,并重新解析 CSS 和 JavaScript - - 即使只有中心内容区域发生了变化。 ## 为什么重要 文档用户经常在不同章节之间跳转,例如教程、API 参考和概念指南。如果每次切换都需要一秒钟或更长时间,就会产生认知摩擦并阻碍深入探索。即时导航使文档感觉像是一个原生应用程序,显著提高了用户满意度和参与度。 ## 方法 `docmd` 利用构建在预生成静态文件之上的高性能 **单页应用 (SPA) 路由**。这允许浏览器拦截链接点击,仅在后台获取必要的内容,并动态更新页面而无需完整重新加载。这种方法保留了侧边栏、目录和主题设置的状态,从而实现近乎瞬时的切换。 ## 实施 `docmd` 的 SPA 路由默认启用,并使用几种先进技术来实现亚秒级导航速度: ### 1. 基于意图的预取 当用户将鼠标悬停在导航链接上时,`docmd` 会检测到导航意图并开始后台获取目标页面的内容。当用户真正点击链接时,数据通常已经存在于浏览器的缓存中,使得切换感觉是瞬间完成的。 ### 2. 局部 DOM 更新 `docmd` 不是重新渲染整个页面,而是智能地仅更新必要的逻辑区域: * **主体内容 (Main Content)**:经过 Markdown 渲染的主要正文。 * **目录 (Table of Contents)**:刷新以匹配新页面的标题。 * **导航状态 (Navigation State)**:更新侧边栏中的活动和展开状态。 ### 3. 用于自定义逻辑的生命周期事件 由于浏览器不执行完整加载,标准事件(如 `DOMContentLoaded`)仅触发一次。要在每次导航后执行自定义 JavaScript(例如重新初始化第三方小部件或跟踪页面视图),您应该监听 `docmd:page-mounted` 事件。 ```javascript // 示例:导航后重新初始化自定义组件 document.addEventListener('docmd:page-mounted', (event) => { const currentPath = event.detail.path; console.log(`成功导航至:${currentPath}`); // 在此处编写自定义逻辑 if (currentPath.includes('/api/')) { initApiConsole(); } }); ``` 有关更多详细信息,请参阅 [客户端事件](../../api/client-side-events) 文档。 ## 权衡 ### 脚本执行 SPA 路由会自动重新执行新页面 Markdown 正文中的 `<script>` 标签。但是,在您的主题或布局中定义的全局脚本仅在初始加载期间运行一次。对于必须在每个页面上执行的逻辑,请始终使用 `docmd:page-mounted` 事件。 ### SEO 和无障碍 尽管具有类似 SPA 的行为,`docmd` 仍然为每个页面生成完整的、独立的 `.html` 文件。这确保了搜索引擎爬虫可以抓取全部内容,并且对于禁用 JavaScript 的用户,网站仍然功能完备,从而保持了卓越的 SEO 和无障碍标准。 --- ## [重大变更与弃用](https://docs.docmd.io/zh/07/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "重大变更与弃用" description: "如何使用版本化文档和上下文标注有效地传达 API 变更和迁移路径。" --- ## 问题 当产品引入重大版本变更时,某些 API、功能或配置不可避免地会被弃用或删除。浏览最新文档的用户必须清楚地知道他们是否正在使用过时的模式,但为了避免混淆,文档本身应集中于现代实现。 ## 为什么重要 未能明确提示重大变更会导致开发者浪费数小时调试引擎不再支持的代码。上下文警告和清晰的迁移路径对于维护用户信任、减少支持请求以及确保顺利过渡到软件的最新版本至关重要。 ## 方法 将 `docmd` 的 [版本控制引擎](../../configuration/versioning.md) 与 [标注容器 (Callout Containers)](../../content/containers/callouts.md) 相结合,在旧版内容和现代内容之间建立清晰的区别。策略是将完整的旧版文档移至归档版本,同时在当前版本中提供链接回归档内容的“迁移锚点”。 ## 实施 ### 1. 归档旧版内容 发布新的大版本(例如 v2.0)时,将现有文档移至归档目录(例如 `docs-v1/`)。这可确保为尚未迁移的用户保留前一版本的完整上下文。 ### 2. 上下文迁移标注 在最新文档中,在发生重大变更的页面顶部使用 `warning`(警告)或 `important`(重要)标注。这为试图使用旧模式的用户提供了即时价值。 ```markdown # 配置 API ::: callout warning "迁移:v2.0 中的重大变更" `siteTitle` 属性已被移除。它已被全局 `title` 属性取代。 * **从 v1.x 迁移?** 请更新您的 `docmd.config.js`。 * **需要 v1.x 文档?** 请参阅 [旧版配置指南](../../configuration/overview.md)。 ::: ``` ### 3. 保持 AI 准确性 通过严格将已弃用的内容与当前版本分开,您可以显著提高 AI 工具的准确性。`docmd` 的 [LLMs 插件](../../plugins/llms.md) 会根据活动版本生成上下文文件。归档旧内容可以防止 AI 模型“产生幻觉”,并向寻找现代解决方案的用户推荐过时的 API。 ## 权衡 主动管理迁移标注会增加维护开销。如果无限期保留,页面可能会充斥着旧的警告。我们建议建立一种策略,即在旧版本达到其生命周期终点 (EOL) 或在一个完整的大版本发布周期后移除迁移标注,以保持文档精简和专注。 --- ## [多团队协作](https://docs.docmd.io/zh/07/guides/scaling-architecture/multi-team-collaboration/) --- title: "多团队协作" description: "如何使用去中心化导航和全局菜单栏,让多个团队在不发生冲突的情况下共同为一个统一的文档项目做出贡献。" --- ## 问题 当多个独立的团队(如前端、后端、DevOps 和产品团队)共同为一个文档库做出贡献时,往往会出现组织摩擦。团队可能会意外地覆盖全局导航设置,创建冲突的样式范式,或者在并发更新期间破坏跨领域边界的链接。 ## 为什么重要 写作体验中的摩擦会导致“文档孤岛”,即团队为了避免共享库的复杂性而创建独立的、孤立的维基。这破坏了统一文档门户的连贯用户体验,并使用户更难找到关于整个系统的全面信息。 ## 方法 利用 `docmd` 的去中心化 [解析优先级](../../configuration/navigation#navigation-resolution-priority) 系统。这允许各个团队使用本地 `navigation.json` 文件对其特定领域拥有完全的自主权,同时由一个核心团队管理全局 [菜单栏](../../configuration/menubar) 和视觉设计系统。 ## 实施 ### 1. 基于领域的归属权 将您的文档划分为分配给特定团队的顶级目录。每个团队完全拥有其分配文件夹的内容和内部结构。 ```text my-project/ ├── docs/ │ ├── frontend/ # 归 UI 团队所有 │ │ ├── navigation.json # 团队特定的侧边栏 │ │ └── components.md │ ├── backend/ # 归 API 团队所有 │ │ ├── navigation.json │ │ └── database.md │ └── docmd.config.js # 归平台/核心团队所有 ``` ### 2. 全局上下文切换 (菜单栏) 中央平台团队控制 [菜单栏](../../configuration/menubar),它作为主要的导航层,用于在不同的团队领域之间切换。 ```javascript // docmd.config.js export default { menubar: { enabled: true, items: [ { text: '前端', url: '/frontend/components' }, { text: '后端', url: '/backend/database' }, { text: '基础设施', url: '/devops/setup' } ] } }; ``` ### 3. 利用 navigation.json 实现本地自主 当用户浏览 `/frontend/` 目录下的内容时,`docmd` 会自动优先处理 `frontend/navigation.json` 文件。侧边栏会动态更新,仅反映前端特定的层级结构,从而防止导航被来自其他团队的无关信息所淹没。 ```json // docs/frontend/navigation.json [ { "title": "设计系统", "path": "/frontend/design-system" }, { "title": "组件库", "path": "/frontend/components" } ] ``` ## 权衡 去中心化导航要求团队注意跨领域的链接。虽然 `docmd` 可以有效地处理相对链接,但移动整个团队目录将破坏其他团队文件中的链接。我们建议在不同团队领域之间的链接使用根相对路径(以 `/` 开头),以确保稳定性。 --- ## [管理多版本文档](https://docs.docmd.io/zh/07/guides/scaling-architecture/multi-version-documentation/) --- title: "管理多版本文档" description: "如何使用统一的切换器和路径保留功能维护文档的多个版本(v1、v2、旧版本)。" --- ## 问题 随着软件产品的演进,企业用户往往仍在使用较旧的 LTS(长期支持)版本。在发布 v2 时直接放弃 v1 的文档会让这些用户陷入困境,而为每个版本维护完全独立的网站则会导致用户体验支离破碎并分散 SEO 权重。 ## 为什么重要 如果没有一种无缝切换版本的方式,开发者往往会错误地将最新文档中的指令应用到旧版本环境中,从而导致错误并增加支持成本。统一的版本控制系统可确保用户始终了解自己所处的上下文,并能轻松地在同一页面的不同版本之间跳转。 ## 方法 `docmd` 具有原生的 [版本控制引擎](../../configuration/versioning),将版本视为一等公民。它将构建结果隔离到以版本为前缀的目录中,提供“粘性切换 (Sticky Switching)”机制来保留当前页面路径,并将搜索结果准确限制在当前版本上下文中。 ## 实施 ### 1. 组织源目录 将最新的文档保留在标准目录中(例如 `docs/`),并将旧版本放在同级目录中(例如 `docs-v1/`)。 ```text my-project/ ├── docs/ # v2.x (当前版本) ├── docs-v1/ # v1.x (旧版 LTS) └── docmd.config.js ``` ### 2. 配置版本映射 在 `docmd.config.js` 中定义您的版本结构。`current`(当前)版本在根 URL 处提供服务,其他版本在 `/{id}/` 处提供服务。 ```javascript // docmd.config.js export default { versions: { current: 'v2', // 在 / 处提供服务 position: 'sidebar-top', // 切换器位置 all: [ { id: 'v2', dir: 'docs', label: 'v2.x (最新)' }, { id: 'v1', dir: 'docs-v1', label: 'v1.x (LTS)' } ] } }; ``` ### 3. 特定版本的导航 如果不同版本的导航结构有所不同,您可以在每个版本的源目录中放置一个 `navigation.json` 文件。`docmd` 会自动检测并将其用于该特定版本。 ```json // docs-v1/navigation.json [ { "title": "旧版安装", "path": "/legacy-setup" }, { "title": "迁移到 v2", "path": "/migration" } ] ``` ### 4. 路径保留 (粘性切换) `docmd` 会在用户切换版本时自动尝试保留其当前路径。如果用户在 `v2` 网站的 `/api/auth` 页面并切换到 `v1`,引擎将尝试将其路由到 `/v1/api/auth`。如果目标版本中不存在该页面,则会退回到该版本的首页。 ## 权衡 在单个代码库中存储多个版本会随着时间的推移增加库的大小。对于非常庞大的文档集,请考虑使用 CI/CD 在构建过程中动态拉取旧版本文档目录,而不是将其提交到主分支。 --- ## [组织大型代码库](https://docs.docmd.io/zh/07/guides/scaling-architecture/organising-large-repositories/) --- title: "组织大型代码库" description: "如何使用落地页和层级导航在复杂的文档结构中保持导航清晰度和易用性。" --- ## 问题 随着文档库增长到数百个页面,在单个庞大的侧边栏中显示所有主题会使网站变得难以使用。用户会陷入“选择瘫痪”,寻找一个特定的模块需要滚动浏览数十个无关的、已展开的分类。 ## 为什么重要 导航是用户体验的关键组成部分。杂乱无章的界面会降低产品的感知质量,使开发者更难找到所需的答案。如果导航感觉混乱,用户通常会认为软件本身也同样难以使用。 ## 方法 使用 `docmd` 的 [导航配置](../../configuration/navigation) 实施层级分组策略。核心原则是在需要之前隐藏复杂性。使用可折叠组和“落地页 (Hub Pages)”来保持侧边栏整洁,确保用户可以专注于当前任务而不会感到不知所措。 ## 实施 ### 1. 层级分组 在 `navigation.json` 或配置文件中使用 `collapsible` 属性对相关页面进行分组。这可以保持侧边栏整洁,并允许用户仅展开他们感兴趣的部分。 ```json // docs/navigation.json [ { "title": "高级 API", "icon": "braces", "collapsible": true, "children": [ { "title": "身份验证", "path": "/api/auth" }, { "title": "Webhook", "path": "/api/webhooks" }, { "title": "速率限制", "path": "/api/rate-limiting" } ] } ] ``` ### 2. 实施落地页 (Hub Pages) 不要在侧边栏中公开每一个单独的页面,而是创建中央“落地页”,作为特定子系统的目录。使用 [网格和卡片](../../content/containers/grids.md) 提供可用内容的视觉化、高层级概览。 ```markdown # 集成中心 (Integrations Hub) ::: grids ::: grid ::: card "数据库集成" icon:database 将您的应用程序连接到 Postgres 和 MongoDB 等流行数据库。 [查看数据库指南](../integrations/openapi-generation.md) ::: ::: ::: grid ::: card "支付网关" icon:credit-card 了解如何集成 Stripe、PayPal 等。 [查看支付指南](../integrations/alongside-other-tools.md) ::: ::: ::: ``` ### 3. 利用面包屑导航 `docmd` 会根据您的文件夹结构和导航层级为每个页面自动生成 [面包屑导航](../../content/syntax/advanced.md#breadcrumbs)。通过使用落地页,您可以保持侧边栏的专注,同时面包屑导航提供必要的上下文,并方便用户向上级层级导航。 ## 权衡 使用落地页可能会增加用户到达深度内容的“点击”次数。然而,这通常优于一个使内容发现变得困难的杂乱侧边栏。权衡的结果是一个更整洁、更专业的界面,显著提高了文档的整体可搜索性和专注度。 --- ## [可扩展的文件夹结构](https://docs.docmd.io/zh/07/guides/scaling-architecture/scalable-folder-structure/) --- title: "可扩展的文件夹结构" description: "如何使用 Diátaxis 框架和 docmd 的解析系统来组织大规模文档项目。" --- ## 问题 小型文档站点通常以一个扁平的 `docs/` 文件夹开始。然而,随着项目发展到包含多个模块、教程、API 和概念深度探讨时,杂乱无章的文件夹结构就变成了沉重的维护负担。文件变得难以定位,导航侧边栏也变成了令人望而生畏的“链接墙”。 ## 为什么这很重要 杂乱无章的文件夹结构会直接导致混乱的用户体验,因为 `docmd` 的路由和默认导航都是派生自你的文件系统。对于作者来说,缺乏清晰的结构会导致内容重复和命名不一致,随着更多贡献者加入项目,文档将变得更难管理。 ## 方法 我们建议采用信息架构框架,如 [Diátaxis](external:https://diataxis.fr/),它将内容分为四个不同的类别:教程 (Tutorials)、操作指南 (How-To Guides)、参考 (Reference) 和解释 (Explanation)。将这些类别严格映射到你的物理文件系统,为读者和作者提供一个清晰的路线图。 ## 实现 ### 1. Diátaxis 层次结构 将你的源目录组织成语义化的子文件夹。这种物理隔离使得管理大量文件变得更加容易,并确保了整洁的 URL 结构。 ```text my-project/ ├── docs/ │ ├── tutorials/ (学习导向:循序渐进的课程) │ │ └── getting-started.md │ ├── guides/ (任务导向:解决特定问题) │ │ └── deployment.md │ ├── reference/ (信息导向:技术描述) │ │ └── api-spec.md │ ├── explanation/ (理解导向:理论背景) │ │ └── architecture.md │ └── navigation.json (主导航定义) └── docmd.config.js ``` ### 2. 战略性地使用 navigation.json 与其在全局配置中定义庞大的导航树,不如在源目录中使用 `navigation.json` 文件。`docmd` 遵循 [解析优先级](../../configuration/navigation#navigation-resolution-priority) 系统,允许你为网站的不同部分定义不同的侧边栏层次结构。 ```json // docs/navigation.json [ { "title": "教程", "icon": "book-open", "children": [ { "title": "开始使用", "path": "/tutorials/getting-started" } ] }, { "title": "参考", "icon": "braces", "children": [ { "title": "API 规范", "path": "/reference/api-spec" } ] } ] ``` ### 3. 基于文件的路由 请记住,每个 Markdown 文件在文件夹结构中的位置决定了它最终的 URL。例如,`docs/guides/auth.md` 变成 `your-site.com/guides/auth`。利用这一点为你的用户创建直观、易记的 URL。 ## 权衡 像 Diátaxis 这样严格的组织框架要求清晰地理解内容类型。技术作家偶尔可能会发现很难对特定文档进行分类(例如,“这是一个指南还是一个教程?”)。随着团队和文档的增长,建立清晰的内部贡献指南对于保持一致性至关重要。 --- ## [扩展到 1000+ 页面](https://docs.docmd.io/zh/07/guides/scaling-architecture/scaling/) --- title: "扩展到 1000+ 页面" description: "如何使用 docmd 在大型文档项目中保持高性能和易用性。" --- ## 问题 随着软件产品的成熟,其文档自然会不断扩展。当一个项目增长到数百或数千个 Markdown 文件时,许多文档生成器都会面临构建时间缓慢、开发服务器热重载滞后以及导航结构让维护者和用户都感到不知所措的问题。 ## 为什么重要 如果文档生成需要几分钟而不是几秒钟,作者就会失去进行细微修改的动力,从而导致内容陈旧且不准确。对于用户来说,庞大且杂乱无章的侧边栏菜单会使查找信息变得非常沮丧,导致支持工单增加,开发者体验下降。 ## 方法 `docmd` 专为速度和可扩展性而设计。通过利用高性能的解析引擎和颗粒化的基于文件的构建策略,它可以在几秒钟内处理数千个页面。其优化的 SPA(单页应用)交付确保了用户在大型网站中的导航依然是瞬时完成的。 ## 实施 ### 1. 颗粒化的项目结构 避免将所有文件放在一个扁平的目录中。使用与您的产品架构相匹配的深层嵌套文件夹结构。这使得项目更易于维护,并允许 `docmd` 在开发期间高效地跟踪更改。 ### 2. 优化的搜索索引 对于大型网站,[搜索插件](../../plugins/search) 至关重要。`docmd` 生成高度压缩的搜索索引,并按需加载。这确保了即使有数千个页面,初始页面加载速度依然很快,同时在整个网站范围内提供全文搜索能力。 ### 3. 版本控制和归档 利用 [版本控制引擎](../../configuration/versioning) 将旧版内容与当前文档分开。通过将旧版本隔离到各自的构建上下文中,可以减少日常更新中需要重新处理的页面数量,从而显著提高开发速度。 ```javascript // docmd.config.js export default { versions: { current: 'v3', all: [ { id: 'v3', dir: 'docs/current', label: 'v3.x (最新)' }, { id: 'v2', dir: 'docs/v2', label: 'v2.x (旧版)' } ] } }; ``` ### 4. 基于组件的导航 使用 `navigation.json` 文件将您的导航分解为逻辑片段。这允许您为网站的不同部分定义独特的侧边栏层级,防止主导航变得杂乱无章。 ## 权衡 大型网站在构建过程中自然会消耗更多的磁盘空间和内存。为了在极端规模(10,000+ 页面)下保持亚秒级的构建时间,请考虑使用配备 SSD 存储和充足 RAM 的高性能 CI/CD 环境,以处理文件的并行处理。 --- ## [Untitled](https://docs.docmd.io/zh/07/guides/search/fast-accurate-search/) --- ## [搜索相关性与结构](https://docs.docmd.io/zh/07/guides/search/improving-search-relevance/) --- title: "搜索相关性与结构" description: "如何组织您的 Markdown 内容以提高搜索相关性,并帮助用户更快地找到信息。" --- ## 问题 搜索引擎根据结构对内容进行优先级排序。如果一篇高质量指南使用“简介”或“步骤 1”等通用标题,搜索引擎可能无法为隐藏在段落中的核心关键词分配足够的权重。这导致相关页面被埋没在搜索结果深处,令期望立即获得答案的用户感到沮丧。 ## 为什么重要 用户通常搜索特定的技术术语(例如“身份验证令牌”或“部署限制”),而不是完整的句子。如果您的文档结构没有强调这些术语,搜索引擎就无法自信地对您的内容进行排名。高搜索相关性是实现文档门户“自助化”与处理大量支持工单之间的区别。 ## 方法 组织您的 Markdown,以便搜索索引器能够自动识别并优先处理核心概念。`docmd` 的搜索引擎为页面 `title`(标题)、`description`(描述)和 `headers`(标题行)分配的权重高于正文文本。通过优化这些结构化元素,您可以显著提高内容的发现率。 ## 实施 ### 1. 优化 Frontmatter 元数据 使用 [Frontmatter](../../content/frontmatter) 块提供明确的关键词和描述性摘要。[搜索插件](../../plugins/search) 会索引这些字段,以便在搜索 UI 中提供更好的结果和更有用的片段。 ```yaml --- title: "AWS S3 存储配置" description: "如何为 AWS S3 集成配置 IAM 角色和存储桶权限。" keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. 使用语义化标题 避免使用通用的标题名称。相反,在标题中包含相关的关键词,为用户和搜索引擎提供上下文。 * **低相关性:** `## 步骤 1:配置` * **高相关性:** `## 步骤 1:配置 AWS IAM 角色` ### 3. 利用标注强调关键信息 使用 [标注容器 (Callout Containers)](../../content/containers/callouts) 来显示关键警告或“专业技巧”也可以提高搜索相关性。标注中的内容通常在语义上是独立的,索引器可以对其进行不同的权重处理,以突出显示重要的故障排除步骤。 ## 权衡 优化搜索相关性需要严谨的写作。随着产品的演进,Frontmatter 中的关键词如果不及进行定期检查,可能会变得过时。此外,在标题中包含过多关键词(关键词堆砌)会使文档显得重复且读起来不够自然。请在 SEO 和可读性之间寻求平衡。 --- ## [本地优先搜索优化](https://docs.docmd.io/zh/07/guides/search/local-first-search/) --- title: "本地优先搜索优化" description: "如何针对 docmd 的高性能客户端搜索引擎优化您的文档内容。" --- ## 问题 本地优先搜索引擎完全在浏览器中运行,无需服务器往返即可提供即时结果。然而,这意味着它们受到浏览器内存和处理能力的限制。如果搜索索引没有得到妥善优化,它可能会消耗过多的 RAM,导致浏览器标签页卡顿甚至崩溃,尤其是在移动设备上。 ## 为什么重要 无缝的搜索体验对于提高开发者效率至关重要。如果搜索工具引起性能问题或消耗过多内存,用户就会避免使用它。针对本地优先搜索优化您的内容,可确保您的文档在所有设备和网络条件下都能保持快速、响应灵敏且可靠。 ## 方法 `docmd` 的 [搜索插件](../../plugins/search) 在构建时使用提取流水线来创建高度优化的索引。通过剪枝不必要的数据并专注于高价值的语义字段,它确保了生成的索引既全面又轻量。 ## 实施 ### 1. 构建时提取 在构建过程中,`docmd` 会处理您的 Markdown 文件,仅提取最相关的文本进行索引。它会自动剥离: * HTML 标签和结构化样板。 * 不增加语义价值的 Markdown 语法字符。 * 仅用于格式化、会导致索引膨胀的元素。 这确保了索引器仅接收干净、有意义的文本,从而显著减小了最终索引的大小。 ### 2. 利用 Frontmatter 进行战略索引 您可以使用 [Frontmatter](../../content/frontmatter) 明确控制页面的索引方式。例如,如果页面包含大量重复数据(如原始 JSON 日志),而这些数据对搜索没有帮助,您可以选择仅索引标题和元数据。 ```yaml --- title: "API 日志参考" search: indexBody: false # 仅索引标题和行标题 --- ``` ### 3. 客户端内存管理 `docmd` 在浏览器中精细管理搜索索引的生命周期。它采用按需加载策略,这意味着仅在用户首次与之交互时才初始化搜索引擎。这保持了初始页面加载的足迹较小,并确保系统资源仅在需要时才被使用。 ## 权衡 从搜索索引中激进地剪枝内容(例如排除大型代码块)有时会导致错过一些冷门的搜索结果。您必须在轻量、快速的索引与全面的搜索覆盖范围之间取得平衡。我们建议优先考虑标题和概念性描述,因为这些是开发者最常用的搜索目标。 --- ## [基于 Git 的工作流](https://docs.docmd.io/zh/07/guides/workflows-teams/git-based-workflows/) --- title: "基于 Git 的工作流" description: "如何使用 Git、拉取请求 (Pull Request) 和自动化的 CI/CD 检查来有效地管理文档贡献。" --- ## 问题 允许直接向主文档分支推送更改通常会导致链接失效、格式不一致以及未经核实的各种技术信息。然而,如果增加过多的摩擦 - - 例如要求单独的 CMS 帐户 - - 会阻碍社区成员和内部开发人员贡献有价值的更新。 ## 为什么重要 协作是优秀文档的生命线。如果开发人员发现了一个拼写错误或过时的示例,他们应该能够在几分钟内提交修复。基于 Git 的工作流提供了一个熟悉、透明且安全的环境来进行贡献,确保每一项更改在发布前都经过审查和验证。 ## 方法 实施一种由自动化验证和预览环境支持的“拉取请求 (Pull Request, PR)”模式。`docmd` 专为这种工作流设计,因为它运行在标准的 Markdown 文件上,这些文件易于使用熟悉的 Git 工具进行差异对比、审查和合并。 ## 实施 ### 1. 启用“编辑此页”链接 您可以配置 `docmd` 在页脚或侧边栏中自动生成“编辑此页”链接。这允许用户直接从文档页面跳转到存储库中对应的源文件。 ```javascript // docmd.config.js export default { editLink: { enabled: true, baseUrl: 'https://github.com/my-org/my-docs/edit/main/docs', text: '建议修改' } }; ``` 有关更多详细信息,请参阅 [编辑链接配置](../../configuration/overview.md#editlink)。 ### 2. 利用 Threads 插件进行上下文审查 对于需要详细反馈的复杂更新,请使用 [Threads 插件](../../plugins/threads.md)。这允许作者和审查人员在审查阶段直接在 Markdown 内容中留下行内评论,保持讨论的上下文一致性。 ```markdown ::: thread "审查人姓名" 我们是否应该在这里添加一个关于新身份验证流程的代码示例? ::: ``` ### 3. CI 中的自动化验证 将 `docmd` 集成到您的 CI/CD 流水线(例如 [GitHub Actions](../integrations/github-actions-cicd.md))中以验证每个 PR。至少,您的流水线应运行构建命令,以确保没有引入语法错误或损坏的配置。 ```bash # 在您的 CI 流水线中 npm install npx @docmd/core build ``` ## 权衡 严格的 Git 工作流偶尔会减慢微小更新的速度,例如修复关键的拼写错误或更新服务状态通知。对于高产出的团队,我们建议指定“文档负责人”,他们有权快速处理小的更改,同时对重大技术更新保持严格的审查标准。 --- ## [维护一致性](https://docs.docmd.io/zh/07/guides/workflows-teams/maintaining-consistency/) --- title: "维护一致性" description: "如何通过使用 Lint 检查和标准化模式,确保大型文档团队中的统一声音和专业质量。" --- ## 问题 在大型团队中,每个技术作家都有不同的风格和偏好。有些人可能使用加粗文本进行强调,而另一些人则使用斜体。有些人可能更喜欢“点击按钮”,而另一些人则使用“选择选项”。随着时间的推移,您的文档可能会变成各种冲突风格的“百纳被”,使用户难以快速解析信息,并降低了产品的专业信任度。 ## 为什么重要 一致性孕育熟悉感。当用户学习复杂的 API 或工作流时,他们依赖一致的词汇和结构模式来有效地浏览内容。统一的声音使您的文档感觉像是一个连贯的、高质量的产品,从而建立了对软件本身的信心。 ## 方法 使用 [标准化容器](../../content/containers) 和自动化 Lint 工具进行机械式的一致性强制执行。通过自动化低层级的风格和语法检查,您可以让编辑人员腾出精力,专注于内容的高层级质量、准确性和清晰度。 ## 实施 ### 1. 使用标准化的 docmd 模式 鼓励所有贡献者使用 `docmd` 内置的主题化容器,而不是即兴使用手动 Markdown 格式。这确保了整个站点中的每一个警告、提示或说明在外观和行为上都是一致的。 ```markdown <!-- ❌ 避免:不一致且无样式 --> **注意:** 请重启服务。 <!-- ✅ 推荐:一致、无障碍且具有主题感 --> ::: callout info 请重启服务。 ::: ``` 使用 [标注 (Callouts)](../../content/containers/callouts) 可确保您的文档保持专业外观并符合无障碍标准,而无需作者付出额外努力。 ### 2. 实施散文 Lint 检查 集成 **Vale** 或 **Markdownlint** 等工具来强制执行品牌术语、语气和语法。这些工具可以配置为自动检查被动语态、偏见语言或不正确的品牌拼写。 ```ini # .vale.ini 示例 MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. CI/CD 中的自动化强制执行 在您的 [GitHub Actions](../../guides/integrations/github-actions-cicd) 或其他 CI/CD 流水线中包含一致性检查。这确保了每个拉取请求 (Pull Request) 在合并之前都会自动进行风格和结构一致性审计。 ```bash # Lint 检查的 CI 步骤示例 - name: Lint Documentation run: vale docs/ ``` ## 权衡 如果社区贡献者在修复简单的拼写错误时遇到了多个“风格错误”,严格的 Lint 检查有时会打击他们的积极性。我们建议将外部贡献的 Linter 敏感度设置为 `warning`(警告),并为内部团队更新保留 `error`(错误)状态,以在一致性与包容性之间取得平衡。 --- ## [预览更改](https://docs.docmd.io/zh/07/guides/workflows-teams/previewing-changes/) --- title: "预览更改" description: "如何设置本地和云端预览环境,以确保您的文档在发布前能够完美渲染。" --- ## 问题 在没有实时预览的情况下编写 Markdown 往往会导致格式错误、容器损坏以及错误的图像路径,而这些问题通常只有在内容发布到生产环境后才会显现。这会导致用户体验不佳,并为维护者增加额外的工作量,因为他们必须不断地为简单的渲染问题推送热修复。 ## 为什么重要 高质量的文档对于赢得开发者的信任至关重要。一个损坏的警告框或未渲染的语法看起来非常不专业,甚至可能在软件运行方式上误导用户。在文档发布前看到“真实”的效果是捕获错误、提高可读性并确保无缝用户体验最有效的方法。 ## 方法 实施多阶段预览策略:在编写时使用 `docmd` 的 [本地开发](../../getting-started/quick-start#local-development) 服务器获取即时反馈,并利用临时云环境(如 Vercel 或 Cloudflare Pages)在拉取请求 (Pull Request) 中进行最终审查。 ## 实施 ### 1. 即时本地预览 查看更改最快的方法是运行 `docmd dev` 服务器。它具有热模块替换 (HMR) 功能,可在您保存 Markdown 文件时自动刷新浏览器。 ```bash # 启动本地开发服务器 npx @docmd/core dev ``` ### 2. 基于云的预览环境 对于协作审查,请配置您的 CI/CD 平台为每个拉取请求生成唯一的“预览 URL”。由于 `docmd` 输出标准的静态文件,它与所有主流托管提供商兼容。 * **构建命令**:`npx @docmd/core build` * **输出目录**:`site` 这允许审查人员在更改合并到主分支之前,查看其在类生产环境中的确切外观和行为。 ### 3. 利用 Threads 进行协作审查 将您的云预览与 [Threads 插件](../../plugins/usage) 相结合。这允许团队成员直接在渲染后的预览页面上留下反馈,弥补了源代码 Markdown 与最终用户体验之间的鸿沟。 ## 权衡 在拥有数千页文档的大型存储库中,为每次提交构建完整的静态站点可能会非常耗时,且会消耗大量的 CI/CD 资源。为了优化这一点,请配置您的 CI 流水线,仅在源目录(例如 `/docs`)中的文件被修改时才触发文档构建。 --- ## [建立工作流](https://docs.docmd.io/zh/07/guides/workflows-teams/setting-up-workflow/) --- title: "建立工作流" description: "如何使用 docmd 和“文档即代码 (docs-as-code)”原则建立高效的多作者文档协作工作流。" --- ## 问题 当团队缺乏结构化的文档工作流时,更新往往会被推迟、遗忘或仅通过临时消息共享。如果没有明确的流程,内容会变得碎片化,格式变得不一致,技术作家花在解决合并冲突上的时间比编写高质量内容的时间还要多。 ## 为什么重要 如果没有正式的流程,文档会迅速过时并失去价值。如果更新文档需要等待缓慢的软件发布周期,您的指南将永远与实际的产品功能脱节,从而导致用户沮丧并增加支持成本。 ## 方法 将文档部署从软件发布周期中解耦出来,同时采用与软件工程相同的健壮流程(分支 → 拉取请求 → CI/CD 预览)。`docmd` 的轻量化特性允许团队以最小的开销实践“文档即代码”,确保您的指南与软件一样可靠且保持最新。 ## 实施 ### 1. 存储库策略 选择最适合您组织结构的策略: * **单体存储库 (Monorepo) 策略**:在主应用存储库中保留一个 `/docs` 文件夹。这非常适合确保文档更改与它们所描述的代码在同一个拉取请求 (Pull Request) 中合并,从而保持完美的同步。 * **独立存储库策略**:最适合大型组织或开源项目,由专门的团队独立于主应用的构建流水线来管理文档。 ### 2. 通过 CI/CD 进行验证 将 `docmd` 集成到您的 CI/CD 流水线中,以确保每次更新在技术上都是完善的。至少,您的流水线应运行构建命令,以检查语法错误和配置问题。 ```bash # GitHub Actions 中的验证步骤示例 - name: 验证文档 run: npm install && npx @docmd/core build ``` 有关详细的设置说明,请参阅 [GitHub Actions 指南](../../guides/integrations/github-actions-cicd)。 ### 3. 协作审查流程 为所有文档更新建立同行评审 (Peer Review) 的文化。使用拉取请求来讨论更改、验证格式并确保技术准确性。您可以利用 [Threads 插件](../../plugins/usage) 在渲染后的内容上直接进行详细讨论。 ## 权衡 采用“文档即代码”工作流可能会给非技术贡献者(如产品经理或法律团队)带来障碍,他们可能会觉得 Git 和 Markdown 令人望而生畏。为了减轻这种影响,可以考虑使用 GitHub 内置的 Web 编辑器进行微小修复,或利用 [实时预览](../../content/live-preview) 功能提供更直观、更具视觉感的创作体验。 --- ## [版本管理工作流](https://docs.docmd.io/zh/07/guides/workflows-teams/versioning-release-workflows/) --- title: "版本管理工作流" description: "如何使用 docmd 的版本控制引擎和发布策略,使文档发布与软件部署保持同步。" --- ## 问题 使软件发布与相应的文档更新保持同步是一项重大的协作挑战。通常情况下,文档在实际代码部署之前就已经在站点上更新(这会误导当前用户),或者在软件发布几天后才延迟更新(这会让早期采用者感到沮丧)。 ## 为什么重要 软件行为与其文档之间的脱节是导致开发者产生挫败感的主要原因。为了使文档有效,它必须严格映射到用户当前运行的软件特定版本。为每个版本提供正确的上下文,可确保顺畅的入门和故障排除体验。 ## 方法 使用 `docmd` 的 [版本控制引擎](../../configuration/versioning) 隔离活跃开发中的文档。这允许您的团队在一个单独的目录(例如 `docs-next/`)中异步编写即将发布的功能的内容,并仅在正式软件发布时才将其提升为“稳定”或“当前”状态。 ## 实施 ### 1. 组织您的目录 在主 `docs/` 文件夹中维护稳定的文档,并为即将发布的版本创建一个专用目录。 ```text 项目根目录/ ├── docs/ # 当前稳定版 (v1.x) ├── docs-v2/ # 即将发布的版本 (v2.0) └── docmd.config.js ``` ### 2. 配置版本 在配置中注册这两个版本。您可以将即将发布的版本标记为“Beta”或“Next”,以通过版本切换器向用户发出状态信号。 ```javascript // docmd.config.js export default { versions: { current: 'v1.0', all: [ { id: 'v1.0', dir: 'docs', label: 'v1.x (稳定版)' }, { id: 'v2.0', dir: 'docs-v2', label: 'v2.0 (Beta)' } ] } }; ``` ### 3. 提升流程 当您准备正式发布新版本时: 1. **更新配置**:将 `docmd.config.js` 中的 `current` 版本 ID 更改为 `v2.0`。 2. **更新标签**:从 `all` 数组的 `label` 中移除“(Beta)”标签。 3. **存档旧文档**:在 `all` 数组中保留 `v1.0` 条目,以便使用旧版本的用户仍然可以访问相关的文档。 ## 权衡 ### 维护开销 维护多个版本的文档需要严谨的态度。如果在稳定版本中修复了关键的拼写错误或安全警告,请确保该修复也应用到即将发布的版本目录中,以防止在新版本发布时出现“回归”问题。 ### SEO 与搜索 多个版本偶尔会导致搜索结果指向旧文档。使用 `seo` 插件和正确的规范 (canonical) 标签,确保“当前”版本始终被搜索引擎优先考虑。有关管理过渡的更多信息,请参阅 [处理重大更改](../scaling-architecture/breaking-changes-deprecations)。 --- ## [docmd 文档:零配置的 Markdown 文档生成器](https://docs.docmd.io/zh/07/) --- title: "docmd 文档:零配置的 Markdown 文档生成器" description: "用 Markdown 在几秒内构建生产级文档。零配置即可上手,默认支持 AI,兼顾性能与 SEO。" titleAppend: false --- ::: hero # docmd 一条命令,将 Markdown 转化为生产级文档网站。静态 HTML 助力 SEO。SPA 提升速度。默认支持 AI。 ::: button "快速开始" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#333 icon:github ::: ## 开始 几秒钟内即可运行一个生产级文档网站 - - 无需样板代码,无需配置文件。 ```bash npx @docmd/core dev ``` 就这么简单。在 `docs/` 文件夹中编写 Markdown,docmd 就会自动构建一个完整的文档网站,包含导航、搜索、SEO、站点地图等 - - 一切开箱即用。 ## 核心功能 所有必要功能均内置,无需为基础功能安装插件。 ::: grids ::: grid ::: card "即时启动" icon:rocket 一条命令,从 Markdown 文件到生产级文档网站。无需配置文件。 ::: ::: ::: grid ::: card "AI 就绪" icon:brain-circuit 自动生成 `llms.txt` 和 `llms-full.txt` 供 LLM 使用。你的文档默认支持 AI。 ::: ::: ::: grid ::: card "内置搜索" icon:search 基于 MiniSearch 的客户端全文搜索。零配置,跨版本和语言均可使用。 ::: ::: ::: grid ::: card "实时预览" icon:monitor 直接在文档页面中嵌入可实时编辑的代码沙盒。 ::: ::: ::: grid ::: card "主题引擎" icon:palette 切换内置主题或创建专属主题。支持浅色、深色及系统偏好模式。 ::: ::: ::: grid ::: card "原生国际化" icon:globe 一流的多语言支持,包含语言优先的 URL、每语言独立搜索及翻译 UI 字符串。 ::: ::: ::: ## 扩展 Markdown 超越静态文本。docmd 在 Markdown 中直接提供丰富的容器语法 - - 提示框、标签页、卡片、网格、主页横幅、折叠面板等。 ::: button "探索容器" ./content/containers/index.md icon:blocks ::: grids ::: grid ::: card "交互式沙盒" 使用 [实时预览](./content/live-preview.md) API,将可编辑的预览窗口自然地嵌入页面。 ::: ::: ::: grid ::: card "内联协作" 在开发模式下选择文本,打开 [讨论区](./plugins/threads.md),与文档团队在旁留下评论。 ::: ::: ::: --- ## [从 Docusaurus 迁移](https://docs.docmd.io/zh/07/migration/docusaurus/) --- title: "从 Docusaurus 迁移" description: "关于将你的 Docusaurus v2/v3 项目转移到 docmd 的综合指南。" --- # 从 Docusaurus 迁移到 docmd Docusaurus 是一个基于 React 的流行文档框架。`docmd` 提供了一个快速、零配置的替代方案,它的编译速度显著提高,并且不需要 React 组件即可渲染丰富的功能。 ## 第 1 步:运行迁移引擎 在现有 Docusaurus 项目的根目录(即 `docusaurus.config.js` 或 `docusaurus.config.ts` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --docusaurus ``` ### 自动发生的更改 1. **备份**: 你的整个项目(不包括 `node_modules` 和 `.git`)会被安全地移动到一个新的 `docusaurus-backup/` 目录中。 2. **内容迁移**: 你的 `docs/` 文件夹将被恢复到根目录,供 `docmd` 使用。 3. **配置生成**: 生成一个 `docmd.config.js` 文件,从你的 Docusaurus 配置中提取站点标题 (`title`)。 ## 第 2 步:测试设置 命令完成后,你可以立即在 `docmd` 中预览你的 Markdown 内容: ```bash npx @docmd/core dev ``` 你的 Markdown 文件将会编译,但你的导航侧边栏将是空的。 ## 第 3 步:手动配置 Docusaurus 拥有复杂的编程式配置,`docmd` 不会尝试猜测这些配置。你需要手动进行映射。 ### 1. 导航设置 Docusaurus 的侧边栏通常是在 `sidebars.js` 中自动生成或配置的。 **所需操作:** 在新的 `docs/` 目录内创建一个 `navigation.json` 文件来构建你的 `docmd` 侧边栏。请参阅 [导航指南](../configuration/navigation.md)。 ### 2. 替换 MDX 组件 Docusaurus 严重依赖 MDX (`.mdx`) 来渲染自定义 React 组件(如 Tabs、Admonitions 或自定义 UI 元素)。`docmd` 是纯粹由 Markdown 驱动的,不使用 React。 **所需操作:** 你必须将任何自定义的 `<MyReactComponent />` 标签转换为标准 Markdown,或使用 `docmd` 原生的 [容器](../content/containers/callouts.md)。 #### 示例:转换提示框 (Admonitions) **Docusaurus:** ```markdown :::tip My Tip 这是一个有用的技巧。 ::: ``` **docmd:** (除了为了更好的用户体验而更改了一些关键字外,学习曲线几乎为零。`docmd` 原生支持 Docusaurus 风格的提示框作为标注)。 ```markdown ::: callout tip "My Tip" 这是一个有用的技巧。 ::: ``` #### 示例:转换选项卡 (Tabs) **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> 这是一个苹果。 </TabItem> <TabItem value="orange" label="Orange"> 这是一个橙子。 </TabItem> </Tabs> ``` **docmd:** (转换为原生的 `docmd` 选项卡容器语法) ```markdown ::: tabs == tab "Apple" 这是一个苹果。 == tab "Orange" 这是一个橙子。 ::: ``` ### 3. 本地化 (i18n) 如果你使用了 Docusaurus 的 `i18n` 功能,你的翻译文件可能位于 `i18n/locale/docusaurus-plugin-content-docs/current/`。 **所需操作:** 将这些文件移入 `docmd` 的目录结构(`docs/en/`、`docs/zh/` 等),并在 `docmd.config.js` 中配置语言环境。请参阅 [本地化指南](../configuration/localisation/index.md)。 ## 后续步骤 - 探索 [布局与 UI](../configuration/layout-ui.md) 设置,以匹配你的 Docusaurus 主题。 - 将基于 React 的 hero 页眉转换为 `docmd` [英雄区块容器](../content/containers/hero.md)。 --- ## [从 MkDocs 迁移](https://docs.docmd.io/zh/07/migration/mkdocs/) --- title: "从 MkDocs 迁移" description: "关于将你的 MkDocs (或 Material for MkDocs) 项目转移到 docmd 的综合指南。" --- # 从 MkDocs 迁移到 docmd MkDocs,特别是配合 Material 主题,是一个流行的基于 Python 的文档生成器。`docmd` 提供了类似的 Markdown 优先体验,但它依赖于 Node.js/Bun 以实现极快的构建速度和丰富的交互功能,而无需复杂的 Python 扩展。 ## 第 1 步:运行迁移引擎 在现有 MkDocs 项目的根目录(即 `mkdocs.yml` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --mkdocs ``` ### 自动发生的更改 1. **备份**: 你的整个项目会被安全地移动到一个新的 `mkdocs-backup/` 目录中。 2. **内容迁移**: 你的 `docs/` 文件夹将被恢复到根目录,供 `docmd` 使用。 3. **配置生成**: 生成一个 `docmd.config.js` 文件,从你的 `mkdocs.yml` 中提取站点名称 (`site_name`)。 ## 第 2 步:测试设置 命令完成后,在 `docmd` 中预览你的内容: ```bash npx @docmd/core dev ``` 你的 Markdown 文件将会编译,但你的导航侧边栏将是空的。 ## 第 3 步:手动配置 MkDocs 使用 `mkdocs.yml` 来定义站点导航和扩展。你需要将这些设置转换为 `docmd`。 ### 1. 导航设置 在 MkDocs 中,导航严格定义在 `mkdocs.yml` 的 `nav` 键中。 **所需操作:** 你必须在 `docs/` 文件夹内创建一个 `navigation.json` 文件。 **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "首页", "path": "/" }, { "title": "指南", "collapsible": true, "children": [ { "title": "安装设置", "path": "/setup" }, { "title": "使用方法", "path": "/usage" } ] } ] ``` ### 2. 替换 Python Markdown 扩展 如果你使用了 "Material for MkDocs",你可能依赖于 Python Markdown 扩展(如 PyMdown Extensions)来实现选项卡、提示框或任务列表。 **所需操作:** 将 MkDocs 特有的扩展语法转换为 `docmd` 原生的 [容器](../content/containers/callouts.md)。 #### 示例:转换提示框 (Admonitions) **MkDocs (PyMdown):** ```markdown !!! note "可选标题" 这是一个提示框内容块。 ``` **docmd:** ```markdown ::: callout info "可选标题" 这是一个提示框内容块。 ::: ``` #### 示例:转换选项卡 (Tabs) **MkDocs (SuperFences):** ```markdown === "选项卡 1" 选项卡 1 的内容。 === "选项卡 2" 选项卡 2 的内容。 ``` **docmd:** ```markdown ::: tabs == tab "选项卡 1" 选项卡 1 的内容。 == tab "选项卡 2" 选项卡 2 的内容。 ::: ``` ## 后续步骤 - `docmd` 具有原生搜索功能。你不需要配置搜索插件。 - 探索 [主题选项](../theming/customisation.md) 来自定义网站颜色,以匹配你旧的 Material 主题。 --- ## [迁移概览](https://docs.docmd.io/zh/07/migration/overview/) --- title: "迁移概览" description: "了解如何轻松将现有文档迁移到 docmd。" --- # 迁移到 docmd `docmd` 提供了一个完全自动化的 **迁移引擎**,帮助您通过一条命令从旧的或竞争性的文档平台过渡。迁移引擎的目的是消除移动 Markdown 文件和重组项目目录的繁琐工作。 ## 工作原理 迁移命令将执行以下操作: 1. **检测**您现有的配置文件(例如 `docusaurus.config.js`,`mkdocs.yml`)。 2. **提取**站点的核心元数据,例如 `title`。 3. **备份**您现有的文件和目录,安全地放入 `*-backup/` 目录(例如 `docusaurus-backup/`)。 4. **复制**您的 Markdown 内容到标准的 `docmd` `docs/` 目录中。 5. **生成**一个为您内容量身定制的全新 `docmd.config.js`。 随后,您可以立即运行 `npx @docmd/core dev`,以查看在 `docmd` 引擎中渲染的内容。 ## 会迁移什么 | 功能 | 是否自动迁移? | | :--- | :--- | | **Markdown 文件** | ✅ 是的,所有 `.md` 和 `.mdx` 文件都会移到 `docs/` | | **目录结构** | ✅ 是的,您的文件夹嵌套会被保留 | | **站点标题** | ✅ 是的,从您的配置中提取 | | **导航 / 侧边栏** | ⚠️ **否**,需要手动映射 | | **国际化 (i18n)** | ⚠️ **否**,需要手动映射 | | **版本管理** | ⚠️ **否**,需要手动映射 | | **自定义 React/Vue 组件** | ❌ 否,这些必须替换为 `docmd` 容器 | ## 为什么不自动迁移导航和 i18n 每个文档平台处理导航侧边栏、翻译和多版本的方式各不相同。例如,Docusaurus 使用复杂的 JavaScript 对象或自动生成的侧边栏,而 MkDocs 依赖严格缩进的 YAML 结构。 为了避免猜测复杂配置带来的错误和损坏迁移,`docmd` 会安全地移动您的内容,并要求您使用 `docmd` 简单的基于 JSON 的 API,原生配置导航、国际化和版本管理。 - **导航:** 请参阅 [导航设置](../configuration/navigation.md) 了解如何创建 `navigation.json`。 - **国际化:** 了解如何设置多语言文档,请参阅 [国际化指南](../configuration/localisation/index.md)。 - **版本管理:** 请参考 [版本管理设置](../configuration/versioning.md)。 ## 支持的平台 选择您当前的平台以获取具体的迁移说明: - [由 Docusaurus 迁移](./docusaurus.md) - [由 MkDocs 迁移](./mkdocs.md) - [由 VitePress 迁移](./vitepress.md) - [由 Astro Starlight 迁移](./starlight.md) --- ## [由 Astro Starlight 迁移](https://docs.docmd.io/zh/07/migration/starlight/) --- title: "由 Astro Starlight 迁移" description: "将您的 Astro Starlight 项目迁移到 docmd 的综合指南。" --- # 由 Astro Starlight 迁移到 docmd Starlight 是一个构建在 Astro 框架上的出色文档主题。`docmd` 提供了类似的默认零 JavaScript 体验,但它消除了配置完整 Web 框架 (Astro) 的需要,从而大幅降低了技术作者的学习曲线。 ## 第一步:运行迁移引擎 在您现有的 Starlight 项目的根目录(即 `astro.config.mjs` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --starlight ``` ### 自动执行的操作 1. **备份**:您的整个项目会被安全地移动到一个新的 `starlight-backup/` 目录中。 2. **内容迁移**:Starlight 将文档保存在 `src/content/docs/` 目录中。迁移引擎会自动提取该特定目录,并将其内容移动至根目录下的 `docs/` 文件夹供 `docmd` 使用。 3. **配置生成**:生成一个 `docmd.config.js` 文件,从 `astro.config.mjs` 内的 Starlight 集成中提取您的站点 `title`。 ## 第二步:测试配置 命令完成后,在 `docmd` 中预览您的内容: ```bash npx @docmd/core dev ``` 您的 Markdown 文件将被编译,但导航侧边栏此时为空。 ## 第三步:手动配置 ### 1. 导航设置 Starlight 通过 `sidebar` 数组在 `astro.config.mjs` 中定义导航。 **所需操作:** 您必须在您新生成的 `docs/` 文件夹内创建一个 `navigation.json` 文件。 **Starlight (`astro.config.mjs`):** ```js sidebar: [ { label: 'Guides', items: [ { label: 'Setup', link: '/guides/setup/' } ], }, ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. 替换 Astro 组件 (MDX/Markdoc) Starlight 使用通过 MDX 或 Markdoc 嵌入的 Astro 组件(`<Tabs>`, `<Card>` 等)。由于 `docmd` 依赖于纯 Markdown 语法而不是 UI 组件,因此需要转换这些内容。 **所需操作:** 将 Astro 组件替换为 `docmd` 的 [容器](../content/containers/callouts.md)。 #### 示例:转换标签页(Tabs) **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### 示例:转换提示框(Asides / Admonitions) **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter 映射 Starlight 通过 Astro 的内容合集功能对 Frontmatter 进行了严格地类型限制。`docmd` 的 Frontmatter 则更加简单。 如果您在 Starlight 中的登录页面使用了 `hero` 或 `banner` 前置属性,则需要将它们替换为直接写在 Markdown 正文中的 `docmd` [主页横幅](../content/containers/hero.md)。 ## 下一步 - 探索 `docmd` 的内置 [搜索插件](../plugins/search.md)(Starlight 使用 Pagefind,而 `docmd` 则原生提供了一个高度优化的本地搜索索引器)。 --- ## [由 VitePress 迁移](https://docs.docmd.io/zh/07/migration/vitepress/) --- title: "由 VitePress 迁移" description: "将您的 VitePress 项目迁移到 docmd 的综合指南。" --- # 由 VitePress 迁移到 docmd VitePress 是一个极其快速的基于 Vue 的静态网站生成器 (SSG) 框架。与 VitePress 类似,`docmd` 的运行速度也非常快,但它通过绝不向客户端加载任何 JavaScript 框架逻辑(没有 Vue 的水合成本)来实现这一点。 ## 第一步:运行迁移引擎 在您现有的 VitePress 项目的根目录运行以下命令: ```bash npx @docmd/core migrate --vitepress ``` ### 自动执行的操作 1. **备份**:您的整个项目会被安全地移动到一个新的 `vitepress-backup/` 目录中。 2. **内容迁移**:您的 `docs/` 文件夹会被恢复到根目录,供 `docmd` 使用。新 `docs/` 目录中会完全剥离 `.vitepress` 隐藏配置文件夹以防止冲突。 3. **配置生成**:生成一个 `docmd.config.js` 文件,从您的 `.vitepress/config.js` 或 `.ts` 中提取您的站点 `title`。 ## 第二步:测试配置 命令完成后,在 `docmd` 中预览您的内容: ```bash npx @docmd/core dev ``` 您的 Markdown 文件将被编译,但导航侧边栏此时为空。 ## 第三步:手动配置 VitePress 在其配置文件中设置导航,并在 Markdown 内部使用 Vue 组件。您需要将这些转换为 `docmd` 的语法。 ### 1. 导航设置 VitePress 在 `themeConfig.sidebar` 中使用对象数组。 **所需操作:** 在您的 `docs/` 目录内创建一个 `navigation.json` 文件。 **VitePress (`.vitepress/config.js`):** ```js themeConfig: { sidebar: [ { text: 'Guide', items: [ { text: 'Introduction', link: '/introduction' }, { text: 'Getting Started', link: '/getting-started' } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. 替换 Vue 组件 VitePress 允许作者在 Markdown 文件中直接嵌入 Vue 组件(例如 `<MyComponent />`)。由于 `docmd` 不会在客户端运行 Vue,您必须移除这些自定义组件,或者用原生的 Markdown 语法代替。 **所需操作:** 将特定的 Vue UI 组件替换为 `docmd` 的 [容器](../content/containers/callouts.md)。 #### 示例:提示框(自定义容器) VitePress 使用了与 `docmd` 非常相似的 markdown-it 自定义块语法。 **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` *注:VitePress 使用 `info`, `tip`, `warning`, `danger`, `details`。`docmd` 原生支持其中绝大多数,但您可能需要查看完整的 [docmd 提示框列表](../content/containers/callouts.md)。* ## 下一步 - 探索 `docmd` 的 [构建与部署](../deployment/index.md) 指南,因为 `docmd` 并不依赖 Vite 的构建管线。 --- ## [Analytics 插件](https://docs.docmd.io/zh/07/plugins/analytics/) --- title: "Analytics 插件" description: "集成 Google Analytics 4 或旧版 Universal Analytics,自动追踪用户交互行为。" --- `@docmd/plugin-analytics` 插件可将 Google Analytics 无缝集成到你的文档中。它支持现代 Google Analytics 4 (GA4)、旧版 Universal Analytics (UA),并内置针对交互弹性文档展示的原生事件追踪功能。 ## 配置 将下方的跟踪凭据添加到 `docmd.config.js` 的 `plugins` 部分即可启用分析功能。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { analytics: { // 1. Google Analytics 4 (Recommended) googleV4: { measurementId: 'G-XXXXXXX' }, // 2. Legacy Universal Analytics googleUA: { trackingId: 'UA-XXXXXXX-X' }, // 3. Behavioural Tracking Settings autoEvents: true, // Track clicks, downloads, and TOC interactions trackSearch: true // Track search keywords used by readers } } }); ``` ## 已追踪事件 当 `autoEvents` 启用时,插件会自动捕获以下用户交互并发送给你的分析提供商: * **外部链接**:追踪用户离开至外部资源。 * **文件下载**:自动记录带 `download` 属性或常见文件扩展名(`.pdf`、`.zip`、`.tar` 等)的链接点击。 * **目录(TOC)**:通过追踪右侧导航栏中的点击,监控哪些章节最受关注。 * **标题锚点**:记录用户点击"固定链接"(标题锚点)以分享特定章节。 * **搜索查询**:当 `trackSearch` 启用时,关键词会被捕获(带 1 秒防抖),帮助你了解用户正在寻找什么。 ## 技术细节 插件将必要的追踪脚本注入每个页面的 `<head>` 中。事件监听器通过高效的事件委托绑定到 `<body>`,确保对页面加载性能和 SPA 切换的零影响。 ::: callout info "隐私与 GDPR" 默认情况下,此插件不匿名处理 IP 地址,因为这现在由 GA4 原生处理。如果需要高级 Cookie 同意管理,可以使用 `customCss` 或自定义插件钩子手动注入你的同意管理脚本。 ::: --- ## [创建插件](https://docs.docmd.io/zh/07/plugins/building-plugins/) --- title: "创建插件" description: "扩展 docmd 的综合指南,涵盖自定义逻辑、数据注入和交互功能。" --- 插件是 `docmd` 的主要扩展机制。它们允许您注入自定义 HTML、修改 Markdown 解析逻辑、在模板渲染前注入构建时数据,以及自动化构建后任务。本指南概述了插件 API 和创建可共享组件的最佳实践。 ## 插件描述符 每个插件都应导出一个 `plugin` 描述符,声明其身份和功能。这使引擎能够在加载时验证、隔离和执行能力边界。 ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` > **注意:** 描述符目前是可选的(软性弃用警告)。从 **0.8.0 开始将成为必需**。 ## 核心能力 `capabilities` 数组决定您的插件可以使用哪些钩子。 | 能力 | 允许的钩子 | 阶段 | | :--- | :--- | :--- | | `init` | `onConfigResolved` | 初始化 | | `markdown` | `markdownSetup` | 设置 | | `head` | `generateMetaTags`, `generateScripts` (head) | 渲染 | | `body` | `generateScripts` (body) | 渲染 | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeRender`, `onPageReady` | 构建 | | `post-build`| `onPostBuild` | 构建后 | | `dev` | `onDevServerReady` | 开发服务器 | | `assets` | `getAssets` | 输出 | | `actions` | `actions` | 交互 | | `events` | `events` | 交互 | | `translations`| `translations` | 国际化 | 没有描述符的旧版插件可以访问所有钩子,因此在过渡期间不会有任何中断。 ## 插件 API 参考 `docmd` 插件是一个标准 JavaScript 对象(或导出为默认值的模块),实现以下一个或多个钩子。 | 钩子 | 描述 | | :--- | :--- | | `markdownSetup(md, opts)` | 扩展 `markdown-it` 实例。同步。 | | `generateMetaTags(config, page, root)` | 向 `<head>` 注入 `<meta>` 或 `<link>` 标签。 | | `generateScripts(config, opts)` | 返回包含 `headScriptsHtml` 和 `bodyScriptsHtml` 的对象。 | | `getAssets(opts)` | 定义要注入的外部文件或 CDN 脚本。 | | `onPostBuild(ctx)` | 在生成所有 HTML 文件后运行逻辑。 | | `translations(localeId)` | 返回给定语言环境的翻译字符串对象。 | | `actions` | 浏览器通过 WebSocket RPC 调用的命名动作处理程序对象。 | | `events` | 浏览器发送的即发即忘消息的命名事件处理程序对象。 | ## 创建本地插件 创建插件就像定义一个 JavaScript 文件一样简单。例如,`my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, markdownSetup: (md, options) => { // 示例:添加规则或使用 markdown-it 插件 }, generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`自定义插件:已验证 ${pages.length} 个页面。`); } }; ``` 在您的 `docmd.config.js` 中通过**完整包名**引用插件: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { 'my-awesome-plugin': { // 您的自定义选项放在这里 } } }); ``` > **注意:** 简写名称(如 `math`、`search`)专门为官方 `@docmd/plugin-*` 包保留。第三方插件必须始终使用其完整 npm 包名。 ### 插件隔离 每个钩子调用都被包裹在 try/catch 边界中。损坏的插件无法使构建崩溃或干扰其他插件。错误会被记录并收集到构建结束时的摘要中。 ## 生命周期钩子 docmd 提供深度集成钩子,允许插件在整个构建管道中操作配置、原始源和页面数据。 | 钩子 | 描述 | 预期返回值 | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | 在初始化后立即读取或修改活动规范化配置。 | `void` 或 `Promise<void>` | | **`onDevServerReady(server, wss)`** | 在开发模式下公开原始 Node.js `http.Server` 和 `WebSocketServer`。 | `void` 或 `Promise<void>` | | **`onBeforeParse(src, frontmatter)`** | 在传递给 markdown-it 解析之前预处理原始 markdown 字符串数据。 | `string` 或 `Promise<string>` | | **`onAfterParse(html, frontmatter)`** | 后处理表示 markdown 正文段的生成 HTML。 | `string` 或 `Promise<string>` | | **`onBeforeRender(page)`** | 在模板渲染前调用。接收完整的 `PageContext`。对 `frontmatter` 和 `html` 的修改会反映在渲染输出中。 | `void` 或 `Promise<void>` | | **`onPageReady(page)`** | 在页面写入目标文件之前访问完整组装的页面元数据。 | `void` 或 `Promise<void>` | ### `onBeforeRender` 和 `PageContext` `onBeforeRender` 钩子适用于需要注入源文件派生构建时数据的插件 - - 读取文件元数据、计算自定义 frontmatter 字段或从外部源加载数据。 ```typescript interface PageContext { sourcePath: string; // .md 源文件的绝对路径。始终设置。 frontmatter: Record<string, any>; // 可变 - 更改反映在模板输出中 html: string; // 可变 - 渲染的 markdown 正文 localeId?: string; versionId?: string; relativePathToRoot?: string; } ``` ```javascript export default { plugin: { name: 'my-metadata-plugin', version: '1.0.0', capabilities: ['build'] }, onBeforeRender: async (page) => { // sourcePath 始终可用 - 无需猜测或路径构建 const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } }; ``` ## 深入了解:资产注入 `getAssets()` 钩子允许您的插件安全地捆绑客户端逻辑。 ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), dest: 'assets/js/plugin-init.js', type: 'js', location: 'body' } ]; } ``` ## 翻译插件(国际化) 渲染客户端 UI 的插件应通过 `translations(localeId)` 钩子公开可翻译字符串。 ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['translations', 'body'] }, translations: (localeId) => { try { const p = path.join(__dirname, 'i18n', `${localeId}.json`); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } try { const p = path.join(__dirname, 'i18n', 'en.json'); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } return {}; } } ``` ## WebSocket RPC 动作 插件可以注册在开发服务器上运行并可通过 `window.docmd` API 从浏览器调用的**动作处理程序**和**事件处理程序**。 ```javascript export default { plugin: { name: 'my-live-plugin', version: '1.0.0', capabilities: ['actions', 'events'] }, actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`页面已查看: ${data.path}`); } } }; ``` `ctx`(ActionContext)对象提供: | 方法 | 描述 | | :--- | :--- | | `ctx.readFile(path)` | 相对于项目根目录读取文件。 | | `ctx.writeFile(path, content)` | 写入文件(触发重建 + 重载)。 | | `ctx.readFileLines(path)` | 将文件读取为行数组。 | | `ctx.broadcast(event, data)` | 向所有连接的浏览器推送事件。 | | `ctx.source` | 用于块级 markdown 操作的源编辑工具。 | | `ctx.projectRoot` | 项目根目录的绝对路径。 | | `ctx.config` | 当前 docmd 站点配置。 | ::: callout info "仅开发模式 🛡️" WebSocket RPC 系统仅在 `docmd dev` 期间活跃。生产构建不包含 API 客户端或任何服务器端动作处理。 ::: ## 最佳实践 1. **声明能力**:始终导出带有声明能力的 `plugin` 描述符。从 `0.8.0` 开始将成为必需。 2. **使用 `onBeforeRender` 进行数据注入**:如果您的插件读取源文件或计算 frontmatter 字段,请使用 `onBeforeRender` - 而不是 `generateMetaTags`。`sourcePath` 在 `PageContext` 中始终可用。 3. **异步/等待**:始终对 `onPostBuild`、`onBeforeRender` 和动作处理程序使用 `async` 函数。 4. **无状态**:避免在插件对象中维护状态,因为 `docmd` 可能在开发重建期间重新初始化插件。 5. **命名约定**:对于社区插件,以 `docmd-plugin-` 为前缀(如 `docmd-plugin-analytics`)。 6. **动作命名空间**:以插件名称为前缀(如 `my-plugin:save-note`)以避免冲突。 7. **动作验证**:始终在动作中定义和要求明确的有效载荷模式。 8. **日志记录**:在 `onPostBuild` 中使用提供的 `log()` 辅助函数。 ::: callout tip "AI 就绪设计 🤖" `docmd` 插件 API 设计为 **LLM 最优**。由于钩子使用标准 JavaScript 对象和类型,没有隐藏的复杂类层次结构,AI 代理可以以最少的指令为您生成无错误的自定义插件。 ::: --- ## [Git 插件](https://docs.docmd.io/zh/07/plugins/git/) --- title: "Git 插件" description: "显示直接从 Git 仓库获取的最后更新时间戳和提交历史。" --- **Git 插件**为您的文档页面添加仓库感知的元数据。它显示每个页面的最后修改时间、贡献者信息,并提供可选的"编辑此页"链接 - 所有这些都直接从您的 Git 历史记录中获取,无需配置。 ::: callout info "核心插件" Git 插件已包含在 `@docmd/core` 中,默认启用。它会自动检测您的项目是否在 Git 仓库中,如果不在则会自动禁用。基本功能无需安装或配置。 ::: ## 功能 ### 最后更新时间戳 每个页面自动显示其最后修改时间,显示在页面底部的编辑链接旁边。时间戳来自最近修改该源文件的 Git 提交。 时间戳对于最近的更改使用相对格式("2小时前"、"3天前"),对于较旧的内容则切换到绝对日期("2026年3月15日")。 ### 提交历史工具提示 将鼠标悬停在"最后更新"文本上,可以显示该页面最近提交的工具提示。每个条目显示提交消息、作者(附带 Gravatar 头像)和相对时间戳。 这提供了关于最近更改的快速上下文,无需离开页面 - 对于了解更新内容和更新者非常有用。 ### 编辑链接 配置仓库 URL 后,插件会显示"编辑此页"链接,直接在您的 Git 提供商的网页编辑器中打开源文件。 ```javascript plugins: { git: { repo: 'https://github.com/your-org/your-docs', branch: 'main' } } ``` 插件自动检测 GitHub、GitLab 和 Bitbucket URL,并为每个提供商构建正确的编辑链接格式。 ## 配置 | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | 仓库 URL(例如 `https://github.com/org/repo`)。编辑链接必需。 | | `branch` | `string` | `'main'` | 编辑链接的分支名称。 | | `editLink` | `boolean` | `true` | 设置 `repo` 时显示"编辑此页"链接。 | | `lastUpdated` | `boolean` | `true` | 显示最后更新时间戳。 | | `commitHistory` | `boolean` | `true` | 悬停时显示提交历史工具提示。 | | `maxCommits` | `number` | `6` | 工具提示中显示的最大提交数。 | | `dateFormat` | `string` | `'relative'` | 时间戳格式:`relative`(相对)、`iso`(ISO 格式)或 `locale-aware`(本地化格式)。 | ### 完整示例 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { git: { repo: 'https://github.com/docmd-io/docs', branch: 'main', editLink: true, lastUpdated: true, commitHistory: true, maxCommits: 5 } } }); ``` ## 页面级控制 使用 frontmatter 为特定页面禁用 Git 插件: ```markdown --- title: "内部笔记" plugins: git: false --- 此页面不会显示最后更新时间或编辑链接。 ``` ## 工作原理 插件在构建时使用标准 Git 命令读取 Git 历史。对于每个 markdown 文件: 1. 运行 `git log` 获取提交历史 2. 提取时间戳、作者和提交消息 3. 将数据注入页面上下文 4. 客户端 JavaScript 渲染 UI 组件 ::: callout tip "性能" Git 数据在构建过程中被缓存。每个文件的历史只查询一次,无论页面被渲染多少次(例如跨多个语言环境)。 ::: ## 要求 - 文档源必须位于 Git 仓库内 - 构建环境中必须可用 Git - 文件在其历史中必须至少有一个提交 没有 Git 历史的页面(尚未提交的新文件)不会显示时间戳或提交历史。 ## 从 editLink 迁移 如果您之前使用 `editLink` 配置选项,Git 插件提供相同的功能并附加额外特性: **之前(editLink 配置):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs', text: '编辑此页' } }); ``` **之后(Git 插件):** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', branch: 'main' } } }); ``` Git 插件自动从仓库和分支构建编辑 URL,因此您不再需要手动指定完整的编辑路径。 ::: callout warning "弃用通知" 独立的 `editLink` 配置选项已弃用,将在未来版本中移除。请迁移到 Git 插件以获取编辑链接功能。 ::: ## 本地化 插件包含所有 UI 字符串的翻译。支持的语言: - 英语 (en) - 德语 (de) - 中文 (zh) 自定义翻译可以通过标准 [UI 字符串](../configuration/localisation/ui-strings.md)系统提供。 --- ## [LLM 上下文插件](https://docs.docmd.io/zh/07/plugins/llms/) --- title: "LLM 上下文插件" description: "通过自动生成 llms.txt 和 llms-full.txt,为 AI 消费优化你的文档。" --- `@docmd/plugin-llms` 插件确保你的文档针对大型语言模型 (LLMs) 和 AI 代理进行了完美优化。它遵循不断增长的行业标准,即提供高层摘要和全面的上下文文件,AI 工具可以提取这些文件,以在产生极少幻觉的情况下理解你的项目。 ## 配置 LLM 插件默认启用。为了使其正常运行,你必须在 `docmd.config.js` 中提供一个 `url`。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ url: 'https://docs.example.com', plugins: { llms: { fullContext: true // 生成 llms-full.txt } } }); ``` ### 排除页面 如果页面包含敏感信息或你不希望 AI 模型学习的内部笔记,请在 frontmatter 中使用 `llms: false` 标志: ```yaml --- title: "内部开发机密" llms: false --- ``` ::: callout tip "最大化 AI 准确性 :robot:" 有关构建 Markdown(语义标题、替代文本等)的详细最佳实践,请参阅我们的 [针对 AI 代理进行优化](../guides/ai-optimisation/generating-ai-ready-docs.md) 指南。 ::: --- ## [Math 插件](https://docs.docmd.io/zh/07/plugins/math/) --- title: "Math 插件" description: "docmd 的原生 KaTeX/LaTeX 数学公式集成。" --- **Math 插件**为你的 docmd 网站添加原生 LaTeX 和 KaTeX 支持。 它将 `markdown-it-texmath` 与 `katex` 计算引擎安全集成,平滑渲染内联和块级数学公式,无需复杂的客户端 JavaScript 库。 ## 安装 ```bash docmd add math ``` ```javascript plugins: { math: {} } ``` ## 工作原理 1. 通过 `docmd.config.js` 启用插件。 2. 用 `$`(内联)或 `$$`(块级)标识符包裹标准 LaTeX 数学公式。 3. 服务器在静态站点构建时以原始静态 HTML 标签的形式智能处理这些数学规则。 4. 注入的极简 CSS 自动为这些类设置作用域,用户访问页面时即刻呈现可视化效果! ## 用法 ### 内联数学公式 使用单个美元符号 `$` 在段落中无缝注入标准方程式: ```markdown 这是一个内联方程式:$E = mc^2$ ``` 这是一个内联方程式:$E = mc^2$ ### 块级数学公式 对于较宽的数学证明或独立公式,使用双美元符号 `$$` 进行块级格式化: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid 图表 (Mermaid Diagrams)](https://docs.docmd.io/zh/07/plugins/mermaid/) --- title: "Mermaid 图表 (Mermaid Diagrams)" description: "使用 Mermaid.js 语法,直接在 Markdown 文件中创建专业的架构图、流程图和序列图。" --- `@docmd/plugin-mermaid` 插件将强大的 [Mermaid.js](external:https://mermaid.js.org/) 引擎集成到你的文档流水线中。它允许你将纯文本描述转换为高保真、交互式的图表,而无需离开 Markdown 环境。 ## 主要特性 - **零脚本**: 无需手动引入外部脚本或 CDN 链接。`docmd` 会检测使用情况,并仅在需要的地方注入渲染引擎。 - **主题感知**: 图表会自动调整其配色方案,以匹配网站的 **浅色** 或 **深色** 模式切换。 - **同构延迟加载**: 为了获得最佳性能,图表仅在进入用户视口时才进行初始化和渲染。 - **交互控制**: 每个图表都内置了 **平移 (Pan)**、**缩放 (Zoom)** 和 **全屏 (Fullscreen)** 功能,确保大型架构图在所有屏幕尺寸上都清晰可见。 - **图标集成**: 深度支持图标库,允许你在架构图中使用 `icon:name` 语法。 - **技术可读性**: 图表在源码中保持纯文本形式,使其易于进行版本控制,并且可被 AI 代理阅读。 ## 配置 要启用图表支持,请在 `docmd.config.js` 中添加 `mermaid` 插件: ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { mermaid: {} // 零配置启用 } }); ``` ## 实现展示 要渲染图表,请将你的 Mermaid 语法放置在带有 `mermaid` 语言标识符的围栏代码块内。 ### 1. 序列图 (Sequence Diagrams) 非常适合说明多个系统组件之间的交互。 ::: tabs == tab "预览" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: 输入 URL Browser->>Server: HTTP 请求 Server-->>Browser: HTTP 响应 Browser-->>User: 显示页面 ``` == tab "Markdown 源码" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: 输入 URL Browser->>Server: HTTP 请求 Server-->>Browser: HTTP 响应 Browser-->>User: 显示页面 ``` ```` ::: ### 2. 分析图表 使用内置的图表类型(如饼图或柱状图)将数据可视化。 ::: tabs == tab "预览" ```mermaid pie title 项目组成 "文档" : 45 "核心引擎" : 30 "插件" : 15 "UI 组件" : 10 ``` == tab "Markdown 源码" ````markdown ```mermaid pie title 项目组成 "文档" : 45 "核心引擎" : 30 "插件" : 15 "UI 组件" : 10 ``` ```` ::: ### 3. Git 工作流 为你的开发者指南可视化分支和合并策略。 ::: tabs == tab "预览" ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` == tab "Markdown 源码" ````markdown ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` ```` ::: ### 4. 架构与图标 使用集成的 **Lucide** 图标库创建与网站视觉风格匹配的丰富架构图。 ::: tabs == tab "预览" ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[数据库] in api service disk(icon:hard-drive)[存储] in api db:L -- R:disk ``` == tab "Markdown 源码" ````markdown ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[数据库] in api service disk(icon:hard-drive)[存储] in api db:L -- R:disk ``` ```` ::: ## 技术实现 Mermaid 插件通过在解析阶段拦截 `mermaid` 代码块并将其包裹在专门的 `<div class="mermaid">` 容器中来运行。 1. **检测**: 引擎扫描渲染后的 HTML 以查找 mermaid 容器的存在。 2. **资源注入**: 如果发现容器,`docmd` 会注入一个轻量级的 `init-mermaid.js` 模块。 3. **渲染**: Mermaid 库会被异步获取,并在客户端渲染图表,确保你的初始 HTML 负载保持小巧且快速。 ::: callout tip "针对 AI 代理的图表" 虽然图表在视觉上对人类有帮助,但它们在技术上对 AI 也是透明的。因为源码是纯文本,像 GPT-4 或 Claude 这样的模型可以通过 `llms-full.txt` 流“看到”你的系统架构或逻辑流。这允许 AI 根据你的图表解释复杂的架构关系。 ::: --- ## [OpenAPI 插件](https://docs.docmd.io/zh/07/plugins/openapi/) --- title: "OpenAPI 插件" description: "直接在 Markdown 页面中从 JSON 或 YAML 规范文件渲染 OpenAPI 3.x API 参考文档。" --- **OpenAPI 插件**将 OpenAPI 3.x 规范文件转换为结构化的 API 参考页面 - - 在构建时渲染,无需客户端 JavaScript,无需第三方依赖。每个端点、参数、请求体和响应都转换为语义化 HTML 表格。 ::: callout info "核心插件" OpenAPI 插件现在已**内置**于 `@docmd/core` 中,无需单独安装。它遵循 Docmd 的构建时渲染理念 - - 插件在构建时读取您的规范并输出干净、可访问的 HTML 表格,无需客户端 JavaScript。 ::: ## 安装 ```bash docmd add openapi # 或手动安装: npm install @docmd/plugin-openapi ``` 在您的配置中启用: ```javascript export default defineConfig({ plugins: { openapi: {} } }); ``` ## 使用方法 在任何 Markdown 页面中使用带 `openapi` 语言标签的围栏代码块嵌入 OpenAPI 规范: ````markdown ### 实时示例 ```openapi assets/docmd-api.json ``` ```` ### 渲染结果 ```openapi assets/docmd-api.json ``` 路径相对于您的 `src` 目录解析。支持 **JSON** 和 **YAML** 格式。YAML 需要安装 `js-yaml`: ```bash npm install js-yaml ``` ## 渲染内容 对于规范中的每个路径和 HTTP 方法,插件渲染: - **方法徽章** - 颜色编码(`GET`、`POST`、`PUT`、`PATCH`、`DELETE`) - **路径** - 完整端点路径 - **摘要和描述** - 来自操作对象 - **参数表格** - 名称、位置(`path`、`query`、`header`、`cookie`)、类型、必填标志、描述 - **请求体表格** - 带类型和默认值的模式属性 - **响应表格** - 带描述和响应模式类型的状态码 - **已弃用通知** - 标记为 `deprecated: true` 的操作内联标注 ::: callout tip "构建时渲染" 所有渲染在构建时发生。生成的页面是完全静态的 - - 无需 JavaScript 即可显示 API 文档,意味着快速页面加载和完整的搜索索引。 ::: ## 支持的 OpenAPI 功能 | 功能 | 支持 | | :--- | :--- | | OpenAPI 3.x | ✓ | | Swagger 2.x | ✗(请先转换为 3.x)| | JSON 格式 | ✓ | | YAML 格式 | ✓(需要 `js-yaml`)| | `$ref` 解析 | ✓(内部 `#/components/schemas/` 引用)| | `oneOf` / `anyOf` 类型 | ✓(显示为联合类型字符串)| | 嵌套模式表格 | ✓ | | `deprecated` 标志 | ✓ | | 外部 `$ref`(远程 URL)| ✗(仅本地引用)| ## 配置 OpenAPI 插件可以在您的 `docmd.config.js` 中配置: ```javascript export default defineConfig({ plugins: { openapi: { info: true, // 显示 API 标题和版本标题 download: true, // 在 UI 中提供“下载 JSON/YAML”链接 summaryOnly: false, // 仅显示摘要,隐藏参数/响应 allowRawHtml: false // 允许在描述中使用 HTML(请谨慎使用) } } }); ``` | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `info` | `boolean` | `true` | 显示规范中 `info` 对象的 API 标题、版本和描述。 | | `download` | `boolean` | `false` | 如果为 true,则在规范页眉添加下载/查看原始 JSON/YAML 文件的链接。**推荐用于 AI 辅助。** | | `summaryOnly` | `boolean` | `false` | 如果为 true,则仅渲染方法、路径和摘要。对大型 API 索引很有用。 | | `allowRawHtml` | `boolean` | `false` | 如果为 true,则不转义描述中的 HTML 标签。 | ## 页面级控制 通过 frontmatter 为特定页面禁用插件: ```markdown --- title: "内部说明" plugins: openapi: false --- ``` --- ## [PWA 与离线支持](https://docs.docmd.io/zh/07/plugins/pwa/) --- title: "PWA 与离线支持" description: "将文档转化为渐进式 Web 应用,支持离线缓存和移动端特性。" --- **PWA 插件**将你的文档转化为渐进式 Web 应用,支持离线缓存和移动端安装。它添加 Web Manifest 以支持移动端安装,并注册 Service Worker 处理智能离线缓存,确保技术文档即使在网络不稳定的环境下仍可访问。 ## 安装 ```bash docmd add pwa ``` ## 配置 可在 `docmd.config.js` 的 `plugins` 部分自定义 PWA 插件的品牌配置。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { pwa: { enabled: true, // Enabled by default if the plugin is loaded themeColor: '#1e293b', // The primary color of the mobile UI bgColor: '#ffffff', // Background color for the splash screen logo: '/assets/logo.png' // Fallback for app icons if not explicitly defined } } }); ``` ## 核心功能 ### 1. 离线缓存 插件会自动生成实现“旧数据优先更新”(Stale-While-Revalidate)缓存策略的 `service-worker.js` 文件。用户访问页面时,Service Worker 将: * 立即返回缓存版本以实现最大速度。 * 在后台从网络获取最新版本。 * 为下次访问更新缓存。 ### 2. 移动端安装 通过生成 `manifest.webmanifest` 并注入所需的 `<meta>` 标签,插件允许用户在 iOS 和 Android 上“添加到主屏幕”。你的文档将表现得像一个独立应用,拥有自己的启动画面和窗口框架。 ### 3. 智能资源解析 插件会通过查找项目的 `logo` 或 `favicon` 自动生成应用图标。如需更多控制,可提供明确的 `icons` 数组: ```javascript pwa: { icons: [ { src: '/icons/icon-192x192.png', sizes: '192x192', type: 'image/png' }, { src: '/icons/icon-512x512.png', sizes: '512x512', type: 'image/png' } ] } ``` ## 技术实现 Service Worker 将与单页应用(SPA)路由兼容地设计。它包含针对 Safari 严格安全策略(涉及重定向流)的安全防护逻辑,确保在所有现代浏览器上的稳定性。 ::: callout tip "开发模式" 在本地开发(`docmd dev`)中,Service Worker 通常会被禁用或绕过,以防止积极缓存干扰你的编辑。如需测试 PWA 功能,请使用 `docmd build` 执行生产构建,并使用静态托管服务输出目录。 ::: ### 完全移除 只需删除 `plugins` 中的 `pwa` 块即可。下次运行 `docmd build` 时不会生成新的 manifest。当用户访问站点时,docmd 的客户端引导程序(`docmd-main.js`)会检查 `<link rel="manifest">` 的存在。如果它不存在但 Service Worker 已注册,将自动**注销所有现存考古 Worker** 并清除缓存外壳 - - 无需用户操作。 ::: callout warning 上次构建产生的 `manifest.webmanifest` 和 `service-worker.js` 文件会在磁盘上持久存在,直到你使用 `docmd build` 或 `rm -rf site` 清除输出目录(默认为 `site/`)为止。这是文件系统残留物,不是活跃的 PWA。 ::: ## 配置参考 所有字段均为可选。默认值设计为零配置即用。 ```javascript export default { plugins: { pwa: { // --- 图标配置 --- // 优先级:pwa.logo > config.logo > config.favicon > (无图标) logo: 'assets/images/app-icon.png', // 相对于源文件夹的路径 // 或者完全手动控制: icons: [ { src: '/assets/images/icon-192.png', sizes: '192x192', type: 'image/png' }, { src: '/assets/images/icon-512.png', sizes: '512x512', type: 'image/png' } ], // --- Manifest 颜色 --- themeColor: '#1e293b', // 浏览器外框 / 顶栏高亮色 bgColor: '#ffffff', // 安装时启动画面背景色 // --- 完全禁用插件 --- enabled: false } } } ``` ### 图标解析优先级 docmd 按以下层级解析 PWA 图标: 1. `pwa.icons` - 手动数组,直接使用 2. `pwa.logo` - 单一图片路径,用于 192x192 和 512x512 条目 3. `config.logo` - 全局站点 logo 4. `config.favicon` - 全局 favicon 5. *(manifest 中未声明图标)* - 以上均未设置时 ## 本地测试 浏览器将 Service Worker 限制在 `https://` 或 `localhost`。使用: ```bash docmd dev ``` 打开 Chrome DevTools → **Application** → **Manifest** 和 **Service Workers**,即可实时查看已激活的注册信息。 Safari → **Develop** → **Service Workers** 面板同样适用。 --- ## [搜索插件 (Search Plugin)](https://docs.docmd.io/zh/07/plugins/search/) --- title: "搜索插件 (Search Plugin)" description: "使用 MiniSearch 为你的文档启用高速、离线优先的全文本搜索。" --- `@docmd/plugin-search` 插件为你的文档提供了强大的客户端搜索体验。它使用 [MiniSearch](external:https://github.com/lucaong/minisearch) 在构建过程中构建轻量级索引,允许用户在没有服务器端数据库的情况下即时查找技术信息。 ## 配置 在大多数 `docmd` 模板中,搜索是默认启用的。你可以通过 `layout` 配置来控制其可见性和位置。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ layout: { optionsMenu: { position: 'header', // 'header', 'sidebar-top', 'sidebar-bottom', 或 'menubar' components: { search: true // 设置为 false 以完全禁用搜索插件 } } } }); ``` ## 工作原理 ### 1. 索引 (构建时) 在 `docmd build` 过程中,搜索插件会遍历网站上的每一个页面。它会提取标题、副标题和正文文本,然后将这些数据编译成压缩的 `search-index.json` 文件。 * **深层链接**: 索引器会自动将每个标题(`#`、`##` 等)注册为可搜索目标。 * **相关性提升**: 标题被赋予最高权重,其次是副标题,最后是页面内容。 ### 2. 检索 (客户端) 当用户打开搜索弹窗(通常通过 `/` 或 `Ctrl+K`)时,浏览器会获取 `search-index.json` 文件。搜索是在本地执行的,采用模糊匹配(允许轻微的拼写错误)和即时前缀匹配。 ## 自定义搜索行为 虽然搜索插件旨在实现零配置的简洁性,但你可以通过在页面的 frontmatter 中使用 `noindex` 标志来从索引中排除特定页面: ```yaml --- title: "内部规范" noindex: true # 此页面将不会出现在搜索结果或站点地图中 --- ``` ## 技术实现 该插件在网站的 `<body>` 中注入一个轻量级的搜索弹窗。它完全符合无障碍标准 (ARIA 兼容),并支持键盘导航,以提供类似于原生应用的体验。 ::: callout tip "搜索分析" 如果你启用了 [分析插件](./analytics.md),读者使用的搜索关键词会被自动捕获并发送到你的分析提供商,从而让你深入了解哪些信息缺失或最难找到。 ::: 由于搜索完全在客户端进行,没有任何数据(甚至是按键)会被发送到服务器。这使得 `docmd` 成为隐私敏感行业(医疗、金融、安全)文档搜索的金标准。 ## 对比 许多文档生成器(如 Docusaurus)依赖于 **Algolia DocSearch**。虽然 Algolia 功能强大,但它也引入了摩擦: | 功能 | docmd 搜索 | Algolia / 外部方案 | | :--- | :--- | :--- | | **设置** | **零配置** (自动化) | 复杂 (API 密钥, CI/CD 爬取) | | **隐私** | **100% 私有** (客户端) | 数据发送到第三方服务器 | | **离线** | **支持** | 不支持 | | **成本** | **免费** | 免费层级限制或付费 | | **速度** | **即时** (内存中) | 较快 (取决于网络延迟) | --- ## [SEO 插件](https://docs.docmd.io/zh/07/plugins/seo/) --- title: "SEO 插件" description: "通过原生的元标签生成功能,为搜索引擎优化你的文档并控制 AI 爬虫的访问。" --- `@docmd/plugin-seo` 插件负责为每个页面生成高质量的元数据。它确保你的文档不仅能被搜索引擎上的人类读者发现,而且能被 AI 模型和社交媒体平台正确解读。 ## 全局配置 在 `docmd.config.js` 中配置全站的 SEO 默认设置。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ plugins: { seo: { defaultDescription: 'docmd 生态系统的全面文档。', aiBots: false, // 设置为 false 以阻止常见的 AI 爬虫 (GPTBot 等) openGraph: { defaultImage: '/assets/og-image.png' }, twitter: { siteUsername: '@docmd_io', cardType: 'summary_large_image' } } } }); ``` ## 页面级覆盖 你可以使用 frontmatter 为单个页面微调 SEO 设置。页面级设置始终优先于全局默认设置。 ```yaml --- title: "高级配置" description: "学习如何精通 docmd 的内部引擎。" noindex: true # 从所有搜索引擎中隐藏此特定页面 seo: keywords: ["docmd", "javascript", "ssg"] ogType: "article" canonicalUrl: "https://mysite.com/canonical-path" aiBots: true # 覆盖全局阻止设置,允许 AI 访问此页面 --- ``` ## 核心功能 ### 1. 智能描述降级 如果在 frontmatter 或全局配置中未提供描述,插件会自动提取页面正文的前 150 个字符作为 `<meta name="description">`,确保每个页面都有用于搜索摘要的基础元数据。 ### 2. AI 机器人治理 通过设置 `aiBots: false`,插件会专门针对主要的 AI 爬虫(包括 `GPTBot`、`Claude-Web` 和 `Google-Extended`)注入 `noindex` 指令。这允许你区分传统的搜索引擎索引与 LLM 训练会话。 ### 3. 规范化 URL 解析 插件会根据你的 `siteUrl` 自动生成 `<link rel="canonical">` 标签。它可以智能地处理目录索引,将 `guide/index.html` 转换为干净的 `/guide/` 规范 URL,以防止重复内容问题。 ### 4. 丰富的社交预览 对 Open Graph 和 Twitter Cards 的原生支持确保了指向你文档的链接在 X (Twitter)、LinkedIn 和 Discord 等平台上分享时显得非常专业。 ::: callout tip "搜索发现" 为了获得最佳的 SEO 效果,请确保在配置根目录中定义了 `siteUrl`。如果没有基准 URL,插件将无法生成绝对规范链接或 Open Graph 图像路径。 ::: ## 结构化数据 (LD+JSON) `docmd` 可以自动生成 [Article Schema](external:https://developers.google.com/search/docs/appearance/structured-data/article),以帮助搜索引擎显示丰富摘要。 ```yaml --- title: "如何构建 docmd 插件" seo: ldJson: true --- ``` ::: callout tip "结构化数据" 配置良好的 SEO 插件有助于 AI 驱动的搜索引擎(如 SearchGPT 或 Perplexity)准确总结你的网站。通过提供清晰的描述和阻止特定的机器人,你可以准确控制 AI 模型在网上感知和获取你的内容的方式。 ::: --- ## [Sitemap 插件](https://docs.docmd.io/zh/07/plugins/sitemap/) --- title: "Sitemap 插件" description: "自动生成符合标准的 sitemap.xml,提升搜索引擎发现效率。" --- `@docmd/plugin-sitemap` 插件在构建目录根目录自动生成 `sitemap.xml` 文件。该文件为 Google、Bing 等搜索引擎提供完整的站点架构地图,确保包括版本化文档中深层链接在内的所有页面都能被爬取和索引。 ## 配置 提供站点的 `siteUrl` 即可开启站点地图生成。可在 `plugins` 对象中自定义各章节的爬取权重。 ```javascript import { defineConfig } from '@docmd/core'; export default defineConfig({ siteUrl: 'https://docs.example.com', // Required for sitemap generation plugins: { sitemap: { defaultChangefreq: 'weekly', // 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never' defaultPriority: 0.8, // Default weight for standard pages rootPriority: 1.0 // Weight for the homepage (index.md) } } }); ``` ## 页面级控制 可使用 frontmatter 覆盖特定页面的站点地图行为。 ```yaml --- title: "归档页面" priority: 0.3 # 旧版内容的较低权重 changefreq: "monthly" # 提示爬虫此页面变更频率较低 lastmod: "2024-03-15" # 明确设置最后修改日期 sitemap: false # 将此页面从 sitemap.xml 中排除 --- ``` ## 核心功能 ### 1. 自动 URL 构建 插件智能地将页面路径解析为规范的公开 URL。它自动处理目录索引,确保 `guide/index.html` 列为 `https://yoursite.com/guide/`,以维护简洁的 URL 结构。 ### 2. 版本化发现 如果你的项目使用[版本控制](../configuration/versioning),站点地图插件会自动включать所有版本的所有页面(如 `/v1/getting-started`、`/v2/getting-started`),无需手动配置即可让搜索引擎发现你的归档文档。 ### 3. 智能排除 在 frontmatter 中标记 `noindex: true` 或 `sitemap: false` 的页面会自动从生成的 `sitemap.xml` 中排除,让你精细控制呈现给搜索引擎的内容。 ::: callout tip "验证" 构建站点后,通常可在 `your-output-dir/sitemap.xml` 找到站点地图。大多数搜索引擎控制台允许你直接提交此文件以加速索引。 ::: --- ## [评论线程插件 (Threads Plugin)](https://docs.docmd.io/zh/07/plugins/threads/) --- title: "评论线程插件 (Threads Plugin)" description: "为你的文档添加行内讨论线程 - - 直接存储在你的 markdown 文件中。" --- **Threads 插件** 为你的文档带来协作式的行内评论功能。选择页面上的任何文本,留下评论,开始讨论 - - 所有内容都直接存储在你的 markdown 源文件中,无需任何数据库。 原作者:[@svallory](external:https://github.com/svallory) ::: callout info "Alpha 版本" 此插件处于 alpha 阶段。API 和存储格式是稳定的,但 UI 仍处于活跃开发中。 ::: ## 安装设置 ```bash docmd add threads ``` ```javascript plugins: { threads: {} } ``` ### 配置选项 | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | 当为 `true` 时,线程会分组在页面底部。当为 `false` (默认) 时,线程会定位在所选文本旁边的行内位置。 | ```javascript // 将线程保留在页面底部而不是行内 plugins: { threads: { sidebar: true } } ``` ## 工作原理 1. 在 `docmd dev` 期间,在任何文档页面上 **选择文本** 2. 出现一个 **评论弹出层** - - 写下你的评论并提交 3. 所选文本会被 **高亮显示** 并带有线程标记 4. 线程以 `::: threads` 块的形式存储在 markdown 文件的底部 5. **无需数据库** - - 你的 markdown 文件就是事实来源 ## 预览 这是实时页面上线程的样子。带有讨论的文本会被 <span class="threads-preview-highlight">像这样高亮显示</span>,线程卡片会显示在下方。 <div class="threads-preview-card"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 2d ago</div> <div class="threads-preview-body">这一部分可以使用图表来解释架构。你觉得呢?</div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">B</div> <div class="threads-preview-meta"><strong>Bob</strong> · 1d ago</div> <div class="threads-preview-body">好主意 - - 我会添加一个 Mermaid 流程图。这里可以使用 <code>sequenceDiagram</code> 吗?</div> <div class="threads-preview-reactions"> <div class="threads-preview-reaction">👍 <span>2</span></div> <div class="threads-preview-reaction">🚀 <span>1</span></div> </div> </div> <div class="threads-preview-comment threads-preview-reply"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 12h ago</div> <div class="threads-preview-body">太棒了。一个简单的流程图会很理想。</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ 新评论</div> </div> </div> 这是 <span class="threads-preview-highlight-blue">第二种不同颜色的高亮</span> - - 线程会自动循环使用一系列颜色。 <div class="threads-preview-card threads-preview-card-blue"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">C</div> <div class="threads-preview-meta"><strong>Charlie</strong> · 3d ago</div> <div class="threads-preview-body">我们应该在这里提到向后兼容性吗?</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ 新评论</div> </div> </div> 已解决的线程显示为变暗: <div class="threads-preview-card threads-preview-card-resolved"> <div class="threads-preview-comment"> <div class="threads-preview-avatar">A</div> <div class="threads-preview-meta"><strong>Alice</strong> · 5d ago  <span class="threads-preview-resolved-badge">✓ 已解决</span></div> <div class="threads-preview-body">修复了配置示例中的拼写错误。</div> </div> <div class="threads-preview-footer"> <div class="threads-preview-footer-btn">+ 新评论</div> </div> </div> 页面右下角会出现一个悬浮的 **讨论按钮** <span class="threads-preview-fab">💬<span class="threads-preview-fab-badge">2</span></span>,显示未解决线程的数量。点击它可跳转到页面上的第一个线程。 ## 存储格式 线程使用 docmd 的容器语法嵌入在你的 markdown 中: ```markdown # 我的文档页面 一些内容带有 ==高亮文本=={t-a1b2c3d4},该文本关联了一个线程。 ::: threads ::: thread t-a1b2c3d4 ::: comment c-e5f6a7b8 "Alice" "2026-04-09" 这段文本需要澄清。 ::: ::: comment c-d9e0f1a2 "Bob" "2026-04-09" reply-to c-e5f6a7b8 更新了 - - 这样可以吗? ::: reactions - 👍 Alice ::: ::: ::: ::: ``` `==文本=={threadId}` 语法将文档正文中的高亮文本链接到特定的线程。 ## 特性 | 特性 | 描述 | | :--- | :--- | | **文本选择** | 选择任何文本来启动新线程 | | **回复** | 每个线程内嵌套的回复链 | | **回应** | 对单个评论的表情回应 | | **编辑 / 删除** | 修改或移除你的评论 | | **解决** | 将线程标记为已解决,带有作者和时间戳 | | **作者资料** | 基于 Git 的作者检测,支持 Gravatar | | **高亮标记** | 页面上的视觉指示器,显示线程锚定的位置 | | **悬浮按钮** | 带有未解决线程计数的快速访问 FAB | | **滚动保留** | 添加评论后页面保持在原处 | ## Actions API Threads 插件通过 WebSocket RPC 系统公开以下操作。这些操作可以从浏览器插件中使用 `docmd.call()` 调用: | 操作 | 描述 | | :--- | :--- | | `threads:get-threads` | 解析并返回文件中的所有线程 | | `threads:add-thread` | 创建一个带首条评论的新线程 | | `threads:add-comment` | 向现有线程添加评论 | | `threads:edit-comment` | 编辑现有评论的正文 | | `threads:delete-comment` | 从线程中移除评论 | | `threads:delete-thread` | 移除整个线程并清理高亮 | | `threads:resolve-thread` | 切换已解决/未解决状态 | | `threads:toggle-reaction` | 切换评论上的表情回应 | | `threads:get-authors` | 读取作者资料映射表 | | `threads:upsert-author` | 创建或更新作者资料 | ## 作者资料 作者信息存储在 `<docsRoot>/.threads/authors.json` 中: ```json { "alice@example.com": { "name": "Alice", "avatarUrl": "https://gravatar.com/avatar/..." } } ``` 在开发过程中,插件会自动检测你的 git 用户名和电子邮件以进行作者识别。 ::: callout tip "版本控制友好" 由于线程存储在你的 markdown 文件中,它们会自动随 git 进行版本控制。可以在 PR 中审阅评论,跟踪讨论历史,并通过你现有的工作流进行协作。 ::: --- ## [插件机制与用法 (Plugin Mechanism & Usage)](https://docs.docmd.io/zh/07/plugins/usage/) --- title: "插件机制与用法 (Plugin Mechanism & Usage)" description: "了解 docmd 的生命周期钩子、插件安全机制以及如何扩展引擎的功能。" --- `docmd` 采用可插拔架构。几乎所有核心功能(从搜索到 SEO 再到实时预览)都是作为插件实现的。这种设计确保了引擎保持轻量,同时允许开发者根据具体项目需求选择性地开启功能。 ## 插件概览 | 插件 | 功能 | | :--- | :--- | | **[搜索 (Search)](search.md)** | 提供高性能、离线优先的全文本搜索。 | | **[SEO](seo.md)** | 自动生成元标签、Sitemap 并控制 AI 爬虫访问。 | | **[Mermaid](mermaid.md)** | 渲染流程图、序列图和甘特图。 | | **[LLMs](llms.md)** | 生成机器可读的全量文档流以供 AI 训练或搜索。 | | **[实时预览 (Live)](../content/live-preview.md)** | 为自定义编辑器提供在浏览器中运行的渲染引擎。 | ## 生命周期钩子 插件可以通过连接到以下生命周期钩子来介入构建过程: | 钩子 | 描述 | | :--- | :--- | | `onInit(ctx)` | 在引擎启动且配置加载后立即运行 | | `onPostBuild(ctx)` | 在所有 HTML 文件生成后运行逻辑 | | `translations(localeId)` | 返回语言环境翻译后的 UI 字符串 | | `actions` | 可从浏览器通过 WebSocket RPC 调用的服务器端处理程序 | | `events` | 浏览器推送事件的“发后即忘”式处理程序 | ## 插件安全 插件系统提供内置的安全保证: - **验证**: 插件可以声明一个包含 `name`、`version` 和 `capabilities` 的插件描述符。无效的描述符在加载时会被拒绝。 - **隔离**: 每次钩子调用都包裹在 try/catch 边界内。一个损坏的插件不会导致构建崩溃或影响其他插件。 - **能力强制**: 声明了能力的插件只能注册其已明确声明的钩子。未声明的钩子将被跳过并发出警告。 有关完整的 API 参考,请参阅 [开发插件](building-plugins.md)。 ::: callout tip "针对 AI 的透明架构 :robot:" 插件架构旨在具有 **确定性**。插件注入的每个元标签和脚本都是可追溯的,这允许 AI 代理(和人类开发人员)准确了解网站的行为,而不会产生隐藏的副作用。 ::: --- ## [发布说明 - 0.7.0](https://docs.docmd.io/zh/07/release-notes/0-7-0/) --- title: "发布说明 - 0.7.0" description: "一流的国际化支持、零配置核心插件与真正的零配置默认值。" --- `docmd` 0.7.0 是一次重大跨越 - - 带来了原生多语言支持(i18n)、内置翻译系统,以及所有核心插件开箱即用的真正零配置默认值。 ## ✨ 亮点 ### 🌍 国际化(i18n) docmd 现已提供一流的 i18n 支持。配置多个语言区域后,docmd 将为每个语言区域构建完整的本地化站点 - - 包含语言优先 URL(`/hi/`、`/zh/`)、翻译后的 UI 字符串和自动语言检测。 每个语言区域独占一个子目录(包括默认语言),让源目录保持整洁,结构一目了然: ``` docs/ en/ ← 默认语言区域(渲染至 /) hi/ ← 印地语(渲染至 /hi/) zh/ ← 中文(渲染至 /zh/) ``` 语言区域 ID、文件夹名称和默认语言完全由你决定 - - `en`、`hi`、`fr`、`de` 或你偏好的任意标识符均可使用。 ```js // docmd.config.js export default { i18n: { default: 'en', locales: [ { id: 'en', label: 'English' }, { id: 'hi', label: 'हिन्दी' }, { id: 'zh', label: '中文' }, ] } } ``` 此版本还支持**跨版本自动生成的各语言区域搜索索引**,以及 Search 和 Threads 等官方插件的翻译 UI 组件! ### 🚀 零配置核心插件 `0.7.0` 版全面拥抱零配置理念。所有官方核心插件(`search`、`seo`、`sitemap`、`analytics`、`llms`、`mermaid`)现已**默认自动启用**,无需再手动在 `plugins` 数组中声明即可使用。 > **注意:** `pwa` 插件自 0.7.0 起已变更为**可选**插件。其 Service Worker 的激进缓存策略导致用户在重新构建后看到过期内容。如需离线支持,请使用 `docmd add pwa` 显式安装。 如需禁用某个核心插件,只需将其标记为 `false`: ```js export default { plugins: { search: false // 禁用自动启用的 search 插件 } } ``` ## 📝 完整更新日志 ### 🌍 i18n 架构 - **干净的语言区域目录**:每个语言区域(包括默认语言)均存放在 `src` 下独立的子目录中,不再将语言文件夹与内容文件夹混合。 - **语言优先 URL 生成**:构建循环现在会为每个已配置语言区域生成嵌套目录。 - **逐文件回退**:非默认语言区域在翻译缺失时自动继承默认语言区域的页面,并显示自动警告标注。 - **各语言区域独立导航**:每个语言区域目录可拥有自己的 `navigation.json`,缺失时回退到默认语言区域的导航。 - **版本控制 + i18n**:不含语言区域目录的旧版本仅以默认语言渲染。在任意旧版本中添加语言区域子目录,即可为其启用翻译。 - **翻译 UI 字符串**:原生翻译系统覆盖所有 UI 元素和模板。处理程序解析至 JSON 语言文件(`en.json`、`hi.json`、`zh.json`),所有模板字符串均可通过快速 `t('key')` 助手访问。 - **插件 i18n API**:插件现支持新增的 `translations(localeId)` 钩子及客户端字符串的 `i18n/` 目录约定。 - **全局搜索本地化**:本地 MiniSearch 索引现按语言区域构建,动态根据上下文渲染版本标记,并优雅提供本地化搜索结果。 - **零成本回退**:未配置 `i18n` 块的站点构建结果与 0.7.0 之前完全一致 - - 路径和输出均无任何变化。 - **字符串模式(`stringMode: true`)**:一种专为 noStyle 页面设计的 i18n 模式 - - 从单一源文件生成多语言 HTML。在 HTML 中添加 `data-i18n` 属性,将翻译文件放置在 `assets/i18n/{locale}.json`,docmd 即可在构建时克隆渲染输出并进行**服务端字符串替换**。生成完全翻译的、可被搜索引擎索引的页面,输出至 `/{locale}/` 路径。支持 `data-i18n`(textContent)、`data-i18n-html`(innerHTML)和 `data-i18n-{attr}`(属性值)。翻译文件缺失时优雅回退至默认语言。仅适用于 noStyle/HTML 页面 - - Markdown 文档应使用目录模式。 - **noStyle 页面客户端 i18n**:启用 i18n 配置后,自动注入轻量级 `docmd-i18n-strings.js` 模块。提供运行时 `switchLocale()` API、面向 SPA 的 `inPlace` 模式,以及用于自定义语言切换器的 `docmd:i18n-applied` 事件。 ### 🔌 插件系统与引擎 - **核心插件自动激活**:零配置默认值自动提供完整的 docmd 套件,无配置开销。 - **资源生成优化**:重构资源流水线,确保静态 CSS、JS 和全局配置仅被构建一次至根目录,无论启用了多少个语言区域或版本。 ### 🎨 界面与容器 - **容器 `icon:` 参数**:Callout、Card、Collapsible 和 Button 现支持 `icon:` 参数,可内联渲染 Lucide 图标并与标题对齐。图标已通过 Flexbox 垂直居中并正确缩放。 ```md ::: card "Setup" icon:rocket ::: button "Get Started" /start icon:arrow-right ``` - **`titleAppend` frontmatter 选项**:页面现可在 frontmatter 中设置 `titleAppend: false`,以禁止在 `<title>` 标签中自动追加" - 网站标题"后缀。适用于主页和落地页。 - **胶囊样式版本与语言切换器**:侧边栏中的版本下拉和语言切换现在渲染为紧凑胶囊按钮,并排在同一行,节省纵向空间。共享 CSS 类确保两个组件尺寸一致。 - **语言切换器版本感知**:浏览无翻译版本的旧版本时,非默认语言区域在语言切换器中显示为不可用(含"N/A"标记),防止导航到不存在的页面。 - **可翻译的"(最新)"标记**:当前版本现在在版本下拉中显示自动生成的、可翻译的"最新"标记,不再在配置标签中硬编码 - - 使用内置翻译系统。 - **搜索结果版本标记**:搜索结果现在在结果标题右侧显示彩色胶囊版本标记。每个版本在构建时获得确定性颜色,便于视觉识别。 - **响应式语言胶囊**:当版本和语言胶囊同时存在时,语言标签在标准侧边栏中自动隐藏,仅显示地球图标;在宽屏模式下展开显示标签。 - **开发服务器配置热重载**:`docmd.config.js` 的修改现在在 `docmd dev` 期间触发完整重新构建,无需手动重启。文件监视器在所有平台上均可正确检测配置文件变更。 ## 🐛 问题修复 - **版本控制 + i18n 冲突**:不含语言区域子目录的旧版本目录被错误地复制到所有语言区域。现已修正,仅为默认语言区域渲染 - - 非默认语言区域跳过无翻译的版本。 - **旧版本中的幽灵语言页面**:旧版本目录中的语言区域子目录(如 `docs-v1/hi/`)在默认语言区域构建时被渲染为常规内容页,产生重复 URL。已通过在扫描时过滤已知语言区域目录名修复。 - **导航警告误报**:即使 `navigation.json` 存在于语言区域或版本目录中,也会显示"未找到导航设置"消息。现已修复,当任何语言区域或版本目录中存在导航时,不再显示此警告。 - **自动导航扫描错误目录**:启用 i18n 时,自动导航构建器扫描的是源根目录(仅含语言区域目录),导致从文件夹名称生成错误的导航。现已修正为扫描默认语言区域目录。 - **`<title>` 标签缺少网站名称**:没有显式标题的页面产生空标题标签。模板现在自动使用破折号分隔符追加网站标题(`页面 - 网站`),主页仅显示网站标题。 - **旧版本语言切换器 URL 重复**:浏览非当前版本时切换语言会产生版本前缀重复的 URL(如 `/zh/06/06/page`)。已通过在重建语言区域 URL 前剥离版本前缀修复。 ## 🧪 质量保证 0.7.0 通过了涵盖 **25 个独立场景**、**85 项独立断言**的完整暴力测试套件 - - 全部通过。每项主要功能均经过单独测试和组合测试: ::: collapsible "查看完整测试覆盖" | # | 场景 | 断言数 | |:--|:---------|:-----------| | 1 | 零配置(无配置文件) | 5 | | 2 | 零配置 + 嵌套目录 | 4 | | 3 | 独立 i18n(非英文默认语言) | 5 | | 4 | 独立版本控制(无 i18n) | 5 | | 5 | i18n + 版本控制组合 | 6 | | 6 | 含部分翻译的旧版本 | 4 | | 7 | 语言区域目录缺失(优雅跳过) | 3 | | 8 | 导航解析优先级 | 2 | | 9 | Frontmatter 解析 | 3 | | 10 | 容器(callout、tabs、steps、hero) | 5 | | 11 | 代码块(JS、Python) | 3 | | 12 | 自定义 CSS/JS 注入 | 3 | | 13 | 编辑链接 | 3 | | 14 | 无样式页面 | 3 | | 15 | 搜索索引生成 | 3 | | 16 | Sitemap 生成 | 3 | | 17 | EJS 内容页 | 3 | | 18 | README.md 作为 index 回退 | 4 | | 19 | `.markdown` 文件扩展名 | 3 | | 20 | 深层嵌套结构(4+ 层) | 2 | | 21 | 零配置自动导航准确性 | 3 | | 22 | 标题标签自动追加 | 2 | | 23 | Open Graph 元标签 | 3 | | 24 | 重定向 | 3 | | 25 | 页面级布局覆盖 | 3 | 所有 13 项内部保障检查同样通过。暴力测试脚本包含在 `scripts/brute-test.js` 中,任何人均可在本地运行。 ::: ## ⚠️ 重大变更 - **第三方插件简写名称不再解析** - - 如果你正在导入第三方插件,必须使用完整包名。(`search`、`threads` 等名称严格保留给 `@docmd/plugin-*`)。 - **`pnpm onboard` 已移除** - - `onboard` 脚本已合并到 `pnpm prep`。使用 `pnpm prep` 进行完整环境设置,使用 `pnpm prep --link`(或 `pnpm verify --link`)同时全局链接 `docmd`。 ## 迁移指南 运行 `npm install docmd@latest` 升级。然后: 1. 如果你以默认设置使用核心插件,**可以从** `plugins` 数组中**移除**它们 - - 它们现已自动启用! 2. 如果你通过简写名称使用第三方插件,请将其更新为完整包名。 完整操作步骤请参阅[入门指南 - 安装](../getting-started/installation)。 --- ## [发布说明 - 0.7.1](https://docs.docmd.io/zh/07/release-notes/0-7-1/) --- title: "发布说明 - 0.7.1" description: "专用插件 API 包、插件描述符、隔离机制与功能执行。" --- `docmd` 0.7.1 引入了一项重大架构改进 - - 插件系统已提取到独立的 `@docmd/api` 包中,为生态系统带来了插件描述符、崩溃隔离和功能执行机制。 ## ✨ 亮点 ### 📦 `@docmd/api` - 专用插件包 插件 API 接口 - - 钩子注册、WebSocket RPC 调度和源码编辑工具 - - 现已拥有独立的专用包:`@docmd/api`。 ```bash npm install @docmd/api ``` 这将插件生态系统与构建引擎解耦,允许插件作者依赖轻量的 API 合约,而无需引入整个 `@docmd/core` 包。 > **向后兼容:** `@docmd/api` 的所有导出均从 `@docmd/core` 重新导出。使用 `@docmd/core` 导入的现有代码无需修改即可继续使用。 ### 🛡️ 插件描述符 插件现可导出 `plugin` 描述符,声明其身份和功能: ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` 引擎在加载时验证描述符 - - 无效的名称、版本或未知功能会被立即拒绝(官方插件)或发出警告(第三方包)。 > **迁移说明:** 描述符在 0.7.x 中为**可选**。未提供描述符的插件会收到软弃用警告。这将在 **0.8.0 中成为硬性要求**。 ### 🔒 插件隔离 每个钩子调用现在都包裹在 try/catch 边界中。故障插件不会导致构建崩溃或影响其他插件。错误会被记录并收集到构建结束时显示的摘要中: ``` ⚠️ 2 plugin error(s) occurred (build completed) ``` ### 🔑 功能执行 声明了功能的插件只能注册与其声明匹配的钩子。如果插件导出了未声明的钩子,引擎会跳过它并输出警告: ``` Plugin "analytics" exports markdownSetup but didn't declare "markdown" capability - skipped ``` | 功能 | 允许的钩子 | 阶段 | | :--- | :--- | :--- | | `init` | `onConfigResolved` | 初始化 | | `markdown` | `markdownSetup` | 设置 | | `head` | `generateMetaTags`、`generateScripts` (head) | 渲染 | | `body` | `generateScripts` (body) | 渲染 | | `build` | `onBeforeParse`、`onAfterParse`、`onPageReady` | 构建 | | `post-build` | `onPostBuild` | 构建后 | | `dev` | `onDevServerReady` | 开发服务器 | | `assets` | `getAssets` | 输出 | | `actions` | `actions` | 交互 | | `events` | `events` | 交互 | | `translations` | `translations` | 国际化 | 没有描述符的旧版插件仍可完全访问所有钩子。 ## 📝 完整更新日志 ### 📦 架构 - **`@docmd/api` 包**:将 `loadPlugins`、`createActionDispatcher`、`createSourceTools` 及所有插件/RPC 类型提取到 `packages/api/`。 - **`@docmd/core` 重新导出**:所有迁移的 API 符号均从 `@docmd/core/src/index.ts` 重新导出,实现无缝向后兼容。 - **死代码清理**:迁移完成后,从 `@docmd/core` 删除了原始的 `plugin-loader.ts`、`action-dispatcher.ts`、`source-tools.ts` 和 `types.ts`。 ### 🔌 插件系统 - **插件描述符**(`plugin` 导出):名称、版本和功能声明。 - **验证(§1)**:对 `@docmd/plugin-*` 包严格执行;对第三方插件发出软警告。 - **隔离(§2)**:所有同步钩子使用 `safeCall()` 包裹;`onPostBuild` 使用异步 try/catch。 - **功能执行(§3)**:钩子注册受声明功能限制。 - **扩展生命周期钩子(§4)**:引入 `onConfigResolved`、`onDevServerReady`、`onBeforeParse`、`onAfterParse` 和 `onPageReady`,处理复杂的站点集成。 - **错误摘要**:插件错误被收集并在构建结束时以计数形式显示,不会中断构建过程。 ### 🐛 问题修复 - **404 页面原始键名显示**:修复了翻译加载失败时 404 页面可能显示 `errorCode404` 纯文本的问题。错误代码现已硬编码为 `404`。 - **i18n `stringMode` 脚本泄漏**:修复了 `no-style.ejs` 在 `stringMode` 激活时注入 `docmd-i18n-strings.js` 运行时的问题。客户端语言区域运行时现在在字符串模式下被正确禁止。 - **pnpm 工作区中的插件解析**:修复了从 `@docmd/api` 调用时 `loadPlugins` 无法定位 `@docmd/plugin-*` 包的问题 - - 该函数现接受调用方传入的 `resolvePaths` 以支持 pnpm 的严格 `node_modules` 布局。 ## ⚠️ 重大变更 ### 插件 API 导入路径(推荐迁移) 插件 API 的规范包现为 `@docmd/api`。虽然 `@docmd/core` 重新导出了一切以保持向后兼容,**但建议插件作者更新其导入**: ```diff -import { createActionDispatcher, createSourceTools } from '@docmd/core'; +import { createActionDispatcher, createSourceTools } from '@docmd/api'; ``` ```diff -import type { PluginModule, ActionContext, SourceTools } from '@docmd/core'; +import type { PluginModule, ActionContext, SourceTools, PluginDescriptor, Capability } from '@docmd/api'; ``` > **最终用户无需操作。** 这仅影响直接导入 API 工具函数的插件开发者。`@docmd/core` 的重新导出将无限期保留。 ### Threads 插件对等依赖 `@docmd/plugin-threads` 包现在以 `@docmd/api` 而非 `@docmd/core` 作为对等依赖。如果你手动安装 Threads(而非通过 `docmd add threads`),请确保依赖树中有 `@docmd/api`。 ## 迁移指南 **最终用户**:无需任何操作。`npm install docmd@latest` 即可。 **插件作者**: 1. **添加插件描述符**到默认导出中(目前可选,0.8.0 将成为必需项): ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, // ... 钩子 }; ``` 2. **更新导入**:将 `createActionDispatcher`、`createSourceTools`、`loadPlugins` 及所有类型导出的导入源从 `@docmd/core` 改为 `@docmd/api`。 3. **更新对等依赖**:如果你的插件使用 RPC 或源码编辑 API,请在 `package.json` 中将对等依赖从 `@docmd/core` 改为 `@docmd/api`。 详见[构建插件](../../plugins/building-plugins)获取完整的更新后 API 参考。 --- ## [发布说明 - 0.7.2](https://docs.docmd.io/zh/07/release-notes/0-7-2/) --- title: "发布说明 - 0.7.2" description: "引入配置感知的 'docmd deploy' 命令、生产级安全头,以及 7 大支柱 Failsafe 验证引擎。" --- `docmd` 0.7.2 版本引入了 **`docmd deploy`** 命令 - - 一个配置感知的部署脚手架工具,它会读取你的项目配置并生成针对项目量身定制的生产级服务器配置文件。 没有任何其他文档工具能做到这一点。Docusaurus、VitePress、MkDocs - - 它们都需要你从零开始手动编写 Dockerfile 和服务器配置。`docmd` 读取你的 `docmd.config.js`(或零配置默认值),生成的文件即可直接上线。 ## ✨ `docmd deploy` - 配置感知部署 一条命令即可生成为你项目量身定制的生产级部署文件: ```bash docmd deploy --docker # Dockerfile + .dockerignore docmd deploy --nginx # nginx.conf docmd deploy --caddy # Caddyfile ``` ### 智能之处 deploy 命令会在生成前**读取你的配置**,提取以下信息: - **项目标题** - 作为注释头写入每个生成的文件中 - **输出目录** (`out`) - 用于 Dockerfile 的 `COPY` 路径、Nginx/Caddy 的 `root` 指令,取代硬编码的值 - **站点 URL** (`url`) - 提取的主机名注入为 Nginx 的 `server_name` 或 Caddy 的站点地址 - **SPA 模式** (`layout.spa`) - 仅在 SPA 模式激活时才生成 `try_files` SPA 路由回退 - **配置文件路径** - 如果使用非默认配置文件名,Dockerfile 构建步骤会运行 `docmd build --config your-config.js` 没有 `docmd.config.js`?命令依然可以正常工作 - - 它会使用与 `docmd dev` 和 `docmd build` 相同的零配置默认值。 ### 始终同步 每次运行都会重新生成部署文件以匹配你当前的配置。修改了 `url` 或 `out` 目录?只需重新运行 `docmd deploy --nginx`。你的配置始终反映项目的最新状态。 ### 生成文件的质量 - **Docker**:多阶段构建,具备 `package.json` 层缓存和精确的 `@docmd/core` 版本锁定,确保可复现构建 - **Nginx**:安全头(`X-Content-Type-Options`、`X-Frame-Options`)、GZIP 压缩、不可变资产缓存 - **Caddy**:支持 HTTPS 的自动寻址、安全头、SPA 路由、静态资产缓存 ## 🛡️ 7 大支柱 Failsafe 验证 内部验证引擎已重构为 **7 个逻辑稳定性支柱**,包含全新的**动态完整性引擎**,能即时捕捉整个 Monorepo 中的版本不匹配问题。 ## 🌍 全球生态系统扩展 本次发布包含重大的本地化更新: - **原生语言支持**:核心引擎新增了**德语、西班牙语、日语和法语**的内置 UI 翻译 - - 这些语言开箱即用,适用于所有 UI 组件。 - **德语文档上线**:完整的文档套件现已支持德语 (`/de/`)。 ## 📝 完整更新日志 ### 🚀 功能与增强 - **新命令**:`docmd deploy`,支持 `--docker`、`--nginx`、`--caddy` 目标。 - **配置感知脚手架**:deploy 命令读取 `docmd.config.js`(或零配置默认值),用项目标题、输出目录、主机名、SPA 模式和配置路径定制生成文件。 - **始终最新的配置**:部署文件在每次运行时重新生成,与配置变更保持同步。 - **Docker 脚手架**:多阶段 Dockerfile,具备 `package.json` 层缓存和版本锁定的 `@docmd/core`。 - **Web 服务器脚手架**:强化的 Nginx 和 Caddy 模板,包含安全头、GZIP 和智能 404/SPA 路由。 - **统一配置标签**:所有内部模块(SEO、站点地图、LLMS、PWA、部署器、生成器)现在统一使用现代配置键(`config.title`、`config.url`、`config.out`、`config.src`),不再使用分散的旧版回退。默认值在 `normalizeConfig` 中统一定义 - - 唯一的事实来源。 - **Failsafe**:验证逻辑合并为更快、更专业的 7 阶段流水线。 - **版本控制**:全新的完整性引擎自动标记过时的内部工作区引用。 - **SEO 插件**:完全遵循 `titleAppend` frontmatter 属性用于社交媒体(OG/Twitter)元数据。 - **原生支持**:核心引擎新增**德语、西班牙语、日语和法语**的内置 UI 翻译。 - **本地化**:新增完整的**德语**文档翻译,优化**中文**文档翻译。 ### 🐛 问题修复 - **Deploy CLI**:修复通过 `pnpm` 代理脚本使用 `--cwd` 时的参数解析问题。 - **Deploy UX**:未知参数现在显示有用的使用摘要,而不是带有退出码 1 的原始错误。 - **Caddy 配置**:修正了 Caddyfile 兼容性的 Cache-Control 头部语法。 - **Bump 脚本**:修复了 `scripts/bump.js` 中的正则 `lastIndex` 漏洞。 - **CLI 安全**:为所有部署命令入口点添加了适当的异步错误处理。 - **在线编辑器**:修复移动端溢出问题和模板切换状态追踪。 ## 迁移指南 **最终用户**:无破坏性更改。更新后尝试 `docmd deploy`,生成针对你项目定制的部署配置。 **插件作者**:无需任何操作。 --- ## [发布说明 - 0.7.3](https://docs.docmd.io/zh/07/release-notes/0-7-3/) --- title: "发布说明 - 0.7.3" description: "引入代码块标题、多服务迁移引擎、带有 Lucide 图标的交互式 Mermaid 图表,以及一流的 Bun 生态系统支持。" --- `docmd` 0.7.3 版本带来了重要的新内容创作功能、一个为切换平台的用户准备的生产级迁移引擎,以及对 Mermaid 图表渲染管线的全面重构。我们还统一了所有交互式容器的图标渲染逻辑,并引入了深度上下文感知的翻页逻辑。 ## ✨ Highlights ### 🚀 多服务迁移引擎 我们将旧版的内部配置迁移工具替换为了一个全功能的**迁移引擎**,它可以帮助您通过单条命令将整个文档项目从竞争平台无缝迁移到 `docmd`。 ### 支持的数据源 | 源平台 | 迁移命令 | 自动检测的配置 | |---|---|---| | **Docusaurus** | `npx @docmd/core migrate --docusaurus` | `docusaurus.config.js` / `.ts` | | **MkDocs** | `npx @docmd/core migrate --mkdocs` | `mkdocs.yml` | | **VitePress** | `npx @docmd/core migrate --vitepress` | `.vitepress/config.[js\|ts\|mjs]` | | **Astro Starlight** | `npx @docmd/core migrate --starlight` | `astro.config.mjs` / `.ts` | 每次迁移将自动执行: 1. 检测源项目的配置文件并提取站点标题。 2. 将所有现有文件安全地移动到 `<source>-backup/` 目录。 3. 将文档源文件(如 `docs/`,`src/content/docs/` 等)复制到 `docmd` 标准的 `docs/` 结构中。 4. 生成一个带有合理默认值的、随时可用的 `docmd.config.js`。 ```bash cd my-docusaurus-site npx @docmd/core migrate --docusaurus npx @docmd/core dev ``` > **注意:** 由于各个文档平台处理诸如侧边栏、版本控制和国际化(i18n)等复杂逻辑的方式各不相同(通常使用专有代码或 API),为了避免破坏您的构建,`docmd` 不会尝试自动翻译这些配置。迁移引擎专注于安全移动您的 Markdown 内容和静态资源,而将 `navigation.json` 和 `localisation` 的设置交给您通过 `docmd` 原生的、简单直观的 API 进行手动配置。 请阅读我们全新的综合 [迁移指南](../migration/overview.md) ,以了解具体迁移了哪些内容,以及将以前工具的配置映射到 `docmd` 所需的简单步骤。 ### 📝 代码块标题 您现在可以通过在语言标识符后面添加引号字符串,为任何代码块添加描述性的**文件名或标题**。这会在代码上方渲染出一个干净的、Mintlify 风格的标题栏。 ````markdown ```javascript "config.js" export default { title: "My Site" }; ``` ```` 该标题被渲染为语义标签(而不是标题节点),因此它永远不会出现在目录中或干扰您的页面结构。 ### 📊 交互式 Mermaid 图表 我们彻底重构了 `docmd` 渲染 Mermaid 图表的方式,将静态的 SVG 转变为深度交互的视觉元素。 - **智能缩放**:图表首先以完整的 Mermaid 质量渲染,然后使用 CSS transforms 智能缩放以适应内容宽度,从而完美保留所有的标签和连线位置。 - **平移与拖拽**:原生支持通过拖拽、或者使用方向控件在大型图表上平移。 - **缩放控件**:悬停时会出现专门的放大/缩小按钮,以便于精确检查细节。 - **全屏模式**:原生的全屏切换功能,允许用户全屏展开复杂的架构图,获得无干扰的视觉体验。 - **Lucide 图标集成**:Lucide 图标库已被直接注册到 Mermaid 引擎内部(`icon:icon-name`),使您可以使用与侧边栏和标签页相同的图标库来构建丰富的架构图。 - **暗黑模式**:图表及其容器现在能在暗黑模式下正确渲染,具备正确主题化的边框和背景。 ### ✨ 通用容器图标 我们重构了核心解析器,采用了共享的**容器完整性引擎**。这确保了所有交互式元素 - - 提示框、卡片、折叠面板,以及现在的**标签页** - - 都支持统一的 `icon:name` 语法。 ### 标签页中的图标 现在,您可以直接在标签页标签中添加任何 Lucide 图标,为用户提供即时的视觉上下文。 ```markdown ::: tabs == tab "npm" icon:box npx @docmd/core dev == tab "Bun" icon:zap bunx docmd dev ::: ``` ### ⚡ 一流的 Bun 支持 我们更新了所有核心文档和“入门指南”,加入了原生的 Bun 示例(支持 `bunx`,`bun add` 等操作)。英文、中文和德文指南已完成同步。 ### 🧭 上下文感知的分页导航 文章底部的“上一页”和“下一页”分页链接进行了重大的智能升级。现在,核心引擎能够原生理解 `outputPrefix` 上下文,确保读者在顺序浏览您的文档时,完美地停留在当前语言和版本的环境中,不会意外跳转至默认语言层。 ### 🎨 视觉打磨 - **更柔和的代码块**:所有代码块现在具有更柔和的 `border-radius` 圆角和微妙的框阴影,外观更加高级。 - **暗黑模式代码边框**:为暗黑模式增加了专用的 `--border-color-codeblock` 变量,修复了代码块和图表容器边框不可见的问题。 - **Mermaid 容器外观**:图表现在被包裹在一个带有边框和内边距的容器中,无论是在亮色还是暗黑主题下都具有一致的样式。 ### 🛠️ 内部重构 此版本包含了对 `docmd/parser` 包的一次重大架构清理,包括重构实用程序层(共享的 `parseTitleAndIcon` 工具)、添加自定义的围栏渲染器(防止代码标题被解析为 markdown 标题节点)以及相关正则性能的优化。 ## Migration Guide 对于**终端用户**:无破坏性变更。`npm update @docmd/core` 即可。 对于**插件作者**:如果您之前手动解析标签页页眉,我们建议切换到 `@docmd/parser` 导出的 `parseTitleAndIcon` 实用程序,以保持与未来图标增强功能的兼容性。 对于**其他文档平台的用户**:运行 `npx @docmd/core migrate --help` 查看所有可用的迁移源并在几秒钟内开始使用。 --- ## [发布说明 - 0.7.4](https://docs.docmd.io/zh/07/release-notes/0-7-4/) --- title: "发布说明 - 0.7.4" description: "引入离线搜索的上下文感知版本过滤功能,以及 Mermaid 图标渲染标准化。" --- `docmd` 0.7.4 版本为我们的离线搜索插件引入了一项强大的新功能:**上下文感知的版本过滤**。此版本还包含针对 Mermaid 图标渲染和语法标准化的热修复。 ## ✨ 亮点 ### 🔍 搜索中的版本过滤 在构建包含多个版本的文档时,查找正确的信息可能具有挑战性。内置的搜索模态框现在原生理解版本隔离,并自动生成动态过滤栏。 - **智能版本检测**:搜索引擎会自动从您的索引中提取所有可用版本,并生成可点击的过滤标签。 - **彩色编码标签**:系统会自动从预定义调色板中为每个版本标签分配独特、美观的颜色,帮助用户在视觉上区分不同的文档版本。 - **实时切换**:用户可以点击标签,立即将搜索结果缩小到一个或多个特定版本,从而提供更清晰、更准确的搜索体验。 ### 🏷️ 内联标签容器 我们引入了全新的 `tag`(标签)容器!这是一个自闭合的内联组件,专为在文本或标题中直接插入药丸状徽章而设计。 - **完全可自定义**:可以使用任何 CSS 颜色字符串(如 `color:#ef4444`)覆盖默认颜色。 - **图标支持**:支持直接将任何 Lucide 图标(如 `icon:check-circle`)附加到标签上。 - **超链接**:使用 `link:` 属性将标签无缝转换为链接。 - **兼容标题**:在 `<h1>` 或 `<h2>` 元素中使用时,标签会自动与基线对齐,而不会继承巨大的字体大小。 ## 🐛 问题修复 - **Mermaid 图标注册**:修复了在 Mermaid 流程图中,Lucide 图标库未能与用户使用的语法正确解耦的问题。 - **架构图语法支持**:我们已正式将 Mermaid 图标支持的文档迁移至使用 Mermaid 原生的 `architecture` 和 `architecture-beta` 图表类型,这些类型原生完美支持内联 Iconify 图标节点。 ## 🛡️ 安全更新 - **依赖审计**:通过在整个 monorepo 中强制升级深层嵌套的子依赖(`cross-spawn`、`dompurify`、`lodash-es`、`uuid` 和 `mermaid`),解决了多个安全警告。整个引擎生态系统现在 100% 干净且无漏洞。 ## ✨ 标准化的图标语法 为了在图表中抽象底层的图标库(目前为 Lucide),我们将图标包统一注册为 `icon`。 这意味着,您现在应该使用 `icon:` 而不是将文档显式绑定到 `lucide:`。这能为您的图表提供面向未来的保障 - - 如果我们将来在 `docmd` 中扩展或更改了底层图标库,您的图表将自动继承这些更新,而无需您进行任何修改! **示例:** ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[Database] in api service disk(icon:hard-drive)[Storage] in api db:L -- R:disk ``` ## 迁移指南 对于**最终用户**:使用 `npm update @docmd/core` 更新到最新的补丁版本。 如果您之前在 Mermaid 图表中使用了 `lucide:`,请将其替换为新的 `icon:` 前缀。 --- ## [发布说明 - 0.7.5](https://docs.docmd.io/zh/07/release-notes/0-7-5/) --- title: "发布说明 - 0.7.5" description: "安全补丁与 i18n 优化:消除 uuid 漏洞,添加语言切换保护,引入构建时页面清单实现零延迟切换。" --- `docmd` 0.7.5 版本将安全修复与重大 i18n 优化相结合。它消除了 Mermaid 插件中的上游 `uuid` 漏洞,为语言切换器添加了多层保护机制,并引入了**构建时页面清单**,用即时本地查找替代所有运行时网络检查。 ## 🛡️ 安全更新 ### Mermaid 插件 - 依赖树修复 `@docmd/plugin-mermaid` 包此前将 `mermaid` 声明为生产环境 `dependency`。这导致存在漏洞的传递性子依赖 `uuid@<14.0.0` 被安装到每个使用者的 `node_modules` 中,尽管该包在运行时从未使用它。 **根本原因**:Mermaid 库在运行时仅通过 CDN 在浏览器中加载。npm 上的 `mermaid` 包仅在开发过程中用于 TypeScript 类型检查和 esbuild 打包步骤。它被错误地归类为生产依赖。 **修复方案**:`mermaid` 已从 `@docmd/plugin-mermaid` 的 `dependencies` 移至 `devDependencies`。发布的包现在具有**零生产依赖**,因此 `mermaid` 及其存在漏洞的 `uuid` 子依赖不会为最终用户安装。 - `npm audit` / `pnpm audit` 现在对使用 `@docmd/plugin-mermaid` 的项目报告 **0 个漏洞**。 - 无功能变更 - Mermaid 渲染流程完全不受影响。 ## 🌐 i18n - 语言切换安全机制 此前,如果在 `i18n.locales` 中声明了某个语言区域,但其源目录(如 `docs/hi/`)不存在,语言切换器仍会将其显示为可点击状态 - 选择后会导致 **404 错误**。 **修复方案**:引擎现在在构建时**预扫描语言区域目录**。没有源目录的语言区域会在语言切换器中自动显示为禁用状态,带有 **N/A** 标记、`aria-disabled` 属性,且不可点击。 - **构建时检测**:引擎在渲染任何页面之前检查哪些语言区域目录实际存在。 - **模板级禁用**:不可用的语言区域显示为灰色,带有"N/A"标记和 `href="#"`。 - **客户端保护**:点击已禁用的语言区域不会执行任何操作 - 无导航、无 404。 - **链式回退**:如果某个语言区域可用但特定页面缺失,引擎会回退到默认语言版本的页面,并显示本地化的警告提示。 ## ⚡ i18n - 构建时页面清单 此前,语言切换器使用 `fetch(url, { method: 'HEAD' })` 来验证目标语言区域中是否存在某个页面。这增加了延迟,在某些 CDN 上无法正常工作,且离线时完全失效。 **修复方案**:引擎现在在构建时生成一个**页面清单** - 一个微小的 JS 文件(`docmd-i18n-manifest.js`),将每个语言区域映射到其可用的页面路径。客户端切换器同步读取此清单。 - **零网络请求**:页面存在性从清单本地检查 - 无 HEAD 请求。 - **离线可用**:清单与站点资产一起打包。 - **CDN 无关**:不依赖托管提供商如何处理 HEAD 请求。 - **优雅降级**:如果清单加载失败,切换器会自动回退到 HEAD 请求。 ::: callout info 启用 i18n 时,每个语言区域**必须**在源目录下拥有自己的子目录(如 `docs/en/`、`docs/hi/`)。默认语言的目录是部分翻译语言区域的回退源,必须存在。 ::: ## i18n 安全机制 - docmd 对比 | 能力 | docmd | VitePress | Docusaurus | Starlight | |:----|:-----:|:---------:|:----------:|:---------:| | 逐页回退到默认语言 | ✅ | ❌ (404) | ❌ (404) | ✅ | | 本地化"未翻译"警告 | ✅ | ❌ | ❌ | ✅ | | 自动禁用缺失语言区域 | ✅ | ❌ | ❌ | ❌ | | 客户端导航保护 | ✅ | ❌ | ❌ | ❌ | | 版本控制 + i18n 组合 | ✅ | ❌ | ❌ | ❌ | | 旧版本向后兼容(无语言区域目录) | ✅ | N/A | N/A | N/A | | RTL 方向支持 | ✅ | ✅ | ✅ | ✅ | | 零配置(无需自定义 React/Vue) | ✅ | 部分 | ❌ | ✅ | VitePress 和 Docusaurus 在非默认语言区域缺少页面时都会返回 **404 错误** - 需要手动配置服务器端重定向或自定义组件来优雅处理。Starlight (Astro) 提供逐页回退和翻译提示,与 docmd 类似 - 但不会自动禁用缺失的语言区域目录,也不会防止客户端导航到不存在的语言区域。 ## 迁移指南 对于**最终用户**:使用 `npm update @docmd/plugin-mermaid` 或 `pnpm update @docmd/plugin-mermaid` 更新到最新的补丁版本。无需任何配置更改。 --- ## [发行说明 - 0.7.6](https://docs.docmd.io/zh/07/release-notes/0-7-6/) --- title: "发行说明 - 0.7.6" description: "统一 URL 规范化引擎、通用 external: 和 raw: 链接前缀、SEO 尾随斜杠强制执行、SPA 哈希导航修复以及开发模式下的静默插件警告。" --- `docmd` 0.7.6 版本引入了 **统一 URL 规范化引擎**,消除了 301 重定向,强制执行用于 SEO 的尾随斜杠 URL,并在每个层面带来了始终如一的链接处理。 ## ✨ 特性亮点 ### 统一 URL 规范化 现在所有 URL 处理都通过 `@docmd/parser` 中的单个 `resolveHref()` 函数进行。尾随斜杠强制执行、`index.md` 剥离和双斜杠防止一致地应用于 Markdown 链接、按钮容器、导航和菜单栏。 - **消除 301 重定向**: 像 `/configuration/overview` 这样的 URL 直接在构建时解析为 `/configuration/overview/`。 - **无路径残留**: 在任何渲染的链接中不再有 `/index` 残留或 `.md` 扩展名。 - **Hreflang 准确性**: 备用标签现在可以正确地从页面路径中剥离语言环境前缀。 请参阅 [链接与引用](https://docs.docmd.io/zh/content/syntax/linking/) 指南以获取完整的 URL 转换表。 ### 通用的 `external:` 和 `raw:` 前缀 我们引入了两个新的魔法前缀,让你能够完全控制所有 `docmd` 组件中的链接行为。 - **`external:` - 强制新标签页打开**: 在任何链接(Markdown、按钮、菜单栏)中添加此前缀,以强制其在新标签页中打开。 - **`raw:` - 绕过规范化**: 当你需要链接到一个原始的 `.md` 文件而不希望引擎剥离其扩展名时,请使用此前缀。 ```markdown [在新标签页中打开](external:./configuration/overview.md) ::: button "API 文档" external:./api/node-api.md [下载模板](raw:templates/starter.md) ``` **行为变更**: HTTP/HTTPS 链接不再自动在新标签页中打开。当你需要该行为时,请显式使用 `external:`。 ### 插件的集中式 URL API `@docmd/parser` 中新的 URL 工具层通过 `@docmd/api` 重新导出。插件不再需要手动解析 `outputPath` - - 引擎会为每个页面预先计算纯净的 URL: ```typescript import { outputPathToSlug, sanitizeUrl } from '@docmd/api'; export async function onPostBuild({ pages }) { for (const page of pages) { page.urls.slug; // "guide/" page.urls.canonical; // "https://example.com/guide/" page.urls.pathname; // "/guide/" } } ``` 请参阅 [插件开发](https://docs.docmd.io/zh/advanced/plugins/) 指南以获取完整的 API 参考。 ## 🔧 开发者体验 ### 静默插件警告 以前,缺失或配置错误的插件会在 `docmd dev` 期间的 **每次文件更改** 时打印警告。现在,插件警告在每个开发会话中 **仅打印一次**,并在随后的重建中被抑制,以保持终端整洁。 ``` ↻ Change in docs/en/guide.md... ⚠️ Could not load plugin: @docmd/plugin-math Done. ``` ### SPA 哈希导航修复 在 SPA 模式下,单击当前页面上的 `#heading` 锚点现在会平滑地滚动到目标元素。通过哈希历史记录进行的浏览器后退/前进(通过 `popstate`)也能正确滚动。 ```markdown [跳转到配置](#configuration) <!-- 现在在 SPA 模式下可以工作 --> ``` ## 🚀 SEO 改进 - **尾随斜杠**: 所有内部 URL 渲染时带有尾随斜杠,以消除 301 重定向链。 - **纯净路径**: 规范链接和 hreflang `<link>` 标签使用正确的规范化路径。 - **零残留**: 生产环境 HTML 中无 `.md` 扩展名或 `/index` 片段。 ## 迁移指南 使用 `npm update @docmd/core` 或 `pnpm update @docmd/core` 更新。无需更改配置。 ::: callout info 如果你有剥离尾随斜杠的自定义服务器端重定向规则,请将其删除。引擎现在原生生成规范的尾随斜杠格式。 ::: --- ## [发布说明 - 0.7.7](https://docs.docmd.io/zh/07/release-notes/0-7-7/) --- title: "发布说明 - 0.7.7" description: "引入多项目支持、通用 TUI 设计系统,以及为专业文档工作流打造的优质、无表情符号的终端体验。" --- `docmd` 0.7.7 版本引入了**多项目支持** - - 允许您从单个代码库编排多个独立的文档站点。伴随着这一架构演进,我们还首次推出了**通用 TUI 设计系统**。通过全新的独立样式包,该系统全面现代化了我们的终端界面,带来了优质、高信号的开发者体验。 ## ✨ Highlights ### 🚀 多项目支持 您现在可以从单个 `docmd` 实例构建和提供多个独立的文档站点。通过根配置,您可以定义多个项目,每个项目都有自己的前缀、独立版本控制和隔离的导航,同时共享统一的主题和部署流水线。 ```javascript // docmd.config.js (root) import { defineConfig } from '@docmd/api'; export default defineConfig({ projects: [ { prefix: '/', src: 'docmd-main' }, { prefix: '/search', src: 'docmd-search' } ] }); ``` 每个项目都保持自己的目录结构和配置,允许您在单个域名下管理复杂的文档生态系统(例如核心引擎及其卫星工具),而不会产生版本冲突。 ### 🖥️ 通用 TUI 设计系统 我们彻底重构了 `docmd` 终端界面,以提供专业的、高信号的体验。新系统告别了“俏皮”的表情符号,转而使用精细的制表符(box-drawing characters)和精心挑选的配色方案,以提供清晰且可操作的反馈。 - **品牌形象提升**:TUI 系统中集中的 ASCII Logo 定义确保了所有 CLI 交互中品牌呈现的一致性。 - **高信号输出**:日志现在采用干净的表格化审美进行结构化处理,优先考虑本地开发和 CI/CD 环境下的可读性。 - **一致性**:无论是在构建站点、运行开发服务器还是使用迁移工具,终端体验都保持完美统一。 ### 📦 独立的 `@docmd/tui` 包 为了支持这一新设计系统,我们将终端审美从核心逻辑中解耦,放入了专门的 `@docmd/tui` 包中。 这一架构转变消除了循环依赖,并允许插件作者使用与核心引擎相同的专业 UI 组件。通过集中我们的“终端用户界面”(TUI)逻辑,我们确保了每一条输出 - - 从核心构建日志到第三方插件警告 - - 都遵循相同的高级设计语言。 ### 🚫 无表情符号的专业审美 为了履行我们提供优质开发者体验的承诺,0.7.7 版本转向了**无表情符号标准**。我们用成熟的制表符审美取代了旧有的基于表情符号的状态标记。这一改变确保了 `docmd` 的外观和感官更像是一个生产级工具,提供了一个能无缝集成到专业 IDE 和终端模拟器中的更简洁的界面。 ### 🔍 智能配置校验 配置错误不再泄露 Node.js 堆栈跟踪(stack traces)。我们使用标准化的 TUI 组件增强了实时配置反馈,以提供简洁、易读的错误消息。 校验器现在可以检测多项目根配置,并为缺失属性或错别字提供具体指导。当发生配置错误时,`docmd` 现在会呈现一个清晰的“错误报告”,包含准确的行引用和修复建议,确保您花更少的时间调试,花更多的时间写作。 ### ⚡ 多项目开发服务器 `docmd dev` 命令已升级以支持多项目编排。它会构建所有项目并从单个端口提供服务,具备智能文件监控功能,可针对正在编辑的特定项目触发定向重建。 ``` ──────────────────────────────────────── 多项目开发服务器 (MULTI-PROJECT DEV SERVER) 本地: http://127.0.0.1:3000 网络: http://192.168.1.5:3000 项目: / → docmd-main/ 项目: /search → docmd-search/ ──────────────────────────────────────── ``` ## 🛠️ 内部重构 此版本包含了为支持新 TUI 和多项目功能而进行的重大架构强化: - **依赖架构**:优化了包依赖关系,确保严格的有向无环流,防止引擎层和 UI 层之间出现循环导入。 - **日志重构**:完全废弃了旧的日志工具,转而使用集中的 TUI 系统。 - **项目编排**:多项目处理器位于一个独立的模块中,安全地管理目录上下文(`chdir`)并将独立输出合并到统一的站点结构中,而无需修改现有的构建流水线。 ## 📝 完整更新日志 ### 🚀 特性与增强 - **多项目引擎**:支持根配置中的 `projects[]`,具备共享资产和独立版本控制。 - **通用 TUI**:使用制表符和专业样式重构了终端界面。 - **独立 TUI 包**:全新的 `@docmd/tui` 库,用于在整个 Monorepo 中实现统一的 CLI 审美。 - **品牌提升**:为所有 CLI 入口点引入了集中的 ASCII Logo。 - **配置校验**:通过易读的错误报告增强了实时反馈,且无堆栈跟踪。 - **依赖优化**:在所有内部包中严格执行无环依赖流。 ### 🧹 清理与移除 - **无表情符号标准**:移除了所有旧有的基于表情符号的终端输出。 - **冗余日志**:取消了零散的 `chalk` 和 `console.log` 调用,转而使用 TUI 日志记录器。 - **旧版工具**:移除了已弃用的内部日志辅助工具。 ## Migration Guide ### 针对现有项目 **现有的单项目设置无需更改。** 引擎将默认继续支持标准的单项目工作流。 ### 采用多项目支持 要过渡到多项目设置: 1. 将现有的文档源移动到子目录中。 2. 创建根 `docmd.config.js` 并使用 `projects` 数组定义您的项目。 3. 从子配置中移除冗余的 `src` 和 `out` 路径,因为根编排器现在负责管理这些。 ### 针对插件作者 我们建议将任何自定义的 `console.log` 或 `chalk` 语句迁移到新的 `@docmd/tui` 包,以确保您的插件输出与核心 `docmd` 审美相匹配。 --- ## [版本说明 - 0.7.8](https://docs.docmd.io/zh/07/release-notes/0-7-8/) --- title: "版本说明 - 0.7.8" description: "引入 Git 插件、重新设计的终端界面与实时进度跟踪、并行页面处理显著提升构建速度、官方插件自动安装以及容器语法兼容性。" --- `docmd` 0.7.8 版本引入了 **Git 插件**用于仓库感知元数据,全新**重新设计的终端界面**提供实时进度反馈,**并行页面处理**显著加速构建,**官方插件自动安装**,以及**容器语法兼容性**方便从其他文档引擎迁移的用户。 ## 重点更新 ### 构建引擎 - 并行处理 页面渲染管线已从顺序处理重新设计为**批量并行处理**,为各种规模的文档站点带来显著加速。 **变更内容:** - **批量文件 I/O**:文件现在通过 `Promise.all` 一次读取 64 个、一次写入 128 个,而非逐个顺序处理 - **管线重叠**:文件读取、Markdown 解析和 HTML 写入阶段现在跨批次重叠进行 - **并行写入**:所有渲染的 HTML 文件批量并发写入磁盘 **预计性能(简单页面):** | 规模 | 之前 (0.7.7) | 之后 (0.7.8) | 提升 | | :--- | :--- | :--- | :--- | | ~1,000 页面 | ~22秒 | ~12秒 | **快约45%** | | ~10,000 页面 | ~4分钟+ | ~1.5分钟 | **快约60%** | | 文件读取阶段 | 顺序 | 64文件批次 | **64倍并发** | | 文件写入阶段 | 顺序 | 128文件批次 | **128倍并发** | | 进度反馈 | 无(静默) | 实时进度条 | 实时 | ::: callout tip "随文档规模扩展" 性能改进随文档规模增长而增强。拥有大量 I/O 的大型站点(1,000+ 页面)从批量并行处理中受益最大。 ::: ### 终端界面 - 统一 TUI 所有终端输出已重新设计为**统一的高信号设计系统**,在所有命令间共享。不再有静默等待、不一致的格式或杂乱的多行输出。 **新 TUI 组件:** | 功能 | 描述 | | :--- | :--- | | **进度条** | `━━━━━━━━━━━━───────── 42/100 (42%)` - 单行,原地更新 | | **旋转器** | `⠋ ⠙ ⠹` - 长时间操作期间的盲文点动画 | | **计时器** | 每次构建、重建和项目都显示耗时 | | **分区** | 所有命令统一使用 `┌─ 分区 / └──` 框架 | **所有命令统一输出:** ``` ┌─ Build │ Source docs/ │ Output site/ │ Versions 2 (v06, v07) │ Locales 4 (en, hi, zh, fr) │ Processing pages ━━━━━━━━━━━━━━━━━━━━ 419/419 (100%) └────────────────────────────────────────────────────────── ┌─ Post-Build Tasks │ Search index [ DONE ] │ Sitemap [ DONE ] └────────────────────────────────────────────────────────── ⬢ Build complete. Generated 238 pages in 1.4s. ``` **统一的命令:** - **`docmd build`** - 显示来源/输出/版本/语言的分区头,进度条,计时 - **`docmd dev`** - 初始构建和重建时的动画旋转器,每次重建计时 - **多项目构建** - 每个项目旋转器动画,每个项目计时,总结概览 - **`docmd live`** - 与所有其他命令一致的分区框架 ### Git 插件 新的 **Git 插件**为您的文档页面带来仓库感知元数据 - - 最后更新时间戳、提交历史工具提示和编辑链接 - - 全部直接从您的 Git 历史中获取,无需配置。 ```javascript // 配置编辑链接 plugins: { git: { repo: 'https://github.com/your-org/docs', branch: 'main' } } ``` **功能:** - **最后更新时间戳**:显示每个页面的最后修改时间,近期更改使用相对时间格式 - **提交历史工具提示**:悬停可查看近期提交,包含作者姓名和提交信息 - **编辑链接**:自动为 GitHub、GitLab 和 Bitbucket 构建"编辑此页面"链接 - **优雅降级**:如果项目不在 Git 仓库中,会自动禁用 该插件取代了旧的 `editLink` 配置选项,提供更丰富的功能。详见 [Git 插件文档](/plugins/git)。 ### 官方插件自动安装 在 `docmd.config.js` 中列出的官方插件如果缺失,现在会自动安装。当您在配置中添加一个未安装的插件时,docmd 会在下次构建时从 npm 下载。 ```javascript // docmd.config.js plugins: { pwa: {}, // 未安装?docmd 自动安装 threads: {} // 同上 } ``` **安全特性:** - 仅适用于注册表中的官方 `@docmd/plugin-*` 包 - 安装与您的 `@docmd/core` 版本匹配的精确版本 - 使用您项目的包管理器(npm、pnpm、yarn 或 bun) - 在终端中显示进度 ### 容器语法兼容性 从 **VitePress**、**Docusaurus** 或类似文档引擎迁移的用户现在可以直接使用熟悉的容器语法。 **VitePress 风格容器现已支持:** ```markdown :::tip 这将渲染为提示提醒。 ::: :::warning 这将渲染为警告提醒。 ::: :::details 点击展开 这将渲染为可折叠区域。 ::: ``` **Docusaurus 风格容器现已支持:** ```markdown :::note 这将渲染为信息提醒。 ::: :::caution 这将渲染为警告提醒。 ::: ``` 此外,所有容器现在支持**无空格语法**: ```markdown :::callout info 与 ::: callout info 效果相同 ::: :::tabs 与 ::: tabs 效果相同 ::: ``` 这使得从其他引擎迁移文档时只需最少的更改。 ### 迁移友好别名 | 别名 | 映射到 | 来源 | | :--- | :--- | :--- | | `:::tip` | `callout tip` | VitePress | | `:::warning` | `callout warning` | VitePress | | `:::danger` | `callout danger` | VitePress | | `:::info` | `callout info` | VitePress | | `:::details` | `collapsible` | VitePress | | `:::note` | `callout info` | Docusaurus | | `:::caution` | `callout warning` | Docusaurus | ::: callout tip "无缝迁移" 这些别名与标准 `docmd` 语法同时工作。您现有的文档继续正常运行,而从其他引擎导入的内容也能正确渲染。 ::: ## 内部改进 ### 英式英语标准化 文档已更新为在全文中一致使用英式英语拼写。这包括 "optimised"、"centralised"、"localisation" 和 "colour" 等术语。 ### 代码质量 - 在文档和代码注释中将长破折号替换为标准连字符以提高可读性 - 标准化源文件中的注释格式 - 改进了插件 API 的 TypeScript 类型定义 ## 完整变更日志 ### 功能 - **Git 插件(核心)**:新的核心插件,提供最后更新时间戳、提交历史和编辑链接,支持优雅降级 - **自动安装**:配置中的官方插件如果缺失会自动安装 - **容器别名**:VitePress 和 Docusaurus 容器语法现在开箱即用 - **无空格容器**:所有容器现在接受 `:::` 后有或无空格的语法 - **并行处理**:批量文件 I/O,64文件读取和128文件写入并发 - **统一 TUI**:进度条、旋转器、计时器和所有命令的一致分区输出 ### 改进 - **构建性能**:大型站点通过并行 I/O 批处理构建速度提升最高约60% - **实时进度**:页面处理期间的实时进度条 - **动画旋转器**:构建、重建和多项目处理期间的视觉反馈 - **构建计时**:每个操作报告耗时 - **Git 小部件 UI**:工具提示使用 CSS `:hover`/`:focus-within` 实现流畅无抖动显示 - **代码块样式**:`docmd-code-block-wrapper` 现在使用通用 `--shadow-sm` 变量 - **实时编辑器 TUI**:统一的分区框架和优雅关闭 - **文档**:英式英语拼写标准化 - **代码风格**:整个代码库的一致格式化 - **插件注册表**:Git 插件已添加到官方注册表 ### 弃用 - **editLink 配置**:独立的 `editLink` 配置选项已弃用,改用 Git 插件 ## 迁移指南 ### 采用 Git 插件 如果您之前使用 `editLink` 配置,请替换为 `git` 插件。新方式更智能 - - 它会自动检测您的 git 仓库根目录并计算正确的文件路径,无需在 URL 中硬编码目录。 **之前(已弃用):** ```javascript export default defineConfig({ editLink: { enabled: true, baseUrl: 'https://github.com/org/repo/edit/main/docs' // ← 硬编码目录 } }); ``` **之后:** ```javascript export default defineConfig({ plugins: { git: { repo: 'https://github.com/org/repo', // ← 只需仓库地址,无需路径 branch: 'main' } } }); ``` 插件会自动解析相对于 git 根目录的正确文件路径。这意味着在 monorepo 和多项目设置中,编辑链接无需任何手动路径配置即可正确工作。 **附加选项:** | 选项 | 默认值 | 描述 | | :--- | :--- | :--- | | `repo` | - | 仓库 URL(任意提供商) | | `branch` | `'main'` | 链接到的分支 | | `editPath` | `'edit'` | 编辑页面的 URL 段。GitLab 使用 `'-/edit'`,Bitbucket 使用 `'src'` | | `editLink` | `true` | 设为 `false` 可禁用编辑链接 | | `editLinkText` | i18n 字符串 | 编辑链接的自定义标签 | ::: callout warning "重大变更:editLink baseUrl 格式" 如果您之前在 `editLink.baseUrl` 中使用了硬编码的子目录(例如 `.../edit/main/docs`),该目录段现在会自动计算。切换到 git 插件时,需要从 URL 中移除子目录 - - `repo` 值只需使用 `https://github.com/org/repo`。 ::: ### 从其他引擎迁移的用户 如果您从 VitePress、Docusaurus 或类似引擎导入文档: 1. 您现有的 `:::tip`、`:::warning`、`:::note` 容器将正确渲染 2. 无空格语法如 `:::tabs` 与标准 `::: tabs` 并行工作 3. 无需更改您的 Markdown 文件 我们建议在新内容中逐步过渡到标准 `docmd` 语法(`::: callout tip`),因为它提供更多标题和图标的灵活性。 --- ## [版本说明 - 0.7.9](https://docs.docmd.io/zh/07/release-notes/0-7-9/) --- title: "版本说明 - 0.7.9" description: "OpenAPI 插件、插件 API 改进(onBeforeRender 钩子和 sourcePath)、修复多项目构建中 Git 插件提交历史准确性问题、贡献者头像和智能粘性页脚。" --- `docmd` 0.7.9 版本引入了 **增量重建(Incremental Rebuilds)** 以实现近乎瞬时的开发体验、**OpenAPI 插件**以及通过**并行插件架构**实现的重大性能优化。它还解决了关键的配置文件泄露问题,修复了 Monorepo Git 历史准确性,添加了贡献者头像,并实现了智能粘性页脚。 ## ✨ 亮点 ### OpenAPI 插件 新的 **OpenAPI 插件**直接在 Markdown 页面中从 OpenAPI 3.x 规范文件渲染 API 参考文档 - - 在构建时,无客户端 JavaScript,无第三方 UI 库(无 Swagger UI,无 Redoc)。 在任何 Markdown 中添加规范嵌入: ````markdown ```openapi ./api/openapi.json ``` ```` 插件在构建时读取规范并输出静态 HTML:颜色编码的方法徽章、参数表格、请求/响应模式表格和状态码描述。支持 JSON 和 YAML 规范,解析内部 `$ref` 引用,处理 `oneOf`/`anyOf` 联合类型。 **0.7.9 新功能:** 添加了 `download: true` 选项,在 UI 中提供指向原始规范文件的直接链接 - - 非常适合 GPT-4 或 Claude 等 AI 模型通过编程方式获取您的 API 文档。 ```bash docmd add openapi ``` 详情请参阅 [OpenAPI 插件文档](../plugins/openapi/)。 ### 增量重建(瞬时开发模式) 开发服务器现在配备了**定向重建(Targeted Rebuild)**系统。此前,编辑单个 Markdown 文件会触发全站重建。对于拥有数百个页面的网站,这可能需要 10 秒以上的时间。 在 0.7.9 中,`docmd dev` 仅重新渲染您修改的特定文件。即使对于大型项目,页面重新加载现在也是**瞬时的(<1s)**。系统在这些部分更新期间能够正确维护所有导航、版本控制和资源上下文。 ### 并行插件架构(多线程性能提升) 构建引擎已全面重构,支持**并行插件执行**。此前,`onBeforeRender` 等插件钩子是针对每个页面顺序执行的。对于执行 I/O 或启动子进程的插件(如 Git 插件),这是一个显著的性能瓶颈。 在 0.7.9 中,引擎现在采用并行分批处理页面渲染。结合采用非阻塞 `execFile` 调用的新版**异步 Git 插件**,拥有数百个页面的大型网站的构建速度提升了 **3 倍**。 **核心改进:** - **分批渲染**:生成器的第 3 阶段现在以 64 页为一批并行运行。 - **异步钩子**:所有插件钩子现在都支持 `async`,引擎会并行等待它们完成。 - **Git 插件重构**:将同步的 `execSync` 替换为异步、非阻塞的进程生成。 ### 插件 API - `onBeforeRender` 钩子和 `sourcePath` 插件作者现在可以在构建管道的新阶段挂钩:**模板渲染前**,完全访问页面上下文。 新的 `onBeforeRender(page: PageContext)` 钩子接收包含 `sourcePath`(始终设置)的完整页面上下文,以及可变的 `frontmatter` 和 `html`。 声明 `build` 能力以使用它。详情请参阅 [创建插件](../plugins/building-plugins/) 文档。 ## 📝 完整更新日志 ### 错误修复 - **Git 插件 - 多项目构建中的按文件提交历史**:模块级单例状态被修复为每目录缓存,确保每个文件始终在其自己的仓库上下文中查询。在单项目、多项目、版本化和多语言配置中均正确。 - **Git 插件 - SPA 水合**:修复为监听 `docmd:page-mounted` 事件,确保 SPA 导航后时间戳正确格式化。 ### 新功能 - **OpenAPI 插件(`@docmd/plugin-openapi`)**:构建时 OpenAPI 3.x 规范渲染器,无客户端依赖。 - **插件 API - `onBeforeRender` 钩子**:在模板渲染前调用,接收包含 `sourcePath` 的完整 `PageContext`。 - **插件 API - `PageContext` 类型**:从 `@docmd/api` 正式导出。 - **Git 插件 - 贡献者头像**:提交历史工具提示现在显示 Gravatar 图像。 - **Git 插件 - 可配置日期格式**:新的 `dateFormat` 选项:`relative`(默认)、`iso` 或 `locale-aware`。 - **并行构建管道**:生成器现在并行化模板渲染阶段。插件现在可以通过子进程在多个 CPU 核心上并发执行昂贵的操作(如 Git 调用或 OpenAPI 解析)。 - **异步 Git 插件**:Git 插件现在完全异步。它使用非阻塞子进程和路径规范化,确保在复杂的 monorepo 结构中也能保持高性能和准确性。 - **增量重建系统**:开发服务器现在执行定向部分构建。编辑文件仅重新渲染该文件,将大型网站的重新加载时间从 10s+ 缩短到 300ms 以下。 - **OpenAPI 插件 - 下载规范**:新的 `download` 选项在页面页眉提供指向原始 JSON/YAML 规范的链接,方便 AI 访问。 - **UI - 智能粘性页脚**:页脚现在始终使用 flex 布局固定在视口底部。(已修复)。 ### 内部 - **编辑链接路径解析**:根据 Git 仓库根目录计算,而非 `config.src` 或 `process.cwd()`。在所有项目布局中均正确。 - **配置加载器 - 硬化**:实现了对孤立临时配置文件 (`docmd.config-*.js`) 的强制清理,并添加了 `try-finally` 安全保护以防止语法错误期间的文件泄露。 --- ## [资源管理 (Assets Management)](https://docs.docmd.io/zh/07/theming/assets-management/) --- title: "资源管理 (Assets Management)" description: "docmd 如何在构建过程中处理 CSS、JavaScript 和图像资源。" --- `docmd` 对资源采取“镜像与映射”的方法。这确保了你的本地开发路径与生产构建保持一致。 ## 目录结构 默认情况下,`docmd` 会在项目根目录下寻找 `assets/` 文件夹。 ```bash my-docs/ ├── assets/ # 源码资源 │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # 内容 ├── docmd.config.js └── site/ # 构建输出 (自动镜像) ``` ## 自动复制 当你运行 `docmd build` 或 `docmd dev` 时: 1. **镜像逻辑**: `assets/` 文件夹的全部内容会被递归复制到 `site/assets/`。 2. **稳定性**: 我们使用经过加固的复制引擎,支持自动重试,以防止在 macOS 和现代 SSD 上出现“文件忙”或“ENOENT”错误。 3. **引用**: 你应该始终使用 **相对于根目录的路径** 在 Markdown 或配置中引用资源: ```markdown ![Logo](/assets/images/logo.png) ``` ## 自定义 CSS 与 JS 集成 要将你的资源链接到每个页面,请将它们添加到你的主题配置中: ```javascript // docmd.config.js export default { theme: { customCss: ['/assets/css/branding.css'] }, customJs: ['/assets/js/utils.js'] } ``` ::: callout info "AI 识别策略 :robot:" * **按类型组织**: 保持 `/css`、`/js` 和 `/images` 的分离。当你要求 AI 代理“编辑页眉颜色”时,这有助于它们立即定位相关的样式或脚本。 * **使用描述性的文件名**: 将图像命名为 `authentication-flow-diagram.png` 比 `img_01.png` 能为 `llms.txt` 爬虫提供更多的上下文。 ::: --- ## [可用主题 (Available Themes)](https://docs.docmd.io/zh/07/theming/available-themes/) --- title: "可用主题 (Available Themes)" description: "探索 docmd 内置的主题,包括 Sky、Ruby 和 Retro。了解如何通过单行配置切换主题。" --- `docmd` 提供了一套专业设计的、支持浅色/深色响应的主题。你可以通过更改 `docmd.config.js` 中的一个键值来切换整个网站的美学风格。 ## 如何切换主题 ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system', // 选项: 'light', 'dark', 'system' } } ``` ## 内置主题展示 | 主题 | 最适合 | 氛围 | | :--- | :--- | :--- | | `default` | 简约文档 | 干净、轻量、中性 | | `sky` | 产品文档 | 现代、高级、标准 | | `ruby` | 品牌标识 | 精致、衬线页眉、充满活力 | | `retro` | 开发工具 | 80 年代终端、等宽字体、霓虹点缀 | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` 正是此文档网站所使用的主题。如果你打算添加大量的自定义 CSS 并且不希望任何内置的设计层产生干扰,请使用此主题。 ### 2. `sky` 现代文档的金标准。它具有清晰的排版、微妙的过渡以及与现代 SaaS 平台匹配的高对比度浅色/深色模式。 ### 3. `ruby` 一个高雅的主题,页眉使用衬线体排版,并配以深沉、如宝石般色调的调色板。非常适合需要权威感和高级感的文档。 ### 4. `retro` 一个受复古计算启发、充满怀旧感的主题。特性包括黑色背景上的磷光绿文本(在深色模式下)、扫描线效果,以及默认使用的 Fira Code 等等宽字体。 ## 主题架构 1. **CSS 分层**: 主题是累加的。选择 `sky` 实际上会加载基础的 `default` 样式,然后在此基础上覆盖 `sky` 的美学样式。 2. **原生深色模式**: 每个主题都包含一流的深色模式实现。 3. **无需刷新**: 当用户通过 UI 切换主题时,SPA 引擎会立即更新 `--docmd-primary` 变量,而无需重新加载页面。 ::: callout tip 当向 AI 开发工具描述你的文档布局时,提到你的主题(例如,“我正在使用 `retro` 主题”)有助于模型建议符合该特定主题变量架构的自定义 CSS 覆盖方案。 ::: --- ## [自定义样式与脚本](https://docs.docmd.io/zh/07/theming/custom-css-js/) --- title: "自定义样式与脚本" description: "注入自定义 CSS 和 JS 文件,扩展 docmd 的功能与品牌形象。" --- 虽然 `docmd` 主题具备高度的灵活性,你仍可能需要注入自定义样式表或交互脚本。通过在配置文件中设置 `theme.customCss` 和 `customJs` 数组即可实现。 ## 自定义 CSS 使用 `theme.customCss` 覆盖现有样式或添加新样式。 ```javascript // docmd.config.js export default { theme: { customCss: [ '/assets/css/branding.css' // 相对站点根目录的路径 ] } } ``` ### 工作原理 1. 将 CSS 文件放入项目的 assets 文件夹(如 `docs/assets/css/branding.css`)。 2. `docmd` 会自动将其复制到构建目录,并在每个页面中注入 `<link>` 标签。 3. 自定义 CSS 在主题样式**之后**加载,确保你的覆盖具有优先级。 ## 自定义 JavaScript 使用顶级 `customJs` 数组添加行为性脚本或集成第三方服务。 ```javascript // docmd.config.js export default { customJs: [ '/assets/js/feedback-widget.js' ] } ``` ### 生命周期感知 脚本在 `<body>` 标签底部注入。由于 `docmd` 是**单页应用(SPA)**,需注意: * 导航链接时页面不会完整重载。 * 你可能需要监听自定义生命周期事件,以便在新页面上重新初始化脚本。 有关完整的事件列表和用法示例,请参阅 [客户端事件](../api/client-side-events)。 ::: callout tip 添加自定义 CSS 和 JS 后,AI 模型(如 ChatGPT)可提出更有针对性的 UI 优化建议。如果你说"我有一个自定义的 `branding.css` 文件",模型可提供不会与引擎冲突的具体选择器。 ::: --- ## [自定义与变量](https://docs.docmd.io/zh/07/theming/customisation/) --- title: "自定义与变量" description: "docmd CSS 变量和组件类的完整参考,用于高级样式定制。" --- `docmd` 采用 CSS 变量优先架构。这意味着只需在 `:root` 块中覆盖少数几个变量,无需编写复杂的 CSS 选择器,即可重新设计整个网站的样式。 ## 全局变量参考 | 变量 | 亮色模式默认值 | 暗色模式默认值 | 说明 | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | 页面主背景色 | | `--text-color` | `#3f3f46` | `#a1a1aa` | 正文文本颜色 | | `--text-heading` | `#09090b` | `#fafafa` | 标题与页眉颜色 | | `--link-color` | `#068ad5` | `#068ad5` | 主色调 / 链接颜色 | | `--border-color` | `#e4e4e7` | `#27272a` | 分割线与边框颜色 | | `--sidebar-bg` | `#fafafa` | `#09090b` | 导航背景色 | | `--ui-border-radius` | `6px` | `6px` | 所有 UI 项的圆角大小 | | `--sidebar-width` | `260px` | `260px` | 侧边栏列宽 | ## 覆盖示例 如需更改网站主色调,请将以下内容添加到 `customCss` 文件中: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## 组件定向覆盖 如需对特定组件进行样式化,可使用以下顶级类名: * `.main-content`:所有 Markdown 内容的包裹容器。 * `.sidebar-nav`:内部导航列表。 * `.page-header`:顶部导航栏。 * `.docmd-search-modal`:搜索弹框。 * `.docmd-tabs`:标签组件容器。 * `.callout`:提示/备注框。 ## 优先级排查 大多数 `docmd` 样式的优先级较低。如果覆盖未生效,请确认 `customCss` 是否已正确注册,并尝试在选择器前增加 `body` 前缀(如 `body .main-content`)。 ::: callout tip 由于 `docmd` 使用标准 CSS 变量,你可以直接询问 AI:*"为 docmd 的 --link-color 和 --bg-color 提供一套专业配色方案"*。模型将给出即用型 CSS,完美兼容内置主题。 ::: --- ## [图标 (Icons)](https://docs.docmd.io/zh/07/theming/icons/) --- title: "图标 (Icons)" description: "如何在你的文档中使用和自定义 Lucide 图标。" --- `docmd` 内置支持 [Lucide](external:https://lucide.dev/) 图标库。图标可以用于你的导航侧边栏、按钮和自定义组件,以提供视觉线索并提高可扫描性。 ## 导航图标 在 `docmd.config.js` 中为任何导航项分配一个图标。请使用 Lucide 网站上找到的任何图标的短横线命名法 (kebab-case) 名称。 ```javascript navigation: [ { title: '首页', path: '/', icon: 'home' }, { title: '设置', path: '/setup', icon: 'settings' } ] ``` ## 容器中的图标 你也可以通过包含原始 HTML 或在整个 docmd 中使用标准的 `icon:` 前缀,在按钮、标签、选项卡和其他容器内部使用图标。 ```markdown ::: button "下载" /download icon:download ``` ## CSS 样式 所有图标都渲染为带有 `.lucide-icon` 类的行内 SVG。你可以在你的 `customCss` 中全局更改它们的大小或线条粗细: ```css .lucide-icon { stroke-width: 1.5px; /* 更细的图标,呈现现代感 */ width: 1.2rem; height: 1.2rem; } /* 针对特定图标 */ .icon-rocket { color: #ff5733; } ``` ## 图标参考 我们支持整个 Lucide 库。你可以在这里浏览数千个可用的图标: ::: button "浏览 Lucide 图标" external:https://lucide.dev/icons icon:globe --- ## [明暗模式](https://docs.docmd.io/zh/07/theming/light-dark-mode/) --- title: "明暗模式" description: "如何配置默认浏览模式并管理主题切换器,以提供最佳用户体验。" --- `docmd` 内置支持明色和暗色配色方案。它会自动检测用户的系统偏好,并允许通过 UI 切换按鈕手动覆盖。 ## 默认浏览模式 在 `docmd.config.js` 中指定文档的初始状态。 ```javascript // docmd.config.js export default { theme: { name: 'sky', appearance: 'system' // 可选值:'light'、'dark'、'system'(默认) } } ``` * **`system`**:匹配用户的操作系统偏好(推荐)。 * **`light`**:首次加载时强制使用亮色模式。 * **`dark`**:首次加载时强制使用暗色模式。 ## 配置切换按鈕 主题切换器是**选项菜单**的组成部分。可通过 `layout` 对象控制其可见性和位置。 ```javascript layout: { optionsMenu: { position: 'header', // 可选:'header'、'sidebar-top'、'sidebar-bottom' components: { themeSwitch: true // 显示或隐藏太阳/月亮切换按鈕 } } } ``` ## 工作原理(技术详解) 主题引擎会向 `<body>` 标签添加 `data-theme` 属性: * `<body data-theme="light">` * `<body data-theme="dark">` 如果使用类似 `sky` 这样的主题设计,属性值将为 `sky-light` 或 `sky-dark`。 ### CSS 变量 `docmd` 主题为所有颜色使用 CSS 变量。可在自定义 CSS 中覆盖这些变量,自定义任意模式的外观。 ```css /* 自定义 CSS 覆盖 */ :root { --docmd-primary: #4f46e5; /* 亮色模式主色调 */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* 暗色模式主色调 */ } ``` ## 用户偏好持久化 用户手动切换模式后,居好将存入 `localStorage`。`docmd` 在每次页面加载时即时读取该值,防止“主题闪烁”(FOUC)。 ::: callout tip 生成内容时,LLM 偏幽高对比结构。`docmd` 确保代码片段和提示框在两种模式下均可正常访问,保证 `llms-full.txt` 内容无论在哪种模式下构建,都能被正确解析为语义块。 ::: --- ## [浏览器 API(客户端)](https://docs.docmd.io/zh/api/browser-api/) --- title: "浏览器 API(客户端)" description: "在浏览器中与 docmd 交互 - - 实时编译与开发模式插件通信。" --- `docmd` 提供两类浏览器 API:用于在浏览器中渲染 Markdown 的**同构编译引擎**,以及用于与开发服务器实时通信的**开发模式插件 API**。 ## 同构编译引擎 在 Node.js 中生成静态站点的同一引擎可完全在浏览器中运行。非常适合构建 CMS 预览、交互式演示场,或将文档嵌入现有 Web 应用。 ### 通过 CDN 安装 ```html <!-- 核心样式 --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 同构引擎 --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` ### `docmd.compile(markdown, config)` 使用默认的 `docmd` 布局将原始 Markdown 编译为完整的 HTML 文档字符串。 **参数:** - `markdown`(String):原始 Markdown 内容。 - `config`(Object):配置覆盖(与 `docmd.config.json` 使用相同的 schema)。 **返回值:** `Promise<String>`:完整的 HTML 文档。 ### 示例:实时预览 为确保样式隔离,建议通过 `srcdoc` 属性在 `<iframe>` 内渲染输出。 ```javascript const editor = document.getElementById('editor'); const preview = document.getElementById('preview'); async function updatePreview() { const html = await docmd.compile(editor.value, { title: '预览', theme: { appearance: 'light' } }); preview.srcdoc = html; } editor.addEventListener('input', updatePreview); ``` ## 开发模式插件 API 在 `npx @docmd/core dev` 运行期间,`window.docmd` 全局对象会自动注入每个页面。该 API 通过 WebSocket RPC 实现浏览器端插件代码与服务器端动作处理程序的实时通信。 ::: callout info "仅限开发模式" 以下插件 API 方法仅在 `npx @docmd/core dev` 期间可用,不包含在生产构建中。 ::: ### `docmd.call(action, payload)` 调用插件注册的服务器端动作处理程序。返回一个 Promise,其值为处理程序的返回值。 ```javascript // 调用插件动作并获取结果 const threads = await docmd.call('threads:get-threads', { file: 'docs/getting-started.md' }); console.log(threads); // 线程对象数组 ``` 如果动作修改了源文件,Promise 完成后页面将自动重载。 ### `docmd.send(name, data)` 向服务器发送即发即忘事件,不返回响应。 ```javascript // 通知服务器页面浏览(不期待响应) docmd.send('analytics:page-view', { path: window.location.pathname }); ``` ### `docmd.on(name, callback)` 订阅服务器推送事件。返回取消订阅函数。 ```javascript // 监听服务器广播事件 const unsub = docmd.on('threads:updated', (data) => { console.log('线程已更新:', data); }); // 稍后取消订阅 unsub(); ``` ### `docmd.afterReload(name, callback)` 声明页面重载后运行的处理程序。如果使用 `scheduleReload` 存储了上下文,回调将接收到该上下文。 ```javascript // 在实时重载后恢复滚动位置 docmd.afterReload('scroll-restore', (ctx) => { window.scrollTo(0, ctx.scrollY); }); ``` ### `docmd.scheduleReload(name, context)` 将上下文存储到 `sessionStorage` 中,供命名的 `afterReload` 处理程序使用。在下次页面重载后,匹配的处理程序将以此上下文触发。 ```javascript // 在文件编辑触发重载之前,保存状态 docmd.scheduleReload('scroll-restore', { scrollY: window.scrollY }); ``` ## 注意事项 - **WebSocket 连接**:开发模式 API 需要与开发服务器保持活跃的 WebSocket 连接。如果连接断开,将以指数退避方式自动重连。 --- ## [CLI 命令](https://docs.docmd.io/zh/api/cli-commands/) --- title: "CLI 命令" description: "docmd 的命令行参考 - 所有可用的命令和选项。" --- ## 命令概览 | 命令 | 描述 | |:--------|:------------| | [`npx @docmd/core init`](#npx-docmdcore-init) | 初始化一个新的文档项目 | | [`npx @docmd/core dev`](#npx-docmdcore-dev) | 启动带有热重载的开发服务器 | | [`npx @docmd/core build`](#npx-docmdcore-build) | 生成生产环境静态网站 | | [`npx @docmd/core live`](#npx-docmdcore-live) | 启动基于浏览器的实时编辑器 | | [`npx @docmd/core stop`](#npx-docmdcore-stop) | 停止正在运行的开发服务器 | | [`npx @docmd/core deploy`](#npx-docmdcore-deploy) | 生成部署配置 | | [`npx @docmd/core migrate`](#npx-docmdcore-migrate) | 升级旧版配置或从其他工具迁移 | | [`npx @docmd/core add <plugin>`](#npx-docmdcore-add-plugin) | 安装并配置插件 | | [`npx @docmd/core remove <plugin>`](#npx-docmdcore-remove-plugin) | 移除插件及其配置 | ## 全局选项 | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--config <path>` | `-c` | 配置文件路径(默认:`docmd.config.json`) | | `--verbose` | `-V` | 显示详细的构建日志 | | `--version` | `-v` | 输出安装的版本号 | | `--help` | `-h` | 显示帮助菜单 | | `--cwd <path>` | - | 覆盖当前工作目录(适用于 monorepos) | ## `npx @docmd/core init` 在当前目录中初始化一个新的文档项目。 ```bash npx @docmd/core init ``` 创建内容: - `docs/index.md` - 示例主页 - `docmd.config.json` - 推荐的默认配置 - 更新 `package.json` 并添加构建脚本 ## `npx @docmd/core dev` 启动一个带有即时热重载的开发服务器。 ```bash npx @docmd/core dev [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--port <number>` | `-p` | 服务器端口(默认:`3000`) | | `--config <path>` | `-c` | 配置文件路径 | ## `npx @docmd/core build` 在 `site/` 目录中生成生产就绪的静态网站。 ```bash npx @docmd/core build [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--offline` | - | 将链接重写为 `.html` 以进行 `file://` 浏览 | | `--config <path>` | `-c` | 配置文件路径 | ## `npx @docmd/core live` 启动基于浏览器的实时编辑器。 ```bash npx @docmd/core live [options] ``` | 选项 | 描述 | |:-------|:------------| | `--build-only` | 仅生成编辑器捆绑包而不启动服务器 | ## `npx @docmd/core stop` 停止正在运行的 docmd 开发服务器。 ```bash npx @docmd/core stop [options] ``` | 选项 | 别名 | 描述 | |:-------|:------|:------------| | `--port <number>` | `-p` | 仅停止该端口上的服务器 | | `--force` | `-f` | 同时强制停止端口 3000、3001、8080、8081 上的服务进程 | ## `npx @docmd/core deploy` 生成部署配置文件。 ```bash npx @docmd/core deploy [options] ``` | 选项 | 描述 | |:-------|:------------| | `--docker` | 生成 `Dockerfile` | | `--nginx` | 生成 `nginx.conf` | | `--caddy` | 生成 `Caddyfile` | | `--force` | 覆盖现有的部署文件 | ## `npx @docmd/core migrate` 将旧版 docmd V1 配置升级到 V2 架构。 ```bash npx @docmd/core migrate ``` 自动重新映射已弃用的键(例如,`siteTitle` → `title`)并重构配置对象。 ## `npx @docmd/core add <plugin>` 安装并配置官方或社区插件。 ```bash npx @docmd/core add <plugin-name> ``` | 示例 | 描述 | |:--------|:------------| | `npx @docmd/core add analytics` | 安装 `@docmd/plugin-analytics` | | `npx @docmd/core add search` | 安装 `@docmd/plugin-search` | CLI 会自动检测你的包管理器(npm、pnpm、yarn 或 bun),并将推荐的默认设置注入到 `docmd.config.json` 中。 ## `npx @docmd/core remove <plugin>` 安全地卸载插件并清理其配置。 ```bash npx @docmd/core remove <plugin-name> ``` 移除: - npm 软件包 - `docmd.config.json` 中的插件配置 ::: callout tip "代理兼容的日志记录 :robot:" `docmd` 使用结构化的终端日志记录。AI 代理可以精确解析输出,以便进行错误检测和自动化维护。 ::: --- ## [客户端事件](https://docs.docmd.io/zh/api/client-side-events/) --- title: "客户端事件" description: "接入 docmd SPA 生命周期,添加交互式功能。" --- `docmd` 使用轻量级单页应用(SPA)路由器,提供即时页面切换。由于浏览器在导航时不执行完整刷新,依赖 `DOMContentLoaded` 的脚本将不会重新执行。 为此,`docmd` 分发自定义生命周期事件,你可以在 `customJs` 文件中监听这些事件。 ## `docmd:page-mounted` 每当新页面成功获取并注入到 DOM 时,此事件就会被分发。 ### 用法 在 `document` 对象上添加监听器,以重新初始化第三方库或触发自定义动画。 ```javascript document.addEventListener('docmd:page-mounted', (event) => { const { url } = event.detail; console.log(`已导航至:${url}`); // 重新初始化组件 // 示例:Prism.highlightAll(); }); ``` ### 事件详情(`event.detail`) | 属性 | 类型 | 说明 | | :--- | :--- | :--- | | `url` | `String` | 刚刚挂载的页面的绝对 URL。 | ## 最佳实践 1. **幂等性**:确保你的初始化逻辑可以在同一页面上安全多次调用,或在下次导航前妥善清理。 2. **全局作用域**:通过 `customJs` 添加的脚本在全局作用域中执行。使用 IIFE(立即调用函数表达式)避免污染 `window` 对象。 3. **清理**:如果脚本添加了全局事件监听器(如 `window.onresize`),考虑追踪当前路径,以便用户离开时将其移除。 --- ## [实时编辑器](https://docs.docmd.io/zh/api/live-api/) --- title: "实时编辑器" description: "了解 docmd 实时编辑器及其基于浏览器的创作工作流。" --- `docmd` 实时编辑器是专为实时文档创作而设计的专用环境。它使用 `docmd` 的同构核心,无需后端构建流程,即可即时并排预览 Markdown 内容。 ## 启动编辑器 运行以下命令启动本地实时编辑器: ```bash docmd live ``` 编辑器通常可在 `http://localhost:3000` 访问。 ## 架构 与标准 `dev` 服务器(在磁盘上重新构建文件)不同,实时编辑器直接在浏览器中运行 `docmd` 引擎。这实现了: 1. **即时反馈**:内容在输入时即时重新渲染。 2. **可移植沙盒**:编辑器可以打包成静态站点,托管在 GitHub Pages 等平台上。 3. **跨平台一致性**:预览使用与生产构建完全相同的渲染逻辑。 ## 静态部署 生成一个可共享的独立编辑器版本: ```bash docmd live --build-only ``` 这会创建一个包含编辑器 HTML 和打包同构引擎的 `dist/` 目录。 --- ## [MCP 服务端](https://docs.docmd.io/zh/api/mcp-server/) --- title: "MCP 服务端" description: "通过 Model Context Protocol 将 AI 开发 Agent 连接到您的文档工作区。" --- docmd 包含原生的 Model Context Protocol (MCP) 服务端,使 AI 开发 Agent 能够以编程方式与您的文档工作区进行交互。 ## 什么是 MCP? [Model Context Protocol](external:https://modelcontextprotocol.io/) 是一个连接 AI 模型与外部工具和数据源的开放标准。它使用 JSON-RPC 2.0 消息通过传输层(stdio、HTTP)进行通信。docmd 实现了 `stdio` 传输 — Agent 以子进程方式启动 `docmd mcp`,通过 stdin/stdout 进行通信。 ## 快速开始 ```bash docmd mcp ``` 这将通过 `stdio` 启动 MCP 服务端。不会打开任何网络端口 — 所有通信都通过标准输入/输出流进行。 ### Claude Desktop 配置 添加到 `claude_desktop_config.json`: ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/您的/文档/项目/路径" } } } ``` ### Cursor / Windsurf 配置 ```json { "command": "npx @docmd/core mcp", "transport": "stdio" } ``` ## 可用工具 | 工具 | 描述 | | :--- | :--- | | **`search_docs`** | 对所有文档文件进行全文搜索。 | | **`read_doc`** | 通过相对路径读取文档的原始 Markdown 内容。 | | **`validate_docs`** | 对所有 Markdown 文件执行链接校验。 | | **`get_llms_context`** | 返回完整的 `llms-full.txt` 上下文内容。 | ## 协议详情 docmd 实现了 MCP 规范(协议版本 `2025-03-26`): - **传输**: `stdio` — 通过 stdin/stdout 传输 JSON-RPC 2.0 消息 - **诊断**: 日志输出到 `stderr` - **生命周期**: `initialize` → `notifications/initialized` → 工具调用 - **Ping**: 响应 `ping` 请求,返回 `{}`,用于连接健康检查 ## 隐私与安全 - **仅限本地**: 服务端作为子进程运行 — 无网络暴露 - **沙箱隔离**: 文件操作限制在项目工作目录内 - **无遥测**: 不会向任何地方发送数据 ## 互补功能 - **`llms.txt` / `llms-full.txt`**: 由 `llms` 插件在构建时生成。 - **复制上下文组件**: 浏览器按钮,将页面内容复制为 AI 优化格式。 - **SKILL.md**: 由 `docmd init` 生成的 Agent 指令手册。指向 [docmd-skills](external:https://github.com/docmd-io/docmd-skills)。 --- ## [Node.js API](https://docs.docmd.io/zh/api/node-api/) --- title: "Node.js API" description: "将 docmd 的构建引擎集成到你的自定义 Node.js 脚本和自动化流水线中。" --- 对于高级工作流,你可以直接在自己的 Node.js 应用程序中导入并使用 `docmd` 构建引擎。这对于自定义 CI/CD 流水线、自动化文档生成或为特定环境扩展 `docmd` 非常理想。 ## 安装 确保你的项目中安装了 `@docmd/core`: ```bash npm install @docmd/core ``` ## 核心函数 ### `buildSite(configPath, options)` 主要的构建函数。它处理配置加载、Markdown 解析和资源生成。 ```javascript import { buildSite } from '@docmd/core'; async function runBuild() { await buildSite('./docmd.config.json', { isDev: false, // 设置为 true 以启用监视模式逻辑 offline: false, // 设置为 true 以优化 file:// 访问 zeroConfig: false // 设置为 true 以跳过配置文件检测 }); } ``` ### `buildLive(options)` 生成基于浏览器的 **实时编辑器 (Live Editor)** 捆绑包。 ```javascript import { buildLive } from '@docmd/core'; async function generateEditor() { await buildLive({ serve: false, // true 启动本地服务器;false 生成静态文件 port: 3000 // 如果 serve 为 true,则指定自定义端口 }); } ``` ## 示例:自定义流水线 你可以封装 `docmd` 来创建复杂的文档工作流。 ```javascript import { buildSite } from '@docmd/core'; import fs from 'fs-extra'; async function deploy() { // 1. 生成动态内容 await fs.writeFile('./docs/dynamic.md', '# Generated Content'); // 2. 执行 docmd 构建 await buildSite('./docmd.config.json'); // 3. 移动输出结果 await fs.move('./site', './public/docs'); } ``` ::: callout tip 编程式 API 与 **AI 驱动的文档** 高度兼容。代理可以在内容更新后触发构建以验证完整性,并自主管理部署。 ::: ## 插件 API (`@docmd/api`) `@docmd/api` 软件包是插件系统的专属家园。它提供钩子注册、WebSocket RPC 调度、源码编辑工具以及 **集中式 URL 实用程序**。 ```bash npm install @docmd/api ``` ### URL 实用程序 插件应使用这些集中式实用程序,而不是编写自己的 URL 逻辑。 #### `outputPathToSlug(outputPath)` 将构建引擎输出路径转换为干净的目录样式 slug。 ```javascript import { outputPathToSlug } from '@docmd/api'; outputPathToSlug('guide/index.html'); // → 'guide/' outputPathToSlug('index.html'); // → '/' outputPathToSlug('de/v1/api/index.html'); // → 'de/v1/api/' ``` #### `outputPathToPathname(outputPath)` 转换为根相对路径名。 ```javascript import { outputPathToPathname } from '@docmd/api'; outputPathToPathname('guide/index.html'); // → '/guide/' outputPathToPathname('index.html'); // → '/' ``` #### `outputPathToCanonical(outputPath, siteUrl)` 构建完整的规范 URL。 ```javascript import { outputPathToCanonical } from '@docmd/api'; outputPathToCanonical('guide/index.html', 'https://example.com'); // → 'https://example.com/guide/' ``` #### `sanitizeUrl(url)` 折叠双斜杠(协议之后的除外)。 ```javascript import { sanitizeUrl } from '@docmd/api'; sanitizeUrl('https://example.com//path/'); // → 'https://example.com/path/' sanitizeUrl('/foo//bar/'); // → '/foo/bar/' ``` #### `buildAbsoluteUrl(base, localePrefix, versionPrefix, pagePath)` 构建带有语言环境和版本前缀的绝对 URL。 ```javascript import { buildAbsoluteUrl } from '@docmd/api'; buildAbsoluteUrl('/', 'de/', 'v1/', 'guide/'); // → '/de/v1/guide/' ``` #### `resolveHref(href)` 将用户编写的 href 规范化为干净的 URL。处理 `.md` 剥离、尾随斜杠、`external:` 和 `raw:` 前缀。 ```javascript import { resolveHref } from '@docmd/api'; resolveHref('overview.md'); // → { href: 'overview/', isExternal: false, isRaw: false } resolveHref('external:https://github.com/docmd-io/docmd'); // → { href: 'https://github.com/docmd-io/docmd', isExternal: true, isRaw: false } resolveHref('raw:docs/readme.md'); // → { href: 'docs/readme.md', isExternal: false, isRaw: true } ``` ### 预计算的页面 URL 每个页面对象都包含预计算的 URL 数据。插件可以直接读取这些数据——无需计算。 ```javascript export async function onPostBuild({ pages, config }) { for (const page of pages) { console.log(page.urls.slug); // "guide/" console.log(page.urls.canonical); // "https://example.com/guide/" console.log(page.urls.pathname); // "/guide/" } } ``` | 属性 | 类型 | 描述 | |:---------|:-----|:------------| | `slug` | `string` | 干净的目录样式 slug (例如, `guide/` 或 `/`) | | `canonical` | `string` | 完整规范 URL (仅当设置了 `config.url` 时) | | `pathname` | `string` | 根相对路径 (例如, `/guide/`) | > **向后兼容性:** `@docmd/api` 中的所有导出也从 `@docmd/core` 中重新导出,因此现有代码可以继续运行而无需更改。建议新项目直接从 `@docmd/api` 导入。 ### `createActionDispatcher(hooks, options)` 创建一个调度程序,将 WebSocket RPC 消息路由到插件动作/事件处理程序。 ```javascript import { createActionDispatcher } from '@docmd/api'; const dispatcher = createActionDispatcher( { actions: myPlugin.actions, events: myPlugin.events }, { projectRoot: '/path/to/project', config, broadcast } ); const { result, reload } = await dispatcher.handleCall('my-action', payload); ``` ### `createSourceTools({ projectRoot })` 创建用于操作 markdown 文件的源编辑实用程序。 ```javascript import { createSourceTools } from '@docmd/api'; const source = createSourceTools({ projectRoot: '/path/to/project' }); // 获取特定行范围的块信息 const block = await source.getBlockAt('docs/page.md', [10, 12]); // 使用语法标记包装文本 await source.wrapText('docs/page.md', [10, 12], 'important', 0, '**', '**'); ``` ### `loadPlugins(config, options)` 加载、验证并注册配置中声明的所有插件。返回填充好的钩子注册表。 ```javascript import { loadPlugins, hooks } from '@docmd/api'; const registeredHooks = await loadPlugins(config, { resolvePaths: [__dirname] // 帮助解析 pnpm 工作区中的插件 }); ``` ### 类型导出 对于 TypeScript 插件作者,可以使用以下类型: ```typescript import type { PluginModule, // 完整插件合约接口 PluginDescriptor, // 插件元数据(名称、版本、能力) PluginHooks, // 钩子注册表形状 PageContext, // 传递给构建钩子的上下文(sourcePath、html 等) Capability, // 钩子类别声明(init、body、actions 等) ActionContext, // 传递给动作/事件处理程序的上下文 ActionHandler, // 动作处理程序签名 EventHandler, // 事件处理程序签名 SourceTools, // 源编辑工具接口 BlockInfo, // getBlockAt 返回的块信息 TextLocation, // findText 返回的文本位置 } from '@docmd/api'; ``` --- ## [工具对比](https://docs.docmd.io/zh/comparison/) --- title: "工具对比" description: "docmd 与 Docusaurus、VitePress、MkDocs、Starlight、Mintlify 的真实数据对比。" --- 你选过文档工具,将来还会再选。这里是真正重要的指标,以及 docmd 的定位。 ## 3 秒开始写作,而不是折腾 30 分钟 ::: tabs == tab "docmd" ```bash npx @docmd/core dev ``` 完成。文档已上线。无需配置文件,无需项目脚手架,无需陷入依赖地狱。 == tab "Docusaurus" ```bash npx create-docusaurus@latest my-site classic cd my-site npm install npm start ``` 四条命令,`node_modules` 占用约 250MB,还得先编辑 `docusaurus.config.js` 才能做任何有用的事。 == tab "VitePress" ```bash npx vitepress init ``` 回答 5 个问题,生成配置文件,再运行 `vitepress dev`。流程还算简洁,但仍需脚手架。 == tab "MkDocs" ```bash pip install mkdocs-material mkdocs new my-site && cd my-site mkdocs serve ``` Python 生态。渲染第一个页面之前,你需要 `pip`、虚拟环境和一个 `mkdocs.yml`。 ::: ## 体积差距是真实存在的 读者不应该为了看一段文字就下载整个 React 应用。以下是 50 页站点浏览器实际接收的数据量: | 生成器 | 首次加载总量 | JS 体积 | CSS 体积 | |:----------|:------------------:|:----------:|:----------:| | **docmd** | **~18 KB** | ~12 KB | ~6 KB | | MkDocs Material | ~40 KB | ~25 KB | ~15 KB | | VitePress | ~50 KB | ~35 KB | ~15 KB | | Mintlify | ~120 KB | ~80 KB | ~40 KB | | Docusaurus | ~250 KB | ~200 KB | ~50 KB | ::: callout tip "为什么这很重要" icon:lightbulb 中端手机上每 100 KB JavaScript 需要约 50ms 解析时间。docmd 只有 12 KB JS,即使在 3G 网络下文档也能即时加载。Docusaurus 为相同内容传输了 16 倍以上的 JavaScript。 ::: ## 构建速度 在 M1 MacBook Air 上构建同一个 50 页站点: | 生成器 | 冷启动构建 | 热重载 (dev) | |:----------|:----------:|:-----------------:| | **docmd** | **~1.2s** | **~80ms** | | VitePress | ~2.5s | ~150ms | | MkDocs Material | ~3.0s | ~500ms | | Docusaurus | ~15s | ~2s | docmd 的重建速度极快,页面刷新比切换窗口还快。 ## 真正能用的多语言支持 这是大多数工具的软肋。你添加了 6 种语言,翻译了 3 个印地语页面,然后用户在每个未翻译的页面上都遇到 404。 | 功能 | docmd | VitePress | Docusaurus | Starlight | |:-----------|:-----:|:---------:|:----------:|:---------:| | 未翻译页面回退到默认语言 | ✅ | ❌ (404) | ❌ (404) | ✅ | | 显示本地化的"未翻译"提示 | ✅ | ❌ | ❌ | ✅ | | 语言切换器中自动隐藏缺失语言 | ✅ | ❌ | ❌ | ❌ | | 即时页面存在性检查(无需网络请求) | ✅ | ❌ | ❌ | ❌ | | 版本控制与 i18n 同时使用 | ✅ | ❌ | ❌ | ❌ | | 零配置(无需自定义 React/Vue) | ✅ | 部分支持 | ❌ | ✅ | ::: callout warning "VitePress 和 Docusaurus 的实际情况" icon:info 如果读者切换到印地语而该页面尚未翻译,他们会看到 **404 错误**。唯一的解决方案是服务器端重定向或编写自定义 React/Vue 组件。docmd 在构建阶段处理这个问题——缺失的语言在切换器中显示"N/A"标记,未翻译的页面会静默回退并显示一个本地化的提示框。 ::: ## 工作区支持 在同一域名下维护多个产品文档的团队,需要各自独立的版本、导航和发布周期。大多数工具要么让你维护多个独立站点,要么在插件系统里凑合。 | 功能 | docmd | Docusaurus | VitePress | MkDocs | Starlight | |:-----------|:-----:|:----------:|:---------:|:------:|:---------:| | 原生工作区支持 | ✅ | 插件 | ❌ | 插件 | ❌ | | 每个项目只需一行配置 | ✅ | ❌ | ❌ | ❌ | ❌ | | 每个项目独立版本控制 | ✅ | ✅ | ❌ | ❌ | ❌ | | 每个项目独立多语言 | ✅ | ❌ | ❌ | ❌ | ❌ | | 跨项目共享静态资源 | ✅ | ❌ | ❌ | ❌ | ❌ | | 单一 `site/` 输出(无需反向代理) | ✅ | ❌ | ❌ | ❌ | ❌ | | 零配置自动检测 | ✅ | ❌ | ❌ | ❌ | ❌ | ::: callout info "docmd 的实现方式" icon:info ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "Docs" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK" } ] } } ``` 每个项目目录有自己的 `docmd.config.json`。一次 `npx @docmd/core build` 生成一个可直接部署的目录——无需反向代理、无需 nginx、无需独立 CI 流水线。 ::: Docusaurus 通过多实例插件实现类似功能,但配置复杂——每个实例需要单独的插件入口、侧边栏文件和手动路由配置。MkDocs 需要第三方 `mkdocs-monorepo-plugin`。VitePress、Starlight 和 Mintlify 均不支持原生工作区。 ## 完整功能对比 | 功能 | docmd | Docusaurus | VitePress | MkDocs Material | Starlight | Mintlify | |:--------|:-----:|:----------:|:---------:|:---------------:|:---------:|:--------:| | **零配置启动** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **所需配置文件** | 无 | `docusaurus.config.js` | `config.mts` | `mkdocs.yml` | `astro.config.mjs` | `mint.json` | | **工作区支持** | ✅ | 插件 | ❌ | 插件 | ❌ | ❌ | | **SPA 导航** | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | **原生版本控制** | ✅ | ✅ | ❌ | 插件 | ❌ | ✅ | | **原生多语言** | ✅ | ✅ | 手动 | 插件 | ✅ | ✅ | | **内置搜索** | ✅ | ❌ (Algolia) | ✅ | ✅ | ✅ | 云端 | | **llms.txt** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **MCP 服务端** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Agent 技能** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **Docker 镜像** | ✅ | ❌ | ✅ | ❌ | ❌ | N/A | | **页内评论** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | **PWA 支持** | ✅ | 社区插件 | ❌ | ❌ | ❌ | ❌ | | **自托管** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | **部署配置生成** | ✅ | ❌ | ❌ | ❌ | ❌ | N/A | ## 配置复杂度 实现版本控制、多语言、搜索和站点地图所需的配置行数: | 生成器 | 配置行数 | 所需文件数 | |:----------|:------------:|:--------------:| | **docmd** | **约 15 行** | 1 (`docmd.config.json`) | | MkDocs Material | ~50 行 | 1 + 插件 | | VitePress | ~80 行 | 1 + 主题目录 | | Docusaurus | ~120 行 | 3+ 个配置文件 | ## 质量保证 docmd 附带一套完整的测试套件,通过 **85 项断言**验证 **25 个独立场景**——涵盖每项功能的单独测试和组合测试。每个版本发布前必须通过全部 85 项断言和 13 项内部安全检查。 ::: callout tip "自己跑一遍测试" icon:lightbulb ```bash git clone https://github.com/docmd-io/docmd.git cd docmd && node scripts/brute-test.js ``` ::: 同类文档生成器中,没有任何一个在源码中公开了同等规模的端到端功能测试套件。 --- ## [布局与 UI 区域](https://docs.docmd.io/zh/configuration/layout-ui/) --- title: "布局与 UI 区域" description: "通过管理头部、侧边栏和功能 UI 插槽来控制界面结构。" --- 一个标准页面包含六个主要功能区域: 1. **菜单栏**:用于全局站点链接的全宽顶部导航栏。 2. **头部**:一个持久的辅助栏。它包含页面标题和工具按钮。 3. **侧边栏**:主要导航树,通常在左侧。 4. **内容区**:中心的 Markdown 渲染区域。包含**面包屑**。 5. **目录(TOC)**:右侧当前页面的标题导航。 6. **页脚**:底部版权、品牌和全站链接区域。 ## 全局组件配置 引擎使用模块化布局系统。在 `docmd.config.json` 的 `layout` 部分配置大多数 UI 区域。 ### 菜单栏 菜单栏提供高层导航层。支持品牌标题、常规链接和嵌套下拉菜单。 * **位置**:固定在 `top` 或内联在 `header` 中。 * **文档**:有关架构和样式,请参阅[菜单栏配置](menubar.md)。 ### 页面头部 头部显示页面标题、面包屑和工具菜单。 * **控制**:通过 `layout.header` 全局启用或禁用头部。通过 `layout.breadcrumbs` 切换面包屑。 * **覆盖**:在你的[页面 Frontmatter](../content/frontmatter.md) 中使用 `hideTitle: true` 来本地隐藏标题区域。 ### 复制小部件(AI 集成) 为了方便开发者和 LLM Agent 处理你的文档,docmd 在面包屑导航栏中提供了集成的复制按钮。这些按钮允许用户快速复制页面的原始 Markdown 内容,或合并后的 LLM 上下文。 在 `docmd.config.json` 的 `theme.copyWidgets` 设置块下配置这些按钮: ```json { "theme": { "copyWidgets": { "enabled": true, "raw": true, "context": true } } } ``` * `enabled`:设置为 `false` 可以完全禁用复制小部件栏。 * `raw`:设置为 `false` 可以隐藏“复制 Markdown”按钮。 * `context`:设置为 `false` 可以隐藏“复制上下文”按钮。 ### 工具菜单(选项菜单) `optionsMenu` 将**全局搜索**、**主题切换**和**赞助链接**等核心实用功能分组。 ```json { "layout": { "optionsMenu": { "position": "header", "components": { "search": true, "themeSwitch": true, "sponsor": "https://github.com/sponsors/mgks" } } } } ``` ::: callout info "自动回退" icon:sparkles 如果所选位置针对的是已禁用的容器,引擎会将选项菜单移动到 `sidebar-top`。这确保实用功能保持可访问。 ::: ### 侧边栏与导航 侧边栏是主要导航树。在配置或外部 JSON 文件中定义其结构。 * **行为**:支持动画、可折叠组和自动路径保留。 * **文档**:请参阅[导航配置](navigation.md)。 ### 页脚 引擎为你的网站页脚提供 **minimal** 和 **complete** 布局。 ```json { "layout": { "footer": { "style": "complete", "description": "使用 docmd 构建的文档。", "branding": true, "columns": [ { "title": "社区", "links": [ { "text": "GitHub", "url": "https://github.com/docmd-io/docmd" } ] } ] } } } ``` ::: callout tip "界面层级" icon:lightbulb 将你的**菜单栏**用于全局链接。将你的**侧边栏**用于逻辑文档结构。AI 代理依靠这个层级来理解模块之间的关系。 ::: --- ## [国际化](https://docs.docmd.io/zh/configuration/localisation/) --- title: "国际化" description: "通过语言区域优先路由、翻译导航和自动降级回退,以多种语言提供文档服务。" --- 为你的文档站点添加多语言支持。docmd 以各自的 URL 前缀提供每种语言区域的内容,翻译系统 UI 字符串,并在缺少翻译时优雅地回退。 ## 在配置中添加语言 ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "hi", "label": "हिन्दी" }, { "id": "zh", "label": "中文" } ] } } ``` `default` 语言区域在站点根路径(`/`)渲染。其他所有区域在 `/{id}/` 渲染。你可以自由选择 ID、标签以及哪个区域为默认值 - - 没有任何硬编码假设。如果想以印地语为默认语言,设置 `default: 'hi'`,印地语将在 `/` 渲染,英语在 `/en/` 渲染。 | 键 | 类型 | 说明 | |:----|:-----|:------------| | `default` | `string` | 在 `/` 渲染的区域 ID。省略时默认为第一个区域。 | | `locales` | `array` | 区域对象列表。每个对象必须包含 `id`。 | | `position` | `string` | 语言切换器的显示位置。`options-menu`(默认)、`sidebar-top` 或 `sidebar-bottom`。 | 每个区域对象可包含以下字段: | 键 | 类型 | 默认值 | 说明 | |:----|:-----|:--------|:------------| | `id` | `string` | - | 你选择的任意标识符(如 `en`、`hi`、`fr-ca`)。用作文件夹名称和 URL 前缀。必填。 | | `label` | `string` | 同 `id` | 语言切换器中显示的名称。 | | `dir` | `string` | `ltr` | 文字方向。阿拉伯语、希伯来语等设为 `rtl`。 | | `translations` | `object` | `{}` | 自定义 UI 字符串覆盖(参见 [自定义 UI 字符串](./ui-strings))。 | ## URL 结构 默认区域没有 URL 前缀。非默认区域嵌套在 `/{id}/` 下。与[版本控制](../versioning)结合使用时,URL 格式为 `/{locale}/{version}/page`。 ``` / ← 默认区域,当前版本 /getting-started ← 默认区域页面 /05/ ← 默认区域,旧版本 /hi/ ← 非默认区域,当前版本 /hi/getting-started ← 非默认区域页面 /hi/05/ ← 非默认区域,旧版本 ``` 切换语言时,语言切换器会保留当前页面和版本。版本切换器会保留当前语言区域。 ## 缺失的语言区域目录 如果在 `locales` 中声明了某个语言区域,但其源目录不存在(例如没有 `docs/hi/` 文件夹),docmd 会自动在语言切换器中**禁用**该语言区域。该语言区域仍会出现在下拉菜单中 - 带有"N/A"标记和灰色样式 - 但点击不会产生任何效果。 这可以防止在您列出计划中的语言但内容尚未准备好时出现 404 错误。 ## 语言切换器位置 <img width="500" class="with-border" src="/assets/previews/menu-versioning.webp"> 使用 `position` 选项控制语言切换器的显示位置: ```js i18n: { position: 'sidebar-top', // 默认 // ... } ``` | 位置 | 行为 | |:---------|:----------| | `options-menu` | 紧凑的地球仪图标,与主题切换和搜索并排。默认。 | | `sidebar-top` | 带标签的完整下拉菜单,位于侧边栏顶部。 | | `sidebar-bottom` | 带标签的完整下拉菜单,位于侧边栏底部。 | ## 字符串模式(仅适用于 noStyle 页面) 标准 i18n 对每种语言区域使用单独的目录(`docs/en/`、`docs/hi/`),每个目录都有自己的 markdown 文件。**字符串模式**是一种更简单的替代方案,专为 [noStyle 页面](../../content/no-style-pages.md) 设计 - 使用原始 HTML 而非 markdown 的页面。 ```json "i18n": { "default": "en", "stringMode": true, "locales": [ { "id": "en", "label": "English" }, { "id": "zh", "label": "中文" } ] } ``` 启用 `stringMode: true` 后: 1. 源文件保留在根 `docs/` 目录中(无语言子目录) 2. 默认语言区域正常在 `/` 构建 3. 对于每种非默认语言区域,docmd 会克隆渲染的 HTML,并使用 `assets/i18n/{locale}.json` 中的 JSON 文件应用**服务器端字符串替换** 4. 输出到 `/{locale}/` - 例如 `/zh/index.html` - 包含完整 SEO(hreflang 标签、正确的 `lang` 属性) 5. 如果翻译文件缺失,页面将使用默认语言文本渲染 有关 `data-i18n` 属性语法和 JSON 文件格式的完整详情,请参阅 [noStyle 字符串替换](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle)。 ::: callout warning "字符串模式不翻译 markdown 内容" icon:info 字符串替换通过在渲染的 HTML 中查找 `data-i18n` 属性来工作。标准 markdown 内容(`## Heading`、段落、列表)渲染为普通 HTML 标签,没有这些属性 - 因此替换器找不到任何内容。 - **文档站点** → 使用目录模式(默认)。每种语言区域都有自己的 markdown 文件,包含完全翻译的文章。 - **着陆页、营销网站、仪表板** → 使用字符串模式。这些是 noStyle 页面,使用自定义 HTML,你可以控制每个标签并添加 `data-i18n` 属性。 如果你的站点同时包含两者 - 例如,noStyle 着陆页 plus 文档 - 对文档使用目录模式,并在你的 noStyle 页面添加 `data-i18n` 属性。字符串模式将翻译 noStyle HTML,而目录模式处理文档内容。 ::: ## 后续步骤 - [翻译内容](translated-content.md) - 目录结构、编写翻译、导航 - [UI 字符串与 SEO](ui-strings.md) - 自定义系统文本、hreflang 标签 - [noStyle 字符串替换](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle) - noStyle 页面的 `data-i18n` 属性语法和 JSON 格式 --- ## [翻译内容](https://docs.docmd.io/zh/configuration/localisation/translated-content/) --- title: "翻译内容" description: "在语言区域子目录中组织翻译内容,支持逐文件降级回退和各区域独立导航。" --- ## 目录结构 每种语言区域(包括默认区域)在源目录中都有自己的子目录。文件夹名称与配置中的区域 `id` 匹配。 ``` docs/ ├── en/ ← 默认区域内容 │ ├── index.md │ ├── navigation.json │ └── getting-started/ │ └── installation.md ├── hi/ ← 第二语言区域 │ ├── index.md ← 翻译后的首页 │ ├── navigation.json ← 翻译后的导航标签 │ └── getting-started/ │ └── installation.md ← 翻译后的页面 └── zh/ ← 第三语言区域 └── index.md ← 仅翻译了首页 ``` 源目录是纯净的容器 - - 启用 i18n 后,根目录下不放任何内容文件,只放语言区域文件夹。 ::: callout info "文件夹名称由你决定" 文件夹名称直接来自配置中的 `id` 值。如果配置中写的是 `{ id: 'fr-ca' }`,文件夹就是 `docs/fr-ca/`。如果印地语是默认区域(`default: 'hi'`),则 `docs/hi/` 就是规范内容目录。 ::: ## 逐文件回退 无需翻译每一个页面。docmd 以**默认区域的目录**为页面规范列表。对于其他区域,会检查每个页面是否存在翻译版本: - 如果 `docs/hi/getting-started/installation.md` 存在 → 提供印地语翻译 - 如果不存在 → 提供该页面的默认区域版本 当页面发生回退时,docmd 可以显示一个翻译后的提示框,告知用户当前页面以默认语言展示。该消息可通过[UI 字符串](./ui-strings)配置自定义。 ## 仅限该区域的页面 非默认区域也可以拥有默认区域中不存在的页面。这些页面仅为该区域渲染,不会出现在其他区域中。 ## 翻译导航 每个区域目录都可以有自己的 `navigation.json`。`docmd` 使用级联优先级系统来解析侧边栏。 有关解析层级结构和视觉示例的详细信息,请参阅 [导航解析优先级](../navigation#daohang-jiexi-youxianji)。 区域的 `navigation.json` 使用相同格式: ```json [ { "title": "शुरू करें", "children": [ { "title": "इंस्टालेशन", "path": "/getting-started/installation" }, { "title": "स्थानीयकरण", "path": "/configuration/localisation" } ] } ] ``` ::: callout tip "部分导航" 只有在需要翻译标签时才需要创建区域 `navigation.json`。如果缺少该文件,将使用默认区域的导航 - - 页面仍正常渲染,只是标签未翻译。 ::: ## 版本控制与 i18n 结合使用 同时配置版本控制和 i18n 时,源目录结构如下: ``` docs/ ← 当前版本(容器) en/ ← 当前版本,默认区域 hi/ ← 当前版本,翻译区域 docs-v1/ ← 旧版本 index.md ← 旧版本内容(无区域结构) navigation.json ``` 早于 i18n 的旧版本可自动工作 - - 当没有区域子目录时,docmd 直接读取。只有默认区域渲染旧版本。如需为旧版本添加翻译,在旧版本目录中创建区域子目录: ``` docs-v1/ hi/ ← v1 的印地语翻译 index.md navigation.json ``` 输出 URL 按区域优先、版本其次的顺序嵌套: ``` / ← 默认区域,当前版本 /hi/ ← 翻译区域,当前版本 /v1/ ← 默认区域,旧版本 /hi/v1/ ← 翻译区域,旧版本 ``` --- ## [UI 字符串与 SEO](https://docs.docmd.io/zh/configuration/localisation/ui-strings/) --- title: "UI 字符串与 SEO" description: "为每种语言自定义系统界面文字,了解多语言网站的自动 SEO 标签生成。" --- ## 内置语言支持 docmd 及其官方插件内置了常见语言的翻译。配置受支持的语言后,引擎会自动翻译系统文字,例如搜索占位符、导航标签和主题切换按钮。 对于不支持的语言或需要自定义措辞,系统会回退到英文。你可以为每种语言单独覆盖任意字符串。 ## 自定义 UI 字符串 在语言配置中使用 `translations` 属性来覆盖系统文字: ```json { "i18n": { "default": "en", "locales": [ { "id": "en", "label": "English" }, { "id": "ar", "label": "العربية", "dir": "rtl", "translations": { "onThisPage": "في هذه الصفحة", "previous": "السابق", "next": "التالي", "search": "بحث", "toggleTheme": "تبديل المظهر", "editThisPage": "تعديل هذه الصفحة", "selectLanguage": "اختر اللغة", "selectVersion": "اختر الإصدار", "fallbackMessage": "هذه الصفحة غير متاحة بعد باللغة {active}. عرض اللغة الافتراضية ({default})." } } ] } } ``` 合并顺序为:**系统翻译 → 插件翻译 → 你的配置翻译**。你的配置始终具有最高优先级。 ## 可用键名 你可以直接在 docmd 源码仓库中查看所有支持的语言和翻译键。 **[在 GitHub 上查看翻译源码](external:https://github.com/docmd-io/docmd/tree/main/packages/ui/translations)** `fallbackMessage` 键支持 `{active}` 和 `{default}` 占位符,引擎在构建时会将其替换为对应的语言标签。 ## SEO 与 Hreflang docmd 会为所有语言的每个页面自动生成 `<link rel="alternate" hreflang="...">` 标签。默认语言还会额外获得 `x-default` hreflang 值。 ```html <!-- 每个页面自动生成 --> <link rel="alternate" hreflang="en" href="/"> <link rel="alternate" hreflang="x-default" href="/"> <link rel="alternate" hreflang="hi" href="/hi/"> <link rel="alternate" hreflang="zh" href="/zh/"> ``` 无需任何配置,启用 i18n 后引擎会自动注入这些标签。 ::: callout info "noStyle 页面" icon:info UI 字符串系统适用于使用主题布局的页面。对于使用自定义 HTML 的 noStyle 页面,请参阅[客户端字符串替换](../../content/no-style-pages.md#string-replacement-i18n-for-nostyle)。 ::: --- ## [菜单栏](https://docs.docmd.io/zh/configuration/menubar/) --- title: "菜单栏" description: "构建和定位你的菜单栏,管理导航链接,以及配置下拉菜单。" --- `menubar` 是一个高级导航层。它在你的网站上提供全局上下文。将其定位为固定栏在视口顶部,或相对位于页面头部上方。 ## 配置 在 `docmd.config.json` 的 `layout` 部分配置菜单栏。 ```json { "layout": { "menubar": { "enabled": true, "position": "top", "left": [ { "type": "title", "text": "品牌", "url": "/", "icon": "home" }, { "text": "文档", "url": "/docs" }, { "type": "dropdown", "text": "生态", "items": [ { "text": "GitHub", "url": "https://github.com/docmd-io/docmd" }, { "text": "实时编辑器", "url": "https://live.docmd.io" } ] } ], "right": [ { "text": "支持", "url": "/support", "icon": "help-circle" } ] } } } ``` ### 选项 | 选项 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | `enabled` | `Boolean` | `false` | 切换菜单栏可见性。 | | `position` | `String` | `'top'` | `'top'`(固定在绝对顶部)或 `'header'`(位于页面标题上方)。 | | `left` | `Array` | `[]` | 左对齐的导航项。 | | `right` | `Array` | `[]` | 右对齐的导航项。 | ## 项目类型 `left` 和 `right` 数组支持各种项目类型。 ### 1. 标准链接 最常见的项目类型。 - `text`:显示标签。 - `url`:路径或外部 URL。 - `icon`:可选的 Lucide 图标名称。 - `external`:设为 `true` 在新标签页打开。 ### 2. 标题(品牌) 设置 `type: 'title'` 以应用品牌样式(例如粗体字体)。 ### 3. 下拉菜单 设置 `type: 'dropdown'` 并提供 `items` 数组以创建嵌套菜单。 ## 工具集成 将全局搜索和主题切换托管在菜单栏中。将 `optionsMenu.position` 设为 `'menubar'`。 ```json { "layout": { "optionsMenu": { "position": "menubar" } } } ``` 选项菜单自动对齐到**右侧区域**。它出现在 `right` 数组中定义的任何链接之后。 ::: callout info "自动回退" 如果 `menubar` 被禁用,分配的实用工具会自动回退到 `sidebar-top` 位置。 ::: ## 自定义样式 在自定义样式表中使用 CSS 变量来覆盖菜单栏外观。详见[自定义 CSS 与 JS](../theming/custom-css-js.md)。 ```css :root { --menubar-height: 56px; --menubar-bg: var(--docmd-bg-secondary); --menubar-border: var(--docmd-border-color); --menubar-text: var(--docmd-text-primary); } ``` --- ## [多项目配置](https://docs.docmd.io/zh/configuration/multi-project/) --- title: "多项目配置" description: "从单个 docmd 实例构建多个独立文档项目,具有全局配置层叠和内置项目切换器。" --- 多项目配置让你从单个仓库构建和部署多个文档项目。每个项目保持自己的配置。在工作区根目录定义的全局设置自动层叠到每个项目。 ```text docs.example.com/ → 主文档 docs.example.com/sdk/ → SDK 参考 docs.example.com/cli/ → CLI 文档 ``` ## 设置 ### 1. 目录结构 每个项目一个目录。共享资源和全局配置位于仓库根目录。 ```text my-docs/ ├── assets/ ← 共享资源(所有项目继承这些) ├── main-docs/ │ ├── docmd.config.json ← 项目配置(覆盖根默认值) │ └── docs/ ← 项目内容 ├── sdk-docs/ │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← 工作区根配置 └── package.json ``` ### 2. 根工作区配置 根 `docmd.config.json` 使用 `workspace` 键。任何顶层键(例如 `theme`、`menubar`、`logo`)作为每个项目的**全局默认值**。 ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "文档" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK 参考" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg" }, "menubar": [ { "text": "GitHub", "url": "https://github.com/my-org/my-repo", "external": true } ] } ``` #### `workspace` 选项 | 键 | 类型 | 描述 | | :-- | :--- | :---------- | | `projects` | `Array` | 项目条目列表。至少一个必须使用 `prefix: "/"`。 | | `switcher` | `Object` | 控制[项目切换器](#项目切换器)的可见性和位置。 | #### 项目条目字段 | 键 | 类型 | 必需 | 描述 | | :-- | :--- | :------- | :---------- | | `prefix` | `String` | ✅ | URL 前缀。根项目使用 `"/"`。 | | `src` | `String` | ✅ | 包含项目内容和可选 `docmd.config.json` 的目录路径(相对于 CWD)。 | | `title` | `String` | - | 在项目切换器 UI 中显示的名称。 | ### 3. 项目级配置 每个项目目录可以有自己的 `docmd.config.json`。在这里定义的设置**覆盖**工作区根默认值。 ```json { "title": "SDK 参考", "src": "docs", "plugins": { "search": {}, "openapi": {} } } ``` 如果未找到本地配置文件,引擎将使用工作区默认值应用零配置自动路由。 ### 4. 全局配置层叠 在工作区根配置中定义的任何键自动应用于每个项目。项目配置可以选择性地覆盖这些全局设置。 | 层级 | 优先级 | | :---- | :--------- | | 根工作区配置 | 最低(首先应用作为默认值) | | 项目 `docmd.config.json` | 更高(覆盖根默认值) | | 项目 `navigation.json` | 最高(导航始终以此为准) | --- ## [导航配置](https://docs.docmd.io/zh/configuration/navigation/) --- title: "导航配置" description: "构建你的侧边栏、分类链接,并为读者和搜索引擎配置图标。" --- 编译器提供对你网站导航的明确控制。清晰的导航层级创建了逻辑阅读序列。这优化了 SPA 体验,并为搜索索引和 AI 模型提供了清晰的上下文映射。 ## 1. 导航架构 你 `docmd.config.json` 文件中的链接对象数组控制侧边栏。每个对象是一个直接链接或嵌套分类组。 <img width="260" class="with-border" src="/assets/previews/navigation-hierarchy.webp"> ```json { "navigation": [ { "title": "概览", "path": "/", "icon": "home" }, { "title": "快速开始", "path": "/getting-started/quick-start", "icon": "rocket" } ] } ``` ## 2. 支持的属性 每个项目都支持以下设置: | 属性 | 类型 | 必需 | 描述 | | :--- | :--- | :--- | :--- | | `title` | `String` | 是 | 侧边栏菜单中显示的文本。 | | `path` | `String` | 否 | 目标 URL。相对本地路径必须以正斜杠 (`/`) 开头。 | | `icon` | `String` | 否 | 任何 [Lucide 图标](https://lucide.dev/icons) 的名称,使用 kebab-case 格式(例如 `git-branch`)。 | | `children` | `Array` | 否 | 嵌套导航项数组,用于建立子菜单。 | | `collapsible`| `Boolean`| 否 | 当为 `true` 时,用户可以展开或折叠分类文件夹。 | | `external` | `Boolean`| 否 | 当为 `true` 时,在新浏览器标签页中打开链接。 | ## 3. 组织分类组 使用两种主要分组方法构建你的侧边栏: ### 点击分组(直接页面 + 子文件夹) 为分类头部指定 `path` 以及 `children`。点击标题会加载首页并展开子链接。 ```json { "title": "云服务", "path": "/cloud/overview", "children": [ { "title": "AWS 设置", "path": "/cloud/aws" }, { "title": "GCP 设置", "path": "/cloud/gcp" } ] } ``` ### 静态标签(仅分类头部) 省略 `path` 参数。头部作为不可点击的标题来分组相关链接。用于在没有一个着陆页的情况下划分主要技术分类。 ```json { "title": "格式与元素", "icon": "layout-grid", "children": [ { "title": "语法指南", "path": "/content/syntax" }, { "title": "丰富容器", "path": "/content/containers" } ] } ``` ## 4. 自动面包屑 引擎为每个页面自动生成上下文面包屑。这些直接显示在主页面头部上方,以帮助快速定位。 <img width="500" class="with-border" src="/assets/previews/navigation-breadcrumb.webp"> ### 关键行为 * **自动解析**:引擎通过导航树追踪活动路由来构建层级结构。 * **活动指示器**:当前页面是最后一个未链接的面包屑项目。 * **移动端优化**:面包屑在小屏幕上会简化或动态隐藏以节省屏幕空间。 ### 禁用面包屑 面包屑默认启用。更新你的网站布局选项以全局禁用它们: ```json { "layout": { "breadcrumbs": false } } ``` ## 5. 导航解析层叠 编译器使用"最近文件获胜"的层叠解析系统。这支持多个版本或语言,而不会使你的全局配置膨胀。 ```text my-project/ ├── docmd.config.json [级别 3:全局配置] - 默认后备 ├── docs-v1.0/ │ ├── navigation.json [级别 2:版本导航] - 覆盖全局 │ └── zh/ │ └── navigation.json [级别 1:语言导航] - 绝对优先 ``` 1. **级别 1:语言特定**(语言文件夹内的 `navigation.json`):覆盖此特定语言和版本的所有设置。 2. **级别 2:版本特定**(版本文件夹内的 `navigation.json`):覆盖此版本在所有语言中的全局配置。 3. **级别 3:全局配置**(`config.navigation`):中央配置文件中的基础后备定义。 ### 智能断链预防 引擎在级别 2 或 3 导航后备时自动检查目标文件是否存在。缺失的文件会动态从侧边栏中过滤掉。这消除了旧版本或缺失翻译的断链。 ## 6. 图标集成 编译器包含完整的 **Lucide 图标** 系统。使用官方 Lucide 名称(kebab-case 格式,例如 `settings`、`folder-open`、`book-marked-line`)来应用图标。 ::: callout tip "优化侧边栏标签" icon:sparkles 保持侧边栏标题清晰且描述性强。简洁的导航结构允许 AI 代理从编译的 `llms.txt` 提要轻松解析你的站点地图。 ::: --- ## [配置概览](https://docs.docmd.io/zh/configuration/overview/) --- title: "配置概览" description: "配置 docmd.config.json 以管理品牌、自定义模式、路由、布局行为和构建引擎。" --- `docmd.config.json` 文件是你工作区的核心配置。它控制网站样式、侧边栏层级、多语言详情和编译器选项。 ## 1. 配置架构 JSON 是标准配置格式。这允许引擎工作池之间的高性能序列化。 但是,如果你需要动态 JavaScript 逻辑,`docmd.config.js` 和 `docmd.config.ts` 仍然完全支持。 ```json { "title": "My Project", "url": "https://docs.myproject.com", "src": "docs", "out": "site", "base": "/" } ``` ## 2. 核心设置 这些顶层参数配置编译器的输入和输出基础。 | 参数 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `title` | `String` | `"Documentation"` | 你的网站的正式名称。显示在导航头部和浏览器标题标签中。 | | `url` | `String` | `null` | 你的规范生产 URL。对 SEO 验证、站点地图索引和 OpenGraph 元数据至关重要。 | | `src` | `String` | `"docs"` | 包含源 Markdown (.md) 文件的文件夹的相对路径。 | | `out` | `String` | `"site"` | 编译器写入优化后的生产静态网站的相对路径。 | | `base` | `String` | `"/"` | 你网站的根基础路径(例如,如果托管在子文件夹中,设置为 `/docs/`)。 | | `tmp` | `String` | `null` | 临时编译文件和缓存的自定义目录。默认为隔离的系统临时文件夹。 | | `i18n` | `Object` | `null` | 多语言参数。请参阅[本地化指南](localisation/translated-content.md)。 | | `plugins` | `Object` | `{}` | 配置标准和自定义插件的键值映射。请参阅[插件指南](../plugins/usage.md)。 | | `engine` | `String` | `"js"` | 活动的处理引擎:`"js"` 或 `"rust"`(预览)。 | ## 3. 品牌与标识 管理你的品牌在头部和浏览器标签中的显示方式。 ```json { "logo": { "light": "assets/images/logo-dark.png", "dark": "assets/images/logo-light.png", "href": "/", "alt": "Company Logo", "height": "32px" }, "favicon": "assets/favicon.ico" } ``` ## 4. UI 布局与行为 引擎提供模块化的头部和侧边栏布局。自定义功能区域。更改搜索和深色模式切换等组件的可见性。启用或禁用面包屑。 ```json { "layout": { "spa": true, "header": { "enabled": true }, "sidebar": { "collapsible": true, "defaultCollapsed": false }, "optionsMenu": { "position": "header", "components": { "search": true, "themeSwitch": true } } } } ``` 有关完整的视觉自定义选项,请参阅[布局和 UI 区域](layout-ui.md)指南。 ## 5. 核心引擎功能 微调解析器处理内容文件的方式。 ```json { "minify": true, "autoTitleFromH1": true, "copyCode": true, "pageNavigation": true, "markdown": { "breaks": true } } ``` | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `minify` | `Boolean` | `true` | 压缩输出 HTML 和 JS 结构以获得最大速度。 | | `autoTitleFromH1` | `Boolean` | `true` | 使用文件中第一个 H1 标题解析缺失的页面标题。 | | `copyCode` | `Boolean` | `true` | 在语法块右上角显示"复制代码"按钮。 | | `pageNavigation` | `Boolean` | `true` | 自动生成右侧"本页内容"目录。 | | `markdown.breaks` | `Boolean` | `true` | 标准化换行符。如果你在 80 列处换行 markdown 行,请设置为 `false`。 | ::: callout warning "独立的 editLink 已弃用" icon:alert-triangle 独立的 `editLink` 配置已弃用。请改用核心 [Git 插件](../plugins/git.md)。它提供相同的编辑链接功能以及提交时间戳和元数据日志。 ::: --- ## [重定向与 404](https://docs.docmd.io/zh/configuration/redirects/) --- title: "重定向与 404" description: "为静态部署配置基于元数据的重定向和自定义品牌化 404 错误页面。" --- 静态托管环境缺少服务端逻辑(如 Nginx 规则)来处理动态路由。docmd 生成原生 HTML 保障机制以自动处理重定向和错误状态。 ## 无服务器重定向 通过在 `redirects` 对象中定义映射,将旧 URL 的流量转发到新目标。 ```json { "redirects": { "/setup": "/getting-started/installation", "/v1/api": "/api-reference" } } ``` ### 技术实现 当你定义重定向时,引擎在旧路径创建一个包含 `<meta http-equiv="refresh">` 标签的 `index.html` 文件。此策略确保: 1. **无缝重定向**:用户立即转发到新目标。 2. **SEO 保留**:搜索引擎识别重定向以保持链接权重。 3. **分析追踪**:在重定向发生前记录页面浏览。 ## 品牌化 404 页面 当用户请求缺失的 URL 时,静态主机自动加载根 `404.html` 文件。docmd 默认生成此文件。它完美继承你网站的主题、侧边栏和 SPA 功能。 ### 自定义错误内容 在配置中个性化 404 错误消息: ```json { "notFound": { "title": "404:页面未找到", "content": "我们找不到您要查找的页面。使用侧边栏找到返回的路。" } } ``` ::: callout tip "本地开发" icon:lightbulb 开发服务器自动为缺失的文件提供你的自定义 404 页面。在本地测试错误体验。 ::: --- ## [版本管理](https://docs.docmd.io/zh/configuration/versioning/) --- title: "版本管理" description: "启用多版本文档管理,支持无缝切换、路径保留和独立构建目录。" --- docmd 具有原生版本管理引擎。同时管理和提供项目的多个版本。引擎自动处理 URL 路由、侧边栏更新和切换逻辑。 ## 目录组织 将文档组织到版本化的源文件夹中。常见模式是将活动版本保存在 `docs/`,归档版本保存在以 `docs-` 为前缀的目录中。 ```text my-project/ ├── docs/ # 最新版本(主版本) ├── docs-v1/ # 旧版本 ├── docmd.config.json ``` ## 配置 <img width="500" class="with-border" src="/assets/previews/menu-versioning.webp"> 在 `versions` 对象中定义你的版本: ```json { "versions": { "current": "v2", "position": "sidebar-top", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x(最新)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x" } ] } } ``` ## 核心功能 ### 1. 根目录 SEO(「当前」版本) `current` 版本直接在输出根目录生成(例如 `mysite.com/`)。这确保搜索流量始终落在你最新的文档上。 ### 2. 独立子目录 非当前版本自动构建到与其 `id` 匹配的子文件夹中。 * `v2(当前)` → `mysite.com/` * `v1` → `mysite.com/v1/` ### 3. 粘性切换(路径保留) docmd 在用户切换版本时保留相对路径。如果用户正在阅读 `mysite.com/getting-started` 并切换到 **v1**,他们会自动重定向到 `mysite.com/v1/getting-started`(如果该页面存在)。 ### 4. 资源隔离 每个版本继承你的全局 `assets/` 目录。docmd 在构建过程中隔离它们以防止样式泄漏或冲突。 ### 5. 版本化导航 每个版本可以维护独立的导航结构。docmd 使用级联优先级系统来解析侧边栏。 有关解析层级结构的详细信息,请参阅[导航配置](navigation.md)。 ## 最佳实践 1. **语义化 ID**:使用简洁、URL 友好的 ID,如 `v1`、`v2` 或 `beta`。 2. **导航结构一致**:跨版本保持一致的文件夹结构,以最大化"粘性切换"。 3. **统一配置**:不要为每个版本创建单独的配置文件。docmd 在单次运行中处理所有版本。 --- ## [多项目配置](https://docs.docmd.io/zh/configuration/workspaces/) --- title: "多项目配置" description: "通过单一 docmd 实例构建多个独立的文档项目,支持全局配置级联和内置的项目切换器。" --- 多项目配置允许你从一个仓库构建和部署多个文档项目。每个项目保持独立的配置。在工作区根目录定义的全局设置会自动级联到每个项目。 ```text docs.example.com/ → 主文档 docs.example.com/sdk/ → SDK 参考文档 docs.example.com/cli/ → CLI 文档 ``` ## 设置 ### 1. 目录结构 每个项目一个目录。共享资源和全局配置位于仓库根目录。 ```text my-docs/ ├── assets/ ← 共享资源(所有项目继承) ├── main-docs/ │ ├── docmd.config.json ← 项目配置(覆盖根目录默认值) │ └── docs/ ← 项目内容 ├── sdk-docs/ │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← 工作区根配置 └── package.json ``` ### 2. 根工作区配置 根目录的 `docmd.config.json` 使用 `workspace` 键。任何顶层键(例如 `theme`、`menubar`、`logo`)作为每个项目的**全局默认值**。 ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "文档" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK 参考" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg" }, "menubar": [ { "text": "GitHub", "url": "https://github.com/my-org/my-repo", "external": true } ] } ``` #### `workspace` 选项 | 键 | 类型 | 说明 | | :-- | :--- | :---------- | | `projects` | `Array` | 项目列表。至少一个必须使用 `prefix: "/"`。 | | `switcher` | `Object` | 控制[项目切换器](#项目切换器)的可见性和位置。 | #### 项目条目字段 | 键 | 类型 | 必填 | 说明 | | :-- | :--- | :------- | :---------- | | `prefix` | `String` | ✅ | URL 前缀。根项目使用 `"/"`。 | | `src` | `String` | ✅ | 目录路径(相对于 CWD),包含项目内容和可选的 `docmd.config.json`。 | | `title` | `String` | - | 在项目切换器 UI 中显示的名称。 | ### 3. 项目级配置 每个项目目录可以有自己的 `docmd.config.json`。在这里定义的设置**覆盖**工作区根目录的默认值。 ```json { "title": "SDK 参考", "src": "docs", "plugins": { "search": {}, "openapi": {} } } ``` 如果未找到本地配置文件,引擎将使用工作区默认值应用零配置自动路由。 ### 4. 全局配置级联 在工作区根配置中定义的任何键都会自动应用到每个项目。项目配置可以选择性地覆盖这些全局设置。 | 层级 | 优先级 | | :---- | :--------- | | 根工作区配置 | 最低(首先应用作为默认值) | | 项目 `docmd.config.json` | 较高(覆盖根默认值) | | 项目 `navigation.json` | 最高(导航始终优先) | **示例**:在根目录定义一次全局 `theme` 和 `menubar`。每个项目只需设置 `title`、`src` 和自己的 `plugins`。 ::: callout info "导航优先级" icon:info 项目级的 `navigation.json` 文件**始终优先于**工作区根配置中定义的任何 `navigation` 数组。如果两者都不存在,docmd 会回退到自动目录扫描。 ::: ## 项目切换器 项目切换器呈现一个精简的 UI 组件,用于在工作区项目之间导航。 ### 配置 ```json { "workspace": { "switcher": { "enabled": true, "position": "sidebar-top" } } } ``` | 位置 | 说明 | | :------- | :---------- | | `sidebar-top`(默认) | 固定在侧边栏顶部,导航上方。 | | `sidebar-bottom` | 固定在侧边栏底部。 | | `options-menu` | 集成到头部选项菜单中,与搜索和主题切换器并排。 | 仅当定义了两个或更多项目时,切换器才会渲染。 ## 资源 ### 共享资源 将图标、favicon 和全局 CSS 放在根目录的 `assets/` 中。引擎会在 `dev` 和 `build` 期间自动将这些复制到每个项目的输出中。 ### 项目特定资源 每个项目可以有自己的 `assets/` 目录。当文件名冲突时,项目资源优先于共享资源。 ## 构建与开发 ### 开发服务器 ```bash npx @docmd/core dev ``` 构建所有项目并从单个端口提供文件服务。文件更改会触发**有针对性的、按项目的**重新构建——只有修改后的项目会重新渲染,而不是整个工作区。根配置更改会触发完整的工作区重新构建。 ### 生产构建 ```bash npx @docmd/core build ``` 输出单个静态目录。所有项目合并到各自的子路径中。无需反向代理或复杂的 CI 管道。 ## 规则与约束 1. **必须包含根项目**:恰好一个项目必须使用 `prefix: "/"`。 2. **前缀唯一**:每个项目必须使用唯一的 URL 前缀。 3. **仅根目录配置 `out`**:只有根工作区配置控制输出目录。子项目配置不得定义 `out`。 4. **无前缀冲突**:如果根项目有一个名为 `sdk/` 的文件夹,而另一个项目使用 `prefix: "/sdk"`,引擎会发出冲突警告。前缀项目始终获胜。 ## 从旧配置迁移 0.8.3 之前的 `projects` 数组语法和其他旧配置键会自动规范化为现代 `workspace` 架构以保持向后兼容性。 虽然手动更新不是严格必需的,但你可以使用 CLI 自动升级配置文件到现代架构。 ::: callout tip "一键迁移" icon:lightbulb 运行 `npx @docmd/core migrate --upgrade` 自动将根配置重写为当前架构。 ::: --- ## [零配置 (Zero-Config)](https://docs.docmd.io/zh/configuration/zero-config/) --- title: "零配置 (Zero-Config)" description: "了解 docmd 的启发式引擎如何自动结构化你的站点,而无需任何配置文件。" --- `docmd` 拥有智能的启发式引擎,旨在自动解析和结构化你的文档。你可以直接开始编写、预览和翻译你的文档,而无需编写任何配置。 ## 工作原理 在没有 `docmd.config.json` 文件的情况下运行时,引擎会自动触发 **零配置模式 (Zero-Config Mode)**。它会扫描工作区目录以查找内容并应用以下启发式规则: ### 1. 源目录检测 引擎会按顺序在以下候选目录中寻找文档文件: 1. `docs/` 2. `src/docs/` 3. `documentation/` 4. `content/` 5. `.` (根目录回退) 如果找到其中一个候选目录且包含 Markdown 文件,它就会被选为源目录。如果没有找到候选目录,但项目根目录下有 Markdown 文件,则直接使用根目录(自动忽略 `node_modules`、`.git` 以及输出文件夹如 `site/`、`dist/` 和 `out/`)。 如果完全没有找到文档内容,`docmd` 会自动初始化一个全新的默认脚手架结构。 ### 2. 版本与语言环境启发式 引擎会扫描文件夹结构以动态提取版本控制和本地化元数据: - **版本**:匹配 `v[0-9]+`(例如 `v1.0`,`v08`)的子目录被解析为文档版本。 - **语言环境**:具有两位字母语言代码(例如 `en`,`de`,`zh`)的子目录被视为本地化变体。 - **结构提取**:最高版本被指定为当前版本,找到的第一个语言环境(如果存在,优先考虑 `en`)被设置为默认语言。 ### 3. 自动导航路由 如果根目录没有版本或语言环境目录,引擎会通过分析文件结构动态构建导航树: - 子目录映射为导航分组。 - 标题根据文件名动态生成。例如,`getting-started.md` 会被格式化为 `Getting Started`。 - 索引文件(`index.md`,`README.md`)被路由为当前目录的落地页。 ## 零配置最佳实践 为了充分利用零配置模式,建议遵循以下结构规范: - **明确的文件命名**:使用清晰的、以连字符或驼峰式命名的文件名。自动加载器会将其转换为易读的标题。 - **基于文件夹的分组**:将相关文档放入子文件夹中,以在侧边栏中自动分组。 - **索引回退**:始终在源文件夹的根目录下放置 `index.md` 或 `README.md`,以用作落地页。 - **干净的输出路径**:如果你使用根目录 `.` 作为源目录,请将构建产物保留在默认的 `site/` 文件夹中,该文件夹会被自动忽略。 --- ## [按钮 (Buttons)](https://docs.docmd.io/zh/content/containers/buttons/) --- title: "按钮 (Buttons)" description: "通过单行语法注入用于内部路由或外部资源的呼吁操作按钮。" --- 按钮是用于突出导航的高影响力 UI 元素。与块容器不同,`button` 是**自闭合的**——它定义在单行上,不需要结束标签 `:::`。 ## 语法 ```markdown ::: button "标签" 路径 [选项] ``` ### 选项参考 | 属性 | 格式 | 描述 | | :--- | :--- | :--- | | **路径 (Path)** | `/path/` | 相对项目 URL(会自动解析以用于 SPA 导航)。 | | **外部 (External)** | `external:URL`| 在新的浏览器标签页中打开目标 URL (`target="_blank"`)。 | | **颜色 (Color)** | `color:VALUE` | 应用背景颜色(支持 CSS 名称或十六进制代码)。 | | **图标 (Icon)** | `icon:NAME` | 在按钮标签前添加 [Lucide](external:https://lucide.dev/icons) 图标。 | ## 使用示例 ### 1. 内部导航 使用相对路径以确保在 `docmd` SPA 中实现无缝、零刷新的切换。 ```markdown ::: button "安装 docmd" /getting-started/installation ``` ::: button "安装 docmd" /getting-started/installation ### 2. 外部资源链接 在 URL 前面加上 `external:` 以确保安全的外部链接。 ```markdown ::: button "查看 GitHub 仓库" external:https://github.com/docmd-io/docmd ``` ::: button "查看 GitHub 仓库" external:https://github.com/docmd-io/docmd ### 3. 语义与品牌样式 使用颜色覆盖来使按钮符合你的品牌标识或语义优先级。 ```markdown ::: button "危险操作" /delete color:crimson ::: button "成功确认" /success color:#228B22 ``` ::: button "危险操作" ./#delete color:crimson ::: button "成功确认" ./#success color:#228B22 ### 4. 带有图标的按钮 添加 Lucide 图标以增强视觉清晰度。 ```markdown ::: button "开始使用" /getting-started/installation icon:arrow-right ::: button "查看源码" external:https://github.com/docmd-io/docmd icon:github ``` ::: button "开始使用" /getting-started/installation icon:arrow-right ::: button "查看源码" external:https://github.com/docmd-io/docmd icon:github ## 关键提示:自闭合逻辑 由于按钮是自闭合的,添加结尾的 `:::` 行将终止按钮所在的 **父容器**(例如 Card 或 Tab),这可能会破坏你的布局。 **不正确的序列:** ```markdown ::: card "设置" ::: button "开始" /setup ::: <-- 错误:这将提前关闭 Card。 ::: ``` **正确的序列:** ```markdown ::: card "设置" ::: button "开始" /setup ::: <-- 正确:这将关闭 Card。 ``` --- ## [标注 (Callouts)](https://docs.docmd.io/zh/content/containers/callouts/) --- title: "标注 (Callouts)" description: "使用语义化的视觉区块突出显示关键警告、专业技巧和背景信息。" --- 标注用于隔离那些需要读者立即注意的信息。`docmd` 提供了五种语义类型,每种都具有独特的视觉样式和主题图标。 ::: callout info "迁移友好的别名" 如果您从 **VitePress** 或 **Docusaurus** 迁移,可以直接使用它们的原生语法: - `:::tip`、`:::warning`、`:::danger`、`:::info`(VitePress) - `:::note`、`:::caution`(Docusaurus) 这些别名的渲染效果与 `docmd` 等效语法完全相同。无空格语法如 `:::callout` 也同样支持。 ::: ## 语法参考 ```markdown ::: callout 类型 "可选标题" 技术内容或警告放在这里。 ::: ``` 添加可选的 `icon:` 参数,可以用任何 [Lucide](external:https://lucide.dev/icons) 图标覆盖默认的类型图标: ```markdown ::: callout info "自定义图标" icon:sparkles 此标注使用自定义图标而不是默认的 info 图标。 ::: ``` ### 支持的语义类型 | 类型 | 意图 | 视觉信号 | | :--- | :--- | :--- | | `info` | **通用数据** | 上下文背景或有用的非关键信息。 | | `tip` | **优化** | 性能捷径或“专业技巧”。 | | `warning`| **警告** | 潜在问题或需要关注的弃用功能。 | | `danger` | **危险** | 数据丢失风险、破坏性变更或系统故障。 | | `success`| **成功** | 成功配置或构建的确认。 | ## 实现展示 ### 1. 极简信息说明 ```markdown ::: callout info 旧版配置架构仍然受支持,但不再推荐使用。 ::: ``` ::: callout info 旧版配置架构仍然受支持,但不再推荐使用。 ::: ### 2. 带有自定义标题的高优先级警报 ```markdown ::: callout warning "破坏性变更目标" 自 `v0.7.0` 起,内部 WebSocket RPC 系统将正式弃用。 ::: ``` ::: callout warning "破坏性变更目标" 自 `v0.7.0` 起,内部 WebSocket RPC 系统将正式弃用。 ::: ### 3. 丰富内容组合 标注支持全方位的 Markdown,允许你在警报中嵌入按钮和代码块。 ````markdown ::: callout tip "优化的本地测试" icon:command 在开发过程中使用 preserve 标志来保留构建文件: ```bash docmd dev --preserve ``` ::: button "CLI 标志参考" /cli-commands ::: ```` ::: callout info "优化的本地测试" icon:command 使用 preserve 标志来保留构建文件: ```bash npx @docmd/core dev --preserve ``` ::: button "CLI 标志参考" ./#cli-commands ::: ::: callout tip "AI 的优先逻辑" 对于 LLM,标注充当 **高优先级锚点 (High-Priority Anchors)**。通过使用 `::: callout danger` 来记录破坏性变更或系统限制,你可以提供一个清晰的信号,即 AI 模型在推理和生成过程中必须优先处理此信息。 ::: --- ## [卡片 (Cards)](https://docs.docmd.io/zh/content/containers/cards/) --- title: "卡片 (Cards)" description: "将信息组织到带边框的视觉独特容器中,非常适合功能网格和落地页。" --- 卡片将相关内容封装到一个独特的、带边框的框架中,可选带标题,为文档提供清晰的视觉层次结构。 ## 语法参考 ```markdown ::: card "标题文本" [属性:值...] 这是卡片的主要内容区域。 ::: ``` | 参数 | 类型 | 说明 | | :--- | :--- | :--- | | **标题** | `"字符串"` | 可选的页眉标题,渲染在卡片顶部。 | | **图标** | `icon:名称` | 可选。在标题文本旁边添加一个 [Lucide](external:https://lucide.dev/icons) 图标。 | ## 示例 ### 功能亮点 使用卡片来框定具有清晰标题和图标的单一技术功能。 ```markdown ::: card "异步生成" icon:zap 核心引擎使用非阻塞 I/O 管道,可在毫秒内生成数千个页面。 ::: ``` ::: card "异步生成" icon:zap 核心引擎使用非阻塞 I/O 管道,可在毫秒内生成数千个页面。 ::: ### 丰富内容 卡片接受任何标准 Markdown,包括代码块和按钮。 ````markdown ::: card "即时国际化" 使用内置的 i18n 支持为全球受众准备文档。 ```bash npx @docmd/core add i18n ``` ::: button "国际化策略指南" /guides/localization ::: ```` ::: card "即时国际化" 使用内置的 i18n 支持为全球受众准备文档。 ```bash npx @docmd/core add i18n ``` ::: button "国际化策略指南" ./#localization ::: ### 多列布局 将多个卡片包裹在 `grids` 容器中,以获得响应式多列布局。 ```markdown ::: grids ::: grid ::: card "主节点" 主实例的配置。 ::: ::: ::: grid ::: card "从节点" 冗余从实例的配置。 ::: ::: ::: ``` ::: grids ::: grid ::: card "主节点" 主实例的配置。 ::: ::: ::: grid ::: card "从节点" 冗余从实例的配置。 ::: ::: ::: ::: callout tip "AI 的语义聚类" icon:lightbulb 在 `llms-full.txt` 流中,卡片包裹的内容被 AI 代理视为**内聚主题集群**。使用卡片来分隔不相关的概念可防止上下文泄漏,并确保 LLM 生成的摘要在逻辑上保持隔离。 ::: --- ## [更新日志](https://docs.docmd.io/zh/content/containers/changelogs/) --- title: "更新日志" description: "生成结构化、基于时间线的版本历史记录和发布说明。" --- The `changelog` container provides a specialised layout for documenting project evolution. It automatically parses date or version headers into a vertical timeline, ensuring historical updates are easily scannable. ## 语法 使用专用的 `==` 分隔符定义条目。`==` 行上的文本渲染为左侧的时间线徽章,后续内容填充相邻的时间槽。 ```markdown ::: changelog == v2.0.0 重大功能发布说明。 == v1.5.0 维护更新和安全补丁说明。 ::: ``` ## 详细示例:发布历史 更新日志在每个条目中支持丰富的 Markdown,包括列表、提示框和代码块。 ```markdown ::: changelog == v2.0.0 (2026-03-15) ### 重大系统重构 核心引擎已针对同构执行进行重新架构。 * 实现了**SPA 路由器**,实现零刷新导航。 * 引入了**同构插件**系统。 ::: callout success 此版本初始构建速度提升 40%。 ::: == v1.5.1 (2025-12-10) ### 安全补丁 * 修复了内部解析器中的高危漏洞。 * 将依赖 `flatted` 升级至 `v3.3.2`。 == v1.0.0 (2024-05-01) 首次公开发布。 ::: ``` ::: changelog == v2.0.0 (2026-03-15) ### 重大系统重构 核心引擎已针对同构执行进行重新架构。 * 实现了**SPA 路由器**,实现零刷新导航。 * 引入了**同构插件**系统。 ::: callout success 此版本初始构建速度提升 40%。 ::: == v1.5.1 (2025-12-10) ### 安全补丁 * 修复了内部解析器中的高危漏洞。 * 将依赖 `flatted` 升级至 `v3.3.2`。 == v1.0.0 (2024-05-01) 首次公开发布。 ::: ::: callout tip "为 AI 提供历史上下文" 更新日志为 AI Agent 提供时间映射。当 LLM 解析 `llms-full.txt` 上下文时,`::: changelog` 结构使其能够准确识别特定功能、破坏性变更或安全修复的引入时间,从而提高开发建议的准确性。 ::: --- ## [折叠区块 (Collapsible Sections)](https://docs.docmd.io/zh/content/containers/collapsible/) --- title: "折叠区块 (Collapsible Sections)" description: "为常见问题、深度内容和剧透内容嵌入交互式手风琴式切换按钮。" --- `collapsible` 容器创建一个交互式的、可切换的区域(手风琴)。这种模式非常适合常见问题 (FAQ)、详细的技术配置,或任何应该在不干扰主要文档流程的情况下可以访问的次要信息。 ::: callout info "VitePress 别名" 如果您从 **VitePress** 迁移,可以使用 `:::details` 作为 `:::collapsible` 的别名。无空格语法如 `:::collapsible` 也同样支持。 ::: ## 语法 ```markdown ::: collapsible [open] "标题文本" 主要内容放在这里。 ::: ``` ### 选项参考 - **`open`**: (可选) 如果指定,该区域初始化时处于展开状态。 - **`"标题"`**: 渲染在交互式切换栏上的文本。如果省略,默认显示为 "点击以展开"。 - **`icon:NAME`**: (可选) 在标题文本前添加一个 [Lucide](external:https://lucide.dev/icons) 图标。 ## 详细实现示例 ### 标准用法 (初始状态:关闭) 主要用于常见问题或降低技术页面的视觉密度。 ```markdown ::: collapsible "如何升级 docmd?" 运行 `npm update -g @docmd/core` 来获取最新的稳定引擎。 ::: ``` ::: collapsible "如何升级 docmd?" 运行 `npm update -g @docmd/core` 来获取最新的稳定引擎。 ::: ### 选择性可见 (初始状态:打开) 非常适合那些默认应该可见,但允许用户将其最小化以获得更整洁视图的区域。 ```markdown ::: collapsible open "环境先决条件" 1. Node.js v18+ (推荐 LTS) 2. PNPM 包管理器 ::: ``` ::: collapsible open "环境先决条件" 1. Node.js v18+ (推荐 LTS) 2. PNPM 包管理器 ::: ### 嵌套技术数据 折叠区块可以包含复杂的 Markdown 元素,包括语法高亮的代码块。 ````markdown ::: collapsible "分析示例 JSON 响应" ```json { "status": "success", "data": { "version": "0.6.2" } } ``` ::: ```` ::: collapsible "分析示例 JSON 响应" ```json { "status": "success", "data": { "version": "0.8.2" } } ``` ::: ::: callout tip 虽然 `collapsible` 内部的内容可能对人类用户隐藏,但它对 `docmd` 搜索索引保持完全可见,并包含在统一的 `llms-full.txt` 流中。这确保了 AI 代理可以根据隐藏的技术细节提供全面的答案,同时人类界面保持整洁并具有优先级。 ::: --- ## [URL 嵌入 (Embeds)](https://docs.docmd.io/zh/content/containers/embed/) --- title: URL 嵌入 (Embeds) description: 如何安全地将动态组件、视频和社交媒体直接嵌入到你的文档中。 --- `docmd` 原生搭载了高度优化的 **[embed-lite](external:https://github.com/mgks/embed-lite)** 解析器生态系统。这允许你将原始外部 URL 严格映射到页面上,并瞬间将它们精美地转换为完全安全、零延迟的 UI 组件! ## 支持的平台 集成引擎原生公开了针对以下网络的结构化格式化程序: * **视频生态系统:** YouTube (包括原生 9:16 Shorts 支持), Vimeo, Dailymotion, TikTok * **社交连接:** X (Twitter), Reddit, Instagram, Facebook, LinkedIn * **代码与原型:** GitHub Gists, CodePen, Figma, Google Maps * **音乐服务:** Spotify, SoundCloud ## 使用语法 你只需使用 `::: embed` 容器,后跟任何目标 URL。以下三种封闭格式是等效的: ```md ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ``` ### 标准结果示例 渲染引擎会在后台严格解析该 URL,检查验证矩阵,并将原生 HTML 节点直接结构化地注入到你的页面输出中: ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ## 降级安全 不用担心生成损坏的屏幕。如果内部解析器扫描到未经验证或严格不可用的域名配置映射,`docmd` 会优雅地降级为生成一个简单的、实心的 `<a>` 超链接按钮,明确指向目标: ```md ::: embed "https://docs.docmd.io/zh/content/containers/embed/" ``` *(接下来会生成你下面看到的内容)* ::: embed "https://docs.docmd.io/zh/content/containers/embed/" --- ## [网格 (Grids)](https://docs.docmd.io/zh/content/containers/grids/) --- title: "网格 (Grids)" description: "使用原生 markdown 容器,通过自动调整的响应式列无缝组织布局。" --- 网格在 `docmd` 中提供了一个原生的、由 markdown 驱动的布局系统。你可以利用 `grids` 容器来并排构建元素,而无需编写手动的 HTML 包装器。 列会自动调整宽度以填满可用空间,并在较小屏幕(移动设备)上逻辑地堆叠成垂直行。 ## 语法参考 ```markdown ::: grids ::: grid #### 组件 A 左侧的内容。 ::: ::: grid #### 组件 B 右侧的内容。 ::: ::: ``` ## 实际应用示例 ### 1. 并排展示功能 使用网格将关键功能并排展示,例如将结构化卡片与信息块结合。 ```markdown ::: grids ::: grid ::: card "速度 :rocket:" 建立在非阻塞 I/O 流水线上,以获得最高性能。 ::: ::: ::: grid ::: card "可扩展性 :zap:" 专为大规模 monorepos 和广泛的项目结构而设计。 ::: ::: ::: ``` ::: grids ::: grid ::: card "速度 :rocket:" 建立在非阻塞 I/O 流水线上,以获得最高性能。 ::: ::: ::: grid ::: card "可扩展性 :zap:" 专为大规模 monorepos 和广泛的项目结构而设计。 ::: ::: ::: ### 2. 布局平衡 网格将根据可用内容自动计算每列的最佳宽度(超宽屏幕上每行最多 4 个项目),并在窄视口上无缝分组行。 ::: callout tip "语义化布局" 使用 `grids` 容器可以使你的文档结构纯粹用 Markdown 编写,从而产生更整洁的源文件,并确保 LLM 完美地解释你的结构关系! ::: --- ## [英雄区块 (Hero Sections)](https://docs.docmd.io/zh/content/containers/hero/) --- title: "英雄区块 (Hero Sections)" description: "纯粹用 Markdown 构建高影响力的落地页页眉和营销亮点。" --- `hero` 容器可以创建专业且视觉冲击力强的落地页页眉。它可以处理复杂的 CSS 需求,如 **分割布局 (Split Layouts)**、**发光效果 (Glow Effects)** 和 **滑块 (Sliders)**,同时保持简洁的编写体验。 ## 基本语法 默认情况下,`hero` 会将其内容居中,非常适合横幅和简单的标题。 ```markdown ::: hero # 构建更快。 一行命令,从 Markdown 到生产文档。 ::: button "开始使用" /intro color:blue ::: ``` ## 高级布局 `hero` 容器支持专门的标志来控制其结构行为。 | 标志 | 效果 | | :--- | :--- | | `layout:split` | 将 hero 分为文本区域(左侧)和媒体区域(右侧)。在移动端垂直堆叠。 | | `layout:slider` | 将 hero 转换为具有滚动捕捉行为的水平滑块。 | | `glow:true` | 在背景中注入微妙的径向渐变发光。 | ### 分割布局 (`== side`) 使用 `== side` 分隔符来定义哪些内容放入主文本区域,哪些内容放入次要的“侧边”区域(通常是图像或视频嵌入)。 ```markdown ::: hero layout:split glow:true # docmd 2.0 同构执行。针对 AI 优化。 ::: button "快速开始" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ``` ::: hero layout:split glow:true # docmd 2.0 同构执行。针对 AI 优化。 ::: button "快速开始" /getting-started/basic-usage color:blue == side ::: embed "https://www.youtube.com/watch?v=0CSyIBHQy9g" ::: ### 滑块布局 (`== slide`) 通过在不同的内容节点之间使用 `== slide` 分隔符来创建交互式 hero 滑块。 ```markdown ::: hero layout:slider == slide # 同构核心 引擎可在任何地方渲染。 == slide # AI 优化 为 LLM 时代而生。 ::: ``` ::: hero layout:slider == slide # 同构核心 引擎可在任何地方渲染。 == slide # AI 优化 为 LLM 时代而生。 ::: ## 响应式行为 `hero` 容器默认完全响应: - 在 **桌面端**,`layout:split` 并排显示。 - 在 **移动端**,它会自动转换为居中的垂直堆叠,以确保最佳的可读性。 ## 最佳实践 1. **发光效果**:在暗黑模式网站上谨慎使用 `glow:true`,以获得高级的“霓虹灯”感。 2. **媒体类型**:分割布局的“侧边”内容非常适合 `::: embed` 组件、高质量 PNG 或原始 `<video>` 标签。 3. **CTA 放置**:始终将 `::: button` 元素放置在主“Hero 副本”部分(在 `== side` 分隔符之前),以确保它们是用户在移动端看到的第一件东西。 --- ## [自定义交互式容器](https://docs.docmd.io/zh/content/containers/) --- title: "自定义交互式容器" description: "docmd 中可用的交互式 UI 构建块的完整目录。" --- 标准的 Markdown 擅长基础文本格式化,但专业的开发文档需要丰富的结构组件来有效传达复杂的逻辑。`docmd` 通过一系列**同构容器**扩展了 Markdown,这些容器可直接渲染为响应式、高保真 UI 元素。 ::: callout tip "从其他文档引擎迁移?" `docmd` 开箱即支持 **VitePress** 和 **Docusaurus** 的语法别名。`:::tip`、`:::warning`、`:::note`、`:::details` 和 `:::caution` 等容器无需修改即可工作。所有容器也支持无空格语法(例如 `:::tabs` 而不是 `::: tabs`)。 ::: ## 块语法参考 所有容器都使用一致的块语法,确保在整个项目中拥有可预测的编写体验。 ```markdown ::: 类型 "可选页眉标题" 这是主要内容区域。 它支持 **Markdown**、图像和深层组件嵌套。 ::: ``` | 组件 | 关键字 | 主要用例 | | :--- | :--- | :--- | | **[标注](callouts.md)** | `callout` | 用于技巧、警告和警报的语义化突出显示。 | | **[卡片](cards.md)** | `card` | 用于功能网格和布局控制的有框结构块。 | | **[网格](grids.md)** | `grids` | 自动调整的多列结构组。 | | **[选项卡](tabs.md)** | `tabs` | 用于替代平台说明的交互式可切换面板。 | | **[步骤](steps.md)** | `steps` | 用于“如何操作”指南和教程的视觉数字时间线。 | | **[折叠区块](collapsible.md)** | `collapsible` | 用于 FAQ 和深度技术数据的交互式手风琴切换。 | | **[按钮](buttons.md)** | `button` | 自闭合、突出的呼吁操作导航链接。 | | **[标签](tags.md)** | `tag` | 用于版本、状态或突出的自闭合彩色标签。 | | **[英雄区块](hero.md)** | `hero` | 具有布局和滑块支持的高影响力落地页部分。 | | **[URL 嵌入](embed.md)** | `embed` | 用于视频、社交和交互式内容的安全、零延迟嵌入。 | | **[变更日志](changelogs.md)** | `changelog` | 结构化、基于时间线的版本历史和发布说明。 | | **[嵌套容器](nested-containers.md)** | - | 用于复杂、多组件布局的递归组合模式。 | ## 容器的战略重要性 容器的作用不仅仅是视觉上的点缀;它们向 `docmd` 引擎和下游 AI 代理提供高保真的 **语义信号 (Semantic Signals)**: 1. **AI 上下文映射**:将一个块标记为 `callout warning` 会明确告诉 LLM 在其推理和生成阶段优先考虑该信息。 2. **结构完整性**:将 `cards` 与标准 CSS 结合使用,可以在不离开 Markdown 环境的情况下创建复杂的落地页。 3. **源码可维护性**:消除文档源码中的“HTML 臃肿”,保持 `.md` 文件整洁且机器可读。 ## 递归组合 `docmd` 支持 **无限嵌套深度**。你可以在一个容器内组合任何其他容器,纯粹用 Markdown 构建复杂的交互式文档节点。 ```markdown ::: card "架构概览" ::: callout info 此模块利用异步 I/O 流水线。 ::: ::: button "深入核心引擎" /advanced/developer-guide ::: ``` [掌握嵌套指南](nested-containers.md) --- ## [嵌套容器](https://docs.docmd.io/zh/content/containers/nested-containers/) --- title: "嵌套容器" description: "利用 docmd 的递归解析器将卡片、标签页和提示框组合成高保真页面布局。" --- One of `docmd`’s most powerful technical capabilities is its **Recursive Parsing Engine**. You can nest components within each other infinitely to synthesize complex, interactive documentation blocks that would otherwise require deep HTML knowledge or custom templates. ## 架构规则 虽然嵌套在数学上无限,但请始终遵循**自闭合组件规则**: ::: callout warning "自闭合按钮" 由于 `::: button` 组件是自闭合的(单行),绝不要在其后添加终止 `:::` 行。否则会意外关闭容纳按钮的**父容器**,导致布局断裂。 ::: ## 技术组合示例 ### 1. 交互式资源块 将**卡片**用于结构框架,**标签页**用于特定环境的说明,**提示框**用于高亮关键信息。 ````markdown ::: card "Monorepo 快速开始" 选择你偏好的初始化方式: ::: tabs == tab "自动化" ```bash pnpm onboard ``` ::: callout success 此脚本自动处理所有包安装和构建任务。 ::: == tab "手动" 手动获取并链接核心引擎。 ::: button "前往开发者指南" /advanced/developer-guide ::: ::: ```` ### 2. 多平台教程 将**标签页**嵌套在**步骤**中是标准教程序列中提供平台特定说明的专业模式。 ```markdown ::: steps 1. **环境设置** 配置本地操作系统。 ::: tabs == tab "macOS" 确保 Homebrew 已安装并为最新版本。 == tab "Linux" 验证 `curl` 和 `bash` 是否存在。 ::: 2. **核心验证** 执行版本检查以确认连接性。 ::: ``` ::: steps 1. **环境设置** 配置本地操作系统。 ::: tabs == tab "macOS" 确保 Homebrew 已安装并为最新版本。 == tab "Linux" 验证 `curl` 和 `bash` 是否存在。 ::: 2. **核心验证** 执行版本检查以确认连接性。 ::: ## 设计约束 为保持性能和移动端响应性,请遵守以下约束: * **递归标签页**:在标签页中嵌套标签页在技术上受支持,但强烈不建议。在小视口上会造成混乱的导航"循环"。 * **顺序冲突**:如果需要在标签页内使用编号步骤,请使用标准有序列表(`1. 步骤内容`)而非 `::: steps` 容器,以避免布局冲突。 * **可读性**:虽然 `docmd` 不严格要求嵌套块的缩进,但使用 2 或 4 个空格的缩进可显著提高 Markdown 源码的可读性。 ::: callout tip "为 AI 提供知识分割" 嵌套提供清晰的**语义边界**。当 AI Agent 解析 `llms-full.txt` 流时,嵌套在 `card` 中的 `callout` 明确告知模型该提示的范围限定于该卡片的特定主题,防止上下文泄漏并提高生成响应的技术准确性。 ::: --- ## [步骤](https://docs.docmd.io/zh/content/containers/steps/) --- title: "步骤" description: "将标准有序列表转化为高冲击力的可视化时间线和教程。" --- `steps` 容器将标准 Markdown 有序列表转化为带编号的垂直时间线。专为技术教程和顺序操作指南设计。 ::: callout info "无空格语法" `::: steps` 和 `:::steps`(无空格)均原生支持,使用你喜欢的风格即可。 ::: ## 语法参考 ```markdown ::: steps 1. **步骤标题** 步骤描述放在这里。 2. **下一步** 继续步骤序列。 ::: ``` | 容器 | 说明 | | :--- | :--- | | **`::: steps`** | 父容器,将子有序列表项转化为带编号的时间线。 | | **`1. `** | 任何标准 Markdown 有序列表项都作为一个步骤。加粗每项的第一行作为标题。 | ## 示例 ### 基础工作流 ```markdown ::: steps 1. **初始化项目** 运行 `npx @docmd/core init` 搭建目录结构。 2. **编写内容** 使用标准 Markdown 文件编写文档。 3. **构建与部署** 运行 `npx @docmd/core build` 生成静态站点。 ::: ``` ::: steps 1. **初始化项目** 运行 `npx @docmd/core init` 搭建目录结构。 2. **编写内容** 使用标准 Markdown 文件编写文档。 3. **构建与部署** 运行 `npx @docmd/core build` 生成静态站点。 ::: ### 包含富内容的步骤 每个步骤可以包含代码块、标注和其他嵌套容器。 ```markdown ::: steps 1. **配置环境** 在 `docmd.config.json` 中定义项目变量。 ::: callout tip 使用 `defineConfig` 可为所有配置键启用 IDE 自动补全。 ::: 2. **生成生产构建** 执行构建命令生成高度优化的静态站点。 ```bash npx @docmd/core build ``` 3. **部署到基础设施** 将 `site/` 目录同步到 S3、Cloudflare Pages 或 Vercel。 ::: ``` ::: steps 1. **配置环境** 在 `docmd.config.json` 中定义项目变量。 ::: callout tip 使用 `defineConfig` 可为所有配置键启用 IDE 自动补全。 ::: 2. **生成生产构建** 执行构建命令生成高度优化的静态站点。 ```bash npx @docmd/core build ``` 3. **部署到基础设施** 将 `site/` 目录同步到 S3、Cloudflare Pages 或 Vercel。 ::: ::: callout tip "工作流优化" icon:lightbulb AI 模型将 `steps` 容器解读为**顺序工作流**的高保真信号。始终以**加粗标题**开头每个列表项——这让 AI Agent 能在处理实现细节之前,可靠地从 `llms.txt` 上下文中解析每个步骤的目标。 ::: --- ## [选项卡 (Tabs)](https://docs.docmd.io/zh/content/containers/tabs/) --- title: "选项卡 (Tabs)" description: "将密集、替代或多语言信息组织到可切换的交互式面板中。" --- 选项卡是在紧凑、交互式的格式中展示互斥或相关数据集(例如,“通过 NPM 与 Yarn 安装”或“macOS 与 Windows”指令)的最佳 UI 模式。 ## 语法参考 `tabs` 容器使用专门的子分隔符 `== tab "标签"`。你可以选择使用 `icon:name` 语法添加图标。 ```markdown ::: tabs == tab "标签 1" icon:rocket 第一个选项卡的内容。 == tab "标签 2" icon:settings 第二个选项卡的内容。 ::: ``` ## 实现展示 ### 1. 包管理 选项卡最常用于在单个视图中显示不同包管理器的安装说明。 ::: tabs == tab "pnpm" ```bash pnpm add @docmd/core ``` == tab "npm" ```bash npm install @docmd/core ``` == tab "yarn" ```bash yarn add @docmd/core ``` ::: ### 2. 多语言代码片段 通过分离不同的编程语言或环境来保持逻辑整洁。 ::: tabs == tab "TypeScript" icon:hexagon ```typescript import { build } from '@docmd/core'; await build('./docmd.config.json'); ``` == tab "JavaScript" icon:braces ```javascript const { build } = require('@docmd/core'); build('./docmd.config.json'); ``` ::: ## 核心能力 ### 同构延迟渲染 `docmd` 实现了 **条件资源延迟 (Conditional Resource Laziness)**。如果选项卡包含计算密集型元素(例如 **Mermaid.js** 图表或高分辨率图像),则仅在用户激活该特定选项卡时才初始化并渲染这些资源。这确保了初始页面的快速加载。 ### 状态持久化 默认的 SPA 路由器会在类似的文档页面之间跟踪活动选项卡的索引。如果用户在某一页选择了“pnpm”,并导航到另一页具有匹配选项卡结构的页面,则“pnpm”选项卡将自动保持活动状态。 ## 技术约束 | 约束 | 说明 | | :--- | :--- | | **嵌套深度** | 为了保持布局完整性,选项卡不能嵌套在其他选项卡组件内。 | | **交互冲突**| 高冲突语法:要在选项卡内嵌套“步骤”,请使用标准有序列表 (`1. 第一步`) 而不是 `::: steps` 容器。 | | **响应限制** | 建议将每个区块的选项卡数量限制在 6 个以内,以确保移动设备兼容性。 | ::: callout tip "AI 上下文映射" 在将选项卡用于代码片段时,始终直接在选项卡标签中包含目标语言(例如 `== tab "TypeScript"`)。这允许 LLM 从 `llms-full.txt` 上下文流中立即识别并提取技术相关的部分。 ::: --- ## [标签 (Tags)](https://docs.docmd.io/zh/content/containers/tags/) --- title: "标签 (Tags)" description: "使用标签容器在行内无缝标注版本、状态或突出显示短文本片段。" --- `tag` 容器是一个自闭合组件,用于直接在文本中插入小巧的药丸状徽章。与块容器不同,标签不会继承父元素(如标题)的巨大尺寸,无论放置在哪里,它们都会保留紧凑、整洁的比例。 ## 基本用法 要创建一个基本标签,只需提供你想要显示的文本: ::: tabs == tab "预览" 此功能已在 ::: tag "v0.7.4" color:blue 中添加,且运行完美。 == tab "Markdown 源码" ```markdown 此功能已在 ::: tag "v0.7.4" 中添加,且运行完美。 ``` ::: ## 自定义颜色 你可以通过提供任何有效的 CSS 颜色字符串(例如 `#ff0000`、`blue` 或 `hsl(...)`),使用 `color:` 属性来覆盖默认的标签样式。`docmd` 会自动计算出精美的淡色背景,并配以对比完美的文本和边框! ::: tabs == tab "预览" ::: tag "已弃用" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "稳定版" color:#22c55e == tab "Markdown 源码" ````markdown ::: tag "已弃用" color:#ef4444 ::: tag "Beta" color:#eab308 ::: tag "稳定版" color:#22c55e ```` ::: ## 添加图标 就像按钮和标注一样,你可以使用 `icon:` 属性轻松附加来自 `docmd` 图标库的图标。 ::: tabs == tab "预览" ::: tag "已验证" icon:check-circle color:#10b981 == tab "Markdown 源码" ````markdown ::: tag "已验证" icon:check-circle color:#10b981 ```` ::: ## 链接标签 如果你需要标签充当超链接(例如,将版本标签直接链接到其发布说明),可以使用 `link:` 属性。外部链接会被自动检测并在新标签页中打开。 ::: tabs == tab "预览" 查看最新的 ::: tag "发行说明" icon:external-link link:/release-notes/0-7-4 == tab "Markdown 源码" ````markdown 查看最新的 ::: tag "发行说明" icon:external-link link:/release-notes/0-7-4 ```` ::: ## 在标题中使用标签 因为标签是真正的行内元素,所以当用于标记主标题时,它们看起来非常华丽。它们会自动对齐到基线,而不会继承标题巨大的字体大小。 ::: tabs == tab "预览" # 搜索过滤 ::: tag "新" color:#8b5cf6 == tab "Markdown 源码" ````bash # 搜索过滤 ::: tag "新" color:#8b5cf6 ```` ::: --- ## [Frontmatter 参考](https://docs.docmd.io/zh/content/frontmatter/) --- title: "Frontmatter 参考" description: "docmd 中页面级元数据与配置的完整指南。" --- Frontmatter 允许你在单个页面上覆盖全局设置。它必须写在 Markdown 文件最顶部,以 YAML 格式编写。 ## 核心元数据 | 键名 | 类型 | 说明 | | :--- | :--- | :--- | | `title` | `String` | **必填。** 设置 HTML `<title>` 和页面主标题。 | | `description` | `String` | SEO 和搜索结果的元描述。 | | `keywords` | `Array` | `<meta name="keywords">` 标签的关键词列表。 | ::: callout warning "标题很重要" 虽然并非必填,但强烈建议填写 `title`。如果缺失,docmd 会回退到第一个 `# H1` 标题或文件名作为标题,可能产生不理想的 `<title>` 标签和搜索结果。 ::: ## 显示与索引 | 键名 | 类型 | 说明 | | :--- | :--- | :--- | | `noindex` | `Boolean` | 将该页面排除在内部搜索索引之外。 | | `llms` | `Boolean` | 设为 `false` 可将该页面排除在 AI 上下文文件(`llms.txt`)之外。 | | `hideTitle` | `Boolean` | 隐藏固定头部中的标题(当使用自定义 H1 时很有用)。 | | `bodyClass` | `String` | 为该页面的 `<body>` 标签添加自定义 CSS 类。 | ## 布局控制 | 键 | 类型 | 说明 | | :--- | :--- | :--- | | `layout` | `String` | 设为 `full` 使用主内容宽度并隐藏目录侧边栏。 | | `toc` | `Boolean` | 设为 `false` 完全禁用目录。 | | `noStyle` | `Boolean` | 为自定义页面禁用整个 `docmd` UI(侧边栏、Header、Footer)。 | | `titleAppend` | `Boolean` | 设为 `false` 可防止将站点标题附加到 `<title>`、OpenGraph (`og:title`) 和 Twitter 元数据标签。默认值:`true`。 | ### `noStyle` 组件控制 `noStyle: true` 启用时,必须显式选择要保留的组件: ```yaml --- noStyle: true components: meta: true # 注入 SEO 元数据 favicon: true # 注入站点 favicon css: true # 注入 docmd-main.css theme: true # 注入主题特定样式 highlight: true # 注入语法高亮 scripts: true # 注入 SPA 路由器逻辑 sidebar: true # 注入导航侧边栏 footer: true # 注入站点页脚 --- ``` ## 插件覆盖 ### SEO(`seo`) * `image`:页面的自定义社交分享图片 URL。 * `aiBots`:设为 `false` 可阻止 AI 爬虫访问此页面。 * `canonicalUrl`:为 SEO 设置自定义规范链接。 --- ## [实时预览](https://docs.docmd.io/zh/content/live-preview/) --- title: "实时预览" description: "使用 Live 架构完全在浏览器中运行渲染引擎,无需后端服务器。" --- 编译器采用模块化架构,将文件系统操作与核心逻辑分离。这使得引擎能够完全在浏览器中运行,无需 Node.js 后端即可轻松实现实时编辑器和 CMS 预览。 <img width="720" class="with-border" src="/assets/previews/live-editor-preview.webp"> ::: button "打开实时编辑器" external:https://live.docmd.io ## 实时编辑器 内置的实时编辑器提供高性能的左右分栏界面。在左栏编写 Markdown,在右栏实时同步查看渲染后的输出。 ### 本地运行 在项目中本地启动实时编辑器: ```bash npx @docmd/core live ``` ### 静态部署 生成独立、静态版本的编辑器,并将其托管到 Vercel 或 GitHub Pages 等平台: ```bash npx @docmd/core live --build-only ``` 这会生成一个 `dist/` 目录,其中包含入口文件 `index.html` 和打包后的 `docmd-live.js` 引擎。 ## 嵌入 @docmd/core 将兼容浏览器的打包文件集成到你的应用中,提供内置的 Markdown 渲染或预览功能。 ### 1. 资源集成 从你的资源目录或 CDN 中包含所需的 CSS 和 JavaScript 文件: ```html <link rel="stylesheet" href="/assets/css/docmd-main.css"> <script src="/docmd-live.js"></script> ``` ### 2. 同构 API 全局 `docmd` 对象提供了用于瞬时渲染的 `compile` 方法。 ```javascript const html = await docmd.compile(markdown, { "title": "动态预览", "theme": { "appearance": "dark" } }); document.getElementById("preview-frame").srcdoc = html; ``` ::: callout tip "AI 反馈循环" icon:sparkles 实时架构是构建 **AI 代理沙箱** 的理想选择。你可以将代理建议的更改传输到实时编译缓冲区,在将更改提交到仓库之前,直观地验证 AI 的建议。 ::: --- ## [docmd : Bespoke No-Style Page Demo](https://docs.docmd.io/zh/content/no-style-example/) --- title: "docmd : Bespoke No-Style Page Demo" description: "noStyle 架构功能的实际演示。" noStyle: true components: meta: true favicon: true css: true theme: true scripts: true mainScripts: true copyCode: true customHead: | <style> body { font-family: 'Inter', -apple-system, system-ui, sans-serif; margin: 0; padding: 0; line-height: 1.6; background: var(--bg-primary); color: var(--text-primary); } .demo-container { max-width: 900px; margin: 0 auto; padding: 80px 20px; } .demo-hero { text-align: center; margin-bottom: 60px; } .demo-hero h1 { font-size: 3.5rem; margin-bottom: 20px; color: var(--brand-primary, #4a6cf7); } .demo-hero p { font-size: 1.25rem; color: var(--text-secondary); } .demo-card { background: var(--bg-secondary, #f8f9fa); padding: 40px; border-radius: 16px; border: 1px solid var(--border-color); box-shadow: 0 4px 20px rgba(0,0,0,0.05); } .demo-button { display: inline-block; padding: 14px 28px; background-color: var(--brand-primary, #4a6cf7); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 30px; transition: filter 0.2s ease; } .demo-button:hover { filter: brightness(1.1); } </style> --- <div class="demo-container"> <div class="demo-hero"> <h1>定制页面架构</h1> <p>演示通过 <code>noStyle: true</code> 实现的绝对布局控制。</p> </div> <div class="demo-card"> <h2>逻辑基础</h2> <p> 本演示使用 <code>noStyle: true</code> frontmatter 指令绕过全局文档布局(侧边栏、Header 和目录)。这提供了一个"零阻力"画布,用于创建营销落地页或自定义产品仪表盘。 </p> <h3>已启用的系统组件</h3> <p>在 No-Style 模式下,你需要明确选择文档引擎的核心功能:</p> <ul> <li><strong>SEO 元引擎</strong>:结构化标签和社交图谱数据被保留。</li> <li><strong>项目品牌</strong>:全局 favicon 注入保持活跃。</li> <li><strong>基础排版</strong>:处理后的 <code>docmd-main.css</code> 提供基础样式。</li> <li><strong>主题同步</strong>:浅色/深色模式状态完全保留。</li> <li><strong>交互能力</strong>:SPA 路由器和组件逻辑保持可用。</li> </ul> <h3>技术实现</h3> <p> 此页面的布局使用标准 HTML 包装器和在 <code>customHead</code> frontmatter 字段中定义的作用域 CSS 编写。这确保了零 CSS 泄漏到文档站点的其余部分。 </p> <a href="/content/no-style-pages/" class="demo-button">分析实现指南 →</a> </div> </div> --- ## [无样式页面](https://docs.docmd.io/zh/content/no-style-pages/) --- title: "无样式页面" description: "通过禁用默认 docmd 主题创建自定义落地页和独特布局。" --- `docmd` 允许你在单个页面上跳过标准文档布局(侧边栏、头部和页脚)。这非常适合创建产品落地页、自定义仪表盘或运营起始页,同时使用文档引擎的各种组件。 ## 启用无样式模式 在页面的 frontmatter 中添加 `noStyle: true` 即可禁用全局 UI。 ```yaml --- title: "产品展示" noStyle: true components: meta: true # 保留 SEO 和 OpenGraph 标签 favicon: true # 保留网站图标 css: true # 注入 docmd-main.css 用于排版 --- <!-- 原生 HTML 或特殊 Markdown 放在这里 --> <div class="hero"> <h1>下一代文档</h1> <p>零配置。同构。AI 就绪。</p> </div> ::: callout info "无限层级嵌套" 即使开启 `noStyle: true`,所有标准 `docmd` 容器(如 `::: card`、`::: tabs`、`::: hero`)仍完全可用,并可以无限深度嵌套。 ::: ``` ## 组件单独启用 开启 `noStyle` 后,页面从空白画布开始。根据需要选择性地开启核心组件: | 组件 | 说明 | | :--- | :--- | | `meta` | 注入 `<title>`、SEO 元标签和 OpenGraph 结构化数据。 | | `favicon` | 注入项目全局网站图标。 | | `css` | 注入 `docmd-main.css`。强烈建议开启,提供基础网格和排版。 | | `menubar` | 注入网站顶部菜单栏。 | | `theme` | 注入当前主题的 CSS 变量和外观覆盖。 | | `scripts` | 注入交互组件逻辑(需要 `mainScripts: true`)。 | | `spa` | 启用单页应用路由(需要 `scripts: true`)。 | ## 组合式落地页 `noStyle` 的核心优势在于:它允许你将所有 `docmd` 组件使用为在空白画布上的高价值“小插件”。你不局限于原始 HTML,可以纯粹用 Markdown 构建复杂的结构化设计。 ### 打造现代入口页 ```yaml --- title: "欢迎使用" noStyle: true components: meta: true css: true menubar: true # 使用网站顶部导航 scripts: true spa: true --- ::: hero # 下一代文档 沈浸式, 18kb, AI 就绪. ::: button "立马开始" /getting-started/quick-start ::: ``` ::: callout tip "AI 辅助布局设计" `noStyle` 页面同时支持原生 HTML 和 `docmd` 容器,因此非常适合 **AI 驱动的 UI 设计**。你可以提示 AI:*"使用 Tailwind 风格的工具类和 docmd 按钮设计一个现代 hero 区块,封装在 noStyle: true 容器中。"* AI 即可在你的静态网站流水线中快速迭代设计,无需任何额外配置。 ::: --- ## [高级 Markdown 语法](https://docs.docmd.io/zh/content/syntax/advanced/) --- title: "高级 Markdown 语法" description: "充分利用 docmd 的扩展功能:自定义属性、GFM 扩展与语义定义。" --- 除标准 Markdown 外,`docmd` 还支持多种源自 GitHub Flavored Markdown (GFM) 和自定义属性插件的高保真扩展。这些工具可让你完全掌控文档的结构与样式。 ## GFM 扩展 ### 任务列表 创建可交互或只读的检查列表,适用于路线跟踪。 ```markdown - [x] 引擎优化完成 - [ ] 插件 API 内容确定 ``` - [x] 引擎优化完成 - [ ] 插件 API 内容确定 ### 自动链接识别 标准 URL 和电子邮件地址会被自动识别并转化为链接,无需额外标记:`https://docmd.io` ### 短代码 Emoji `docmd` 支持标准短代码,可为文档增添视觉趣味。 > 我们 :heart: 高性能文档!:rocket: :smile: ## 自定义元素属性 使用花括号 `{}` 语法可为标题、图片和链接添加唯一 ID 和 CSS 类。这是应用 [自定义 CSS 样式](../../theming/custom-css-js.md) 的主要方式。 ### 唯一语义 ID 用于直接定位到技术子章节的深层链接。 ```markdown ## 性能基准测试 {#benchmarks-2026} ``` ### CSS 功能类 为特定元素应用样式工具。 ```markdown ## 居中对齐章节 {.text-center .text-blue} ``` ### 按钮链接 将任意标准 Markdown 链接转化为样式化的行动按钮。 ```markdown [下载最新版本](#download){.docmd-button} ``` ## 引用与定义 ### 脚注引用 添加引用或技术深层内容[^1],引擎自动收集并在页面底部渲染。 ```markdown 架构决策记录在 RFC[^1] 中。 [^1]: RFC-42: 同构渲染流水线。 ``` ### 定义列表 非常适合 API 参数说明和词汇表。 ```markdown PropName : 该配置项的唯一标识符。 ``` PropName : 该配置项的唯一标识符。 ### 节略词生成 在页面中全局定义节略词,悬停时显示完整定义。 ```markdown *[SPA]: Single Page Application docmd 路由器带来流畅的 SPA 体验。 ``` *[SPA]: Single Page Application docmd 路由器带来流畅的 SPA 体验。 ::: callout tip "AI 上下文精确性" 使用**定义**和**节略词**可为 AI Agent 提供高质量的技术信号。当 AI 处理你的 `llms-full.txt` 上下文时,这些明确的定义可防止词义模糊,确保模型为项目特定术语生成逻辑正确的解释。 ::: --- ## [代码块](https://docs.docmd.io/zh/content/syntax/code/) --- title: "代码块" description: "高保真语法高亮与一键复制按钮,清晰呈现技术实现细节。" --- `docmd` 使用超快速的 `lite-hl` 引擎,为数百种编程语言和配置格式提供自动、上下文感知的语法高亮。 ## 语法高亮 使用标准 Markdown 代码围斜线语法编写技术示例。始终指定语言标识符,确保高亮引擎应用正确的词法规则。 ````markdown ```typescript async function build(config: string): Promise<void> { await initialise(config); } ``` ```` ```typescript async function build(config: string): Promise<void> { await initialise(config); } ``` ## 块标题 在语言标识符后跟一个带引号的文件名,以在块上方渲染标签头。这对于直接引用配置文件和源路径很有用。 ````markdown ```json "docmd.config.json" { "title": "My Documentation", "src": "docs/" } ``` ```` ```json "docmd.config.json" { "title": "My Documentation", "src": "docs/" } ``` ::: callout tip "一键复制" 开启配置中的 `copyCode: true`(默认开启)后,每个代码块右上角悬停时会自动显示复制按鈕,方便用户将代码片段直接复制到 IDE。 ::: ## AI 上下文策略 编写面向 LLM 和 AI Agent 的代码文档时,建议遵循以下最佳实践: 1. **严格语言标注**:明确标注为 `typescript`、`bash` 或 `json`,确保 AI 解析器在 `llms-full.txt` 流中准确解析代码块的语法。 2. **嵌入意图**:在代码块中使用内联注释解释复杂逻辑背后的原因。这为 AI 提供了关键的推理上下文,而这是代码块外的简单文本难以传达的。 ## 支持的语言 `docmd` 开箱即用地支持最常用的技术生态系统,包括: * **逻辑语言**:`javascript`、`typescript`、`python`、`rust`、`go`、`ruby`、`csharp`。 * **Web**:`html`、`css`、`markdown`。 * **数据与 Shell**:`json`、`yaml`、`bash`、`powershell`、`dockerfile`。 * **文档**:`mermaid`、`changelog`。 --- ## [图片与视觉媒体](https://docs.docmd.io/zh/content/syntax/images/) --- title: "图片与视觉媒体" description: "掌握媒体管理:响应式图片、样式属性与自动 Lightbox 效果。" --- `docmd` 使用标准 Markdown 语法集成媒体资源。建议将媒体资源集中存放在项目源目录的 `assets/images/` 文件夹中。 ```markdown ![技术架构图](/assets/images/architecture.png "可选提示标题") ``` ## 样式属性参考 使用 `{ .class }` 属性语法可直接为图片添加 CSS 类。 ### 动态缩放 ```markdown ![小尺寸](/assets/icon.png){ .size-small } ![标准视图](/assets/preview.png){ .size-medium } ![全尺寸](/assets/banner.png){ .size-large } ``` ### 对齐与布局 ```markdown ![居中](/assets/img.png){ .align-center } ![右对齐](/assets/img.png){ .align-right .with-shadow .with-border } ``` ![高级样式示例](/assets/images/docmd-preview.png){.with-border .with-shadow .size-medium .align-center} ## 结构化媒体元素 ### 图片标题 对于精确的可访问性媒体标注,建议使用标准 HTML5 `<figure>` 元素。 ```html <figure> <img src="/assets/diagram.png" alt="云基础架构图"> <figcaption>图 1.1:核心系统基础架构。</figcaption> </figure> ``` ### 图片画廊 使用 `image-gallery` 类将多张图片整理到响应式均衡网格中。 ```html <div class="image-gallery"> <figure> <img src="/assets/screen1.jpg" alt="用户仪表盘视图"> <figcaption>应用性能监控</figcaption> </figure> <figure> <img src="/assets/screen2.jpg" alt="配置面板视图"> <figcaption>项目全局设置</figcaption> </figure> </div> ``` ## 交互式 Lightbox 缩放 开启 `mainScripts` 组件(默认开启)后,`docmd` 会自动为画廊内的图片或带有 `.lightbox` 类的图片应用全屏缩放效果。 ```markdown ![深层纹理分析](/assets/sample.png){ .lightbox } ``` ::: callout tip "AI 上下文与可访问性" 媒体内容始终要提供全面的 **Alt 文本**。虽然高级 AI 模型具备视觉能力,但 Markdown 源文件中的描述性文本为模型推理引擎提供了直接、高保真的信号,有助于增强 `llms-full.txt` 流中的架构分析和功能理解。 ::: --- ## [Markdown 语法基础](https://docs.docmd.io/zh/content/syntax/) --- title: "Markdown 语法基础" description: "掌握 docmd 的基础格式规则:标题、排版样式和技术块。" --- `docmd` 遵循标准 **GitHub Flavored Markdown (GFM)** 规范。本指南建立了在整个文档网站中编写核心内容的基准标准。 ## 排版样式 | 属性 | Markdown 语法 | 视觉效果 | | :--- | :--- | :--- | | **强调** | `**Text**` | **粗体技术术语** | | **斜体** | `*Text*` | *斜体变量* | | **删除线** | `~~Text~~` | ~~已废弃逻辑~~ | | **内联代码** | `` `code` `` | `engine.initialize()` | ## 结构元素 ### 语义化标题层次 ```markdown # 一级标题(通过 Frontmatter 自动生成) ## 二级标题(主要章节) ### 三级标题(功能细节) ``` ::: callout tip "AI 逻辑完整性" 高级 AI 模型和搜索索引器依靠严格的标题层次结构来建立对项目的精确理解。避免"跳级标题"(如从 H2 直接跳到 H4),可确保 `llms-full.txt` 上下文流在时序和逻辑上保持连贯。 ::: ### 导航与引用 内部文档节点和外部资源均使用标准链接语法。 ```markdown [外部资源](https://docmd.io) [内部模块](../api/node-api.md) ``` ### 枚举与列表 * **无序列表**:使用 `*` 或 `-` 创建易于扫描的项目符号。 * **有序逻辑**:使用 `1.`、`2.` 等表示有序步骤。(对于教程,建议使用高级**[步骤容器](../containers/steps)**。) ## 技术块级元素 ### 引用块 标准 `>` 语法非常适合突出显示外部引用或背景上下文。 > docmd 引擎重新定义了静态站点生成与动态应用交付之间的边界。 ### 数据表格 | 属性 | 数据类型 | 默认值 | | :--- | :--- | :--- | | `name` | `string` | `undefined` | | `active` | `boolean` | `true` | ## 原生 HTML 支持 `docmd` 启用了原生 HTML 解析,你可以直接在 Markdown 文件中嵌入复杂布局或特殊样式,满足个性化 UI 需求。 ```html <div style="padding: 2rem; border: 1px solid var(--border-color); border-radius: 12px; text-align: center;"> 自定义 UI 元素放在这里。 </div> ``` --- ## [链接与引用](https://docs.docmd.io/zh/content/syntax/linking/) --- title: "链接与引用" description: "掌握内部交叉链接、外部资源、新标签页行为和静态资源引用。" --- docmd 提供了一套可靠的、具有文件系统感知能力的链接系统。你可以用任何格式自然地编写指向源 `.md` 文件的链接——引擎会自动将它们规范化为干净、经过 SEO 优化的 URL。 ::: callout info "自然编写,完美交付" 你不需要任何特殊的链接约定。无论写的是 `overview.md`、`overview/` 还是 `overview`,构建引擎都会生成相同的干净带尾斜杠 URL。 ::: ## URL 规范化 在构建过程中,引擎会对每一个内部链接自动应用规范化。这适用于 Markdown 文本、按钮容器、标签和导航配置中的链接。 | 你编写的内容 | 渲染后的内容 | 原因 | | :--- | :--- | :--- | | `overview.md` | `overview/` | 剥离 `.md` 扩展名,添加尾斜杠 | | `overview` | `overview/` | 自动添加尾斜杠 | | `overview/` | `overview/` | 已正确,无需更改 | | `api/commands.md` | `api/commands/` | 规范化子目录链接 | | `localisation/index.md` | `localisation/` | 剥离 `index`,文件夹为规范 URL | | `../index.md` | `../` | 清晰解析父目录索引 | | `overview.md#settings` | `overview/#settings` | 保留哈希片段 | | `https://example.com` | `https://example.com` | 外部链接不做修改 | ## 内部链接 使用指向源 `.md` 文件的相对路径链接到其他页面。无论目录深度如何,引擎都能正确解析。 | 目标 | 示例 | | :--- | :--- | | 同级页面 | `[系统概览](overview.md)` | | 子目录页面 | `[API 参考](api/node-api.md)` | | 子目录索引 | `[本地化](localisation/index.md)` | | 父目录 | `[回到首页](../index.md)` | ## 章节锚点 使用标准 URL 哈希片段直接跳转到指定标题。 ```markdown <!-- 页内锚点 --> [跳转到路线图](#project-roadmap) <!-- 跨页锚点 --> [查看 CLI 标志](../api/cli-commands.md#available-flags) ``` 哈希片段在规范化过程中会被保留。上面的跨页链接在生产环境中渲染为 `../api/cli-commands/#available-flags`。 ## 在新标签页中打开 在任何链接 URL 前加上 `external:` 前缀,即可强制其在新标签页中打开。适用于标准 Markdown 链接、按钮和标签容器。 ```markdown [在新标签页中打开](external:./configuration/overview.md) [GitHub](external:https://github.com/docmd-io/docmd) ``` `external:` 前缀会从渲染后的 URL 中剥离。默认情况下,所有链接都在同一个窗口中打开。 ## 链接到原始文件 使用 `raw:` 前缀可绕过规范化,直接链接到可下载的原始文件。扩展名和路径将完全按照编写的方式保留。 ```markdown [查看原始源码](raw:docs/readme.md) ``` ## 按钮与标签 `::: button` 和 `::: tag` 容器支持所有标准链接约定,包括 `external:` 和 `raw:` 前缀。 ```markdown ::: button "开始使用" ./getting-started/quick-start.md icon:rocket ::: button "在 GitHub 上查看" external:https://github.com/docmd-io/docmd icon:github ::: button "下载源码" raw:docs/readme.md icon:download ::: tag "v0.8.2" link:release-notes/0-8-2.md icon:tag color:#22c55e ::: tag "从外部打开" link:external:./configuration/overview.md icon:external-link ``` ## 导航配置 在 `navigation.json` 和 `docmd.config.json` 中定义的路径会在构建时规范化。三种写法均生成相同的规范 URL。 ```json "navigation.json" [ { "title": "概览", "path": "configuration/overview" }, { "title": "概览", "path": "configuration/overview.md" }, { "title": "概览", "path": "configuration/overview/" } ] ``` 对于需要在新标签页中打开的导航项,设置 `external` 标志。 ```json "navigation.json" [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ::: callout warning "导航中的索引页" 链接到目录的索引页时,使用文件夹路径比显式引用 `index.md` 更整洁。两者效果相同。 ```markdown <!-- 推荐 --> [本地化](localisation/) <!-- 同样有效 --> [本地化](localisation/index.md) ``` ::: ## 协议与外部资源 引擎遵循标准浏览器协议,不修改这些链接。 * **HTTPS** — `[docmd 主页](https://docmd.io)` — 在同一标签页中打开。 * **邮件** — `[支持](mailto:help@docmd.io)` — 打开邮件客户端。 * **资源** — `[下载 CLI 二进制](/assets/bin/docmd-mac.zip)` — 不做规范化。 ## 静态资源 将可下载文件放在项目的 `assets/` 目录中。构建器会将这些文件移动到生产根目录,不修改路径。 ```markdown [下载文档 PDF](/assets/pdf/handbook.pdf) [查看原始全局配置](/assets/config/docmd.config.json) ``` ::: callout tip "针对 AI 的语义链接" 优先使用**描述性锚点文本**(例如 `[优化 PWA 缓存](../plugins/pwa.md)`),而非通用标签(例如 `[阅读更多](../plugins/pwa.md)`)。详细的链接标签能让 AI 代理在 `llms.txt` 流中精准解析文档节点之间的语义关系。 ::: --- ## [参与贡献](https://docs.docmd.io/zh/contributing/) --- title: "参与贡献" description: "参与 docmd 项目贡献的指南和环境设置说明。" --- 感谢您对 `docmd` 项目的关注。我们非常欢迎各种形式的贡献,包括修复错误、改进文档、开发新功能以及提出设计建议。 ## 开发环境 `docmd` 是一个使用 [pnpm](https://pnpm.io/) 管理的 Monorepo 项目。 ### 前提条件 - **Node.js**: v22.x 或更高版本 (推荐 LTS) - **pnpm**: v10.x 或更高版本 ### 项目设置 克隆仓库并运行初始设置以安装依赖并构建项目: ```bash git clone https://github.com/docmd-io/docmd.git cd docmd pnpm install pnpm build ``` 要在全局范围内链接本地 `docmd` 命令以便在其他项目中进行测试: ```bash pnpm verify --link ``` ### 本地开发 我们提供了一个主代理命令,可以直接针对内部的 `_playground` 目录运行任何 `docmd` 命令。这使得开发体验与用户 CLI 完全一致: ```bash pnpm docmd dev # 启动 Playground 开发服务器 (也可直接运行 pnpm dev) pnpm docmd build # 构建 Playground 文档 ``` 如需开启热重载监控内部源码文件(引擎、模板和插件),请设置 `DOCMD_DEV` 环境变量: ```bash DOCMD_DEV=true pnpm dev ``` ## 质量标准 ### 代码检查 (Linting) 确保您的代码符合我们的 ESLint 配置。要自动修复格式问题,请运行: ```bash pnpm lint --fix ``` ### 验证 在提交 Pull Request 之前,您 **必须** 确保整个 Monorepo 通过我们的强化验证流水线。该流水线会模拟一个全新的发布环境,审核安全漏洞,并验证 Monorepo 的完整性: ```bash pnpm prep ``` *(该命令会链式执行 `pnpm reset`、依赖安装、代码检查、7 项端到端测试,以及最终的发布预演。)* ## GitHub 工作流 1. **Fork 和 分支**: 从最新的 `main` 分支创建一个特性分支。 2. **验证**: 确保 `pnpm prep` 返回 `🛡️ docmd is ready for production!`。 3. **提交 PR**: 提交预览时请清晰地描述所解决的问题或新增的功能。 ### 提交规范 (Commit Guidelines) 我们遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范。请为您的提交消息添加以下前缀: - `feat:` (新增功能) - `fix:` (错误修复) - `docs:` (文档更改) - `refactor:` (内部重构) ### 源码头部 (Source Headers) 所有在 `packages/` 目录下的新文件必须包含标准的项目版权声明头部: ```javascript /** * -------------------------------------------------------------------- * docmd : the zero-config documentation engine. * * @package @docmd/core (and ecosystem) * @website https://docmd.io * @repository https://github.com/docmd-io/docmd * @license MIT * @copyright Copyright (c) 2025-present docmd.io * * [docmd-source] - Please do not remove this header. * -------------------------------------------------------------------- */ ``` --- ## [Caddy](https://docs.docmd.io/zh/deployment/caddy/) --- title: "Caddy" description: "使用生产级 Caddyfile 部署 docmd。" --- [Caddy](https://caddyserver.com/) 是一个现代 Web 服务器,能自动处理 HTTPS 证书配置和续期。 ## 生成 Caddyfile ```bash npx @docmd/core deploy --caddy ``` 这会生成针对你项目定制的 `Caddyfile`: - **站点地址**设置为从 `url` 配置中提取的主机名。Caddy 会自动为其签发 SSL 证书。如果未配置 URL 则回退到 `:80`。 - **根目录**使用你配置的 `out` 目录(不是硬编码的值)。 - **SPA 回退**仅在配置中 `layout.spa` 为 `true` 时包含。 ### 生成内容 ```caddy docs.example.com { root * ./site file_server # SPA Routing Fallback (only when layout.spa is true) try_files {path} {path}/ /index.html # Security Headers header { X-Content-Type-Options "nosniff" X-Frame-Options "SAMEORIGIN" -Server } # Custom 404 handle_errors { rewrite * /404.html file_server } # Cache Static Assets (6 months) @static { file path *.ico *.css *.js *.gif *.jpg *.jpeg *.png *.webp *.avif *.svg *.woff *.woff2 *.eot *.ttf *.otf } header @static Cache-Control "public, max-age=15552000, immutable" } ``` 当你使用真实域名作为站点地址时(例如 `docs.example.com` 而不是 `:80`),Caddy 会通过 Let's Encrypt 自动签发免费 SSL 证书。无需 HTTPS 配置。 ## 部署步骤 1. 构建站点:`npx @docmd/core build` 2. 将输出文件夹和生成的 `Caddyfile` 传输到服务器。 3. 在包含 Caddyfile 的目录中运行 `caddy start` 或 `caddy run`。 ### 重新生成 修改了站点 URL 或输出目录?重新运行 `npx @docmd/core deploy --caddy` - Caddyfile 会根据当前 `docmd.config.json` 重新生成。 --- ## [CI/CD 流水线](https://docs.docmd.io/zh/deployment/ci-cd/) --- title: "CI/CD 流水线" description: "通过 GitHub Pages、Vercel、Netlify 等 CI/CD 流水线自动化文档的构建与部署。" --- 使用 CI/CD 工作流,在每次推送更改时自动构建并部署你的 `docmd` 站点。以下是常用云平台的即插即用配置。 ## 云平台 ::: tabs == tab "GitHub Pages" 推荐的方法是使用 **GitHub Actions** 在每次推送时自动化部署。 **创建 `.github/workflows/deploy.yml`:** ```yaml name: 部署 docmd on: push: branches: ["main"] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: '22' } - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: { path: ./site } - uses: actions/deploy-pages@v4 ``` == tab "Vercel" 1. 将你的存储库连接到 Vercel。 2. 在项目 **Build Settings** 中: - **Framework Preset**: `Other` - **Build Command**: `npx @docmd/core build` - **Output Directory**: `site` 3. 部署。Vercel 会自动检测静态输出并进行全球分发。 == tab "Netlify" 1. 从 GitHub/GitLab/Bitbucket 导入你的项目。 2. 配置构建设置: - **Build command**: `npx @docmd/core build` - **Publish directory**: `site` 3. 点击 **Deploy site**。Netlify 的 CDN 将处理路由和资源分发。 == tab "Cloudflare Pages" 1. 在 Cloudflare 控制面板的 **Pages** 下创建一个新项目。 2. 连接你的 git 提供商并选择你的存储库。 3. 配置构建设置: - **Framework preset**: `None` - **Build command**: `npx @docmd/core build` - **Build output directory**: `site` 4. 保存并部署。 == tab "Firebase" 1. 安装 Firebase CLI: `npm install -g firebase-tools`。 2. 构建你的站点: `npx @docmd/core build`。 3. 运行 `firebase init hosting` 并选择你的项目。 4. 将公共目录设置为 `site`。 5. 配置为单页面应用: `Yes`(这会处理 404 行为)。 6. 使用 `firebase deploy` 进行部署。 ::: ::: callout info "为什么使用 npx @docmd/core?" 在未全局安装 `docmd` 的 CI/CD 环境中,使用 `npx @docmd/core` 直接运行作用域包。如果你的项目已将 `@docmd/core` 列为 `devDependency`,那么在 `npm install` 之后直接使用 `docmd build` 同样有效。 ::: ## 手动 / 静态服务器 对于传统的 Web 服务器(Apache、IIS 等): 1. 生成站点: `npx @docmd/core build`。 2. 通过 SFTP、SCP 或你喜欢的部署工具将 `site/` 文件夹的内容上传到你的服务器。 3. 确保你的服务器配置为对目录提供 `index.html`(大多数服务器的默认设置)。 --- ## [Cloudflare Pages](https://docs.docmd.io/zh/deployment/cloudflare-pages/) --- title: "Cloudflare Pages" description: "使用全球边缘网络将 docmd 文档部署到 Cloudflare Pages。支持 CI/CD 自动构建。" --- [Cloudflare Pages](https://pages.cloudflare.com/) 在 Cloudflare 的全球边缘网络上托管你的 docmd 站点,提供零配置 CI/CD。连接你的仓库,每次推送都会触发自动构建和部署。 ## 控制台设置 1. 前往 [Cloudflare 控制台](https://dash.cloudflare.com/),导航到 **Workers & Pages → Create → Pages**。 2. 连接你的 git 提供商(GitHub 或 GitLab)并选择你的仓库。 3. 配置构建设置: | 设置 | 值 | |---------|-------| | 框架预设 | `None` | | 构建命令 | `npx @docmd/core build` | | 构建输出目录 | `site` | 4. 点击 **Save and Deploy**。 Cloudflare Pages 会自动检测静态输出并将其分发到边缘网络。 ## 自定义域名 在 **Pages → 你的项目 → Custom domains** 下添加自定义域名。Cloudflare 会自动配置 SSL 证书。 在 `docmd.config.json` 中设置 `url` 字段以匹配你的域名。这可确保规范标签、站点地图和 LLMs 插件生成正确的绝对 URL。 ## CI/CD 注意事项 Cloudflare Pages 在每次推送到已连接分支时都会运行全新的 CI/CD 构建。你不需要单独的 GitHub Actions 工作流。Cloudflare 管理构建流水线。 ::: callout info "为什么使用 `npx @docmd/core`?" 在未全局安装 docmd 的 CI/CD 环境中,`npx @docmd/core` 会直接获取并运行该包。如果你的项目将 `@docmd/core` 列为 `devDependency`,在 `npm install` 后运行 `npx @docmd/core build` 可以完美工作。 ::: ## SPA 路由 docmd 将每个页面生成为独立的 `index.html`。直接访问 URL 无需任何重写规则即可工作。不需要额外的 Cloudflare 配置。 --- ## [使用 Deployer 包进行部署](https://docs.docmd.io/zh/deployment/deployer-package/) --- title: "使用 Deployer 包进行部署" description: "docmd 的模块化 @docmd/deployer 包如何从项目配置自动生成特定提供商的部署配置。" --- ## 概览 docmd 附带了专用的 `@docmd/deployer` 包。它读取你的 `docmd.config.json` 并自动生成特定提供商的部署文件。每个生成的文件都根据你的确切配置进行个性化 —— 你的输出目录、站点 URL、SPA 路由规则和 Node.js 版本都会被反映出来,无需手动编辑。 ## 支持的提供商 | 提供商 | 命令标志 | 生成的文件 | | :------- | :----------- | :-------------- | | Docker + Nginx | `--docker` | `Dockerfile`、`.dockerignore` | | Nginx | `--nginx` | `nginx.conf` | | Caddy | `--caddy` | `Caddyfile` | | GitHub Pages | `--github-pages` | `.github/workflows/deploy.yml` | | Vercel | `--vercel` | `vercel.json` | | Netlify | `--netlify` | `netlify.toml` | ## 使用方法 从项目根目录(`docmd.config.json` 所在位置)运行: ```bash # 单个提供商 npx @docmd/core deploy --github-pages # 一次生成多个提供商 npx @docmd/core deploy --docker --nginx # 覆盖现有文件 npx @docmd/core deploy --vercel --force ``` ## 提供商详情 ### GitHub Pages ```bash npx @docmd/core deploy --github-pages ``` 生成包含完整构建和部署流水线的 `.github/workflows/deploy.yml`。该工作流: - 检出你的仓库 - 安装 Node.js(匹配项目所需版本) - 运行 `npx @docmd/core build` - 将输出目录上传到 GitHub Pages ### Vercel ```bash npx @docmd/core deploy --vercel ``` 生成包含 SPA 路由规则(将所有路径重写到 `index.html`)和已配置输出目录的 `vercel.json`。 ### Netlify ```bash npx @docmd/core deploy --netlify ``` 生成包含构建命令、发布目录和 SPA 重定向规则的 `netlify.toml`。 ### Docker ```bash npx @docmd/core deploy --docker ``` 生成使用多阶段构建的 `Dockerfile`: 1. **构建阶段**:安装你精确固定的 `@docmd/core` 版本并运行构建。 2. **服务阶段**:将输出复制到最小的 `nginx:alpine` 镜像中。 如果项目根目录中已存在 `nginx.conf`,Dockerfile 会自动将其复制到容器中。 ```bash # 同时生成 Docker 和 Nginx 配置 npx @docmd/core deploy --docker --nginx ``` ### Nginx ```bash npx @docmd/core deploy --nginx ``` 生成包含 SPA 路由、gzip 压缩和输出目录正确 `root` 路径的 `nginx.conf`。 ### Caddy ```bash npx @docmd/core deploy --caddy ``` 生成包含自动 HTTPS、SPA 路由和从输出目录提供文件服务的 `Caddyfile`。 ## 重新生成 如果更改了 `out` 目录或 `url` 等配置字段,重新运行命令以重新生成文件。这可使配置保持同步。 --- ## [Deployer](https://docs.docmd.io/zh/deployment/deployer/) --- title: "Deployer" description: "从您的 docmd 项目配置生成特定提供商的部署配置文件,只需一条命令。" --- `deploy` 命令读取您的 `docmd.config.json` 并生成针对您项目定制的部署配置文件——输出目录、站点 URL、SPA 路由和 Node.js 版本都会自动反映。无通用模板。 ## 支持的提供商 | 提供商 | 标志 | 生成的文件 | | :------- | :--- | :-------------- | | Docker + Nginx | `--docker` | `Dockerfile`, `.dockerignore` | | Nginx | `--nginx` | `nginx.conf` | | Caddy | `--caddy` | `Caddyfile` | | GitHub Pages | `--github-pages` | `.github/workflows/deploy.yml` | | Vercel | `--vercel` | `vercel.json` | | Netlify | `--netlify` | `netlify.toml` | ## 使用方法 从项目根目录运行(`docmd.config.json` 所在位置): ```bash # 单个提供商 npx @docmd/core deploy --github-pages # 同时使用多个提供商 npx @docmd/core deploy --docker --nginx # 覆盖现有文件 npx @docmd/core deploy --vercel --force ``` ## 自动定制的内容 deploy 命令读取您的配置(或零配置默认值)并注入: | 配置字段 | 用于 | |:--|:--| | `title` | 每个生成文件中的注释头 | | `out` | Dockerfile 中的 `COPY` 路径、Nginx/Caddy 中的 `root` 指令 | | `url` | Nginx 中的 `server_name`、Caddy 中的站点地址 | | `layout.spa` | 控制是否包含 SPA 路由回退 | | 配置路径 | 非默认时,Dockerfile 构建步骤使用 `--config` | 没有 `docmd.config.json`?没问题。命令使用与 `npx @docmd/core dev` 和 `npx @docmd/core build` 相同的零配置默认值。 ## 始终同步 每次运行都会重新生成部署文件以匹配您当前的配置。修改了站点 URL 或输出目录?直接重新运行 deploy 命令即可。使用 `--force` 无提示覆盖现有文件。 ## 提供商详情 ### GitHub Pages ```bash npx @docmd/core deploy --github-pages ``` 生成带有完整构建和部署管道的 `.github/workflows/deploy.yml`。工作流检出您的仓库,安装 Node.js,运行 `npx @docmd/core build`,并将输出上传到 GitHub Pages。 ::: callout tip "更喜欢直接使用 GitHub Action?" 如果您想部署到 GitHub Pages 而不自己生成工作流文件,直接使用 [GitHub Action](./github-action)——它在一个可组合步骤中处理所有事情。 ::: ### Docker ```bash npx @docmd/core deploy --docker ``` 生成使用多阶段构建的 `Dockerfile`: 1. **构建阶段** — 安装您精确固定的 `@docmd/core` 版本并运行构建。 2. **服务阶段** — 将输出复制到最小的 `nginx:alpine` 镜像中。 如果项目根目录中已存在 `nginx.conf`,Dockerfile 会自动将其复制到容器中。 ```bash # 一起生成 Docker 和 Nginx 配置 npx @docmd/core deploy --docker --nginx ``` ::: callout tip "官方 Docker 镜像" 想在容器中运行 docmd 而不构建自定义镜像?请参阅 [Docker 镜像](./docker) 页面了解官方预构建镜像。 ::: ### Nginx ```bash npx @docmd/core deploy --nginx ``` 生成带有 SPA 路由、gzip 压缩和输出目录正确 `root` 路径的 `nginx.conf`。完整生成的配置请参阅 [NGINX](./nginx) 页面。 ### Caddy ```bash npx @docmd/core deploy --caddy ``` 生成带有自动 HTTPS、SPA 路由和从输出目录提供文件服务的 `Caddyfile`。完整生成的配置请参阅 [Caddy](./caddy) 页面。 ### Vercel ```bash npx @docmd/core deploy --vercel ``` 生成带有 SPA 路由规则和配置的输出目录的 `vercel.json`。部署步骤请参阅 [Vercel](./vercel) 页面。 ### Netlify ```bash npx @docmd/core deploy --netlify ``` 生成带有构建命令、发布目录和 SPA 重定向规则的 `netlify.toml`。部署步骤请参阅 [Netlify](./netlify) 页面。 ## 权衡 生成的配置是有主见的起点。它们对大多数 docmd 部署都是正确的,但对于自定义域、CDN 重写或多区域部署等高级场景可能需要调整。在部署到生产环境之前,请始终查看生成的文件。 --- ## [Docker](https://docs.docmd.io/zh/deployment/docker/) --- title: "Docker" description: "在 Docker 容器中运行 docmd——使用官方预构建镜像或从项目配置生成自定义 Dockerfile。" --- docmd 生成静态 HTML,非常适合轻量级、可复现的 Docker 容器。根据您的使用场景,有两种不同的方法。 ## 官方 Docker 镜像 官方镜像让您无需在本地安装任何东西即可构建和服务文档。它支持多架构(`linux/amd64` 和 `linux/arm64`)。 ### 快速开始 ```bash # 拉取最新镜像 docker pull ghcr.io/docmd-io/docmd:latest # 构建文档(挂载本地 docs 并输出到 ./site) docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build # 运行内置演示站点 docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest ``` ### Docker Compose 使用 Docker Compose 在单个工作流中构建和服务: ```yaml version: '3.8' services: docs: image: ghcr.io/docmd-io/docmd:latest command: build volumes: - ./docs:/docs - ./site:/site - ./docmd.config.json:/docmd.config.json:ro serve: image: nginx:alpine ports: - "8080:80" volumes: - ./site:/usr/share/nginx/html:ro depends_on: - docs ``` ### 镜像详情 | 属性 | 值 | |:--|:--| | 基础镜像 | Alpine Linux(极小体积) | | 安全性 | 以非 root 用户运行 | | 健康检查 | 内置容器健康状态监控 | | SBOM | 提供软件物料清单证明 | | 支持架构 | `linux/amd64`, `linux/arm64` | ## 自定义 Dockerfile(通过 Deployer) 对于生产自托管,使用 [Deployer](./deployer) 生成针对您项目配置定制的 `Dockerfile`: ```bash npx @docmd/core deploy --docker ``` 这会生成使用多阶段构建的 `Dockerfile`: 1. **构建阶段** — 安装您精确固定的 `@docmd/core` 版本并运行构建。 2. **服务阶段** — 将输出复制到最小的 `nginx:alpine` 镜像中。 一起生成 Docker 和 Nginx 配置以实现完整的自托管设置: ```bash npx @docmd/core deploy --docker --nginx ``` ### 构建和运行 ```bash docker build -t my-docs . docker run -p 8080:80 my-docs ``` 您的文档将在 `http://localhost:8080` 运行。 ::: callout tip "重新生成" 配置更改了?重新运行 `npx @docmd/core deploy --docker`。使用 `--force` 覆盖现有文件。 ::: --- ## [Firebase Hosting](https://docs.docmd.io/zh/deployment/firebase/) --- title: "Firebase Hosting" description: "将 docmd 文档部署到 Firebase Hosting。支持手动部署或通过 GitHub Actions 部署。" --- [Firebase Hosting](https://firebase.google.com/products/hosting) 通过全球 CDN 提供你的 docmd 静态站点,并包含 SSL。它可通过 Firebase CLI 或 GitHub Actions 完美集成到 CI/CD 流水线中。 ## 前提条件 安装 Firebase CLI: ```bash npm install -g firebase-tools firebase login ``` ## 设置 1. 构建你的站点: ```bash npx @docmd/core build ``` 2. 在项目根目录中初始化 Firebase Hosting: ```bash firebase init hosting ``` 当提示时: - 选择你的 Firebase 项目(或创建一个新项目)。 - 将 **public directory** 设置为 `site`。 - 配置为单页应用:**No**(docmd 为每个页面生成独立的 `index.html` 文件。不需要全局重写)。 - 不要覆盖 `site/index.html`。 3. 部署: ```bash firebase deploy --only hosting ``` ## 使用 GitHub Actions 进行 CI/CD 要在每次推送时自动部署,创建 `.github/workflows/firebase.yml`: ```yaml name: Deploy to Firebase Hosting on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: "20" - run: npm install - run: npx @docmd/core build - uses: FirebaseExtended/action-hosting-deploy@v0 with: repoToken: ${{ secrets.GITHUB_TOKEN }} firebaseServiceAccount: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }} channelId: live ``` 在仓库的 **Settings → Secrets** 中使用 Firebase 服务账户 JSON 密钥设置 `FIREBASE_SERVICE_ACCOUNT`。 ::: callout info "为什么使用 `npx @docmd/core`?" 在未全局安装 docmd 的 CI/CD 环境中,`npx @docmd/core` 会直接获取并运行该包。如果你的项目将 `@docmd/core` 列为 `devDependency`,在 `npm install` 后运行 `npx @docmd/core build` 可以完美工作。 ::: ## 自定义域名 在 Firebase 控制台的 **Hosting → Add custom domain** 下添加自定义域名。Firebase 会自动配置 SSL。 在 `docmd.config.json` 中设置 `url` 字段以匹配你的域名。这可确保规范标签和站点地图生成正确的绝对 URL。 --- ## [GitHub Action](https://docs.docmd.io/zh/deployment/github-action/) --- title: "GitHub Action" description: "使用官方 docmd GitHub Action 将文档部署到 GitHub Pages——零配置,一个可组合步骤。" --- `docmd-io/deploy` action 构建您的文档站点并输出已编译资产的路径,供上传至 GitHub Pages 或其他托管目标使用。它在单个可组合的 action 中处理 Node.js 安装、配置检测、依赖安装和构建步骤。 ::: button "在 GitHub Marketplace 查看" external:https://github.com/marketplace/actions/build-and-deploy-documentation-with-docmd icon:github ::: button "源代码" external:https://github.com/docmd-io/deploy icon:code ::: callout tip "启动新项目?" 使用[起始模板](./starter-template)——它包含预配置的工作流文件和即用型仓库结构。GitHub Action 最适合向**现有**仓库添加 docmd 部署。 ::: ## 快速开始 在您的仓库中添加以下工作流文件: ```yaml # .github/workflows/docs.yml name: 部署文档 on: push: branches: [main] permissions: contents: write pages: write id-token: write jobs: docs: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deploy.outputs.page_url }} steps: - uses: actions/checkout@v4 - uses: docmd-io/deploy@v1 id: build - uses: actions/upload-pages-artifact@v3 with: path: ${{ steps.build.outputs.site-dir }} - uses: actions/deploy-pages@v4 id: deploy ``` ## 可复用工作流 若希望最大程度减少样板代码,可使用托管的可复用工作流。它在一次调用中处理权限、检出、构建、上传和部署: ```yaml # .github/workflows/docs.yml on: push: branches: [main] jobs: docs: uses: docmd-io/deploy/.github/workflows/deploy.yml@v1 ``` ## 输入参数 | 参数 | 默认值 | 说明 | |------|--------|------| | `node` | `20` | 构建时使用的 Node.js 版本 | ## 输出参数 | 输出 | 说明 | |------|------| | `site-dir` | 已编译站点目录的相对路径(例如 `site/`) | ## Action 执行步骤 1. **安装 Node.js** — 使用指定版本。 2. **检测配置文件** — 在仓库树中(最多两层深度)搜索 `docmd.config.json`、`docmd.config.js` 或 `docmd.config.ts`,完全支持子目录配置。 3. **初始化 docmd** — 若未找到配置,运行 `npx @docmd/core init` 自动生成。 4. **安装依赖** — 若存在 `package.json` 则运行 `npm ci`,否则直接安装 `@docmd/core`。 5. **构建站点** — 运行 `npx @docmd/core build` 并从配置中读取输出目录。 6. **输出路径** — 通过 `site-dir` 告知上传步骤编译资产的位置。 ## 首次配置 GitHub Pages 必须配置为从 **GitHub Actions** 部署(而非从分支)。每个仓库仅需设置一次: 1. 在 GitHub 上进入您的仓库。 2. 导航至 **Settings → Pages**。 3. 在 **Source** 下选择 **GitHub Actions**。 4. 保存。 此后,每次推送到 `main` 都会自动触发部署。 ## 嵌套配置支持 若 `docmd.config.json` 位于子目录中(例如 Monorepo 中的 `packages/docs/docmd.config.json`),action 会自动检测并传递 `--cwd` 参数,无需手动配置路径。 ## 自定义域名 使用自定义域名: 1. 在 `docs/` 目录(或配置的资产文件夹)中添加包含您域名的 `CNAME` 文件,例如 `docs.example.com`。 2. 在 `docmd.config.json` 中将 `url` 字段设置为您的自定义域名,以确保站点地图和规范标签正确。 3. 在 **Settings → Pages → Custom domain** 中配置域名。 ## 固定 Action 版本 对于生产文档站点,固定到特定发布标签而不是 `@v1`: ```yaml - uses: docmd-io/deploy@v1.0.0 id: build ``` 这可防止未来次要更新带来的意外行为。 ## 故障排查 **`Error: Dependencies lock file is not found`** 当 `actions/setup-node` 配置了 `cache: 'npm'` 但不存在 `package-lock.json` 时会出现此错误。`docmd-io/deploy` action 内部处理缓存——使用本 action 时,请勿单独添加带有 `cache: 'npm'` 的 `actions/setup-node` 步骤。 **构建成功但站点未上线** 请确认 GitHub Pages 已设置为从 **GitHub Actions** 部署,而非从分支部署。参见上面的[首次配置](#首次配置)。 **配置未检测到** action 搜索最多两个目录层级。如果您的配置更深,请在自定义工作流步骤中手动传递 `--cwd`,或使用 [Deployer](./deployer) 生成定制的工作流文件。 --- ## [GitHub Pages](https://docs.docmd.io/zh/deployment/github-pages/) --- title: "GitHub Pages" description: "使用生成的 GitHub Actions CI/CD 工作流自动将 docmd 文档部署到 GitHub Pages。" --- `npx @docmd/core deploy --github-pages` 会在 `.github/workflows/deploy.yml` 生成一个即用型 GitHub Actions CI/CD 工作流文件。将其推送到仓库后,GitHub 会在每次推送到 `main` 时自动构建和部署你的站点。 ```bash npx @docmd/core deploy --github-pages ``` 这会创建一个针对你项目个性化的 `.github/workflows/deploy.yml`。无需手动编辑。 ## 生成的内容 该工作流: 1. 检出你的仓库。 2. 安装 Node.js 和项目依赖。 3. 安装用于生成文件的确切 `@docmd/core` 版本。 4. 运行 `npx @docmd/core build`。 5. 将输出目录作为 GitHub Pages 工件上传。 6. 部署到 GitHub Pages。 ## 启用 GitHub Pages 在推送工作流之前,在仓库中启用 GitHub Pages: 1. 前往 **Settings → Pages**。 2. 将 **Source** 设置为 **GitHub Actions**。 启用后,每次推送到 `main` 都会触发部署。 ## 自定义工作流 生成的文件是纯 YAML。可以自由编辑。常见更改包括: - **分支**:将 `branches: [main]` 更改为你的默认分支名称。 - **Node 版本**:更新 `node-version: "20"` 以匹配你的项目。 - **构建命令**:工作流默认使用 `npx @docmd/core build`。如果使用自定义配置文件,重新运行 `npx @docmd/core deploy --github-pages --config your-config.json` 以重新生成。 ## 自定义域名 部署后,你可以在 **Settings → Pages → Custom domain** 中添加自定义域名。在 `docmd.config.json` 中设置 `url` 字段以匹配,然后重新部署,以使站点地图和规范标签保持正确。 --- ## [部署概览](https://docs.docmd.io/zh/deployment/) --- title: "部署概览" description: "选择如何部署您的 docmd 文档站点——从零配置模板到自托管服务器和云平台。" --- docmd 构建完全静态的站点。输出是一个自包含的文件夹(默认:`site/`),可以托管在任何地方——无需服务器端运行时。 ```bash npx @docmd/core build ``` ## 选择部署方式 根据您的情况,有三种主要路径: | 方式 | 最适合 | |:--|:--| | [起始模板](./starter-template) | 从零开始启动新项目 | | [GitHub Action](./github-action) | 向现有仓库添加自动化部署 | | [Deployer](./deployer) | 生成服务器配置(Docker、Nginx、Caddy、Vercel、Netlify) | ## 起始模板 最快的入门方式。克隆官方模板仓库——它包含 `docmd.config.json`、示例页面和预配置的 GitHub Actions 工作流,每次推送时自动部署到 GitHub Pages。 → [起始模板](./starter-template) ## GitHub Action `docmd-io/deploy` action 构建您的站点并输出编译路径,准备上传到 GitHub Pages 或其他目标。使用它可以向现有仓库添加 docmd 部署,而无需更改项目结构。 → [GitHub Action](./github-action) ## Deployer `deploy` 命令读取您的 `docmd.config.json` 并生成针对您项目定制的特定提供商配置文件。无通用模板——每个文件都反映您的实际输出目录、站点 URL 和 SPA 设置。 ```bash # 自托管 npx @docmd/core deploy --docker # Dockerfile + .dockerignore npx @docmd/core deploy --nginx # 生产级 nginx.conf npx @docmd/core deploy --caddy # 生产级 Caddyfile # 云 / CI npx @docmd/core deploy --github-pages # GitHub Actions 工作流 npx @docmd/core deploy --vercel # vercel.json npx @docmd/core deploy --netlify # netlify.toml ``` → [Deployer 参考](./deployer) ## 云平台 无需运行自己的服务器的托管服务: - [Docker 镜像](./docker) — 用于容器化部署的官方多架构镜像 - [NGINX](./nginx) — 使用生成的配置自托管 - [Caddy](./caddy) — 带自动 HTTPS 的自托管 - [Vercel](./vercel) — 零配置云部署 - [Netlify](./netlify) — Git 连接的持续部署 - [Cloudflare Pages](./cloudflare-pages) — 带内置 CI/CD 的边缘原生托管 - [Firebase Hosting](./firebase) — 带 GitHub Actions 集成的 Google CDN ## 生产检查清单 1. **站点 URL** — 在 `docmd.config.json` 中设置 `url`。这驱动规范标签、站点地图、社交预览和生成的部署文件。 2. **重定向** — 从其他工具迁移?使用 `redirects` 配置保留 SEO 排名。 3. **分析** — 启用 `analytics` 插件跟踪参与度和搜索查询。 4. **AI 上下文** — 启用 `llms` 插件生成 `llms.txt` 供 AI 代理摄取。 ::: callout tip "自定义 404 页面" docmd 在您的输出目录中生成 `404.html`。大多数托管提供商会自动为缺失的路由提供服务。 ::: --- ## [Netlify](https://docs.docmd.io/zh/deployment/netlify/) --- title: "Netlify" description: "使用生成的 netlify.toml 将 docmd 文档部署到 Netlify。" --- `npx @docmd/core deploy --netlify` 在项目根目录生成一个 `netlify.toml` 文件。它预先配置了正确的构建命令、发布目录、缓存头和 SPA 重定向。 ```bash npx @docmd/core deploy --netlify ``` ## 生成的内容 `netlify.toml` 配置: - **构建命令** - 安装 `@docmd/core` 并运行 `npx @docmd/core build`。 - **发布目录** - 设置为你配置的 `out` 目录。 - **Node 版本** - 固定为 Node 20。 - **缓存头** - 资源不可变,HTML 页面无缓存。 - **SPA 重定向** - 当启用 `layout.spa` 时,将 `/*` 重写到 `/index.html`。 ## 部署 从 [Netlify 控制台](external:https://app.netlify.com)将仓库连接到 Netlify。它会自动检测 `netlify.toml` 并在每次推送时部署。 或者,使用 [Netlify CLI](external:https://docs.netlify.com/cli/get-started/): ```bash npm install -g netlify-cli netlify deploy --prod ``` ## 重新生成 每当更改 `out` 或其他配置字段时,重新运行 `npx @docmd/core deploy --netlify`。这可使 `netlify.toml` 保持同步。 --- ## [NGINX](https://docs.docmd.io/zh/deployment/nginx/) --- title: "NGINX" description: "使用生产级 NGINX 配置部署 docmd。" --- NGINX 是最可靠的 Web 服务器之一。由于 docmd 输出完全是静态的,NGINX 可以以接近零延迟的速度提供服务。 ## 生成 nginx.conf ```bash npx @docmd/core deploy --nginx ``` 这会生成针对你项目定制的 `nginx.conf`: - **`server_name`** 设置为从 `url` 配置中提取的主机名。如果未设置,则回退到 `localhost`。 - **SPA 回退**(`try_files ... /index.html`)仅在配置中 `layout.spa` 为 `true` 时包含。 - **安全头**、GZIP 压缩和不可变资产缓存默认包含。 ### 生成内容 ```nginx server { listen 80; server_name docs.example.com; root /usr/share/nginx/html; index index.html; # Security server_tokens off; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; # GZIP Compression gzip on; gzip_vary on; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml; # SPA Routing Fallback (only when layout.spa is true) location / { try_files $uri $uri/ /index.html; } # Custom 404 error_page 404 /404.html; # Cache Static Assets (6 months, immutable) location ~* \.(?:ico|css|js|gif|jpe?g|png|webp|avif|woff2?|eot|ttf|otf|svg)$ { expires 6M; access_log off; add_header Cache-Control "public, immutable"; } } ``` ## 部署步骤 1. 构建站点:`npx @docmd/core build` 2. 将输出目录的内容上传到服务器的 Web 根目录(如 `/usr/share/nginx/html/`)。 3. 将生成的 `nginx.conf` 放入服务器配置中(如 `/etc/nginx/conf.d/default.conf`)。 4. 重启 NGINX:`sudo systemctl restart nginx` ### 重新生成 修改了站点 URL 或关闭了 SPA 模式?重新运行 `npx @docmd/core deploy --nginx` - 配置文件会根据当前 `docmd.config.json` 重新生成。 --- ## [起始模板](https://docs.docmd.io/zh/deployment/starter-template/) --- title: "起始模板" description: "使用官方 docmd 起始模板,在一分钟内创建预配置的文档站点,并自动部署至 GitHub Pages。" --- # docmd 起始模板 `docmd-template` 仓库是启动新文档站点的最快方式。它包含一个可用的 `docmd.config.json`、示例页面、用于本地开发的 `package.json`,以及预配置的 GitHub Actions 工作流,每次推送时自动部署至 GitHub Pages。 ::: button "使用此模板" external:https://github.com/docmd-io/docmd-template/generate icon:github color:#2ea44f ::: button "查看仓库" external:https://github.com/docmd-io/docmd-template icon:external-link ## 快速开始 ### 1. 创建您的仓库 在 GitHub 上点击 **[使用此模板](https://github.com/docmd-io/docmd-template/generate)**,为仓库命名后点击 **Create repository**。无需 Fork——模板会创建一个干净的独立副本。 ### 2. 配置您的站点 在新仓库中打开 `docmd.config.json`,更新 `title` 和 `url` 字段: ```json { "title": "我的文档", "url": "https://用户名.github.io/仓库名" } ``` 将 `用户名` 和 `仓库名` 替换为您的 GitHub 用户名和仓库名称。 ### 3. 启用 GitHub Pages 每个仓库仅需设置一次: 1. 进入 **Settings → Pages**。 2. 在 **Source** 下选择 **GitHub Actions**。 3. 保存。 ### 4. 推送并部署 向 `main` 推送任何更改。内置工作流会自动构建站点并部署至 GitHub Pages。文档将上线至: ``` https://<用户名>.github.io/<仓库名>/ ``` ## 包含内容 ``` .github/ workflows/ docs.yml # 推送至 main 时自动构建和部署 docmd.config.json # 站点标题、URL 和输出目录 docs/ index.md # 您的第一个文档页面 package.json # 本地开发脚本 ``` ## 本地开发 克隆您的仓库并运行开发服务器: ```bash npm install npm run dev ``` 站点可在 `http://localhost:3000` 访问,支持热重载。Markdown 文件的更改会即时反映。 本地构建生产版本: ```bash npm run build ``` 编译后的站点默认写入 `site/` 目录。 ## 添加您的第一个页面 在 `docs/` 中创建新的 Markdown 文件: ```bash docs/ index.md # 首页 getting-started.md api-reference.md ``` 添加 `navigation.json` 控制侧边栏: ```json [ { "title": "首页", "path": "/" }, { "title": "快速开始", "path": "/getting-started" }, { "title": "API 参考", "path": "/api-reference" } ] ``` 完整的导航配置说明请参阅[导航配置](../configuration/navigation.md)。 ## 自定义域名 使用自定义域名(例如 `docs.example.com`): 1. 更新 `docmd.config.json` 中的 `url` 字段: ```json { "url": "https://docs.example.com" } ``` 2. 在 `docs/` 目录中添加包含您域名的 `CNAME` 文件。 3. 在 **Settings → Pages → Custom domain** 中配置域名。 ## 起始模板 vs GitHub Action 模板从一开始就为您提供对工作流文件和配置的完全控制。[GitHub Action](./github-action) 更适合向现有仓库添加 docmd 部署而无需重构。 | | 起始模板 | GitHub Action | |---|---|---| | 起点 | 新仓库 | 现有仓库 | | 工作流文件 | 已包含,可自由编辑 | 您编写它,action 处理构建 | | 配置 | 预配置 | 自动检测或生成 | | 适用场景 | 新项目 | 为现有仓库添加文档 | --- ## [Vercel](https://docs.docmd.io/zh/deployment/vercel/) --- title: "Vercel" description: "使用生成的 vercel.json 将 docmd 文档部署到 Vercel。" --- `npx @docmd/core deploy --vercel` 在项目根目录生成一个 `vercel.json` 文件。它会自动配置为你站点的输出目录和 SPA 路由设置。 ```bash npx @docmd/core deploy --vercel ``` ## 生成的内容 `vercel.json` 配置: - **构建命令** - 运行 `npx @docmd/core build`。 - **输出目录** - 设置为配置中的 `out` 属性。 - **安装命令** - 安装使用的确切 `@docmd/core` 版本。 - **缓存头** - 资源不可变缓存,HTML 无缓存。 - **SPA 路由** - 当启用 `layout.spa` 时,将所有路由重定向到 `index.html`。 ## 部署 生成文件后,使用 [Vercel CLI](external:https://vercel.com/docs/cli) 部署: ```bash npm install -g vercel vercel ``` 或者,从控制台将仓库连接到 Vercel。它会自动检测 `vercel.json`。 ## 重新生成 如果在 `docmd.config.json` 中更改了 `out` 目录或 `url`,重新运行命令以重新生成文件。这可使配置保持同步。 --- ## [JavaScript 引擎](https://docs.docmd.io/zh/engines/js/) --- title: "JavaScript 引擎" description: "深入探索 docmd 的原生 JavaScript 执行引擎:用例、可移植性、功能和限制。" --- **JavaScript 引擎**是内置到 docmd 中的基础执行引擎。它在现代 JavaScript 运行时上轻松运行。它在没有外部依赖或复杂编译器的情况下提供出色的性能。 默认情况下,每个 docmd 仓库都依赖于 JavaScript 引擎。它提供高度可靠的文件遍历、元数据索引和构建生成。 ## 配置 要明确指示 docmd 使用 JavaScript 后端,在 `docmd.config.json` 中将 `engine` 属性定义为 `"js"`。 ```json { "title": "开发者手册", "engine": "js", "src": "docs", "out": "site" } ``` ## 理想用例和优势 JavaScript 引擎非常通用。它在以下条件下表现出色: - **标准仓库**:包含多达数百个页面的网站构建速度极快。它利用优化的 JIT 编译和原生 JSON 解析。 - **最大可移植性**:如果你的团队使用不同的操作系统或受限的企业网络,JavaScript 引擎可保证在任何地方完美构建。 - **快速原型开发**:本地开发构建受益于即时热重载(`npx @docmd/core dev`),初始化延迟低。 - **自定义脚本**:配置回退和插件集成在 JavaScript 中自然执行。标准字符串解析避免了跨边界序列化成本。 ## 可用设备和主机兼容性 因为它完全在原生运行时环境中运行,JavaScript 引擎支持详尽的目标平台阵列: - **操作系统**:macOS、Linux、Windows、FreeBSD 和 OpenBSD。 - **硬件架构**:x64、ARM64(Apple Silicon、AWS Graviton)、ARMv7 和 RISC-V。 - **容器环境**:Alpine Linux、标准 Debian/Ubuntu、无服务器构建运行器(Vercel、Netlify)和嵌入式 CI 流水线。 ## 功能和限制 | 维度 | JavaScript 引擎配置文件 | 操作影响 | | :--- | :--- | :--- | | **并发模型** | Node.js 事件循环 + 原生工作线程 | 出色的网络响应异步调度。磁盘密集型块平稳运行。 | | **Git 元数据处理** | 子进程编排(`child_process.execFile`) | 安全地生成原生 Git 二进制文件以获取提交历史。包括持久磁盘缓存。 | | **设置和初始化** | 零配置 | 瞬间启动。不需要包后安装编译。 | | **可扩展性上限** | 在约 1,000 个文档内高性能 | 在超过一千个复杂文件的单体仓库上,顺序子进程开销可能会引入轻微的延迟。 | ## 功能完整性 JavaScript 引擎在**通用功能支持方面是独占的**。每个核心功能、高级语法、模板区域和官方插件都经过精心设计,可在此处轻松运行。 无论是编译数学公式、渲染实时搜索索引还是生成静态站点地图,JavaScript 引擎都保证确定性构建。 --- ## [引擎概览](https://docs.docmd.io/zh/engines/overview/) --- title: "引擎概览" description: "了解可插拔的构建引擎架构并选择最佳的处理后端。" --- 编译器具有高度模块化的多线程**可插拔引擎架构**。它将编排与计算任务解耦,以高效执行繁重的工作负载。 在零配置的 **JavaScript 引擎**和加速的 **Rust 引擎**之间进行选择。根据仓库大小、平台和性能需求选择引擎。 ## 可用引擎 | 引擎 | 标识符 | 默认 | 目标用例 | 核心优势 | | :--- | :--- | :---: | :--- | :--- | | **JavaScript 引擎** | `"js"` | ✅ 是 | 标准网站、快速本地原型开发、可移植性。 | 在任何支持 Node.js 的设备上通用运行。 | | **Rust 引擎(预览)** | `"rust"` | ❌ 否 | 大型仓库(1,000+ 文件)、企业 CI/CD 构建。 | 通过 Tokio 最大化并行文件 I/O。 | ## 配置选项 在 `docmd.config.json` 文件中配置构建引擎。直接设置 `engine` 参数。 ```json { "title": "企业参考", "engine": "js", "src": "docs", "out": "site" } ``` ### 完整选项参考 | 键 | 支持的值 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `engine` | `"js"`、`"rust"` | `"js"` | 处理文件发现和批量读取的执行层。 | ## 高级功能和限制 两个引擎共享严格的执行边界。核心 API 层强制执行统一的安全性和确定性输出。 ### 共享功能 - **线程隔离**:引擎在隔离的工作线程内安全地执行异步任务。这可防止阻塞主服务器循环。 - **任务验证**:严格的白名单防止未经授权的磁盘访问或未验证的执行模式。 - **无缝互操作性**:插件通过标准化接口(`runWorkerTask`)请求数据。它们不知道底层后端。 ### 架构限制 - **序列化开销**:数据跨越原生运行时边界(N-API)。传递大型 JSON 对象的高度迭代任务会产生少量序列化损失。 - **二进制兼容性**:JavaScript 引擎在任何地方原生运行。Rust 引擎依赖于通过 npm 分发的特定于操作系统的平台二进制文件。 ## 引擎加载器的工作原理 当 `@docmd/core` 启动时,内部加载器会检查你的活动配置: 1. **解析**:如果配置为 `"rust"`,引擎会延迟加载特定于架构的原生包(例如 `@docmd/engine-rust-darwin-arm64`)。 2. **优雅降级**:如果二进制文件缺失或不受支持,引擎会记录一条建议通知。然后它会透明地降级到 JavaScript 引擎。你的构建始终会成功。 探索每个引擎的深入文档: - [JavaScript 引擎参考](js.md) - [Rust 引擎参考](rust.md) --- ## [Rust 引擎](https://docs.docmd.io/zh/engines/rust/) --- title: "Rust 引擎" description: "探索可选的原生 Rust 引擎:用例、文件 I/O 功能、支持的包和限制。" --- **Rust 引擎**是一个可选的高性能执行引擎。它加速大型文档项目中繁重的 I/O 工作负载。通过 N-API 使用原生二进制文件,它绕过标准事件循环限制,实现多线程文件读取和子进程编排。 作为**实验性预览**提供,Rust 引擎面向企业规模。它在数千个 Markdown 文件和详尽的 Git 日志引入编译瓶颈时表现出色。 ## 配置 要激活原生 Rust 加速,在 `docmd.config.json` 文件中将 `engine` 指令配置为 `"rust"`。 ```json { "title": "全球 API 注册表", "engine": "rust", "src": "docs", "out": "site" } ``` ## 理想用例和优势 Rust 引擎解决特定的编译瓶颈。在以下场景下它提供出色的效率提升: - **大型仓库(1,000+ 文件)**:单体项目从通过 Tokio 编排的异步并行文件系统访问中获益巨大。 - **密集的 Git 元数据提取**:跨数百个页面提取深层提交日志需要大量子进程生成。Rust 引擎处理 `git:log` 任务的速度比 JavaScript **快约 1.24 倍**。 - **CI/CD 中的冷构建加速**:在磁盘缓存不可用的环境中,原始文件读取吞吐量可减少总处理时间。实际基准测试显示**冷构建速度提升约 25%**,**热构建改善约 17%**。 ## 支持的设备和平台包 引擎执行预编译的机器码。它需要专用的原生二进制文件,这些文件针对你的目标主机架构进行了定制。基础的 `@docmd/engine-rust` 包在启动时自动延迟加载正确的平台二进制文件。 目前分发以下平台包: | 平台包 | 目标架构 | 主机操作系统 | | :--- | :--- | :--- | | `@docmd/engine-rust-darwin-arm64` | ARM64(Apple Silicon) | macOS | | `@docmd/engine-rust-darwin-x64` | x64(Intel) | macOS | | `@docmd/engine-rust-linux-x64-gnu` | x64 | Linux(glibc 环境) | | `@docmd/engine-rust-linux-arm64-gnu` | ARM64 | Linux(glibc 环境) | | `@docmd/engine-rust-win32-x64-msvc` | x64 | Windows | ::: callout info "透明优雅降级" 如果你的环境缺少可用的预构建二进制文件,引擎会记录一条非致命通知并**自动降级**到高性能 JavaScript 引擎。你的构建保持完全确定性。 ::: ## 功能和战略限制 为了实现最大效用,你必须了解其架构权衡。引擎擅长 I/O 密集型操作,但在跨边界序列化期间会产生开销。 | 功能 / 任务 | Rust 引擎性能配置文件 | 架构评估 | | :--- | :--- | :--- | | **批量文件发现和读取** | 通过并行 Tokio 工作线程加速。 | ✅ 对大型目录非常有效。 | | **Git 提交日志提取** | 快速子进程编排,绕过 Node 事件循环。 | ✅ 对冷启动 Git 元数据提取非常出色。 | | **持久磁盘缓存** | 原生支持锚定磁盘缓存以消除冗余读取。 | ✅ 对热构建非常有效。 | | **CPU 密集型搜索索引** | **比原生 JavaScript JIT 更慢。** | ❌ 由于双重序列化开销而效率低下。 | ### 双重序列化税的解释 docmd 核心编排器与原生 Rust 引擎之间的通信依赖于跨 N-API 运行时边界传递的字符串化 JSON: ```text JS Worker → JSON.stringify() → NAPI Boundary → Serde Deserialisation → [Rust Task] → Serde Serialisation → NAPI Boundary → JSON.parse() ``` 对于 I/O 密集型操作(如查询 Git 历史或读取磁盘缓冲区),节省的处理时间远超字符串转换成本。 然而,对于高度迭代的 CPU 密集型任务(如全文搜索索引 `search:index`),**序列化往返消耗的 CPU 资源比底层任务本身更多**。来回序列化大型内容数组会导致 Rust 实现比 Node 的原生 JIT 字符串操作运行得更慢。 因此,**JavaScript 引擎仍然是语义搜索管道的推荐运行时**。有选择地为大规模 Git 和文件管理工作负载启用 Rust 引擎。 --- ## [安装](https://docs.docmd.io/zh/getting-started/installation/) --- title: "安装" description: "全局安装、本地安装 @docmd/core,或使用官方 Docker 镜像运行。需要 Node.js 18+。" --- 选择适合你工作流的安装方法。本地构建需要 Node.js 18 或更高版本。 ## 1. 本地安装(推荐) 在本地运行 `docmd` 可以将文档配置与你的源代码一起进行版本控制。 ::: tabs == tab "npm" icon:box ```bash # 作为开发依赖安装 npm install -D @docmd/core # 初始化新项目 npx docmd init ``` == tab "pnpm" icon:boxes ```bash # 作为开发依赖安装 pnpm add -D @docmd/core # 初始化新项目 pnpm dlx docmd init ``` == tab "yarn" icon:scroll ```bash # 作为开发依赖安装 yarn add -D @docmd/core # 初始化新项目 yarn dlx docmd init ``` == tab "Bun" icon:zap ```bash # 作为开发依赖安装 bun add -D @docmd/core # 初始化新项目 bunx docmd init ``` == tab "Docker" icon:container ```bash # 拉取官方多架构镜像 docker pull ghcr.io/docmd-io/docmd:latest # 构建文档(从本地 docs/ 编译到 site/) docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` 详情见 [Docker 部署指南](../deployment/docker.md),了解 Docker Compose 和 Kubernetes 配置。 ::: <img width="500" class="with-border" src="/assets/previews/terminal-npx-init.webp"> ::: callout tip "快捷脚本" icon:sparkles 本地安装后,你可以使用 `npx docmd dev` 启动实时预览服务器,或直接将其添加到 `package.json` 脚本中。 ::: ## 2. 全局安装 全局安装包,可在系统任何位置创建或预览网站,无需创建本地项目。 ::: tabs == tab "npm" icon:box ```bash npm install -g @docmd/core ``` == tab "pnpm" icon:boxes ```bash pnpm add -g @docmd/core ``` == tab "yarn" icon:scroll ```bash yarn global add @docmd/core ``` == tab "Bun" icon:zap ```bash bun add -g @docmd/core ``` ::: 全局安装后,`docmd` 二进制文件在任何地方都可用: ```bash docmd dev # 启动本地开发服务器 docmd build # 构建静态输出 ``` ## 3. 仅浏览器集成 通过 CDN 直接将引擎嵌入现有 Web 应用中。 ::: callout info "专用库集成" icon:help-circle 这绕过了 CLI,在读者的浏览器中加载解析引擎。用于动态门户,不是静态 SEO 网站。 ::: 将样式表和 JavaScript 引擎添加到你的 HTML 中。 ```html <!-- 核心样式表 --> <link rel="stylesheet" href="https://unpkg.com/@docmd/ui/assets/css/docmd-main.css"> <!-- 同构渲染引擎 --> <script src="https://unpkg.com/@docmd/live/dist/docmd-live.js"></script> ``` 详情见 [浏览器 API 指南](../api/browser-api.md)。 ## 4. 故障排除 ### 权限被拒绝(`EACCES` 错误) 在 macOS 或 Linux 上全局安装时,不要使用 `sudo`。使用 Node.js 版本管理器如 [nvm](https://github.com/nvm-sh/nvm) 或 [fnm](https://github.com/Schniz/fnm) 来解决权限冲突。 ### PowerShell 执行策略(Windows) 如果 Windows 阻止执行,请以管理员身份打开 PowerShell 并启用当前用户脚本执行。 ```powershell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser ``` --- ## [项目结构](https://docs.docmd.io/zh/getting-started/project-structure/) --- title: "项目结构" description: "学习 `@docmd/core` 如何将物理文件夹和 Markdown 文件映射为动态 URL 和清晰的导航结构。" --- 编译器使用本地文件系统作为数据来源。文件夹成为导航部分。Markdown 文件成为内容页面。你的目录层级直接转换为网页 URL。 ## 1. 标准项目脚手架 运行 `npx @docmd/core init` 建立最小化工作区布局。此结构将源内容与资源和生产构建分离。 ```text my-docs/ ├── docs/ ← 源目录,包含你的 Markdown (.md) 页面 │ └── index.md ← 首页(解析为 /) ├── assets/ ← 由引擎直接加载的静态网页资源 │ ├── css/ ← 自定义样式表,用于自定义页面布局 │ ├── js/ ← 自定义脚本,用于扩展浏览器端逻辑 │ └── images/ ← 品牌标志、图标和内联插图 ├── docmd.config.json ← 中央配置方案 ├── package.json ← Node 依赖清单和脚本 └── site/ ← 优化后的生产构建输出文件夹 ``` ::: callout info "配置文件解析" icon:settings `docmd.config.json`(或 `docmd.config.ts`)是推荐的、主要配置格式。旧的 `docmd.config.js` 格式仍然受支持,但仅作为缺少 `.json` 或 `.ts` 配置文件时的后备方案。 ::: ## 2. 目录和 URL 映射 编译器将源文件夹内的文件直接映射为公开 URL。没有尾随的 `.html` 扩展名或复杂的路由规则。 | 源文件 | 解析后的 URL 路径 | 用途 | | :--- | :--- | :--- | | `docs/index.md` | `/` | 首页 | | `docs/api.md` | `/api` | 主要 API 参考 | | `docs/guides/setup.md` | `/guides/setup` | 子章节技术指南 | | `docs/getting-started/quick-start.md` | `/getting-started/quick-start` | 多层级深层页面 | ::: callout tip "自动解析标题" icon:info 如果文件在其 YAML frontmatter 中缺少 `title`,引擎会提取第一个 `H1` 标签(`# Heading`)。此标题会显示在面包屑和搜索中。 ::: ## 3. 工作区 Monorepo 结构 对于复杂布局或具有多个独立产品的大型项目(如核心平台、SDK 和 CLI 工具),`docmd` 原生支持 **工作区 Monorepo** 目录结构。这允许你从单个根仓库管理多个独立的文档站点,同时保持统一的品牌标识。 ```text my-docs-monorepo/ ├── docmd.config.json ← 根配置(定义全局设置) ├── assets/ ← 共享全局资源(由所有项目继承) │ ├── css/ ← 共享全局样式表 │ └── images/ ← 共享标志和图标 ├── package.json ← 根依赖清单 ├── main-site/ ← 根项目目录 │ ├── docmd.config.json ← 项目特定配置覆盖 │ └── docs/ ← main-site 的内容(解析为 /) │ └── index.md └── sdk-reference/ ← 次要项目目录 ├── docmd.config.json ← 项目特定配置覆盖 └── docs/ ← sdk-reference 的内容(解析为 /sdk) └── index.md ``` ### 关键工作区目录模式 * **全局配置层叠:** 根 `docmd.config.json` 中定义的任何配置(如 `theme` 或 `menubar`)都作为后备默认值。各个项目可以在自己的本地配置文件中选择性地覆盖这些默认值。 * **资源分享和优先级:** 共享标志、全局自定义样式和通用脚本放在根 `assets/` 目录中。项目也可以定义自己的本地 `assets/` 目录;发生文件名冲突时,项目特定资源始终优先。 * **输出合并:** 在构建过程中(`npx @docmd/core build`),引擎自动将所有项目合并到单个整合的生产输出目录(例如 `./site/` 和 `./site/sdk/`),无需复杂的反向代理设置或独立的构建管道配置。 有关完整设置步骤和高级层叠规则,请参阅 [多项目配置指南](../configuration/workspaces.md)。 --- ## [快速开始](https://docs.docmd.io/zh/getting-started/quick-start/) --- title: "快速开始" description: "从空文件夹到运行中的文档网站,不到一分钟。" --- 在任何包含 Markdown 文件的文件夹中运行 docmd。无需配置文件、无需安装框架、无需配置知识。 ## 1. 启动开发服务器 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core dev ``` == tab "Bun" icon:zap ```bash bunx @docmd/core dev ``` ::: 访问 `http://localhost:3000`。你的文档已上线。 <img width="500" class="with-border" src="/assets/previews/terminal-npx-dev.webp"> ::: callout tip "自动端口故障转移" 如果端口 `3000` 已被占用,docmd 会自动寻找下一个可用端口(例如 `3001`)。 ::: ## 2. 自动完成的事项 引擎自动设置一切: 1. **目录检测** - 扫描 `docs/`、`src/docs/`、`documentation/` 或 `.md` 文件。 2. **导航生成** - 根据文件夹树自动构建嵌套侧边栏。 3. **标题提取** - 自动从第一个 `H1` 标题提取页面标题。 4. **搜索索引** - 立即启用内置全文搜索。 5. **智能缓存** - 文件保存时触发亚 200ms 的重建。 无需 `docmd.config.json`。稍后可添加来自定义布局、插件或版本。 ## 3. 构建生产版本 将 Markdown 文件编译为静态的、生产就绪的网站。 ::: tabs == tab "npm" icon:box ```bash npx @docmd/core build ``` == tab "Bun" icon:zap ```bash bunx @docmd/core build ``` ::: 编译器将静态网站输出到 `./site/`。 可以将此静态输出托管在任何地方。部署到 GitHub Pages、Vercel、Netlify 或任何静态主机。 --- ## [AI 友好型文档的上下文保留 (Context Preservation)](https://docs.docmd.io/zh/guides/ai-optimisation/context-preservation/) --- title: "AI 友好型文档的上下文保留 (Context Preservation)" description: "如何确保 AI 模型能够理解并利用文档不同部分之间的关系。" --- ## 问题 虽然人类读者可以轻松点击超链接来了解更多关于某个术语的信息,但 AI 模型通常以孤立的“块”形式处理文档。当 AI 遇到超链接时,它无法通过“点击”来获取更多上下文。如果关键信息隐藏在链接后面而不是在上下文中解释,AI 可能会无法提供准确的答案,从而导致幻觉。 ## 为什么这很重要 AI 模型依赖于紧邻的周围文本来确定信息的含义和相关性。如果你的文档高度碎片化且上下文保留较差,AI 驱动的搜索工具(如那些由 RAG 驱动的工具)将难以提供高质量的响应。 ## 方法 使用 **行内上下文展开 (Inline Context Unrolling)**,在每个主要链接旁边提供最小可行上下文。此外,利用 `docmd` 的特定功能,例如 [LLMs 插件](../../plugins/llms.md),来提供整个文档集的统一、机器可读视图。 ## 实现 ### 1. 描述性链接和摘要 避免使用通用的链接文本。相反,在链接本身之前或之后提供所链接概念的一句话简短摘要。 - **❌ 较差 (上下文丢失)**:要配置超时,请参考 [常规配置](../../configuration/overview.md)。 - **✅ 较好 (上下文保留)**:你可以在 [常规配置](../../configuration/overview.md) 中配置 `timeoutMs` 参数,该参数定义了引擎在网络请求失败前等待的时间。 ### 2. 使用折叠区块展示细节 [折叠容器](../../content/containers/collapsible.md) 非常适合 AI 优化。内容仍然是原始 Markdown 源码的一部分(AI 可以阅读),但它被视觉化地收纳起来以方便人类读者。 ```markdown ### 数据库连接 使用主 URI 进行连接。 ::: collapsible "URI 格式是什么?" URI 遵循标准的 PostgreSQL 格式:`postgresql://user:password@host:port/database`。 ::: ``` ### 3. 启用 LLMs 插件 在你的 `docmd.config.js` 中启用 [LLMs 插件](../../plugins/llms.md)。此插件会在每次构建后自动生成一个 `llms-full.txt` 文件,它将你的整个文档集连接成一个单一的、高上下文的文件,该文件可以轻松地被大型语言模型消费。 ## 权衡 行内上下文展开会使你的文档稍微冗长一些,并引入少量的冗余。然而,为了确保你的文档是“AI 就绪”的,并且能够支持高质量的自动化支持和搜索体验,这种冗余是一个很小的代价。 --- ## [创建确定性且可分块的文档](https://docs.docmd.io/zh/guides/ai-optimisation/deterministic-chunkable-docs/) --- title: "创建确定性且可分块的文档" description: "如何组织您的文档结构,以优化其在检索增强生成 (RAG) 和 AI 摄取中的表现。" --- ## 问题 当 AI 流水线(例如 RAG 架构)摄取文档时,它们会将 Markdown 源码切分成更小的“块”(例如每个块 500 个 token)。如果文档由冗长、杂乱且边界不明的段落组成,切分算法可能会在思绪中途切断上下文,从而破坏该块的效用,并导致 AI 的回答不完整或不正确。 ## 为什么重要 如果 AI 检索到的一个块包含代码示例,但遗漏了前面解释 *何时* 使用该代码的段落,那么生成的答案将缺乏必要的条件说明。为“可分块性”组织您的文档可确保每个文本段落都包含足够的上下文,从而能够独立发挥作用。 ## 方法 将您的页面组织成确定性的、原子化的块层级结构。使用 Markdown 标题清晰地描绘概念,并确保相关信息(如警告及其适用的代码)在源文件中物理位置紧密相连。 ## 实施 ### 1. 原子化标题部分 确保每个 `##` 或 `###` 标题都封装了一个单一的、原子化的概念。一个结构良好的部分应该能够作为一个有用的块独立存在,供 AI 模型使用。 - **✅ 正确**:标题为“通过 OAuth 进行身份验证”,后跟简短解释和代码示例。 - **❌ 糟糕**:一个庞大的“入门”页面,包含 15 个不同的概念且没有子标题。 ### 2. 关键信息的紧密排列 不要用长段落将关键警告与其适用的代码分开。使用 [标注 (Callouts)](../../content/containers/callouts) 将它们在纵向上绑定在一起。这增加了它们在摄取过程中保留在同一个向量块中的概率。 ```markdown ::: callout warning "破坏性操作" 运行此命令将永久删除所有日志。 ::: `docmd logs --clear` ``` ### 3. 自动化串联 [LLMs 插件](../../plugins/usage) 通过生成 `llms-full.txt` 文件来促进分块。该文件在页面之间使用标准分隔符 (`---`),帮助摄取流水线识别自然的文档边界,同时保留项目的全局上下文。 ## 权衡 这种方法更倾向于模块化、分段式的写作风格,而不是长篇大论。虽然这对人类读者来说可能感觉更具重复性,但它能显著提高依赖于您文档的 AI 驱动搜索和自动化支持代理的性能。 --- ## [使用 docmd 生成 AI 就绪的文档](https://docs.docmd.io/zh/guides/ai-optimisation/generating-ai-ready-docs/) --- title: "使用 docmd 生成 AI 就绪的文档" description: "如何使用 llms.txt 标准和 docmd 的内置工具为 AI 助手提供优化的上下文。" --- ## 问题 开发者越来越依赖 AI 编程助手(如 Cursor、GitHub Copilot 和 ChatGPT)来代表他们阅读和解释文档。如果您的文档只能通过浏览器访问,并且充斥着导航元素、追踪器和复杂的 HTML,AI 代理将在无关数据上消耗过多的 token,从而迅速耗尽其上下文窗口。 ## 为什么重要 提供文档的纯净、经过 token 优化的文本版本,相当于现代的提供高质量 REST API。它确保 AI 代理可以快速摄取您的整个文档集,从而提供更准确的代码建议,并为使用您产品的开发者提供更好的支持。 ## 方法 利用 `docmd` 内置的 **LLMs 插件**。该插件原生支持新兴的 `llms.txt` 标准,在每次构建过程中自动生成经过 token 优化的摘要文件和全上下文文件。 ## 实施 `llms` 插件可在 `docmd >= 0.7.0` 中使用,并可以在您的 [插件配置](../../plugins/usage) 中进行配置。 ### 1. 配置网站 URL 确保在 `docmd.config.json` 中正确设置了 `url` 属性。这允许插件为 `llms.txt` 文件中的所有页面生成绝对 URL。 ```json { "title": "我的项目文档", "url": "https://docs.example.com", "plugins": { "llms": {} } } ``` ### 2. 输出文件 在构建过程中,`docmd` 会在您的网站根目录下生成两个关键文件: - **`llms.txt`**:所有页面的简明、结构化的 Markdown 摘要,包括标题、描述和完整 URL。 - **`llms-full.txt`**:包含整个网站原始 Markdown 内容的综合文件,使用标准分隔符 (`---`) 进行串联。这为 AI 模型提供了终极的“事实来源”。 ### 3. 控制摄取 您可以使用 [页面 Frontmatter](../../content/frontmatter) 中的 `llms` 属性将特定页面排除在 AI 就绪输出之外。 ```yaml --- title: "内部调试指南" llms: false --- ``` ## 权衡 生成 `llms-full.txt` 会创建一个巨大的单一文件。对于异常庞大的文档网站,该文件可能会超过几兆字节。虽然这对于具有大上下文窗口的现代 LLM(如 Gemini 1.5 Pro 或 Claude 3.5 Sonnet)来说是理想的,但对于较小的模型来说可能过大。请确保逻辑清晰地组织您的 [导航](../../configuration/navigation),以便 AI 可以优先处理最重要的部分。 --- ## [MCP 与 Agent 技能](https://docs.docmd.io/zh/guides/ai-optimisation/mcp-and-agent-skills/) --- title: "MCP 与 Agent 技能" description: "使用 Model Context Protocol 和自定义技能为 AI 开发 Agent 优化你的文档工作区。" --- 将 AI 开发 Agent 集成到你的工作流中,需要结构化的接口来让模型高效地查询、读取和写入文档上下文。`docmd` 通过内置的 **Model Context Protocol (MCP)** 服务端和可扩展的 **Agent Skills (Agent 技能)** 数据库满足了这一需求。 ## Model Context Protocol (MCP) 配置 Model Context Protocol 将 LLM 环境直接连接到你的本地工作区工具。 ### 1. Claude Desktop 集成 将以下内容添加到你的 Desktop 配置文件中(macOS 上通常位于 `~/Library/Application Support/Claude/claude_desktop_config.json`,Windows 上位于 `%APPDATA%\Claude\claude_desktop_config.json`): ```json { "mcpServers": { "docmd": { "command": "npx", "args": ["@docmd/core", "mcp"], "cwd": "/您的/文档/项目/路径" } } } ``` ### 2. IDE 集成 (Cursor / Windsurf) 在编辑器的 MCP 设置面板中,添加一个使用 `stdio` 传输协议的新服务端: - **命令 (Command)**: `npx @docmd/core mcp` - **传输协议 (Transport)**: `stdio` ## 可用的 MCP 工具 连接成功后,Agent 将可以使用以下工具: 1. `search_docs(query)`: 执行工作区范围内的全文检索。 2. `read_doc(route)`: 获取特定路由的原始 Markdown 内容。 3. `validate_docs()`: 校验整个文档并返回验证错误(例如:损坏的链接)。 4. `get_llms_context()`: 获取合并后的 `llms-full.txt` 上下文文件。 ## 杠杆化 Agent 技能 (`SKILL.md`) 当你在项目中运行 `docmd init` 时,引擎会自动在你的根工作区生成一个 `SKILL.md` 文件。该文件可用作在你的仓库上工作的任何 AI Agent 的 Prompt 指导卡。 ### AI Agent 最佳实践 1. **优先阅读 SKILL.md**:指示你的 Agent 在编码会话开始时阅读 `SKILL.md` 文件。这有助于模型学习自定义标注、OpenAPI 标记和文件结构。 2. **修改后进行校验**:每当 Agent 修改 Markdown 文件时,都应当调用 `validate_docs` 工具(或运行 `npx @docmd/core validate`)来校验没有任何相对链接或锚点路径损坏。 3. **同步多语言**:如果项目使用版本控制或多语言环境,Agent 应当使用对比矩阵来确保所有翻译保持同步。 --- ## [通过文档减少 AI 幻觉](https://docs.docmd.io/zh/guides/ai-optimisation/minimising-ai-hallucinations/) --- title: "通过文档减少 AI 幻觉" description: "如何编写显式的、自包含的文档,以防止 AI 模型臆造错误信息。" --- ## 问题 AI 模型是预测引擎,而不是推理引擎。如果一个 API 使用示例不完整、使用了模糊的占位符或依赖于隐含知识,AI 通常会产生“幻觉” - - 它会根据在训练期间学到的通用模式来臆造缺失的部分。这些臆造的内容对于您的特定软件来说往往是错误的,会导致开发者的挫败感。 ## 为什么重要 幻觉代码会破坏用户信任。当开发者向 AI 寻求帮助并收到抛出语法错误或使用不存在参数的代码时,他们往往会归咎于软件本身“有缺陷”或“文档太烂”。减少幻觉对于维护项目的专业声誉至关重要。 ## 方法 实践 **防御性文档 (Defensive Documentation)**。这涉及编写极其显式、完全实例化的代码块,不留任何歧义空间。切勿假设读者(或 AI)了解必要的导入、环境变量或先决配置。 ## 实施 ### 1. 全限定代码块 始终在每个代码片段中包含必要的导入或设置代码。这确保了当 AI 对您的文档进行分块时,代码块仍然是一个自包含的事实单元。 - **❌ 存在幻觉风险**: ```javascript const config = loadConfig(); // loadConfig 是从哪里来的? ``` - **✅ 防御幻觉**: ```javascript import { loadConfig } from '@docmd/core'; const config = loadConfig(); ``` ### 2. 使用具体示例而非占位符 避免使用像 `your-api-key` 或 `env-name` 这样模糊的占位符。相反,提供具体的、有效的示例,或使用注释来指定严格的枚举要求。 ```javascript // 有效的环境:"development", "staging", "production" const app = init({ env: "production" }); ``` ### 3. 内联代码注释 将关键要求作为注释放在代码块 *内部*,而不仅仅是在周围的 Markdown 文本中。AI 模型在生成类似片段时,会非常重视代码内部的注释。 ```json { // 关键:out 必须是一个绝对文件系统路径。 "out": "/var/www/html/docs" }; ``` ### 4. 分类的警告 使用 [标注 (Callouts)](../../content/containers/callouts) 来清晰地标记弃用的功能或破坏性变更。AI 模型比段落中的简单句子更有可能尊重 `::: callout warning` 块。 ## 权衡 防御性文档会使代码块变得更长且更具重复性。人类读者可能会觉得在每个片段中看到相同的 `import` 语句稍微有些乏味。然而,拥有能够显著减少支持工单和用户错误的“防 AI (AI-proof)”文档所带来的好处,远超其冗长带来的微小代价。 --- ## [为语义搜索和 RAG 设计文档](https://docs.docmd.io/zh/guides/ai-optimisation/semantic-search-design/) --- title: "为语义搜索和 RAG 设计文档" description: "如何组织文档结构,以优化其在基于向量的搜索和检索增强生成中的表现。" --- ## 问题 传统的关键字搜索(如 [docmd 的内置搜索](../../plugins/search))依赖于精确的文本匹配。如果用户搜索“身份验证”,基本的关键字引擎可能会因为页面标题为“集成 OAuth2”且该词出现频率不够而无法找到该页面。语义搜索使用向量嵌入来理解查询的 *含义*,解决了这个问题,但需要特定的文档结构才能有效。 ## 为什么重要 现代开发者期望直观、基于意图的搜索体验。如果您的文档由于微小的术语差异而无法显示相关内容,用户将很快放弃您的网站并寻求其他帮助。为语义搜索进行设计可以确保您的文档在用户使用不同术语时仍具有可发现性。 ## 方法 组织您的文档,使其易于被检索增强生成 (RAG) 流水线消费。这涉及创建“语义密集型”内容,其中概念被清晰定义,并且代词被显式实体替换,以便在分块和向量化过程中保留上下文。 ## 实施 ### 1. 丰富的 Frontmatter 元数据 使用 [Frontmatter](../../content/frontmatter) 提供在正文中可能不会自然使用的显式关键字和描述。这为搜索引擎提供了额外的内容“挂钩”。 ```yaml --- title: "集成 OAuth2" description: "了解如何实现安全的身份验证和单点登录 (SSO)。" keywords: ["login", "authentication", "sso", "security", "identity"] --- ``` ### 2. “语义密度”策略 RAG 系统将文档切分为小块(向量)。每个章节的第一段应该包含与该主题相关的、密度最高的名词和动词。这确保了该章节的主要“含义”被捕获在初始向量中。 - **✅ 正确**:“本指南解释了如何实施 **OAuth2 单点登录 (SSO)**,为您的文档网站提供安全的 **身份验证**。” - **❌ 糟糕**:“在本节中,我们将讨论它是如何工作的,以及您如何轻松地设置它。” ### 3. 避免代词歧义 在分块数据库中,如果定义“它”的前一个段落被切分到了不同的块中,那么像“它适用于任何提供商”这样的句子就是无用的。请务必显式表达。 - **❌ 歧义**:“它具有高度的可扩展性。” - **✅ 显式**:“**docmd 搜索引擎** 旨在具有高度的可扩展性。” ## 权衡 为语义密度而写作有时会比传统的叙述性写作感觉稍微正式或具有重复性。然而,由此带来的可发现性的提高以及 AI 生成回答的准确性,使得这成为现代企业级文档的重要实践。 --- ## [为 AI 代理构建文档结构](https://docs.docmd.io/zh/guides/ai-optimisation/structure-for-llms/) --- title: "为 AI 代理构建文档结构" description: "如何从视觉格式转向语义化结构,以提高 AI 编码助手的准确性。" --- ## 问题 人类读者依靠视觉线索、侧边栏导航和推断上下文来理解文档。然而,AI 代理和大型语言模型 (LLMs) 主要消费原始文本流。当文档缺乏严格的语义结构时,这些模型难以映射概念之间的关系,从而导致推理较差和不准确的编码建议。 ## 为什么这很重要 如果你的文档未针对 LLM 进行优化,那么使用 GitHub Copilot、Cursor 或 ChatGPT 等工具的开发人员在处理你的软件时将会遇到更多的幻觉。这直接降低了开发人员的体验,因为用户通常会因为 AI 助手生成的错误而归咎于产品本身。 ## 方法 从"视觉优先"的心态转变为 **"语义优先"** 的心态。使用标准的 Markdown 功能——例如严格的标题层次结构、明确的代码块语言标签和描述性的替代文本——为你的内容提供清晰、机器可读的路线图。`docmd` 通过 [LLMs 插件](../../plugins/llms.md) 将这种结构处理成优化的输出。 ## 实现 ### 1. 严格的标题层次结构 避免为了纯粹的视觉效果而跳过标题级别。一致的层次结构允许 LLM 理解不同章节的范围和关系。 - **`#` 标题**: 页面的主要主题。 - **`##` 主要概念**: 一个原子的、高层的话题。 - **`###` 细节**: 该概念的一个特定子任务或属性。 * **❌ 较差**: 在 `#` 之后立即使用 `###`,只是因为你喜欢较小的字体。 * **✅ 较好**: `# 安装` 之后是 `## 前提条件`,然后是 `### 系统要求`。 ### 2. 媒体的描述性元数据 由于 LLM 无法“看到”图像或图表,你必须在替代文本或相邻段落中提供架构上下文。 ```markdown ![系统架构:前端 React 应用程序通过 REST 与 Node.js API 通信,后者随后查询 Redis 缓存和 PostgreSQL 数据库。](../../static/img/architecture.png) ``` ### 3. 明确的代码块标签 始终使用 [语法高亮](../../content/syntax/index.md) 为每个围栏代码块指定语言。这允许 LLM 正确解析代码的抽象语法树 (AST)。 ```json { "plugins": { "llms": {} } } ``` ### 4. 语义化容器 使用 [标注](../../content/containers/callouts.md) 而不是通用的块引用来提供意图。`docmd` 的语义容器帮助 AI 模型区分核心指令与补充技巧或警告。 ## 权衡 语义上的严谨要求作者具有自律性。你不能再将 Markdown 功能(如块引用或标题)纯粹用作装饰元素。然而,这种自律产生的文档对于 AI 代理和使用辅助技术的人类读者来说,其可访问性都将显著提高。 --- ## [避免反模式](https://docs.docmd.io/zh/guides/content-ux/avoiding-anti-patterns/) --- title: "避免反模式" description: "如何识别并消除常见的文档错误,这些错误会降低用户体验并增加内容债务。" --- ## 问题 随着时间的推移,文档存储库往往会积累一些针对内容问题的“快速修复”,这些修复会无意中侵蚀用户体验。这些反模式 - - 例如模糊的链接文本或臃肿的代码示例 - - 在项目中根深蒂固,使得文档难以维护,对开发者的价值也随之降低。 ## 为什么重要 反模式会导致“内容债务”。它们会降低搜索引擎排名 (SEO),降低残障人士的可访问性,并显著增加读者的认知负荷,而读者仅仅是想快速找到技术问题的解决方案。高质量的文档需要不断的警惕,以保持其整洁、简练且专业。 ## 方法 在 [同行评审流程](../workflows-teams/git-based-workflows.md) 中识别并无情地消除常见的反模式。使用 Vale 等自动化的散文检查工具以及人工审核,确保您的内容在所有页面上保持高质量、易于访问且一致。 ## 实施 ### 1. 非描述性超链接 避免在链接中使用“点击这里”或“阅读更多”等通用文本。这不仅对 SEO 有害,还会导致使用屏幕阅读器的用户无法访问文档,因为他们通常通过在链接之间跳转来浏览页面。 * **❌ 错误示例**:要配置您的服务器,请 [点击这里](../../configuration/overview.md)。 * **✅ 正确示例**:查看 [全局配置](../../configuration/overview.md) 以设置您的生产服务器。 ### 2. “样板代码墙” 在代码示例中,如果核心逻辑之前包含数十行标准导入和样板配置,会分散读者对示例实际重点的注意力。 * **解决方案**:专注于相关的代码片段。如果为了提供上下文而必须包含样板代码,请使用注释说明为了简洁而省略了标准导入,或者使用 [标注](../../content/containers/callouts.md) 来解释所需的设置。 ### 3. 将 FAQ 视为“垃圾场” “常见问题解答”(FAQ) 页面往往成为了难以整合进主指南的信息库。如果一个问题确实是“经常被问到”的,这清楚地表明您的核心文档未能有效地解释该概念。 * **解决方案**:不要将其添加到 FAQ,而是重构相关的教程或概念指南,在用户首次遇到困惑的地方直接解决它。如果信息对操作成功至关重要,请使用 [重要标注](../../content/containers/callouts.md)。 ## 权衡 消除 FAQ 要求作者在发现新的支持问题时不断重构和改进现有的文档层级。虽然这比简单地在 FAQ 列表末尾添加一个要点增加了更多的初始维护开销,但它会为您的用户带来一个更加连贯、专业且实用的文档网站。 --- ## [提高可读性 (Improving Readability)](https://docs.docmd.io/zh/guides/content-ux/improving-readability/) --- title: "提高可读性 (Improving Readability)" description: "如何利用视觉节奏、信息层次结构和 docmd 的结构化工具来创建高度可读的文档。" --- ## 问题 技术文档通常内容密集、术语繁多且难以扫描。当读者遇到没有任何视觉缓冲的“文字墙”时,他们往往会跳过重要细节,或者完全错过关键的安全警告。密集的格式增加了认知摩擦,导致用户产生挫败感并可能引发错误。 ## 为什么这很重要 可读性不仅仅是一种美学选择——它是一项功能要求。如果一个开发人员因为警告被埋没在长篇大论中而错过了它,后果可能会非常严重。清晰的信息层次结构可确保用户能够快速找到所需信息,准确理解并安全地采取行动。 ## 方法 通过打破长段落并使用 [主题容器](../../content/containers/index.md) 突出显示关键信息,建立一种可预测的视觉节奏。利用 `docmd` 内置的结构化工具,你可以创建一个自然引导读者视线看向页面最重要部分的层次结构。 ## 实现 ### 1. “简洁的力量” 尽量将段落限制在三或四句话以内。短段落更易于在屏幕上消化,并为复杂的技术概念提供了自然的“喘息空间”。如果一个段落感觉太长,请考虑将其拆分为列表或使用子标题对信息进行重新分类。 ### 2. 使用标注进行分类 一致地使用 [标注](../../content/containers/callouts.md) 对信息进行分类。这允许正在扫视的用户根据块的视觉样式立即识别其意图: * **Info (信息)**:背景上下文或补充细节,提供更深入的理解。 * **Tip (技巧)**:最佳实践、快捷方式和提高效率的“专业技巧”。 * **Warning/Danger (警告/危险)**:可能导致错误、数据丢失或安全漏洞的关键操作。 ```markdown ::: callout warning "生产环境安全" 在未先核实备份的情况下,切勿在实时数据库上执行此命令。 ::: ``` ### 3. 使用步骤进行顺序说明 对于教程和分步指南,请避免对操作进行叙述性描述。相反,使用 [步骤容器](../../content/containers/steps.md) 创建一个清晰、带编号的进程,使其易于遵循。 ```markdown ::: steps 1. **初始化**: 在项目根目录下运行 `npx @docmd/core init`。 2. **配置**: 更新你的 `docmd.config.js`,包含你的站点标题和导航。 3. **构建**: 运行 `npx @docmd/core build` 生成生产就绪的静态文件。 ::: ``` ## 权衡 使用 `::: steps` 或 `::: callout` 等专门的容器要求贡献者学习 `docmd` 特有的 Markdown 扩展。虽然这增加了一点学习曲线,但信息密度、清晰度和专业呈现方面的显著提升,远远超过了学习这些强大结构化标签所付出的微小努力。 --- ## [大型站点的导航设计](https://docs.docmd.io/zh/guides/content-ux/navigation-large-sites/) --- title: "大型站点的导航设计" description: "如何使用 docmd 的布局工具,将复杂的文档集组织成直观、可扩展的导航结构。" --- ## 问题 随着文档站点从几十页增长到几百或几千页,简单的侧边栏往往会变成深层嵌套文件夹的混乱迷宫。当用户被迫展开多层级目录仅仅为了寻找一个特定的参考信息时,他们会丢失上下文,感到挫败,并往往会放弃文档而转向“试错法”。 ## 为什么重要 导航是您产品功能的“地图”。如果导航难以使用,用户将完全依赖搜索栏,这可能导致知识的碎片化。一个结构良好的导航系统可以在用户浏览时向其传授产品的逻辑和分类,帮助他们随着时间的推移变得更加熟练和自给自足。 ## 方法 优先考虑 **顶级上下文切换 (Top-Level Context Switching)** 而不是深层嵌套。目标是将左侧边栏限制在不超过两到三个层级的深度。使用水平 [菜单栏 (Menubar)](../../configuration/menubar) 分隔不同的文档“领域”(例如:指南、API 参考和社区),这允许每个单独的侧边栏保持聚焦、相关且易于管理。 ## 实施 ### 1. 基于领域的划分 在您的 `docmd.config.js` 中,使用 [菜单栏 (Menubar)](../../configuration/menubar) 将您的内容划分为高级类别。这种方法允许您为每个领域呈现完全不同的侧边栏,防止单一导航树变得过于臃肿。 ### 2. 扁平化层级结构 与其将一个单一的概念拆分为许多零散的 Markdown 页面,不如将相关信息整合到综合性的父页面中。使用清晰的 [标题层级](../../content/syntax),允许用户使用自动生成的右侧目录 (TOC) 在页面内进行导航。 * **❌ 糟糕的信息架构 (IA)**:一个名为“安全”的文件夹,包含十个独立的、只有一个段落的各种协议文件。 * **✅ 更好的信息架构 (IA)**:一个结构良好的“安全概述”页面,涵盖所有协议,并使用标题提供整洁的目录 (TOC)。 ### 3. 利用可折叠部分 对于不经常访问的大组相关内容,在您的 [导航配置](../../configuration/navigation) 中使用 `collapsible` 属性。这通过隐藏次要信息直到用户明确请求,来保持界面的整洁。 ```json // navigation.json { "title": "API 参考", "collapsible": true, "collapsed": true, "children": [ { "title": "身份验证", "path": "api/auth" }, { "title": "端点", "path": "api/endpoints" } ] } ``` ## 权衡 将内容整合到更少、更长的页面中,要求作者在结构清晰度和标题使用方面保持严谨。如果一个页面太长而没有适当的内部导航 (TOC),它本身可能变成一面“文字墙”。然而,对于大型文档集来说,显著减少“点击疲劳”和改进相关内容的发现,使得扁平的、基于领域的层级结构更具优势。 --- ## [可扩展的技术写作 (Scalable Technical Writing)](https://docs.docmd.io/zh/guides/content-ux/scalable-technical-writing/) --- title: "可扩展的技术写作 (Scalable Technical Writing)" description: "如何使用渐进式披露和结构化容器来管理不断增长的文档复杂性,而不让用户感到不知所措。" --- ## 问题 在产品的早期阶段,记录一个功能可能只需要几个段落。然而,随着产品演变为企业平台,这些段落可能会激增,变成充斥着边缘案例、平台特定变体(Docker、Kubernetes、Cloud)以及复杂配置选项的海洋。这会导致“垂直膨胀”,即单页面变成难以阅读、难以导航且难以维护的文字墙。 ## 为什么这很重要 垂直膨胀会破坏理解并增加认知负荷。当用户被迫滚动浏览大量与其特定环境或用例无关的内容时,他们会感到不知所措,并往往认为产品比实际情况更复杂。可扩展的写作可确保用户在任何特定时刻只看到他们需要的信息,从而保持一条清晰的成功之路。 ## 方法 实施 **渐进式披露 (Progressive Disclosure)**。这种技术涉及预先仅呈现最关键的信息(“快乐路径”),并将更复杂、技术性更强或更具体的细节隐藏在交互式 UI 结构后面。`docmd` 提供了几种专门设计的内置容器,可帮助你有效且优雅地管理这种复杂性。 ## 实现 ### 1. 使用选项卡处理变体 与其按顺序罗列多个包管理器、操作系统或云提供商的说明,不如使用 [选项卡容器](../../content/containers/tabs.md)。这允许用户选择他们的特定环境,即时隐藏无关的命令并减少视觉噪音。 ````markdown ::: tabs == tab "npm" ```bash npm install docmd ``` == tab "pnpm" ```bash pnpm add docmd ``` ::: ```` ### 2. 使用折叠区块管理边缘案例 如果一个故障排除步骤或特定的边缘案例仅适用于极少数用户,请不要让它中断主教程的逻辑流程。使用 [折叠容器](../../content/containers/collapsible.md) 来埋没这些细节,同时在需要时保持它们易于访问。 ```markdown 1. 通过运行 `npx @docmd/core dev` 启动开发服务器。 ::: collapsible "故障排除:端口已被占用" 如果你收到 `EADDRINUSE` 错误,可以使用 `--port` 标志指定自定义端口:`npx @docmd/core dev --port 4000`。 ::: ``` ### 3. 使用标注提供渐进式细节 使用 [标注](../../content/containers/callouts.md) 提供补充信息,这些信息虽然不是主要任务所必需的,但能为高级用户提供有价值的上下文。 ## 权衡 将内容隐藏在选项卡或折叠区块中偶尔会使用户更难使用浏览器的原生 `Ctrl+F` 搜索来查找信息。然而,`docmd` 集成的 [搜索引擎](../../plugins/search.md) 会对这些容器内的所有内容进行索引,从而确保用户在享受更整洁的阅读体验的同时,仍能通过网站的主搜索界面准确找到他们需要的内容。 --- ## [任务 vs 概念](https://docs.docmd.io/zh/guides/content-ux/task-vs-concept/) --- title: "任务 vs 概念" description: "如何应用 Diátaxis 框架,将“操作指南”与“概念解释”分离开来,以构建更有效的文档结构。" --- ## 问题 技术写作中常见的一个错误是将“为什么要这样做”与“如何具体操作”混为一谈。例如,一个关于“配置 SSO”的教程,很容易因为大篇幅解释 SAML 协议的历史而变得冗长乏味,分散了用户实现功能这一首要目标的注意力。 ## 为什么重要 用户的意图会根据其当前所处的上下文而有很大差异。凌晨 2 点试图修复生产问题的工程师寻找的是具体、可操作的步骤,而不是架构哲学。相反,正在评估您平台的技术负责人则需要在投入实施之前理解其背后的逻辑。分离这些关注点可以确保这两类角色都能在没有不必要干扰的情况下找到所需的信息。 ## 方法 采用 **Diátaxis 框架**,它将文档分为四个不同的象限:教程 (Tutorials)、操作指南 (How-to Guides)、解释 (Explanation/Concepts) 和技术参考 (Technical Reference)。在本指南中,我们专注于**任务导向型内容**(可操作步骤)与**概念导向型内容**(深入理解)之间的关键分离。 ## 实施 ### 1. 任务导向型指南 (How-To) 完全专注于一个具体、明确的目标。删掉冗长的理论解释,专注于实现该目标所需的最少步骤。使用 [步骤容器 (Steps Container)](../../content/containers/steps) 提供清晰、无歧义的路径。 * **标题示例**:“如何配置 Webhook” * **结构**: * 前提条件 * 直接、可操作的说明 * 验证步骤(如何知道操作已成功) ### 2. 概念导向型指南 (Explanation) 专注于“大局”,包括架构、设计哲学以及特定决策背后的“原因”。在这些部分中,避免提供直接的指令或命令。 * **标题示例**:“理解 Webhook 交付架构” * **结构**: * 高层架构图 * 重试逻辑与可靠性哲学 * 安全注意事项 ### 3. 有效的交叉引用 不要合并这两类内容,而是使用 `docmd` 的链接工具为需要更多上下文或准备实施的用户提供桥梁。 * **在操作指南中**:“有关我们重试逻辑的深入探讨,请参阅 [Webhook 架构](../../guides/performance-delivery/caching-strategies)。” * **在概念指南中**:“准备好开始了吗?请遵循我们的 [Webhook 配置指南](../../guides/integrations/alongside-other-tools)。” ## 权衡 将任务与概念分离开来会增加导航中的页面数量,并需要更严格的交叉引用规范。然而,这种模块化结构显著提高了文档套件的长期可维护性、可搜索性以及整体专业性。 --- ## [自定义 Favicon 和元数据](https://docs.docmd.io/zh/guides/customisation/custom-favicons-metadata/) --- title: "自定义 Favicon 和元数据" description: "如何配置您网站在浏览器中的视觉标识并优化社交媒体预览。" --- ## 问题 默认的文档网站在浏览器中往往缺乏独特的视觉标识(使用通用的 favicon),并且在链接被分享到社交媒体或 Slack、Discord 等沟通工具时,提供的预览效果较差。这会降低品牌识别度和点击率。 ## 为什么重要 Favicon 是浏览器窗口中主要的视觉锚点。高质量的 OpenGraph 和 Twitter 元数据可以确保您的文档在分享时看起来专业且值得信赖,通过标题、描述和英雄图提供必要的上下文。 ## 方法 `docmd` 提供了一个内置的 `favicon` 属性,用于轻松配置图标。对于高级 SEO 和社交元数据,请利用 [SEO 插件](../../plugins/seo),它可以根据您的项目配置和页面 Frontmatter 自动生成元标签。 ## 实施 ### 1. 配置 Favicon 将您的 Favicon 文件(例如 `favicon.svg` 或 `favicon.ico`)放在源目录中,并在 `docmd.config.json` 中引用它。`docmd` 会自动处理相对路径和缓存失效。 ```json { "title": "我的项目", "favicon": "/favicon.svg" } ``` ### 2. 全局 SEO 配置 启用并配置 [SEO 插件](../../plugins/seo),为整个网站设置默认的社交媒体预览。 ```json { "url": "https://docs.example.com", "plugins": { "seo": { "defaultDescription": "关于我们神奇软件的终极指南。", "openGraph": { "defaultImage": "/static/og-banner.png" }, "twitter": { "siteUsername": "@myproject", "cardType": "summary_large_image" } } } } ``` ### 3. 页面级覆盖 您可以使用 [Frontmatter](../../content/frontmatter) 中的 `seo` 属性覆盖单个页面的 SEO 设置。 ```yaml --- title: "重大发布 v2.0" description: "关于我们新引擎您需要了解的一切。" seo: image: "/assets/v2-hero-banner.png" keywords: ["发布", "v2", "更新", "性能"] --- ``` ## 权衡 虽然 `favicon` 属性很方便,但它仅支持单个文件。对于复杂的多尺寸 Favicon 集(Apple Touch 图标、Android manifest 等),您可能需要使用自定义插件将额外的 `<link>` 标签注入 `<head>` 中。 --- ## [自定义字体和品牌](https://docs.docmd.io/zh/guides/customisation/custom-fonts-branding/) --- title: "自定义字体和品牌" description: "如何使用 CSS 变量使您的文档外观与企业形象保持一致。" --- ## 问题 确保您的文档平台与企业形象无缝匹配,对于维护专业外观至关重要。默认的字体堆栈和配色方案旨在提供通用可读性,但可能无法反映您的特定品牌个性。 ## 为什么重要 文档是一个关键的品牌触点。如果您的主产品使用了特定的字体(如 "Outfit")和独特的颜色,您的文档也应该反映这些相同的选择。所有 Web 资产的一致性可以建立信任,并提供更具凝聚力的用户体验。 ## 方法 `docmd` 使用一套 CSS 自定义属性(变量),这些属性定义了布局的视觉标记。您可以轻松地在自定义样式表中覆盖这些变量,而无需修改核心引擎。 ## 实施 ### 1. 创建自定义样式表 在您的源目录(或任何子目录)中创建一个名为 `custom.css` 的文件,并覆盖 `:root` 变量。 ```css /* 导入您的品牌字体 */ @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap'); :root { /* 品牌字体 */ --font-family-sans: "Outfit", system-ui, -apple-system, sans-serif; /* 品牌颜色 (浅色模式) */ --link-color: #8a2be2; /* 您的主品牌颜色 */ --link-color-hover: #7b1fa2; --bg-color: #fcfcfd; /* 细微的背景底色 */ } /* 深色模式覆盖 */ :root[data-theme="dark"] { --bg-color: #0d1117; --link-color: #a855f7; } ``` ### 2. 注册样式表 将您的自定义 CSS 文件添加到 `docmd.config.json` 中的 `theme.customCss` 数组中。 ```json { "theme": { "customCss": ["/custom.css"] } } ``` ## 权衡 导入外部字体(如 Google Fonts)会为初始页面加载增加少量的延迟。为了优化性能,请考虑将字体文件本地托管在您的项目中,并使用 `font-display: swap` 来防止自定义字体加载时的“无样式文本闪烁 (FOUT)”。 --- ## [设计自定义落地页](https://docs.docmd.io/zh/guides/customisation/custom-landing-pages/) --- title: "设计自定义落地页" description: "如何使用 docmd 的 hero 和 grid 容器为您的文档创建高级落地页。" --- ## 问题 默认情况下,大多数文档生成器中的 `index.md` 文件看起来都像一个标准的页面。创建一个具有高冲击力的、营销级的落地页通常需要使用单独的 Web 框架(如 Next.js 或 Astro),这增加了文档工作流的复杂性。 ## 为什么重要 您的文档首页通常是开发者与您产品的第一次互动。一个通俗的 Markdown 解析页面可能无法激发用户对您产品精致程度和专业质量的信心。自定义落地页可以更好地引导用户访问最重要的章节,同时强化您品牌的视觉身份。 ## 方法 `docmd` 提供了专门的 [Hero](../../content/containers/hero) 和 [网格 (Grid)](../../content/containers/grids-cards) 容器,专门用于构建高级落地页。为了获得完全的创作自由,您还可以使用 `noStyle` Frontmatter 属性来完全控制页面的 HTML 和样式。 ## 实施 ### 1. 使用 Hero 容器 `hero` 容器支持多种布局,包括 `split`(用于并排内容)和 `glow`(用于现代美学效果)。 ```markdown ::: hero layout:split glow:true # 使用 docmd 更快地构建 面向现代开发团队的零配置文档引擎。 [开始使用](../../getting-started/quick-start.md) [在 GitHub 上查看](https://github.com/docmd-io/docmd) == side ![仪表板预览](../../static/img/hero-preview.png) ::: ``` ### 2. 使用网格组织内容 使用 [网格和卡片](../../content/containers/grids.md) 创建高层级的导航区域,帮助用户快速找到所需内容。 ```markdown ::: grids ::: grid ::: card "快速入门" icon:rocket 在不到 5 分钟的时间内启动并运行。 [了解更多](../../getting-started/quick-start.md) ::: ::: ::: grid ::: card "API 参考" icon:code 我们所有端点的全面文档。 [探索 API](../../api/node-api.md) ::: ::: ::: ``` ### 3. 使用 noStyle 进行完全自定义 如果您需要一个完全自定义的设计,且忽略标准的文档布局(无侧边栏或页眉),请在 [页面 Frontmatter](../../content/frontmatter) 中使用 `noStyle` 属性。 ```yaml --- title: "自定义仪表板" noStyle: true --- ``` 设置 `noStyle: true` 后,`docmd` 将仅渲染您提供的原始 HTML/Markdown 内容,允许您注入自己的 CSS 和 JavaScript,以实现像素级的完美体验。 ## 权衡 使用 `noStyle: true` 意味着您放弃了 `docmd` 提供的原生导航、搜索和主题切换功能。您负责确保自定义页面是移动端自适应且符合无障碍要求的。对于大多数用例,在标准布局中结合使用 `hero` 和 `grid` 容器可以在美观和功能之间提供最佳平衡。 --- ## [使用自定义插件扩展 docmd](https://docs.docmd.io/zh/guides/customisation/extending-custom-plugins/) --- title: "使用自定义插件扩展 docmd" description: "如何使用 docmd 的生命周期钩子构建自定义功能并扩展文档引擎。" --- ## 问题 有时您有一些非常具体的需求,内置功能或现有插件无法满足。例如,您可能需要在构建过程中从内部 API 获取数据,或者对生成的 HTML 进行超出简单 CSS 范畴的复杂转换。 ## 为什么重要 可扩展性是静态工具与专业文档框架的区别所在。如果没有一种清晰的方式来注入自定义逻辑,团队往往不得不维护脆弱的 shell 脚本或后处理封装程序,这使得构建过程难以管理和调试。 ## 方法 `docmd` 具有强大的基于钩子的 [Plugin API](../../plugins/api)。您可以编写简单的 Node.js 模块,在文档生命周期的各个阶段(从初始配置到最终 HTML 生成)进行拦截,从而允许您任意修改内容和行为。 ## 实施 ### 1. 创建本地插件 插件是一个标准的 JavaScript 模块,它导出一个描述符和若干生命周期钩子。 ```javascript // plugins/version-injector.js export default { // 插件元数据 plugin: { name: 'version-injector', version: '1.0.0', capabilities: ['build'] // 使用 'build' 钩子所必需的 }, // 在钩子之间共享的状态 latestVersion: '0.0.0', // 在配置解析完成后运行 async onConfigResolved(config) { // 从内部 API 获取数据 const response = await fetch('https://api.internal.com/version'); this.latestVersion = await response.text(); console.log(`[插件] 已获取版本:${this.latestVersion}`); }, // 在模板渲染前拦截页面上下文 async onBeforeRender(page) { if (!page.html) return; // 在 HTML 和 frontmatter 中用动态数据替换占位符 page.html = page.html.replace(/\{\{VERSION\}\}/g, this.latestVersion); page.frontmatter.computedVersion = this.latestVersion; } }; ``` ### 2. 注册插件 您可以通过将本地插件导入到 `docmd.config.js` 中来注册它。 ::: callout info "为什么使用 .js 而不是 .json?" 插件注册需要 JavaScript 的 `import` 语句来加载模块。对于需要导入插件的配置,必须使用 `docmd.config.js`。 ::: ```javascript // docmd.config.js import VersionInjector from './plugins/version-injector.js'; export default { title: '我的项目文档', plugins: { // 通过提供导入的模块进行注册 'version-injector': VersionInjector } }; ``` ## 权衡 自定义插件在构建时的 Node.js 环境中运行。虽然功能强大,但如果不进行优化,可能会影响构建性能。像 `onAfterParse` 或 `onPageReady` 这样的钩子逻辑会为网站中的 *每一页* 运行。请确保您的转换是高效的(例如使用优化的正则表达式),以保持快速的构建速度。 --- ## [与其他工具并存](https://docs.docmd.io/zh/guides/integrations/alongside-other-tools/) --- title: "与其他工具并存" description: "如何将 docmd 集成到多工具文档生态系统中,以创建无缝的用户体验。" --- ## 问题 大型组织很少仅使用单一工具来满足其所有文档需求。您的公司可能使用 Confluence 编写内部规范,使用 Stoplight 进行 API 设计,使用 GitHub 存放代码示例。将这些分散的来源整合到一个统一的用户旅程中是一项重大挑战,因为用户经常发现自己在风格和导航完全不同的断开门户之间跳转。 ## 为什么重要 碎片化的文档体验会破坏开发者的信任并增加认知负荷。如果用户为了完成一个教程而被迫在完全不同的界面之间切换,他们更有可能丢失上下文或放弃您的产品。统一您的工具可确保专业、连贯的体验,鼓励用户进行探索和学习。 ## 方法 将 `docmd` 用作您的主要文档中心或“单一窗口 (Single Pane of Glass)”。通过利用 [菜单栏 (Menubar)](../../configuration/menubar) 实现统一导航,并利用 [嵌入容器 (Embed Containers)](../../content/containers/embed) 引入第三方内容,您可以创建一个无缝的界面,隐藏多工具基础设施的复杂性。 ## 实施 ### 1. 统一的全局导航 使用 `menubar` 配置将您的各个文档门户链接在一起。这可确保用户始终能找到返回主指南的路径,无论他们当前处于哪个子域名。 ```json { "layout": { "menubar": { "left": [ { "text": "指南", "url": "/" }, { "text": "API 参考", "url": "https://api.example.com" }, { "text": "社区", "url": "https://forum.example.com", "external": true } ] } } } ``` ### 2. 无缝嵌入 对于提供 Web 界面(如交互式 API 资源管理器或仪表板预览)的工具,使用 `::: embed` 容器直接在您的 `docmd` 页面中显示它们。这可以将用户留在您的品牌环境中。 ```markdown # 交互式 API 资源管理器 ::: embed "https://api.example.com/v1/explorer" ::: ``` 有关更多信息,请参阅 [嵌入参考](../../content/containers/embed)。 ### 3. 内容聚合 对于必须与您的核心文档一起被搜索的外部内容,考虑建立一个构建步骤,从其他来源获取数据并将其转换为 Markdown。这允许 `docmd` 在单一、统一的 [搜索索引](../../plugins/search) 中索引您的所有信息。 ## 权衡 虽然嵌入提供了统一的外观,但它偶尔会引入性能开销或在移动设备上出现“滚动嵌套”问题。此外,iframe 内的内容不会原生被 `docmd` 的搜索引擎索引。如果搜索一致性至关重要,建议优先考虑 [OpenAPI 生成](./openapi-generation) 或其他基于 Markdown 的摄取方法。 --- ## [选择部署方式](https://docs.docmd.io/zh/guides/integrations/choosing-deployment-method/) --- title: "选择部署方式" description: "docmd GitHub App、GitHub Action、起始模板与部署器包的实用对比指南——含决策矩阵与真实使用场景。" --- # 选择部署方式 docmd 提供四种方式将您的文档上线。它们的输出完全相同——一个静态站点,部署至 GitHub Pages 或您选择的托管服务——但在控制程度和起点上有所不同。 ## 快速决策矩阵 | | [GitHub App](../../integrations/github-app.md) | [起始模板](../../integrations/starter-template.md) | [GitHub Action](../../integrations/github-action.md) | [部署器包](../../deployment/deployer-package.md) | |---|---|---|---|---| | **起点** | 现有仓库 | 新仓库 | 任意 | 任意 | | **配置工作量** | 一键 | 两步 | 编写 YAML | 运行命令 | | **工作流文件** | 自动生成 | 已包含 | 自行编写 | 自动生成 | | **可定制性** | 生成后编辑 | 从一开始 | 完全自定义 | 完全自定义 | | **托管目标** | GitHub Pages | GitHub Pages | GitHub Pages | 任意服务商 | | **Monorepo 支持** | ✓ 自动检测 | — | 手动 `--cwd` | ✓ | | **非 GitHub 托管** | ✗ | ✗ | 可适配 | ✓ Docker、Nginx、Vercel、Netlify… | ## 场景指南 ### "我想在两分钟内上线,零配置" 使用 **[GitHub App](../../integrations/github-app.md)**。安装后选择仓库即可。它会检测您的配置、生成工作流、启用 GitHub Pages 并完成部署——无需修改任何文件。 ::: button "安装 GitHub App" external:https://github.com/apps/docmd/installations/new icon:github color:#2ea44f --- ### "我正在创建一个全新的文档站点" 使用 **[起始模板](../../integrations/starter-template.md)**。在 GitHub 上点击"使用此模板",更新 `docmd.config.json` 中的标题和 URL,一次性启用 GitHub Pages,然后推送即可。 ::: button "使用起始模板" external:https://github.com/docmd-io/docmd-template/generate icon:github --- ### "我有现有的 CI/CD 流水线,想将文档加入其中" 使用 **[GitHub Action](../../integrations/github-action.md)**。将 `docmd-io/deploy@v1` 加入您现有的工作流,它可与其他步骤无缝组合——运行测试、构建应用、再构建文档,全在一个 Job 中完成。 --- ### "我要部署到 Vercel、Netlify、Docker 或自有服务器" 使用 **[部署器包](../../deployment/deployer-package.md)**。运行 `npx @docmd/core deploy --vercel`(或 `--netlify`、`--docker`、`--nginx`),自动生成针对您的 `docmd.config.json` 定制的服务商专属配置文件。 --- ### "我在 Monorepo 中,文档位于子目录" **GitHub App** 和**部署器包**均可自动处理。App 会在整个仓库树中检测配置,并自动注入正确的 `--cwd` 标志。 如果您偏好使用 GitHub Action,请手动传入 `--cwd`: ```yaml - run: npx @docmd/core build --cwd packages/docs ``` --- ### "我想在每个 Pull Request 上预览文档" 结合使用 **GitHub Action** 与 PR 预览服务(例如 Cloudflare Pages 预览部署或自托管预览环境)。详见[预览更改](../workflows-teams/previewing-changes.md)完整指南。 --- ## 各方式如何配合使用 这些方式并不互斥,常见的演进路径如下: ``` 从 GitHub App 开始(最快上线) ↓ 随需求增长,自定义生成的工作流文件 ↓ 添加部署器包,生成 Nginx/Docker 配置用于自托管 ↓ 将 Action 集成到更广泛的 CI/CD 流水线中 ``` ## 延伸阅读 - [GitHub Action 参考](../../integrations/github-action.md) - [GitHub App 参考](../../integrations/github-app.md) - [起始模板参考](../../integrations/starter-template.md) - [部署器包参考](../../deployment/deployer-package.md) - [GitHub Actions CI/CD 指南](./github-actions-cicd.md) - [预览更改](../workflows-teams/previewing-changes.md) --- ## [现有的 Markdown 存储库](https://docs.docmd.io/zh/guides/integrations/existing-markdown-repos/) --- title: "现有的 Markdown 存储库" description: "如何从现有的 Markdown 文件中即时生成专业的文档网站,且无需任何配置。" --- ## 问题 您可能有一个已经建立的存储库,其中包含数百或数千个原始 Markdown 文件 - - 例如旧的 Wiki、Obsidian 库或技术笔记集。手动转换 Frontmatter、修复失效链接以及重组文件以适应新引擎是一项艰巨的任务,这往往阻碍了团队对文档进行现代化改造。 ## 为什么重要 您的内容应该保持可移植性且与工具无关。高质量的文档引擎应该适应您现有的文件,而不是强迫您的文件适应引擎。避免厂商锁定可确保您的知识资产保持标准、可读且面向未来。 ## 方法 `docmd` 遵循严格的 CommonMark 规范,并且默认设计为 **零配置 (zero-config)**。您可以将 `docmd` CLI 指向任何包含 Markdown 文件的目录,它将智能地引导生成一个功能齐全的文档网站,而无需修改源内容的任何一行。 ## 实施 ### 1. 即时引导 导航到您现有的 Markdown 文件夹并运行开发服务器。`docmd` 将扫描您的目录结构并立即在内存中构建一个功能完善的站点。 ```bash cd my-existing-docs/ npx @docmd/core dev ``` ### 2. 自动导航 (Auto-Router) 如果没有找到 `navigation.json` 或 `docmd.config.js`,`docmd` 将触发其 [自动路由 (Auto-Router)](../../configuration/navigation#automatic-sidebar-generation)。它会递归映射您的文件夹结构,美化目录名称(例如,`getting-started` 变为 `Getting Started`),并自动生成逻辑侧边栏分类。 ### 3. 智能标题推断 您不需要为每个文件都添加 `title` Frontmatter。`docmd` 采用级联解析策略来确定页面标题: 1. **Frontmatter**:检查 `title` 或 `h1` 键。 2. **第一个标题**:提取文件内容中发现的第一个 `# 标题`。 3. **文件名**:作为备选方案,美化文件名(例如,`install-guide.md` 变为 `Install Guide`)。 ### 4. 弹性的语法处理 `docmd` 的设计具有很强的弹性。如果您现有的文件中包含来自其他引擎的专有语法或旧的短代码,它们将被安全地渲染为原始文本或被跳过,从而确保您的构建永远不会因为尚未迁移的内容而失败。 ## 权衡 自动生成的侧边栏通常按文件名的字母顺序排序。虽然像 `01-intro.md` 和 `02-setup.md` 这样的命名方式效果很好,但更具描述性的文件名可能会以不直观的顺序出现。对于生产级站点,我们建议过渡到手动 [导航配置](../../configuration/navigation),以获得对用户旅程的完全控制。 --- ## [GitHub Actions CI/CD](https://docs.docmd.io/zh/guides/integrations/github-actions-cicd/) --- title: "GitHub Actions CI/CD" description: "如何使用 GitHub Actions 和 docmd 自动化您的文档构建和部署,以实现高效的文档工作流。" --- ## 问题 从本地机器手动构建和部署文档容易出错,且存在环境不一致(例如 Node.js 版本不同)和安全风险。此外,这还会造成瓶颈,因为部署取决于单个人员的可用性和本地设置。 ## 为什么重要 持续部署 (CD) 可确保您的文档始终与软件同步。当技术更新被合并时,它应该在几分钟内(而不是几天)到达用户手中。自动化保证了每次构建都在干净、可重复的环境中进行,从而保持了高质量和高可靠性的标准。 ## 方法 利用 GitHub Actions 在每次推送或拉取请求 (Pull Request) 时运行 `docmd` 构建流水线。生成的静态资产随后可以自动部署到 GitHub Pages、Cloudflare Pages 等托管提供商,或使用 Docker 部署到容器化环境中。 ## 实施 ### 1. 标准 GitHub Pages 工作流 创建 `.github/workflows/docs.yml` 以自动化构建和部署过程。 ```yaml name: 部署文档 on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install # 将站点构建到 'site/' 目录中 - run: npx @docmd/core build - name: 上传产物 uses: actions/upload-pages-artifact@v3 with: path: site/ - name: 部署到 GitHub Pages uses: actions/deploy-pages@v4 ``` ### 2. 容器化部署 (Docker) 如果您自行托管文档,请使用 [部署命令](../../deployment) 生成生产级 `Dockerfile` 和服务器配置。 ```bash # 在本地生成 Docker 和 Nginx 配置 npx @docmd/core deploy --docker --nginx ``` 随后,您可以更新 GitHub Action,以便在发布新版本时构建此 Docker 镜像并将其推送到注册表(如 Docker Hub 或 GitHub Container Registry)。 ### 3. 拉取请求预览 通过为每个拉取请求生成临时的预览环境来增强您的工作流。这允许审查人员在更改合并到主分支之前查看渲染后的文档。有关更多详细信息,请参阅 [预览更改指南](../workflows-teams/previewing-changes)。 ## 权衡 自动化的 CI/CD 需要初始设置时间并需要管理机密(如 API 令牌)。然而,从长远来看,“无需干预”的部署过程带来的好处 - - 包括减少人为错误和缩短更新周期 - - 远超初始投入。对于大型站点,请确保您的工作流仅在文档目录中的文件发生更改时才触发,以节省 CI 额度。 --- ## [OpenAPI 生成](https://docs.docmd.io/zh/guides/integrations/openapi-generation/) --- title: "OpenAPI 生成" description: "如何将 OpenAPI/Swagger 架构集成到你的 docmd 工作流中,以实现自动化且同步的 API 参考文档。" --- ## 问题 手动维护 REST API 文档是一项重大的运营风险。一旦工程师修改了端点或更新了代码中的架构,文档就会过时。手动保持这些内容的同步既枯燥又容易出错,并且经常导致 API 使用者的集成失败。 ## 为什么这很重要 不准确的 API 参考是导致开发人员沮丧和支持工单增加的主要原因。自动化可确保你的文档保持为“事实来源”,实时(或在每次构建时)反映 API 的实际状态。这使工程师能够专注于构建功能,而不是手动更新文档表格。 ## 方法 实施一个异步构建流水线,将你的 `openapi.json` 或 `swagger.yaml` 架构转换为标准的 Markdown 文件。由于 `docmd` 擅长渲染带有复杂 [容器](../../content/containers/index.md) 的 Markdown,因此生成的 API 参考将与文档的其余部分在视觉上保持一致且融为一体。 ## 实现 ### 1. 构建流水线集成 你可以使用 `widdershins` 等工具或自定义脚本,在 CI/CD 流水线中作为一个预构建步骤从 OpenAPI 架构生成 Markdown。 ```json // package.json { "scripts": { "docs:generate-api": "npx widdershins --search false openapi.yaml -o docs/api/reference.md", "docs:build": "npm run docs:generate-api && npx @docmd/core build" } } ``` ### 2. 优化 API 布局 API 参考通常内容密集,具有用于参数的大型表格和嵌套架构。使用 [Frontmatter](../../content/frontmatter.md) 优化页面布局以提高可读性。 ```markdown --- title: "REST API 参考" layout: "full" # 为密集表格最大化水平空间 --- ``` 设置 `layout: "full"` 会移除右侧的目录侧边栏,从而为宽代码块和响应示例提供更多空间。 ### 3. 使用 docmd 容器进行增强 你可以对生成的 Markdown 进行后处理,以注入 `docmd` 功能,例如用于多语言代码示例的 [选项卡 (Tabs)](../../content/containers/tabs.md) 或用于身份验证警告的 [标注 (Callouts)](../../content/containers/callouts.md)。 ````markdown ::: tabs == tab "cURL" ```bash curl -X GET "https://api.example.com/v1/users" ``` == tab "Node.js" ```javascript const users = await client.getUsers(); ``` ::: ```` ## 权衡 机器生成的文档在技术准确性方面非常出色,但往往缺乏有效学习所需的“人文关怀”。我们建议将 OpenAPI 生成用于 **技术参考 (Technical Reference)**(端点、参数、架构),同时提供手写的 **教程 (Tutorials)** 和 **概念指南 (Conceptual Guides)** 来解释 API 的背景和用例。 --- ## [缓存策略](https://docs.docmd.io/zh/guides/performance-delivery/caching-strategies/) --- title: "缓存策略" description: "如何使用不可变缓存、Etag 重新验证和生产级服务器配置来优化您的文档网站性能。" --- ## 问题 如果文档网站在提供服务时没有适当的缓存控制 (cache-control) 响应头,浏览器将在每次访问时非必要地重新下载图像、CSS 和 JavaScript 包。这会导致视觉卡顿、带宽消耗增加,并给期望文档能瞬间加载的重复访问用户带来糟糕的体验。 ## 为什么重要 有效的缓存是提高网站“感知性能”最有效的方法之一。通过确保静态资产存储在用户的浏览器本地,您可以消除重复网络请求带来的延迟。这使您的文档导航感觉更加流畅和可靠,即使在不稳定的网络连接下也是如此。 ## 方法 实施两级缓存策略:针对静态资产(CSS、JS、图像)的 **不可变缓存 (Immutable Caching)**,以及针对动态内容(HTML、JSON)的 **Etag 重新验证**。`docmd` 通过生成生产级配置来简化此过程,这些配置通过版本哈希自动处理缓存失效。 ## 实施 ### 1. 生产级服务器配置 实施最佳缓存的最简单方法是使用 [部署命令](../../deployment) 生成您的服务器配置。 ```bash # 生成经过优化的 Nginx 配置 npx @docmd/core deploy --nginx ``` ### 2. 不可变资产 对于不经常更改的资产(如主题样式和核心脚本),请使用长期缓存。`docmd` 会为这些资产附加版本哈希,以确保用户仅在您更新文档时才下载新版本。 ```nginx # 不可变资产的 Nginx 规则示例 location ~* \.(?:css|js|webp|png|svg|woff2)$ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; } ``` ### 3. HTML 与导航重新验证 您的 HTML 文件和 `navigation.json` 应始终检查更新,以确保用户能立即看到最新的内容和结构。使用 `no-cache` 指令强制浏览器使用 Etag 与服务器进行重新验证。 ```nginx # HTML 文件的 Nginx 规则示例 location ~* \.html$ { add_header Cache-Control "no-cache, must-revalidate"; } ``` ## 权衡 ### 过时内容 vs 性能 为资产设置较长的缓存时间可以获得极高的性能,但需要稳健的“缓存失效”策略。`docmd` 会为其核心文件自动处理此问题,但如果您手动向 `static/` 目录添加资产,则必须确保在内容更改时更新其引用(例如通过更改文件名或添加查询参数)。 ### CDN 集成 如果您正在使用 CDN(如 Cloudflare 或 AWS CloudFront),请确保其配置为遵循服务器的 `Cache-Control` 响应头。大多数现代 CDN 提供“即时刷新”功能,我们建议将其作为 CI/CD 流水线的一部分,在每次部署新版本文档时触发。 --- ## [CDN 与边缘网络部署](https://docs.docmd.io/zh/guides/performance-delivery/deploying-cdn-edge/) --- title: "CDN 与边缘网络部署" description: "如何通过将您的静态文档部署到内容分发网络 (CDN) 或边缘网络来最小化全球延迟。" --- ## 问题 将您的文档托管在一个地理区域(例如美国东部)的单一服务器上,意味着世界其他地区(例如欧洲或亚洲)的用户将体验到显著的网络延迟。每次页面加载、图像和脚本都必须跨越数千英里,这使您的文档在全球观众看来显得迟钝且无响应。 ## 为什么重要 高延迟直接损害开发者体验。即使您的文档写得很好且很轻量,“首字节时间 (TTFB)”也会受到物理定律的限制。如果您的网站感觉很慢,开发者更有可能失去焦点,或者完全放弃您的工具,转而使用文档更快速、更易于访问的工具。 ## 方法 最佳解决方案是将您的网站部署到边缘 CDN。由于 `docmd` 生成的是纯静态资产(HTML、CSS、JS),它非常适合边缘分发。CDN 会将您的文件复制到数百个全球分布的“边缘节点”,从距离用户最近的数据中心为他们提供服务。 ## 实施 ### 1. 选择平台 `docmd` 原生兼容所有现代静态托管和边缘平台。我们推荐以下平台,因为它们具有出色的全球性能和易用性: * **Cloudflare Pages**:极速的全球边缘网络,内置 DDoS 防护。 * **Vercel**:针对性能进行了优化,具有出色的开发工作流集成。 * **Netlify**:强大的自动化功能和稳健的全球 CDN。 ### 2. 自动化构建 使用 CI/CD 流水线,在您推送更改时自动构建并部署您的网站。有关详细示例,请参阅 [GitHub Actions 指南](../../guides/integrations/github-actions-cicd)。 ```yaml # .github/workflows/deploy.yml jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 # 将站点构建到默认的 'site/' 目录中 - run: npm install && npx @docmd/core build # 示例:部署到 Cloudflare Pages - name: Deploy uses: cloudflare/pages-action@v1 with: apiToken: ${{ secrets.CF_API_TOKEN }} accountId: ${{ secrets.CF_ACCOUNT_ID }} projectName: my-docs directory: site ``` ### 3. 验证 部署完成后,您可以使用 PageSpeed Insights 或全球 Ping 测试等工具验证您的全球性能。您应该会看到来自世界各地几乎任何位置的亚秒级响应时间。 ## 权衡 全球边缘网络抽象了服务器管理,这对于文档团队来说是一个主要优势。然而,调试区域性缓存问题偶尔会比查看单一服务器日志更复杂。使用具有强大“即时缓存失效”功能的平台,可确保您的用户在部署后立即看到文档的最新版本。 --- ## [低端设备优化](https://docs.docmd.io/zh/guides/performance-delivery/low-end-devices/) --- title: "低端设备优化" description: "如何构建高性能、无障碍的文档,使其在低配置硬件和慢速网络连接上也能无缝运行。" --- ## 问题 现代文档网站通常依赖沉重的 JavaScript 运行时来显示静态文本。对于使用旧款手机、廉价笔记本电脑或处于 3G/4G 慢速连接的用户,这些网站可能需要几秒钟才能加载完成。设备的处理器在解析大型 JS 包时会感到吃力,导致“输入延迟”、动画卡顿以及糟糕的整体阅读体验。 ## 为什么重要 技术文档应该是普遍可访问的。迫使处于新兴市场或硬件受限的用户下载并执行沉重的框架来阅读教程,会为学习制造不必要的障碍。轻量级的网站可确保您的产品信息可供所有人使用,无论其硬件配置或互联网速度如何。 ## 方法 采用 **HTML 优先** 策略。`docmd` 采用零框架架构设计,确保在构建过程中将主要内容渲染为标准 HTML。这使浏览器的主要线程保持畅通,从而确保即使在廉价设备上也能实现平滑滚动和快速度的导航。 ## 实施 ### 1. 极简的运行时足迹 默认情况下,`docmd` 的核心 UI 不使用 React、Vue 或任何其他沉重的客户端框架。这种预渲染方法确保了初始“首次内容绘制 (First Contentful Paint)”几乎立即发生。为了保持这种性能: * **限制自定义脚本**:避免在 `customJs` 配置中添加大型第三方库。 * **使用原生浏览器功能**:依靠标准 CSS 和 HTML5 元素,这些元素经过所有现代浏览器的高度优化。 ### 2. 战略性插件管理 虽然 [插件](../../plugins/usage) 增加了强大的功能,但它们可能会引入显著的性能开销。例如,[Mermaid 插件](../../plugins/mermaid) 需要大型引擎来渲染图表。如果您的用户主要使用低端设备,请考虑使用静态图像代替客户端渲染的图表。 ### 3. 响应式与优化的媒体 避免向移动用户发送尺寸过大的图像。使用 WebP 等现代格式,并考虑使用 `<picture>` 标签来更精细地控制响应式资产。 ```html <picture> <source srcset="/assets/mobile-hero.webp" media="(max-width: 600px)"> <img src="/assets/desktop-hero.webp" alt="功能概览" loading="lazy"> </picture> ``` 使用 `loading="lazy"` 属性可确保仅在图像进入用户视口时才下载,从而节省慢速连接下的带宽。 ### 4. 高效的搜索索引 `docmd` 生成限定范围的搜索索引,以保持较低的内存占用。然而,对于极大型站点,[搜索插件](../../plugins/search) 仍可能消耗大量内存。鼓励移动设备用户仅在必要时使用搜索栏,或按照 [本地优先搜索指南](../search/local-first-search) 中的说明优化您的索引。 ## 权衡 优先考虑低端设备的性能通常意味着避免使用“沉重”的交互功能,如复杂的 3D 可视化或大型客户端数据处理。这是一种刻意的设计选择,它重视 **包容性和速度** 超过视觉复杂性,确保您的文档对于尽可能广泛的受众来说始终是一个有用的资源。 --- ## [减少 JS 有效载荷](https://docs.docmd.io/zh/guides/performance-delivery/reducing-javascript-payload/) --- title: "减少 JS 有效载荷" description: "如何通过优化 JavaScript 依赖项并利用 docmd 的零框架架构来维护高性能文档网站。" --- ## 问题 许多现代文档工具依赖于沉重的 JavaScript 框架(如 React 或 Vue)来渲染静态文本。这些框架会为您的初始页面加载增加数百 KB 的体积,迫使浏览器在网站变得完全可交互之前下载、解析并执行大量代码。这导致了加载速度缓慢,并在低端设备上出现“点击无效(ghost clicks)”的情况。 ## 为什么重要 大型 JavaScript 有效载荷直接影响“可交互时间 (TTI)”。在技术文档中,用户需要快速获得答案,任何由沉重的框架初始化引起的延迟都是显著的可用性障碍。保持有效载荷较小,可确保搜索、导航和主题切换从页面出现的那一刻起就是瞬时的。 ## 方法 `docmd` 的核心客户端逻辑采用 **零框架 (Zero-Framework)** 架构。通过利用原生 JavaScript 和浏览器 API 而不是沉重的虚拟 DOM,我们将标准站点的总 JS 有效载荷保持在 **20KB** 以下。这种轻量级的基石确保了在所有设备和网络条件下都能获得最佳性能。 ## 实施 ### 1. 利用原生浏览器 API 避免为简单任务导入 jQuery 或 Lodash 等沉重的库。现代浏览器拥有强大的原生 API,几乎可以处理任何与文档相关的需求,且开销为零。 ```json { "customJs": ["/static/js/my-custom-logic.js"] } ``` ### 2. 战略性插件管理 虽然 [插件](../../plugins/usage) 增加了强大的功能,但某些插件会显著增加您的 JavaScript 有效载荷。例如,[Mermaid 插件](../../plugins/mermaid) 需要大型客户端库来渲染图表。仅在对您的内容至关重要时才启用沉重的插件,并考虑它们对整体页面重量的影响。 ### 3. 延迟加载非关键脚本 如果您需要包含第三方服务(如分析或反馈组件),请确保它们异步加载或延迟加载,以免阻塞文档的渲染。 ```html <!-- 在您的自定义 head 注入中 --> <script src="https://analytics.com/script.js" async defer></script> ``` ### 4. 优化资源 确保您提供的任何自定义 JavaScript 都经过压缩。`docmd` 处理其核心资产的压缩,但您需要负责优化添加到 `static/` 目录中的任何文件。 ## 权衡 使用原生 JavaScript 构建复杂的交互功能可能比使用声明式框架需要更多的手动工作。然而,对于文档而言 - - 其中 95% 的内容是静态文本和图像 - - 零框架方法带来的性能收益远超沉重框架带来的开发便利性。 --- ## [亚秒级(Sub-100ms)导航](https://docs.docmd.io/zh/guides/performance-delivery/sub-100ms-navigation/) --- title: "亚秒级(Sub-100ms)导航" description: "docmd 的原生 SPA 路由和基于意图的预取功能如何提供即时页面切换,从而实现最佳阅读体验。" --- ## 问题 传统的单页导航中,每次点击链接都会触发完整的浏览器重新加载,这会产生令人不适的“白屏闪烁”并打断读者的思路。浏览器必须丢弃当前状态,请求新的 HTML,并重新解析 CSS 和 JavaScript - - 即使只有中心内容区域发生了变化。 ## 为什么重要 文档用户经常在不同章节之间跳转,例如教程、API 参考和概念指南。如果每次切换都需要一秒钟或更长时间,就会产生认知摩擦并阻碍深入探索。即时导航使文档感觉像是一个原生应用程序,显著提高了用户满意度和参与度。 ## 方法 `docmd` 利用构建在预生成静态文件之上的高性能 **单页应用 (SPA) 路由**。这允许浏览器拦截链接点击,仅在后台获取必要的内容,并动态更新页面而无需完整重新加载。这种方法保留了侧边栏、目录和主题设置的状态,从而实现近乎瞬时的切换。 ## 实施 `docmd` 的 SPA 路由默认启用,并使用几种先进技术来实现亚秒级导航速度: ### 1. 基于意图的预取 当用户将鼠标悬停在导航链接上时,`docmd` 会检测到导航意图并开始后台获取目标页面的内容。当用户真正点击链接时,数据通常已经存在于浏览器的缓存中,使得切换感觉是瞬间完成的。 ### 2. 局部 DOM 更新 `docmd` 不是重新渲染整个页面,而是智能地仅更新必要的逻辑区域: * **主体内容 (Main Content)**:经过 Markdown 渲染的主要正文。 * **目录 (Table of Contents)**:刷新以匹配新页面的标题。 * **导航状态 (Navigation State)**:更新侧边栏中的活动和展开状态。 ### 3. 用于自定义逻辑的生命周期事件 由于浏览器不执行完整加载,标准事件(如 `DOMContentLoaded`)仅触发一次。要在每次导航后执行自定义 JavaScript(例如重新初始化第三方小部件或跟踪页面视图),您应该监听 `docmd:page-mounted` 事件。 ```javascript // 示例:导航后重新初始化自定义组件 document.addEventListener('docmd:page-mounted', (event) => { const currentPath = event.detail.path; console.log(`成功导航至:${currentPath}`); // 在此处编写自定义逻辑 if (currentPath.includes('/api/')) { initApiConsole(); } }); ``` 有关更多详细信息,请参阅 [客户端事件](../../api/client-side-events) 文档。 ## 权衡 ### 脚本执行 SPA 路由会自动重新执行新页面 Markdown 正文中的 `<script>` 标签。但是,在您的主题或布局中定义的全局脚本仅在初始加载期间运行一次。对于必须在每个页面上执行的逻辑,请始终使用 `docmd:page-mounted` 事件。 ### SEO 和无障碍 尽管具有类似 SPA 的行为,`docmd` 仍然为每个页面生成完整的、独立的 `.html` 文件。这确保了搜索引擎爬虫可以抓取全部内容,并且对于禁用 JavaScript 的用户,网站仍然功能完备,从而保持了卓越的 SEO 和无障碍标准。 --- ## [重大变更与弃用](https://docs.docmd.io/zh/guides/scaling-architecture/breaking-changes-deprecations/) --- title: "重大变更与弃用" description: "如何使用版本化文档和上下文标注有效地传达 API 变更和迁移路径。" --- ## 问题 当产品引入重大版本变更时,某些 API、功能或配置不可避免地会被弃用或删除。浏览最新文档的用户必须清楚地知道他们是否正在使用过时的模式,但为了避免混淆,文档本身应集中于现代实现。 ## 为什么重要 未能明确提示重大变更会导致开发者浪费数小时调试引擎不再支持的代码。上下文警告和清晰的迁移路径对于维护用户信任、减少支持请求以及确保顺利过渡到软件的最新版本至关重要。 ## 方法 将 `docmd` 的 [版本控制引擎](../../configuration/versioning.md) 与 [标注容器 (Callout Containers)](../../content/containers/callouts.md) 相结合,在旧版内容和现代内容之间建立清晰的区别。策略是将完整的旧版文档移至归档版本,同时在当前版本中提供链接回归档内容的“迁移锚点”。 ## 实施 ### 1. 归档旧版内容 发布新的大版本(例如 v2.0)时,将现有文档移至归档目录(例如 `docs-v1/`)。这可确保为尚未迁移的用户保留前一版本的完整上下文。 ### 2. 上下文迁移标注 在最新文档中,在发生重大变更的页面顶部使用 `warning`(警告)或 `important`(重要)标注。这为试图使用旧模式的用户提供了即时价值。 ```markdown # 配置 API ::: callout warning "迁移:v2.0 中的重大变更" `siteTitle` 属性已被移除。它已被全局 `title` 属性取代。 * **从 v1.x 迁移?** 请更新您的 `docmd.config.json`。 * **需要 v1.x 文档?** 请参阅 [旧版配置指南](../../configuration/overview.md)。 ::: ``` ### 3. 保持 AI 准确性 通过严格将已弃用的内容与当前版本分开,您可以显著提高 AI 工具的准确性。`docmd` 的 [LLMs 插件](../../plugins/llms.md) 会根据活动版本生成上下文文件。归档旧内容可以防止 AI 模型“产生幻觉”,并向寻找现代解决方案的用户推荐过时的 API。 ## 权衡 主动管理迁移标注会增加维护开销。如果无限期保留,页面可能会充斥着旧的警告。我们建议建立一种策略,即在旧版本达到其生命周期终点 (EOL) 或在一个完整的大版本发布周期后移除迁移标注,以保持文档精简和专注。 --- ## [多团队协作](https://docs.docmd.io/zh/guides/scaling-architecture/multi-team-collaboration/) --- title: "多团队协作" description: "如何使用去中心化导航和全局菜单栏,让多个团队在不发生冲突的情况下共同为一个统一的文档项目做出贡献。" --- ## 问题 当多个独立的团队(如前端、后端、DevOps 和产品团队)共同为一个文档库做出贡献时,往往会出现组织摩擦。团队可能会意外地覆盖全局导航设置,创建冲突的样式范式,或者在并发更新期间破坏跨领域边界的链接。 ## 为什么重要 写作体验中的摩擦会导致“文档孤岛”,即团队为了避免共享库的复杂性而创建独立的、孤立的维基。这破坏了统一文档门户的连贯用户体验,并使用户更难找到关于整个系统的全面信息。 ## 方法 利用 `docmd` 的去中心化 [解析优先级](../../configuration/navigation#navigation-resolution-priority) 系统。这允许各个团队使用本地 `navigation.json` 文件对其特定领域拥有完全的自主权,同时由一个核心团队管理全局 [菜单栏](../../configuration/menubar) 和视觉设计系统。 ## 实施 ### 1. 基于领域的归属权 将您的文档划分为分配给特定团队的顶级目录。每个团队完全拥有其分配文件夹的内容和内部结构。 ```text my-project/ ├── docs/ │ ├── frontend/ # 归 UI 团队所有 │ │ ├── navigation.json # 团队特定的侧边栏 │ │ └── components.md │ ├── backend/ # 归 API 团队所有 │ │ ├── navigation.json │ │ └── database.md │ └── docmd.config.json # 归平台/核心团队所有 ``` ### 2. 全局上下文切换 (菜单栏) 中央平台团队控制 [菜单栏](../../configuration/menubar),它作为主要的导航层,用于在不同的团队领域之间切换。 ```json { "menubar": { "enabled": true, "items": [ { "text": "前端", "url": "/frontend/components" }, { "text": "后端", "url": "/backend/database" }, { "text": "基础设施", "url": "/devops/setup" } ] } } ``` ### 3. 利用 navigation.json 实现本地自主 当用户浏览 `/frontend/` 目录下的内容时,`docmd` 会自动优先处理 `frontend/navigation.json` 文件。侧边栏会动态更新,仅反映前端特定的层级结构,从而防止导航被来自其他团队的无关信息所淹没。 ```json // docs/frontend/navigation.json [ { "title": "设计系统", "path": "/frontend/design-system" }, { "title": "组件库", "path": "/frontend/components" } ] ``` ## 权衡 去中心化导航要求团队注意跨领域的链接。虽然 `docmd` 可以有效地处理相对链接,但移动整个团队目录将破坏其他团队文件中的链接。我们建议在不同团队领域之间的链接使用根相对路径(以 `/` 开头),以确保稳定性。 --- ## [管理多版本文档](https://docs.docmd.io/zh/guides/scaling-architecture/multi-version-documentation/) --- title: "管理多版本文档" description: "如何使用统一的切换器和路径保留功能维护文档的多个版本(v1、v2、旧版本)。" --- ## 问题 随着软件产品的演进,企业用户往往仍在使用较旧的 LTS(长期支持)版本。在发布 v2 时直接放弃 v1 的文档会让这些用户陷入困境,而为每个版本维护完全独立的网站则会导致用户体验支离破碎并分散 SEO 权重。 ## 为什么重要 如果没有一种无缝切换版本的方式,开发者往往会错误地将最新文档中的指令应用到旧版本环境中,从而导致错误并增加支持成本。统一的版本控制系统可确保用户始终了解自己所处的上下文,并能轻松地在同一页面的不同版本之间跳转。 ## 方法 `docmd` 具有原生的 [版本控制引擎](../../configuration/versioning),将版本视为一等公民。它将构建结果隔离到以版本为前缀的目录中,提供“粘性切换 (Sticky Switching)”机制来保留当前页面路径,并将搜索结果准确限制在当前版本上下文中。 ## 实施 ### 1. 组织源目录 将最新的文档保留在标准目录中(例如 `docs/`),并将旧版本放在同级目录中(例如 `docs-v1/`)。 ```text my-project/ ├── docs/ # v2.x (当前版本) ├── docs-v1/ # v1.x (旧版 LTS) └── docmd.config.js ``` ### 2. 配置版本映射 在 `docmd.config.json` 中定义您的版本结构。`current`(当前)版本在根 URL 处提供服务,其他版本在 `/{id}/` 处提供服务。 ```json { "versions": { "current": "v2", "position": "sidebar-top", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x (最新)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x (LTS)" } ] } } ``` ### 3. 特定版本的导航 如果不同版本的导航结构有所不同,您可以在每个版本的源目录中放置一个 `navigation.json` 文件。`docmd` 会自动检测并将其用于该特定版本。 ```json // docs-v1/navigation.json [ { "title": "旧版安装", "path": "/legacy-setup" }, { "title": "迁移到 v2", "path": "/migration" } ] ``` ### 4. 路径保留 (粘性切换) `docmd` 会在用户切换版本时自动尝试保留其当前路径。如果用户在 `v2` 网站的 `/api/auth` 页面并切换到 `v1`,引擎将尝试将其路由到 `/v1/api/auth`。如果目标版本中不存在该页面,则会退回到该版本的首页。 ## 权衡 在单个代码库中存储多个版本会随着时间的推移增加库的大小。对于非常庞大的文档集,请考虑使用 CI/CD 在构建过程中动态拉取旧版本文档目录,而不是将其提交到主分支。 --- ## [组织大型代码库](https://docs.docmd.io/zh/guides/scaling-architecture/organising-large-repositories/) --- title: "组织大型代码库" description: "如何使用落地页和层级导航在复杂的文档结构中保持导航清晰度和易用性。" --- ## 问题 随着文档库增长到数百个页面,在单个庞大的侧边栏中显示所有主题会使网站变得难以使用。用户会陷入“选择瘫痪”,寻找一个特定的模块需要滚动浏览数十个无关的、已展开的分类。 ## 为什么重要 导航是用户体验的关键组成部分。杂乱无章的界面会降低产品的感知质量,使开发者更难找到所需的答案。如果导航感觉混乱,用户通常会认为软件本身也同样难以使用。 ## 方法 使用 `docmd` 的 [导航配置](../../configuration/navigation) 实施层级分组策略。核心原则是在需要之前隐藏复杂性。使用可折叠组和“落地页 (Hub Pages)”来保持侧边栏整洁,确保用户可以专注于当前任务而不会感到不知所措。 ## 实施 ### 1. 层级分组 在 `navigation.json` 或配置文件中使用 `collapsible` 属性对相关页面进行分组。这可以保持侧边栏整洁,并允许用户仅展开他们感兴趣的部分。 ```json // docs/navigation.json [ { "title": "高级 API", "icon": "braces", "collapsible": true, "children": [ { "title": "身份验证", "path": "/api/auth" }, { "title": "Webhook", "path": "/api/webhooks" }, { "title": "速率限制", "path": "/api/rate-limiting" } ] } ] ``` ### 2. 实施落地页 (Hub Pages) 不要在侧边栏中公开每一个单独的页面,而是创建中央“落地页”,作为特定子系统的目录。使用 [网格和卡片](../../content/containers/grids.md) 提供可用内容的视觉化、高层级概览。 ```markdown # 集成中心 (Integrations Hub) ::: grids ::: grid ::: card "数据库集成" icon:database 将您的应用程序连接到 Postgres 和 MongoDB 等流行数据库。 [查看数据库指南](../integrations/openapi-generation.md) ::: ::: ::: grid ::: card "支付网关" icon:credit-card 了解如何集成 Stripe、PayPal 等。 [查看支付指南](../integrations/alongside-other-tools.md) ::: ::: ::: ``` ### 3. 利用面包屑导航 `docmd` 会根据您的文件夹结构和导航层级为每个页面自动生成 [面包屑导航](../../content/syntax/advanced.md#breadcrumbs)。通过使用落地页,您可以保持侧边栏的专注,同时面包屑导航提供必要的上下文,并方便用户向上级层级导航。 ## 权衡 使用落地页可能会增加用户到达深度内容的“点击”次数。然而,这通常优于一个使内容发现变得困难的杂乱侧边栏。权衡的结果是一个更整洁、更专业的界面,显著提高了文档的整体可搜索性和专注度。 --- ## [可扩展的文件夹结构](https://docs.docmd.io/zh/guides/scaling-architecture/scalable-folder-structure/) --- title: "可扩展的文件夹结构" description: "如何使用 Diátaxis 框架和 docmd 的解析系统来组织大规模文档项目。" --- ## 问题 小型文档站点通常以一个扁平的 `docs/` 文件夹开始。然而,随着项目发展到包含多个模块、教程、API 和概念深度探讨时,杂乱无章的文件夹结构就变成了沉重的维护负担。文件变得难以定位,导航侧边栏也变成了令人望而生畏的“链接墙”。 ## 为什么这很重要 杂乱无章的文件夹结构会直接导致混乱的用户体验,因为 `docmd` 的路由和默认导航都是派生自你的文件系统。对于作者来说,缺乏清晰的结构会导致内容重复和命名不一致,随着更多贡献者加入项目,文档将变得更难管理。 ## 方法 我们建议采用信息架构框架,如 [Diátaxis](external:https://diataxis.fr/),它将内容分为四个不同的类别:教程 (Tutorials)、操作指南 (How-To Guides)、参考 (Reference) 和解释 (Explanation)。将这些类别严格映射到你的物理文件系统,为读者和作者提供一个清晰的路线图。 ## 实现 ### 1. Diátaxis 层次结构 将你的源目录组织成语义化的子文件夹。这种物理隔离使得管理大量文件变得更加容易,并确保了整洁的 URL 结构。 ```text my-project/ ├── docs/ │ ├── tutorials/ (学习导向:循序渐进的课程) │ │ └── getting-started.md │ ├── guides/ (任务导向:解决特定问题) │ │ └── deployment.md │ ├── reference/ (信息导向:技术描述) │ │ └── api-spec.md │ ├── explanation/ (理解导向:理论背景) │ │ └── architecture.md │ └── navigation.json (主导航定义) └── docmd.config.js ``` ### 2. 战略性地使用 navigation.json 与其在全局配置中定义庞大的导航树,不如在源目录中使用 `navigation.json` 文件。`docmd` 遵循 [解析优先级](../../configuration/navigation#navigation-resolution-priority) 系统,允许你为网站的不同部分定义不同的侧边栏层次结构。 ```json // docs/navigation.json [ { "title": "教程", "icon": "book-open", "children": [ { "title": "开始使用", "path": "/tutorials/getting-started" } ] }, { "title": "参考", "icon": "braces", "children": [ { "title": "API 规范", "path": "/reference/api-spec" } ] } ] ``` ### 3. 基于文件的路由 请记住,每个 Markdown 文件在文件夹结构中的位置决定了它最终的 URL。例如,`docs/guides/auth.md` 变成 `your-site.com/guides/auth`。利用这一点为你的用户创建直观、易记的 URL。 ## 权衡 像 Diátaxis 这样严格的组织框架要求清晰地理解内容类型。技术作家偶尔可能会发现很难对特定文档进行分类(例如,“这是一个指南还是一个教程?”)。随着团队和文档的增长,建立清晰的内部贡献指南对于保持一致性至关重要。 --- ## [扩展到 1000+ 页面](https://docs.docmd.io/zh/guides/scaling-architecture/scaling/) --- title: "扩展到 1000+ 页面" description: "如何使用 docmd 在大型文档项目中保持高性能和易用性。" --- ## 问题 随着软件产品的成熟,其文档自然会不断扩展。当一个项目增长到数百或数千个 Markdown 文件时,许多文档生成器都会面临构建时间缓慢、开发服务器热重载滞后以及导航结构让维护者和用户都感到不知所措的问题。 ## 为什么重要 如果文档生成需要几分钟而不是几秒钟,作者就会失去进行细微修改的动力,从而导致内容陈旧且不准确。对于用户来说,庞大且杂乱无章的侧边栏菜单会使查找信息变得非常沮丧,导致支持工单增加,开发者体验下降。 ## 方法 `docmd` 专为速度和可扩展性而设计。通过利用高性能的解析引擎和颗粒化的基于文件的构建策略,它可以在几秒钟内处理数千个页面。其优化的 SPA(单页应用)交付确保了用户在大型网站中的导航依然是瞬时完成的。 ## 实施 ### 1. 颗粒化的项目结构 避免将所有文件放在一个扁平的目录中。使用与您的产品架构相匹配的深层嵌套文件夹结构。这使得项目更易于维护,并允许 `docmd` 在开发期间高效地跟踪更改。 ### 2. 优化的搜索索引 对于大型网站,[搜索插件](../../plugins/search) 至关重要。`docmd` 生成高度压缩的搜索索引,并按需加载。这确保了即使有数千个页面,初始页面加载速度依然很快,同时在整个网站范围内提供全文搜索能力。 ### 3. 版本控制和归档 利用 [版本控制引擎](../../configuration/versioning) 将旧版内容与当前文档分开。通过将旧版本隔离到各自的构建上下文中,可以减少日常更新中需要重新处理的页面数量,从而显著提高开发速度。 ```json { "versions": { "current": "v3", "all": [ { "id": "v3", "dir": "docs/current", "label": "v3.x (最新)" }, { "id": "v2", "dir": "docs/v2", "label": "v2.x (旧版)" } ] } } ``` ### 4. 基于组件的导航 使用 `navigation.json` 文件将您的导航分解为逻辑片段。这允许您为网站的不同部分定义独特的侧边栏层级,防止主导航变得杂乱无章。 ## 权衡 大型网站在构建过程中自然会消耗更多的磁盘空间和内存。为了在极端规模(10,000+ 页面)下保持亚秒级的构建时间,请考虑使用配备 SSD 存储和充足 RAM 的高性能 CI/CD 环境,以处理文件的并行处理。 --- ## [工作区与 Monorepo 架构](https://docs.docmd.io/zh/guides/scaling-architecture/workspace-monorepo/) --- title: "工作区与 Monorepo 架构" description: "如何使用 docmd 的工作区模式,从单个仓库管理多个独立的文档项目,零重复配置。" --- ## 问题 大型组织为多个独立产品维护文档——SDK、CLI 工具和主平台——每个产品都有自己的版本控制、导航和发布周期。为每个产品运行单独的文档站点会造成重复:独立的 CI 流水线、独立的主题配置、独立的部署任务。 ## 为什么重要 碎片化的文档难以维护,对用户来说也令人困惑。如果 SDK 文档与平台文档看起来不同,用户就会失去信心。如果每个项目都需要自己的 CI 任务,你的工程开销会随产品数量的增加而增加。统一的工作区用一个配置文件解决了这两个问题。 ## 方法 使用 docmd 的**工作区模式**。在单个根 `docmd.config.json` 中定义所有项目。全局默认值(主题、菜单栏、Logo)只需设置一次。每个项目继承它们,并可以覆盖需要的部分。一个构建命令生成一个可部署的目录。 ## 实施 ### 1. 仓库结构 ```text my-org-docs/ ├── assets/ ← 共享 Logo、favicon、全局 CSS ├── main-docs/ ← 前缀:/ │ ├── docmd.config.json │ └── docs/ ├── sdk-docs/ ← 前缀:/sdk │ ├── docmd.config.json │ └── docs/ ├── cli-docs/ ← 前缀:/cli │ ├── docmd.config.json │ └── docs/ ├── docmd.config.json ← 工作区根配置 └── package.json ``` ### 2. 根工作区配置 全局设置只需定义一次。所有项目自动继承这些设置。 ```json { "workspace": { "projects": [ { "prefix": "/", "src": "main-docs", "title": "平台文档" }, { "prefix": "/sdk", "src": "sdk-docs", "title": "SDK 参考" }, { "prefix": "/cli", "src": "cli-docs", "title": "CLI 参考" } ], "switcher": { "enabled": true, "position": "sidebar-top" } }, "theme": { "name": "default", "appearance": "system" }, "logo": { "light": "assets/logo-dark.svg", "dark": "assets/logo-light.svg", "alt": "我的组织" }, "menubar": [ { "text": "平台", "url": "/" }, { "text": "SDK", "url": "/sdk" }, { "text": "CLI", "url": "/cli" } ] } ``` ### 3. 每个项目的配置 每个项目只指定与根配置不同的内容。此 SDK 项目示例添加了 OpenAPI 支持并设置了自己的 `title`: ```json { "title": "SDK 参考", "src": "docs", "plugins": { "search": {}, "openapi": {}, "git": { "repo": "https://github.com/my-org/sdk" } }, "versions": { "current": "v2", "all": [ { "id": "v2", "dir": "docs", "label": "v2.x(稳定版)" }, { "id": "v1", "dir": "docs-v1", "label": "v1.x(旧版)" } ] } } ``` 根配置中的全局 `theme`、`logo` 和 `menubar` 仍然适用。SDK 项目只是在其基础上添加了自己的插件和版本。 ### 4. 构建和 CI 使用单个命令构建整个工作区: ```bash npx @docmd/core build ``` 对于 CI/CD,一个最简的 GitHub Actions 工作流: ```yaml name: Deploy Docs on: push: branches: [main] permissions: contents: read pages: write id-token: write jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: 'npm' - run: npm install - run: npx @docmd/core build - uses: actions/upload-pages-artifact@v3 with: path: site/ deploy: needs: build runs-on: ubuntu-latest environment: name: github-pages steps: - uses: actions/deploy-pages@v4 ``` 或自动生成工作流: ```bash npx @docmd/core deploy --github-pages ``` ### 5. 针对项目的开发重建 在开发期间,文件更改只会触发受影响项目的定向重建: ```bash npx @docmd/core dev ``` ## 权衡 工作区模式要求所有项目共享相同的 `@docmd/core` 版本。如果不同的产品团队需要在不同版本的 docmd 上运行,则需要单独的仓库。对于大多数组织来说,锁定到单一版本并统一升级是更简单、更可维护的策略。 --- ## [Untitled](https://docs.docmd.io/zh/guides/search/fast-accurate-search/) --- ## [搜索相关性与结构](https://docs.docmd.io/zh/guides/search/improving-search-relevance/) --- title: "搜索相关性与结构" description: "如何组织您的 Markdown 内容以提高搜索相关性,并帮助用户更快地找到信息。" --- ## 问题 搜索引擎根据结构对内容进行优先级排序。如果一篇高质量指南使用“简介”或“步骤 1”等通用标题,搜索引擎可能无法为隐藏在段落中的核心关键词分配足够的权重。这导致相关页面被埋没在搜索结果深处,令期望立即获得答案的用户感到沮丧。 ## 为什么重要 用户通常搜索特定的技术术语(例如“身份验证令牌”或“部署限制”),而不是完整的句子。如果您的文档结构没有强调这些术语,搜索引擎就无法自信地对您的内容进行排名。高搜索相关性是实现文档门户“自助化”与处理大量支持工单之间的区别。 ## 方法 组织您的 Markdown,以便搜索索引器能够自动识别并优先处理核心概念。`docmd` 的搜索引擎为页面 `title`(标题)、`description`(描述)和 `headers`(标题行)分配的权重高于正文文本。通过优化这些结构化元素,您可以显著提高内容的发现率。 ## 实施 ### 1. 优化 Frontmatter 元数据 使用 [Frontmatter](../../content/frontmatter) 块提供明确的关键词和描述性摘要。[搜索插件](../../plugins/search) 会索引这些字段,以便在搜索 UI 中提供更好的结果和更有用的片段。 ```yaml --- title: "AWS S3 存储配置" description: "如何为 AWS S3 集成配置 IAM 角色和存储桶权限。" keywords: ["aws", "s3", "storage", "iam", "cloud"] --- ``` ### 2. 使用语义化标题 避免使用通用的标题名称。相反,在标题中包含相关的关键词,为用户和搜索引擎提供上下文。 * **低相关性:** `## 步骤 1:配置` * **高相关性:** `## 步骤 1:配置 AWS IAM 角色` ### 3. 利用标注强调关键信息 使用 [标注容器 (Callout Containers)](../../content/containers/callouts) 来显示关键警告或“专业技巧”也可以提高搜索相关性。标注中的内容通常在语义上是独立的,索引器可以对其进行不同的权重处理,以突出显示重要的故障排除步骤。 ## 权衡 优化搜索相关性需要严谨的写作。随着产品的演进,Frontmatter 中的关键词如果不及进行定期检查,可能会变得过时。此外,在标题中包含过多关键词(关键词堆砌)会使文档显得重复且读起来不够自然。请在 SEO 和可读性之间寻求平衡。 --- ## [本地优先搜索优化](https://docs.docmd.io/zh/guides/search/local-first-search/) --- title: "本地优先搜索优化" description: "如何针对 docmd 的高性能客户端搜索引擎优化您的文档内容。" --- ## 问题 本地优先搜索引擎完全在浏览器中运行,无需服务器往返即可提供即时结果。然而,这意味着它们受到浏览器内存和处理能力的限制。如果搜索索引没有得到妥善优化,它可能会消耗过多的 RAM,导致浏览器标签页卡顿甚至崩溃,尤其是在移动设备上。 ## 为什么重要 无缝的搜索体验对于提高开发者效率至关重要。如果搜索工具引起性能问题或消耗过多内存,用户就会避免使用它。针对本地优先搜索优化您的内容,可确保您的文档在所有设备和网络条件下都能保持快速、响应灵敏且可靠。 ## 方法 `docmd` 的 [搜索插件](../../plugins/search) 在构建时使用提取流水线来创建高度优化的索引。通过剪枝不必要的数据并专注于高价值的语义字段,它确保了生成的索引既全面又轻量。 ## 实施 ### 1. 构建时提取 在构建过程中,`docmd` 会处理您的 Markdown 文件,仅提取最相关的文本进行索引。它会自动剥离: * HTML 标签和结构化样板。 * 不增加语义价值的 Markdown 语法字符。 * 仅用于格式化、会导致索引膨胀的元素。 这确保了索引器仅接收干净、有意义的文本,从而显著减小了最终索引的大小。 ### 2. 利用 Frontmatter 进行战略索引 您可以使用 [Frontmatter](../../content/frontmatter) 明确控制页面的索引方式。例如,如果页面包含大量重复数据(如原始 JSON 日志),而这些数据对搜索没有帮助,您可以选择仅索引标题和元数据。 ```yaml --- title: "API 日志参考" search: indexBody: false # 仅索引标题和行标题 --- ``` ### 3. 客户端内存管理 `docmd` 在浏览器中精细管理搜索索引的生命周期。它采用按需加载策略,这意味着仅在用户首次与之交互时才初始化搜索引擎。这保持了初始页面加载的足迹较小,并确保系统资源仅在需要时才被使用。 ## 权衡 从搜索索引中激进地剪枝内容(例如排除大型代码块)有时会导致错过一些冷门的搜索结果。您必须在轻量、快速的索引与全面的搜索覆盖范围之间取得平衡。我们建议优先考虑标题和概念性描述,因为这些是开发者最常用的搜索目标。 --- ## [集成语义搜索](https://docs.docmd.io/zh/guides/search/semantic-search/) --- title: "集成语义搜索" description: "如何使用本地向量嵌入在 docmd 中配置 and 部署客户端混合语义搜索。" --- ## 问题 传统的全文搜索完全依赖于精确的关键词匹配。如果用户搜索“身份验证”,但页面仅使用“OAuth2”或“登录”等术语,标准关键词搜索引擎将无法找到它。这迫使撰写人员进行不自然的关键词堆砌,并在读者无法找到所需内容时使其感到沮丧。 ## 为什么它很重要 现代开发人员期望能够理解意图、同义词和上下文的自然语言界面。实现服务器端语义搜索通常需要设置复杂的架构,如向量数据库(例如 Pinecone 或 pgvector)、托管模型并构建 API,这增加了维护开销和每月托管成本,并引入了安全和隐私问题。 ## 方法 使用 docmd 原生的**语义搜索插件**。它采用高度优化的浏览器运行时,完全在客户端运行。它在构建时使用本地 Hugging Face 模型管道生成结构化的向量分块索引,然后使用混合 BM25 关键词频率和向量余弦相似度对匹配项进行重排序。没有任何数据会被发送到第三方 API。 ## 实现 ### 1. 在配置中启用语义搜索 在 `docmd.config.json` 中添加 `search` 插件选项。将 `semantic` 配置为 `true` 并启用 `showConfidence`,以在搜索结果中直观地展示语义匹配的置信度徽章: ```json { "plugins": { "search": { "semantic": true, "showConfidence": true } } } ``` ### 2. 选择正确的嵌入模型 docmd 既支持轻量级的仅限英语的模型,也支持全面的多语言模型。您可以使用 `docmd-search --settings` 更新模型配置,或进行显式定义: | 模型 ID | 维度 | 大小 | 语言 | 最适合 | | :--- | :---: | :---: | :--- | :--- | | `Xenova/all-MiniLM-L6-v2` | 384 | ~90 MB | 仅限英语 | 快速、高精度的英文文档 | | `Xenova/LaBSE` | 768 | ~470 MB | 100+ 种语言 | 绝对最佳的多语言质量 | | `Xenova/paraphrase-multilingual-MiniLM-L12-v2` | 384 | ~220 MB | 50+ 种语言 | 极佳的多语言平衡性 | ### 3. 在 CI/CD 中预构建索引 为了避免用户首次加载时在浏览器中产生计算开销,请在构建或 CI/CD 流程中使用 CLI 预先生成搜索分块: ```bash # 预构建语义搜索索引 npx docmd-search --build # 随后运行 docmd 构建 npx @docmd/core build ``` 这将在 `.docmd-search/` 目录中生成高度优化的静态 Vecto-JSON 分块文件。当用户进行搜索时,客户端会在后台渐进式加载这些分块,从而使 UI 保持即时响应。 ## 权衡 ### 首次加载资源体积 客户端向量嵌入要求浏览器在首次搜索时下载 WebAssembly 运行时以及预训练 of ONNX 模型文件。尽管这些资源会被持久化缓存到浏览器的 Cache Storage 中,但在较慢的网络连接下,首次加载的搜索延迟可能会稍高(约 1-2 秒的延迟)。 ### 搜索质量与传输体积 选择如 `LaBSE` 等较大的模型可提供出色的多语言质量,但会导致下载体积增加。对于标准的国际化文档网站,`paraphrase-multilingual-MiniLM-L12-v2` 模型是搜索精度与网络传输体积之间的推荐最佳平衡点。 --- ## [基于 Git 的工作流](https://docs.docmd.io/zh/guides/workflows-teams/git-based-workflows/) --- title: "基于 Git 的工作流" description: "如何使用 Git、拉取请求 (Pull Request) 和自动化的 CI/CD 检查来有效地管理文档贡献。" --- ## 问题 允许直接向主文档分支推送更改通常会导致链接失效、格式不一致以及未经核实的各种技术信息。然而,如果增加过多的摩擦 - - 例如要求单独的 CMS 帐户 - - 会阻碍社区成员和内部开发人员贡献有价值的更新。 ## 为什么重要 协作是优秀文档的生命线。如果开发人员发现了一个拼写错误或过时的示例,他们应该能够在几分钟内提交修复。基于 Git 的工作流提供了一个熟悉、透明且安全的环境来进行贡献,确保每一项更改在发布前都经过审查和验证。 ## 方法 实施一种由自动化验证和预览环境支持的“拉取请求 (Pull Request, PR)”模式。`docmd` 专为这种工作流设计,因为它运行在标准的 Markdown 文件上,这些文件易于使用熟悉的 Git 工具进行差异对比、审查和合并。 ## 实施 ### 1. 启用“编辑此页”链接 您可以配置 `docmd` 在页脚或侧边栏中自动生成“编辑此页”链接。这允许用户直接从文档页面跳转到存储库中对应的源文件。 ```json { "editLink": { "enabled": true, "baseUrl": "https://github.com/my-org/my-docs/edit/main/docs", "text": "建议修改" } } ``` 有关更多详细信息,请参阅 [编辑链接配置](../../configuration/overview.md#editlink)。 ### 2. 利用 Threads 插件进行上下文审查 对于需要详细反馈的复杂更新,请使用 [Threads 插件](../../plugins/threads.md)。这允许作者和审查人员在审查阶段直接在 Markdown 内容中留下行内评论,保持讨论的上下文一致性。 ```markdown ::: thread "审查人姓名" 我们是否应该在这里添加一个关于新身份验证流程的代码示例? ::: ``` ### 3. CI 中的自动化验证 将 `docmd` 集成到您的 CI/CD 流水线(例如 [GitHub Actions](../integrations/github-actions-cicd.md))中以验证每个 PR。至少,您的流水线应运行构建命令,以确保没有引入语法错误或损坏的配置。 ```bash # 在您的 CI 流水线中 npm install npx @docmd/core build ``` ## 权衡 严格的 Git 工作流偶尔会减慢微小更新的速度,例如修复关键的拼写错误或更新服务状态通知。对于高产出的团队,我们建议指定“文档负责人”,他们有权快速处理小的更改,同时对重大技术更新保持严格的审查标准。 --- ## [维护一致性](https://docs.docmd.io/zh/guides/workflows-teams/maintaining-consistency/) --- title: "维护一致性" description: "如何通过使用 Lint 检查和标准化模式,确保大型文档团队中的统一声音和专业质量。" --- ## 问题 在大型团队中,每个技术作家都有不同的风格和偏好。有些人可能使用加粗文本进行强调,而另一些人则使用斜体。有些人可能更喜欢“点击按钮”,而另一些人则使用“选择选项”。随着时间的推移,您的文档可能会变成各种冲突风格的“百纳被”,使用户难以快速解析信息,并降低了产品的专业信任度。 ## 为什么重要 一致性孕育熟悉感。当用户学习复杂的 API 或工作流时,他们依赖一致的词汇和结构模式来有效地浏览内容。统一的声音使您的文档感觉像是一个连贯的、高质量的产品,从而建立了对软件本身的信心。 ## 方法 使用 [标准化容器](../../content/containers) 和自动化 Lint 工具进行机械式的一致性强制执行。通过自动化低层级的风格和语法检查,您可以让编辑人员腾出精力,专注于内容的高层级质量、准确性和清晰度。 ## 实施 ### 1. 使用标准化的 docmd 模式 鼓励所有贡献者使用 `docmd` 内置的主题化容器,而不是即兴使用手动 Markdown 格式。这确保了整个站点中的每一个警告、提示或说明在外观和行为上都是一致的。 ```markdown <!-- ❌ 避免:不一致且无样式 --> **注意:** 请重启服务。 <!-- ✅ 推荐:一致、无障碍且具有主题感 --> ::: callout info 请重启服务。 ::: ``` 使用 [标注 (Callouts)](../../content/containers/callouts) 可确保您的文档保持专业外观并符合无障碍标准,而无需作者付出额外努力。 ### 2. 实施散文 Lint 检查 集成 **Vale** 或 **Markdownlint** 等工具来强制执行品牌术语、语气和语法。这些工具可以配置为自动检查被动语态、偏见语言或不正确的品牌拼写。 ```ini # .vale.ini 示例 MinAlertLevel = suggestion Packages = Google, Microsoft [*] BasedOnStyles = Vale, Google ``` ### 3. CI/CD 中的自动化强制执行 在您的 [GitHub Actions](../../guides/integrations/github-actions-cicd) 或其他 CI/CD 流水线中包含一致性检查。这确保了每个拉取请求 (Pull Request) 在合并之前都会自动进行风格和结构一致性审计。 ```bash # Lint 检查的 CI 步骤示例 - name: Lint Documentation run: vale docs/ ``` ## 权衡 如果社区贡献者在修复简单的拼写错误时遇到了多个“风格错误”,严格的 Lint 检查有时会打击他们的积极性。我们建议将外部贡献的 Linter 敏感度设置为 `warning`(警告),并为内部团队更新保留 `error`(错误)状态,以在一致性与包容性之间取得平衡。 --- ## [预览更改](https://docs.docmd.io/zh/guides/workflows-teams/previewing-changes/) --- title: "预览更改" description: "如何设置本地和云端预览环境,以确保您的文档在发布前能够完美渲染。" --- ## 问题 在没有实时预览的情况下编写 Markdown 往往会导致格式错误、容器损坏以及错误的图像路径,而这些问题通常只有在内容发布到生产环境后才会显现。这会导致用户体验不佳,并为维护者增加额外的工作量,因为他们必须不断地为简单的渲染问题推送热修复。 ## 为什么重要 高质量的文档对于赢得开发者的信任至关重要。一个损坏的警告框或未渲染的语法看起来非常不专业,甚至可能在软件运行方式上误导用户。在文档发布前看到“真实”的效果是捕获错误、提高可读性并确保无缝用户体验最有效的方法。 ## 方法 实施多阶段预览策略:在编写时使用 `docmd` 的 [本地开发](../../getting-started/quick-start#local-development) 服务器获取即时反馈,并利用临时云环境(如 Vercel 或 Cloudflare Pages)在拉取请求 (Pull Request) 中进行最终审查。 ## 实施 ### 1. 即时本地预览 查看更改最快的方法是运行 `npx @docmd/core dev` 服务器。它具有热模块替换 (HMR) 功能,可在您保存 Markdown 文件时自动刷新浏览器。 ```bash # 启动本地开发服务器 npx @docmd/core dev ``` ### 2. 基于云的预览环境 对于协作审查,请配置您的 CI/CD 平台为每个拉取请求生成唯一的“预览 URL”。由于 `docmd` 输出标准的静态文件,它与所有主流托管提供商兼容。 * **构建命令**:`npx @docmd/core build` * **输出目录**:`site` 这允许审查人员在更改合并到主分支之前,查看其在类生产环境中的确切外观和行为。 ### 3. 利用 Threads 进行协作审查 将您的云预览与 [Threads 插件](../../plugins/usage) 相结合。这允许团队成员直接在渲染后的预览页面上留下反馈,弥补了源代码 Markdown 与最终用户体验之间的鸿沟。 ## 权衡 在拥有数千页文档的大型存储库中,为每次提交构建完整的静态站点可能会非常耗时,且会消耗大量的 CI/CD 资源。为了优化这一点,请配置您的 CI 流水线,仅在源目录(例如 `/docs`)中的文件被修改时才触发文档构建。 --- ## [建立工作流](https://docs.docmd.io/zh/guides/workflows-teams/setting-up-workflow/) --- title: "建立工作流" description: "如何使用 docmd 和“文档即代码 (docs-as-code)”原则建立高效的多作者文档协作工作流。" --- ## 问题 当团队缺乏结构化的文档工作流时,更新往往会被推迟、遗忘或仅通过临时消息共享。如果没有明确的流程,内容会变得碎片化,格式变得不一致,技术作家花在解决合并冲突上的时间比编写高质量内容的时间还要多。 ## 为什么重要 如果没有正式的流程,文档会迅速过时并失去价值。如果更新文档需要等待缓慢的软件发布周期,您的指南将永远与实际的产品功能脱节,从而导致用户沮丧并增加支持成本。 ## 方法 将文档部署从软件发布周期中解耦出来,同时采用与软件工程相同的健壮流程(分支 → 拉取请求 → CI/CD 预览)。`docmd` 的轻量化特性允许团队以最小的开销实践“文档即代码”,确保您的指南与软件一样可靠且保持最新。 ## 实施 ### 1. 存储库策略 选择最适合您组织结构的策略: * **单体存储库 (Monorepo) 策略**:在主应用存储库中保留一个 `/docs` 文件夹。这非常适合确保文档更改与它们所描述的代码在同一个拉取请求 (Pull Request) 中合并,从而保持完美的同步。 * **独立存储库策略**:最适合大型组织或开源项目,由专门的团队独立于主应用的构建流水线来管理文档。 ### 2. 通过 CI/CD 进行验证 将 `docmd` 集成到您的 CI/CD 流水线中,以确保每次更新在技术上都是完善的。至少,您的流水线应运行构建命令,以检查语法错误和配置问题。 ```bash # GitHub Actions 中的验证步骤示例 - name: 验证文档 run: npm install && npx @docmd/core build ``` 有关详细的设置说明,请参阅 [GitHub Actions 指南](../../guides/integrations/github-actions-cicd)。 ### 3. 协作审查流程 为所有文档更新建立同行评审 (Peer Review) 的文化。使用拉取请求来讨论更改、验证格式并确保技术准确性。您可以利用 [Threads 插件](../../plugins/usage) 在渲染后的内容上直接进行详细讨论。 ## 权衡 采用“文档即代码”工作流可能会给非技术贡献者(如产品经理或法律团队)带来障碍,他们可能会觉得 Git 和 Markdown 令人望而生畏。为了减轻这种影响,可以考虑使用 GitHub 内置的 Web 编辑器进行微小修复,或利用 [实时预览](../../content/live-preview) 功能提供更直观、更具视觉感的创作体验。 --- ## [版本管理工作流](https://docs.docmd.io/zh/guides/workflows-teams/versioning-release-workflows/) --- title: "版本管理工作流" description: "如何使用 docmd 的版本控制引擎和发布策略,使文档发布与软件部署保持同步。" --- ## 问题 使软件发布与相应的文档更新保持同步是一项重大的协作挑战。通常情况下,文档在实际代码部署之前就已经在站点上更新(这会误导当前用户),或者在软件发布几天后才延迟更新(这会让早期采用者感到沮丧)。 ## 为什么重要 软件行为与其文档之间的脱节是导致开发者产生挫败感的主要原因。为了使文档有效,它必须严格映射到用户当前运行的软件特定版本。为每个版本提供正确的上下文,可确保顺畅的入门和故障排除体验。 ## 方法 使用 `docmd` 的 [版本控制引擎](../../configuration/versioning) 隔离活跃开发中的文档。这允许您的团队在一个单独的目录(例如 `docs-next/`)中异步编写即将发布的功能的内容,并仅在正式软件发布时才将其提升为“稳定”或“当前”状态。 ## 实施 ### 1. 组织您的目录 在主 `docs/` 文件夹中维护稳定的文档,并为即将发布的版本创建一个专用目录。 ```text 项目根目录/ ├── docs/ # 当前稳定版 (v1.x) ├── docs-v2/ # 即将发布的版本 (v2.0) └── docmd.config.js ``` ### 2. 配置版本 在配置中注册这两个版本。您可以将即将发布的版本标记为“Beta”或“Next”,以通过版本切换器向用户发出状态信号。 ```json { "versions": { "current": "v1.0", "all": [ { "id": "v1.0", "dir": "docs", "label": "v1.x (稳定版)" }, { "id": "v2.0", "dir": "docs-v2", "label": "v2.0 (Beta)" } ] } } ``` ### 3. 提升流程 当您准备正式发布新版本时: 1. **更新配置**:将 `docmd.config.json` 中的 `current` 版本 ID 更改为 `v2.0`。 2. **更新标签**:从 `all` 数组的 `label` 中移除“(Beta)”标签。 3. **存档旧文档**:在 `all` 数组中保留 `v1.0` 条目,以便使用旧版本的用户仍然可以访问相关的文档。 ## 权衡 ### 维护开销 维护多个版本的文档需要严谨的态度。如果在稳定版本中修复了关键的拼写错误或安全警告,请确保该修复也应用到即将发布的版本目录中,以防止在新版本发布时出现“回归”问题。 ### SEO 与搜索 多个版本偶尔会导致搜索结果指向旧文档。使用 `seo` 插件和正确的规范 (canonical) 标签,确保“当前”版本始终被搜索引擎优先考虑。有关管理过渡的更多信息,请参阅 [处理重大更改](../scaling-architecture/breaking-changes-deprecations)。 --- ## [docmd 文档:一键将 Markdown 部署为生产文档](https://docs.docmd.io/zh/) --- title: "docmd 文档:一键将 Markdown 部署为生产文档" description: "几秒钟内从 Markdown 构建生产就绪的文档站点。零配置,默认高速,SEO 友好,天然支持 AI。" titleAppend: false --- ::: hero # docmd 一条命令,将 Markdown 变成生产文档。静态 HTML 保障 SEO,SPA 提升速度,天然支持 AI。 ::: button "快速开始" ./getting-started/quick-start.md icon:rocket ::: button "GitHub" external:https://github.com/docmd-io/docmd color:#24292e icon:github ::: ## 概览 docmd 是一个零配置的文档生成器,可直接从 Markdown 文件生成高性能静态网站。 ```bash npx @docmd/core dev ``` 运行这一条命令,引擎会自动构建网站、生成导航并启用即时搜索。 ## 核心功能 所有必要功能均已内置,无需安装复杂插件。 ::: grids ::: grid ::: card "即时启动" icon:rocket 无需任何配置,立即开始。引擎自动检测文件,几秒内完成导航结构搭建。 ::: ::: ::: grid ::: card "AI 就绪" icon:brain-circuit 自动生成 `llms.txt` 和 `llms-full.txt`,让 AI 模型轻松理解你的文档。 ::: ::: ::: grid ::: card "本地优先搜索" icon:search 基于 MiniSearch 的客户端全文搜索,开箱即用,支持多版本和多语言。 ::: ::: ::: grid ::: card "实时预览" icon:monitor 在页面中直接嵌入可交互、可编辑的代码沙盒,支持实时演示。 ::: ::: ::: grid ::: card "灵活主题" icon:palette 内置多套主题,支持自定义样式,完全兼容深色模式和系统主题偏好。 ::: ::: ::: grid ::: card "原生多语言" icon:globe 一流的国际化支持,包含按语言路由、独立搜索索引和翻译 UI 字符串。 ::: ::: ::: ::: callout info "丰富的内容容器" icon:info 超越标准 Markdown。在文本中直接使用步骤、标签页、卡片、网格、提示框等结构化视觉组件。 ::: button "探索容器" ./content/containers/index.md icon:blocks ::: --- ## [从 Docusaurus 迁移](https://docs.docmd.io/zh/migration/docusaurus/) --- title: "从 Docusaurus 迁移" description: "关于将你的 Docusaurus v2/v3 项目转移到 docmd 的综合指南。" --- # 从 Docusaurus 迁移到 docmd Docusaurus 是一个基于 React 的流行文档框架。`docmd` 提供了一个快速、零配置的替代方案,它的编译速度显著提高,并且不需要 React 组件即可渲染丰富的功能。 ## 第 1 步:运行迁移引擎 在现有 Docusaurus 项目的根目录(即 `docusaurus.config.js` 或 `docusaurus.config.ts` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --docusaurus ``` ### 自动发生的更改 1. **备份**: 你的整个项目(不包括 `node_modules` 和 `.git`)会被安全地移动到一个新的 `docusaurus-backup/` 目录中。 2. **内容迁移**: 你的 `docs/` 文件夹将被恢复到根目录,供 `docmd` 使用。 3. **配置生成**: 生成一个 `docmd.config.js` 文件,从你的 Docusaurus 配置中提取站点标题 (`title`)。 ## 第 2 步:测试设置 命令完成后,你可以立即在 `docmd` 中预览你的 Markdown 内容: ```bash npx @docmd/core dev ``` 你的 Markdown 文件将会编译,但你的导航侧边栏将是空的。 ## 第 3 步:手动配置 Docusaurus 拥有复杂的编程式配置,`docmd` 不会尝试猜测这些配置。你需要手动进行映射。 ### 1. 导航设置 Docusaurus 的侧边栏通常是在 `sidebars.js` 中自动生成或配置的。 **所需操作:** 在新的 `docs/` 目录内创建一个 `navigation.json` 文件来构建你的 `docmd` 侧边栏。请参阅 [导航指南](../configuration/navigation.md)。 ### 2. 替换 MDX 组件 Docusaurus 严重依赖 MDX (`.mdx`) 来渲染自定义 React 组件(如 Tabs、Admonitions 或自定义 UI 元素)。`docmd` 是纯粹由 Markdown 驱动的,不使用 React。 **所需操作:** 你必须将任何自定义的 `<MyReactComponent />` 标签转换为标准 Markdown,或使用 `docmd` 原生的 [容器](../content/containers/callouts.md)。 #### 示例:转换提示框 (Admonitions) **Docusaurus:** ```markdown :::tip My Tip 这是一个有用的技巧。 ::: ``` **docmd:** (除了为了更好的用户体验而更改了一些关键字外,学习曲线几乎为零。`docmd` 原生支持 Docusaurus 风格的提示框作为标注)。 ```markdown ::: callout tip "My Tip" 这是一个有用的技巧。 ::: ``` #### 示例:转换选项卡 (Tabs) **Docusaurus:** ```jsx import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="apple" label="Apple" default> 这是一个苹果。 </TabItem> <TabItem value="orange" label="Orange"> 这是一个橙子。 </TabItem> </Tabs> ``` **docmd:** (转换为原生的 `docmd` 选项卡容器语法) ```markdown ::: tabs == tab "Apple" 这是一个苹果。 == tab "Orange" 这是一个橙子。 ::: ``` ### 3. 本地化 (i18n) 如果你使用了 Docusaurus 的 `i18n` 功能,你的翻译文件可能位于 `i18n/locale/docusaurus-plugin-content-docs/current/`。 **所需操作:** 将这些文件移入 `docmd` 的目录结构(`docs/en/`、`docs/zh/` 等),并在 `docmd.config.js` 中配置语言环境。请参阅 [本地化指南](../configuration/localisation/index.md)。 ## 后续步骤 - 探索 [布局与 UI](../configuration/layout-ui.md) 设置,以匹配你的 Docusaurus 主题。 - 将基于 React 的 hero 页眉转换为 `docmd` [英雄区块容器](../content/containers/hero.md)。 --- ## [从 MkDocs 迁移](https://docs.docmd.io/zh/migration/mkdocs/) --- title: "从 MkDocs 迁移" description: "关于将你的 MkDocs (或 Material for MkDocs) 项目转移到 docmd 的综合指南。" --- # 从 MkDocs 迁移到 docmd MkDocs,特别是配合 Material 主题,是一个流行的基于 Python 的文档生成器。`docmd` 提供了类似的 Markdown 优先体验,但它依赖于 Node.js/Bun 以实现极快的构建速度和丰富的交互功能,而无需复杂的 Python 扩展。 ## 第 1 步:运行迁移引擎 在现有 MkDocs 项目的根目录(即 `mkdocs.yml` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --mkdocs ``` ### 自动发生的更改 1. **备份**: 你的整个项目会被安全地移动到一个新的 `mkdocs-backup/` 目录中。 2. **内容迁移**: 你的 `docs/` 文件夹将被恢复到根目录,供 `docmd` 使用。 3. **配置生成**: 生成一个 `docmd.config.js` 文件,从你的 `mkdocs.yml` 中提取站点名称 (`site_name`)。 ## 第 2 步:测试设置 命令完成后,在 `docmd` 中预览你的内容: ```bash npx @docmd/core dev ``` 你的 Markdown 文件将会编译,但你的导航侧边栏将是空的。 ## 第 3 步:手动配置 MkDocs 使用 `mkdocs.yml` 来定义站点导航和扩展。你需要将这些设置转换为 `docmd`。 ### 1. 导航设置 在 MkDocs 中,导航严格定义在 `mkdocs.yml` 的 `nav` 键中。 **所需操作:** 你必须在 `docs/` 文件夹内创建一个 `navigation.json` 文件。 **MkDocs (`mkdocs.yml`):** ```yaml nav: - Home: index.md - Guide: - Setup: setup.md - Usage: usage.md ``` **docmd (`navigation.json`):** ```json [ { "title": "首页", "path": "/" }, { "title": "指南", "collapsible": true, "children": [ { "title": "安装设置", "path": "/setup" }, { "title": "使用方法", "path": "/usage" } ] } ] ``` ### 2. 替换 Python Markdown 扩展 如果你使用了 "Material for MkDocs",你可能依赖于 Python Markdown 扩展(如 PyMdown Extensions)来实现选项卡、提示框或任务列表。 **所需操作:** 将 MkDocs 特有的扩展语法转换为 `docmd` 原生的 [容器](../content/containers/callouts.md)。 #### 示例:转换提示框 (Admonitions) **MkDocs (PyMdown):** ```markdown !!! note "可选标题" 这是一个提示框内容块。 ``` **docmd:** ```markdown ::: callout info "可选标题" 这是一个提示框内容块。 ::: ``` #### 示例:转换选项卡 (Tabs) **MkDocs (SuperFences):** ```markdown === "选项卡 1" 选项卡 1 的内容。 === "选项卡 2" 选项卡 2 的内容。 ``` **docmd:** ```markdown ::: tabs == tab "选项卡 1" 选项卡 1 的内容。 == tab "选项卡 2" 选项卡 2 的内容。 ::: ``` ## 后续步骤 - `docmd` 具有原生搜索功能。你不需要配置搜索插件。 - 探索 [主题选项](../theming/customisation.md) 来自定义网站颜色,以匹配你旧的 Material 主题。 --- ## [迁移概览](https://docs.docmd.io/zh/migration/overview/) --- title: "迁移概览" description: "了解如何轻松将现有文档迁移到 docmd。" --- # 迁移到 docmd `docmd` 提供了一个完全自动化的 **迁移引擎**,帮助您通过一条命令从旧的或竞争性的文档平台过渡。迁移引擎的目的是消除移动 Markdown 文件和重组项目目录的繁琐工作。 ## 工作原理 迁移命令将执行以下操作: 1. **检测**您现有的配置文件(例如 `docusaurus.config.js`,`mkdocs.yml`)。 2. **提取**站点的核心元数据,例如 `title`。 3. **备份**您现有的文件和目录,安全地放入 `*-backup/` 目录(例如 `docusaurus-backup/`)。 4. **复制**您的 Markdown 内容到标准的 `docmd` `docs/` 目录中。 5. **生成**一个为您内容量身定制的全新 `docmd.config.js`。 随后,您可以立即运行 `npx @docmd/core dev`,以查看在 `docmd` 引擎中渲染的内容。 ## 会迁移什么 | 功能 | 是否自动迁移? | | :--- | :--- | | **Markdown 文件** | ✅ 是的,所有 `.md` 和 `.mdx` 文件都会移到 `docs/` | | **目录结构** | ✅ 是的,您的文件夹嵌套会被保留 | | **站点标题** | ✅ 是的,从您的配置中提取 | | **容器语法** | ✅ 是的,VitePress/Docusaurus 容器无需更改即可工作 | | **导航 / 侧边栏** | ⚠️ **否**,需要手动映射 | | **国际化 (i18n)** | ⚠️ **否**,需要手动映射 | | **版本管理** | ⚠️ **否**,需要手动映射 | | **自定义 React/Vue 组件** | ❌ 否,这些必须替换为 `docmd` 容器 | ::: callout success "容器语法兼容性" **VitePress**(`:::tip`、`:::warning`、`:::danger`、`:::info`、`:::details`)和 **Docusaurus**(`:::note`、`:::caution`)的容器语法无需修改即可在 docmd 中工作。你现有的警告和可折叠部分在 docmd 中可以正确渲染。 **MkDocs** 使用 `!!!` 语法,需要手动转换为 `:::` 格式。 ::: ## 为什么不自动迁移导航和 i18n 每个文档平台处理导航侧边栏、翻译和多版本的方式各不相同。例如,Docusaurus 使用复杂的 JavaScript 对象或自动生成的侧边栏,而 MkDocs 依赖严格缩进的 YAML 结构。 为了避免猜测复杂配置带来的错误和损坏迁移,`docmd` 会安全地移动您的内容,并要求您使用 `docmd` 简单的基于 JSON 的 API,原生配置导航、国际化和版本管理。 - **导航:** 请参阅 [导航设置](../configuration/navigation.md) 了解如何创建 `navigation.json`。 - **国际化:** 了解如何设置多语言文档,请参阅 [国际化指南](../configuration/localisation/index.md)。 - **版本管理:** 请参考 [版本管理设置](../configuration/versioning.md)。 ## 支持的平台 选择您当前的平台以获取具体的迁移说明: - [由 Docusaurus 迁移](./docusaurus.md) - [由 MkDocs 迁移](./mkdocs.md) - [由 VitePress 迁移](./vitepress.md) - [由 Astro Starlight 迁移](./starlight.md) --- ## [由 Astro Starlight 迁移](https://docs.docmd.io/zh/migration/starlight/) --- title: "由 Astro Starlight 迁移" description: "将您的 Astro Starlight 项目迁移到 docmd 的综合指南。" --- # 由 Astro Starlight 迁移到 docmd Starlight 是一个构建在 Astro 框架上的出色文档主题。`docmd` 提供了类似的默认零 JavaScript 体验,但它消除了配置完整 Web 框架 (Astro) 的需要,从而大幅降低了技术作者的学习曲线。 ## 第一步:运行迁移引擎 在您现有的 Starlight 项目的根目录(即 `astro.config.mjs` 所在的位置)运行以下命令: ```bash npx @docmd/core migrate --starlight ``` ### 自动执行的操作 1. **备份**:您的整个项目会被安全地移动到一个新的 `starlight-backup/` 目录中。 2. **内容迁移**:Starlight 将文档保存在 `src/content/docs/` 目录中。迁移引擎会自动提取该特定目录,并将其内容移动至根目录下的 `docs/` 文件夹供 `docmd` 使用。 3. **配置生成**:生成一个 `docmd.config.js` 文件,从 `astro.config.mjs` 内的 Starlight 集成中提取您的站点 `title`。 ## 第二步:测试配置 命令完成后,在 `docmd` 中预览您的内容: ```bash npx @docmd/core dev ``` 您的 Markdown 文件将被编译,但导航侧边栏此时为空。 ## 第三步:手动配置 ### 1. 导航设置 Starlight 通过 `sidebar` 数组在 `astro.config.mjs` 中定义导航。 **所需操作:** 您必须在您新生成的 `docs/` 文件夹内创建一个 `navigation.json` 文件。 **Starlight (`astro.config.mjs`):** ```js sidebar: [ { label: 'Guides', items: [ { label: 'Setup', link: '/guides/setup/' } ], }, ] ``` **docmd (`navigation.json`):** ```json [ { "title": "Guides", "collapsible": true, "children": [ { "title": "Setup", "path": "/guides/setup" } ] } ] ``` ### 2. 替换 Astro 组件 (MDX/Markdoc) Starlight 使用通过 MDX 或 Markdoc 嵌入的 Astro 组件(`<Tabs>`, `<Card>` 等)。由于 `docmd` 依赖于纯 Markdown 语法而不是 UI 组件,因此需要转换这些内容。 **所需操作:** 将 Astro 组件替换为 `docmd` 的 [容器](../content/containers/callouts.md)。 #### 示例:转换标签页(Tabs) **Starlight:** ```mdx import { Tabs, TabItem } from '@astrojs/starlight/components'; <Tabs> <TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem> <TabItem label="Moons">Io, Europa, Ganymede</TabItem> </Tabs> ``` **docmd:** ```markdown ::: tabs == tab "Stars" Sirius, Vega, Betelgeuse == tab "Moons" Io, Europa, Ganymede ::: ``` #### 示例:转换提示框(Asides / Admonitions) **Starlight:** ```mdx :::note[Optional Title] Some note content. ::: ``` **docmd:** ```markdown ::: note "Optional Title" Some note content. ::: ``` ### 3. Frontmatter 映射 Starlight 通过 Astro 的内容合集功能对 Frontmatter 进行了严格地类型限制。`docmd` 的 Frontmatter 则更加简单。 如果您在 Starlight 中的登录页面使用了 `hero` 或 `banner` 前置属性,则需要将它们替换为直接写在 Markdown 正文中的 `docmd` [主页横幅](../content/containers/hero.md)。 ## 下一步 - 探索 `docmd` 的内置 [搜索插件](../plugins/search.md)(Starlight 使用 Pagefind,而 `docmd` 则原生提供了一个高度优化的本地搜索索引器)。 --- ## [由 VitePress 迁移](https://docs.docmd.io/zh/migration/vitepress/) --- title: "由 VitePress 迁移" description: "将您的 VitePress 项目迁移到 docmd 的综合指南。" --- # 由 VitePress 迁移到 docmd VitePress 是一个极其快速的基于 Vue 的静态网站生成器 (SSG) 框架。与 VitePress 类似,`docmd` 的运行速度也非常快,但它通过绝不向客户端加载任何 JavaScript 框架逻辑(没有 Vue 的水合成本)来实现这一点。 ## 第一步:运行迁移引擎 在您现有的 VitePress 项目的根目录运行以下命令: ```bash npx @docmd/core migrate --vitepress ``` ### 自动执行的操作 1. **备份**:您的整个项目会被安全地移动到一个新的 `vitepress-backup/` 目录中。 2. **内容迁移**:您的 `docs/` 文件夹会被恢复到根目录,供 `docmd` 使用。新 `docs/` 目录中会完全剥离 `.vitepress` 隐藏配置文件夹以防止冲突。 3. **配置生成**:生成一个 `docmd.config.js` 文件,从您的 `.vitepress/config.js` 或 `.ts` 中提取您的站点 `title`。 ## 第二步:测试配置 命令完成后,在 `docmd` 中预览您的内容: ```bash npx @docmd/core dev ``` 您的 Markdown 文件将被编译,但导航侧边栏此时为空。 ## 第三步:手动配置 VitePress 在其配置文件中设置导航,并在 Markdown 内部使用 Vue 组件。您需要将这些转换为 `docmd` 的语法。 ### 1. 导航设置 VitePress 在 `themeConfig.sidebar` 中使用对象数组。 **所需操作:** 在您的 `docs/` 目录内创建一个 `navigation.json` 文件。 **VitePress (`.vitepress/config.js`):** ```js themeConfig: { sidebar: [ { text: 'Guide', items: [ { text: 'Introduction', link: '/introduction' }, { text: 'Getting Started', link: '/getting-started' } ] } ] } ``` **docmd (`navigation.json`):** ```json [ { "title": "Guide", "collapsible": true, "children": [ { "title": "Introduction", "path": "/introduction" }, { "title": "Getting Started", "path": "/getting-started" } ] } ] ``` ### 2. 替换 Vue 组件 VitePress 允许作者在 Markdown 文件中直接嵌入 Vue 组件(例如 `<MyComponent />`)。由于 `docmd` 不会在客户端运行 Vue,您必须移除这些自定义组件,或者用原生的 Markdown 语法代替。 **所需操作:** 将特定的 Vue UI 组件替换为 `docmd` 的 [容器](../content/containers/callouts.md)。 #### 示例:提示框(自定义容器) VitePress 使用了与 `docmd` 非常相似的 markdown-it 自定义块语法。 **VitePress:** ```markdown ::: info This is an info box. ::: ``` **docmd:** ```markdown ::: info This is an info box. ::: ``` *注:VitePress 使用 `info`, `tip`, `warning`, `danger`, `details`。`docmd` 原生支持其中绝大多数,但您可能需要查看完整的 [docmd 提示框列表](../content/containers/callouts.md)。* ## 下一步 - 探索 `docmd` 的 [构建与部署](../deployment/index.md) 指南,因为 `docmd` 并不依赖 Vite 的构建管线。 --- ## [Analytics 插件](https://docs.docmd.io/zh/plugins/analytics/) --- title: "Analytics 插件" description: "集成 Google Analytics 4 或旧版 Universal Analytics,自动追踪用户交互行为。" --- `@docmd/plugin-analytics` 插件可将 Google Analytics 无缝集成到你的文档中。它支持现代 Google Analytics 4 (GA4)、旧版 Universal Analytics (UA),并内置针对交互弹性文档展示的原生事件追踪功能。 ## 配置 将下方的跟踪凭据添加到 `docmd.config.json` 的 `plugins` 部分即可启用分析功能。 ```json { "plugins": { "analytics": { "googleV4": { "measurementId": "G-XXXXXXX" }, "googleUA": { "trackingId": "UA-XXXXXXX-X" }, "autoEvents": true, "trackSearch": true } } } ``` ## 已追踪事件 当 `autoEvents` 启用时,插件会自动捕获以下用户交互并发送给你的分析提供商: * **外部链接**:追踪用户离开至外部资源。 * **文件下载**:自动记录带 `download` 属性或常见文件扩展名(`.pdf`、`.zip`、`.tar` 等)的链接点击。 * **目录(TOC)**:通过追踪右侧导航栏中的点击,监控哪些章节最受关注。 * **标题锚点**:记录用户点击"固定链接"(标题锚点)以分享特定章节。 * **搜索查询**:当 `trackSearch` 启用时,关键词会被捕获(带 1 秒防抖),帮助你了解用户正在寻找什么。 ## 技术细节 插件将必要的追踪脚本注入每个页面的 `<head>` 中。事件监听器通过高效的事件委托绑定到 `<body>`,确保对页面加载性能和 SPA 切换的零影响。 ::: callout info "隐私与 GDPR" 默认情况下,此插件不匿名处理 IP 地址,因为这现在由 GA4 原生处理。如果需要高级 Cookie 同意管理,可以使用 `customCss` 或自定义插件钩子手动注入你的同意管理脚本。 ::: --- ## [创建插件](https://docs.docmd.io/zh/plugins/building-plugins/) --- title: "创建插件" description: "扩展 docmd 的综合指南,涵盖自定义逻辑、数据注入和交互功能。" --- 插件是 `docmd` 的主要扩展机制。它们允许您注入自定义 HTML、修改 Markdown 解析逻辑、在模板渲染前注入构建时数据,以及自动化构建后任务。本指南概述了插件 API 和创建可共享组件的最佳实践。 ## 插件描述符 每个插件都应导出一个 `plugin` 描述符,声明其身份和功能。这使引擎能够在加载时验证、隔离和执行能力边界。 ```javascript export default { plugin: { name: 'my-analytics', version: '1.0.0', capabilities: ['head', 'body', 'post-build'] }, generateScripts: (config, opts) => { ... }, onPostBuild: async (ctx) => { ... } }; ``` > **注意:** 描述符目前是可选的(软性弃用警告)。从 **0.8.0 开始将成为必需**。 ## 核心能力 `capabilities` 数组决定您的插件可以使用哪些钩子。 | 能力 | 允许的钩子 | 阶段 | | :--- | :--- | :--- | | `init` | `onConfigResolved` | 初始化 | | `markdown` | `markdownSetup` | 设置 | | `head` | `generateMetaTags`, `generateScripts` (head) | 渲染 | | `body` | `generateScripts` (body) | 渲染 | | `build` | `onBeforeParse`, `onAfterParse`, `onBeforeRender`, `onPageReady` | 构建 | | `post-build`| `onPostBuild` | 构建后 | | `dev` | `onDevServerReady` | 开发服务器 | | `assets` | `getAssets` | 输出 | | `actions` | `actions` | 交互 | | `events` | `events` | 交互 | | `translations`| `translations` | 国际化 | 没有描述符的旧版插件可以访问所有钩子,因此在过渡期间不会有任何中断。 ## 插件 API 参考 `docmd` 插件是一个标准 JavaScript 对象(或导出为默认值的模块),实现以下一个或多个钩子。 | 钩子 | 描述 | | :--- | :--- | | `markdownSetup(md, opts)` | 扩展 `markdown-it` 实例。同步。 | | `generateMetaTags(config, page, root)` | 向 `<head>` 注入 `<meta>` 或 `<link>` 标签。 | | `generateScripts(config, opts)` | 返回包含 `headScriptsHtml` 和 `bodyScriptsHtml` 的对象。 | | `getAssets(opts)` | 定义要注入的外部文件或 CDN 脚本。 | | `onPostBuild(ctx)` | 在生成所有 HTML 文件后运行逻辑。 | | `translations(localeId)` | 返回给定语言环境的翻译字符串对象。 | | `actions` | 浏览器通过 WebSocket RPC 调用的命名动作处理程序对象。 | | `events` | 浏览器发送的即发即忘消息的命名事件处理程序对象。 | ## 创建本地插件 创建插件就像定义一个 JavaScript 文件一样简单。例如,`my-plugin.js`: ```javascript // my-plugin.js import path from 'path'; export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['head', 'post-build'] }, markdownSetup: (md, options) => { // 示例:添加规则或使用 markdown-it 插件 }, generateMetaTags: async (config, page, relativePathToRoot) => { return `<meta name="x-build-id" content="${config._buildHash}">`; }, onPostBuild: async ({ config, pages, outputDir, log, options }) => { log(`自定义插件:已验证 ${pages.length} 个页面。`); } }; ``` 在您的 `docmd.config.json` 中通过**完整包名**引用插件: ```json { "plugins": { "my-plugin": {} } } ``` } }); ``` > **注意:** 简写名称(如 `math`、`search`)专门为官方 `@docmd/plugin-*` 包保留。第三方插件必须始终使用其完整 npm 包名。 ### 插件隔离 每个钩子调用都被包裹在 try/catch 边界中。损坏的插件无法使构建崩溃或干扰其他插件。错误会被记录并收集到构建结束时的摘要中。 ## 生命周期钩子 docmd 提供深度集成钩子,允许插件在整个构建管道中操作配置、原始源和页面数据。 | 钩子 | 描述 | 预期返回值 | | :--- | :--- | :--- | | **`onConfigResolved(config)`** | 在初始化后立即读取或修改活动规范化配置。 | `void` 或 `Promise<void>` | | **`onDevServerReady(server, wss)`** | 在开发模式下公开原始 Node.js `http.Server` 和 `WebSocketServer`。 | `void` 或 `Promise<void>` | | **`onBeforeParse(src, frontmatter)`** | 在传递给 markdown-it 解析之前预处理原始 markdown 字符串数据。 | `string` 或 `Promise<string>` | | **`onAfterParse(html, frontmatter)`** | 后处理表示 markdown 正文段的生成 HTML。 | `string` 或 `Promise<string>` | | **`onBeforeRender(page)`** | 在模板渲染前调用。接收完整的 `PageContext`。对 `frontmatter` 和 `html` 的修改会反映在渲染输出中。 | `void` 或 `Promise<void>` | | **`onPageReady(page)`** | 在页面写入目标文件之前访问完整组装的页面元数据。 | `void` 或 `Promise<void>` | ### 多线程后台任务 (`runWorkerTask`) 从 0.8.0 开始,docmd 在持久的多线程 `WorkerPool` 中处理 markdown。插件可以将自身繁重的 I/O 或 CPU 密集型任务卸载到这些线程中,而不是阻塞主构建线程。 `runWorkerTask` 方法被注入到 `PageContext`、`PostBuildContext` 和 `ActionContext` 中。 ```javascript export default { plugin: { name: "my-plugin", version: "1.0.0", capabilities: ["post-build"] }, onPostBuild: async (ctx) => { // 传递 worker 脚本的绝对路径、导出的函数名以及参数数组 const result = await ctx.runWorkerTask('/absolute/path/to/worker.js', 'parseData', [ctx.outputDir]); } } ``` ### `onBeforeRender` 和 `PageContext` `onBeforeRender` 钩子适用于需要注入源文件派生构建时数据的插件 - - 读取文件元数据、计算自定义 frontmatter 字段或从外部源加载数据。 ```typescript interface PageContext { sourcePath: string; // .md 源文件的绝对路径。始终设置。 frontmatter: Record<string, any>; // 可变 - 更改反映在模板输出中 html: string; // 可变 - 渲染的 markdown 正文 localeId?: string; versionId?: string; relativePathToRoot?: string; } ``` ```javascript export default { plugin: { name: 'my-metadata-plugin', version: '1.0.0', capabilities: ['build'] }, onBeforeRender: async (page) => { // sourcePath 始终可用 - 无需猜测或路径构建 const stats = fs.statSync(page.sourcePath); page.frontmatter.wordCount = page.html.split(/\s+/).length; page.frontmatter.fileSize = stats.size; } }; ``` ## 深入了解:资产注入 `getAssets()` 钩子允许您的插件安全地捆绑客户端逻辑。 ```javascript getAssets: (options) => { return [ { url: 'https://cdn.example.com/lib.js', type: 'js', location: 'head' }, { src: path.join(__dirname, 'plugin-init.js'), dest: 'assets/js/plugin-init.js', type: 'js', location: 'body' } ]; } ``` ## 翻译插件(国际化) 渲染客户端 UI 的插件应通过 `translations(localeId)` 钩子公开可翻译字符串。 ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['translations', 'body'] }, translations: (localeId) => { try { const p = path.join(__dirname, 'i18n', `${localeId}.json`); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } try { const p = path.join(__dirname, 'i18n', 'en.json'); return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { } return {}; } } ``` ## WebSocket RPC 动作 插件可以注册在开发服务器上运行并可通过 `window.docmd` API 从浏览器调用的**动作处理程序**和**事件处理程序**。 ```javascript export default { plugin: { name: 'my-live-plugin', version: '1.0.0', capabilities: ['actions', 'events'] }, actions: { 'my-plugin:save-note': async (payload, ctx) => { const content = await ctx.readFile(payload.file); const updated = content + '\n\n> ' + payload.note; await ctx.writeFile(payload.file, updated); return { saved: true }; } }, events: { 'my-plugin:page-viewed': (data, ctx) => { console.log(`页面已查看: ${data.path}`); } } }; ``` `ctx`(ActionContext)对象提供: | 方法 | 描述 | | :--- | :--- | | `ctx.readFile(path)` | 相对于项目根目录读取文件。 | | `ctx.writeFile(path, content)` | 写入文件(触发重建 + 重载)。 | | `ctx.readFileLines(path)` | 将文件读取为行数组。 | | `ctx.broadcast(event, data)` | 向所有连接的浏览器推送事件。 | | `ctx.source` | 用于块级 markdown 操作的源编辑工具。 | | `ctx.projectRoot` | 项目根目录的绝对路径。 | | `ctx.config` | 当前 docmd 站点配置。 | ::: callout info "仅开发模式 🛡️" WebSocket RPC 系统仅在 `npx @docmd/core dev` 期间活跃。生产构建不包含 API 客户端或任何服务器端动作处理。 ::: ## 最佳实践 1. **声明能力**:始终导出带有声明能力的 `plugin` 描述符。从 `0.8.0` 开始将成为必需。 2. **使用 `onBeforeRender` 进行数据注入**:如果您的插件读取源文件或计算 frontmatter 字段,请使用 `onBeforeRender` - 而不是 `generateMetaTags`。`sourcePath` 在 `PageContext` 中始终可用。 3. **异步/等待**:始终对 `onPostBuild`、`onBeforeRender` 和动作处理程序使用 `async` 函数。 4. **无状态**:避免在插件对象中维护状态,因为 `docmd` 可能在开发重建期间重新初始化插件。 5. **命名约定**:对于社区插件,以 `docmd-plugin-` 为前缀(如 `docmd-plugin-analytics`)。 6. **动作命名空间**:以插件名称为前缀(如 `my-plugin:save-note`)以避免冲突。 7. **动作验证**:始终在动作中定义和要求明确的有效载荷模式。 8. **日志记录**:在 `onPostBuild` 中使用提供的 `log()` 辅助函数。 ::: callout tip "AI 就绪设计 🤖" `docmd` 插件 API 设计为 **LLM 最优**。由于钩子使用标准 JavaScript 对象和类型,没有隐藏的复杂类层次结构,AI 代理可以以最少的指令为您生成无错误的自定义插件。 ::: --- ## [Git 插件](https://docs.docmd.io/zh/plugins/git/) --- title: "Git 插件" description: "显示直接从 Git 仓库获取的最后更新时间戳和提交历史。" --- **Git 插件**为您的文档页面添加仓库感知的元数据。它显示每个页面的最后修改时间、贡献者信息,并提供可选的"编辑此页"链接 - 所有这些都直接从您的 Git 历史记录中获取,无需配置。 ::: callout info "核心插件" Git 插件已包含在 `@docmd/core` 中,默认启用。它会自动检测您的项目是否在 Git 仓库中,如果不在则会自动禁用。基本功能无需安装或配置。 ::: ## 功能 ### 最后更新时间戳 每个页面自动显示其最后修改时间,显示在页面底部的编辑链接旁边。时间戳来自最近修改该源文件的 Git 提交。 时间戳对于最近的更改使用相对格式("2小时前"、"3天前"),对于较旧的内容则切换到绝对日期("2026年3月15日")。 ### 提交历史工具提示 将鼠标悬停在"最后更新"文本上,可以显示该页面最近提交的工具提示。每个条目显示提交消息、作者(附带 Gravatar 头像)和相对时间戳。 这提供了关于最近更改的快速上下文,无需离开页面 - 对于了解更新内容和更新者非常有用。 ### 编辑链接 配置仓库 URL 后,插件会显示"编辑此页"链接,直接在您的 Git 提供商的网页编辑器中打开源文件。 ```json { "plugins": { "git": { "repo": "https://github.com/your-org/your-docs", "branch": "main" } } } ``` 插件自动检测 GitHub、GitLab 和 Bitbucket URL,并为每个提供商构建正确的编辑链接格式。 ## 配置 | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `repo` | `string` | `null` | 仓库 URL(例如 `https://github.com/org/repo`)。编辑链接必需。 | | `branch` | `string` | `'main'` | 编辑链接的分支名称。 | | `editLink` | `boolean` | `true` | 设置 `repo` 时显示"编辑此页"链接。 | | `lastUpdated` | `boolean` | `true` | 显示最后更新时间戳。 | | `commitHistory` | `boolean` | `true` | 悬停时显示提交历史工具提示。 | | `maxCommits` | `number` | `6` | 工具提示中显示的最大提交数(仅在 `commitHistory` 为 `true` 时适用)。 | | `dateFormat` | `string` | `'relative'` | 时间戳格式:`relative`(相对)、`iso`(ISO 格式)或 `locale-aware`(本地化格式)。 | ### 完整示例 ```json { "plugins": { "git": { "repo": "https://github.com/docmd-io/docs", "branch": "main", "editLink": true, "lastUpdated": true, "commitHistory": true, "maxCommits": 5 } } } ``` ## 页面级控制 使用 frontmatter 为特定页面禁用 Git 插件: ```markdown --- title: "内部笔记" plugins: git: false --- 此页面不会显示最后更新时间或编辑链接。 ``` ## 工作原理 插件在构建时使用标准 Git 命令读取 Git 历史。对于每个 markdown 文件: 1. 运行 `git log` 获取提交历史 2. 提取时间戳、作者和提交消息 3. 将数据注入页面上下文 4. 客户端 JavaScript 渲染 UI 组件 ::: callout tip "性能" Git 数据在构建过程中被缓存。每个文件的历史只查询一次,无论页面被渲染多少次(例如跨多个语言环境)。 ::: ## 要求 - 文档源必须位于 Git 仓库内 - 构建环境中必须可用 Git - 文件在其历史中必须至少有一个提交 没有 Git 历史的页面(尚未提交的新文件)不会显示时间戳或提交历史。 ## 从 editLink 迁移 如果您之前使用 `editLink` 配置选项,Git 插件提供相同的功能并附加额外特性: **之前(editLink 配置):** ```json { "editLink": { "enabled": true, "baseUrl": "https://github.com/org/repo/edit/main/docs", "text": "编辑此页" } } ``` **之后(Git 插件):** ```json { "plugins": { "git": { "repo": "https://github.com/org/repo", "branch": "main" } } } ``` Git 插件自动从仓库和分支构建编辑 URL,因此您不再需要手动指定完整的编辑路径。 ::: callout warning "弃用通知" 独立的 `editLink` 配置选项已弃用,将在未来版本中移除。请迁移到 Git 插件以获取编辑链接功能。 ::: ## 本地化 插件包含所有 UI 字符串的翻译。支持的语言: - 英语 (en) - 德语 (de) - 中文 (zh) 自定义翻译可以通过标准 [UI 字符串](../configuration/localisation/ui-strings.md)系统提供。 --- ## [LLM 上下文插件](https://docs.docmd.io/zh/plugins/llms/) --- title: "LLM 上下文插件" description: "通过自动生成 llms.txt 和 llms-full.txt,为 AI 消费优化你的文档。" --- `@docmd/plugin-llms` 插件确保你的文档针对大型语言模型 (LLMs) 和 AI 代理进行了完美优化。它遵循不断增长的行业标准,即提供高层摘要和全面的上下文文件,AI 工具可以提取这些文件,以在产生极少幻觉的情况下理解你的项目。 ## 配置 LLM 插件默认启用。为了使其正常运行,你必须在 `docmd.config.json` 中提供一个 `url`。 ```json { "url": "https://docs.example.com", "plugins": { "llms": { "fullContext": true } } } ``` ### 排除页面 如果页面包含敏感信息或你不希望 AI 模型学习的内部笔记,请在 frontmatter 中使用 `llms: false` 标志: ```yaml --- title: "内部开发机密" llms: false --- ``` ::: callout tip "最大化 AI 准确性 :robot:" 有关构建 Markdown(语义标题、替代文本等)的详细最佳实践,请参阅我们的 [针对 AI 代理进行优化](../guides/ai-optimisation/generating-ai-ready-docs.md) 指南。 ::: --- ## [Math 插件](https://docs.docmd.io/zh/plugins/math/) --- title: "Math 插件" description: "docmd 的原生 KaTeX/LaTeX 数学公式集成。" --- **Math 插件**为你的 docmd 网站添加原生 LaTeX 和 KaTeX 支持。 它将 `markdown-it-texmath` 与 `katex` 计算引擎安全集成,平滑渲染内联和块级数学公式,无需复杂的客户端 JavaScript 库。 ## 安装 ```bash npx @docmd/core add math ``` 在 `docmd.config.json` 中启用: ```json { "plugins": { "math": {} } } ``` ## 工作原理 1. 通过 `docmd.config.json` 启用插件。 2. 用 `$`(内联)或 `$$`(块级)标识符包裹标准 LaTeX 数学公式。 3. 服务器在静态站点构建时以原始静态 HTML 标签的形式智能处理这些数学规则。 4. 注入的极简 CSS 自动为这些类设置作用域,用户访问页面时即刻呈现可视化效果! ## 用法 ### 内联数学公式 使用单个美元符号 `$` 在段落中无缝注入标准方程式: ```markdown 这是一个内联方程式:$E = mc^2$ ``` 这是一个内联方程式:$E = mc^2$ ### 块级数学公式 对于较宽的数学证明或独立公式,使用双美元符号 `$$` 进行块级格式化: ```markdown $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ ``` $$ \sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6} $$ --- ## [Mermaid 图表 (Mermaid Diagrams)](https://docs.docmd.io/zh/plugins/mermaid/) --- title: "Mermaid 图表 (Mermaid Diagrams)" description: "使用 Mermaid.js 语法,直接在 Markdown 文件中创建专业的架构图、流程图和序列图。" --- `@docmd/plugin-mermaid` 插件将强大的 [Mermaid.js](external:https://mermaid.js.org/) 引擎集成到你的文档流水线中。它允许你将纯文本描述转换为高保真、交互式的图表,而无需离开 Markdown 环境。 ## 主要特性 - **零脚本**: 无需手动引入外部脚本或 CDN 链接。`docmd` 会检测使用情况,并仅在需要的地方注入渲染引擎。 - **主题感知**: 图表会自动调整其配色方案,以匹配网站的 **浅色** 或 **深色** 模式切换。 - **同构延迟加载**: 为了获得最佳性能,图表仅在进入用户视口时才进行初始化和渲染。 - **交互控制**: 每个图表都内置了 **平移 (Pan)**、**缩放 (Zoom)** 和 **全屏 (Fullscreen)** 功能,确保大型架构图在所有屏幕尺寸上都清晰可见。 - **图标集成**: 深度支持图标库,允许你在架构图中使用 `icon:name` 语法。 - **技术可读性**: 图表在源码中保持纯文本形式,使其易于进行版本控制,并且可被 AI 代理阅读。 ## 配置 要启用图表支持,请在 `docmd.config.json` 中添加 `mermaid` 插件: ```json { "plugins": { "mermaid": {} } } ``` ## 实现展示 要渲染图表,请将你的 Mermaid 语法放置在带有 `mermaid` 语言标识符的围栏代码块内。 ### 1. 序列图 (Sequence Diagrams) 非常适合说明多个系统组件之间的交互。 ::: tabs == tab "预览" ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: 输入 URL Browser->>Server: HTTP 请求 Server-->>Browser: HTTP 响应 Browser-->>User: 显示页面 ``` == tab "Markdown 源码" ````markdown ```mermaid sequenceDiagram participant User participant Browser participant Server User->>Browser: 输入 URL Browser->>Server: HTTP 请求 Server-->>Browser: HTTP 响应 Browser-->>User: 显示页面 ``` ```` ::: ### 2. 分析图表 使用内置的图表类型(如饼图或柱状图)将数据可视化。 ::: tabs == tab "预览" ```mermaid pie title 项目组成 "文档" : 45 "核心引擎" : 30 "插件" : 15 "UI 组件" : 10 ``` == tab "Markdown 源码" ````markdown ```mermaid pie title 项目组成 "文档" : 45 "核心引擎" : 30 "插件" : 15 "UI 组件" : 10 ``` ```` ::: ### 3. Git 工作流 为你的开发者指南可视化分支和合并策略。 ::: tabs == tab "预览" ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` == tab "Markdown 源码" ````markdown ```mermaid gitGraph commit branch develop checkout develop commit commit checkout main merge develop commit ``` ```` ::: ### 4. 架构与图标 使用集成的 **Lucide** 图标库创建与网站视觉风格匹配的丰富架构图。 ::: tabs == tab "预览" ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[数据库] in api service disk(icon:hard-drive)[存储] in api db:L -- R:disk ``` == tab "Markdown 源码" ````markdown ```mermaid architecture-beta group api(icon:cloud)[API] service db(icon:database)[数据库] in api service disk(icon:hard-drive)[存储] in api db:L -- R:disk ``` ```` ::: ## 技术实现 Mermaid 插件通过在解析阶段拦截 `mermaid` 代码块并将其包裹在专门的 `<div class="mermaid">` 容器中来运行。 1. **检测**: 引擎扫描渲染后的 HTML 以查找 mermaid 容器的存在。 2. **资源注入**: 如果发现容器,`docmd` 会注入一个轻量级的 `init-mermaid.js` 模块。 3. **渲染**: Mermaid 库会被异步获取,并在客户端渲染图表,确保你的初始 HTML 负载保持小巧且快速。 ::: callout tip "针对 AI 代理的图表" 虽然图表在视觉上对人类有帮助,但它们在技术上对 AI 也是透明的。因为源码是纯文本,像 GPT-4 或 Claude 这样的模型可以通过 `llms-full.txt` 流“看到”你的系统架构或逻辑流。这允许 AI 根据你的图表解释复杂的架构关系。 ::: --- ## [OpenAPI 插件](https://docs.docmd.io/zh/plugins/openapi/) --- title: "OpenAPI 插件" description: "直接在 Markdown 页面中从 JSON 或 YAML 规范文件渲染 OpenAPI 3.x API 参考文档。" --- **OpenAPI 插件**将 OpenAPI 3.x 规范文件转换为结构化的 API 参考页面——在构建时渲染,无需客户端 JavaScript,无需第三方依赖。每个端点、参数、请求体和响应都转换为语义化 HTML 表格。 ::: callout info "核心插件" OpenAPI 插件已**内置**于 `@docmd/core` 中,无需单独安装。它遵循 docmd 的构建时渲染理念——插件在构建时读取你的规范并输出干净、可访问的 HTML 表格,无需客户端 JavaScript。 ::: ## 启用 在 `docmd.config.json` 中启用: ```json { "plugins": { "openapi": {} } } ``` ## 使用方法 在任何 Markdown 页面中使用带 `openapi` 语言标签的围栏代码块嵌入 OpenAPI 规范: ````markdown ```openapi assets/docmd-api.json ``` ```` 路径相对于你的 `src` 目录解析。支持 **JSON** 和 **YAML** 格式。 ## 渲染内容 对于规范中的每个路径和 HTTP 方法,插件渲染: * **方法徽章** — 颜色编码(`GET`、`POST`、`PUT`、`PATCH`、`DELETE`) * **路径** — 完整端点路径 * **摘要和描述** — 来自操作对象 * **参数** — 路径、查询、请求头参数,包含类型和必填标记 * **请求体** — 包含 JSON Schema 示例 * **响应** — 按状态码列出,包含描述和 Schema ::: callout tip "AI 上下文" OpenAPI 规范提供了精确的机器可读 API 合约。当与 `llms-full.txt` 结合使用时,AI 代理可以直接从你的文档中理解你的 API 结构,无需额外说明。 ::: --- ## [PWA 与离线支持](https://docs.docmd.io/zh/plugins/pwa/) --- title: "PWA 与离线支持" description: "将文档转化为渐进式 Web 应用,支持离线缓存和移动端特性。" --- **PWA 插件**将你的文档转化为渐进式 Web 应用,支持离线缓存和移动端安装。它添加 Web Manifest 以支持移动端安装,并注册 Service Worker 处理智能离线缓存,确保技术文档即使在网络不稳定的环境下仍可访问。 ## 安装 ```bash npx @docmd/core add pwa ``` ## 配置 可在 `docmd.config.json` 的 `plugins` 部分自定义 PWA 插件的品牌配置。 ```json { "plugins": { "pwa": { "enabled": true, "themeColor": "#1e293b", "bgColor": "#ffffff", "logo": "/assets/logo.png" } } } ``` ## 核心功能 ### 1. 离线缓存 插件会自动生成实现“旧数据优先更新”(Stale-While-Revalidate)缓存策略的 `service-worker.js` 文件。用户访问页面时,Service Worker 将: * 立即返回缓存版本以实现最大速度。 * 在后台从网络获取最新版本。 * 为下次访问更新缓存。 ### 2. 移动端安装 通过生成 `manifest.webmanifest` 并注入所需的 `<meta>` 标签,插件允许用户在 iOS 和 Android 上“添加到主屏幕”。你的文档将表现得像一个独立应用,拥有自己的启动画面和窗口框架。 ### 3. 智能资源解析 插件会通过查找项目的 `logo` 或 `favicon` 自动生成应用图标。如需更多控制,可提供明确的 `icons` 数组: ```json { "plugins": { "pwa": { "icons": [ { "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" } ] } } } ``` ## 技术实现 Service Worker 将与单页应用(SPA)路由兼容地设计。它包含针对 Safari 严格安全策略(涉及重定向流)的安全防护逻辑,确保在所有现代浏览器上的稳定性。 ::: callout tip "开发模式" 在本地开发(`npx @docmd/core dev`)中,Service Worker 通常会被禁用或绕过,以防止积极缓存干扰你的编辑。如需测试 PWA 功能,请使用 `npx @docmd/core build` 执行生产构建,并使用静态托管服务输出目录。 ::: ### 完全移除 只需删除 `plugins` 中的 `pwa` 块即可。下次运行 `npx @docmd/core build` 时不会生成新的 manifest。当用户访问站点时,docmd 的客户端引导程序(`docmd-main.js`)会检查 `<link rel="manifest">` 的存在。如果它不存在但 Service Worker 已注册,将自动**注销所有现存 Service Worker** 并清除缓存外壳——无需用户操作。 ::: callout warning 上次构建产生的 `manifest.webmanifest` 和 `service-worker.js` 文件会在磁盘上持久存在,直到你使用 `npx @docmd/core build` 或 `rm -rf site` 清除输出目录(默认为 `site/`)为止。这是文件系统残留物,不是活跃的 PWA。 ::: ## 配置参考 所有字段均为可选。默认值设计为零配置即用。 ```json { "plugins": { "pwa": { "logo": "assets/images/app-icon.png", "icons": [ { "src": "/assets/images/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/assets/images/icon-512.png", "sizes": "512x512", "type": "image/png" } ], "themeColor": "#1e293b", "bgColor": "#ffffff", "enabled": false } } } ``` 图标解析优先级:`pwa.logo` > `config.logo` > `config.favicon` > (无图标) ### 图标解析优先级 docmd 按以下层级解析 PWA 图标: 1. `pwa.icons` - 手动数组,直接使用 2. `pwa.logo` - 单一图片路径,用于 192x192 和 512x512 条目 3. `config.logo` - 全局站点 logo 4. `config.favicon` - 全局 favicon 5. *(manifest 中未声明图标)* - 以上均未设置时 ## 本地测试 浏览器将 Service Worker 限制在 `https://` 或 `localhost`。使用: ```bash npx @docmd/core dev ``` 打开 Chrome DevTools → **Application** → **Manifest** 和 **Service Workers**,即可实时查看已激活的注册信息。 Safari → **Develop** → **Service Workers** 面板同样适用。 --- ## [搜索插件 (Search Plugin)](https://docs.docmd.io/zh/plugins/search/) --- title: "搜索插件 (Search Plugin)" description: "使用 MiniSearch 为你的文档启用高速、离线优先的全文搜索,以及基于本地向量嵌入的语义搜索(Alpha 预览)。" --- `@docmd/plugin-search` 插件为你的文档提供了强大的客户端搜索体验。它使用 [MiniSearch](external:https://github.com/lucaong/minisearch) 在构建过程中构建轻量级索引,允许用户在没有服务器端数据库的情况下即时查找技术信息。 ## 配置 在大多数 `docmd` 模板中,搜索是默认启用的。你可以通过 `layout` 配置来控制其可见性和位置。 | 选项 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | `enabled` | `boolean` | `true` | 启用或禁用全文搜索索引器。 | | `placeholder` | `string` | `'Search...'` | 搜索输入框的自定义占位文本。 | | `maxResults` | `number` | `10` | 弹框中显示的最大结果数量。 | ### 示例 ```json { "layout": { "optionsMenu": { "position": "header", "components": { "search": true } } } } ``` ## 工作原理 <img width="720" class="with-border" src="/assets/previews/search-ui-default.webp"> ### 1. 索引(构建时) 在 `npx @docmd/core build` 过程中,搜索插件会遍历网站上的每一个页面。它会提取标题、副标题和正文文本,然后将这些数据编译成压缩的 `search-index.json` 文件。 * **深层链接**:索引器会自动将每个标题(`#`、`##` 等)注册为可搜索目标。 * **相关性提升**:页面标题被赋予最高权重,其次是副标题,最后是正文内容。 ### 2. 检索(客户端) 当用户打开搜索弹窗(通常通过 `/` 或 `Ctrl+K`)时,浏览器会获取 `search-index.json` 文件。搜索在本地执行,采用模糊匹配(允许轻微的拼写错误)和即时前缀匹配。 ## 自定义搜索行为 虽然搜索插件旨在实现零配置的简洁性,但你可以通过在页面的 frontmatter 中使用 `noindex` 标志来将特定页面排除在索引之外: ```yaml --- title: "内部规范" noindex: true # 此页面将不会出现在搜索结果或站点地图中 --- ``` ## 技术实现 该插件在网站的 `<body>` 中注入一个轻量级的搜索弹窗。它完全符合无障碍标准(ARIA 兼容),并支持键盘导航,提供接近原生应用的体验。 ::: callout tip "搜索分析" 如果你启用了 [分析插件](./analytics.md),读者使用的搜索关键词会被自动捕获并发送到你的分析服务商,让你了解哪些信息缺失或最难找到。 ::: 由于搜索完全在客户端进行,没有任何数据(甚至是按键记录)会被发送到服务器。这使得 `docmd` 成为隐私敏感行业(医疗、金融、安全)文档搜索的黄金标准。 ## 对比 许多文档生成器(如 Docusaurus)依赖于 **Algolia DocSearch**。虽然 Algolia 功能强大,但它也引入了额外的复杂性: | 功能 | docmd 搜索 | Algolia / 外部方案 | | :--- | :--- | :--- | | **设置** | **零配置**(自动化) | 复杂(API 密钥、CI/CD 爬取) | | **隐私** | **100% 私有**(客户端) | 数据发送到第三方服务器 | | **离线** | **支持** | 不支持 | | **成本** | **免费** | 免费层级有限制或付费 | | **速度** | **即时**(内存中) | 较快(取决于网络延迟) | ## 语义搜索(Alpha 预览) ::: callout tip "认识 docmd-search" 我们做了一件令自己颇为自豪的事。 **`docmd-search`** 据我们所知,是首个专为文档设计的全离线语义搜索引擎——而且它并不依赖 docmd。它完全在浏览器中运行,无需服务器,无需 API 密钥,用户的任何数据都不会离开本地设备。可接入任何文档引擎、任何静态网站,甚至任意网页,即插即用。 目前处于早期 Alpha 阶段,仍在持续改进中。但核心已经到位——私密、离线、真正智能的搜索。 [→ 在 GitHub 上查看](https://github.com/docmd-io/docmd-search) ::: > **实验性功能** — 语义搜索目前处于 Alpha 预览阶段。默认的关键词搜索仍是生产环境的推荐选项。 <img width="720" class="with-border" src="/assets/previews/search-ui-semantic.webp"> 语义搜索使用本地向量嵌入来理解查询的含义,可提供超越简单关键词匹配的智能搜索结果。 ### 启用语义搜索 首先,安装 `docmd-search` 包: ```bash npm install docmd-search ``` 然后在配置中启用它: ```json { "plugins": { "search": { "semantic": true } } } ``` ### 语义搜索工作原理 与只匹配精确词语的关键词搜索不同,语义搜索能够: * **理解上下文** — 搜索"身份验证"可以找到使用"登录"或"注册"等不同表述的相关页面 * **自然处理拼写错误** — 无需模糊匹配逻辑,模型能理解用户意图 * **发现相关概念** — 搜索"API"会返回相关的接口文档,而不仅仅是包含"API"字样的页面 ### 配置选项 | 选项 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | `semantic` | `boolean` | `false` | 启用语义搜索(需要安装 `docmd-search` 包) | | `showConfidence` | `boolean` | `false` | 在语义搜索结果中显示相似度匹配置信度徽章 | | `showFilters` | `boolean` | `true` | 在搜索结果上方显示版本筛选栏(设为 `false` 可隐藏) | | `model` | `string` | `'Xenova/all-MiniLM-L6-v2'` | 使用的嵌入模型 | | `chunkSize` | `number` | `512` | 文本块的最大字符数 | | `chunkOverlap` | `number` | `50` | 文本块之间的重叠字符数 | | `indexDir` | `string` | — | 预构建语义索引的路径 | ### 对比:语义搜索 vs 关键词搜索 | 功能 | 语义搜索 | 关键词搜索 | | :--- | :--- | :--- | | **理解能力** | 上下文感知 | 仅精确匹配 | | **拼写容错** | 强 | 有限(模糊匹配) | | **同义词支持** | 支持 | 不支持 | | **安装要求** | 需要 `docmd-search` | 内置,无需安装 | | **索引体积** | 较大(每 100 个文件约 1-2 MB) | 较小 | | **隐私保护** | 100% 私有(客户端) | 100% 私有(客户端) | | **离线支持** | 支持 | 支持 | ### 降级机制 如果启用了语义搜索但未安装 `docmd-search`,插件会自动降级到关键词搜索。这确保无论配置如何,你的文档始终可以被搜索。 ::: callout warning "Alpha 版本限制" 语义搜索仍处于实验阶段,目前存在以下限制: * 目前仅支持英语模型(多语言模型可用但测试较少) * 不支持增量更新(需要完整重建索引) * 内存占用较高(浏览器中约 50-100 MB) * 首次加载时可能较慢,因为需要获取嵌入数据 ::: ### 最佳实践 为获得最佳的语义搜索效果: 1. **排除干扰内容** — 不要将更新日志或草稿内容加入索引: ```json { "plugins": { "search": { "semantic": true, "exclude": ["**/release-notes/**", "**/drafts/**"] } } } ``` 2. **为 CI/CD 预构建索引** — 使用 `indexDir` 选项预生成索引: ```bash npx docmd-search --ui ``` 3. **监控索引体积** — 定期检查 `.docmd-search/` 目录的大小 4. **充分测试** — 在部署到生产环境前,验证搜索结果的质量 --- ## [SEO 插件](https://docs.docmd.io/zh/plugins/seo/) --- title: "SEO 插件" description: "通过原生的元标签生成功能,为搜索引擎优化你的文档,并控制 AI 爬虫的访问权限。" --- `@docmd/plugin-seo` 插件负责为每个页面生成高质量的元数据。它确保你的文档不仅能被搜索引擎上的人类读者发现,而且能被 AI 模型和社交媒体平台正确解读。 ## 配置 在 `docmd.config.json` 中配置全站的 SEO 默认设置。页面级设置始终优先于全局默认设置。 | 选项 | 类型 | 默认值 | 说明 | | :--- | :--- | :--- | :--- | | `defaultDescription` | `string` | `null` | 没有 frontmatter 描述的页面的回退描述。 | | `aiBots` | `boolean` | `true` | 允许(`true`)或阻止(`false`)AI 训练爬虫。设为 `false` 时,会阻止 GPTBot、ChatGPT-User、Google-Extended、CCBot 等 AI 爬虫。 | | `openGraph` | `object` | `null` | 用于社交媒体(Facebook、LinkedIn)的 Open Graph 设置。 | | `twitter` | `object` | `null` | Twitter (X) Card 设置,包括用户名和卡片类型。 | ### 示例 ```json { "plugins": { "seo": { "defaultDescription": "docmd 生态系统的全面文档。", "aiBots": false, "twitter": { "siteUsername": "@docmd_io", "cardType": "summary_large_image" } } } } ``` ## 功能 - **自动生成 robots.txt**:如果不存在 `robots.txt`,则自动生成,包含站点地图引用和 AI 爬虫指令。 - **智能描述降级**:如果未提供描述,自动提取正文前 150 个字符作为 `<meta name="description">`。 - **AI 爬虫管理**:默认允许 AI 爬虫索引内容。设置 `aiBots: false` 可阻止 AI 训练爬虫,同时不影响传统搜索引擎。 - **规范化 URL 解析**:自动生成 `<link rel="canonical">` 标签,防止重复内容问题。 - **丰富的社交预览**:原生支持 Open Graph 和 Twitter Cards,确保链接分享时显示专业的预览效果。 - **结构化数据**:支持 LD+JSON Article Schema,有助于在搜索结果中显示富摘要。 ## robots.txt 自动生成 如果输出目录中不存在 `robots.txt`,插件会在构建过程中自动生成该文件。 **生成内容示例:** ```txt User-agent: * Allow: / # Sitemap Sitemap: https://your-domain.com/sitemap.xml ``` **阻止 AI 训练爬虫:** 当设置 `aiBots: false` 时,生成的 `robots.txt` 会包含: ```txt # Block AI training bots User-agent: GPTBot Disallow: / User-agent: ChatGPT-User Disallow: / User-agent: Google-Extended Disallow: / # ...(其他 AI 爬虫) ``` ### robots.txt 位置策略 插件会智能处理多个位置的 `robots.txt`: **优先级顺序:** 1. **站点根目录**(`site/robots.txt`)— 优先检查,优先级最高 2. **Assets 文件夹**(`site/assets/robots.txt`)— 若存在则复制到站点根目录 **处理逻辑:** - 若 `robots.txt` 已存在于**站点根目录**:保留原文件,不做任何修改 - 若 `robots.txt` 存在于 **assets 文件夹**:自动复制到站点根目录(推荐的 SEO 放置位置) - 若**找不到** `robots.txt`:根据 SEO 配置自动生成 **推荐做法:** 将自定义 `robots.txt` 放在文档源的 `assets/` 文件夹中,插件会在构建时自动将其复制到站点根目录: ``` your-docs/ ├── assets/ │ └── robots.txt ← 放在这里 ├── index.md └── docmd.config.json ``` 构建后,文件会出现在正确位置: ``` site/ ├── robots.txt ← 复制到此处(SEO 标准位置) ├── assets/ │ └── robots.txt ← 原文件也保留 └── index.html ``` ::: callout tip "为什么要放在站点根目录?" 搜索引擎期望 `robots.txt` 位于域名根目录(`https://example.com/robots.txt`)。无论你提供自定义文件还是让插件自动生成,插件都能确保文件始终处于正确位置。 ::: ## 页面级覆盖 使用 frontmatter 为单个页面微调 SEO 设置: ```markdown --- title: "高级配置" noindex: true # 从所有搜索引擎中隐藏此页面 seo: keywords: ["docmd", "javascript", "ssg"] aiBots: true # 覆盖全局阻止设置,允许 AI 访问此页面 ldJson: true # 启用 Article Schema --- ``` ::: callout tip "搜索发现" 为获得最佳效果,请确保在配置根目录中定义了 `url`。没有基准 URL,插件将无法生成绝对规范链接或社交图片路径。 ::: --- ## [Sitemap 插件](https://docs.docmd.io/zh/plugins/sitemap/) --- title: "Sitemap 插件" description: "自动生成符合标准的 sitemap.xml,提升搜索引擎发现效率。" --- `@docmd/plugin-sitemap` 插件在构建目录根目录自动生成 `sitemap.xml` 文件。该文件为 Google、Bing 等搜索引擎提供完整的站点架构地图,确保包括版本化文档中深层链接在内的所有页面都能被爬取和索引。 ## 配置 提供站点的 `url` 即可开启站点地图生成。可在 `plugins` 对象中自定义各章节的爬取权重。 ```json { "url": "https://docs.example.com", "plugins": { "sitemap": { "defaultChangefreq": "weekly", "defaultPriority": 0.8, "rootPriority": 1.0 } } } ``` ## 页面级控制 可使用 frontmatter 覆盖特定页面的站点地图行为。 ```yaml --- title: "归档页面" priority: 0.3 # 旧版内容的较低权重 changefreq: "monthly" # 提示爬虫此页面变更频率较低 lastmod: "2024-03-15" # 明确设置最后修改日期 sitemap: false # 将此页面从 sitemap.xml 中排除 --- ``` ## 核心功能 ### 1. 自动 URL 构建 插件智能地将页面路径解析为规范的公开 URL。它自动处理目录索引,确保 `guide/index.html` 列为 `https://yoursite.com/guide/`,以维护简洁的 URL 结构。 ### 2. 版本化发现 如果你的项目使用[版本控制](../configuration/versioning),站点地图插件会自动включать所有版本的所有页面(如 `/v1/getting-started`、`/v2/getting-started`),无需手动配置即可让搜索引擎发现你的归档文档。 ### 3. 智能排除 在 frontmatter 中标记 `noindex: true` 或 `sitemap: false` 的页面会自动从生成的 `sitemap.xml` 中排除,让你精细控制呈现给搜索引擎的内容。 ::: callout tip "验证" 构建站点后,通常可在 `your-output-dir/sitemap.xml` 找到站点地图。大多数搜索引擎控制台允许你直接提交此文件以加速索引。 ::: --- ## [评论线程插件](https://docs.docmd.io/zh/plugins/threads/) --- title: "评论线程插件" description: "为你的文档添加行内讨论线程——直接存储在你的 markdown 文件中。" --- **Threads 插件**为你的文档带来协作式的行内评论功能。选择页面上的任何文本,留下评论,开始讨论——所有内容都直接存储在你的 markdown 源文件中,无需任何数据库。 原作者:[@svallory](external:https://github.com/svallory) ::: callout info "Alpha 版本" 此插件处于 alpha 阶段。API 和存储格式是稳定的,但 UI 仍处于活跃开发中。 ::: ## 安装设置 ```bash npx @docmd/core add threads ``` 在 `docmd.config.json` 中启用: ```json { "plugins": { "threads": {} } } ``` ### 配置选项 | 选项 | 类型 | 默认值 | 描述 | | :--- | :--- | :--- | :--- | | `sidebar` | `boolean` | `false` | 当为 `true` 时,线程会分组在页面底部。当为 `false`(默认)时,线程会定位在所选文本旁边的行内位置。 | ```json { "plugins": { "threads": { "sidebar": true } } } ``` ## 工作原理 1. 在 `npx @docmd/core dev` 期间,在任何文档页面上**选择文本** 2. 出现一个**评论弹出层**——写下你的评论并提交 3. 所选文本会被**高亮显示**并带有线程标记 4. 线程以 `::: threads` 块的形式存储在 markdown 文件的底部 5. **无需数据库**——你的 markdown 文件就是事实来源 ## 技术实现 * **无数据库**:所有评论都作为 YAML frontmatter 存储在源 `.md` 文件中 * **Git 友好**:线程是纯文本,可以进行版本控制、合并和审查 * **零配置**:开箱即用,无需外部服务或 API 密钥 * **隐私优先**:所有数据保留在你的仓库中 ::: callout tip "协作工作流" Threads 插件非常适合技术写作团队。审阅者可以直接在文档中留下反馈,作者可以在提交前解决评论——所有内容都在同一个 Git 工作流中。 ::: --- ## [使用插件](https://docs.docmd.io/zh/plugins/usage/) --- title: "使用插件" description: "安装、配置和管理 docmd 插件 - 从必需的默认插件到可选的附加组件。" --- docmd 具有模块化插件架构。必需的插件随核心一起发布,无需安装。可选插件可以通过单一 CLI 命令安装。 ## 安装插件 使用 docmd CLI 安装和移除插件: ```bash # 安装插件 npx @docmd/core add <plugin-name> # 移除插件 npx @docmd/core remove <plugin-name> ``` 安装程序检测你的包管理器(npm、pnpm、yarn 或 bun)。它将短名称解析为完整的包名称,并将配置注入到你的 `docmd.config.json` 中。 使用 `--verbose`(或 `-V`)获取完整的安装程序输出: ```bash npx @docmd/core add <plugin-name> -V ``` ## 必需插件 这些插件与 `@docmd/core` 一起打包。无需安装。在你的 `docmd.config.json` 中启用它们: ```json { "plugins": { "search": {}, "seo": { "aiBots": false }, "sitemap": {}, "analytics": {}, "llms": {}, "mermaid": {}, "openapi": {}, "git": {} } } ``` ::: callout tip "Git 插件" Git 插件检测你的项目是否是 Git 仓库。如果不是,它会自动禁用自己。无需配置即可获取最后更新时间戳。 ::: ## 可选插件 可选插件需要在启用之前安装。 | 插件 | 安装命令 | 描述 | | :--- | :--- | :--- | | [PWA](pwa.md) | `npx @docmd/core add pwa` | 具有离线缓存的渐进式 Web 应用支持 | | [Threads](threads.md) | `npx @docmd/core add threads` | 存储在 Markdown 中的行内讨论评论 | | [Math](math.md) | `npx @docmd/core add math` | 原生 KaTeX 和 LaTeX 数学渲染 | `docmd` 采用可插拔架构。几乎所有核心功能(从搜索到 SEO 再到实时预览)都是作为插件实现的。这种设计确保了引擎保持轻量,同时允许开发者根据具体项目需求选择性地开启功能。 ## 插件概览 | 插件 | 功能 | | :--- | :--- | | **[搜索 (Search)](search.md)** | 提供高性能、离线优先的全文本搜索。 | | **[SEO](seo.md)** | 自动生成元标签、Sitemap 并控制 AI 爬虫访问。 | | **[Mermaid](mermaid.md)** | 渲染流程图、序列图和甘特图。 | | **[LLMs](llms.md)** | 生成机器可读的全量文档流以供 AI 训练或搜索。 | | **[实时预览 (Live)](../content/live-preview.md)** | 为自定义编辑器提供在浏览器中运行的渲染引擎。 | ## 生命周期钩子 插件可以通过连接到以下生命周期钩子来介入构建过程: | 钩子 | 描述 | | :--- | :--- | | `onInit(ctx)` | 在引擎启动且配置加载后立即运行 | | `onPostBuild(ctx)` | 在所有 HTML 文件生成后运行逻辑 | | `translations(localeId)` | 返回语言环境翻译后的 UI 字符串 | | `actions` | 可从浏览器通过 WebSocket RPC 调用的服务器端处理程序 | | `events` | 浏览器推送事件的“发后即忘”式处理程序 | ## 插件安全 插件系统提供内置的安全保证: - **验证**: 插件可以声明一个包含 `name`、`version` 和 `capabilities` 的插件描述符。无效的描述符在加载时会被拒绝。 - **隔离**: 每次钩子调用都包裹在 try/catch 边界内。一个损坏的插件不会导致构建崩溃或影响其他插件。 - **能力强制**: 声明了能力的插件只能注册其已明确声明的钩子。未声明的钩子将被跳过并发出警告。 有关完整的 API 参考,请参阅 [开发插件](building-plugins.md)。 ::: callout tip "针对 AI 的透明架构 :robot:" 插件架构旨在具有 **确定性**。插件注入的每个元标签和脚本都是可追溯的,这允许 AI 代理(和人类开发人员)准确了解网站的行为,而不会产生隐藏的副作用。 ::: --- ## [发行说明 - 0.8.0](https://docs.docmd.io/zh/release-notes/0-8-0/) --- title: "发行说明 - 0.8.0" description: "高性能多线程架构、通用 Worker 插件 API 以及大幅度的性能提升。" --- `docmd` 0.8.0 版本带来了一次具有里程碑意义的架构升级——引入了原生的多线程 Worker 池,支持并行处理页面,极大地缩短了大型文档网站的构建时间,并推出了强大的全新插件 Worker API。 ## ✨ 亮点功能 ### ⚡ 多线程构建架构 docmd 现在通过高度优化的 `WorkerPool` 并行构建您的文档。通过将构建流水线中最繁重的部分(Markdown AST 解析和处理器钩子)移至独立的后台线程中,docmd 现在可以充分利用所有可用的 CPU 核心。 对于大型工作区(例如拥有超过 1000 个页面的项目),这将带来**巨大的性能提升**,大幅缩短冷启动构建时间,并使热重载(hot-reload)开发体验变得更加流畅。系统会智能地限制线程池的规模(即 `os.cpus().length - 1`),以确保您的主系统在繁重的构建过程中依然保持响应。 ### 🔌 插件 Worker API 我们不仅让 docmd 支持多线程,还让整个生态系统都能轻松利用它。 插件现在可以将自身繁重的计算任务或同步操作交由 docmd 的 Worker 池处理,而无需自行管理线程的创建与生命周期。我们在 `ActionContext`、`PageContext` 以及 `PostBuildContext` 中注入了一个全新的 `runWorkerTask` API。 ```javascript export default { plugin: { name: 'my-plugin', version: '1.0.0', capabilities: ['post-build'] }, async onPostBuild(ctx) { // 将重型操作(如解析 Git 历史记录)发送到后台线程处理 const result = await ctx.runWorkerTask( '/absolute/path/to/my-worker-script.js', 'parseGitHistory', [ctx.outputDir] ); } } ``` ### 🧩 共享模块化核心 我们正式提取了一个新的底层包 `@docmd/utils`,这是一个零依赖的共享实用工具库。该包集中了文件系统封装、路径规范化、哈希生成机制以及核心的 `WorkerPool`,从而避免了循环依赖,并允许插件直接从 docmd 生态系统中引入可靠的实用工具。 ## 📝 完整更新日志 ### 🚀 引擎与架构 - **Worker-Parser 流水线**:核心 Markdown 处理器现在在后台线程中动态重构。文件被并发读取,并分批交由 Worker 处理。 - **AST 缓存引擎**:引入了基于 MD5 的缓存层来拦截未修改的文件。如果文件的原始内容哈希值与上次构建相比没有改变,将直接跳过 AST 解析。 - **持久化开发 Worker**:在运行 `npx @docmd/core dev` 期间,Worker 池会在文件保存时保持持久化运行。这消除了 Node.js Worker 常见的 200-500 毫秒线程启动延迟,实现了近乎瞬时的增量重建。 - **Worker CPU 节流**:线程池会根据系统架构精确计算线程数量,并保留一个 CPU 核心,以防止 I/O 饥饿和操作系统卡顿。 ### 🔌 插件系统 - **`runWorkerTask` API**:直接在插件上下文(`onBeforeRender`、`onPostBuild`、`actions`、`events`)中公开,用于在后台执行通用脚本。 - **Git 插件持久化缓存**:Git 插件现在利用了强大的持久化磁盘缓存 (`.docmd/cache/git-history.json`),并通过文件修改时间 (`mtimeMs`) 进行失效验证。这完全消除了在后续构建中多余的 `git log` shell 子进程,将大型仓库(800+ 页面)的构建时间从约 18 秒缩短至仅约 3.5 秒。 - **解耦的 API 导入**:插件现在可以直接从 `@docmd/utils` 导入 `fsUtils`、`WorkerPool` 和 `getGitRoot`。 ### ⚙️ 基础设施与工具 - **集中式的 Git 上下文**:内部的 Git 分支检测和仓库根目录解析(`getGitRoot`)已被提取到安全的工具边界内。 - **JSON 可序列化配置**:通过确保解析后的配置对象完全可转换为 JSON 格式,进一步向零配置架构过渡,使其能够安全地传输到 Worker 线程中。 ## ⚠️ 破坏性变更 - **核心模块导入**:如果您的自定义插件之前依赖于 `@docmd/core/src/utils/fs-utils` 等深层相对路径导入,您必须将这些导入更新为 `@docmd/utils`。 - **Worker 执行上下文**:挂载在 `markdownSetup` 中的插件必须确保其扩展是完全可序列化的,因为 markdown-it 处理器现在跨线程边界实例化。 ## 升级指南 运行 `npm install docmd@latest` 进行升级,然后: 1. **测试您的自定义插件**:如果您维护了一个操作 AST 或需要大量 CPU 时间的自定义 docmd 插件,请尝试使用全新的 `runWorkerTask`,这能让构建循环保持极速。 2. **移除手动核心导入**:将 `import { fsUtils } from '@docmd/core/dist/utils/fs-utils'` 替换为 `import { fsUtils } from '@docmd/utils'`。 获取完整演练,请参阅[快速入门 - 安装](../getting-started/installation)。 --- ## [docmd v0.8.1 - 引擎架构与 Git 缓存修复](https://docs.docmd.io/zh/release-notes/0-8-1/) --- title: "docmd v0.8.1 - 引擎架构与 Git 缓存修复" description: "可插拔引擎架构(预览)、持久化 Git 索引、导航修复和 JSON 配置标准化。" --- ::: callout danger **此版本已弃用。** v0.8.1 包含一个打包缺陷,会导致 `npm install` 以 `EUNSUPPORTEDPROTOCOL` 错误失败。所有更改和修复已合并到 [v0.8.2](./0-8-2.md)。请立即升级。 ::: docmd v0.8.1 引入了可插拔引擎架构、对 Git 索引性能的重大改进,以及 SPA 导航的重要修复。 ## ✨ 亮点 ### 可插拔引擎架构(预览) docmd 现在支持可插拔引擎系统。新的 `@docmd/engine-rust` 包为加速 I/O 操作提供了基础,设计为可轻松与现有插件配合使用。 ```json { "engine": "rust" } ``` 引擎是**可选的**——默认的 JavaScript 引擎处理所有工作负载。Rust 引擎为大型仓库(1000+ 文件)提供可测量的增益,其中 Git 索引和批量文件操作主导构建时间。 **架构亮点:** - **可插拔设计**:引擎是 `@docmd/engine-*` 下的包,遵循与插件相同的模式 - **捆绑预构建二进制文件**:所有支持的平台二进制文件现在通过单一集中的 `@docmd/engine-rust-binaries` 包分发 - **延迟加载**:原生二进制文件仅在明确选择引擎时加载 - **插件兼容**:插件可以使用引擎 API 进行加速 I/O - **自动降级**:如果原生二进制文件不可用,JS 引擎会透明地接管 **可用引擎包:** | 包 | 描述 | |---------|-------------| | `@docmd/engine-js` | 默认 JavaScript 引擎(始终可用) | | `@docmd/engine-rust` | Rust 引擎加载器(编排原生加速) | | `@docmd/engine-rust-binaries` | 所有平台的集中原生二进制分发 | ::: callout info "预览状态和平台支持" Rust 引擎处于预览阶段。在最初的 **v0.8.1 发布**中,预编译的原生二进制文件仅在二进制包中为 **macOS ARM64(Apple Silicon)** 平台发布。在其他架构上执行的构建会自动且透明地降级到高性能 JS 引擎。内部基准测试显示,在 886 页工作区站点上,**冷构建改善约 25%**,**热构建改善约 17%**。 ::: ### Git 索引:持久磁盘缓存 Git 插件现在**将索引结果持久化到磁盘**,跨构建保留。以前,即使没有文件发生变化,Git 元数据也会在每次构建时从头重新索引。新的缓存系统: - 将缓存存储干净地路由到操作系统的隔离临时目录(`os.tmpdir()`),防止顶级目录混乱。 - 通过生成锚定到仓库 Git 跟踪 URL 或唯一操作系统 inode 标识符的可靠哈希,在目录重命名或移动时安全地持久检索缓存。 - 通过新的 `tmp` 配置参数支持可配置的存储路径。 - 适用于**两种**引擎路径(Rust 和 JS)以及 `execFile` 降级。 - 在官方文档站点(886 页)上提供**约 45% 更快的热构建**。 ### 可配置的 `tmp` 目录 默认情况下,docmd 现在将内部状态和构建缓存路由到系统的隔离临时文件夹,以保持项目根目录整洁。对于需要在特定位置进行持久缓存的环境(例如,具有缓存键要求的 CI/CD 流水线),你现在可以使用新的 `tmp` 键配置完整存储路径: ```json { "src": ".", "out": "site", "tmp": ".docmd-cache" } ``` 这允许你将 `.docmd/` 状态文件夹锚定到任何目录,确保它可以在构建会话之间轻松缓存和恢复。 ### JSON 配置标准 从 v0.8.0 开始,`docmd.config.json` 是推荐的配置格式。所有 v0.8 文档已更新为使用 JSON 示例。对于动态配置逻辑,`.js` 和 `.ts` 格式仍然完全支持作为降级选项。 ## 🐛 Bug 修复 ### SPA 导航中的外部链接 修复了一个问题:在通过 SPA 路由器导航到另一个内部页面后,`navigation.json` 中定义了 `external: true` 的外部链接被错误地解析为相对路径。链接现在在客户端导航期间正确保留其绝对 URL。 ### 导航外部链接简写 `external:` 前缀以前只在 Markdown 内容中可用,现在在 `navigation.json` 中也作为方便的简写支持: ```json [ { "title": "GitHub", "path": "external:https://github.com/docmd-io/docmd" } ] ``` 这等同于: ```json [ { "title": "GitHub", "path": "https://github.com/docmd-io/docmd", "external": true } ] ``` ### Git 缓存目录稳定性和重新定位 修复了一个 bug:在工作区构建期间,Git 插件的磁盘缓存被写入到不断变化的目录。缓存已使用持久仓库标识符从项目根目录直接干净地重新定位到 `os.tmpdir()`,完全支持自定义 `tmp` 覆盖路径参数。 ### 引擎配置被遵守 Git 插件现在遵守 `engine` 配置键。以前,无论配置如何,它总是首先尝试加载 Rust 引擎。设置 `"engine": "js"` 现在可以正确强制使用 JavaScript 引擎。 ## 📝 完整更新日志 ### 🚀 引擎和架构 - **可插拔引擎系统**:`@docmd/api` 中用于构建加速的新 `Engine` 接口 - **JS 引擎包**:默认引擎提取到 `@docmd/engine-js` - **Rust 引擎生态**:通过 `@docmd/engine-rust-binaries` 集中分发二进制的原生 Rust 加速 - **引擎加载器 API**:用于自定义引擎注册的 `loadEngine()` 和 `registerEngine()` - **引擎配置键**:`docmd.config.json` 中用于选择构建引擎的新 `engine` 键 - **引擎显著性**:在 TUI 布局内提升了自定义构建引擎的顶级日志显著性 ### ⚡ 性能 - **Git 磁盘缓存**:引擎路径结果现在持久化到磁盘用于热构建 - **持久标识**:使用 Git 远程 URL 哈希和操作系统 inode 降级的双模式缓存标识 - **可配置存储**:添加了通过 `tmp` 配置参数覆盖缓存目标的支持 - **配置解析器**:在工作区子项目循环中添加了对标准 JSON 配置文件的无缝检测支持 - **磁盘缓存预热**:构建流水线在引擎/子进程调用之前读取磁盘缓存 ### 🐛 Bug 修复 - **SPA 路由器**:侧边栏导航中的外部链接现在在客户端导航期间正确保留 - **导航配置**:`external:` 前缀现在在 `navigation.json` 中支持作为简写 - **链接解析**:修复了协议相对 URL 的 URL 解析边缘情况 - **Git 插件**:现在遵守 `engine` 配置键,而不是总是默认使用 Rust - **工作区缓存**:将状态存储重新定位到确定性临时操作系统结构,以防止循环边界之间的丢失 --- ## [docmd v0.8.2 - 补丁版本](https://docs.docmd.io/zh/release-notes/0-8-2/) --- title: "docmd v0.8.2 - 补丁版本" description: "修复了依赖协议错误并更新了发布自动化。" --- 这是一个关键补丁版本,解决了使用 `npm` 的用户的安装问题,并标准化了 monorepo 的内部依赖解析。 ### 🚀 亮点 #### 修复 `npm install` 兼容性 解决了一个关键问题:发布到 NPM 注册表的包在其 `optionalDependencies` 中包含未解析的 `workspace:` 协议引用。这导致 `npm install` 以 `EUNSUPPORTEDPROTOCOL` 错误失败。发布流水线已更新,以确保所有依赖类型在发布时正确解析为 semver 范围。 ### 🛠 改进和修复 - **发布流水线**:修复了 `scripts/resolve-ws-deps.js`,以在发布过程中正确转换 `optionalDependencies`。 - **依赖标准化**:更新了所有内部包引用,以确保整个生态系统的一致性。 - **工作流优化**:更新了 GitHub Actions 以使用稳定的运行器配置,以实现可靠的二进制生成。 ### 📦 包更新 `@docmd` 生态系统中的所有包都已升级到 `v0.8.2`,以确保完全兼容性和锁步版本控制。 有关 v0.8 系列中引入的架构变更的完整列表,请参阅 [v0.8.1 发布说明](./0-8-1.md)。 --- ## [docmd v0.8.3 - 工作区与增强安全性](https://docs.docmd.io/zh/release-notes/0-8-3/) --- title: "docmd v0.8.3 - 工作区与增强安全性" description: "引入了具有配置级联的新工作区架构、高级项目切换器,以及重大的安全加固。" --- docmd v0.8.3 是一个重大架构更新,引入了**工作区**,支持从单个根配置集中管理多个文档项目。此版本还优先考虑**安全性和稳定性**,在整个生态系统中加固了渲染,并提高了路由可靠性。 ### ✨ 亮点 #### 🚀 工作区架构 多项目系统已完全重新设计为**工作区**。你现在可以从单个根配置管理多个独立的文档项目,具有强大的新功能: - **全局配置级联**:在根目录定义 `theme`、`menubar`、`navigation` 和 `logo`,自动应用于所有项目。 - **高级项目切换器**:一个新的纤细 UI 组件,用于在项目之间无缝导航,支持多个位置(`sidebar-top`、`sidebar-bottom` 和 `options-menu`)。 - **灵活覆盖**:项目可以在其本地配置中有选择地覆盖全局默认值。 - **向后兼容**:现有的多项目配置会自动规范化到新的工作区架构。 #### 🛡️ 增强的安全性和稳定性 此版本引入了一系列内部改进,以加固文档引擎及其插件,防止边缘情况下的渲染问题: - **加固渲染**:系统地将核心和插件中的 `innerHTML` 使用替换为安全的 DOM API(`createElement`、`DOMParser`)。 - **通用安全审计**:monorepo 故障保护流水线现在包括一个专门的、基于 AST 的安全审计,以在任何发布之前检测和阻止不安全的 DOM 模式(`innerHTML`、`outerHTML`、`document.write`)。 - **改进的搜索安全性**:搜索结果现在使用更可靠的渲染流水线,以确保内容始终被安全处理。 - **开发服务器隔离**:增强了本地开发服务器中的目录遍历保护,以改善环境隔离。 ### 🛠 改进和修复 #### 自动指定索引规范化 修复了零配置自动路由器中的一个 bug:当没有 `index.md` 时,被指定为目录索引的文件由于尾部斜杠不匹配而无法正确渲染。引擎现在正确规范化这些路径,确保所有自动索引目录的稳定路由和正确的 `index.html` 生成。 #### 路由稳定性 改进了自动路由器中的路径可预测性,以解决没有专用索引文件的目录中尾部斜杠不一致的问题。 #### TUI 流水线和工作区构建清晰度 改进了多项目工作区构建的终端输出(TUI)。构建日志现在在独立构建和工作区构建中都一致地结构化为严格的部分(`Data Indexing`、`Publishing` 等),防止文本重叠、循环加载动画和断开的状态消息。 #### UI 侧边栏调整 修复了一个布局 bug:侧边栏内的下拉菜单(版本、语言和项目切换器)会被侧边栏的边界框裁剪。这些菜单现在安全地在主内容区域上方渲染,并动态对齐到侧边栏宽度,防止它们溢出浏览器视口。 ### 📦 包更新 - **Node.js 类型**:将 `@types/node` 更新到 `v25.8.0`。 - **GitHub Actions**:将 CI/CD 工作流更新到最新稳定版本,以提高可靠性。 ### 📝 完整更新日志 #### 🚀 新功能 - **核心引擎**:引入了用于集中项目管理的 `workspace` 架构。 - **UI 组件**:添加了 `project-switcher` 局部模板和事件委托逻辑。 - **配置加载器**:实现了全局默认合并和 `menubar` 项目别名(`title`/`path`)。 - **流水线**:将静态分析安全审计集成到通用故障保护 V5.0 中,以在所有包中强制执行严格的 DOM 安全标准。 #### 🐛 Bug 修复 - **Threads 插件**:通过移至 DOMParser,加固了评论渲染和元数据转义。 - **搜索插件**:改进了结果渲染和数据属性安全性,替换了 innerHTML。 - **图标渲染器**:加固了 SVG 图标的图标属性渲染。 - **标签页组件**:改进了标签导航项中的属性安全性。 - **核心引擎**:修复了生成器中自动指定索引文件的路径规范化。 - **路由**:从自动路由器中删除了隐式索引指定,以提高路径可预测性。 - **开发服务器**:增强了静态文件服务的路径验证。 - **UI 资源**:从侧边栏中删除了 `overflow: hidden`,并重构了定位上下文以防止下拉菜单被裁剪。 - **CLI / TUI**:修复了工作区和开发构建期间悬挂的状态消息和未关闭的 UI 部分。 #### 🚀 基础设施 - **重构**:将工作区引擎重命名为 `workspace.ts`,并在整个 monorepo 中重构了术语。 - **依赖**:将 `@types/node` 从 25.7.0 升级到 25.8.0。 - **工作流**:将 GitHub Actions 组更新到最新版本。 --- ## [v0.8.4 - 部署器与安全性](https://docs.docmd.io/zh/release-notes/0-8-4/) --- title: "v0.8.4 - 部署器与安全性" description: "docmd v0.8.4 发布说明——模块化部署器包、Markdown 换行控制、安全加固和稳定性修复。" date: "2026-05-18" --- ### ✨ 亮点 此版本引入了新的 Deployer V2 系统,以及对插件安全性、构建可靠性和开发工作流的改进。 ### 部署目标 部署引擎已提取到专用的 `@docmd/deployer` 包中,提供基于提供商的部署目标。 你现在可以直接为 GitHub Pages、Vercel 和 Netlify 生成部署文件: ```bash npx @docmd/core deploy --github-pages npx @docmd/core deploy --vercel npx @docmd/core deploy --netlify ``` 生成的文件自动从你的 `docmd.config.json` 继承值,包括输出目录、站点 URL、SPA 路由和 Node.js 版本。 Docker、Nginx 和 Caddy 的现有部署目标继续正常工作。 ### Markdown 换行 `docmd.config.json` 中添加了新的 `markdown.breaks` 选项。 将其设置为 `false` 可禁用自动 Markdown 换行,并保留换行的 Markdown 格式。 ```json { "markdown": { "breaks": false } } ``` ### 更新日志 1. **部署器**:将部署引擎提取到 `@docmd/deployer`,原生支持 GitHub Pages、Vercel 和 Netlify 目标。 2. **Markdown 格式化**:添加了 `markdown.breaks` 配置选项,用于控制自动软换行(#137、#127)。 3. **安装器安全性**:将插件安装限制为官方 npm 注册表,并替换了不安全的基于 shell 的执行路径。 4. **Threads 插件**:在保留标准 Markdown 格式的同时,禁用了线程评论内的原始 HTML 渲染(#136)。 5. **构建可靠性**:解析器和构建生命周期现在在插件失败时以非零状态码退出,改善了 CI 流水线行为(#134)。 6. **开发者体验**:减少了热重载期间的开发服务器噪音,并向解析器生命周期钩子添加了 `filePath` 参数(#135)。 7. **UI 更新**:用 Lucide 图标优化了版本切换器,并将项目切换器下拉样式与标准主题菜单对齐。 8. **Bug 修复**:修复了项目切换缓存重叠、`noStyle` 页面上的翻译获取问题和复制代码图标悬停状态。 ### 致谢 💖 感谢所有帮助改进此版本的贡献者、测试人员和问题报告者。特别感谢安全研究人员进行负责任的披露协调。 文档:https://docs.docmd.io/ GitHub:https://github.com/docmd-io/docmd --- ## [v0.8.5 - 语义搜索 Alpha 预览与 SEO 增强](https://docs.docmd.io/zh/release-notes/0-8-5/) --- title: "v0.8.5 - 语义搜索 Alpha 预览与 SEO 增强" description: "docmd v0.8.5 发布说明 - 语义搜索 Alpha 预览、SEO 插件 robots.txt 自动生成、Mermaid C4Context 修复以及配置升级 CLI。" date: "2026-05-31" --- ### ✨ 亮点 本次发布引入了语义搜索 Alpha 预览功能、SEO 插件自动 `robots.txt` 生成、修复 Mermaid C4Context 图表渲染问题,并新增了用于无缝迁移的配置升级命令。 ### 语义搜索(Alpha 预览) docmd 现在支持基于本地向量嵌入的语义搜索,能够提供超越简单关键词匹配的上下文感知搜索结果。 **核心特性:** * **上下文理解** — 超越精确关键词匹配的上下文感知搜索 * **自然拼写容错** — 轻松处理拼写错误 * **发现相关内容** — 即使使用不同术语也能找到相关内容 * **完全本地处理** — 无需外部服务或 API 调用 通过安装 `docmd-search` 并在配置中添加 `semantic: true` 来启用语义搜索: ```bash npm install docmd-search ``` ```json { "plugins": { "search": { "semantic": true } } } ``` 如果未安装 `docmd-search`,插件会自动降级到关键词搜索,确保文档始终可被搜索。 **注意:** 此功能为 Alpha 预览版。目前仅提供英语模型,多语言支持计划在未来版本中推出。 ## 介绍离线语义搜索引擎(docmd-search) 我们很高兴介绍 **docmd-search**。 ```bash npm install docmd-search ``` docmd-search 是专为文档站点打造的语义搜索引擎。它完全在浏览器或 CLI 中运行,无需服务器或 API 密钥,所有处理都在本地完成。 虽然为 docmd 开发,但它也可以集成到其他文档平台、网站和 Web 应用中。 这是早期 Alpha 版本,会继续迭代,但基础架构已经完备。 **GitHub:** https://github.com/docmd-io/docmd-search **文档:** https://docs.docmd.io/search/ ### SEO 插件:robots.txt 自动生成 SEO 插件现在会在构建过程中自动生成 `robots.txt` 文件(前提是该文件不存在)。 **功能特性:** * **智能默认值** — 默认包含 `User-agent: *` 和 `Allow: /` * **站点地图引用** — 设置 `config.url` 后自动添加站点地图 URL * **可选的 AI 爬虫控制** * **非破坏性** — 已存在的 `robots.txt` 文件不会被覆盖 ```json { "plugins": { "seo": { "aiBots": false } } } ``` 默认情况下允许 AI 爬虫。设置 `aiBots: false` 会为 GPTBot、ChatGPT-User、Google-Extended、CCBot 等支持的 AI 爬虫添加指令。 ### Mermaid C4Context 修复 C4Context 图表现在能够正确渲染,不再显示为空白白框。 该问题是由 Mermaid 渲染 C4Context 图表时缺少 SVG 命名空间引起的。docmd 现在会在解析前自动注入所需的命名空间,确保这些图表能够正确渲染。 感谢 @sinsombat 提供的修复和配套测试套件。 ### 配置升级命令 `docmd migrate` 命令新增了 `--upgrade` 标志。运行该命令可自动将配置文件就地重写为现代格式。 ```bash npx @docmd/core migrate --upgrade ``` 升级会自动处理以下遗留键映射: | 遗留键 | 现代键 | | :--- | :--- | | `projects`(顶级) | `workspace.projects` | | `siteTitle` | `title` | | `siteUrl` / `baseUrl` | `url` | | `srcDir` / `source` | `src` | | `outputDir` | `out` | | `defaultLocale` | `i18n.default` | 原始文件会就地重写。由于迁移是非破坏性的(只重命名键,不修改值),因此不需要备份。 ### TOC HTML 实体解码 包含特殊字符(如 `<`、`>`、`&` 或弯引号)的标题文本,现在能在目录侧边栏中正确解码显示。此前,包含这些字符的标题会显示原始 HTML 实体(如 `&`)而非正确字符。 ### 更新日志 **新功能:** 1. 新增基于 `docmd-search` 的语义搜索 Alpha 预览支持。 2. SEO 插件新增自动 `robots.txt` 生成功能。 3. 新增 `search.showFilters`,用于隐藏搜索结果上方的版本筛选栏。 4. 新增 `search.showConfidence`,用于显示语义搜索置信度百分比。 5. 新增右侧对齐的搜索结果元数据,显示版本和置信度徽章。 **缺陷修复:** 1. 修复 Mermaid C4Context 图表渲染为空白白框的问题。 2. 修复因 `workspace` 变量在初始化前被访问而导致的实时编辑器模板渲染崩溃。 3. 修复目录中的 HTML 实体解码问题。 4. 修复 macOS 上因重复 `fs.watch` 事件导致的过度开发服务器重载问题。 **改进:** 1. 新增 `docmd migrate --upgrade`,实现配置自动现代化。 2. 重新设计项目切换器样式,与国际化(i18n)和外观按钮保持视觉一致。 3. 配置和 `navigation.json` 的更改现在会触发快速定向重建,而非完全重启。 4. 开发服务器现已在启动时自动在默认浏览器中打开文档 URL。 ### 感谢 💖 感谢所有贡献者、测试人员和问题报告者帮助改进本次发布。 文档:https://docs.docmd.io/ GitHub:https://github.com/docmd-io/docmd --- ## [v0.8.6 - AI-First 集成、MCP 与 Docker](https://docs.docmd.io/zh/release-notes/0-8-6/) --- title: "v0.8.6 - AI-First 集成、MCP 与 Docker" description: "docmd v0.8.6 版本说明 - 原生 MCP 服务端、模块化 Agent 技能集、官方 Docker 镜像、CJK 分词修复、复制上下文组件及 TOC 优化。" date: "2026-06-05" --- ### ✨ 亮点 此版本正式确立了 docmd 作为领先的 "AI-First"(AI 优先)文档引擎的地位。核心升级是一个**原生 Model Context Protocol (MCP) 服务端**,使 AI Agent 能够通过 `docmd mcp` 与文档工作区交互。此外,此版本还提供了一个**模块化 Agent 技能集**(`docmd-skills`)、**官方 Docker 镜像**(支持多架构)、客户端"复制 Markdown"和"复制上下文"组件、CJK 及无空格语言的搜索分词引擎重构,以及对目录(TOC)布局的关键优化。 ### 🔌 原生 Model Context Protocol (MCP) 服务端 您现在可以直接在工作区中启动原生的 MCP 服务端: ```bash docmd mcp ``` 该服务端运行于本地 `stdio` 模式(协议版本 `2025-03-26`),允许 AI 开发 Agent(如 Claude Desktop、Cursor 或 Windsurf)安全地连接您的文档工作区: - 执行全文及语义文档搜索(`search_docs`) - 读取 Markdown 文件和配置信息(`read_doc`) - 执行超链接与相对路径校验(`validate_docs`) - 获取统一的仓库上下文(`get_llms_context`) 完整的协议合规性,包括 `ping` 健康检查和 `notifications/initialized` 生命周期。 ### 📖 模块化 Agent 技能集(`docmd-skills`) 在运行 `docmd init` 时,会在项目根目录生成一个版本化的 `SKILL.md` 文件。完整的技能集作为模块化集合维护在 [`docmd-skills`](https://github.com/docmd-io/docmd-skills) 仓库中: - **`cli.md`**:安装、所有 CLI 命令及其选项和标志。 - **`config.md`**:完整的 `docmd.config.json` Schema,包含默认值和内联注释。 - **`plugins.md`**:每个内置插件的所有配置键、默认值和行为说明。 - **`plugin-development.md`**:Hook 签名、生命周期、ActionContext、自定义插件创建指南。 - **`formatting.md`**:容器语法、Frontmatter 参考、自闭合规则。 - **`api.md`**:Node.js 构建 API、浏览器 API、MCP 服务端、URL 工具函数、客户端事件。 - **`validation.md`**:链接检查和 CI/CD 集成。 所有技能文件均包含解释默认值的内联注释、完整文档的参考链接以及 `llms-full.txt` 可发现性指南。 ### 🐳 官方 Docker 镜像 docmd 现已提供官方 Docker 镜像,支持多架构(`linux/amd64` 和 `linux/arm64`): ```bash docker pull ghcr.io/docmd-io/docmd:latest docker run -p 3000:3000 ghcr.io/docmd-io/docmd:latest docker run -v $(pwd)/docs:/docs -v $(pwd)/site:/site ghcr.io/docmd-io/docmd:latest build ``` 包括 Docker Compose 和 Kubernetes 部署示例、非 root 安全运行、Alpine Linux 基础镜像、健康检查及 GitHub Actions CI/CD 集成。 ### 🧠 AI-First 上下文提取组件 为了使 AI 助手能够无缝摄取文档内容,我们在页面面包屑导航旁引入了两个全新的本地化按钮: - **复制 Markdown**:复制清理后的文档正文,自动剥离 YAML 前言元数据。 - **复制上下文**:复制结构化的上下文信息,包含页面 URL、标题、标签、版本及全文。 - **本地化支持**:支持所有 7 种主要语言(`en`、`de`、`es`、`fr`、`hi`、`ja`、`zh`)。 ### 🔍 无空格语言搜索分词(中日韩、泰语、老挝语等) 我们解决了 `MiniSearch` 搜索索引在处理词与词之间不使用空格的语言时的局限性。新版本引入了统一的 `CJK_AND_SPACELESS_REGEX` 分词器,对称运行于构建时索引生成器、多线程后台工作线程和客户端浏览器查询解析器。 ### 🔢 docmd-search 0.1.0-alpha.1 此版本集成了 docmd-search 0.1.0-alpha.1,修复了搜索结果置信度百分比可能超过 100% 的关键 bug。 ### 📚 目录(TOC)增强 目录组件获得了显著改进:H1 标题现已正确包含在目录中。TOC 侧边栏支持独立滚动,活跃目录项自动居中,并使用去抖的平滑滚动。 ### 更新日志 1. **MCP**:实现了运行于本地 stdio 的原生 `docmd mcp` 服务端功能。 2. **MCP**:协议更新至 `2025-03-26` — 添加 `ping` 处理器,修复 `notifications/initialized` 生命周期。 3. **MCP**:修复了 `readline` 输出污染导致 JSON-RPC 流损坏的问题。 4. **MCP**:新增专门的 MCP 服务端文档页面。 5. **Skills**:将 Agent 手册模块化为 `docmd-skills/` 目录下的 7 个技能文件。 6. **Skills**:新增 `api.md` 和 `plugin-development.md` 模块。 7. **Skills**:新增 `llms-full.txt` 可发现性指南和 Agent 使用说明。 8. **Docker**:新增官方 Docker 镜像,支持多架构(amd64/arm64)。 9. **Docker**:新增 Docker Compose、Kubernetes 和 GitHub Actions 部署示例。 10. **Docker**:非 root 安全运行、Alpine 基础镜像、健康检查、SBOM 认证。 11. **AI**:新增"复制 Markdown"和"复制上下文"UI 组件,并支持 7 种语言的本地化。 12. **Search**:在 MiniSearch 中为中日韩、泰文、老挝文、高棉文、缅甸文和藏文脚本添加了统一分词器。 13. **TOC**:支持 H1 标题并应用相应的锚点链接和样式。 14. **TOC**:为 TOC 侧边栏实现了独立滚动。 15. **TOC**:活跃目录项自动居中,使用去抖的平滑滚动。 16. **TOC**:扩展滚动监听以同时观察 H1 和 H2-H4 标题。 17. **Parser**:更新标题锚点注入,使 H1 标题也包含永久链接图标。 18. **UI**:修复了因 TOC 溢出引起的页脚渲染问题。 19. **Search**:修复了 docmd-search 0.1.0-alpha.1 中的置信度百分比计算。 20. **UI**:升级 Steps 步骤组件,实现精确对齐、悬停状态和发光的品牌色节点。 21. **UI**:重构 Changelog 更新日志时间线,采用连续的网格轴和交互式可扩展标记。 22. **UI**:在内容页面顶部添加现代自适应径向光晕效果(适配亮/暗模式)。 23. **UI**:将复制小部件重新设计为统一、美观的分段控制按钮组。 24. **UI**:修复了一个关键的 SPA 路由错误——在客户端导航期间,由于相对路径解析偏移,head 资源(样式表和图标)会被重复注入。 ### 感谢 💖 感谢所有报告问题并提供反馈的贡献者和社区成员。 官方文档:https://docs.docmd.io/ GitHub 仓库:https://github.com/docmd-io/docmd --- ## [静态资源管理](https://docs.docmd.io/zh/theming/assets-management/) --- title: "静态资源管理" description: "docmd 如何在构建过程中处理 CSS、JavaScript 和图像资源。" --- `docmd` 对资源采取“镜像与映射”的方法。这确保了你的本地开发路径与生产构建保持一致。 ## 目录结构 默认情况下,`docmd` 会在项目根目录下寻找 `assets/` 文件夹。 ```bash my-docs/ ├── assets/ # 源码资源 │ ├── css/ │ ├── js/ │ └── images/ ├── docs/ # 内容 ├── docmd.config.json └── site/ # 构建输出 (自动镜像) ``` ## 自动复制 当你运行 `npx @docmd/core build` 或 `npx @docmd/core dev` 时: 1. **镜像逻辑**: `assets/` 文件夹的全部内容会被递归复制到 `site/assets/`。 2. **稳定性**: 我们使用经过加固的复制引擎,支持自动重试,以防止在 macOS 和现代 SSD 上出现“文件忙”或“ENOENT”错误。 3. **引用**: 你应该始终使用 **相对于根目录的路径** 在 Markdown 或配置中引用资源: ```markdown ![Logo](/assets/images/logo.png) ``` ## 自定义 CSS 与 JS 集成 要将你的资源链接到每个页面,请将它们添加到配置中: ```json { "customCss": ["/assets/css/branding.css"], "customJs": ["/assets/js/utils.js"] } ``` ::: callout info "AI 识别策略 :robot:" * **按类型组织**: 保持 `/css`、`/js` 和 `/images` 的分离。当你要求 AI 代理“编辑页眉颜色”时,这有助于它们立即定位相关的样式或脚本。 * **使用描述性的文件名**: 将图像命名为 `authentication-flow-diagram.png` 比 `img_01.png` 能为 `llms.txt` 爬虫提供更多的上下文。 ::: --- ## [可用主题](https://docs.docmd.io/zh/theming/available-themes/) --- title: "可用主题" description: "探索 docmd 内置的主题,包括 Sky、Ruby 和 Retro。了解如何通过单行配置切换主题。" --- `docmd` 提供了一套专业设计的、支持浅色/深色响应的主题。你可以通过更改 `docmd.config.json` 中的一个键值来切换整个网站的美学风格。 ## 如何切换主题 ```json { "theme": { "name": "sky", "appearance": "system" } } ``` ## 内置主题展示 | 主题 | 最适合 | 氛围 | | :--- | :--- | :--- | | `default` | 简约文档 | 干净、轻量、中性 | | `sky` | 产品文档 | 现代、高级、标准 | | `ruby` | 品牌标识 | 精致、衬线页眉、充满活力 | | `retro` | 开发工具 | 80 年代终端、等宽字体、霓虹点缀 | ::: grids ::: grid ::: button "Default" javascript:switchDocTheme('default') ::: ::: grid ::: button "Sky" javascript:switchDocTheme('sky') ::: ::: grid ::: button "Ruby" javascript:switchDocTheme('ruby') ::: ::: grid ::: button "Retro" javascript:switchDocTheme('retro') ::: ::: ### 1. `default` 正是此文档网站所使用的主题。如果你打算添加大量的自定义 CSS 并且不希望任何内置的设计层产生干扰,请使用此主题。 ### 2. `sky` 现代文档的金标准。它具有清晰的排版、微妙的过渡以及与现代 SaaS 平台匹配的高对比度浅色/深色模式。 ### 3. `ruby` 一个高雅的主题,页眉使用衬线体排版,并配以深沉、如宝石般色调的调色板。非常适合需要权威感和高级感的文档。 ### 4. `retro` 一个受复古计算启发、充满怀旧感的主题。特性包括黑色背景上的磷光绿文本(在深色模式下)、扫描线效果,以及默认使用的 Fira Code 等等宽字体。 ## 主题架构 1. **CSS 分层**: 主题是累加的。选择 `sky` 实际上会加载基础的 `default` 样式,然后在此基础上覆盖 `sky` 的美学样式。 2. **原生深色模式**: 每个主题都包含一流的深色模式实现。 3. **无需刷新**: 当用户通过 UI 切换主题时,SPA 引擎会立即更新 `--docmd-primary` 变量,而无需重新加载页面。 ::: callout tip 当向 AI 开发工具描述你的文档布局时,提到你的主题(例如,“我正在使用 `retro` 主题”)有助于模型建议符合该特定主题变量架构的自定义 CSS 覆盖方案。 ::: --- ## [自定义 CSS 与 JS](https://docs.docmd.io/zh/theming/custom-css-js/) --- title: "自定义 CSS 与 JS" description: "注入自定义 CSS 和 JS 文件,扩展 docmd 的功能与品牌形象。" --- 虽然 `docmd` 主题具备高度的灵活性,你仍可能需要注入自定义样式表或交互脚本。通过在配置文件中设置 `customCss` 和 `customJs` 数组即可实现。 ## 自定义 CSS 使用 `customCss` 覆盖现有样式或添加新样式。 ```json { "customCss": [ "/assets/css/branding.css" ] } ``` ### 工作原理 1. 将 CSS 文件放入项目的 assets 文件夹(如 `docs/assets/css/branding.css`)。 2. `docmd` 会自动将其复制到构建目录,并在每个页面中注入 `<link>` 标签。 3. 自定义 CSS 在主题样式**之后**加载,确保你的覆盖具有优先级。 ## 自定义 JavaScript 使用 `customJs` 数组添加行为性脚本或集成第三方服务。 ```json { "customJs": [ "/assets/js/feedback-widget.js" ] } ``` ### 生命周期感知 脚本在 `<body>` 标签底部注入。由于 `docmd` 是**单页应用(SPA)**,需注意: * 导航链接时页面不会完整重载。 * 你可能需要监听自定义生命周期事件,以便在新页面上重新初始化脚本。 有关完整的事件列表和用法示例,请参阅 [客户端事件](../api/client-side-events)。 ::: callout tip 添加自定义 CSS 和 JS 后,AI 模型(如 ChatGPT)可提出更有针对性的 UI 优化建议。如果你说"我有一个自定义的 `branding.css` 文件",模型可提供不会与引擎冲突的具体选择器。 ::: --- ## [自定义与变量](https://docs.docmd.io/zh/theming/customisation/) --- title: "自定义与变量" description: "docmd CSS 变量和组件类的完整参考,用于高级样式定制。" --- `docmd` 采用 CSS 变量优先架构。这意味着只需在 `:root` 块中覆盖少数几个变量,无需编写复杂的 CSS 选择器,即可重新设计整个网站的样式。 ## 全局变量参考 | 变量 | 亮色模式默认值 | 暗色模式默认值 | 说明 | | :--- | :--- | :--- | :--- | | `--bg-color` | `#ffffff` | `#09090b` | 页面主背景色 | | `--text-color` | `#3f3f46` | `#a1a1aa` | 正文文本颜色 | | `--text-heading` | `#09090b` | `#fafafa` | 标题与页眉颜色 | | `--link-color` | `#068ad5` | `#068ad5` | 主色调 / 链接颜色 | | `--border-color` | `#e4e4e7` | `#27272a` | 分割线与边框颜色 | | `--sidebar-bg` | `#fafafa` | `#09090b` | 导航背景色 | | `--ui-border-radius` | `6px` | `6px` | 所有 UI 项的圆角大小 | | `--sidebar-width` | `260px` | `260px` | 侧边栏列宽 | ## 覆盖示例 如需更改网站主色调,请将以下内容添加到 `customCss` 文件中: ```css :root { --link-color: #f43f5e; /* Rose 500 */ } body[data-theme="dark"] { --link-color: #fb7185; /* Rose 400 */ } ``` ## 组件定向覆盖 如需对特定组件进行样式化,可使用以下顶级类名: * `.main-content`:所有 Markdown 内容的包裹容器。 * `.sidebar-nav`:内部导航列表。 * `.page-header`:顶部导航栏。 * `.docmd-search-modal`:搜索弹框。 * `.docmd-tabs`:标签组件容器。 * `.callout`:提示/备注框。 ## 优先级排查 大多数 `docmd` 样式的优先级较低。如果覆盖未生效,请确认 `customCss` 是否已正确注册,并尝试在选择器前增加 `body` 前缀(如 `body .main-content`)。 ::: callout tip 由于 `docmd` 使用标准 CSS 变量,你可以直接询问 AI:*"为 docmd 的 --link-color 和 --bg-color 提供一套专业配色方案"*。模型将给出即用型 CSS,完美兼容内置主题。 ::: --- ## [图标](https://docs.docmd.io/zh/theming/icons/) --- title: "图标" description: "如何在你的文档中使用和自定义 Lucide 图标。" --- `docmd` 内置支持 [Lucide](external:https://lucide.dev/) 图标库。图标可以用于你的导航侧边栏、按钮和自定义组件,以提供视觉线索并提高可扫描性。 ## 导航图标 在 `docmd.config.json` 中为任何导航项分配一个图标。请使用 Lucide 网站上找到的任何图标的短横线命名法 (kebab-case) 名称。 ```json { "navigation": [ { "title": "首页", "path": "/", "icon": "home" }, { "title": "设置", "path": "/setup", "icon": "settings" } ] } ``` ## 容器中的图标 你也可以通过包含原始 HTML 或在整个 docmd 中使用标准的 `icon:` 前缀,在按钮、标签、选项卡和其他容器内部使用图标。 ```markdown ::: button "下载" /download icon:download ``` ## CSS 样式 所有图标都渲染为带有 `.lucide-icon` 类的行内 SVG。你可以在你的 `customCss` 中全局更改它们的大小或线条粗细: ```css .lucide-icon { stroke-width: 1.5px; /* 更细的图标,呈现现代感 */ width: 1.2rem; height: 1.2rem; } /* 针对特定图标 */ .icon-rocket { color: #ff5733; } ``` ## 图标参考 我们支持整个 Lucide 库。你可以在这里浏览数千个可用的图标: ::: button "浏览 Lucide 图标" external:https://lucide.dev/icons icon:globe --- ## [明暗模式](https://docs.docmd.io/zh/theming/light-dark-mode/) --- title: "明暗模式" description: "如何配置默认浏览模式并管理主题切换器,以提供最佳用户体验。" --- `docmd` 内置支持明色和暗色配色方案。它会自动检测用户的系统偏好,并允许通过 UI 切换按钮手动覆盖。 ## 默认浏览模式 在 `docmd.config.json` 中指定文档的初始状态。 ```json { "theme": { "name": "sky", "appearance": "system" } } ``` * **`system`**:匹配用户的操作系统偏好(推荐)。 * **`light`**:首次加载时强制使用亮色模式。 * **`dark`**:首次加载时强制使用暗色模式。 ## 配置切换按钮 主题切换器是**选项菜单**的组成部分。可通过 `layout` 对象控制其可见性和位置。 ```json { "layout": { "optionsMenu": { "position": "header", "components": { "themeSwitch": true } } } } ``` ## 工作原理(技术详解) 主题引擎会向 `<body>` 标签添加 `data-theme` 属性: * `<body data-theme="light">` * `<body data-theme="dark">` 如果使用类似 `sky` 这样的主题设计,属性值将为 `sky-light` 或 `sky-dark`。 ### CSS 变量 `docmd` 主题为所有颜色使用 CSS 变量。可在自定义 CSS 中覆盖这些变量,自定义任意模式的外观。 ```css /* 自定义 CSS 覆盖 */ :root { --docmd-primary: #4f46e5; /* 亮色模式主色调 */ } body[data-theme="dark"] { --docmd-primary: #818cf8; /* 暗色模式主色调 */ } ``` ## 用户偏好持久化 用户手动切换模式后,偏好将存入 `localStorage`。`docmd` 在每次页面加载时即时读取该值,防止“主题闪烁”(FOUC)。 ::: callout tip 生成内容时,LLM 偏幽高对比结构。`docmd` 确保代码片段和提示框在两种模式下均可正常访问,保证 `llms-full.txt` 内容无论在哪种模式下构建,都能被正确解析为语义块。 ::: ---