@file-viewer/renderer-text 3.1.1 → 3.2.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 (64) hide show
  1. package/README.en.md +3 -50
  2. package/README.md +3 -50
  3. package/bin/copy-xml-profile-assets.mjs +59 -0
  4. package/dist/code.d.ts +0 -7
  5. package/dist/code.js +6 -138
  6. package/dist/html.js +2 -4
  7. package/dist/index.js +30 -3
  8. package/dist/largeText.js +39 -24
  9. package/dist/lrc.d.ts +2 -0
  10. package/dist/lrc.js +185 -0
  11. package/dist/lrcParser.d.ts +23 -0
  12. package/dist/lrcParser.js +83 -0
  13. package/dist/markdown.d.ts +1 -1
  14. package/dist/markdown.js +95 -31
  15. package/dist/markdownAnchors.d.ts +1 -0
  16. package/dist/markdownAnchors.js +66 -0
  17. package/dist/optionalCapabilities.d.ts +0 -4
  18. package/dist/optionalCapabilities.js +0 -4
  19. package/dist/patch.js +11 -4
  20. package/dist/prettyPrint.d.ts +0 -7
  21. package/dist/prettyPrint.js +0 -9
  22. package/dist/sanitizeHtml.d.ts +0 -1
  23. package/dist/sanitizeHtml.js +0 -1
  24. package/dist/syntaxGrammars/data.d.ts +10 -0
  25. package/dist/syntaxGrammars/data.js +8 -0
  26. package/dist/syntaxGrammars/documents.d.ts +5 -0
  27. package/dist/syntaxGrammars/documents.js +3 -0
  28. package/dist/syntaxGrammars/managed.d.ts +7 -0
  29. package/dist/syntaxGrammars/managed.js +5 -0
  30. package/dist/syntaxGrammars/native.d.ts +10 -0
  31. package/dist/syntaxGrammars/native.js +8 -0
  32. package/dist/syntaxGrammars/php.d.ts +5 -0
  33. package/dist/syntaxGrammars/php.js +3 -0
  34. package/dist/syntaxGrammars/scripting.d.ts +9 -0
  35. package/dist/syntaxGrammars/scripting.js +7 -0
  36. package/dist/syntaxGrammars/tooling.d.ts +8 -0
  37. package/dist/syntaxGrammars/tooling.js +6 -0
  38. package/dist/syntaxGrammars/web.d.ts +8 -0
  39. package/dist/syntaxGrammars/web.js +6 -0
  40. package/dist/syntaxHighlight.d.ts +5 -0
  41. package/dist/syntaxHighlight.js +167 -0
  42. package/dist/xml-profiles.d.ts +3 -0
  43. package/dist/xml-profiles.js +4 -0
  44. package/dist/xml.d.ts +10 -0
  45. package/dist/xml.js +169 -0
  46. package/dist/xmlEngines.d.ts +9 -0
  47. package/dist/xmlEngines.js +157 -0
  48. package/dist/xmlProfiles.d.ts +7 -0
  49. package/dist/xmlProfiles.js +145 -0
  50. package/dist/xmlRegistration.d.ts +8 -0
  51. package/dist/xmlRegistration.js +13 -0
  52. package/dist/xmlSafety.d.ts +18 -0
  53. package/dist/xmlSafety.js +143 -0
  54. package/dist/xmlWasmMemory.d.ts +1 -0
  55. package/dist/xmlWasmMemory.js +71 -0
  56. package/file-viewer.capability.json +1 -1
  57. package/licenses/xml-profiles/NOTICE.md +31 -0
  58. package/licenses/xml-profiles/libxml2-xsd-Copyright.txt +23 -0
  59. package/licenses/xml-profiles/libxml2-xslt-Copyright.txt +24 -0
  60. package/licenses/xml-profiles/libxslt-Copyright.txt +53 -0
  61. package/licenses/xml-profiles/xmllint-wasm-COPYING.txt +21 -0
  62. package/licenses/xml-profiles/xslt-polyfill-LICENSE.txt +28 -0
  63. package/licenses/xml-profiles/zlib-LICENSE.txt +22 -0
  64. package/package.json +104 -23
package/README.en.md CHANGED
@@ -1,54 +1,7 @@
1
1
  # @file-viewer/renderer-text
2
2
 
3
- Base code, text, and Markdown renderer package for Flyfish File Viewer. Mermaid, side-by-side patch diff, and Git bundle inspection live in `@file-viewer/capability-mermaid` and `@file-viewer/capability-text-tools`; they are excluded from the standard/full default closure.
3
+ Runtime package version 3.2.0.
4
4
 
5
- ## Usage
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { textRenderer } from '@file-viewer/renderer-text'
10
-
11
- const options = {
12
- builtinRenderers: 'none',
13
- renderers: textRenderer,
14
- text: {
15
- lineNumbers: true,
16
- wrapLongLines: true,
17
- prettyPrint: true,
18
- prettyPrintMaxBytes: 512 * 1024,
19
- },
20
- }
21
- ```
22
-
23
- You can also compose it with other renderers:
24
-
25
- ```ts
26
- import { textRenderer } from '@file-viewer/renderer-text'
27
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
28
-
29
- const options = {
30
- builtinRenderers: 'none',
31
- renderers: [pdfRenderer, textRenderer],
32
- }
33
- ```
34
-
35
- ## Capabilities
36
-
37
- - Code and text preview uses `highlight.js` core with per-language dynamic imports instead of registering every language up front.
38
- - Code, text, and virtualized Markdown source views show their file type, indexing status, and line-count metadata bar by default. Set `options.text.toolbar: false` to hide this renderer-local bar without hiding the viewer-level download, search, or zoom toolbar.
39
- - Regular code and text previews can show a line-number gutter with `options.text.lineNumbers: true`. The gutter is excluded from copied source, search matches, and assistive reading. Virtual large-text views keep their existing gutter unless it is explicitly set to `false`.
40
- - `options.text.wrapLongLines: true` changes layout only and never inserts source newlines. Regular previews keep one gutter entry per logical line; large files remain bounded in the virtual window while wrapping to the available width.
41
- - `options.text.prettyPrint: true` lazily loads Prettier and only the parser plugins needed by a supported structured format. It formats a display copy, labels the toolbar as a formatted preview, and provides a switch back to the original source. JSON/JSONC/JSON5, JavaScript/TypeScript, HTML/Vue, CSS, YAML, Markdown, GraphQL, and XML share this path.
42
- - `prettyPrintMaxBytes` limits only Prettier and defaults to the effective `virtualizeAboveBytes` value (512 KiB when omitted). Oversized, malformed, and unsupported inputs fall back to the original source, which continues through the existing regular or virtual renderer. XML uses a conservative whitespace-preserving mode; mixed content and `xml:space="preserve"` stay on the original source path.
43
- - The legacy `*-full` script-tag IIFE assets do not bundle Prettier, so `prettyPrint` falls back to the original source there. Use the ESM integration (standard component packages or `@file-viewer/preset-*`) for formatted previews.
44
- - With the text-tools capability installed, `patch` uses `diff2html` for side-by-side review and `bundle` / `bdl` enables Git bundle inspection.
45
- - With the Mermaid capability installed, fenced Mermaid blocks render as diagrams. Without it, the source stays visible with the exact CLI enablement command.
46
- - HTML/HTM opens a static page preview with a source-view toggle. `options.text.htmlView: 'source'` starts with the original source. Inline CSS and embedded images are preserved; scripts, forms, external navigation, and external resource requests are blocked by sanitization, CSP, and an opaque sandbox. This is not a website runtime.
47
- - XML, Vue, and similar files remain escaped source previews. HTML source supports the same highlighting, formatting, and large-text virtualization options.
48
- - Markdown uses `marked` for a read-only reading surface with dark/light theme support, table scrolling, and a unified zoom provider.
49
- - Markdown no longer falls back to source because of the general large-text threshold. Set `options.text.markdownVirtualizeAboveBytes` only when an application must bound exceptionally large Markdown files.
50
- - Does not depend on any online service or public CDN, making it suitable for intranet logs, configs, snippets, README files, and knowledge-base attachments.
51
-
52
- ## Migration Note
53
-
54
- Standard/full includes base code, text, and Markdown without installing `diff2html`, `pako`, or Mermaid. Optional uploads show `npx file-viewer-cli add text-tools --write` or `add mermaid-markdown --write`; `preset-all` is only for explicit all/debug use.
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
package/README.md CHANGED
@@ -1,54 +1,7 @@
1
1
  # @file-viewer/renderer-text
2
2
 
3
- Flyfish File Viewer 的基础代码、文本和 Markdown renderer 包。Mermaid、patch 左右比对和 Git bundle 检查已拆到 `@file-viewer/capability-mermaid` 与 `@file-viewer/capability-text-tools`,不进入 standard/full 默认闭包。
3
+ Runtime package version 3.2.0.
4
4
 
5
- ## 用法
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { textRenderer } from '@file-viewer/renderer-text'
10
-
11
- const options = {
12
- builtinRenderers: 'none',
13
- renderers: textRenderer,
14
- text: {
15
- lineNumbers: true,
16
- wrapLongLines: true,
17
- prettyPrint: true,
18
- prettyPrintMaxBytes: 512 * 1024,
19
- },
20
- }
21
- ```
22
-
23
- 也可以与其他 renderer 组合:
24
-
25
- ```ts
26
- import { textRenderer } from '@file-viewer/renderer-text'
27
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
28
-
29
- const options = {
30
- builtinRenderers: 'none',
31
- renderers: [pdfRenderer, textRenderer],
32
- }
33
- ```
34
-
35
- ## 能力边界
36
-
37
- - 代码和文本使用 `highlight.js` core + 按语言动态加载,避免一次性注册全部语言。
38
- - 代码、文本和超大 Markdown 源码视图默认显示文件类型、索引状态和行数元信息栏;传入 `options.text.toolbar: false` 可隐藏该 renderer 内部栏,不影响 Viewer 的下载、搜索、缩放等全局工具栏。
39
- - 普通代码和文本可通过 `options.text.lineNumbers: true` 显示行号;行号不会进入复制内容、搜索结果或无障碍朗读。超大文本保留原有的虚拟行号栏,可显式传 `false` 隐藏。
40
- - `options.text.wrapLongLines: true` 仅改变布局,不向源码插入换行。普通预览会按逻辑行维护行号,超大文本仍使用有界虚拟窗口并按可用宽度换行。
41
- - `options.text.prettyPrint: true` 会在支持的结构化文本上按需加载 Prettier 与对应 parser,仅格式化显示副本;工具栏会标明“格式化预览”,并可切回原始源码。JSON/JSONC/JSON5、JavaScript/TypeScript、HTML/Vue、CSS、YAML、Markdown、GraphQL 和 XML 共用同一路径。
42
- - `prettyPrintMaxBytes` 只限制 Prettier,默认继承 `virtualizeAboveBytes`(未配置时为 512 KiB)。超限、语法错误或不支持的格式直接回退原始源码,之后仍由普通或虚拟文本 renderer 决定展示方式。XML 使用保守的 whitespace-preserving 模式;检测到混合内容或 `xml:space="preserve"` 时直接保留原文。
43
- - 历史 `*-full` 包的 script 标签 IIFE 资源不打包 Prettier,该路径下 `prettyPrint` 无错误回退到原始源码;需要格式化预览时使用 ESM 集成(标准组件包或 `@file-viewer/preset-*`)。
44
- - 安装 text-tools capability 后,`patch` 使用 `diff2html` 渲染左右比对视图,`bundle` / `bdl` 才启用 Git bundle 结构检查。
45
- - 安装 Mermaid capability 后,Markdown 内嵌 Mermaid 图才会渲染;未安装时保留源码并显示精确 CLI 启用命令。
46
- - HTML / HTM 默认显示静态页面,提供页面与源码切换;`options.text.htmlView: 'source'` 可默认查看原始源码。页面保留内联 CSS 和内嵌图片,通过净化、CSP 和独立沙箱阻止脚本、表单、外链跳转和外部资源请求,不用于运行完整网站。
47
- - XML / Vue 等仍按源码转义展示。HTML 源码视图继续支持高亮、格式化和大文本虚拟化。
48
- - Markdown 使用 `marked` 输出只读阅读面,并保留明暗主题、表格滚动和统一缩放 provider。
49
- - Markdown 不再因为通用大文本阈值自动退化成源码;如业务必须限制超大 Markdown,可单独设置 `options.text.markdownVirtualizeAboveBytes`。
50
- - 不绑定任何在线服务或公共 CDN,适合内网日志、配置、代码片段、README 和知识库附件预览。
51
-
52
- ## 迁移说明
53
-
54
- standard/full 默认包含基础代码、文本和 Markdown,不安装 `diff2html`、`pako` 或 Mermaid。打开可选格式时会提示运行 `npx file-viewer-cli add text-tools --write` 或 `add mermaid-markdown --write`;`preset-all` 仅用于显式全量/调试。
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module'
3
+ import { realpathSync } from 'node:fs'
4
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
5
+ import { createHash } from 'node:crypto'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const require = createRequire(import.meta.url)
10
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
11
+ const engines = [
12
+ { name: 'xmllint-wasm', version: '5.3.0', files: ['xmllint-browser.mjs', 'xmllint.wasm'] },
13
+ { name: 'xslt-polyfill', version: '1.0.31', files: ['dist/xslt-wasm.js'] }
14
+ ]
15
+
16
+ /** Copy pinned optional runtimes and notices; never download or install packages. */
17
+ export async function copyXmlProfileAssets(destination = 'public/file-viewer/xml') {
18
+ const output = new Map()
19
+ for (const engine of engines) {
20
+ let manifest
21
+ try { manifest = require.resolve(`${engine.name}/package.json`) } catch {
22
+ throw new Error(`Install the optional XML engines first: pnpm add xmllint-wasm@5.3.0 xslt-polyfill@1.0.31 (missing ${engine.name}).`)
23
+ }
24
+ const metadata = JSON.parse(await readFile(manifest, 'utf8'))
25
+ if (metadata.version !== engine.version) throw new Error(`Expected ${engine.name}@${engine.version}; found ${metadata.version}.`)
26
+ for (const name of engine.files) output.set(name.split('/').at(-1), await readFile(join(dirname(manifest), name)))
27
+ }
28
+ const licenses = join(packageRoot, 'licenses/xml-profiles')
29
+ for (const name of await readdir(licenses)) output.set(`licenses/${name}`, await readFile(join(licenses, name)))
30
+ const files = Object.fromEntries([...output].map(([name, bytes]) => [name, {
31
+ bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex')
32
+ }]))
33
+ output.set('manifest.json', Buffer.from(JSON.stringify({
34
+ schema: 1, engines: engines.map(({ name, version }) => ({ name, version })), files
35
+ }, null, 2) + '\n'))
36
+ destination = resolve(destination)
37
+ // Resolve every dependency before writing, and touch only the named XML assets.
38
+ for (const [name, bytes] of output) {
39
+ const filename = join(destination, name)
40
+ await mkdir(dirname(filename), { recursive: true })
41
+ await writeFile(filename, bytes)
42
+ }
43
+ return { destination, files }
44
+ }
45
+
46
+ let entryPoint = false
47
+ try { entryPoint = !!process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url) } catch { /* Imported helper. */ }
48
+ if (entryPoint) {
49
+ if (process.argv.includes('--help')) {
50
+ console.log('Usage: file-viewer-xml-assets [destination-directory]\nDefault: public/file-viewer/xml\nRequires xmllint-wasm@5.3.0 and xslt-polyfill@1.0.31 installed by the host.')
51
+ } else if (process.argv.length > 3 || process.argv[2]?.startsWith('-')) {
52
+ console.error('Expected one destination directory.'); process.exitCode = 1
53
+ } else {
54
+ copyXmlProfileAssets(process.argv[2]).then(
55
+ ({ destination }) => console.log(`XML profile assets copied to ${destination}`),
56
+ error => { console.error(error.message); process.exitCode = 1 }
57
+ )
58
+ }
59
+ }
package/dist/code.d.ts CHANGED
@@ -1,9 +1,2 @@
1
1
  import { type FileRenderContext, type FileViewerRenderedInstance } from '@file-viewer/core';
2
- /**
3
- * Framework-neutral text/code renderer.
4
- *
5
- * highlight.js core, Prettier standalone, and parser definitions are loaded
6
- * lazily by format. HTML and XML are always mounted as escaped source text and
7
- * never executed as real DOM.
8
- */
9
2
  export default function renderText(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
package/dist/code.js CHANGED
@@ -1,90 +1,8 @@
1
1
  import { createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, decodeFileViewerTextBuffer, registerFileViewerZoomProvider, unregisterFileViewerZoomProvider } from '@file-viewer/core';
2
+ import { escapeHtml, loadHighlighter, registerLanguageOnce, resolveLanguage } from './syntaxHighlight.js';
2
3
  import { codeStyle } from './codeStyle.js';
3
4
  import renderLargeText, { shouldVirtualizeTextBuffer } from './largeText.js';
4
5
  import { formatFileViewerTextForDisplay, resolveFileViewerPrettyPrintMaxBytes, supportsFileViewerPrettyPrint } from './prettyPrint.js';
5
- const languageMap = {
6
- bash: 'bash',
7
- c: 'cpp',
8
- cc: 'cpp',
9
- cjs: 'javascript',
10
- cpp: 'cpp',
11
- cs: 'csharp',
12
- css: 'css',
13
- diff: 'diff',
14
- patch: 'diff',
15
- bundle: 'plaintext',
16
- bdl: 'plaintext',
17
- gv: 'plaintext',
18
- go: 'go',
19
- graphql: 'graphql',
20
- gql: 'graphql',
21
- h: 'cpp',
22
- hcl: 'plaintext',
23
- hpp: 'cpp',
24
- html: 'xml',
25
- htm: 'xml',
26
- http: 'http',
27
- ini: 'ini',
28
- ipynb: 'json',
29
- java: 'java',
30
- js: 'javascript',
31
- json: 'json',
32
- json5: 'json',
33
- jsonc: 'json',
34
- jsx: 'javascript',
35
- kt: 'kotlin',
36
- log: 'plaintext',
37
- md: 'markdown',
38
- markdown: 'markdown',
39
- mjs: 'javascript',
40
- php: 'php',
41
- proto: 'protobuf',
42
- py: 'python',
43
- rb: 'ruby',
44
- react: 'javascript',
45
- rs: 'rust',
46
- sh: 'bash',
47
- sql: 'sql',
48
- swift: 'swift',
49
- tex: 'latex',
50
- toml: 'ini',
51
- ts: 'typescript',
52
- tsx: 'typescript',
53
- txt: 'plaintext',
54
- vue: 'xml',
55
- xml: 'xml',
56
- yaml: 'yaml',
57
- yml: 'yaml'
58
- };
59
- const languageLoaders = {
60
- bash: () => import('highlight.js/lib/languages/bash'),
61
- cpp: () => import('highlight.js/lib/languages/cpp'),
62
- csharp: () => import('highlight.js/lib/languages/csharp'),
63
- css: () => import('highlight.js/lib/languages/css'),
64
- diff: () => import('highlight.js/lib/languages/diff'),
65
- go: () => import('highlight.js/lib/languages/go'),
66
- graphql: () => import('highlight.js/lib/languages/graphql'),
67
- http: () => import('highlight.js/lib/languages/http'),
68
- ini: () => import('highlight.js/lib/languages/ini'),
69
- java: () => import('highlight.js/lib/languages/java'),
70
- javascript: () => import('highlight.js/lib/languages/javascript'),
71
- json: () => import('highlight.js/lib/languages/json'),
72
- kotlin: () => import('highlight.js/lib/languages/kotlin'),
73
- latex: () => import('highlight.js/lib/languages/latex'),
74
- markdown: () => import('highlight.js/lib/languages/markdown'),
75
- php: () => import('highlight.js/lib/languages/php'),
76
- protobuf: () => import('highlight.js/lib/languages/protobuf'),
77
- python: () => import('highlight.js/lib/languages/python'),
78
- ruby: () => import('highlight.js/lib/languages/ruby'),
79
- rust: () => import('highlight.js/lib/languages/rust'),
80
- sql: () => import('highlight.js/lib/languages/sql'),
81
- swift: () => import('highlight.js/lib/languages/swift'),
82
- typescript: () => import('highlight.js/lib/languages/typescript'),
83
- xml: () => import('highlight.js/lib/languages/xml'),
84
- yaml: () => import('highlight.js/lib/languages/yaml')
85
- };
86
- let highlighterPromise = null;
87
- const registeredLanguages = new Set();
88
6
  const createElement = (documentRef, tagName, className, text) => {
89
7
  const element = documentRef.createElement(tagName);
90
8
  if (className) {
@@ -100,40 +18,6 @@ const createStyle = (documentRef) => {
100
18
  style.textContent = codeStyle;
101
19
  return style;
102
20
  };
103
- const resolveLanguage = (type) => {
104
- return languageMap[type.trim().toLowerCase()] || 'plaintext';
105
- };
106
- const escapeHtml = (value) => {
107
- return value.replace(/[&<>"']/g, char => {
108
- const entities = {
109
- '&': '&amp;',
110
- '<': '&lt;',
111
- '>': '&gt;',
112
- '"': '&quot;',
113
- "'": '&#39;'
114
- };
115
- return entities[char];
116
- });
117
- };
118
- const loadHighlighter = async () => {
119
- if (!highlighterPromise) {
120
- highlighterPromise = import('highlight.js/lib/core').then(module => module.default);
121
- }
122
- return highlighterPromise;
123
- };
124
- const registerLanguageOnce = async (hljs, name) => {
125
- if (registeredLanguages.has(name)) {
126
- return true;
127
- }
128
- const loader = languageLoaders[name];
129
- if (!loader) {
130
- return false;
131
- }
132
- const { default: language } = await loader();
133
- hljs.registerLanguage(name, language);
134
- registeredLanguages.add(name);
135
- return true;
136
- };
137
21
  const clampZoom = (value) => {
138
22
  return Math.min(2.6, Math.max(0.6, Number(value.toFixed(2))));
139
23
  };
@@ -152,12 +36,6 @@ const createWrappedSourceLine = (documentRef, lineNumber) => {
152
36
  row.append(number, content);
153
37
  return { row, content };
154
38
  };
155
- /**
156
- * Splits trusted highlight.js markup into logical source-line wrappers while
157
- * recreating active token spans after every newline. This keeps multiline
158
- * comments and strings highlighted without coupling visual wrapping to source
159
- * line numbers.
160
- */
161
39
  const mountWrappedHighlightedLines = (code, highlightedHtml, expectedLineCount) => {
162
40
  const documentRef = code.ownerDocument;
163
41
  const staging = createElement(documentRef, 'span');
@@ -172,7 +50,7 @@ const mountWrappedHighlightedLines = (code, highlightedHtml, expectedLineCount)
172
50
  lineIndex += 1;
173
51
  lines.push(createWrappedSourceLine(documentRef, lineIndex + 1));
174
52
  let parent = currentContent();
175
- activeClones = activeElements.map(element => {
53
+ activeClones = activeElements.map((element) => {
176
54
  const clone = element.cloneNode(false);
177
55
  parent.append(clone);
178
56
  parent = clone;
@@ -209,7 +87,7 @@ const mountWrappedHighlightedLines = (code, highlightedHtml, expectedLineCount)
209
87
  while (lines.length < expectedLineCount) {
210
88
  lines.push(createWrappedSourceLine(documentRef, lines.length + 1));
211
89
  }
212
- code.replaceChildren(...lines.map(line => line.row));
90
+ code.replaceChildren(...lines.map((line) => line.row));
213
91
  };
214
92
  const mountCodeMarkup = (pre, code, highlightedHtml, lineCount, showLineNumbers, wrapLongLines) => {
215
93
  code.replaceChildren();
@@ -231,18 +109,8 @@ const mountCodeMarkup = (pre, code, highlightedHtml, lineCount, showLineNumbers,
231
109
  code.innerHTML = highlightedHtml;
232
110
  };
233
111
  const canPossiblyFitDecodedPrettyPrintLimit = (buffer, maxBytes) => {
234
- // UTF-16 ASCII is the widest supported source encoding relative to its
235
- // decoded UTF-8 representation. This fast guard avoids decoding enormous
236
- // structured files that cannot possibly fit the configured decoded limit.
237
- return buffer.byteLength <= (maxBytes * 2) + 4;
112
+ return buffer.byteLength <= maxBytes * 2 + 4;
238
113
  };
239
- /**
240
- * Framework-neutral text/code renderer.
241
- *
242
- * highlight.js core, Prettier standalone, and parser definitions are loaded
243
- * lazily by format. HTML and XML are always mounted as escaped source text and
244
- * never executed as real DOM.
245
- */
246
114
  export default async function renderText(buffer, target, type, context) {
247
115
  var _a, _b;
248
116
  const t = createFileViewerTranslator(context === null || context === void 0 ? void 0 : context.options);
@@ -254,7 +122,7 @@ export default async function renderText(buffer, target, type, context) {
254
122
  if ((textOptions === null || textOptions === void 0 ? void 0 : textOptions.prettyPrint) === true &&
255
123
  supportsFileViewerPrettyPrint(normalizedExtension) &&
256
124
  canPossiblyFitDecodedPrettyPrintLimit(buffer, resolveFileViewerPrettyPrintMaxBytes(textOptions))) {
257
- sourceText = decodeFileViewerTextBuffer(buffer, textOptions.encoding).text;
125
+ sourceText = decodeFileViewerTextBuffer(buffer, textOptions.encoding, textOptions.fallbackEncoding).text;
258
126
  prettyPrintResult = await formatFileViewerTextForDisplay(sourceText, normalizedExtension, textOptions, context === null || context === void 0 ? void 0 : context.signal);
259
127
  }
260
128
  if (!(prettyPrintResult === null || prettyPrintResult === void 0 ? void 0 : prettyPrintResult.formatted) &&
@@ -271,7 +139,7 @@ export default async function renderText(buffer, target, type, context) {
271
139
  const { default: renderGitBundle } = await import('./gitBundle.js');
272
140
  return renderGitBundle(buffer, target, extension, context);
273
141
  }
274
- const originalText = sourceText !== null && sourceText !== void 0 ? sourceText : decodeFileViewerTextBuffer(buffer, textOptions === null || textOptions === void 0 ? void 0 : textOptions.encoding).text;
142
+ const originalText = sourceText !== null && sourceText !== void 0 ? sourceText : decodeFileViewerTextBuffer(buffer, textOptions === null || textOptions === void 0 ? void 0 : textOptions.encoding, textOptions === null || textOptions === void 0 ? void 0 : textOptions.fallbackEncoding).text;
275
143
  const formattedText = (prettyPrintResult === null || prettyPrintResult === void 0 ? void 0 : prettyPrintResult.formatted) ? prettyPrintResult.text : null;
276
144
  const language = resolveLanguage(extension);
277
145
  const showToolbar = (textOptions === null || textOptions === void 0 ? void 0 : textOptions.toolbar) !== false;
package/dist/html.js CHANGED
@@ -40,8 +40,6 @@ export function createHtmlPreviewDocument(documentRef, source) {
40
40
  }
41
41
  }
42
42
  }
43
- // CSP is first, before any retained inline CSS. The containing iframe also has
44
- // an opaque origin and no sandbox permissions, even if sanitization regresses.
45
43
  const policy = preview.createElement('meta');
46
44
  policy.httpEquiv = 'Content-Security-Policy';
47
45
  policy.content = previewPolicy;
@@ -99,7 +97,7 @@ export default async function renderHtml(buffer, target, type, context) {
99
97
  let sourcePending;
100
98
  let disposed = false;
101
99
  const select = async (view) => {
102
- var _a, _b;
100
+ var _a, _b, _c, _d;
103
101
  if (disposed)
104
102
  return;
105
103
  root.dataset.htmlView = view;
@@ -109,7 +107,7 @@ export default async function renderHtml(buffer, target, type, context) {
109
107
  sourceTarget.hidden = view !== 'source';
110
108
  hint.hidden = view !== 'preview';
111
109
  if (view === 'preview' && !frame.hasAttribute('srcdoc')) {
112
- frame.srcdoc = createHtmlPreviewDocument(documentRef, decodeFileViewerTextBuffer(buffer, (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.encoding).text);
110
+ frame.srcdoc = createHtmlPreviewDocument(documentRef, decodeFileViewerTextBuffer(buffer, (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.encoding, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.fallbackEncoding).text);
113
111
  }
114
112
  if (view === 'source' && !sourcePending) {
115
113
  sourcePending = renderCode(buffer, sourceTarget, type, context).then((instance) => {
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ import { getXmlProfilesLoader } from './xmlRegistration.js';
2
3
  export { getFileViewerMermaidLoader, getFileViewerDiffToHtml, getFileViewerPakoLoader, registerFileViewerDiffToHtml, registerFileViewerMermaidLoader, registerFileViewerPakoLoader, } from './optionalCapabilities.js';
3
4
  export { sanitizeFileViewerRichHtml } from './sanitizeHtml.js';
4
5
  const textRendererIds = ['code', 'markdown'];
@@ -7,9 +8,35 @@ if (textDefinitions.length !== textRendererIds.length) {
7
8
  throw new Error('@file-viewer/renderer-text could not locate the shared code/markdown format definitions.');
8
9
  }
9
10
  export const textRendererDefinitions = textDefinitions;
10
- export const renderFileViewerCode = (buffer, target, type, context) => /^(?:html|htm)$/i.test(type || '')
11
- ? import('./html.js').then(({ default: renderHtml }) => renderHtml(buffer, target, type, context))
12
- : import('./code.js').then(({ default: renderCode }) => renderCode(buffer, target, type, context));
11
+ export const renderFileViewerCode = async (buffer, target, type, context) => {
12
+ var _a, _b, _c, _d, _e;
13
+ if ((type === null || type === void 0 ? void 0 : type.trim().toLowerCase()) === 'lrc') {
14
+ const { default: renderLrc } = await import('./lrc.js');
15
+ return renderLrc(buffer, target, type, context);
16
+ }
17
+ if (/^(?:html|htm)$/i.test(type || '')) {
18
+ const { default: renderHtml } = await import('./html.js');
19
+ return renderHtml(buffer, target, type, context);
20
+ }
21
+ if ((type === null || type === void 0 ? void 0 : type.trim().toLowerCase()) === 'xml' && ((_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.xml)) {
22
+ const loader = getXmlProfilesLoader();
23
+ if (loader) {
24
+ const { default: renderXml } = await loader();
25
+ return renderXml(buffer, target, context);
26
+ }
27
+ const message = 'Enable @file-viewer/renderer-text/xml-profiles and deploy its self-hosted runtime assets.';
28
+ try {
29
+ (_c = (_b = context.options.xml).onDiagnostic) === null || _c === void 0 ? void 0 : _c.call(_b, { code: 'capability-unavailable', message });
30
+ }
31
+ catch { }
32
+ try {
33
+ (_e = (_d = context.options).onDiagnostic) === null || _e === void 0 ? void 0 : _e.call(_d, { code: 'xml-profile-capability-unavailable', level: 'warning', message });
34
+ }
35
+ catch { }
36
+ }
37
+ const { default: renderCode } = await import('./code.js');
38
+ return renderCode(buffer, target, type, context);
39
+ };
13
40
  export const renderFileViewerMarkdown = (buffer, target, type, context) => import('./largeText.js').then(async ({ default: renderLargeText, shouldVirtualizeMarkdownBuffer }) => {
14
41
  if (shouldVirtualizeMarkdownBuffer(buffer, context)) {
15
42
  return renderLargeText(buffer, target, type || 'md', context);
package/dist/largeText.js CHANGED
@@ -1,4 +1,4 @@
1
- import { DEFAULT_FILE_VIEWER_SEARCH_MAX_MATCHES, createFileViewerTextDecoder, createEmptyFileViewerSearchState, createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, normalizeFileViewerSearchOptions, resolveFileViewerTextEncoding, registerFileViewerSearchProvider, registerFileViewerZoomProvider, unregisterFileViewerSearchProvider, unregisterFileViewerZoomProvider } from '@file-viewer/core';
1
+ import { DEFAULT_FILE_VIEWER_SEARCH_MAX_MATCHES, createFileViewerTextDecoder, createEmptyFileViewerSearchState, createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, isSingleByteFileViewerTextEncoding, normalizeFileViewerSearchOptions, resolveFileViewerTextEncoding, registerFileViewerSearchProvider, registerFileViewerZoomProvider, unregisterFileViewerSearchProvider, unregisterFileViewerZoomProvider } from '@file-viewer/core';
2
2
  import { codeStyle } from './codeStyle.js';
3
3
  export const DEFAULT_LARGE_TEXT_THRESHOLD_BYTES = 512 * 1024;
4
4
  export const DEFAULT_LARGE_TEXT_LINE_SEGMENT_BYTES = 16 * 1024;
@@ -75,9 +75,22 @@ const alignGb18030Boundary = (bytes, knownBoundary, requestedOffset, limit) => {
75
75
  return cursor;
76
76
  };
77
77
  const alignTextBoundary = (index, knownBoundary, requestedOffset, limit) => {
78
- return index.encoding === 'gb18030'
79
- ? alignGb18030Boundary(index.bytes, knownBoundary, requestedOffset, limit)
80
- : alignUtf8End(index.bytes, requestedOffset, limit);
78
+ if (index.encoding === 'gb18030') {
79
+ return alignGb18030Boundary(index.bytes, knownBoundary, requestedOffset, limit);
80
+ }
81
+ if (isSingleByteFileViewerTextEncoding(index.encoding)) {
82
+ return clamp(requestedOffset, 0, limit);
83
+ }
84
+ return alignUtf8End(index.bytes, requestedOffset, limit);
85
+ };
86
+ const alignSegmentStart = (index, lineStart, requestedOffset, limit) => {
87
+ if (index.encoding === 'gb18030') {
88
+ return alignTextBoundary(index, lineStart, requestedOffset, limit);
89
+ }
90
+ if (isSingleByteFileViewerTextEncoding(index.encoding)) {
91
+ return clamp(requestedOffset, 0, limit);
92
+ }
93
+ return alignUtf8Start(index.bytes, requestedOffset, limit);
81
94
  };
82
95
  const isLineBreak = (bytes, offset) => {
83
96
  const byte = bytes[offset];
@@ -178,9 +191,7 @@ const decodeLargeTextSegment = (index, line, segmentIndex, segmentBytes) => {
178
191
  const normalizedSegment = clamp(Math.trunc(segmentIndex), 0, segmentCount - 1);
179
192
  const rawStart = line.start + (normalizedSegment * segmentBytes);
180
193
  const rawEnd = Math.min(line.end, rawStart + segmentBytes);
181
- const start = index.encoding === 'gb18030'
182
- ? alignTextBoundary(index, line.start, rawStart, line.end)
183
- : alignUtf8Start(index.bytes, rawStart, line.end);
194
+ const start = alignSegmentStart(index, line.start, rawStart, line.end);
184
195
  const end = alignTextBoundary(index, start, rawEnd, line.end);
185
196
  return {
186
197
  text: createFileViewerTextDecoder(index.encoding).decode(index.bytes.subarray(start, end)),
@@ -207,7 +218,7 @@ const cloneLargeTextSearchState = (state) => ({
207
218
  matches: state.matches.map(match => ({ ...match }))
208
219
  });
209
220
  export const shouldVirtualizeTextBuffer = (buffer, context) => {
210
- var _a, _b, _c, _d;
221
+ var _a, _b, _c, _d, _e, _f;
211
222
  const configured = (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.virtualizeAboveBytes;
212
223
  const threshold = Number.isFinite(configured)
213
224
  ? Math.max(0, Number(configured))
@@ -216,11 +227,11 @@ export const shouldVirtualizeTextBuffer = (buffer, context) => {
216
227
  return false;
217
228
  }
218
229
  const bytes = new Uint8Array(buffer);
219
- const { encoding } = resolveFileViewerTextEncoding(bytes, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.encoding);
230
+ const { encoding } = resolveFileViewerTextEncoding(bytes, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.encoding, (_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.text) === null || _f === void 0 ? void 0 : _f.fallbackEncoding);
220
231
  return encoding !== 'utf-16le' && encoding !== 'utf-16be';
221
232
  };
222
233
  export const shouldVirtualizeMarkdownBuffer = (buffer, context) => {
223
- var _a, _b, _c, _d;
234
+ var _a, _b, _c, _d, _e, _f;
224
235
  const configured = (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.markdownVirtualizeAboveBytes;
225
236
  if (!Number.isFinite(configured)) {
226
237
  return false;
@@ -229,7 +240,7 @@ export const shouldVirtualizeMarkdownBuffer = (buffer, context) => {
229
240
  return false;
230
241
  }
231
242
  const bytes = new Uint8Array(buffer);
232
- const { encoding } = resolveFileViewerTextEncoding(bytes, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.encoding);
243
+ const { encoding } = resolveFileViewerTextEncoding(bytes, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.encoding, (_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.text) === null || _f === void 0 ? void 0 : _f.fallbackEncoding);
233
244
  return encoding !== 'utf-16le' && encoding !== 'utf-16be';
234
245
  };
235
246
  const largeTextStyle = `
@@ -255,25 +266,23 @@ const largeTextStyle = `
255
266
  .code-viewer--virtual.code-viewer--wrap-lines .code-virtual-content{display:block;min-width:0;flex:1 1 auto;padding:0 18px;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
256
267
  `;
257
268
  export default async function renderLargeText(buffer, target, type = 'txt', context) {
258
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
269
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
259
270
  const t = createFileViewerTranslator(context === null || context === void 0 ? void 0 : context.options);
260
271
  const documentRef = target.ownerDocument;
261
272
  const sourceBytes = new Uint8Array(buffer);
262
- const source = resolveFileViewerTextEncoding(sourceBytes, (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.encoding);
273
+ const source = resolveFileViewerTextEncoding(sourceBytes, (_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.encoding, (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.fallbackEncoding);
263
274
  const bytes = sourceBytes.subarray(source.bomLength);
264
- const configuredSegmentBytes = (_d = (_c = context === null || context === void 0 ? void 0 : context.options) === null || _c === void 0 ? void 0 : _c.text) === null || _d === void 0 ? void 0 : _d.maxRenderedLineBytes;
275
+ const configuredSegmentBytes = (_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.text) === null || _f === void 0 ? void 0 : _f.maxRenderedLineBytes;
265
276
  const segmentBytes = Number.isFinite(configuredSegmentBytes)
266
277
  ? clamp(Math.trunc(Number(configuredSegmentBytes)), 1024, 256 * 1024)
267
278
  : DEFAULT_LARGE_TEXT_LINE_SEGMENT_BYTES;
268
- const configuredOverscan = (_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.text) === null || _f === void 0 ? void 0 : _f.virtualOverscanLines;
279
+ const configuredOverscan = (_h = (_g = context === null || context === void 0 ? void 0 : context.options) === null || _g === void 0 ? void 0 : _g.text) === null || _h === void 0 ? void 0 : _h.virtualOverscanLines;
269
280
  const overscan = Number.isFinite(configuredOverscan)
270
281
  ? clamp(Math.trunc(Number(configuredOverscan)), 2, 100)
271
282
  : DEFAULT_LARGE_TEXT_OVERSCAN_LINES;
272
- const showToolbar = ((_h = (_g = context === null || context === void 0 ? void 0 : context.options) === null || _g === void 0 ? void 0 : _g.text) === null || _h === void 0 ? void 0 : _h.toolbar) !== false;
273
- // Undefined preserves the large-text renderer's pre-option behavior. An
274
- // explicit boolean has the same meaning in both regular and virtual views.
275
- const showLineNumbers = ((_k = (_j = context === null || context === void 0 ? void 0 : context.options) === null || _j === void 0 ? void 0 : _j.text) === null || _k === void 0 ? void 0 : _k.lineNumbers) !== false;
276
- const wrapLongLines = ((_m = (_l = context === null || context === void 0 ? void 0 : context.options) === null || _l === void 0 ? void 0 : _l.text) === null || _m === void 0 ? void 0 : _m.wrapLongLines) === true;
283
+ const showToolbar = ((_k = (_j = context === null || context === void 0 ? void 0 : context.options) === null || _j === void 0 ? void 0 : _j.text) === null || _k === void 0 ? void 0 : _k.toolbar) !== false;
284
+ const showLineNumbers = ((_m = (_l = context === null || context === void 0 ? void 0 : context.options) === null || _l === void 0 ? void 0 : _l.text) === null || _m === void 0 ? void 0 : _m.lineNumbers) !== false;
285
+ const wrapLongLines = ((_p = (_o = context === null || context === void 0 ? void 0 : context.options) === null || _o === void 0 ? void 0 : _o.text) === null || _p === void 0 ? void 0 : _p.wrapLongLines) === true;
277
286
  let disposed = false;
278
287
  let zoom = 1;
279
288
  let scheduledFrame = 0;
@@ -313,7 +322,7 @@ export default async function renderLargeText(buffer, target, type = 'txt', cont
313
322
  root.append(toolbar);
314
323
  }
315
324
  target.replaceChildren(style, root);
316
- (_o = context === null || context === void 0 ? void 0 : context.onProgressiveRender) === null || _o === void 0 ? void 0 : _o.call(context);
325
+ (_q = context === null || context === void 0 ? void 0 : context.onProgressiveRender) === null || _q === void 0 ? void 0 : _q.call(context);
317
326
  const index = await buildLargeTextIndex(bytes, source.encoding, target, progress => {
318
327
  if (!disposed) {
319
328
  status.textContent = t('text.code.indexingLargeFile', { progress });
@@ -651,11 +660,17 @@ export default async function renderLargeText(buffer, target, type = 'txt', cont
651
660
  const maxMatches = Math.max(1, options.maxMatches || DEFAULT_FILE_VIEWER_SEARCH_MAX_MATCHES);
652
661
  const expression = createLargeTextSearchRegExp(query, options);
653
662
  const encoder = new TextEncoder();
663
+ const singleByte = isSingleByteFileViewerTextEncoding(index.encoding);
654
664
  const encodedQueryBytes = index.encoding === 'gb18030'
655
665
  ? query.length * 4
656
- : encoder.encode(query).byteLength;
666
+ : singleByte
667
+ ? query.length
668
+ : encoder.encode(query).byteLength;
657
669
  const overlap = clamp(encodedQueryBytes * 2, 256, 64 * 1024);
658
670
  const advanceBytesForCharacters = (start, end, characterCount) => {
671
+ if (singleByte) {
672
+ return clamp(characterCount, 0, Math.max(0, end - start));
673
+ }
659
674
  if (index.encoding !== 'gb18030') {
660
675
  const decoded = createFileViewerTextDecoder(index.encoding).decode(index.bytes.subarray(start, end));
661
676
  return encoder.encode(decoded.slice(0, characterCount)).byteLength;
@@ -753,7 +768,7 @@ export default async function renderLargeText(buffer, target, type = 'txt', cont
753
768
  getState: getZoomState,
754
769
  subscribe: zoomEmitter.subscribe
755
770
  });
756
- (_p = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _p === void 0 ? void 0 : _p.call(context, { print: false, exportHtml: false });
771
+ (_r = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _r === void 0 ? void 0 : _r.call(context, { print: false, exportHtml: false });
757
772
  viewport.addEventListener('scroll', scheduleRender, { passive: true });
758
773
  viewport.addEventListener('click', event => {
759
774
  var _a, _b;
@@ -779,7 +794,7 @@ export default async function renderLargeText(buffer, target, type = 'txt', cont
779
794
  lineSegments.set(lineIndex, clamp(next, 0, segmentCount - 1));
780
795
  renderWindow(true);
781
796
  });
782
- const ResizeObserverCtor = (_q = getWindow(target)) === null || _q === void 0 ? void 0 : _q.ResizeObserver;
797
+ const ResizeObserverCtor = (_s = getWindow(target)) === null || _s === void 0 ? void 0 : _s.ResizeObserver;
783
798
  const resizeObserver = ResizeObserverCtor
784
799
  ? new ResizeObserverCtor(() => {
785
800
  if (wrapLongLines) {
package/dist/lrc.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { type FileRenderContext, type FileViewerRenderedInstance } from '@file-viewer/core';
2
+ export default function renderLrc(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;