@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
@@ -0,0 +1,157 @@
1
+ import { checkXmlAbort, XmlProfileError } from './xmlSafety.js';
2
+ import { limitXmlWasmMemory } from './xmlWasmMemory.js';
3
+ function runXsltWorker() {
4
+ const scope = globalThis;
5
+ const NativeModule = WebAssembly.Module;
6
+ WebAssembly.Module = class extends NativeModule {
7
+ constructor(bytes) {
8
+ super(scope.__fileViewerLimitXmlWasmMemory(bytes));
9
+ if (NativeModule.imports(this).some(entry => entry.kind === 'memory')) {
10
+ throw new Error('Imported XML WASM memory is not supported.');
11
+ }
12
+ }
13
+ };
14
+ let networkAttempt = false;
15
+ const deny = () => { networkAttempt = true; throw new Error('External XML resources are disabled.'); };
16
+ Object.defineProperty(globalThis, 'fetch', { value: async () => deny(), writable: false, configurable: false });
17
+ for (const name of ['XMLHttpRequest', 'WebSocket', 'EventSource', 'importScripts']) {
18
+ Object.defineProperty(globalThis, name, { value: deny, writable: false, configurable: false });
19
+ }
20
+ scope.onmessage = async ({ data }) => {
21
+ let engine;
22
+ const pointers = [];
23
+ try {
24
+ engine = await createXSLTTransformModule({ print: () => undefined, printErr: () => undefined });
25
+ const encoder = new TextEncoder();
26
+ const allocate = (bytes) => {
27
+ const pointer = engine._malloc(bytes.length + 1);
28
+ if (!pointer)
29
+ throw new Error('XSLT memory allocation failed.');
30
+ pointers.push(pointer);
31
+ const heap = new Uint8Array(engine.wasmMemory.buffer);
32
+ heap.set(bytes, pointer);
33
+ heap[pointer + bytes.length] = 0;
34
+ return pointer;
35
+ };
36
+ const xml = encoder.encode(data.xml);
37
+ const style = encoder.encode(data.resource);
38
+ const xmlPointer = allocate(xml);
39
+ const stylePointer = allocate(style);
40
+ const urlPointer = allocate(encoder.encode('stylesheet.xsl'));
41
+ const mimePointer = allocate(new Uint8Array(32));
42
+ const transform = engine.cwrap('transform', 'number', Array(7).fill('number'), { async: true });
43
+ const result = await transform(xmlPointer, xml.length, stylePointer, style.length, 0, urlPointer, mimePointer);
44
+ if (!result)
45
+ throw new Error('The XSLT engine could not transform this document.');
46
+ pointers.push(result);
47
+ if (networkAttempt)
48
+ throw new Error('The XSLT engine attempted to read a blocked external resource.');
49
+ const heap = new Uint8Array(engine.wasmMemory.buffer);
50
+ let end = result;
51
+ const bound = Math.min(heap.length, result + data.maxOutputBytes + 1);
52
+ while (end < bound && heap[end] !== 0)
53
+ end++;
54
+ if (end === bound)
55
+ throw new Error('XSLT output exceeds its byte limit.');
56
+ const mime = new TextDecoder().decode(heap.subarray(mimePointer, mimePointer + 32)).split('\0')[0];
57
+ if (mime !== 'text/html' && mime !== 'application/xml')
58
+ throw new Error('XSLT did not produce HTML-compatible output.');
59
+ scope.postMessage({ html: new TextDecoder('utf-8', { fatal: true }).decode(heap.subarray(result, end)) });
60
+ }
61
+ catch (error) {
62
+ scope.postMessage({ error: error instanceof Error ? error.message.slice(0, 1024) : 'XSLT engine failed.' });
63
+ }
64
+ finally {
65
+ for (const pointer of pointers)
66
+ engine === null || engine === void 0 ? void 0 : engine._free(pointer);
67
+ }
68
+ };
69
+ }
70
+ function runXsdWorker() {
71
+ const scope = globalThis;
72
+ const deny = () => { throw new Error('External XML resources are disabled.'); };
73
+ Object.defineProperty(globalThis, 'fetch', { value: async () => deny(), writable: false, configurable: false });
74
+ for (const name of ['XMLHttpRequest', 'WebSocket', 'EventSource', 'importScripts']) {
75
+ Object.defineProperty(globalThis, name, { value: deny, writable: false, configurable: false });
76
+ }
77
+ scope.onmessage = async ({ data }) => {
78
+ let errors = '';
79
+ try {
80
+ if (!data.wasm || !WebAssembly.validate(data.wasm)) {
81
+ throw new Error('Invalid XML Schema WASM binary.');
82
+ }
83
+ await Module({
84
+ inputFiles: [
85
+ { fileName: 'input.xml', contents: data.xml },
86
+ { fileName: 'schema.xsd', contents: data.resource }
87
+ ],
88
+ arguments: ['--nonet', '--noout', '--schema', 'schema.xsd', 'input.xml'],
89
+ wasmBinary: data.wasm,
90
+ wasmMemory: new WebAssembly.Memory({ initial: 256, maximum: 1024 }),
91
+ print: () => undefined,
92
+ printErr: (message) => { errors = (errors + message + '\n').slice(0, 8192); },
93
+ onExit: (exitCode) => {
94
+ if (![0, 3, 4].includes(exitCode))
95
+ scope.postMessage({ error: errors || 'XML Schema engine failed.' });
96
+ else
97
+ scope.postMessage({ valid: exitCode === 0, message: errors });
98
+ },
99
+ onAbort: () => scope.postMessage({ error: 'XML Schema engine exhausted its memory or aborted.' })
100
+ });
101
+ }
102
+ catch (error) {
103
+ scope.postMessage({ error: error instanceof Error ? error.message.slice(0, 1024) : 'XML Schema engine failed.' });
104
+ }
105
+ };
106
+ }
107
+ async function runWorker(source, bootstrap, task, signal, module) {
108
+ checkXmlAbort(signal);
109
+ if (typeof Worker === 'undefined')
110
+ throw new XmlProfileError('engine-error', 'XML profiles require Web Workers.');
111
+ const memoryGuard = module ? '' : `\n;globalThis.__fileViewerLimitXmlWasmMemory = (${limitXmlWasmMemory.toString()});\n`;
112
+ const blobUrl = URL.createObjectURL(new Blob([source, memoryGuard, '\n;(', bootstrap.toString(), ')();'], { type: 'text/javascript' }));
113
+ let worker;
114
+ let abort;
115
+ try {
116
+ worker = new Worker(blobUrl, { type: module ? 'module' : 'classic', name: module ? 'file-viewer-xsd' : 'file-viewer-xslt' });
117
+ return await new Promise((resolve, reject) => {
118
+ abort = () => {
119
+ try {
120
+ checkXmlAbort(signal);
121
+ }
122
+ catch (error) {
123
+ reject(error);
124
+ }
125
+ };
126
+ signal.addEventListener('abort', abort, { once: true });
127
+ worker.onmessage = ({ data }) => {
128
+ if (data === null || data === void 0 ? void 0 : data.error)
129
+ reject(new XmlProfileError(module ? 'engine-error' : 'transform-error', data.error));
130
+ else if (module ? typeof (data === null || data === void 0 ? void 0 : data.valid) === 'boolean' : typeof (data === null || data === void 0 ? void 0 : data.html) === 'string')
131
+ resolve(data);
132
+ else
133
+ reject(new XmlProfileError('engine-error', 'Invalid XML worker response.'));
134
+ };
135
+ worker.onerror = event => {
136
+ var _a;
137
+ event.preventDefault();
138
+ reject(new XmlProfileError('engine-error', `XML worker failed to load or execute: ${((_a = event.message) === null || _a === void 0 ? void 0 : _a.slice(0, 1024)) || 'unknown worker error'}`));
139
+ };
140
+ worker.onmessageerror = () => reject(new XmlProfileError('engine-error', 'Invalid XML worker message.'));
141
+ checkXmlAbort(signal);
142
+ worker.postMessage(task);
143
+ });
144
+ }
145
+ finally {
146
+ if (abort)
147
+ signal.removeEventListener('abort', abort);
148
+ worker === null || worker === void 0 ? void 0 : worker.terminate();
149
+ URL.revokeObjectURL(blobUrl);
150
+ }
151
+ }
152
+ export function validateXmlWithWasm(source, wasm, xml, schema, signal) {
153
+ return runWorker(source, runXsdWorker, { xml, resource: schema, wasm, maxOutputBytes: 0 }, signal, true);
154
+ }
155
+ export function transformXmlWithWasm(source, xml, stylesheet, maxOutputBytes, signal) {
156
+ return runWorker(source, runXsltWorker, { xml, resource: stylesheet, maxOutputBytes }, signal, false);
157
+ }
@@ -0,0 +1,7 @@
1
+ import { type FileViewerXmlDiagnostic, type FileViewerXmlOptions, type FileViewerXmlProfile } from '@file-viewer/core';
2
+ export interface XmlProfileResult {
3
+ profileId: string;
4
+ html: string;
5
+ }
6
+ export declare function readXmlManifest(value: unknown, maxProfiles: number): FileViewerXmlProfile[];
7
+ export declare function applyXmlProfiles(source: string, originalBytes: number, options: FileViewerXmlOptions, documentRef: Document, signal: AbortSignal, emit: (diagnostic: FileViewerXmlDiagnostic) => void): Promise<XmlProfileResult | undefined>;
@@ -0,0 +1,145 @@
1
+ import { decodeFileViewerTextBuffer, resolveFileViewerAssetUrl } from '@file-viewer/core';
2
+ import { checkXmlAbort, fetchXmlBytes, parseSafeXml, resolveXmlLimits, sameOriginXmlUrl, xmlEngineText, XmlProfileError } from './xmlSafety.js';
3
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ export function readXmlManifest(value, maxProfiles) {
5
+ if (!record(value) || !Array.isArray(value.profiles) || value.profiles.length > maxProfiles) {
6
+ throw new XmlProfileError('invalid-manifest', 'XML manifest must contain a bounded profiles array.');
7
+ }
8
+ const ids = new Set();
9
+ return value.profiles.map((candidate) => {
10
+ if (!record(candidate) || typeof candidate.id !== 'string' || !candidate.id.trim() || candidate.id.length > 128 || ids.has(candidate.id)) {
11
+ throw new XmlProfileError('invalid-manifest', 'XML profile IDs must be nonempty and unique.');
12
+ }
13
+ ids.add(candidate.id);
14
+ const match = candidate.match;
15
+ if (!record(match))
16
+ throw new XmlProfileError('invalid-manifest', 'XML profiles require explicit enabled checks.');
17
+ for (const key of ['rootNamespace', 'xsd']) {
18
+ const check = match[key];
19
+ if (check !== undefined && (!record(check) || typeof check.enabled !== 'boolean')) {
20
+ throw new XmlProfileError('invalid-manifest', 'XML match checks require a boolean enabled field.');
21
+ }
22
+ }
23
+ const rootCheck = match.rootNamespace;
24
+ const xsdCheck = match.xsd;
25
+ if (!(rootCheck === null || rootCheck === void 0 ? void 0 : rootCheck.enabled) && !(xsdCheck === null || xsdCheck === void 0 ? void 0 : xsdCheck.enabled)) {
26
+ throw new XmlProfileError('invalid-manifest', 'Each XML profile must enable at least one check.');
27
+ }
28
+ if ((rootCheck === null || rootCheck === void 0 ? void 0 : rootCheck.enabled) && (typeof rootCheck.root !== 'string' || !rootCheck.root || typeof rootCheck.namespace !== 'string')) {
29
+ throw new XmlProfileError('invalid-manifest', 'Root matching requires a root local name and namespace (which may be empty).');
30
+ }
31
+ for (const key of (xsdCheck === null || xsdCheck === void 0 ? void 0 : xsdCheck.enabled) ? ['xsd', 'xslt'] : ['xslt']) {
32
+ if (typeof candidate[key] !== 'string' || !candidate[key] || candidate[key].length > 4096) {
33
+ throw new XmlProfileError('invalid-manifest', `XML profile is missing a valid ${key} resource.`);
34
+ }
35
+ }
36
+ return candidate;
37
+ });
38
+ }
39
+ export async function applyXmlProfiles(source, originalBytes, options, documentRef, signal, emit) {
40
+ var _a, _b, _c, _d, _e, _f;
41
+ checkXmlAbort(signal);
42
+ const limits = resolveXmlLimits(options);
43
+ if (originalBytes > limits.maxXmlBytes || new TextEncoder().encode(source).length > limits.maxXmlBytes) {
44
+ throw new XmlProfileError('limit-exceeded', 'XML exceeds the profile processing byte limit.');
45
+ }
46
+ const doc = parseSafeXml(source, documentRef, 'xml');
47
+ const origin = new URL(documentRef.URL).origin;
48
+ const resourceUrl = (value, base) => sameOriginXmlUrl(value, base, origin);
49
+ let base = documentRef.baseURI;
50
+ const cache = new Map();
51
+ let totalBytes = 0;
52
+ const read = async (url, maxBytes = limits.maxResourceBytes) => {
53
+ checkXmlAbort(signal);
54
+ let pending = cache.get(url);
55
+ if (!pending) {
56
+ pending = fetchXmlBytes(url, Math.min(maxBytes, limits.maxTotalResourceBytes - totalBytes), signal).then(bytes => {
57
+ totalBytes += bytes.length;
58
+ if (totalBytes > limits.maxTotalResourceBytes)
59
+ throw new XmlProfileError('limit-exceeded', 'XML profile resources exceed the total byte limit.');
60
+ return bytes;
61
+ });
62
+ cache.set(url, pending);
63
+ }
64
+ const bytes = await pending;
65
+ if (bytes.length > maxBytes)
66
+ throw new XmlProfileError('limit-exceeded', 'XML resource exceeds its byte limit.');
67
+ return bytes;
68
+ };
69
+ const readText = async (url) => {
70
+ const bytes = await read(url);
71
+ return decodeFileViewerTextBuffer(bytes.buffer).text;
72
+ };
73
+ try {
74
+ let profiles;
75
+ if (options.profilesUrl !== undefined && options.profiles !== undefined) {
76
+ throw new XmlProfileError('invalid-manifest', 'Use either profilesUrl or inline profiles, not both.');
77
+ }
78
+ if (options.profilesUrl !== undefined) {
79
+ if (!options.profilesUrl)
80
+ throw new XmlProfileError('invalid-manifest', 'profilesUrl must not be empty.');
81
+ base = resourceUrl(options.profilesUrl, base);
82
+ const bytes = await read(base, Math.min(limits.maxResourceBytes, 256 * 1024));
83
+ let manifest;
84
+ try {
85
+ manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
86
+ }
87
+ catch {
88
+ throw new XmlProfileError('invalid-manifest', 'XML profile manifest is not valid UTF-8 JSON.');
89
+ }
90
+ profiles = readXmlManifest(manifest, limits.maxProfiles);
91
+ }
92
+ else {
93
+ if (options.baseUrl)
94
+ base = resourceUrl(options.baseUrl, base);
95
+ profiles = readXmlManifest({ profiles: (_a = options.profiles) !== null && _a !== void 0 ? _a : [] }, limits.maxProfiles);
96
+ }
97
+ const runtimeUrl = (value, fallback) => resourceUrl(resolveFileViewerAssetUrl(value, fallback, { documentBaseUrl: documentRef.baseURI }), documentRef.baseURI);
98
+ const accepted = [];
99
+ const engineXml = xmlEngineText(source);
100
+ for (const profile of profiles) {
101
+ checkXmlAbort(signal);
102
+ const rootCheck = profile.match.rootNamespace;
103
+ if ((rootCheck === null || rootCheck === void 0 ? void 0 : rootCheck.enabled) && (doc.documentElement.localName !== rootCheck.root || ((_b = doc.documentElement.namespaceURI) !== null && _b !== void 0 ? _b : '') !== rootCheck.namespace)) {
104
+ emit({ code: 'root-mismatch', profileId: profile.id, message: 'Root element or namespace did not match.' });
105
+ continue;
106
+ }
107
+ if ((_c = profile.match.xsd) === null || _c === void 0 ? void 0 : _c.enabled) {
108
+ const schema = await readText(resourceUrl(profile.xsd, base));
109
+ parseSafeXml(schema, documentRef, 'xsd');
110
+ const workerUrl = runtimeUrl((_d = options.runtime) === null || _d === void 0 ? void 0 : _d.xsdWorkerUrl, 'xml/xmllint-browser.mjs');
111
+ const workerSource = new TextDecoder('utf-8', { fatal: true }).decode(await read(workerUrl, 4 * 1024 * 1024));
112
+ const wasm = await read(resourceUrl('./xmllint.wasm', workerUrl), 4 * 1024 * 1024);
113
+ const { validateXmlWithWasm } = await import('./xmlEngines.js');
114
+ const validation = await validateXmlWithWasm(workerSource, wasm, engineXml, xmlEngineText(schema), signal);
115
+ if (!validation.valid) {
116
+ emit({ code: 'xsd-invalid', profileId: profile.id, message: ((_e = validation.message) === null || _e === void 0 ? void 0 : _e.slice(0, 4096)) || 'XML Schema validation failed.' });
117
+ continue;
118
+ }
119
+ }
120
+ accepted.push(profile);
121
+ }
122
+ checkXmlAbort(signal);
123
+ if (accepted.length !== 1) {
124
+ emit(accepted.length > 1
125
+ ? { code: 'ambiguous-profile', message: `Multiple XML profiles matched: ${accepted.map(profile => profile.id).join(', ')}.` }
126
+ : { code: 'no-match', message: 'No XML profile passed every enabled check.' });
127
+ return undefined;
128
+ }
129
+ const profile = accepted[0];
130
+ const stylesheet = await readText(resourceUrl(profile.xslt, base));
131
+ parseSafeXml(stylesheet, documentRef, 'xslt');
132
+ const moduleUrl = runtimeUrl((_f = options.runtime) === null || _f === void 0 ? void 0 : _f.xsltModuleUrl, 'xml/xslt-wasm.js');
133
+ const moduleSource = new TextDecoder('utf-8', { fatal: true }).decode(await read(moduleUrl, 4 * 1024 * 1024));
134
+ const { transformXmlWithWasm } = await import('./xmlEngines.js');
135
+ const result = await transformXmlWithWasm(moduleSource, engineXml, xmlEngineText(stylesheet), limits.maxOutputBytes, signal);
136
+ checkXmlAbort(signal);
137
+ if (typeof result.html !== 'string')
138
+ throw new XmlProfileError('transform-error', 'XSLT returned no output.');
139
+ emit({ code: 'profile-selected', profileId: profile.id, message: 'All enabled checks passed and XSLT transformation succeeded.' });
140
+ return { profileId: profile.id, html: result.html };
141
+ }
142
+ finally {
143
+ cache.clear();
144
+ }
145
+ }
@@ -0,0 +1,8 @@
1
+ import type { FileRenderContext, FileViewerRenderedInstance } from '@file-viewer/core';
2
+ type XmlRenderer = (buffer: ArrayBuffer, target: HTMLDivElement, context?: FileRenderContext) => Promise<FileViewerRenderedInstance>;
3
+ type XmlLoader = () => Promise<{
4
+ default: XmlRenderer;
5
+ }>;
6
+ export declare function registerXmlProfiles(loader: XmlLoader): () => void;
7
+ export declare function getXmlProfilesLoader(): XmlLoader | undefined;
8
+ export {};
@@ -0,0 +1,13 @@
1
+ const key = Symbol.for('@file-viewer/renderer-text/xml-profiles');
2
+ const registry = globalThis;
3
+ export function registerXmlProfiles(loader) {
4
+ var _a;
5
+ const registrations = (_a = registry[key]) !== null && _a !== void 0 ? _a : (registry[key] = new Map());
6
+ const token = Symbol();
7
+ registrations.set(token, loader);
8
+ return () => { registrations.delete(token); };
9
+ }
10
+ export function getXmlProfilesLoader() {
11
+ var _a;
12
+ return (_a = registry[key]) === null || _a === void 0 ? void 0 : _a.values().next().value;
13
+ }
@@ -0,0 +1,18 @@
1
+ import type { FileViewerXmlDiagnosticCode, FileViewerXmlOptions } from '@file-viewer/core';
2
+ export declare class XmlProfileError extends Error {
3
+ readonly code: FileViewerXmlDiagnosticCode;
4
+ constructor(code: FileViewerXmlDiagnosticCode, message: string);
5
+ }
6
+ export declare const xmlHardLimits: Readonly<{
7
+ maxXmlBytes: number;
8
+ maxResourceBytes: number;
9
+ maxOutputBytes: number;
10
+ maxProfiles: 32;
11
+ maxTotalResourceBytes: number;
12
+ }>;
13
+ export declare function resolveXmlLimits(options: FileViewerXmlOptions): Record<"maxXmlBytes" | "maxResourceBytes" | "maxOutputBytes" | "maxProfiles" | "maxTotalResourceBytes", number>;
14
+ export declare function checkXmlAbort(signal: AbortSignal): void;
15
+ export declare function sameOriginXmlUrl(value: string, base: string, origin: string): string;
16
+ export declare function fetchXmlBytes(url: string, maxBytes: number, signal: AbortSignal): Promise<Uint8Array>;
17
+ export declare function parseSafeXml(source: string, documentRef: Document, kind: 'xml' | 'xsd' | 'xslt'): XMLDocument;
18
+ export declare function xmlEngineText(source: string): string;
@@ -0,0 +1,143 @@
1
+ export class XmlProfileError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.code = code;
5
+ this.name = 'XmlProfileError';
6
+ }
7
+ }
8
+ const MiB = 1024 * 1024;
9
+ export const xmlHardLimits = Object.freeze({
10
+ maxXmlBytes: 4 * MiB,
11
+ maxResourceBytes: 2 * MiB,
12
+ maxOutputBytes: 8 * MiB,
13
+ maxProfiles: 32,
14
+ maxTotalResourceBytes: 16 * MiB
15
+ });
16
+ export function resolveXmlLimits(options) {
17
+ var _a;
18
+ const limits = { ...xmlHardLimits };
19
+ for (const key of Object.keys(limits)) {
20
+ const value = (_a = options.limits) === null || _a === void 0 ? void 0 : _a[key];
21
+ if (value !== undefined) {
22
+ if (!Number.isSafeInteger(value) || value < 1) {
23
+ throw new XmlProfileError('invalid-manifest', `Invalid XML limit: ${key}`);
24
+ }
25
+ limits[key] = Math.min(value, limits[key]);
26
+ }
27
+ }
28
+ return limits;
29
+ }
30
+ export function checkXmlAbort(signal) {
31
+ if (signal.aborted) {
32
+ throw signal.reason instanceof XmlProfileError
33
+ ? signal.reason
34
+ : new XmlProfileError('cancelled', 'XML profile processing was cancelled.');
35
+ }
36
+ }
37
+ export function sameOriginXmlUrl(value, base, origin) {
38
+ let url;
39
+ try {
40
+ url = new URL(value, base);
41
+ }
42
+ catch {
43
+ throw new XmlProfileError('resource-error', 'Invalid XML resource URL.');
44
+ }
45
+ if (!/^https?:$/.test(url.protocol) || url.origin !== origin || url.username || url.password || url.hash) {
46
+ throw new XmlProfileError('unsafe-resource', 'XML resources must use same-origin HTTP(S) URLs without credentials or fragments.');
47
+ }
48
+ return url.href;
49
+ }
50
+ export async function fetchXmlBytes(url, maxBytes, signal) {
51
+ var _a, _b;
52
+ checkXmlAbort(signal);
53
+ const response = await fetch(url, {
54
+ signal, redirect: 'error', credentials: 'same-origin', mode: 'same-origin', referrerPolicy: 'no-referrer'
55
+ });
56
+ if (!response.ok) {
57
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
58
+ throw new XmlProfileError('resource-error', `XML resource returned HTTP ${response.status}.`);
59
+ }
60
+ const length = Number(response.headers.get('content-length'));
61
+ if (length > maxBytes) {
62
+ await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());
63
+ throw new XmlProfileError('limit-exceeded', 'XML resource exceeds its byte limit.');
64
+ }
65
+ if (!response.body)
66
+ return new Uint8Array();
67
+ const reader = response.body.getReader();
68
+ const chunks = [];
69
+ let total = 0;
70
+ let completed = false;
71
+ try {
72
+ while (true) {
73
+ checkXmlAbort(signal);
74
+ const { done, value } = await reader.read();
75
+ if (done)
76
+ break;
77
+ total += value.byteLength;
78
+ if (total > maxBytes)
79
+ throw new XmlProfileError('limit-exceeded', 'XML resource exceeds its byte limit.');
80
+ chunks.push(value);
81
+ }
82
+ checkXmlAbort(signal);
83
+ completed = true;
84
+ const bytes = new Uint8Array(total);
85
+ let offset = 0;
86
+ for (const chunk of chunks) {
87
+ bytes.set(chunk, offset);
88
+ offset += chunk.byteLength;
89
+ }
90
+ return bytes;
91
+ }
92
+ finally {
93
+ if (!completed)
94
+ await reader.cancel().catch(() => undefined);
95
+ reader.releaseLock();
96
+ }
97
+ }
98
+ const XSD = 'http://www.w3.org/2001/XMLSchema';
99
+ const XSL = 'http://www.w3.org/1999/XSL/Transform';
100
+ export function parseSafeXml(source, documentRef, kind) {
101
+ var _a;
102
+ if (/<!\s*(?:DOCTYPE|ENTITY)\b/i.test(source)) {
103
+ throw new XmlProfileError('unsafe-resource', 'DTD and entity declarations are disabled for XML profiles.');
104
+ }
105
+ const Parser = (_a = documentRef.defaultView) === null || _a === void 0 ? void 0 : _a.DOMParser;
106
+ if (!Parser)
107
+ throw new XmlProfileError('engine-error', 'XML parsing requires a browser document.');
108
+ const doc = new Parser().parseFromString(source, 'application/xml');
109
+ if (!doc.documentElement || doc.getElementsByTagName('parsererror').length) {
110
+ throw new XmlProfileError('invalid-xml', `Malformed ${kind.toUpperCase()} document.`);
111
+ }
112
+ const root = doc.documentElement;
113
+ if (kind === 'xsd' && (root.namespaceURI !== XSD || root.localName !== 'schema')) {
114
+ throw new XmlProfileError('invalid-xml', 'Expected an XML Schema document.');
115
+ }
116
+ if (kind === 'xslt' && (root.namespaceURI !== XSL || !['stylesheet', 'transform'].includes(root.localName))) {
117
+ throw new XmlProfileError('invalid-xml', 'Expected an XSLT 1.0 stylesheet.');
118
+ }
119
+ for (const element of Array.from(doc.getElementsByTagName('*'))) {
120
+ if ((element.namespaceURI === XSD && ['include', 'import', 'redefine', 'override'].includes(element.localName)) ||
121
+ (element.namespaceURI === XSL && ['include', 'import'].includes(element.localName)) ||
122
+ element.namespaceURI === 'http://www.w3.org/2001/XInclude') {
123
+ throw new XmlProfileError('unsafe-resource', 'Schema dependencies, XSLT imports/includes and XInclude are disabled.');
124
+ }
125
+ if (kind !== 'xslt')
126
+ continue;
127
+ for (const attribute of Array.from(element.attributes)) {
128
+ if (/(?:^|[^\w.-])document\s*\(/.test(attribute.value) ||
129
+ (attribute.localName === 'extension-element-prefixes' && attribute.value.trim())) {
130
+ throw new XmlProfileError('unsafe-resource', 'XSLT document() and extension instructions are disabled.');
131
+ }
132
+ }
133
+ if (element.namespaceURI === XSL && element.localName === 'output') {
134
+ const method = element.getAttribute('method');
135
+ if (method && method !== 'html')
136
+ throw new XmlProfileError('transform-error', 'XML profiles require HTML output.');
137
+ }
138
+ }
139
+ return doc;
140
+ }
141
+ export function xmlEngineText(source) {
142
+ return source.replace(/^(\uFEFF?<\?xml\s[^?]*?encoding\s*=\s*)(["'])[^"']*\2/, '$1"UTF-8"');
143
+ }
@@ -0,0 +1 @@
1
+ export declare function limitXmlWasmMemory(input: BufferSource, maxPages?: number): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,71 @@
1
+ export function limitXmlWasmMemory(input, maxPages = 1024) {
2
+ const bytes = ArrayBuffer.isView(input)
3
+ ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
4
+ : new Uint8Array(input);
5
+ if (!Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > 1024)
6
+ throw new Error('Invalid XML WASM memory limit.');
7
+ if (bytes.length < 8 || ![0, 97, 115, 109, 1, 0, 0, 0].every((value, index) => bytes[index] === value)) {
8
+ throw new Error('Invalid XML WASM module.');
9
+ }
10
+ let offset = 8;
11
+ const read = () => {
12
+ let value = 0;
13
+ for (let index = 0; index < 5; index++) {
14
+ if (offset >= bytes.length)
15
+ throw new Error('Truncated WASM section.');
16
+ const byte = bytes[offset++];
17
+ if (index === 4 && byte > 15)
18
+ throw new Error('Invalid WASM section integer.');
19
+ value += (byte & 127) * 2 ** (index * 7);
20
+ if (!(byte & 128))
21
+ return value;
22
+ }
23
+ throw new Error('Invalid WASM section integer.');
24
+ };
25
+ const encode = (value) => {
26
+ const output = [];
27
+ do {
28
+ const byte = value % 128;
29
+ value = Math.floor(value / 128);
30
+ output.push(byte | (value ? 128 : 0));
31
+ } while (value);
32
+ return output;
33
+ };
34
+ const parts = [bytes.subarray(0, 8)];
35
+ let foundMemory = false;
36
+ while (offset < bytes.length) {
37
+ const start = offset;
38
+ const id = bytes[offset++];
39
+ const length = read();
40
+ const end = offset + length;
41
+ if (end > bytes.length)
42
+ throw new Error('Truncated WASM section.');
43
+ if (id !== 5) {
44
+ parts.push(bytes.subarray(start, end));
45
+ }
46
+ else {
47
+ if (foundMemory || read() !== 1)
48
+ throw new Error('XML WASM requires exactly one defined memory.');
49
+ foundMemory = true;
50
+ const flags = read();
51
+ if (flags !== 0 && flags !== 1)
52
+ throw new Error('Shared or memory64 XML WASM is not supported.');
53
+ const initial = read();
54
+ const maximum = flags === 1 ? read() : maxPages;
55
+ if (initial > maxPages || maximum < initial || offset !== end)
56
+ throw new Error('Invalid XML WASM memory declaration.');
57
+ const memory = [1, 1, ...encode(initial), ...encode(Math.min(maximum, maxPages))];
58
+ parts.push(new Uint8Array([5, ...encode(memory.length), ...memory]));
59
+ }
60
+ offset = end;
61
+ }
62
+ if (!foundMemory)
63
+ throw new Error('XML WASM did not declare its own memory.');
64
+ const output = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
65
+ offset = 0;
66
+ for (const part of parts) {
67
+ output.set(part, offset);
68
+ offset += part.length;
69
+ }
70
+ return output;
71
+ }
@@ -4,7 +4,7 @@
4
4
  "id": "text",
5
5
  "packageName": "@file-viewer/renderer-text",
6
6
  "rendererIds": ["markdown", "code"],
7
- "formats": ["md", "markdown", "txt", "json", "js", "mjs", "cjs", "css", "java", "py", "html", "htm", "jsx", "ts", "tsx", "xml", "log", "vue", "yaml", "yml", "ini", "sh", "bash", "sql", "go", "rs", "php", "c", "cpp", "cc", "h", "hpp", "cs", "jsonc", "json5", "ipynb", "toml", "proto", "hcl", "tex", "gv", "http", "react", "rb", "swift", "kt"],
7
+ "formats": ["md", "markdown", "txt", "lrc", "json", "js", "mjs", "cjs", "css", "java", "py", "html", "htm", "jsx", "ts", "tsx", "xml", "log", "vue", "yaml", "yml", "ini", "sh", "bash", "sql", "go", "rs", "php", "c", "cpp", "cc", "h", "hpp", "cs", "jsonc", "json5", "ipynb", "toml", "proto", "hcl", "tex", "gv", "http", "react", "rb", "swift", "kt"],
8
8
  "assets": { "rendererIds": [] },
9
9
  "license": { "spdx": "Apache-2.0", "policy": "permissive" },
10
10
  "weight": "standard",
@@ -0,0 +1,31 @@
1
+ # Optional XML profile runtimes
2
+
3
+ Retain this directory when redistributing the runtime assets. File Viewer's own
4
+ adapter is Apache-2.0; upstream engines retain their original licenses.
5
+ The asset helper copies engine files unchanged. During XSLT execution the adapter
6
+ limits the WASM memory declaration to 64 MiB before compilation; it does not change
7
+ the engine's instructions or data, nor install the automatic page polyfill.
8
+
9
+ | Component | Verified upstream notice | Included notice |
10
+ | --- | --- | --- |
11
+ | xslt-polyfill 1.0.31 | [BSD-3-Clause](https://github.com/mfreed7/xslt_polyfill/blob/main/LICENSE) | xslt-polyfill-LICENSE.txt |
12
+ | xmllint-wasm 5.3.0 | [MIT](https://github.com/noppa/xmllint-wasm/blob/master/COPYING) | xmllint-wasm-COPYING.txt |
13
+ | XSLT libxml2 submodule | [Copyright at c34742f](https://github.com/GNOME/libxml2/blob/c34742f3017f6d39f3e4ccae4f70172238160ef8/Copyright) | libxml2-xslt-Copyright.txt |
14
+ | XSD libxml2 submodule | [Copyright at eb0a2f2](https://github.com/GNOME/libxml2/blob/eb0a2f2b91566384f378d870ffcd69c0a24162cc/Copyright) | libxml2-xsd-Copyright.txt |
15
+ | libxslt and libexslt | [Copyright at 923903c](https://github.com/GNOME/libxslt/blob/923903c59d668af42e3144bc623c9190a0f65988/Copyright) | libxslt-Copyright.txt |
16
+ | zlib | [Upstream notice](https://github.com/madler/zlib/blob/develop/LICENSE) | zlib-LICENSE.txt |
17
+
18
+ The xmllint [build command](https://github.com/noppa/xmllint-wasm/blob/master/script/compile)
19
+ links its repository's `libz.a`. Its precise zlib version is not identified in the
20
+ published npm metadata; the upstream zlib notice is included conservatively.
21
+
22
+ API evidence: xmllint's published browser module contains the Emscripten `Module`
23
+ factory used by its Worker wrapper; the adapter supplies in-memory XML/schema
24
+ files, `--nonet --noout --schema`, a WASM binary and bounded imported memory.
25
+ The XSLT package's `dist/xslt-wasm.js` exposes `createXSLTTransformModule`,
26
+ `cwrap('transform', ...)`, `_malloc`, `_free`, and `wasmMemory`; its
27
+ [C entry point](https://github.com/mfreed7/xslt_polyfill/blob/main/src/transform.c)
28
+ accepts input/style byte pointers and lengths and returns an allocated result.
29
+ Both factories run in disposable workers with network access disabled. These
30
+ adapters are pinned to the exact package versions above; review the ABI and
31
+ rerun the browser tests before upgrading.
@@ -0,0 +1,23 @@
1
+ Except where otherwise noted in the source code (e.g. the files dict.c and
2
+ list.c, which are covered by a similar licence but with different Copyright
3
+ notices) all the files are:
4
+
5
+ Copyright (C) 1998-2012 Daniel Veillard. All Rights Reserved.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is fur-
12
+ nished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
19
+ NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.