boltdocs 1.10.2 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/package.json +29 -7
  2. package/src/client/app/config-context.tsx +18 -0
  3. package/src/client/app/docs-layout.tsx +14 -0
  4. package/src/client/app/index.tsx +132 -260
  5. package/src/client/app/mdx-component.tsx +52 -0
  6. package/src/client/app/mdx-components-context.tsx +23 -0
  7. package/src/client/app/mdx-page.tsx +20 -0
  8. package/src/client/app/preload.tsx +38 -30
  9. package/src/client/app/router.tsx +30 -0
  10. package/src/client/app/scroll-handler.tsx +40 -0
  11. package/src/client/app/theme-context.tsx +75 -0
  12. package/src/client/components/default-layout.tsx +80 -0
  13. package/src/client/components/docs-layout.tsx +105 -0
  14. package/src/client/components/icons-dev.tsx +74 -0
  15. package/src/client/components/mdx/admonition.tsx +107 -0
  16. package/src/client/components/mdx/badge.tsx +41 -0
  17. package/src/client/components/mdx/button.tsx +35 -0
  18. package/src/client/components/mdx/card.tsx +124 -0
  19. package/src/client/components/mdx/code-block.tsx +119 -0
  20. package/src/client/components/mdx/component-preview.tsx +47 -0
  21. package/src/client/components/mdx/component-props.tsx +83 -0
  22. package/src/client/components/mdx/field.tsx +66 -0
  23. package/src/client/components/mdx/file-tree.tsx +287 -0
  24. package/src/client/components/mdx/hooks/use-code-block.ts +56 -0
  25. package/src/client/components/mdx/hooks/use-component-preview.ts +16 -0
  26. package/src/client/components/mdx/hooks/useTable.ts +74 -0
  27. package/src/client/components/mdx/hooks/useTabs.ts +68 -0
  28. package/src/client/components/mdx/image.tsx +23 -0
  29. package/src/client/components/mdx/index.ts +53 -0
  30. package/src/client/components/mdx/link.tsx +38 -0
  31. package/src/client/components/mdx/list.tsx +192 -0
  32. package/src/client/components/mdx/table.tsx +156 -0
  33. package/src/client/components/mdx/tabs.tsx +135 -0
  34. package/src/client/components/mdx/video.tsx +68 -0
  35. package/src/client/components/primitives/breadcrumbs.tsx +79 -0
  36. package/src/client/components/primitives/button-group.tsx +54 -0
  37. package/src/client/components/primitives/button.tsx +145 -0
  38. package/src/client/components/primitives/helpers/observer.ts +120 -0
  39. package/src/client/components/primitives/index.ts +17 -0
  40. package/src/client/components/primitives/link.tsx +122 -0
  41. package/src/client/components/primitives/menu.tsx +159 -0
  42. package/src/client/components/primitives/navbar.tsx +359 -0
  43. package/src/client/components/primitives/navigation-menu.tsx +116 -0
  44. package/src/client/components/primitives/on-this-page.tsx +461 -0
  45. package/src/client/components/primitives/page-nav.tsx +87 -0
  46. package/src/client/components/primitives/popover.tsx +47 -0
  47. package/src/client/components/primitives/search-dialog.tsx +183 -0
  48. package/src/client/components/primitives/sidebar.tsx +154 -0
  49. package/src/client/components/primitives/tabs.tsx +90 -0
  50. package/src/client/components/primitives/tooltip.tsx +83 -0
  51. package/src/client/components/primitives/types.ts +11 -0
  52. package/src/client/components/ui-base/breadcrumbs.tsx +42 -0
  53. package/src/client/components/ui-base/copy-markdown.tsx +112 -0
  54. package/src/client/components/ui-base/error-boundary.tsx +52 -0
  55. package/src/client/components/ui-base/github-stars.tsx +27 -0
  56. package/src/client/components/ui-base/head.tsx +69 -0
  57. package/src/client/components/ui-base/loading.tsx +87 -0
  58. package/src/client/components/ui-base/navbar.tsx +138 -0
  59. package/src/client/components/ui-base/not-found.tsx +24 -0
  60. package/src/client/components/ui-base/on-this-page.tsx +152 -0
  61. package/src/client/components/ui-base/page-nav.tsx +39 -0
  62. package/src/client/components/ui-base/powered-by.tsx +19 -0
  63. package/src/client/components/ui-base/progress-bar.tsx +67 -0
  64. package/src/client/components/ui-base/search-dialog.tsx +82 -0
  65. package/src/client/components/ui-base/sidebar.tsx +104 -0
  66. package/src/client/components/ui-base/tabs.tsx +65 -0
  67. package/src/client/components/ui-base/theme-toggle.tsx +32 -0
  68. package/src/client/hooks/index.ts +12 -0
  69. package/src/client/hooks/use-breadcrumbs.ts +22 -0
  70. package/src/client/hooks/use-i18n.ts +84 -0
  71. package/src/client/hooks/use-localized-to.ts +95 -0
  72. package/src/client/hooks/use-location.ts +5 -0
  73. package/src/client/hooks/use-navbar.ts +60 -0
  74. package/src/client/hooks/use-onthispage.ts +23 -0
  75. package/src/client/hooks/use-page-nav.ts +22 -0
  76. package/src/client/hooks/use-routes.ts +72 -0
  77. package/src/client/hooks/use-search.ts +71 -0
  78. package/src/client/hooks/use-sidebar.ts +49 -0
  79. package/src/client/hooks/use-tabs.ts +43 -0
  80. package/src/client/hooks/use-version.ts +78 -0
  81. package/src/client/index.ts +55 -17
  82. package/src/client/integrations/codesandbox.ts +179 -0
  83. package/src/client/ssr.tsx +27 -16
  84. package/src/client/theme/neutral.css +360 -0
  85. package/src/client/types.ts +131 -27
  86. package/src/client/utils/cn.ts +6 -0
  87. package/src/client/utils/copy-clipboard.ts +22 -0
  88. package/src/client/utils/get-base-file-path.ts +21 -0
  89. package/src/client/utils/github.ts +121 -0
  90. package/src/client/utils/use-on-change.ts +15 -0
  91. package/src/client/virtual.d.ts +24 -0
  92. package/src/node/cache.ts +156 -156
  93. package/src/node/config.ts +159 -103
  94. package/src/node/index.ts +13 -13
  95. package/src/node/mdx.ts +213 -61
  96. package/src/node/plugin/entry.ts +29 -18
  97. package/src/node/plugin/html.ts +11 -11
  98. package/src/node/plugin/index.ts +161 -83
  99. package/src/node/plugin/types.ts +2 -4
  100. package/src/node/routes/cache.ts +6 -6
  101. package/src/node/routes/index.ts +206 -113
  102. package/src/node/routes/parser.ts +106 -81
  103. package/src/node/routes/sorter.ts +15 -15
  104. package/src/node/routes/types.ts +24 -24
  105. package/src/node/ssg/index.ts +46 -46
  106. package/src/node/ssg/meta.ts +4 -4
  107. package/src/node/ssg/options.ts +5 -5
  108. package/src/node/ssg/sitemap.ts +14 -14
  109. package/src/node/utils.ts +31 -31
  110. package/tsconfig.json +25 -20
  111. package/tsup.config.ts +23 -14
  112. package/dist/PackageManagerTabs-NVT7G625.mjs +0 -99
  113. package/dist/SearchDialog-AGVF6JBO.mjs +0 -194
  114. package/dist/SearchDialog-YPDOM7Q6.css +0 -2847
  115. package/dist/Video-KNTY5BNO.mjs +0 -6
  116. package/dist/cache-KNL5B4EE.mjs +0 -12
  117. package/dist/chunk-7SFUJWTB.mjs +0 -211
  118. package/dist/chunk-FFBNU6IJ.mjs +0 -386
  119. package/dist/chunk-FMTOYQLO.mjs +0 -37
  120. package/dist/chunk-TKLQWU7H.mjs +0 -1920
  121. package/dist/chunk-Z7JHYNAS.mjs +0 -57
  122. package/dist/client/index.css +0 -2847
  123. package/dist/client/index.d.mts +0 -372
  124. package/dist/client/index.d.ts +0 -372
  125. package/dist/client/index.js +0 -3630
  126. package/dist/client/index.mjs +0 -697
  127. package/dist/client/ssr.css +0 -2847
  128. package/dist/client/ssr.d.mts +0 -27
  129. package/dist/client/ssr.d.ts +0 -27
  130. package/dist/client/ssr.js +0 -2928
  131. package/dist/client/ssr.mjs +0 -33
  132. package/dist/config-BsFQ-ErD.d.mts +0 -159
  133. package/dist/config-BsFQ-ErD.d.ts +0 -159
  134. package/dist/node/index.d.mts +0 -91
  135. package/dist/node/index.d.ts +0 -91
  136. package/dist/node/index.js +0 -1187
  137. package/dist/node/index.mjs +0 -762
  138. package/dist/types-Dj-bfnC3.d.mts +0 -74
  139. package/dist/types-Dj-bfnC3.d.ts +0 -74
  140. package/src/client/theme/components/CodeBlock/CodeBlock.tsx +0 -61
  141. package/src/client/theme/components/CodeBlock/index.ts +0 -1
  142. package/src/client/theme/components/PackageManagerTabs/PackageManagerTabs.tsx +0 -131
  143. package/src/client/theme/components/PackageManagerTabs/index.ts +0 -1
  144. package/src/client/theme/components/PackageManagerTabs/pkg-tabs.css +0 -64
  145. package/src/client/theme/components/Playground/Playground.tsx +0 -180
  146. package/src/client/theme/components/Playground/index.ts +0 -1
  147. package/src/client/theme/components/Playground/playground.css +0 -238
  148. package/src/client/theme/components/Video/Video.tsx +0 -84
  149. package/src/client/theme/components/Video/index.ts +0 -1
  150. package/src/client/theme/components/Video/video.css +0 -41
  151. package/src/client/theme/components/mdx/Admonition.tsx +0 -80
  152. package/src/client/theme/components/mdx/Badge.tsx +0 -31
  153. package/src/client/theme/components/mdx/Button.tsx +0 -50
  154. package/src/client/theme/components/mdx/Card.tsx +0 -80
  155. package/src/client/theme/components/mdx/Field.tsx +0 -60
  156. package/src/client/theme/components/mdx/FileTree.tsx +0 -229
  157. package/src/client/theme/components/mdx/List.tsx +0 -57
  158. package/src/client/theme/components/mdx/Table.tsx +0 -151
  159. package/src/client/theme/components/mdx/Tabs.tsx +0 -123
  160. package/src/client/theme/components/mdx/index.ts +0 -27
  161. package/src/client/theme/components/mdx/mdx-components.css +0 -764
  162. package/src/client/theme/icons/bun.tsx +0 -62
  163. package/src/client/theme/icons/deno.tsx +0 -20
  164. package/src/client/theme/icons/discord.tsx +0 -12
  165. package/src/client/theme/icons/github.tsx +0 -15
  166. package/src/client/theme/icons/npm.tsx +0 -13
  167. package/src/client/theme/icons/pnpm.tsx +0 -72
  168. package/src/client/theme/icons/twitter.tsx +0 -12
  169. package/src/client/theme/styles/markdown.css +0 -394
  170. package/src/client/theme/styles/variables.css +0 -175
  171. package/src/client/theme/styles.css +0 -39
  172. package/src/client/theme/ui/Breadcrumbs/Breadcrumbs.tsx +0 -68
  173. package/src/client/theme/ui/Breadcrumbs/index.ts +0 -1
  174. package/src/client/theme/ui/CopyMarkdown/CopyMarkdown.tsx +0 -82
  175. package/src/client/theme/ui/CopyMarkdown/copy-markdown.css +0 -112
  176. package/src/client/theme/ui/CopyMarkdown/index.ts +0 -1
  177. package/src/client/theme/ui/ErrorBoundary/ErrorBoundary.tsx +0 -50
  178. package/src/client/theme/ui/ErrorBoundary/error-boundary.css +0 -55
  179. package/src/client/theme/ui/ErrorBoundary/index.ts +0 -1
  180. package/src/client/theme/ui/Footer/footer.css +0 -32
  181. package/src/client/theme/ui/Head/Head.tsx +0 -69
  182. package/src/client/theme/ui/Head/index.ts +0 -1
  183. package/src/client/theme/ui/LanguageSwitcher/LanguageSwitcher.tsx +0 -125
  184. package/src/client/theme/ui/LanguageSwitcher/index.ts +0 -1
  185. package/src/client/theme/ui/LanguageSwitcher/language-switcher.css +0 -98
  186. package/src/client/theme/ui/Layout/Layout.tsx +0 -203
  187. package/src/client/theme/ui/Layout/base.css +0 -106
  188. package/src/client/theme/ui/Layout/index.ts +0 -2
  189. package/src/client/theme/ui/Layout/pagination.css +0 -72
  190. package/src/client/theme/ui/Layout/responsive.css +0 -47
  191. package/src/client/theme/ui/Link/Link.tsx +0 -392
  192. package/src/client/theme/ui/Link/LinkPreview.tsx +0 -59
  193. package/src/client/theme/ui/Link/index.ts +0 -2
  194. package/src/client/theme/ui/Link/link-preview.css +0 -48
  195. package/src/client/theme/ui/Loading/Loading.tsx +0 -10
  196. package/src/client/theme/ui/Loading/index.ts +0 -1
  197. package/src/client/theme/ui/Loading/loading.css +0 -30
  198. package/src/client/theme/ui/Navbar/GithubStars.tsx +0 -27
  199. package/src/client/theme/ui/Navbar/Navbar.tsx +0 -193
  200. package/src/client/theme/ui/Navbar/Tabs.tsx +0 -99
  201. package/src/client/theme/ui/Navbar/index.ts +0 -2
  202. package/src/client/theme/ui/Navbar/navbar.css +0 -347
  203. package/src/client/theme/ui/NotFound/NotFound.tsx +0 -19
  204. package/src/client/theme/ui/NotFound/index.ts +0 -1
  205. package/src/client/theme/ui/NotFound/not-found.css +0 -64
  206. package/src/client/theme/ui/OnThisPage/OnThisPage.tsx +0 -244
  207. package/src/client/theme/ui/OnThisPage/index.ts +0 -1
  208. package/src/client/theme/ui/OnThisPage/toc.css +0 -152
  209. package/src/client/theme/ui/PoweredBy/PoweredBy.tsx +0 -18
  210. package/src/client/theme/ui/PoweredBy/index.ts +0 -1
  211. package/src/client/theme/ui/PoweredBy/powered-by.css +0 -76
  212. package/src/client/theme/ui/ProgressBar/ProgressBar.css +0 -17
  213. package/src/client/theme/ui/ProgressBar/ProgressBar.tsx +0 -51
  214. package/src/client/theme/ui/ProgressBar/index.ts +0 -1
  215. package/src/client/theme/ui/SearchDialog/SearchDialog.tsx +0 -209
  216. package/src/client/theme/ui/SearchDialog/index.ts +0 -1
  217. package/src/client/theme/ui/SearchDialog/search.css +0 -152
  218. package/src/client/theme/ui/Sidebar/Sidebar.tsx +0 -244
  219. package/src/client/theme/ui/Sidebar/index.ts +0 -1
  220. package/src/client/theme/ui/Sidebar/sidebar.css +0 -230
  221. package/src/client/theme/ui/ThemeToggle/ThemeToggle.tsx +0 -69
  222. package/src/client/theme/ui/ThemeToggle/index.ts +0 -1
  223. package/src/client/theme/ui/VersionSwitcher/VersionSwitcher.tsx +0 -136
  224. package/src/client/theme/ui/VersionSwitcher/index.ts +0 -1
  225. package/src/client/utils.ts +0 -49
@@ -1,1187 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/node/utils.ts
34
- function normalizePath(p) {
35
- return p.replace(/\\/g, "/");
36
- }
37
- function stripNumberPrefix(name) {
38
- return name.replace(/^\d+\./, "");
39
- }
40
- function extractNumberPrefix(name) {
41
- const match = name.match(/^(\d+)\./);
42
- return match ? parseInt(match[1], 10) : void 0;
43
- }
44
- function isDocFile(filePath) {
45
- return /\.mdx?$/.test(filePath);
46
- }
47
- function getFileMtime(filePath) {
48
- try {
49
- return import_fs.default.statSync(filePath).mtimeMs;
50
- } catch {
51
- return 0;
52
- }
53
- }
54
- function parseFrontmatter(filePath) {
55
- const raw = import_fs.default.readFileSync(filePath, "utf-8");
56
- const { data, content } = (0, import_gray_matter.default)(raw);
57
- return { data, content };
58
- }
59
- function escapeHtml(str) {
60
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
61
- }
62
- function escapeXml(str) {
63
- return escapeHtml(str);
64
- }
65
- function fileToRoutePath(relativePath) {
66
- let cleanedPath = relativePath.split("/").map(stripNumberPrefix).join("/");
67
- let routePath = cleanedPath.replace(/\/$/, "");
68
- routePath = routePath.replace(/\.mdx?$/, "");
69
- if (routePath === "index" || routePath.endsWith("/index")) {
70
- routePath = routePath.replace(/index$/, "");
71
- }
72
- if (!routePath.startsWith("/")) {
73
- routePath = "/" + routePath;
74
- }
75
- if (routePath.length > 1 && routePath.endsWith("/")) {
76
- routePath = routePath.slice(0, -1);
77
- }
78
- return routePath;
79
- }
80
- function capitalize(str) {
81
- return str.charAt(0).toUpperCase() + str.slice(1);
82
- }
83
- var import_fs, import_gray_matter;
84
- var init_utils = __esm({
85
- "src/node/utils.ts"() {
86
- "use strict";
87
- import_fs = __toESM(require("fs"));
88
- import_gray_matter = __toESM(require("gray-matter"));
89
- }
90
- });
91
-
92
- // src/node/cache.ts
93
- var cache_exports = {};
94
- __export(cache_exports, {
95
- AssetCache: () => AssetCache,
96
- FileCache: () => FileCache,
97
- TransformCache: () => TransformCache,
98
- flushCache: () => flushCache
99
- });
100
- async function flushCache() {
101
- await backgroundQueue.flush();
102
- }
103
- var import_fs2, import_path, import_crypto, import_zlib, import_util, writeFile, readFile, mkdir, rename, unlink, CACHE_DIR, ASSETS_DIR, SHARDS_DIR, DEFAULT_LRU_LIMIT, DEFAULT_COMPRESS, LRUCache, BackgroundQueue, backgroundQueue, FileCache, TransformCache, AssetCache;
104
- var init_cache = __esm({
105
- "src/node/cache.ts"() {
106
- "use strict";
107
- import_fs2 = __toESM(require("fs"));
108
- import_path = __toESM(require("path"));
109
- import_crypto = __toESM(require("crypto"));
110
- import_zlib = __toESM(require("zlib"));
111
- import_util = require("util");
112
- init_utils();
113
- writeFile = (0, import_util.promisify)(import_fs2.default.writeFile);
114
- readFile = (0, import_util.promisify)(import_fs2.default.readFile);
115
- mkdir = (0, import_util.promisify)(import_fs2.default.mkdir);
116
- rename = (0, import_util.promisify)(import_fs2.default.rename);
117
- unlink = (0, import_util.promisify)(import_fs2.default.unlink);
118
- CACHE_DIR = process.env.BOLTDOCS_CACHE_DIR || ".boltdocs";
119
- ASSETS_DIR = "assets";
120
- SHARDS_DIR = "shards";
121
- DEFAULT_LRU_LIMIT = parseInt(
122
- process.env.BOLTDOCS_CACHE_LRU_LIMIT || "2000",
123
- 10
124
- );
125
- DEFAULT_COMPRESS = process.env.BOLTDOCS_CACHE_COMPRESS !== "0";
126
- LRUCache = class {
127
- constructor(limit) {
128
- this.limit = limit;
129
- }
130
- cache = /* @__PURE__ */ new Map();
131
- get(key) {
132
- const val = this.cache.get(key);
133
- if (val !== void 0) {
134
- this.cache.delete(key);
135
- this.cache.set(key, val);
136
- }
137
- return val;
138
- }
139
- set(key, value) {
140
- if (this.cache.has(key)) {
141
- this.cache.delete(key);
142
- } else if (this.cache.size >= this.limit) {
143
- const firstKey = this.cache.keys().next().value;
144
- if (firstKey !== void 0) {
145
- this.cache.delete(firstKey);
146
- }
147
- }
148
- this.cache.set(key, value);
149
- }
150
- get size() {
151
- return this.cache.size;
152
- }
153
- clear() {
154
- this.cache.clear();
155
- }
156
- };
157
- BackgroundQueue = class {
158
- queue = Promise.resolve();
159
- pendingCount = 0;
160
- add(task) {
161
- this.pendingCount++;
162
- this.queue = this.queue.then(task).finally(() => {
163
- this.pendingCount--;
164
- });
165
- }
166
- async flush() {
167
- await this.queue;
168
- }
169
- get pending() {
170
- return this.pendingCount;
171
- }
172
- };
173
- backgroundQueue = new BackgroundQueue();
174
- FileCache = class {
175
- entries = /* @__PURE__ */ new Map();
176
- cachePath = null;
177
- compress;
178
- constructor(options = {}) {
179
- this.compress = options.compress !== void 0 ? options.compress : DEFAULT_COMPRESS;
180
- if (options.name) {
181
- const root = options.root || process.cwd();
182
- const ext = this.compress ? "json.gz" : "json";
183
- this.cachePath = import_path.default.resolve(root, CACHE_DIR, `${options.name}.${ext}`);
184
- }
185
- }
186
- /**
187
- * Loads the cache. Synchronous for startup simplicity but uses fast I/O.
188
- */
189
- load() {
190
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
191
- if (!this.cachePath || !import_fs2.default.existsSync(this.cachePath)) return;
192
- try {
193
- let raw = import_fs2.default.readFileSync(this.cachePath);
194
- if (this.cachePath.endsWith(".gz")) {
195
- raw = import_zlib.default.gunzipSync(raw);
196
- }
197
- const data = JSON.parse(raw.toString("utf-8"));
198
- this.entries = new Map(Object.entries(data));
199
- } catch (e) {
200
- }
201
- }
202
- /**
203
- * Saves the cache in the background.
204
- */
205
- save() {
206
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
207
- if (!this.cachePath) return;
208
- const data = Object.fromEntries(this.entries);
209
- const content = JSON.stringify(data);
210
- const target = this.cachePath;
211
- const useCompress = this.compress;
212
- backgroundQueue.add(async () => {
213
- try {
214
- await mkdir(import_path.default.dirname(target), { recursive: true });
215
- let buffer = Buffer.from(content);
216
- if (useCompress) {
217
- buffer = import_zlib.default.gzipSync(buffer);
218
- }
219
- const tempPath = `${target}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
220
- await writeFile(tempPath, buffer);
221
- await rename(tempPath, target);
222
- } catch (e) {
223
- }
224
- });
225
- }
226
- get(filePath) {
227
- const entry = this.entries.get(filePath);
228
- if (!entry) return null;
229
- if (getFileMtime(filePath) !== entry.mtime) return null;
230
- return entry.data;
231
- }
232
- set(filePath, data) {
233
- this.entries.set(filePath, {
234
- data,
235
- mtime: getFileMtime(filePath)
236
- });
237
- }
238
- isValid(filePath) {
239
- const entry = this.entries.get(filePath);
240
- if (!entry) return false;
241
- return getFileMtime(filePath) === entry.mtime;
242
- }
243
- invalidate(filePath) {
244
- this.entries.delete(filePath);
245
- }
246
- invalidateAll() {
247
- this.entries.clear();
248
- }
249
- pruneStale(currentFiles) {
250
- for (const key of this.entries.keys()) {
251
- if (!currentFiles.has(key)) {
252
- this.entries.delete(key);
253
- }
254
- }
255
- }
256
- get size() {
257
- return this.entries.size;
258
- }
259
- async flush() {
260
- await backgroundQueue.flush();
261
- }
262
- };
263
- TransformCache = class {
264
- index = /* @__PURE__ */ new Map();
265
- // key -> hash
266
- memoryCache = new LRUCache(DEFAULT_LRU_LIMIT);
267
- baseDir;
268
- shardsDir;
269
- indexPath;
270
- constructor(name, root = process.cwd()) {
271
- this.baseDir = import_path.default.resolve(root, CACHE_DIR, `transform-${name}`);
272
- this.shardsDir = import_path.default.resolve(this.baseDir, SHARDS_DIR);
273
- this.indexPath = import_path.default.resolve(this.baseDir, "index.json");
274
- }
275
- /**
276
- * Loads the index into memory.
277
- */
278
- load() {
279
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
280
- if (!import_fs2.default.existsSync(this.indexPath)) return;
281
- try {
282
- const data = import_fs2.default.readFileSync(this.indexPath, "utf-8");
283
- this.index = new Map(Object.entries(JSON.parse(data)));
284
- } catch (e) {
285
- }
286
- }
287
- /**
288
- * Persists the index in background.
289
- */
290
- save() {
291
- if (process.env.BOLTDOCS_NO_CACHE === "1") return;
292
- const data = JSON.stringify(Object.fromEntries(this.index));
293
- const target = this.indexPath;
294
- backgroundQueue.add(async () => {
295
- await mkdir(import_path.default.dirname(target), { recursive: true });
296
- await writeFile(target, data);
297
- });
298
- }
299
- /**
300
- * Batch Read: Retrieves multiple transformation results concurrently.
301
- */
302
- async getMany(keys) {
303
- const results = /* @__PURE__ */ new Map();
304
- const toLoad = [];
305
- for (const key of keys) {
306
- const mem = this.memoryCache.get(key);
307
- if (mem) results.set(key, mem);
308
- else if (this.index.has(key)) toLoad.push(key);
309
- }
310
- if (toLoad.length > 0) {
311
- const shards = await Promise.all(
312
- toLoad.map(async (key) => {
313
- const hash = this.index.get(key);
314
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
315
- try {
316
- const compressed = await readFile(shardPath);
317
- const decompressed = import_zlib.default.gunzipSync(compressed).toString("utf-8");
318
- this.memoryCache.set(key, decompressed);
319
- return { key, val: decompressed };
320
- } catch (e) {
321
- return null;
322
- }
323
- })
324
- );
325
- for (const s of shards) {
326
- if (s) results.set(s.key, s.val);
327
- }
328
- }
329
- return results;
330
- }
331
- /**
332
- * Retrieves a cached transformation. Fast lookup via index, lazy loading from disk.
333
- */
334
- get(key) {
335
- const mem = this.memoryCache.get(key);
336
- if (mem) return mem;
337
- const hash = this.index.get(key);
338
- if (!hash) return null;
339
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
340
- if (!import_fs2.default.existsSync(shardPath)) return null;
341
- try {
342
- const compressed = import_fs2.default.readFileSync(shardPath);
343
- const decompressed = import_zlib.default.gunzipSync(compressed).toString("utf-8");
344
- this.memoryCache.set(key, decompressed);
345
- return decompressed;
346
- } catch (e) {
347
- return null;
348
- }
349
- }
350
- /**
351
- * Stores a transformation result.
352
- */
353
- set(key, result) {
354
- const hash = import_crypto.default.createHash("md5").update(result).digest("hex");
355
- this.index.set(key, hash);
356
- this.memoryCache.set(key, result);
357
- const shardPath = import_path.default.resolve(this.shardsDir, `${hash}.gz`);
358
- backgroundQueue.add(async () => {
359
- if (import_fs2.default.existsSync(shardPath)) return;
360
- await mkdir(this.shardsDir, { recursive: true });
361
- const compressed = import_zlib.default.gzipSync(Buffer.from(result));
362
- const tempPath = `${shardPath}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
363
- await writeFile(tempPath, compressed);
364
- await rename(tempPath, shardPath);
365
- });
366
- }
367
- get size() {
368
- return this.index.size;
369
- }
370
- async flush() {
371
- await backgroundQueue.flush();
372
- }
373
- };
374
- AssetCache = class {
375
- assetsDir;
376
- constructor(root = process.cwd()) {
377
- this.assetsDir = import_path.default.resolve(root, CACHE_DIR, ASSETS_DIR);
378
- }
379
- getFileHash(filePath) {
380
- return import_crypto.default.createHash("md5").update(import_fs2.default.readFileSync(filePath)).digest("hex");
381
- }
382
- get(sourcePath, cacheKey) {
383
- if (!import_fs2.default.existsSync(sourcePath)) return null;
384
- const sourceHash = this.getFileHash(sourcePath);
385
- const cachedPath = this.getCachedPath(
386
- sourcePath,
387
- `${cacheKey}-${sourceHash}`
388
- );
389
- return import_fs2.default.existsSync(cachedPath) ? cachedPath : null;
390
- }
391
- set(sourcePath, cacheKey, content) {
392
- const sourceHash = this.getFileHash(sourcePath);
393
- const cachedPath = this.getCachedPath(
394
- sourcePath,
395
- `${cacheKey}-${sourceHash}`
396
- );
397
- backgroundQueue.add(async () => {
398
- await mkdir(this.assetsDir, { recursive: true });
399
- const tempPath = `${cachedPath}.${import_crypto.default.randomBytes(4).toString("hex")}.tmp`;
400
- await writeFile(tempPath, content);
401
- await rename(tempPath, cachedPath);
402
- });
403
- }
404
- getCachedPath(sourcePath, cacheKey) {
405
- const ext = import_path.default.extname(sourcePath);
406
- const name = import_path.default.basename(sourcePath, ext);
407
- const safeKey = cacheKey.replace(/[^a-z0-9]/gi, "-").toLowerCase();
408
- return import_path.default.join(this.assetsDir, `${name}.${safeKey}${ext}`);
409
- }
410
- clear() {
411
- if (import_fs2.default.existsSync(this.assetsDir)) {
412
- import_fs2.default.rmSync(this.assetsDir, { recursive: true, force: true });
413
- }
414
- }
415
- async flush() {
416
- await backgroundQueue.flush();
417
- }
418
- };
419
- }
420
- });
421
-
422
- // src/node/index.ts
423
- var node_exports = {};
424
- __export(node_exports, {
425
- default: () => boltdocs,
426
- generateStaticPages: () => generateStaticPages
427
- });
428
- module.exports = __toCommonJS(node_exports);
429
-
430
- // src/node/plugin/index.ts
431
- var import_vite = require("vite");
432
-
433
- // src/node/routes/index.ts
434
- var import_fast_glob = __toESM(require("fast-glob"));
435
- init_utils();
436
-
437
- // src/node/routes/cache.ts
438
- init_cache();
439
- var docCache = new FileCache({ name: "routes" });
440
- function invalidateRouteCache() {
441
- docCache.invalidateAll();
442
- }
443
- function invalidateFile(filePath) {
444
- docCache.invalidate(filePath);
445
- }
446
-
447
- // src/node/routes/parser.ts
448
- var import_path2 = __toESM(require("path"));
449
- var import_github_slugger = __toESM(require("github-slugger"));
450
- init_utils();
451
- function parseDocFile(file, docsDir, basePath, config) {
452
- const decodedFile = decodeURIComponent(file);
453
- const absoluteFile = import_path2.default.resolve(decodedFile);
454
- const absoluteDocsDir = import_path2.default.resolve(docsDir);
455
- const relativePath = normalizePath(
456
- import_path2.default.relative(absoluteDocsDir, absoluteFile)
457
- );
458
- if (relativePath.startsWith("../") || relativePath === ".." || absoluteFile.includes("\0")) {
459
- throw new Error(
460
- `Security breach: File is outside of docs directory or contains null bytes: ${file}`
461
- );
462
- }
463
- const { data, content } = parseFrontmatter(file);
464
- let parts = relativePath.split("/");
465
- let locale;
466
- let version;
467
- if (config?.versions && parts.length > 0) {
468
- const potentialVersion = parts[0];
469
- if (config.versions.versions[potentialVersion]) {
470
- version = potentialVersion;
471
- parts = parts.slice(1);
472
- }
473
- }
474
- if (config?.i18n && parts.length > 0) {
475
- const potentialLocale = parts[0];
476
- if (config.i18n.locales[potentialLocale]) {
477
- locale = potentialLocale;
478
- parts = parts.slice(1);
479
- }
480
- }
481
- let inferredTab;
482
- if (parts.length > 0) {
483
- const tabMatch = parts[0].match(/^\((.+)\)$/);
484
- if (tabMatch) {
485
- inferredTab = tabMatch[1].toLowerCase();
486
- parts = parts.slice(1);
487
- }
488
- }
489
- const cleanRelativePath = parts.join("/");
490
- let cleanRoutePath;
491
- if (data.permalink) {
492
- cleanRoutePath = data.permalink.startsWith("/") ? data.permalink : `/${data.permalink}`;
493
- } else {
494
- cleanRoutePath = fileToRoutePath(cleanRelativePath || "index.md");
495
- }
496
- let finalPath = basePath;
497
- if (version) {
498
- finalPath += "/" + version;
499
- }
500
- if (locale) {
501
- finalPath += "/" + locale;
502
- }
503
- finalPath += cleanRoutePath === "/" ? "" : cleanRoutePath;
504
- if (!finalPath || finalPath === "") finalPath = "/";
505
- const rawFileName = parts[parts.length - 1];
506
- const cleanFileName = stripNumberPrefix(rawFileName);
507
- const inferredTitle = stripNumberPrefix(
508
- import_path2.default.basename(file, import_path2.default.extname(file))
509
- );
510
- const sidebarPosition = data.sidebarPosition ?? extractNumberPrefix(rawFileName);
511
- const rawDirName = parts.length >= 2 ? parts[0] : void 0;
512
- const cleanDirName = rawDirName ? stripNumberPrefix(rawDirName) : void 0;
513
- const isGroupIndex = parts.length >= 2 && /^index\.mdx?$/.test(cleanFileName);
514
- const headings = [];
515
- const slugger = new import_github_slugger.default();
516
- const headingsRegex = /^(#{2,4})\s+(.+)$/gm;
517
- let match;
518
- while ((match = headingsRegex.exec(content)) !== null) {
519
- const level = match[1].length;
520
- const text = match[2].replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/[_*`]/g, "").trim();
521
- const id = slugger.slug(text);
522
- headings.push({ level, text, id });
523
- }
524
- const sanitizedTitle = data.title ? data.title : inferredTitle;
525
- let sanitizedDescription = data.description ? data.description : "";
526
- if (!sanitizedDescription && content) {
527
- const summary = content.replace(/^#+.*$/gm, "").replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/[_*`]/g, "").replace(/\n+/g, " ").trim().slice(0, 160);
528
- sanitizedDescription = summary;
529
- }
530
- const sanitizedBadge = data.badge ? data.badge : void 0;
531
- const icon = data.icon ? String(data.icon) : void 0;
532
- const plainText = content.replace(/^#+.*$/gm, "").replace(/\[([^\]]+)\]\([^\)]+\)/g, "$1").replace(/<[^>]+>/g, "").replace(/\{[^\}]+\}/g, "").replace(/[_*`]/g, "").replace(/\n+/g, " ").trim();
533
- return {
534
- route: {
535
- path: finalPath,
536
- componentPath: file,
537
- filePath: relativePath,
538
- title: sanitizedTitle,
539
- description: sanitizedDescription,
540
- sidebarPosition,
541
- headings,
542
- locale,
543
- version,
544
- badge: sanitizedBadge,
545
- icon,
546
- tab: inferredTab,
547
- _content: plainText,
548
- _rawContent: content
549
- },
550
- relativeDir: cleanDirName,
551
- isGroupIndex,
552
- inferredTab,
553
- groupMeta: isGroupIndex ? {
554
- title: data.groupTitle || data.title || (cleanDirName ? capitalize(cleanDirName) : ""),
555
- position: data.groupPosition ?? data.sidebarPosition ?? (rawDirName ? extractNumberPrefix(rawDirName) : void 0),
556
- icon
557
- } : void 0,
558
- inferredGroupPosition: rawDirName ? extractNumberPrefix(rawDirName) : void 0
559
- };
560
- }
561
-
562
- // src/node/routes/sorter.ts
563
- function sortRoutes(routes) {
564
- return routes.sort((a, b) => {
565
- if (!a.group && !b.group) return compareByPosition(a, b);
566
- if (!a.group) return -1;
567
- if (!b.group) return 1;
568
- if (a.group !== b.group) {
569
- return compareByGroupPosition(a, b);
570
- }
571
- return compareByPosition(a, b);
572
- });
573
- }
574
- function compareByPosition(a, b) {
575
- if (a.sidebarPosition !== void 0 && b.sidebarPosition !== void 0)
576
- return a.sidebarPosition - b.sidebarPosition;
577
- if (a.sidebarPosition !== void 0) return -1;
578
- if (b.sidebarPosition !== void 0) return 1;
579
- return a.title.localeCompare(b.title);
580
- }
581
- function compareByGroupPosition(a, b) {
582
- if (a.groupPosition !== void 0 && b.groupPosition !== void 0)
583
- return a.groupPosition - b.groupPosition;
584
- if (a.groupPosition !== void 0) return -1;
585
- if (b.groupPosition !== void 0) return 1;
586
- return (a.groupTitle || a.group).localeCompare(b.groupTitle || b.group);
587
- }
588
-
589
- // src/node/routes/index.ts
590
- async function generateRoutes(docsDir, config, basePath = "/docs") {
591
- docCache.load();
592
- docCache.invalidateAll();
593
- const files = await (0, import_fast_glob.default)(["**/*.md", "**/*.mdx"], {
594
- cwd: docsDir,
595
- absolute: true
596
- });
597
- docCache.pruneStale(new Set(files));
598
- if (config?.i18n) {
599
- docCache.invalidateAll();
600
- }
601
- let cacheHits = 0;
602
- const parsed = await Promise.all(
603
- files.map(async (file) => {
604
- const cached = docCache.get(file);
605
- if (cached) {
606
- cacheHits++;
607
- return cached;
608
- }
609
- const result = parseDocFile(file, docsDir, basePath, config);
610
- docCache.set(file, result);
611
- return result;
612
- })
613
- );
614
- if (files.length > 0) {
615
- console.log(
616
- `[boltdocs] Routes generated: ${files.length} files (${cacheHits} from cache, ${files.length - cacheHits} parsed)`
617
- );
618
- }
619
- docCache.save();
620
- const groupMeta = /* @__PURE__ */ new Map();
621
- for (const p of parsed) {
622
- if (p.relativeDir) {
623
- if (!groupMeta.has(p.relativeDir)) {
624
- groupMeta.set(p.relativeDir, {
625
- title: capitalize(p.relativeDir),
626
- position: p.inferredGroupPosition,
627
- icon: p.route.icon
628
- });
629
- } else {
630
- const entry = groupMeta.get(p.relativeDir);
631
- if (entry.position === void 0 && p.inferredGroupPosition !== void 0) {
632
- entry.position = p.inferredGroupPosition;
633
- }
634
- if (!entry.icon && p.route.icon) {
635
- entry.icon = p.route.icon;
636
- }
637
- }
638
- }
639
- if (p.isGroupIndex && p.relativeDir && p.groupMeta) {
640
- const entry = groupMeta.get(p.relativeDir);
641
- entry.title = p.groupMeta.title;
642
- if (p.groupMeta.position !== void 0) {
643
- entry.position = p.groupMeta.position;
644
- }
645
- if (p.groupMeta.icon) {
646
- entry.icon = p.groupMeta.icon;
647
- }
648
- }
649
- }
650
- const routes = parsed.map((p) => {
651
- const dir = p.relativeDir;
652
- const meta = dir ? groupMeta.get(dir) : void 0;
653
- return {
654
- ...p.route,
655
- group: dir,
656
- groupTitle: meta?.title || (dir ? capitalize(dir) : void 0),
657
- groupPosition: meta?.position,
658
- groupIcon: meta?.icon
659
- };
660
- });
661
- if (config?.i18n) {
662
- const defaultLocale = config.i18n.defaultLocale;
663
- const allLocales = Object.keys(config.i18n.locales);
664
- const fallbackRoutes = [];
665
- const defaultRoutes = routes.filter(
666
- (r) => (r.locale || defaultLocale) === defaultLocale
667
- );
668
- for (const locale of allLocales) {
669
- if (locale === defaultLocale) continue;
670
- const localeRoutePaths = new Set(
671
- routes.filter((r) => r.locale === locale).map((r) => r.path)
672
- );
673
- for (const defRoute of defaultRoutes) {
674
- let prefix = basePath;
675
- if (defRoute.version) {
676
- prefix += "/" + defRoute.version;
677
- }
678
- let pathAfterVersion = defRoute.path.substring(prefix.length);
679
- if (pathAfterVersion.startsWith("/" + defaultLocale + "/")) {
680
- pathAfterVersion = pathAfterVersion.substring(
681
- defaultLocale.length + 1
682
- );
683
- } else if (pathAfterVersion === "/" + defaultLocale) {
684
- pathAfterVersion = "/";
685
- }
686
- const targetPath = prefix + "/" + locale + (pathAfterVersion === "/" || pathAfterVersion === "" ? "" : pathAfterVersion);
687
- if (!localeRoutePaths.has(targetPath)) {
688
- fallbackRoutes.push({
689
- ...defRoute,
690
- path: targetPath,
691
- locale
692
- });
693
- }
694
- }
695
- }
696
- return sortRoutes([...routes, ...fallbackRoutes]);
697
- }
698
- return sortRoutes(routes);
699
- }
700
-
701
- // src/node/plugin/index.ts
702
- var import_vite_plugin_image_optimizer = require("vite-plugin-image-optimizer");
703
-
704
- // src/node/config.ts
705
- var import_path3 = __toESM(require("path"));
706
- var import_url = require("url");
707
- var import_fs3 = __toESM(require("fs"));
708
- var CONFIG_FILES = [
709
- "boltdocs.config.js",
710
- "boltdocs.config.mjs",
711
- "boltdocs.config.ts"
712
- ];
713
- async function resolveConfig(docsDir, root = process.cwd()) {
714
- const projectRoot = root;
715
- const defaults = {
716
- docsDir: import_path3.default.resolve(docsDir),
717
- themeConfig: {
718
- title: "Boltdocs",
719
- description: "A Vite documentation framework",
720
- navbar: [
721
- { text: "Home", link: "/" },
722
- { text: "Documentation", link: "/docs" }
723
- ]
724
- }
725
- };
726
- for (const filename of CONFIG_FILES) {
727
- const configPath = import_path3.default.resolve(projectRoot, filename);
728
- if (import_fs3.default.existsSync(configPath)) {
729
- try {
730
- const isTest = process.env.NODE_ENV === "test" || global.__vitest_worker__;
731
- const fileUrl = (0, import_url.pathToFileURL)(configPath).href + (isTest ? "" : "?t=" + Date.now());
732
- const mod = await import(fileUrl);
733
- const userConfig = mod.default || mod;
734
- const userThemeConfig = userConfig.themeConfig || userConfig;
735
- return {
736
- docsDir: import_path3.default.resolve(docsDir),
737
- themeConfig: {
738
- ...defaults.themeConfig,
739
- ...userThemeConfig
740
- },
741
- i18n: userConfig.i18n,
742
- versions: userConfig.versions,
743
- siteUrl: userConfig.siteUrl,
744
- plugins: userConfig.plugins || []
745
- };
746
- } catch (e) {
747
- console.warn(`[boltdocs] Failed to load config from ${filename}:`, e);
748
- }
749
- }
750
- }
751
- return defaults;
752
- }
753
-
754
- // src/node/ssg/index.ts
755
- var import_fs4 = __toESM(require("fs"));
756
- var import_path4 = __toESM(require("path"));
757
- init_utils();
758
- var import_url2 = require("url");
759
- var import_module = require("module");
760
-
761
- // src/node/ssg/meta.ts
762
- init_utils();
763
- function replaceMetaTags(html, meta) {
764
- const title = escapeHtml(meta.title);
765
- const description = escapeHtml(meta.description);
766
- return html.replace(/<title>.*?<\/title>/, `<title>${title}</title>`).replace(
767
- /(<meta name="description" content=")[^"]*(")/,
768
- `$1${description}$2`
769
- ).replace(/(<meta property="og:title" content=")[^"]*(")/, `$1${title}$2`).replace(
770
- /(<meta property="og:description" content=")[^"]*(")/,
771
- `$1${description}$2`
772
- ).replace(/(<meta name="twitter:title" content=")[^"]*(")/, `$1${title}$2`).replace(
773
- /(<meta name="twitter:description" content=")[^"]*(")/,
774
- `$1${description}$2`
775
- );
776
- }
777
-
778
- // src/node/ssg/sitemap.ts
779
- init_utils();
780
- function generateSitemap(routePaths, config) {
781
- const baseUrl = config?.siteUrl?.replace(/\/$/, "") || "https://example.com";
782
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
783
- const rootEntries = [{ url: "/", priority: "1.0", changefreq: "daily" }];
784
- if (config?.i18n) {
785
- const defaultLocale = config.i18n.defaultLocale;
786
- for (const locale of Object.keys(config.i18n.locales)) {
787
- if (locale !== defaultLocale) {
788
- rootEntries.push({
789
- url: `/${locale}/`,
790
- priority: "1.0",
791
- changefreq: "daily"
792
- });
793
- }
794
- }
795
- }
796
- const entries = [
797
- ...rootEntries,
798
- ...routePaths.map((p) => ({
799
- url: p,
800
- priority: "0.8",
801
- changefreq: "weekly"
802
- }))
803
- ];
804
- return `<?xml version="1.0" encoding="UTF-8"?>
805
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
806
- ${entries.map(
807
- (e) => ` <url>
808
- <loc>${escapeXml(baseUrl)}${escapeXml(e.url)}</loc>
809
- <lastmod>${today}</lastmod>
810
- <changefreq>${e.changefreq}</changefreq>
811
- <priority>${e.priority}</priority>
812
- </url>`
813
- ).join("\n")}
814
- </urlset>`;
815
- }
816
-
817
- // src/node/ssg/index.ts
818
- var import_meta2 = {};
819
- var _filename = (0, import_url2.fileURLToPath)(import_meta2.url);
820
- var _dirname = import_path4.default.dirname(_filename);
821
- var _require = (0, import_module.createRequire)(import_meta2.url);
822
- async function generateStaticPages(options) {
823
- const { docsDir, docsDirName, outDir, config } = options;
824
- const routes = await generateRoutes(docsDir, config);
825
- const siteTitle = config?.themeConfig?.title || "Boltdocs";
826
- const siteDescription = config?.themeConfig?.description || "";
827
- const ssrModulePath = import_path4.default.resolve(_dirname, "../client/ssr.js");
828
- if (!import_fs4.default.existsSync(ssrModulePath)) {
829
- console.error(
830
- "[boltdocs] SSR module not found at",
831
- ssrModulePath,
832
- "- Did you build the core package?"
833
- );
834
- return;
835
- }
836
- const { render } = _require(ssrModulePath);
837
- const templatePath = import_path4.default.join(outDir, "index.html");
838
- if (!import_fs4.default.existsSync(templatePath)) {
839
- console.warn("[boltdocs] No index.html found in outDir, skipping SSG.");
840
- return;
841
- }
842
- const template = import_fs4.default.readFileSync(templatePath, "utf-8");
843
- await Promise.all(
844
- routes.map(async (route) => {
845
- const pageTitle = `${route.title} | ${siteTitle}`;
846
- const pageDescription = route.description || siteDescription;
847
- const fakeModules = {};
848
- fakeModules[route.componentPath] = { default: () => {
849
- } };
850
- try {
851
- const appHtml = await render({
852
- path: route.path,
853
- routes,
854
- config: config || {},
855
- docsDirName,
856
- modules: fakeModules,
857
- homePage: void 0
858
- // No custom home page for now
859
- });
860
- const html = replaceMetaTags(template, {
861
- title: escapeHtml(pageTitle),
862
- description: escapeHtml(pageDescription)
863
- }).replace("<!--app-html-->", appHtml).replace(`<div id="root"></div>`, `<div id="root">${appHtml}</div>`);
864
- const routeDir = import_path4.default.join(outDir, route.path);
865
- await import_fs4.default.promises.mkdir(routeDir, { recursive: true });
866
- await import_fs4.default.promises.writeFile(
867
- import_path4.default.join(routeDir, "index.html"),
868
- html,
869
- "utf-8"
870
- );
871
- } catch (e) {
872
- console.error(`[boltdocs] Error SSR rendering route ${route.path}:`, e);
873
- }
874
- })
875
- );
876
- const sitemap = generateSitemap(
877
- routes.map((r) => r.path),
878
- config
879
- );
880
- import_fs4.default.writeFileSync(import_path4.default.join(outDir, "sitemap.xml"), sitemap, "utf-8");
881
- console.log(
882
- `[boltdocs] Generated ${routes.length} static pages + sitemap.xml`
883
- );
884
- const { flushCache: flushCache2 } = await Promise.resolve().then(() => (init_cache(), cache_exports));
885
- await flushCache2();
886
- }
887
-
888
- // src/node/plugin/index.ts
889
- init_utils();
890
- var import_path6 = __toESM(require("path"));
891
-
892
- // src/node/plugin/entry.ts
893
- init_utils();
894
- var import_path5 = __toESM(require("path"));
895
- function generateEntryCode(options, config) {
896
- const homeImport = options.homePage ? `import HomePage from '${normalizePath(options.homePage)}';` : "";
897
- const homeOption = options.homePage ? "homePage: HomePage," : "";
898
- const customCssImport = options.customCss ? `import '${normalizePath(options.customCss)}';` : "";
899
- const pluginComponents = config?.plugins?.flatMap((p) => Object.entries(p.components || {})) || [];
900
- const componentImports = pluginComponents.map(
901
- ([
902
- name,
903
- path7
904
- ]) => `import * as _comp_${name} from '${normalizePath(path7)}';
905
- const ${name} = _comp_${name}.default || _comp_${name}['${name}'] || _comp_${name};`
906
- ).join("\n");
907
- const componentMap = pluginComponents.map(([name]) => name).join(", ");
908
- const docsDirName = import_path5.default.basename(options.docsDir || "docs");
909
- return `
910
- import { createBoltdocsApp as _createApp } from 'boltdocs/client';
911
- import 'boltdocs/style.css';
912
- ${customCssImport}
913
- import _routes from 'virtual:boltdocs-routes';
914
- import _config from 'virtual:boltdocs-config';
915
- ${homeImport}
916
- ${componentImports}
917
-
918
- _createApp({
919
- target: '#root',
920
- routes: _routes,
921
- docsDirName: '${docsDirName}',
922
- config: _config,
923
- modules: import.meta.glob('/${docsDirName}/**/*.{md,mdx}'),
924
- hot: import.meta.hot,
925
- ${homeOption}
926
- components: { ${componentMap} },
927
- });
928
- `;
929
- }
930
-
931
- // src/node/plugin/html.ts
932
- function injectHtmlMeta(html, config) {
933
- const title = config.themeConfig?.title || "Boltdocs";
934
- const description = config.themeConfig?.description || "";
935
- const seoTags = [
936
- `<meta name="description" content="${description}">`,
937
- `<meta property="og:title" content="${title}">`,
938
- `<meta property="og:description" content="${description}">`,
939
- `<meta property="og:type" content="website">`,
940
- `<meta name="twitter:card" content="summary">`,
941
- `<meta name="twitter:title" content="${title}">`,
942
- `<meta name="twitter:description" content="${description}">`,
943
- `<meta name="generator" content="Boltdocs">`
944
- ].join("\n ");
945
- const themeScript = `
946
- <script>
947
- (function() {
948
- try {
949
- var stored = localStorage.getItem("boltdocs-theme");
950
- var theme = stored || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
951
- if (theme === "light") {
952
- document.documentElement.classList.add("theme-light");
953
- document.documentElement.dataset.theme = "light";
954
- } else {
955
- document.documentElement.classList.remove("theme-light");
956
- document.documentElement.dataset.theme = "dark";
957
- }
958
- } catch (e) {}
959
- })();
960
- </script>
961
- `;
962
- html = html.replace(/<title>.*?<\/title>/, `<title>${title}</title>`);
963
- html = html.replace("</head>", ` ${seoTags}
964
- ${themeScript} </head>`);
965
- if (!html.includes("src/main")) {
966
- html = html.replace(
967
- "</body>",
968
- ' <script type="module">import "virtual:boltdocs-entry";</script>\n </body>'
969
- );
970
- }
971
- return html;
972
- }
973
-
974
- // src/node/plugin/index.ts
975
- function boltdocsPlugin(options = {}, passedConfig) {
976
- const docsDir = import_path6.default.resolve(process.cwd(), options.docsDir || "docs");
977
- const normalizedDocsDir = normalizePath(docsDir);
978
- let config = passedConfig;
979
- let viteConfig;
980
- let isBuild = false;
981
- const extraVitePlugins = config?.plugins?.flatMap((p) => p.vitePlugins || []) || [];
982
- return [
983
- {
984
- name: "vite-plugin-boltdocs",
985
- enforce: "pre",
986
- async config(userConfig, env) {
987
- isBuild = env.command === "build";
988
- const envDir = userConfig.envDir || process.cwd();
989
- const envs = (0, import_vite.loadEnv)(env.mode, envDir, "");
990
- Object.assign(process.env, envs);
991
- if (!config) {
992
- config = await resolveConfig(docsDir);
993
- }
994
- if (!options.customCss && config.themeConfig?.customCss) {
995
- options.customCss = config.themeConfig.customCss;
996
- }
997
- return {
998
- optimizeDeps: { include: ["react", "react-dom"] }
999
- };
1000
- },
1001
- configResolved(resolved) {
1002
- viteConfig = resolved;
1003
- },
1004
- configureServer(server) {
1005
- const configPaths = CONFIG_FILES.map(
1006
- (c) => import_path6.default.resolve(process.cwd(), c)
1007
- );
1008
- server.watcher.add(configPaths);
1009
- const handleFileEvent = async (file, type) => {
1010
- const normalized = normalizePath(file);
1011
- if (CONFIG_FILES.some((c) => normalized.endsWith(c))) {
1012
- server.restart();
1013
- return;
1014
- }
1015
- if (!normalized.startsWith(normalizedDocsDir) || !isDocFile(normalized))
1016
- return;
1017
- if (type === "add" || type === "unlink") {
1018
- invalidateRouteCache();
1019
- } else {
1020
- invalidateFile(file);
1021
- }
1022
- const newRoutes = await generateRoutes(docsDir, config);
1023
- const routesMod = server.moduleGraph.getModuleById(
1024
- "\0virtual:boltdocs-routes"
1025
- );
1026
- if (routesMod) server.moduleGraph.invalidateModule(routesMod);
1027
- server.ws.send({
1028
- type: "custom",
1029
- event: "boltdocs:routes-update",
1030
- data: newRoutes
1031
- });
1032
- };
1033
- server.watcher.on("add", (f) => handleFileEvent(f, "add"));
1034
- server.watcher.on("unlink", (f) => handleFileEvent(f, "unlink"));
1035
- server.watcher.on("change", (f) => handleFileEvent(f, "change"));
1036
- },
1037
- resolveId(id) {
1038
- if (id === "virtual:boltdocs-routes" || id === "virtual:boltdocs-config" || id === "virtual:boltdocs-entry") {
1039
- return "\0" + id;
1040
- }
1041
- },
1042
- async load(id) {
1043
- if (id === "\0virtual:boltdocs-routes") {
1044
- const routes = await generateRoutes(docsDir, config);
1045
- return `export default ${JSON.stringify(routes, null, 2)};`;
1046
- }
1047
- if (id === "\0virtual:boltdocs-config") {
1048
- const clientConfig = {
1049
- themeConfig: config?.themeConfig,
1050
- i18n: config?.i18n,
1051
- versions: config?.versions,
1052
- siteUrl: config?.siteUrl
1053
- };
1054
- return `export default ${JSON.stringify(clientConfig, null, 2)};`;
1055
- }
1056
- if (id === "\0virtual:boltdocs-entry") {
1057
- const code = generateEntryCode(options, config);
1058
- return code;
1059
- }
1060
- },
1061
- transformIndexHtml: {
1062
- order: "pre",
1063
- handler(html) {
1064
- return injectHtmlMeta(html, config);
1065
- }
1066
- },
1067
- async closeBundle() {
1068
- if (!isBuild) return;
1069
- const outDir = viteConfig?.build?.outDir ? import_path6.default.resolve(viteConfig.root, viteConfig.build.outDir) : import_path6.default.resolve(process.cwd(), "dist");
1070
- const docsDirName = import_path6.default.basename(docsDir || "docs");
1071
- await generateStaticPages({ docsDir, docsDirName, outDir, config });
1072
- const { flushCache: flushCache2 } = await Promise.resolve().then(() => (init_cache(), cache_exports));
1073
- await flushCache2();
1074
- }
1075
- },
1076
- (0, import_vite_plugin_image_optimizer.ViteImageOptimizer)({
1077
- includePublic: true,
1078
- png: { quality: 80 },
1079
- jpeg: { quality: 80 },
1080
- jpg: { quality: 80 },
1081
- webp: { quality: 80 },
1082
- avif: { quality: 80 },
1083
- svg: {
1084
- multipass: true,
1085
- plugins: [
1086
- {
1087
- name: "preset-default",
1088
- params: { overrides: { removeViewBox: false } }
1089
- }
1090
- ]
1091
- }
1092
- }),
1093
- ...extraVitePlugins.filter((p) => !!p)
1094
- ];
1095
- }
1096
-
1097
- // src/node/mdx.ts
1098
- var import_rollup = __toESM(require("@mdx-js/rollup"));
1099
- var import_remark_gfm = __toESM(require("remark-gfm"));
1100
- var import_remark_frontmatter = __toESM(require("remark-frontmatter"));
1101
- var import_rehype_slug = __toESM(require("rehype-slug"));
1102
- var import_rehype_pretty_code = __toESM(require("rehype-pretty-code"));
1103
- var import_crypto2 = __toESM(require("crypto"));
1104
- init_cache();
1105
- var mdxCache = new TransformCache("mdx");
1106
- var mdxCacheLoaded = false;
1107
- function boltdocsMdxPlugin(config, compiler = import_rollup.default) {
1108
- const extraRemarkPlugins = config?.plugins?.flatMap((p) => p.remarkPlugins || []) || [];
1109
- const extraRehypePlugins = config?.plugins?.flatMap((p) => p.rehypePlugins || []) || [];
1110
- const baseMdxPlugin = compiler({
1111
- remarkPlugins: [import_remark_gfm.default, import_remark_frontmatter.default, ...extraRemarkPlugins],
1112
- rehypePlugins: [
1113
- import_rehype_slug.default,
1114
- ...extraRehypePlugins,
1115
- [
1116
- import_rehype_pretty_code.default,
1117
- {
1118
- theme: config?.themeConfig?.codeTheme || "one-dark-pro",
1119
- keepBackground: false
1120
- }
1121
- ]
1122
- ],
1123
- jsxRuntime: "automatic",
1124
- providerImportSource: "@mdx-js/react"
1125
- });
1126
- if (baseMdxPlugin.isMock) {
1127
- console.log("MDX PLUGIN IS MOCKED");
1128
- }
1129
- return {
1130
- ...baseMdxPlugin,
1131
- name: "vite-plugin-boltdocs-mdx",
1132
- async buildStart() {
1133
- hits = 0;
1134
- total = 0;
1135
- if (!mdxCacheLoaded) {
1136
- mdxCache.load();
1137
- mdxCacheLoaded = true;
1138
- }
1139
- if (baseMdxPlugin.buildStart) {
1140
- await baseMdxPlugin.buildStart.call(this);
1141
- }
1142
- },
1143
- async transform(code, id, options) {
1144
- if (!id.endsWith(".md") && !id.endsWith(".mdx")) {
1145
- return baseMdxPlugin.transform?.call(this, code, id, options);
1146
- }
1147
- total++;
1148
- const contentHash = import_crypto2.default.createHash("md5").update(code).digest("hex");
1149
- const cacheKey = `${id}:${contentHash}`;
1150
- const cached = mdxCache.get(cacheKey);
1151
- if (cached) {
1152
- hits++;
1153
- return { code: cached, map: null };
1154
- }
1155
- const result = await baseMdxPlugin.transform.call(
1156
- this,
1157
- code,
1158
- id,
1159
- options
1160
- );
1161
- if (result && typeof result === "object" && result.code) {
1162
- mdxCache.set(cacheKey, result.code);
1163
- }
1164
- return result;
1165
- },
1166
- async buildEnd() {
1167
- mdxCache.save();
1168
- await mdxCache.flush();
1169
- if (baseMdxPlugin.buildEnd) {
1170
- await baseMdxPlugin.buildEnd.call(this);
1171
- }
1172
- }
1173
- };
1174
- }
1175
- var hits = 0;
1176
- var total = 0;
1177
-
1178
- // src/node/index.ts
1179
- async function boltdocs(options) {
1180
- const docsDir = options?.docsDir || "docs";
1181
- const config = await resolveConfig(docsDir);
1182
- return [...boltdocsPlugin(options, config), boltdocsMdxPlugin(config)];
1183
- }
1184
- // Annotate the CommonJS export names for ESM import in node:
1185
- 0 && (module.exports = {
1186
- generateStaticPages
1187
- });