igniteui-astro-components 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +374 -0
- package/package.json +109 -0
- package/src/components/DocsSidebar/DocsSidebar.astro +99 -0
- package/src/components/DocsSidebar/README.md +166 -0
- package/src/components/DocsSidebar/SidebarFilterInput.astro +74 -0
- package/src/components/DocsSidebar/SidebarLabel.astro +40 -0
- package/src/components/DocsSidebar/sidebar-filter.ts +393 -0
- package/src/components/DocsSidebar/toTreeNodes.ts +66 -0
- package/src/components/DocsSubHeader/DocsSubHeader.astro +320 -0
- package/src/components/DocsSubHeader/README.md +74 -0
- package/src/components/DocsToc/DocsToc.astro +307 -0
- package/src/components/DocsToc/README.md +68 -0
- package/src/components/DocsToc/toTreeNodes.ts +57 -0
- package/src/components/DocsTree/DocsTree.astro +66 -0
- package/src/components/DocsTree/DocsTreeItem.astro +84 -0
- package/src/components/DocsTree/README.md +105 -0
- package/src/components/DocsTree/docs-tree.css +227 -0
- package/src/components/DocsTree/types.ts +47 -0
- package/src/components/GlobalFooter/GlobalFooter.astro +90 -0
- package/src/components/GlobalFooter/GlobalFooter.module.scss +23 -0
- package/src/components/GlobalFooter/README.md +35 -0
- package/src/components/GlobalNavBar/GlobalNavBar.astro +218 -0
- package/src/components/GlobalNavBar/GlobalNavBar.module.scss +215 -0
- package/src/components/GlobalNavBar/README.md +49 -0
- package/src/components/MobileSidebarToggle/MobileSidebarToggle.astro +112 -0
- package/src/components/MobileSidebarToggle/README.md +31 -0
- package/src/components/Search/README.md +43 -0
- package/src/components/Search/Search.astro +222 -0
- package/src/components/ThemingWidget/README.md +35 -0
- package/src/components/ThemingWidget/ThemingWidget.astro +152 -0
- package/src/components/mdx/ApiLink/ApiLink.astro +121 -0
- package/src/components/mdx/ApiLink/README.md +68 -0
- package/src/components/mdx/ApiRef/ApiRef.astro +92 -0
- package/src/components/mdx/ApiRef/README.md +50 -0
- package/src/components/mdx/DocsAside/DocsAside.astro +86 -0
- package/src/components/mdx/DocsAside/README.md +66 -0
- package/src/components/mdx/DocsAside/icons/caution.svg +3 -0
- package/src/components/mdx/DocsAside/icons/danger.svg +3 -0
- package/src/components/mdx/DocsAside/icons/note.svg +3 -0
- package/src/components/mdx/DocsAside/icons/tip.svg +4 -0
- package/src/components/mdx/PlatformBlock/PlatformBlock.astro +24 -0
- package/src/components/mdx/PlatformBlock/README.md +57 -0
- package/src/components/mdx/Sample/README.md +59 -0
- package/src/components/mdx/Sample/Sample.astro +142 -0
- package/src/content-helper.ts +159 -0
- package/src/content.config.ts +17 -0
- package/src/index.ts +42 -0
- package/src/integration.ts +841 -0
- package/src/layouts/DocsLayout/DocsLayout.astro +307 -0
- package/src/layouts/DocsLayout/README.md +124 -0
- package/src/lib/nav-helpers.ts +155 -0
- package/src/lib/platform-context.ts +305 -0
- package/src/lib/sidebar/helpers.ts +81 -0
- package/src/lib/sidebar/types.ts +36 -0
- package/src/llms.ts +315 -0
- package/src/platform.ts +281 -0
- package/src/plugins/remark-docfx.ts +368 -0
- package/src/scripts/sample-widget.ts +516 -0
- package/src/sidebar.ts +167 -0
- package/src/styles/custom.scss +254 -0
- package/src/styles/ig-theme.scss +43 -0
- package/src/virtual-modules.d.ts +35 -0
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* integration.ts
|
|
3
|
+
*
|
|
4
|
+
* Shared configuration helpers for Astro + Starlight docs sites.
|
|
5
|
+
* All functions are independently usable; `createDocsSite` is the
|
|
6
|
+
* convenience wrapper that composes them all.
|
|
7
|
+
*
|
|
8
|
+
* --- Option A: one-liner config (recommended for standard setups) ---
|
|
9
|
+
*
|
|
10
|
+
* import { createDocsSite } from 'docs-template/integration';
|
|
11
|
+
*
|
|
12
|
+
* export default createDocsSite({
|
|
13
|
+
* site: 'https://my-org.github.io/my-docs',
|
|
14
|
+
* title: 'My Library',
|
|
15
|
+
* description: 'Reference docs for My Library.',
|
|
16
|
+
* platform: 'angular', // drives CDN head entries + nav prefetch
|
|
17
|
+
* navLang: 'en', // 'en' | 'jp' | 'kr'
|
|
18
|
+
* source: {
|
|
19
|
+
* tocPath: './my-docs/toc.yml',
|
|
20
|
+
* docsDir: './my-docs/en/components',
|
|
21
|
+
* imagesDir: './my-docs/en/images', // omit to skip image serving
|
|
22
|
+
* },
|
|
23
|
+
* sidebar: { exclude: [/^internal\//] }, // optional TOC excludes
|
|
24
|
+
* head: [ // extra <head> entries after platform ones
|
|
25
|
+
* { tag: 'link', attrs: { rel: 'stylesheet', href: '...' } },
|
|
26
|
+
* ],
|
|
27
|
+
* // Extra Starlight options (logo, social, editLink, customCss, …)
|
|
28
|
+
* starlight: {
|
|
29
|
+
* logo: { src: './public/favicon.svg' },
|
|
30
|
+
* },
|
|
31
|
+
* // Extra Astro options (markdown, image, build, …)
|
|
32
|
+
* markdown: { remarkPlugins: [] },
|
|
33
|
+
* });
|
|
34
|
+
*
|
|
35
|
+
* --- Option B: manual composition (for full control) ---
|
|
36
|
+
*
|
|
37
|
+
* import { buildSidebarFromToc, staticImagesIntegration, siteMetaIntegration } from 'docs-template/integration';
|
|
38
|
+
*
|
|
39
|
+
* const sidebar = buildSidebarFromToc({ tocPath, docsDir });
|
|
40
|
+
*
|
|
41
|
+
* export default defineConfig({
|
|
42
|
+
* integrations: [
|
|
43
|
+
* siteMetaIntegration({ title: 'My Library', description: 'Reference docs.' }),
|
|
44
|
+
* starlight({ sidebar }),
|
|
45
|
+
* staticImagesIntegration('/abs/path/to/my-docs/images'),
|
|
46
|
+
* ],
|
|
47
|
+
* });
|
|
48
|
+
*
|
|
49
|
+
* Generated output:
|
|
50
|
+
* /llms.txt — manifest listing every page with its .md URL
|
|
51
|
+
* /{slug}.md — raw markdown for each page (env-vars substituted)
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
import fs from 'node:fs';
|
|
55
|
+
import fsp from 'node:fs/promises';
|
|
56
|
+
import path from 'node:path';
|
|
57
|
+
import { createIndex as pagefindCreateIndex } from 'pagefind';
|
|
58
|
+
import { fileURLToPath } from 'node:url';
|
|
59
|
+
import { defineConfig } from 'astro/config';
|
|
60
|
+
import type { AstroIntegration } from 'astro';
|
|
61
|
+
import mdx from '@astrojs/mdx';
|
|
62
|
+
import {
|
|
63
|
+
buildLlmsTxt, buildLlmsMetaMap, getBroadSectionsForPlatform, toUrlSlug,
|
|
64
|
+
type LlmsMeta, type LlmsSet, type SidebarItem,
|
|
65
|
+
} from './llms.ts';
|
|
66
|
+
import { buildSidebarFromToc } from './sidebar';
|
|
67
|
+
import { getNavConfig, getPlatformHead } from './platform';
|
|
68
|
+
import type { HeadEntry, PlatformKey, NavLang } from './platform.ts';
|
|
69
|
+
import { remarkDocfx, rehypeCodeView } from './plugins/remark-docfx';
|
|
70
|
+
import { stripScripts, absolutifyNavUrls, extractOuterHtml } from './lib/nav-helpers.ts';
|
|
71
|
+
|
|
72
|
+
/** Build / deployment mode. Drives env-var `DOCS_BUILD_MODE`. */
|
|
73
|
+
export type DocsMode = 'development' | 'staging' | 'production';
|
|
74
|
+
|
|
75
|
+
/** Module-level cache so the nav URL is fetched at most once per build. */
|
|
76
|
+
let _navHtmlCache: string | null = null;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Read `themeApiUrl` and `themingWidgetVersion` from the project's
|
|
80
|
+
* environment.json at build time. Mirrors the lookup order in remark-docfx.ts
|
|
81
|
+
* so both always resolve from the same file.
|
|
82
|
+
*/
|
|
83
|
+
function readThemingEnv(sourcePath: string | undefined, envKey: string): {
|
|
84
|
+
themeApiUrl: string;
|
|
85
|
+
widgetVersion: string;
|
|
86
|
+
} {
|
|
87
|
+
if (!sourcePath) return { themeApiUrl: '', widgetVersion: 'latest' };
|
|
88
|
+
const root = path.resolve(sourcePath);
|
|
89
|
+
const parent = path.dirname(root);
|
|
90
|
+
const candidates = [
|
|
91
|
+
path.join(root, 'en', 'environment.json'),
|
|
92
|
+
path.join(root, 'environment.json'),
|
|
93
|
+
path.join(parent, 'environment.json'),
|
|
94
|
+
path.join(parent, 'en', 'environment.json'),
|
|
95
|
+
];
|
|
96
|
+
const envPath = candidates.find(c => fs.existsSync(c));
|
|
97
|
+
if (!envPath) return { themeApiUrl: '', widgetVersion: 'latest' };
|
|
98
|
+
try {
|
|
99
|
+
const data = JSON.parse(fs.readFileSync(envPath, 'utf-8'));
|
|
100
|
+
const env = data[envKey] ?? data.production ?? {};
|
|
101
|
+
return {
|
|
102
|
+
themeApiUrl: (env.themeApiUrl as string) ?? '',
|
|
103
|
+
widgetVersion: (env.themingWidgetVersion as string) ?? 'latest',
|
|
104
|
+
};
|
|
105
|
+
} catch {
|
|
106
|
+
return { themeApiUrl: '', widgetVersion: 'latest' };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// Site meta virtual module
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
export interface ProductLink {
|
|
115
|
+
/** Display label shown in the DocsSubHeader, e.g. `"Angular"`. */
|
|
116
|
+
label: string;
|
|
117
|
+
/** Absolute or root-relative href to the sibling docs site. */
|
|
118
|
+
href: string;
|
|
119
|
+
/**
|
|
120
|
+
* Optional platform key (matches `PlatformKey`).
|
|
121
|
+
* When it equals the current build's platform the link is omitted from the DocsSubHeader.
|
|
122
|
+
*/
|
|
123
|
+
platform?: PlatformKey;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface SiteMetaOptions {
|
|
127
|
+
title: string;
|
|
128
|
+
description?: string;
|
|
129
|
+
/** Path to the source markdown files. */
|
|
130
|
+
docsDir?: string;
|
|
131
|
+
sidebar?: SidebarItem[];
|
|
132
|
+
platform?: PlatformKey | null;
|
|
133
|
+
navLang?: NavLang;
|
|
134
|
+
/** Build / deployment mode. Exposed via `process.env.DOCS_BUILD_MODE`. */
|
|
135
|
+
mode?: DocsMode;
|
|
136
|
+
/** Named documentation subsets linked from llms.txt. */
|
|
137
|
+
llmsSets?: LlmsSet[];
|
|
138
|
+
/** Cross-product navigation links rendered in the DocsSubHeader. */
|
|
139
|
+
productLinks?: ProductLink[];
|
|
140
|
+
/**
|
|
141
|
+
* Extra `<head>` entries injected via the `virtual:docs-template/site-meta`
|
|
142
|
+
* module and rendered by `DocsLayout.astro`.
|
|
143
|
+
*/
|
|
144
|
+
head?: HeadEntry[];
|
|
145
|
+
/** @deprecated Use `platform` instead. */
|
|
146
|
+
prefetchNav?: boolean;
|
|
147
|
+
/** @deprecated Use `platform: 'appbuilder'` instead. */
|
|
148
|
+
prefetchAppBuilderNav?: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Strip MDX-specific syntax from a source file so the `.md` endpoint
|
|
153
|
+
* served to LLM crawlers contains clean markdown instead of JSX.
|
|
154
|
+
*
|
|
155
|
+
* Removes:
|
|
156
|
+
* - `import … from '…'` lines at the top of the file
|
|
157
|
+
* - Self-closing JSX components: <Sample …/>, <ApiRef …/>, <ApiLink …/>
|
|
158
|
+
* - Block JSX components: <ApiRef …>…</ApiRef>
|
|
159
|
+
* - Inline <style>{`…`}</style> blocks
|
|
160
|
+
*/
|
|
161
|
+
function stripMdxForLlms(raw: string): string {
|
|
162
|
+
return raw
|
|
163
|
+
// Remove all import lines
|
|
164
|
+
.replace(/^import\s+.+from\s+['"][^'"]+['"];?\r?\n/gm, '')
|
|
165
|
+
// Remove <style>{`...`}</style> blocks (multiline)
|
|
166
|
+
.replace(/<style>\{`[\s\S]*?`\}<\/style>\s*/g, '')
|
|
167
|
+
// Remove self-closing components: <Sample … />, <ApiRef … />, <ApiLink … />
|
|
168
|
+
.replace(/<(Sample|ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*\/>\s*/g, '')
|
|
169
|
+
// Remove paired components: <ApiRef …>…</ApiRef>
|
|
170
|
+
.replace(/<(ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*>[\s\S]*?<\/\1>\s*/g, '')
|
|
171
|
+
// Collapse 3+ blank lines left behind into 2
|
|
172
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
173
|
+
.trim() + '\n';
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Astro integration that exposes site metadata as the virtual module
|
|
178
|
+
* `virtual:docs-template/site-meta` and generates /llms.txt at build time.
|
|
179
|
+
*/
|
|
180
|
+
export function siteMetaIntegration({
|
|
181
|
+
title,
|
|
182
|
+
description = '',
|
|
183
|
+
docsDir,
|
|
184
|
+
sidebar,
|
|
185
|
+
platform = null,
|
|
186
|
+
navLang = 'en',
|
|
187
|
+
mode = 'development',
|
|
188
|
+
llmsSets = [],
|
|
189
|
+
productLinks = [],
|
|
190
|
+
head = [],
|
|
191
|
+
prefetchNav = false,
|
|
192
|
+
prefetchAppBuilderNav = false,
|
|
193
|
+
}: SiteMetaOptions = {} as SiteMetaOptions): AstroIntegration {
|
|
194
|
+
const llmsMetaMap = docsDir
|
|
195
|
+
? buildLlmsMetaMap(docsDir, sidebar ?? [])
|
|
196
|
+
: new Map<string, LlmsMeta>();
|
|
197
|
+
|
|
198
|
+
const virtualId = 'virtual:docs-template/site-meta';
|
|
199
|
+
const resolvedId = '\0' + virtualId;
|
|
200
|
+
|
|
201
|
+
const navVirtualId = 'virtual:docs-template/nav-html';
|
|
202
|
+
const navResolvedId = '\0' + navVirtualId;
|
|
203
|
+
|
|
204
|
+
// Resolve effective platform: explicit `platform` option wins; fall back to
|
|
205
|
+
// deprecated boolean flags for backwards compatibility.
|
|
206
|
+
const effectivePlatform: PlatformKey | null =
|
|
207
|
+
platform ??
|
|
208
|
+
(prefetchAppBuilderNav ? 'appbuilder' : null) ??
|
|
209
|
+
(prefetchNav ? 'angular' : null);
|
|
210
|
+
|
|
211
|
+
const { navType, navUrl } = getNavConfig(effectivePlatform, navLang);
|
|
212
|
+
|
|
213
|
+
// Navigation buckets for this platform — stripped from ancestor paths during label generation.
|
|
214
|
+
const broadSections = getBroadSectionsForPlatform(effectivePlatform);
|
|
215
|
+
const moduleCode = `export const title = ${JSON.stringify(title)};
|
|
216
|
+
export const sidebar = ${JSON.stringify(sidebar ?? [])};
|
|
217
|
+
export const productLinks = ${JSON.stringify(productLinks)};
|
|
218
|
+
export const headEntries = ${JSON.stringify(head ?? [])};
|
|
219
|
+
`;
|
|
220
|
+
|
|
221
|
+
// Captured from astro:config:done; used to generate llms.txt content.
|
|
222
|
+
let configuredSite = '';
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
name: 'docs-template:site-meta',
|
|
226
|
+
hooks: {
|
|
227
|
+
'astro:config:done'({ config }) {
|
|
228
|
+
configuredSite = (config.site?.toString() ?? '').replace(/\/$/, '');
|
|
229
|
+
},
|
|
230
|
+
'astro:config:setup'({ updateConfig, injectRoute }) {
|
|
231
|
+
injectRoute({
|
|
232
|
+
pattern: '/sitemap.xml',
|
|
233
|
+
entrypoint: fileURLToPath(new URL('./routes/sitemap.xml.ts', import.meta.url)),
|
|
234
|
+
prerender: true,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// Inject the dynamic doc-page route so consuming projects don't
|
|
238
|
+
// need their own [...slug].astro. Project pages take priority over
|
|
239
|
+
// injected routes, so the template's own src/pages/[...slug].astro
|
|
240
|
+
// still wins when the template is used standalone.
|
|
241
|
+
injectRoute({
|
|
242
|
+
pattern: '/[...slug]',
|
|
243
|
+
entrypoint: fileURLToPath(new URL('./routes/[...slug].astro', import.meta.url)),
|
|
244
|
+
prerender: true,
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// Vite alias: redirect @astrojs/starlight/components to our compat shim so
|
|
248
|
+
// MDX files that import Starlight UI components continue to build without the
|
|
249
|
+
// Starlight integration being active.
|
|
250
|
+
const compatIndex = fileURLToPath(new URL('./compat/starlight-components/index.ts', import.meta.url));
|
|
251
|
+
updateConfig({
|
|
252
|
+
vite: {
|
|
253
|
+
resolve: {
|
|
254
|
+
alias: [
|
|
255
|
+
{ find: '@astrojs/starlight/components', replacement: compatIndex },
|
|
256
|
+
],
|
|
257
|
+
},
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
// Configure Sass loadPaths so bare `highlight.js/scss/vs2015`
|
|
262
|
+
// imports in the platform theme files resolve from node_modules.
|
|
263
|
+
updateConfig({
|
|
264
|
+
vite: {
|
|
265
|
+
css: {
|
|
266
|
+
preprocessorOptions: {
|
|
267
|
+
scss: {
|
|
268
|
+
loadPaths: [path.join(process.cwd(), 'node_modules')],
|
|
269
|
+
// The if-function deprecation originates inside
|
|
270
|
+
// igniteui-theming (vendor code we cannot modify).
|
|
271
|
+
silenceDeprecations: ['if-function'],
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
updateConfig({
|
|
278
|
+
vite: {
|
|
279
|
+
plugins: [{
|
|
280
|
+
name: 'vite-plugin-docs-template-site-meta',
|
|
281
|
+
resolveId(id: string) {
|
|
282
|
+
if (id === virtualId) return resolvedId;
|
|
283
|
+
if (id === navVirtualId) return navResolvedId;
|
|
284
|
+
},
|
|
285
|
+
async load(id: string) {
|
|
286
|
+
if (id === resolvedId) return moduleCode;
|
|
287
|
+
if (id !== navResolvedId) return;
|
|
288
|
+
|
|
289
|
+
// Return cached module code — fetched at most once per build.
|
|
290
|
+
if (_navHtmlCache) return _navHtmlCache;
|
|
291
|
+
|
|
292
|
+
// ── Theming env ──────────────────────────────────────────────
|
|
293
|
+
const envKey = process.env.DOCS_ENV ?? process.env.NODE_ENV ?? 'production';
|
|
294
|
+
const { themeApiUrl, widgetVersion } = readThemingEnv(process.env.DOCS_SOURCE_PATH, envKey);
|
|
295
|
+
const widgetScriptSrc = widgetVersion
|
|
296
|
+
? `https://cdn-na.infragistics.com/igniteui/theming-widget/${widgetVersion}/igniteui-theming-widget.js`
|
|
297
|
+
: '';
|
|
298
|
+
|
|
299
|
+
let headerHtml = '';
|
|
300
|
+
let uiFooterHtml = '';
|
|
301
|
+
let footerHtml = '';
|
|
302
|
+
|
|
303
|
+
// ── IG nav prefetch ──────────────────────────────────────────
|
|
304
|
+
if (navType === 'infragistics' && navUrl) {
|
|
305
|
+
try {
|
|
306
|
+
const res = await fetch(navUrl, {
|
|
307
|
+
credentials: 'omit',
|
|
308
|
+
signal: AbortSignal.timeout(15_000),
|
|
309
|
+
});
|
|
310
|
+
if (res.ok) {
|
|
311
|
+
const html = await res.text();
|
|
312
|
+
const igBase = navLang === 'jp' ? 'https://jp.infragistics.com' : 'https://www.infragistics.com';
|
|
313
|
+
headerHtml = absolutifyNavUrls(stripScripts(extractOuterHtml(html, '<header[^>]+id="header"')), igBase);
|
|
314
|
+
uiFooterHtml = absolutifyNavUrls(stripScripts(extractOuterHtml(html, '<footer[^>]+class="[^"]*\\bui-footer\\b')), igBase);
|
|
315
|
+
footerHtml = absolutifyNavUrls(stripScripts(extractOuterHtml(html, '<footer[^>]+id="footer"')), igBase);
|
|
316
|
+
// Strip the hello-bar promotional strip
|
|
317
|
+
headerHtml = headerHtml.replace(
|
|
318
|
+
/<div[^>]+id="hello-bar"[\s\S]*?<\/div>\s*/i, ''
|
|
319
|
+
);
|
|
320
|
+
} else {
|
|
321
|
+
console.warn(`[docs-template] Navigation fetch returned ${res.status} — falling back to empty markup.`);
|
|
322
|
+
}
|
|
323
|
+
} catch (err: unknown) {
|
|
324
|
+
console.warn(`[docs-template] Could not fetch navigation HTML: ${(err as Error).message} — falling back to empty markup.`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ── AppBuilder nav prefetch ──────────────────────────────────
|
|
329
|
+
let abHeaderHtml = '';
|
|
330
|
+
let abFooterHtml = '';
|
|
331
|
+
let abFooterUtilsHtml = '';
|
|
332
|
+
let abFooterCopyrightHtml = '';
|
|
333
|
+
let abContactSalesHtml = '';
|
|
334
|
+
|
|
335
|
+
if (navType === 'appbuilder' && navUrl) {
|
|
336
|
+
try {
|
|
337
|
+
const abRes = await fetch(navUrl, {
|
|
338
|
+
credentials: 'omit',
|
|
339
|
+
signal: AbortSignal.timeout(15_000),
|
|
340
|
+
});
|
|
341
|
+
if (abRes.ok) {
|
|
342
|
+
const abRaw = await abRes.text();
|
|
343
|
+
// Endpoint may return JSON { header, footer } or a full HTML page.
|
|
344
|
+
let parsed = false;
|
|
345
|
+
try {
|
|
346
|
+
const data = JSON.parse(abRaw) as { header?: string; footer?: string };
|
|
347
|
+
if (data.header || data.footer) {
|
|
348
|
+
abHeaderHtml = data.header ?? '';
|
|
349
|
+
abFooterHtml = data.footer ?? '';
|
|
350
|
+
parsed = true;
|
|
351
|
+
}
|
|
352
|
+
} catch { /* not JSON — fall through to HTML extraction */ }
|
|
353
|
+
|
|
354
|
+
if (!parsed) {
|
|
355
|
+
abHeaderHtml = extractOuterHtml(abRaw, '<header');
|
|
356
|
+
abFooterHtml = extractOuterHtml(abRaw, '<footer');
|
|
357
|
+
abFooterUtilsHtml = extractOuterHtml(abRaw, '<[a-z][a-z0-9]*[^>]+class="[^"]*\\bfooter-utils\\b');
|
|
358
|
+
abFooterCopyrightHtml = extractOuterHtml(abRaw, '<[a-z][a-z0-9]*[^>]+class="[^"]*\\bfooter-copyright\\b');
|
|
359
|
+
abContactSalesHtml = extractOuterHtml(abRaw, '<[a-z][a-z0-9]*[^>]+id="contactSales"');
|
|
360
|
+
}
|
|
361
|
+
} else {
|
|
362
|
+
console.warn(`[docs-template] AppBuilder nav fetch returned ${abRes.status} — falling back to runtime loading.`);
|
|
363
|
+
}
|
|
364
|
+
} catch (err: unknown) {
|
|
365
|
+
console.warn(`[docs-template] Could not prefetch AppBuilder navigation: ${(err as Error).message} — falling back to runtime loading.`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
_navHtmlCache = [
|
|
370
|
+
`export const platform = ${JSON.stringify(effectivePlatform ?? null)};`,
|
|
371
|
+
`export const navLang = ${JSON.stringify(navLang)};`,
|
|
372
|
+
`export const themeApiUrl = ${JSON.stringify(themeApiUrl)};`,
|
|
373
|
+
`export const widgetScriptSrc = ${JSON.stringify(widgetScriptSrc)};`,
|
|
374
|
+
`export const prefetched = ${JSON.stringify(!!headerHtml)};`,
|
|
375
|
+
`export const headerHtml = ${JSON.stringify(headerHtml)};`,
|
|
376
|
+
`export const uiFooterHtml = ${JSON.stringify(uiFooterHtml)};`,
|
|
377
|
+
`export const footerHtml = ${JSON.stringify(footerHtml)};`,
|
|
378
|
+
`export const abPrefetched = ${JSON.stringify(!!abHeaderHtml)};`,
|
|
379
|
+
`export const abHeaderHtml = ${JSON.stringify(abHeaderHtml)};`,
|
|
380
|
+
`export const abFooterHtml = ${JSON.stringify(abFooterHtml)};`,
|
|
381
|
+
`export const abFooterUtilsHtml = ${JSON.stringify(abFooterUtilsHtml)};`,
|
|
382
|
+
`export const abFooterCopyrightHtml = ${JSON.stringify(abFooterCopyrightHtml)};`,
|
|
383
|
+
`export const abContactSalesHtml = ${JSON.stringify(abContactSalesHtml)};`,
|
|
384
|
+
].join('\n');
|
|
385
|
+
return _navHtmlCache;
|
|
386
|
+
},
|
|
387
|
+
}],
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
},
|
|
391
|
+
|
|
392
|
+
'astro:server:setup'({ server }) {
|
|
393
|
+
if (!docsDir) return;
|
|
394
|
+
server.middlewares.use(async (req, res, next) => {
|
|
395
|
+
// Only handle requests ending in .md
|
|
396
|
+
if (!req.url?.endsWith('.md')) return next();
|
|
397
|
+
// Strip leading slash and .md suffix to get the slug
|
|
398
|
+
const slug = req.url.slice(1, -3);
|
|
399
|
+
for (const ext of ['.md', '.mdx']) {
|
|
400
|
+
const src = path.join(docsDir, slug + ext);
|
|
401
|
+
try {
|
|
402
|
+
const raw = await fsp.readFile(src, 'utf-8');
|
|
403
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
404
|
+
res.end(raw);
|
|
405
|
+
return;
|
|
406
|
+
} catch { /* try next extension */ }
|
|
407
|
+
}
|
|
408
|
+
next();
|
|
409
|
+
});
|
|
410
|
+
},
|
|
411
|
+
|
|
412
|
+
async 'astro:build:done'({ dir, pages }) {
|
|
413
|
+
const outDir = fileURLToPath(dir);
|
|
414
|
+
|
|
415
|
+
// Copy package scripts to the build output /scripts/ directory.
|
|
416
|
+
const pkgScripts = fileURLToPath(new URL('../public/scripts', import.meta.url));
|
|
417
|
+
if (fs.existsSync(pkgScripts)) copyDirSync(pkgScripts, path.join(outDir, 'scripts'));
|
|
418
|
+
|
|
419
|
+
// Write our custom llms.txt after all rendering — always wins over plugin output.
|
|
420
|
+
const llmsContent = buildLlmsTxt(configuredSite, title, description, sidebar ?? [], llmsMetaMap, llmsSets, broadSections);
|
|
421
|
+
await fsp.writeFile(path.join(outDir, 'llms.txt'), llmsContent, 'utf-8');
|
|
422
|
+
|
|
423
|
+
if (!docsDir) return;
|
|
424
|
+
|
|
425
|
+
// pages[].pathname is like "accordion/" or "charts/chart-api/" — strip trailing slash.
|
|
426
|
+
const slugs = pages
|
|
427
|
+
.map(p => p.pathname.replace(/\/$/, ''))
|
|
428
|
+
.filter(s => s && s !== '404' && s !== 'index');
|
|
429
|
+
|
|
430
|
+
await Promise.all(
|
|
431
|
+
slugs.map(async (slug) => {
|
|
432
|
+
for (const ext of ['.md', '.mdx']) {
|
|
433
|
+
const src = path.join(docsDir, slug + ext);
|
|
434
|
+
try {
|
|
435
|
+
const raw = await fsp.readFile(src, 'utf-8');
|
|
436
|
+
const dest = path.join(outDir, slug + '.md');
|
|
437
|
+
await fsp.mkdir(path.dirname(dest), { recursive: true });
|
|
438
|
+
await fsp.writeFile(dest, stripMdxForLlms(raw), 'utf-8');
|
|
439
|
+
break;
|
|
440
|
+
} catch { /* try next extension */ }
|
|
441
|
+
}
|
|
442
|
+
})
|
|
443
|
+
);
|
|
444
|
+
|
|
445
|
+
// ── llms-full.txt / llms-small.txt ──────────────────────────────────
|
|
446
|
+
// Read back the already-written per-page .md files and combine them.
|
|
447
|
+
const pageTexts = (
|
|
448
|
+
await Promise.all(
|
|
449
|
+
slugs.map(async (slug) => {
|
|
450
|
+
try {
|
|
451
|
+
return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
|
|
452
|
+
} catch { return ''; }
|
|
453
|
+
})
|
|
454
|
+
)
|
|
455
|
+
).filter(Boolean);
|
|
456
|
+
|
|
457
|
+
const fullContent = pageTexts.join('\n\n---\n\n');
|
|
458
|
+
await fsp.writeFile(path.join(outDir, 'llms-full.txt'), fullContent, 'utf-8');
|
|
459
|
+
|
|
460
|
+
// Small variant: strip fenced code blocks and inline code.
|
|
461
|
+
const smallContent = fullContent
|
|
462
|
+
.replace(/^```[\s\S]*?^```/gm, '')
|
|
463
|
+
.replace(/`[^`\n]+`/g, '')
|
|
464
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
465
|
+
.trim();
|
|
466
|
+
await fsp.writeFile(path.join(outDir, 'llms-small.txt'), smallContent, 'utf-8');
|
|
467
|
+
|
|
468
|
+
// ── /_llms-txt/{set-slug}.txt ────────────────────────────────────────
|
|
469
|
+
if (llmsSets.length > 0) {
|
|
470
|
+
const llmsTxtDir = path.join(outDir, '_llms-txt');
|
|
471
|
+
await fsp.mkdir(llmsTxtDir, { recursive: true });
|
|
472
|
+
|
|
473
|
+
await Promise.all(
|
|
474
|
+
llmsSets.map(async (set) => {
|
|
475
|
+
const matchingSlugs = slugs.filter((slug) =>
|
|
476
|
+
set.paths.some((pattern) => {
|
|
477
|
+
if (pattern.endsWith('*')) {
|
|
478
|
+
return slug.startsWith(pattern.slice(0, -1));
|
|
479
|
+
}
|
|
480
|
+
return slug === pattern || slug.startsWith(pattern + '/');
|
|
481
|
+
})
|
|
482
|
+
);
|
|
483
|
+
|
|
484
|
+
const setText = (
|
|
485
|
+
await Promise.all(
|
|
486
|
+
matchingSlugs.map(async (slug) => {
|
|
487
|
+
try {
|
|
488
|
+
return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
|
|
489
|
+
} catch { return ''; }
|
|
490
|
+
})
|
|
491
|
+
)
|
|
492
|
+
).filter(Boolean).join('\n\n---\n\n');
|
|
493
|
+
|
|
494
|
+
await fsp.writeFile(
|
|
495
|
+
path.join(llmsTxtDir, toUrlSlug(set.label) + '.txt'),
|
|
496
|
+
setText,
|
|
497
|
+
'utf-8',
|
|
498
|
+
);
|
|
499
|
+
})
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// Run pagefind to generate the search index from the built HTML.
|
|
504
|
+
// The index is written to <outDir>/pagefind/ and served statically.
|
|
505
|
+
console.log('[docs-template] Running pagefind…');
|
|
506
|
+
try {
|
|
507
|
+
const { index, errors: initErrors } = await pagefindCreateIndex({});
|
|
508
|
+
if (initErrors?.length) throw new Error(initErrors.join(', '));
|
|
509
|
+
const { errors: addErrors } = await index!.addDirectory({ path: outDir });
|
|
510
|
+
if (addErrors?.length) console.warn('[docs-template] pagefind addDirectory warnings:', addErrors);
|
|
511
|
+
const { errors: writeErrors } = await index!.writeFiles({
|
|
512
|
+
outputPath: path.join(outDir, 'pagefind'),
|
|
513
|
+
});
|
|
514
|
+
if (writeErrors?.length) console.warn('[docs-template] pagefind writeFiles warnings:', writeErrors);
|
|
515
|
+
console.log('[docs-template] pagefind index written.');
|
|
516
|
+
} catch (err) {
|
|
517
|
+
console.warn('[docs-template] pagefind failed — search index will be unavailable.', err);
|
|
518
|
+
}
|
|
519
|
+
},
|
|
520
|
+
},
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export { buildSidebarFromToc };
|
|
525
|
+
export type { LlmsMeta, LlmsSet } from './llms.ts';
|
|
526
|
+
|
|
527
|
+
// ---------------------------------------------------------------------------
|
|
528
|
+
// Static images integration
|
|
529
|
+
// ---------------------------------------------------------------------------
|
|
530
|
+
|
|
531
|
+
const MIME: Record<string, string> = {
|
|
532
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
|
533
|
+
gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',
|
|
534
|
+
avif: 'image/avif', ico: 'image/x-icon',
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
function copyDirSync(src: string, dest: string): void {
|
|
538
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
539
|
+
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
540
|
+
const s = path.join(src, entry.name);
|
|
541
|
+
const d = path.join(dest, entry.name);
|
|
542
|
+
if (entry.isDirectory()) copyDirSync(s, d);
|
|
543
|
+
else fs.copyFileSync(s, d);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Astro integration that serves a local images directory during development
|
|
549
|
+
* (via Vite middleware) and copies it to the build output.
|
|
550
|
+
*
|
|
551
|
+
* @param imagesDir - Absolute path to the directory of images to serve.
|
|
552
|
+
* @param options.urlPath - URL prefix under which images are served (default `'/images'`).
|
|
553
|
+
*/
|
|
554
|
+
export function staticImagesIntegration(
|
|
555
|
+
imagesDir: string,
|
|
556
|
+
{ urlPath = '/images' }: { urlPath?: string } = {},
|
|
557
|
+
): AstroIntegration {
|
|
558
|
+
return {
|
|
559
|
+
name: 'static-images',
|
|
560
|
+
hooks: {
|
|
561
|
+
'astro:server:setup'({ server }) {
|
|
562
|
+
server.middlewares.use(urlPath, (req, res, next) => {
|
|
563
|
+
// Extract path (no query string)
|
|
564
|
+
const rawUrl = req.url || '/';
|
|
565
|
+
const requestPath = rawUrl.split('?', 1)[0] || '/';
|
|
566
|
+
// Decode URL component; reject malformed encodings
|
|
567
|
+
let decodedPath: string;
|
|
568
|
+
try {
|
|
569
|
+
decodedPath = decodeURIComponent(requestPath);
|
|
570
|
+
} catch {
|
|
571
|
+
return next();
|
|
572
|
+
}
|
|
573
|
+
// Build absolute file path and ensure it stays within imagesDir
|
|
574
|
+
const basePath = path.resolve(imagesDir);
|
|
575
|
+
const relativePath = decodedPath.replace(/^\/+/, '');
|
|
576
|
+
const filePath = path.resolve(path.join(basePath, relativePath));
|
|
577
|
+
// Prevent path traversal outside of imagesDir
|
|
578
|
+
if (filePath !== basePath && !filePath.startsWith(basePath + path.sep)) {
|
|
579
|
+
return next();
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
if (fs.statSync(filePath).isFile()) {
|
|
583
|
+
const ext = path.extname(filePath).slice(1).toLowerCase();
|
|
584
|
+
res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
|
|
585
|
+
fs.createReadStream(filePath).pipe(res);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
} catch {
|
|
589
|
+
/* file not found — fall through */
|
|
590
|
+
}
|
|
591
|
+
next();
|
|
592
|
+
});
|
|
593
|
+
},
|
|
594
|
+
async 'astro:build:done'({ dir }) {
|
|
595
|
+
const destImages = path.join(fileURLToPath(dir), urlPath.replace(/^\//, ''));
|
|
596
|
+
copyDirSync(imagesDir, destImages);
|
|
597
|
+
},
|
|
598
|
+
},
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Astro integration that post-processes all built HTML files to prepend `base`
|
|
604
|
+
* to root-relative `src="/..."` attributes that Astro doesn't rewrite automatically
|
|
605
|
+
* (e.g. raw `<img>` tags in markdown/MDX content).
|
|
606
|
+
*/
|
|
607
|
+
function createBasePrependIntegration(base: string): AstroIntegration {
|
|
608
|
+
const normalizedBase = base.replace(/\/$/, '');
|
|
609
|
+
|
|
610
|
+
function rewriteDir(dir: string): void {
|
|
611
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
612
|
+
const full = path.join(dir, entry.name);
|
|
613
|
+
if (entry.isDirectory()) { rewriteDir(full); continue; }
|
|
614
|
+
if (!entry.name.endsWith('.html')) continue;
|
|
615
|
+
|
|
616
|
+
const original = fs.readFileSync(full, 'utf-8');
|
|
617
|
+
const rewritten = original.replace(
|
|
618
|
+
/\bsrc="(\/[^"]*)"/g,
|
|
619
|
+
(_: string, url: string) => {
|
|
620
|
+
if (url.startsWith(normalizedBase + '/')) return `src="${url}"`;
|
|
621
|
+
return `src="${normalizedBase}${url}"`;
|
|
622
|
+
},
|
|
623
|
+
);
|
|
624
|
+
if (rewritten !== original) fs.writeFileSync(full, rewritten, 'utf-8');
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return {
|
|
629
|
+
name: 'docs-template:base-prepend',
|
|
630
|
+
hooks: {
|
|
631
|
+
'astro:build:done'({ dir }) {
|
|
632
|
+
rewriteDir(fileURLToPath(dir));
|
|
633
|
+
},
|
|
634
|
+
},
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// ---------------------------------------------------------------------------
|
|
639
|
+
// All-in-one factory
|
|
640
|
+
// ---------------------------------------------------------------------------
|
|
641
|
+
|
|
642
|
+
export interface DocsSiteSource {
|
|
643
|
+
/** Absolute path to the TOC file. */
|
|
644
|
+
tocPath: string;
|
|
645
|
+
/** Absolute path to the Markdown docs directory. */
|
|
646
|
+
docsDir: string;
|
|
647
|
+
/**
|
|
648
|
+
* Absolute path to images directory.
|
|
649
|
+
* Omit to skip the images integration.
|
|
650
|
+
*/
|
|
651
|
+
imagesDir?: string;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export interface CreateDocsSiteOptions {
|
|
655
|
+
/** Deployed site URL. */
|
|
656
|
+
site: string;
|
|
657
|
+
/** Base path, e.g. `'/docs'`. */
|
|
658
|
+
base?: string;
|
|
659
|
+
/** Site title shown in the browser tab and DocsSubHeader. */
|
|
660
|
+
title: string;
|
|
661
|
+
/** Short description for the llms.txt header. */
|
|
662
|
+
description?: string;
|
|
663
|
+
/** Content source paths. */
|
|
664
|
+
source: Partial<DocsSiteSource>;
|
|
665
|
+
/** Sidebar builder options. */
|
|
666
|
+
sidebar?: {
|
|
667
|
+
/** Patterns to exclude from the TOC. */
|
|
668
|
+
exclude?: RegExp[];
|
|
669
|
+
};
|
|
670
|
+
/**
|
|
671
|
+
* Platform identifier. Drives CDN styles/scripts injected into `<head>`
|
|
672
|
+
* and the build-time nav prefetch endpoint.
|
|
673
|
+
*/
|
|
674
|
+
platform?: PlatformKey | null;
|
|
675
|
+
/** Locale for the nav prefetch URL. */
|
|
676
|
+
navLang?: NavLang;
|
|
677
|
+
/**
|
|
678
|
+
* Extra `<head>` entries appended after the platform entries.
|
|
679
|
+
*/
|
|
680
|
+
head?: HeadEntry[];
|
|
681
|
+
/**
|
|
682
|
+
* Build / deployment mode.
|
|
683
|
+
* - `'development'` — local development (default)
|
|
684
|
+
* - `'staging'` — pre-production environment
|
|
685
|
+
* - `'production'` — production deployment
|
|
686
|
+
*
|
|
687
|
+
* Exposed as `process.env.DOCS_BUILD_MODE`.
|
|
688
|
+
*/
|
|
689
|
+
mode?: DocsMode;
|
|
690
|
+
/**
|
|
691
|
+
* Named documentation subsets. Each entry generates a dedicated
|
|
692
|
+
* `/_llms-txt/{slug}.txt` and adds a link under
|
|
693
|
+
* `## Documentation sets` in `llms.txt`.
|
|
694
|
+
*/
|
|
695
|
+
llmsSets?: LlmsSet[];
|
|
696
|
+
/** Cross-product navigation links rendered in the DocsSubHeader. */
|
|
697
|
+
productLinks?: ProductLink[];
|
|
698
|
+
/** Extra Astro integrations appended after the built-in ones. */
|
|
699
|
+
integrations?: AstroIntegration[];
|
|
700
|
+
/**
|
|
701
|
+
* @deprecated Starlight has been removed. This option is ignored.
|
|
702
|
+
* Use `head` for extra head entries and `integrations` for extra integrations.
|
|
703
|
+
*/
|
|
704
|
+
starlight?: Record<string, unknown>;
|
|
705
|
+
/** Any remaining keys are spread into `defineConfig` (markdown, image, build, …). */
|
|
706
|
+
[key: string]: unknown;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Creates a complete Astro config for a standard Starlight docs site.
|
|
711
|
+
*
|
|
712
|
+
* All individual helpers (`buildSidebarFromToc`, `staticImagesIntegration`,
|
|
713
|
+
* `siteMetaIntegration`) remain independently importable for cases that
|
|
714
|
+
* need finer control.
|
|
715
|
+
* @param options - Configuration options.
|
|
716
|
+
*/
|
|
717
|
+
export function createDocsSite(options: CreateDocsSiteOptions = {} as CreateDocsSiteOptions): ReturnType<typeof defineConfig> {
|
|
718
|
+
const {
|
|
719
|
+
site,
|
|
720
|
+
base,
|
|
721
|
+
title,
|
|
722
|
+
description = '',
|
|
723
|
+
source = {},
|
|
724
|
+
sidebar: sidebarOptions = {},
|
|
725
|
+
platform = null,
|
|
726
|
+
navLang = 'en',
|
|
727
|
+
mode = 'development',
|
|
728
|
+
productLinks = [],
|
|
729
|
+
head = [],
|
|
730
|
+
llmsSets = [] as LlmsSet[],
|
|
731
|
+
integrations: extraIntegrations = [],
|
|
732
|
+
...astroExtra
|
|
733
|
+
} = options;
|
|
734
|
+
|
|
735
|
+
const sidebar = buildSidebarFromToc({
|
|
736
|
+
tocPath: source.tocPath!,
|
|
737
|
+
docsDir: source.docsDir!,
|
|
738
|
+
exclude: sidebarOptions.exclude ?? [],
|
|
739
|
+
});
|
|
740
|
+
|
|
741
|
+
// Expose env vars so consuming content.config.ts and components can read them.
|
|
742
|
+
if (source.docsDir) {
|
|
743
|
+
process.env.DOCS_SOURCE_PATH = source.docsDir;
|
|
744
|
+
}
|
|
745
|
+
process.env.DOCS_BUILD_MODE = mode;
|
|
746
|
+
process.env.DOCS_BASE = base ? base.replace(/\/$/, '') : '';
|
|
747
|
+
if (!process.env.DOCS_ENV) {
|
|
748
|
+
process.env.DOCS_ENV = mode;
|
|
749
|
+
}
|
|
750
|
+
// Expose the platform so remark-docfx can set data-platform on widgets it generates.
|
|
751
|
+
if (platform) {
|
|
752
|
+
process.env.DOCS_PLATFORM = platform;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Platform CDN entries come first so site-specific `head` entries can override.
|
|
756
|
+
const platformHead = platform ? getPlatformHead(platform, navLang) : [];
|
|
757
|
+
|
|
758
|
+
// highlight.js for code-tab syntax highlighting inside code-view widgets.
|
|
759
|
+
const codeViewHead: HeadEntry[] = [
|
|
760
|
+
{ tag: 'link', attrs: { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.min.css' } },
|
|
761
|
+
{ tag: 'script', attrs: { src: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js', defer: true } },
|
|
762
|
+
];
|
|
763
|
+
|
|
764
|
+
// Auto-configure a Vite dev-server proxy so sample-widget.ts can fetch
|
|
765
|
+
// /code-viewer/*.json from the local demos server without CORS issues.
|
|
766
|
+
const devProxy: Record<string, object> = {};
|
|
767
|
+
if (source.docsDir) {
|
|
768
|
+
try {
|
|
769
|
+
const docsRoot = path.resolve(source.docsDir);
|
|
770
|
+
const envCandidates = [
|
|
771
|
+
path.join(docsRoot, 'en', 'environment.json'),
|
|
772
|
+
path.join(docsRoot, 'environment.json'),
|
|
773
|
+
path.join(path.dirname(docsRoot), 'environment.json'),
|
|
774
|
+
path.join(path.dirname(docsRoot), 'en', 'environment.json'),
|
|
775
|
+
];
|
|
776
|
+
const envFile = envCandidates.find(c => fs.existsSync(c));
|
|
777
|
+
if (envFile) {
|
|
778
|
+
const envData = JSON.parse(fs.readFileSync(envFile, 'utf-8'));
|
|
779
|
+
const envKey = process.env.DOCS_ENV ?? process.env.NODE_ENV ?? 'production';
|
|
780
|
+
const env: Record<string, string> = envData[envKey] ?? envData.production ?? {};
|
|
781
|
+
const demosUrl = env.dvDemosBaseUrl || env.demosBaseUrl;
|
|
782
|
+
if (demosUrl) {
|
|
783
|
+
const u = new URL(demosUrl);
|
|
784
|
+
if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
|
|
785
|
+
const cfg = { target: demosUrl, changeOrigin: true, secure: false };
|
|
786
|
+
devProxy['/code-viewer'] = cfg;
|
|
787
|
+
devProxy['/assets/code-viewer'] = cfg;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
} catch { /* non-fatal — proxy just won't be configured */ }
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
return defineConfig({
|
|
795
|
+
site,
|
|
796
|
+
...(base !== undefined ? { base } : {}),
|
|
797
|
+
// Docs sites serve images statically — disable Astro's image optimization
|
|
798
|
+
// so relative image paths in markdown don't cause build errors.
|
|
799
|
+
image: { service: { entrypoint: 'astro/assets/services/noop' }, ...(astroExtra as any).image },
|
|
800
|
+
...astroExtra,
|
|
801
|
+
vite: {
|
|
802
|
+
...(astroExtra as any).vite,
|
|
803
|
+
server: {
|
|
804
|
+
...(astroExtra as any).vite?.server,
|
|
805
|
+
proxy: {
|
|
806
|
+
...devProxy,
|
|
807
|
+
...(astroExtra as any).vite?.server?.proxy,
|
|
808
|
+
},
|
|
809
|
+
},
|
|
810
|
+
},
|
|
811
|
+
markdown: {
|
|
812
|
+
...(astroExtra as any).markdown,
|
|
813
|
+
remarkPlugins: [
|
|
814
|
+
remarkDocfx,
|
|
815
|
+
...((astroExtra as any).markdown?.remarkPlugins ?? []),
|
|
816
|
+
],
|
|
817
|
+
rehypePlugins: [
|
|
818
|
+
rehypeCodeView,
|
|
819
|
+
...((astroExtra as any).markdown?.rehypePlugins ?? []),
|
|
820
|
+
],
|
|
821
|
+
},
|
|
822
|
+
integrations: [
|
|
823
|
+
siteMetaIntegration({
|
|
824
|
+
title,
|
|
825
|
+
description,
|
|
826
|
+
docsDir: source.docsDir,
|
|
827
|
+
sidebar,
|
|
828
|
+
platform,
|
|
829
|
+
navLang,
|
|
830
|
+
mode,
|
|
831
|
+
llmsSets,
|
|
832
|
+
productLinks,
|
|
833
|
+
head: [...platformHead, ...codeViewHead, ...head],
|
|
834
|
+
}),
|
|
835
|
+
mdx(),
|
|
836
|
+
...(source.imagesDir ? [staticImagesIntegration(source.imagesDir)] : []),
|
|
837
|
+
...(base ? [createBasePrependIntegration(base)] : []),
|
|
838
|
+
...extraIntegrations,
|
|
839
|
+
],
|
|
840
|
+
});
|
|
841
|
+
}
|