@alauda/doom 2.3.1 → 2.5.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 (44) hide show
  1. package/lib/cli/helpers.d.ts +12 -0
  2. package/lib/cli/helpers.js +58 -1
  3. package/lib/cli/load-config.js +1 -1
  4. package/lib/cli/translate.js +25 -39
  5. package/lib/global/Intelligence/AIAssistant/Chat/ChatRefDocs/index.d.ts +2 -2
  6. package/lib/global/Intelligence/AIAssistant/Chat/ThinkingProcess/index.js +2 -1
  7. package/lib/global/Intelligence/AIAssistant/Chat/index.js +1 -1
  8. package/lib/global/Intelligence/AIAssistant/index.js +21 -55
  9. package/lib/global/Intelligence/AIAssistant/types.d.ts +3 -8
  10. package/lib/global/Intelligence/index.js +2 -7
  11. package/lib/plugins/global/index.js +20 -5
  12. package/lib/plugins/replace/parse-toc.js +1 -1
  13. package/lib/products/index.d.ts +15 -0
  14. package/lib/products/index.js +25 -0
  15. package/lib/remark-lint/check-dead-links.js +6 -1
  16. package/lib/runtime/components/ExternalSiteLink.js +3 -2
  17. package/lib/runtime/components/Markdown.js +0 -1
  18. package/lib/runtime/components/Masonry.js +0 -1
  19. package/lib/runtime/components/OpenAPIPath.d.ts +1 -1
  20. package/lib/runtime/components/OpenAPIPath.js +1 -1
  21. package/lib/runtime/components/_HeadingTitle.d.ts +1 -1
  22. package/lib/runtime/components/_HeadingTitle.js +1 -1
  23. package/lib/runtime/hooks/useSiteOverrides.js +2 -5
  24. package/lib/runtime/hooks/useTranslation.d.ts +1 -1
  25. package/lib/runtime/translation.d.ts +12 -0
  26. package/lib/runtime/translation.js +9 -0
  27. package/lib/shared/context.d.ts +5 -0
  28. package/lib/shared/context.js +2 -0
  29. package/lib/theme/AutoExpandable.js +0 -1
  30. package/lib/theme/Breadcrumb/index.d.ts +6 -0
  31. package/lib/theme/Breadcrumb/index.js +85 -0
  32. package/lib/theme/Layout.js +6 -3
  33. package/lib/theme/_X.d.ts +23 -0
  34. package/lib/theme/_X.js +2 -0
  35. package/package.json +24 -23
  36. package/styles/_mixins.scss +19 -0
  37. package/styles/breadcrumb.scss +42 -0
  38. package/styles/chat-ref-docs.module.scss +4 -0
  39. package/styles/chat.module.scss +85 -6
  40. package/styles/global.scss +1 -0
  41. package/styles/login.module.scss +3 -12
  42. package/styles/products.module.scss +45 -0
  43. package/lib/global/Intelligence/AIAssistant/utils.d.ts +0 -19
  44. package/lib/global/Intelligence/AIAssistant/utils.js +0 -131
@@ -1,7 +1,9 @@
1
+ import type { Code, Root, RootContent } from 'mdast';
1
2
  export declare const parseBoolean: (value?: string) => boolean;
2
3
  export declare const parseBooleanOrString: (value?: string) => string | boolean;
3
4
  export declare const isDoc: (filename: string) => boolean;
4
5
  export declare const getMatchedDocFilePaths: (matched: string[]) => Promise<(string | string[])[]>;
6
+ export declare const stringifyMatter: (frontmatter: object, content: string) => string;
5
7
  /**
6
8
  * Support custom id like `#hello world {#custom-id}`
7
9
  * Avoid https://mdxjs.com/docs/troubleshooting-mdx/#could-not-parse-expression-with-acorn-error
@@ -21,3 +23,13 @@ export declare const parseTerms: () => Promise<{
21
23
  } | undefined;
22
24
  name?: "company" | "product" | "productShort" | "alaudaCloudLink" | undefined;
23
25
  }[]>;
26
+ export declare const translateCodeFile: (content: RootContent, { sourceBase, targetBase }: {
27
+ sourceBase: string;
28
+ targetBase: string;
29
+ }) => RootContent;
30
+ export interface CodeBlockPlaceholder {
31
+ node: Code;
32
+ placeholder: string;
33
+ }
34
+ export declare const replaceCodeBlocksWithPlaceholders: (content: Root | RootContent) => CodeBlockPlaceholder[];
35
+ export declare const restoreCodeBlockPlaceholders: (content: Root | RootContent, placeholders: readonly CodeBlockPlaceholder[]) => RootContent | Root;
@@ -1,7 +1,9 @@
1
1
  import fs from 'node:fs/promises';
2
+ import path from 'node:path';
2
3
  import { glob } from 'tinyglobby';
4
+ import { visit } from 'unist-util-visit';
3
5
  import { xfetch } from 'x-fetch';
4
- import { parse } from 'yaml';
6
+ import { parse, stringify } from 'yaml';
5
7
  import { FALSY_VALUES, TRUTHY_VALUES } from "../shared/index.js";
6
8
  export const parseBoolean = (value) => value === undefined || !FALSY_VALUES.has(value);
7
9
  export const parseBooleanOrString = (value) => value === undefined ||
@@ -21,6 +23,10 @@ export const getMatchedDocFilePaths = (matched) => Promise.all(matched.map(async
21
23
  }
22
24
  return [];
23
25
  }));
26
+ export const stringifyMatter = (frontmatter, content) => '---\n' +
27
+ stringify(frontmatter) +
28
+ '---\n' +
29
+ (content.startsWith('\n') ? content : '\n' + content);
24
30
  /**
25
31
  * Support custom id like `#hello world {#custom-id}`
26
32
  * Avoid https://mdxjs.com/docs/troubleshooting-mdx/#could-not-parse-expression-with-acorn-error
@@ -43,3 +49,54 @@ const parseTerms_ = async () => {
43
49
  };
44
50
  let parsedTermsCache;
45
51
  export const parseTerms = () => (parsedTermsCache ??= parseTerms_());
52
+ const RELATIVE_FILE_META_REGEX = /(^|\s)(file)(\s*=\s*)(['"`]?)(\.\.?\/[^\s'"`]+)\4/g;
53
+ export const translateCodeFile = (content, { sourceBase, targetBase }) => {
54
+ visit(content, 'code', (code) => {
55
+ const nextMeta = code.meta?.replace(RELATIVE_FILE_META_REGEX, (_match, prefix, key, equals, quote, value) => `${prefix}${key}${equals}${quote}${path.relative(targetBase, path.resolve(sourceBase, value))}${quote}`);
56
+ if (nextMeta !== code.meta) {
57
+ code.meta = nextMeta;
58
+ }
59
+ });
60
+ return content;
61
+ };
62
+ const CODE_BLOCK_PLACEHOLDER_PREFIX = '__DOOM_TRANSLATE_CODE_BLOCK_';
63
+ const CODE_BLOCK_PLACEHOLDER_PATTERN = new RegExp(`^${CODE_BLOCK_PLACEHOLDER_PREFIX}(\\d+)__$`);
64
+ const getCodeBlockPlaceholderIndex = (value) => {
65
+ const match = CODE_BLOCK_PLACEHOLDER_PATTERN.exec(value);
66
+ if (!match) {
67
+ return;
68
+ }
69
+ return +match[1];
70
+ };
71
+ export const replaceCodeBlocksWithPlaceholders = (content) => {
72
+ const placeholders = [];
73
+ visit(content, 'code', (code) => {
74
+ if (code.value.length <= 50) {
75
+ return;
76
+ }
77
+ const placeholder = `${CODE_BLOCK_PLACEHOLDER_PREFIX}${placeholders.length}__`;
78
+ placeholders.push({
79
+ node: { ...code },
80
+ placeholder,
81
+ });
82
+ code.value = placeholder;
83
+ delete code.lang;
84
+ delete code.meta;
85
+ });
86
+ return placeholders;
87
+ };
88
+ export const restoreCodeBlockPlaceholders = (content, placeholders) => {
89
+ visit(content, 'code', (code) => {
90
+ const value = code.value.trim();
91
+ const index = getCodeBlockPlaceholderIndex(value);
92
+ if (index == null) {
93
+ return;
94
+ }
95
+ const placeholder = placeholders.at(index);
96
+ if (!placeholder || placeholder.placeholder !== value) {
97
+ throw new Error(`Unmatched code block placeholder: ${value}`);
98
+ }
99
+ Object.assign(code, placeholder.node);
100
+ });
101
+ return content;
102
+ };
@@ -208,7 +208,7 @@ const getCommonConfig = async ({ config, root, configFilePath, base, version, do
208
208
  server: {
209
209
  open,
210
210
  proxy: {
211
- '/smart/api': 'https://docs-dev.alauda.cn',
211
+ '/smart/api': 'https://docs.alauda.cn',
212
212
  },
213
213
  },
214
214
  tools: {
@@ -5,9 +5,9 @@ import { setTimeout } from 'node:timers/promises';
5
5
  import { isDeepStrictEqual } from 'node:util';
6
6
  import { logger } from '@rspress/core';
7
7
  import { removeLeadingSlash } from '@rspress/shared';
8
+ import matter from '@rspress/shared/gray-matter';
8
9
  import { Command } from 'commander';
9
10
  import ejs from 'ejs';
10
- import matter from 'gray-matter';
11
11
  import { OpenAI, RateLimitError } from 'openai';
12
12
  import { pRateLimit } from 'p-ratelimit';
13
13
  import { glob } from 'tinyglobby';
@@ -15,13 +15,15 @@ import { cyan, red } from 'yoctocolors';
15
15
  import { mdProcessor, mdxProcessor, normalizeImgSrc, } from '../plugins/index.js';
16
16
  import { Language, SUPPORTED_LANGUAGES, TITLE_TRANSLATION_MAP, } from '../shared/index.js';
17
17
  import { pathExists } from '../utils/index.js';
18
- import { escapeMarkdownHeadingIds, getMatchedDocFilePaths, parseBoolean, parseTerms, } from './helpers.js';
18
+ import { escapeMarkdownHeadingIds, getMatchedDocFilePaths, parseBoolean, parseTerms, replaceCodeBlocksWithPlaceholders, restoreCodeBlockPlaceholders, stringifyMatter, translateCodeFile, } from './helpers.js';
19
19
  import { loadConfig } from './load-config.js';
20
20
  export const TERMS_SUPPORTED_LANGUAGES = ['en', 'zh', 'ru'];
21
21
  // Directories that should be copied instead of translated
22
22
  const COPY_ONLY_DIRECTORIES = [
23
23
  'apis/advanced_apis/**',
24
+ 'apis/crds/**',
24
25
  'apis/kubernetes_apis/**',
26
+ 'apis/references/**',
25
27
  ];
26
28
  const DEFAULT_SYSTEM_PROMPT = `
27
29
  You are a professional technical documentation engineer, skilled in writing high-quality technical documentation in <%= targetLang %>. Please accurately translate the following text from <%= sourceLang %> to <%= targetLang %>, maintaining the style consistent with technical documentation in <%= sourceLang %>.
@@ -30,16 +32,16 @@ You are a professional technical documentation engineer, skilled in writing high
30
32
  - Sentences should be fluent and conform to the expression habits of the <%= targetLang %> language.
31
33
  - Input format is MDX; output format must also retain the original MDX format. Do not translate the names of jsx components such as <Overview />, and do not wrap output in unnecessary code blocks.
32
34
  - **CRITICAL**: Do not translate or modify ANY link content in the document. This includes:
33
- - URLs in markdown links: [text](URL) - keep URL exactly as is
35
+ - URLs in markdown links: [text](URL) - keep URL exactly as is but translate the text
34
36
  - Reference-style links: [text][ref] and [ref]: URL - keep both ref and URL unchanged
35
37
  - Inline URLs: https://example.com - keep completely unchanged
36
- - Image links: ![alt](src) - keep src unchanged, but alt text can be translated
38
+ - Image links: ![alt](src) - keep src unchanged, but alt text should be translated
37
39
  - Anchor links: [text](#anchor) - keep #anchor unchanged
40
+ - Custom anchors in headings: # Heading \\{#custom-anchor} - keep \\{#custom-anchor} unchanged and translate "Heading"
38
41
  - Any href attributes in HTML tags - keep unchanged
39
42
  - Do not translate professional technical terms and proper nouns, including but not limited to: Kubernetes, Docker, CLI, API, REST, GraphQL, JSON, YAML, Git, GitHub, GitLab, AWS, Azure, GCP, Linux, Windows, macOS, Node.js, React, Vue, Angular, TypeScript, JavaScript, Python, Java, Go, Rust, etc. Keep these terms in their original form.
40
43
  - The title field and description field in frontmatter should be translated, other frontmatter fields should retain and do not translate.
41
44
  - Content within MDX components needs to be translated, whereas MDX component names and parameter keys do not.
42
- - Do not modify or translate any placeholders in the format of __ANCHOR_N__ (where N is a number). These placeholders must be kept exactly as they appear in the source text.
43
45
  - Keep original escape characters like backslash, angle brackets, etc. unchanged during translation.
44
46
  - Do not add any escape characters to special characters like [], (), {}, etc. unless they were explicitly present in the source text. For example:
45
47
  - If source has "Architecture [Optional]", keep it as "Architecture [Optional]" (not "Architecture \\[Optional]")
@@ -106,29 +108,6 @@ const resolveTerms = async (sourceLang, targetLang, sourceContent) => {
106
108
  logger.debug('Resolved terms:', terms);
107
109
  return terms;
108
110
  };
109
- const ANCHOR_REGEX = /\\\\?\{#[\w-]+\}/g;
110
- function replaceAnchorsWithPlaceholders(content) {
111
- // Handle escaped underscores in anchor IDs (e.g., \{#independent\_doc\_site} -> \{#independent_doc_site})
112
- // This is necessary because MDX processor automatically escapes underscores in heading IDs
113
- // to ensure proper Markdown parsing, but we need the original unescaped form for anchor matching
114
- const unescapedContent = content.replace(/\\_/g, '_');
115
- const anchors = [];
116
- const contentWithPlaceholders = unescapedContent.replace(ANCHOR_REGEX, (match) => {
117
- anchors.push(match);
118
- return `__ANCHOR_${anchors.length - 1}__`;
119
- });
120
- return { content: contentWithPlaceholders, anchors };
121
- }
122
- function restoreAnchors(content, anchors) {
123
- return content.replace(/__ANCHOR_(\d+)__/g, (_, index) => {
124
- const numIndex = parseInt(index, 10);
125
- if (isNaN(numIndex) || numIndex < 0 || numIndex >= anchors.length) {
126
- throw new Error(`Invalid anchor index: ${index}`);
127
- }
128
- const anchor = anchors[numIndex];
129
- return anchor;
130
- });
131
- }
132
111
  function extractFirstLevelHeading(content) {
133
112
  const lines = content.split('\n');
134
113
  for (const line of lines) {
@@ -168,12 +147,11 @@ export const translate = async ({ source, sourceContent, target, systemPrompt, u
168
147
  titleTranslationPrompt = `- The heading "${firstLevelHeading}" should be translated as "${titleTranslation}".`;
169
148
  }
170
149
  }
171
- const { content: contentWithPlaceholders, anchors } = replaceAnchorsWithPlaceholders(sourceContent);
172
150
  const finalSystemPrompt = await ejs.render(systemPrompt?.trim() || DEFAULT_SYSTEM_PROMPT, {
173
151
  sourceLang,
174
152
  targetLang,
175
153
  userPrompt,
176
- additionalPrompts: additionalPrompts,
154
+ additionalPrompts,
177
155
  terms,
178
156
  titleTranslationPrompt,
179
157
  }, { async: true });
@@ -186,7 +164,7 @@ export const translate = async ({ source, sourceContent, target, systemPrompt, u
186
164
  },
187
165
  {
188
166
  role: 'user',
189
- content: contentWithPlaceholders,
167
+ content: sourceContent,
190
168
  },
191
169
  ],
192
170
  model: openaiModel,
@@ -197,7 +175,7 @@ export const translate = async ({ source, sourceContent, target, systemPrompt, u
197
175
  for await (const chunk of stream) {
198
176
  content += chunk.choices[0]?.delta.content ?? '';
199
177
  }
200
- return restoreAnchors(content, anchors);
178
+ return content;
201
179
  };
202
180
  const limit = pRateLimit({
203
181
  interval: 60_000, // 1min
@@ -314,7 +292,7 @@ export const translateCommand = new Command('translate')
314
292
  const newFrontmatter = { ...sourceFrontmatter, sourceSHA };
315
293
  delete newFrontmatter.i18n;
316
294
  const { content } = matter(sourceContent);
317
- targetContent = matter.stringify(content.startsWith('\n') ? content : '\n' + content, newFrontmatter);
295
+ targetContent = stringifyMatter(newFrontmatter, content);
318
296
  const targetBase = path.dirname(targetFilePath);
319
297
  await fs.mkdir(targetBase, { recursive: true });
320
298
  await fs.writeFile(targetFilePath, targetContent);
@@ -325,17 +303,20 @@ export const translateCommand = new Command('translate')
325
303
  const isMdx = sourceFilePath.endsWith('.mdx');
326
304
  const processor = isMdx ? mdxProcessor : mdProcessor;
327
305
  const ast = processor.parse(escapeMarkdownHeadingIds(sourceContent));
306
+ const sourceBase = path.dirname(sourceFilePath);
328
307
  const targetBase = path.dirname(targetFilePath);
308
+ const normalizeOptions = { sourceBase, targetBase };
329
309
  const normalizeImgSrcOptions = {
310
+ ...normalizeOptions,
330
311
  localPublicBase: path.resolve(docsDir, 'public'),
331
- sourceBase: path.dirname(sourceFilePath),
332
- targetBase,
333
312
  translating: { source, target, copy },
334
313
  };
335
- const normalizedSourceContent = processor.stringify({
314
+ const normalizedAst = {
336
315
  ...ast,
337
- children: ast.children.map((it) => normalizeImgSrc(it, normalizeImgSrcOptions)),
338
- });
316
+ children: ast.children.map((it) => translateCodeFile(normalizeImgSrc(it, normalizeImgSrcOptions), normalizeOptions)),
317
+ };
318
+ const codeBlockPlaceholders = replaceCodeBlocksWithPlaceholders(normalizedAst);
319
+ const normalizedSourceContent = processor.stringify(normalizedAst);
339
320
  targetContent = await translate({
340
321
  ...config.translate,
341
322
  source,
@@ -343,6 +324,11 @@ export const translateCommand = new Command('translate')
343
324
  target,
344
325
  additionalPrompts: sourceFrontmatter.i18n?.additionalPrompts,
345
326
  });
327
+ if (codeBlockPlaceholders.length > 0) {
328
+ const targetAst = processor.parse(targetContent);
329
+ restoreCodeBlockPlaceholders(targetAst, codeBlockPlaceholders);
330
+ targetContent = processor.stringify(targetAst);
331
+ }
346
332
  const newFrontmatter = { ...sourceFrontmatter, sourceSHA };
347
333
  delete newFrontmatter.i18n;
348
334
  const { data, content } = matter(targetContent);
@@ -363,7 +349,7 @@ export const translateCommand = new Command('translate')
363
349
  if (typeof newFrontmatter.title !== 'string') {
364
350
  delete newFrontmatter.title;
365
351
  }
366
- targetContent = matter.stringify(content.startsWith('\n') ? content : '\n' + content, newFrontmatter);
352
+ targetContent = stringifyMatter(newFrontmatter, content);
367
353
  await fs.mkdir(targetBase, { recursive: true });
368
354
  await fs.writeFile(targetFilePath, targetContent);
369
355
  logger.info(`${cyan(sourceRelativePath)} translated to ${cyan(targetRelativePath)}`);
@@ -1,5 +1,5 @@
1
- import type { RefDoc } from '../../types.ts';
1
+ import type { SmartDocDisplayReferenceDoc } from '@alauda/doc-stream-sdk';
2
2
  export interface ChatRefDocsProps {
3
- refDocs: RefDoc[];
3
+ refDocs: SmartDocDisplayReferenceDoc[];
4
4
  }
5
5
  export declare const ChatRefDocs: ({ refDocs }: ChatRefDocsProps) => import("react/jsx-runtime").JSX.Element;
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Markdown, useTranslation } from '@alauda/doom/runtime';
3
+ import classes from '@alauda/doom/styles/chat.module.scss';
3
4
  export const ThinkingProcess = ({ children }) => {
4
5
  const t = useTranslation();
5
- return (_jsxs("div", { children: [_jsx("div", { children: t('thinking_process') }), _jsx(Markdown, { children: children })] }));
6
+ return (_jsxs("div", { children: [_jsx("div", { children: t('thinking_process') }), _jsx("div", { className: classes.markdown, children: _jsx(Markdown, { children: children }) })] }));
6
7
  };
@@ -5,4 +5,4 @@ import { ThinkingProcess } from './ThinkingProcess/index.js';
5
5
  import AssistantIcon from '@alauda/doom/assets/assistant.svg?react';
6
6
  import { Markdown } from '@alauda/doom/runtime';
7
7
  import classes from '@alauda/doom/styles/chat.module.scss';
8
- export const Chat = ({ ref, messages }) => (_jsx("ul", { ref: ref, className: classes.container, children: messages.map(({ id, role, content, thinkingProcess, refDocs }) => (_jsxs("li", { className: clsx(classes.chat, classes[role]), children: [role === 'assistant' && _jsx(AssistantIcon, { className: classes.icon }), _jsxs("div", { className: classes.content, children: [thinkingProcess && (_jsx(ThinkingProcess, { children: thinkingProcess })), refDocs?.length ? _jsx(ChatRefDocs, { refDocs: refDocs }) : null, typeof content === 'string' ? (_jsx(Markdown, { children: content })) : (content)] })] }, `${role}-${id}`))) }));
8
+ export const Chat = ({ ref, messages }) => (_jsx("ul", { ref: ref, className: classes.container, children: messages.map(({ id, role, content, thoughtProcess, refDocs }) => (_jsxs("li", { className: clsx(classes.chat, classes[role]), children: [role === 'assistant' && _jsx(AssistantIcon, { className: classes.icon }), _jsxs("div", { className: classes.content, children: [thoughtProcess && (_jsx(ThinkingProcess, { children: thoughtProcess })), refDocs?.length ? _jsx(ChatRefDocs, { refDocs: refDocs }) : null, typeof content === 'string' ? (_jsx("div", { className: clsx(classes.markdown), children: _jsx(Markdown, { children: content }) })) : (content)] })] }, `${role}-${id}`))) }));
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { consumeSmartDocDisplayStream } from '@alauda/doc-stream-sdk';
2
3
  import { clsx } from 'clsx';
3
4
  import { useEffect, useRef, useState } from 'react';
4
5
  import { Tooltip } from 'react-tooltip';
@@ -9,7 +10,6 @@ import { Chat } from "./Chat/index.js";
9
10
  import { Preamble } from "./Preamble/index.js";
10
11
  import { ResizableUserInput } from "./ResizableUserInput/index.js";
11
12
  import { Thinking } from "./Thinking.js";
12
- import { consumeSSEEvents, getAnswerDelta, parseStreamContent, } from "./utils.js";
13
13
  import CloseIcon from '@alauda/doom/assets/close.svg?react';
14
14
  import LogoutIcon from '@alauda/doom/assets/logout.svg?react';
15
15
  import NewChatIcon from '@alauda/doom/assets/new-chat.svg?react';
@@ -99,61 +99,27 @@ export const AIAssistant = ({ open, onOpenChange }) => {
99
99
  session_id: sessionId,
100
100
  },
101
101
  });
102
- const textDecoder = new TextDecoder();
103
- let text = '';
104
- let sseBuffer = '';
105
- let sseEvent;
106
- for await (const chunk_ of res.body) {
107
- if (sessionId !== sessionIdRef.current) {
108
- break;
109
- }
110
- sseBuffer += textDecoder.decode(chunk_, { stream: true });
111
- const result = consumeSSEEvents(sseBuffer, sseEvent);
112
- const { events, remainder } = result;
113
- sseBuffer = remainder;
114
- sseEvent = result.event;
115
- let updated = false;
116
- for (const event of events) {
117
- const delta = getAnswerDelta(event);
118
- if (!delta) {
119
- continue;
120
- }
121
- text += delta;
122
- updated = true;
123
- }
124
- if (!updated) {
125
- continue;
126
- }
127
- const parsed = parseStreamContent(text);
128
- flushMessages((messages) => [
129
- ...messages.slice(0, index),
130
- { ...messages[index], ...parsed },
131
- ...messages.slice(index + 1),
132
- ]);
133
- }
134
- if (sessionId !== sessionIdRef.current) {
135
- return;
136
- }
137
- sseBuffer += textDecoder.decode();
138
- const { events } = consumeSSEEvents(`${sseBuffer}\n`, sseEvent);
139
- let updated = false;
140
- for (const event of events) {
141
- const delta = getAnswerDelta(event);
142
- if (!delta) {
143
- continue;
144
- }
145
- text += delta;
146
- updated = true;
147
- }
148
- if (!updated) {
102
+ if (!res.body) {
149
103
  return;
150
104
  }
151
- const parsed = parseStreamContent(text);
152
- flushMessages((messages) => [
153
- ...messages.slice(0, index),
154
- { ...messages[index], ...parsed },
155
- ...messages.slice(index + 1),
156
- ]);
105
+ await consumeSmartDocDisplayStream(res.body, {
106
+ ignoreDocsBlocks: false,
107
+ onDisplayMessage(nextMessage) {
108
+ if (sessionId !== sessionIdRef.current) {
109
+ return;
110
+ }
111
+ flushMessages((messages) => [
112
+ ...messages.slice(0, index),
113
+ {
114
+ ...messages[index],
115
+ content: nextMessage.content,
116
+ thoughtProcess: nextMessage.thoughtProcess || undefined,
117
+ refDocs: nextMessage.refDocs,
118
+ },
119
+ ...messages.slice(index + 1),
120
+ ]);
121
+ },
122
+ });
157
123
  };
158
124
  const [loading, setLoading] = useState(false);
159
125
  const onSend = useMemoizedFn(async (content) => {
@@ -178,5 +144,5 @@ export const AIAssistant = ({ open, onOpenChange }) => {
178
144
  setLoading(false);
179
145
  }
180
146
  });
181
- return (_jsxs("div", { className: clsx(classes.container, 'rspress-doc', open && classes.open), children: [_jsxs("div", { className: classes.header, children: [_jsxs("div", { className: classes.title, children: [t('ai_assistant'), loggedIn && (_jsxs(_Fragment, { children: [_jsxs("span", { className: classes.username, children: ["(", authInfo.detail.user.name, ")"] }), _jsx(LogoutIcon, { className: "ai-assistant-logout", onClick: onLogout }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-logout", children: t('logout') })] }))] }), _jsxs("div", { className: classes.icons, children: [messages.length ? (_jsxs(_Fragment, { children: [_jsx(NewChatIcon, { className: "ai-assistant-new-chat", onClick: onNewChat }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-new-chat", children: t('new_chat') })] })) : null, _jsx(CloseIcon, { className: "ai-assistant-close", onClick: onClose }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-close", children: t('close') })] })] }), messages.length ? (_jsx(Chat, { ref: chatRef, messages: messages })) : (_jsx(Preamble, { loggedIn: loggedIn })), loggedIn && _jsx(ResizableUserInput, { loading: loading, onSend: onSend })] }));
147
+ return (_jsxs("div", { className: clsx(classes.container, 'rp-doc', open && classes.open), children: [_jsxs("div", { className: classes.header, children: [_jsxs("div", { className: classes.title, children: [t('ai_assistant'), loggedIn && (_jsxs(_Fragment, { children: [_jsxs("span", { className: classes.username, children: ["(", authInfo.detail.user.name, ")"] }), _jsx(LogoutIcon, { className: "ai-assistant-logout", onClick: onLogout }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-logout", children: t('logout') })] }))] }), _jsxs("div", { className: classes.icons, children: [messages.length ? (_jsxs(_Fragment, { children: [_jsx(NewChatIcon, { className: "ai-assistant-new-chat", onClick: onNewChat }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-new-chat", children: t('new_chat') })] })) : null, _jsx(CloseIcon, { className: "ai-assistant-close", onClick: onClose }), _jsx(Tooltip, { anchorSelect: ".ai-assistant-close", children: t('close') })] })] }), messages.length ? (_jsx(Chat, { ref: chatRef, messages: messages })) : (_jsx(Preamble, { loggedIn: loggedIn })), loggedIn && _jsx(ResizableUserInput, { loading: loading, onSend: onSend })] }));
182
148
  };
@@ -1,14 +1,9 @@
1
+ import type { SmartDocDisplayReferenceDoc } from '@alauda/doc-stream-sdk';
1
2
  import type { ReactNode } from 'react';
2
- export interface RefDoc {
3
- content: string;
4
- cos_sim: number;
5
- id: number;
6
- path: string;
7
- }
8
3
  export interface ChatMessage {
9
4
  id: number;
10
5
  role: 'user' | 'assistant';
11
6
  content: ReactNode;
12
- refDocs?: RefDoc[];
13
- thinkingProcess?: string | null;
7
+ refDocs?: SmartDocDisplayReferenceDoc[];
8
+ thoughtProcess?: string | null;
14
9
  }
@@ -1,9 +1,7 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { isProduction, NoSSR, useLang } from '@rspress/core/runtime';
3
- import virtual from 'doom-@global-virtual';
2
+ import { isProduction, NoSSR } from '@rspress/core/runtime';
4
3
  import { useState } from 'react';
5
4
  import { Tooltip } from 'react-tooltip';
6
- import { ACP_BASE } from "../../shared/index.js";
7
5
  import { AIAssistant } from "./AIAssistant/index.js";
8
6
  import assistantIcon from '@alauda/doom/assets/assistant.svg';
9
7
  import { useMemoizedFn, useTranslation } from '@alauda/doom/runtime';
@@ -24,10 +22,7 @@ const Intelligence_ = () => {
24
22
  return (_jsxs(_Fragment, { children: [_jsx(AIAssistant, { open: open, onOpenChange: toggleOpen }), open || (_jsx("button", { type: "button", className: "intelligence-entry", onClick: toggleOpen, children: _jsx("img", { alt: t('ai_assistant'), src: assistantIcon }) })), _jsx(Tooltip, { anchorSelect: ".intelligence-entry", place: "left", children: t('ai_assistant') })] }));
25
23
  };
26
24
  const Intelligence = () => {
27
- const lang = useLang();
28
- if (lang !== 'en' ||
29
- !ALLOWED_DOMAINS.has(location.hostname) ||
30
- virtual.userBase !== ACP_BASE) {
25
+ if (!ALLOWED_DOMAINS.has(location.hostname)) {
31
26
  return;
32
27
  }
33
28
  return _jsx(Intelligence_, {});
@@ -41,9 +41,11 @@ export const globalPlugin = ({ version, download, }) => {
41
41
  },
42
42
  addPages(config) {
43
43
  let loginPath;
44
+ let productsPath;
44
45
  for (const ext of ['.js', '.tsx']) {
45
46
  loginPath = baseResolve(`login/index${ext}`);
46
- if (fs.existsSync(loginPath)) {
47
+ productsPath = baseResolve(`products/index${ext}`);
48
+ if (fs.existsSync(loginPath) && fs.existsSync(productsPath)) {
47
49
  break;
48
50
  }
49
51
  }
@@ -53,13 +55,26 @@ export const globalPlugin = ({ version, download, }) => {
53
55
  routePath: '/login',
54
56
  filepath: loginPath,
55
57
  },
58
+ {
59
+ routePath: '/products',
60
+ filepath: productsPath,
61
+ },
56
62
  ];
57
63
  }
58
64
  const lang = config.lang;
59
- return config.themeConfig.locales.map((l) => ({
60
- routePath: l.lang && l.lang !== lang ? `/${l.lang}/login` : '/login',
61
- filepath: loginPath,
62
- }));
65
+ return config.themeConfig.locales.flatMap((l) => {
66
+ const prefix = l.lang && l.lang !== lang ? `/${l.lang}` : '';
67
+ return [
68
+ {
69
+ routePath: `${prefix}/login`,
70
+ filepath: loginPath,
71
+ },
72
+ {
73
+ routePath: `${prefix}/products`,
74
+ filepath: productsPath,
75
+ },
76
+ ];
77
+ });
63
78
  },
64
79
  };
65
80
  };
@@ -1,5 +1,5 @@
1
+ import Slugger from '@rspress/shared/github-slugger';
1
2
  import { extractTextAndId } from '@rspress/shared/node-utils';
2
- import Slugger from 'github-slugger';
3
3
  import { visitChildren } from 'unist-util-visit-children';
4
4
  export const parseToc = (tree, allDepths) => {
5
5
  let title = '';
@@ -0,0 +1,15 @@
1
+ export interface BuildInfoItem {
2
+ base: string;
3
+ version: string;
4
+ displayName?: {
5
+ en: string;
6
+ zh?: string;
7
+ ru?: string;
8
+ };
9
+ }
10
+ export interface BuildInfoGroup {
11
+ id: string;
12
+ items: BuildInfoItem[];
13
+ }
14
+ declare const _default: () => import("react/jsx-runtime").JSX.Element;
15
+ export default _default;
@@ -0,0 +1,25 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { addLeadingSlash, NoSSR, useSite } from '@rspress/core/runtime';
3
+ import virtual from 'doom-@global-virtual';
4
+ import { use } from 'react';
5
+ import { BuildInfoContext } from "../shared/context.js";
6
+ import { isUnversioned } from '../shared/helpers.js';
7
+ import { useIsPrint, useLang, useTranslation } from '@alauda/doom/runtime';
8
+ import classes from '@alauda/doom/styles/products.module.scss';
9
+ const Products = () => {
10
+ const lang = useLang();
11
+ const isPrint = useIsPrint();
12
+ const { site } = useSite();
13
+ const { groups: buildInfoGroups } = use(BuildInfoContext);
14
+ return (_jsx("div", { className: classes.container, children: buildInfoGroups.map((group) => (_jsxs("div", { className: classes.group, children: [_jsx("h2", { children: group.id.toUpperCase() }), _jsx("ul", { children: group.items.map((item) => (_jsx("li", { children: _jsx("a", { className: "rp-link", href: (isPrint ? 'https://docs.alauda.io' : '') +
15
+ (virtual.prefix || '') +
16
+ addLeadingSlash(item.base) +
17
+ (isUnversioned(virtual.version) ? '' : `/${item.version}`) +
18
+ (lang !== site.lang ? addLeadingSlash(lang) : ''), target: "_blank", rel: "noopener noreferrer", children: item.displayName?.[lang] ||
19
+ item.displayName?.en ||
20
+ item.base }) }, item.base))) })] }, group.id))) }));
21
+ };
22
+ export default () => {
23
+ const t = useTranslation();
24
+ return (_jsxs(_Fragment, { children: [_jsx("h1", { children: t('all_product_documentation') }), _jsx("p", { children: t('explore_doc_all_products') }), _jsx(NoSSR, { children: _jsx(Products, {}) })] }));
25
+ };
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { PluginDriver, RouteService, remarkLink } from '@rspress/core';
2
+ import { PluginDriver, RouteService, remarkImage, remarkLink, } from '@rspress/core';
3
3
  import { isProduction } from '@rspress/shared';
4
4
  import { lintRule } from 'unified-lint-rule';
5
5
  import { getConfig } from "./utils.js";
@@ -26,4 +26,9 @@ export const checkDeadLinks = lintRule('doom-lint:check-dead-links', async (tree
26
26
  remarkLinkOptions: config.markdown?.link,
27
27
  lint: true,
28
28
  })(tree, vfile);
29
+ remarkImage({
30
+ docDirectory: config.root,
31
+ remarkImageOptions: config.markdown?.image,
32
+ lint: true,
33
+ })(tree, vfile);
29
34
  });
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useLang, useSite } from '@rspress/core/runtime';
2
+ import { useSite } from '@rspress/core/runtime';
3
3
  import { addTrailingSlash, isExternalUrl, normalizeHref, parseUrl, removeLeadingSlash, } from '@rspress/shared';
4
4
  import { DEFAULT_PAGE_EXTENSIONS } from '@rspress/shared/constants';
5
5
  import { clsx } from 'clsx';
@@ -7,6 +7,7 @@ import virtual from 'doom-@global-virtual';
7
7
  import { useMemo } from 'react';
8
8
  import { isUnversioned } from '../../shared/helpers.js';
9
9
  import { useIsPrint } from '../hooks/index.js';
10
+ import { useLang } from '@alauda/doom/runtime';
10
11
  const ExternalSiteLink_ = ({ name, href = '', className, ...props }) => {
11
12
  const isPrint = useIsPrint();
12
13
  const { site: siteData } = useSite();
@@ -31,7 +32,7 @@ const ExternalSiteLink_ = ({ name, href = '', className, ...props }) => {
31
32
  (isUnversioned(virtual.version)
32
33
  ? site.base
33
34
  : addTrailingSlash(site.base + site.version)) +
34
- (lang && lang !== siteData.lang ? addTrailingSlash(lang) : '') +
35
+ (lang !== siteData.lang ? addTrailingSlash(lang) : '') +
35
36
  (hash ? `${url}#${hash}` : url), target: "_blank", rel: "noopener noreferrer", className: clsx('rp-link', className), ...props }));
36
37
  };
37
38
  export const ExternalSiteLink = (props) => (_jsx(ExternalSiteLink_, { ...props }));
@@ -1,5 +1,4 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import {} from 'react';
3
2
  import ReactMarkdown from 'react-markdown';
4
3
  import rehypeRaw from 'rehype-raw';
5
4
  import rehypeSanitize from 'rehype-sanitize';
@@ -2,7 +2,6 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { NoSSR } from '@rspress/core/runtime';
3
3
  import { lazy, Suspense, useLayoutEffect, useRef, } from 'react';
4
4
  const LazyMasonry = lazy(() => import('masonry-layout').then(({ default: MasonryLayout }) => {
5
- // eslint-disable-next-line @eslint-react/component-hook-factories
6
5
  const Masonry = ({ options, ...props }) => {
7
6
  const ref = useRef(null);
8
7
  useLayoutEffect(() => {
@@ -1,4 +1,4 @@
1
- import BananaSlug from 'github-slugger';
1
+ import BananaSlug from '@rspress/shared/github-slugger';
2
2
  import { type OpenAPIV3_1 } from 'openapi-types';
3
3
  export interface OpenAPIPathProps {
4
4
  /**
@@ -1,9 +1,9 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { usePage } from '@rspress/core/runtime';
3
3
  import { Badge } from '@rspress/core/theme-original';
4
+ import BananaSlug from '@rspress/shared/github-slugger';
4
5
  import openapisMap from 'doom-@api-openapisMap';
5
6
  import virtual from 'doom-@api-virtual';
6
- import BananaSlug from 'github-slugger';
7
7
  import { OpenAPIV3 } from 'openapi-types';
8
8
  import { Fragment, useMemo } from 'react';
9
9
  import { omitRoutePathRefs, resolveRef } from '../utils.js';
@@ -1,4 +1,4 @@
1
- import BananaSlug from 'github-slugger';
1
+ import BananaSlug from '@rspress/shared/github-slugger';
2
2
  import { type ReactNode } from 'react';
3
3
  export interface HeadingTitleProps {
4
4
  slug?: string;
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import BananaSlug from 'github-slugger';
2
+ import BananaSlug from '@rspress/shared/github-slugger';
3
3
  import { Children, useMemo } from 'react';
4
4
  import { X } from './_X.js';
5
5
  // TODO: use context to simplify the usage of `slugger`