merong-docs 0.1.11 → 1.0.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.
- package/OVERVIEW.md +19 -19
- package/OVERVIEW.zh-CN.md +19 -22
- package/README.md +77 -77
- package/README.zh-CN.md +81 -81
- package/client/android-file-share.ts +25 -25
- package/client/controls.tsx +163 -163
- package/client/document-panel.tsx +166 -166
- package/client/external-file.tsx +78 -78
- package/client/file-reader.tsx +43 -43
- package/client/markdown-panel.tsx +737 -737
- package/client/markdown-scroll.ts +122 -122
- package/client/messages.ts +224 -224
- package/client/native-contacts.ts +145 -145
- package/client/page-render-queue.ts +12 -12
- package/client/page-selection.tsx +227 -227
- package/client/page-tools.tsx +72 -72
- package/client/pdf-geometry.ts +96 -96
- package/client/pdf-panel.tsx +477 -477
- package/client/reader-find.tsx +190 -190
- package/client/reader-notice.tsx +46 -46
- package/client/settings.tsx +143 -143
- package/client/syntax.tsx +55 -55
- package/client/viewport-geometry.ts +61 -61
- package/client/web.ts +462 -462
- package/client/worksheet-panel.tsx +631 -631
- package/client/zoom-controls.tsx +140 -140
- package/index.client.tsx +36 -36
- package/index.server.ts +73 -73
- package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
- package/node_modules/yaml/bin.mjs +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/prepare-office.mjs +20 -20
- package/server/engine.ts +89 -89
- package/server/external-file.ts +42 -42
- package/server/generated/document-worker.ts +1 -1
- package/server/generated/rust-reader_bg.wasm +0 -0
- package/server/markdown-index.ts +305 -305
- package/server/markdown-links.ts +51 -51
- package/server/markdown-page.ts +120 -120
- package/server/office-fonts.cjs +824 -824
- package/server/office-location.ts +41 -41
- package/server/office-preview.ts +186 -186
- package/server/office-worker.cjs +49 -49
- package/server/office-xml.ts +79 -79
- package/server/pdf-engine.ts +168 -168
- package/server/pdf-text-geometry.ts +60 -60
- package/server/rust-reader.ts +40 -40
- package/server/structured-document.ts +69 -69
- package/server/text-search.ts +15 -15
- package/server/worker-entry.ts +42 -42
- package/server/worker-protocol.ts +38 -38
- package/server/worksheet.ts +67 -67
- package/server/workspace-file.ts +63 -63
- package/shared/contracts.ts +187 -187
- package/shared/file-limits.ts +5 -5
- package/shared/markdown-constants.ts +4 -4
- package/shared/markdown-math.ts +198 -198
- package/shared/markdown-references.ts +83 -83
- package/shared/markdown-source-location.ts +8 -8
- package/shared/reader-settings.ts +15 -15
- package/shared/reader-shortcuts.ts +132 -132
- package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
package/server/rust-reader.ts
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { workerData } from "node:worker_threads";
|
|
4
|
-
import type { MarkdownReference } from "../shared/contracts";
|
|
5
|
-
import { officeDirectory } from "./office-location";
|
|
6
|
-
|
|
7
|
-
interface RustWorkbook {
|
|
8
|
-
sheetFiles(): string;
|
|
9
|
-
previewSheet(source: string): string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
interface RustReader {
|
|
13
|
-
Workbook: new (workbook: string, relationships: string, styles: string, strings: string) => RustWorkbook;
|
|
14
|
-
markdownStructure(source: string): string;
|
|
15
|
-
markdownHeading(source: string): string;
|
|
16
|
-
encodePageJpeg(pixels: Uint8Array, width: number, height: number, maxBytes: number): Uint8Array;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
let runtime: Promise<RustReader> | undefined;
|
|
20
|
-
|
|
21
|
-
function readerDirectory() {
|
|
22
|
-
return typeof workerData === "string" ? Promise.resolve(workerData) : officeDirectory();
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function rustReader() {
|
|
26
|
-
return runtime ??= readerDirectory().then((directory) => {
|
|
27
|
-
const requireFromPlugin = createRequire(join(directory, "package.json"));
|
|
28
|
-
return requireFromPlugin("./server/generated/rust-reader.cjs") as RustReader;
|
|
29
|
-
}).catch((error) => {
|
|
30
|
-
runtime = undefined;
|
|
31
|
-
throw error;
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function markdownStructure(reader: RustReader, source: string) {
|
|
36
|
-
return JSON.parse(reader.markdownStructure(source)) as {
|
|
37
|
-
tables: [first: number, end: number][];
|
|
38
|
-
references: MarkdownReference[];
|
|
39
|
-
};
|
|
40
|
-
}
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { workerData } from "node:worker_threads";
|
|
4
|
+
import type { MarkdownReference } from "../shared/contracts";
|
|
5
|
+
import { officeDirectory } from "./office-location";
|
|
6
|
+
|
|
7
|
+
interface RustWorkbook {
|
|
8
|
+
sheetFiles(): string;
|
|
9
|
+
previewSheet(source: string): string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface RustReader {
|
|
13
|
+
Workbook: new (workbook: string, relationships: string, styles: string, strings: string) => RustWorkbook;
|
|
14
|
+
markdownStructure(source: string): string;
|
|
15
|
+
markdownHeading(source: string): string;
|
|
16
|
+
encodePageJpeg(pixels: Uint8Array, width: number, height: number, maxBytes: number): Uint8Array;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
let runtime: Promise<RustReader> | undefined;
|
|
20
|
+
|
|
21
|
+
function readerDirectory() {
|
|
22
|
+
return typeof workerData === "string" ? Promise.resolve(workerData) : officeDirectory();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function rustReader() {
|
|
26
|
+
return runtime ??= readerDirectory().then((directory) => {
|
|
27
|
+
const requireFromPlugin = createRequire(join(directory, "package.json"));
|
|
28
|
+
return requireFromPlugin("./server/generated/rust-reader.cjs") as RustReader;
|
|
29
|
+
}).catch((error) => {
|
|
30
|
+
runtime = undefined;
|
|
31
|
+
throw error;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function markdownStructure(reader: RustReader, source: string) {
|
|
36
|
+
return JSON.parse(reader.markdownStructure(source)) as {
|
|
37
|
+
tables: [first: number, end: number][];
|
|
38
|
+
references: MarkdownReference[];
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -1,69 +1,69 @@
|
|
|
1
|
-
import { extname } from "node:path";
|
|
2
|
-
import type { DocumentBlock, DocumentSection } from "../shared/contracts";
|
|
3
|
-
import { pagedOfficeFileLimit } from "../shared/file-limits";
|
|
4
|
-
import { children, descendants, loadOffice, plainText, relatedParts } from "./office-xml";
|
|
5
|
-
import { withWorkspaceFile } from "./workspace-file";
|
|
6
|
-
|
|
7
|
-
const maxSections = 32;
|
|
8
|
-
const maxBlocks = 180;
|
|
9
|
-
const maxRows = 120;
|
|
10
|
-
const maxColumns = 20;
|
|
11
|
-
const importantPart = /^(?:word\/document\.xml|ppt\/(?:presentation\.xml|slides\/[^/]+\.xml|_rels\/presentation\.xml\.rels))$/;
|
|
12
|
-
type XmlParts = Awaited<ReturnType<typeof loadOffice>>;
|
|
13
|
-
|
|
14
|
-
function wordSections(documents: XmlParts): DocumentSection[] {
|
|
15
|
-
const doc = documents.get("word/document.xml");
|
|
16
|
-
const body = doc && descendants(doc, "body")[0];
|
|
17
|
-
if (!body) throw new Error("Missing document body.");
|
|
18
|
-
const blocks = children(body, ["p", "tbl"]).slice(0, maxBlocks + 1).flatMap((node): DocumentBlock[] => {
|
|
19
|
-
if (node.localName === "tbl") {
|
|
20
|
-
const rows = children(node, ["tr"]).slice(0, maxRows + 1).map((row) =>
|
|
21
|
-
children(row, ["tc"]).slice(0, maxColumns + 1).map((cell) => children(cell, ["p"]).map(plainText).join("\n")),
|
|
22
|
-
);
|
|
23
|
-
return [{ kind: "table", rows }];
|
|
24
|
-
}
|
|
25
|
-
const text = plainText(node);
|
|
26
|
-
const style = descendants(node, "pStyle")[0]?.getAttribute("w:val") ?? "";
|
|
27
|
-
return text ? [{ kind: "paragraph", text, heading: /^(title|heading)/i.test(style) }] : [];
|
|
28
|
-
});
|
|
29
|
-
return [{ blocks }];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function slideSections(documents: XmlParts): DocumentSection[] {
|
|
33
|
-
return relatedParts(documents, "ppt/presentation.xml", "sldId").slice(0, maxSections + 1).map(({ content }) => {
|
|
34
|
-
const texts = content ? descendants(content, "p").slice(0, maxBlocks + 1).map(plainText).filter(Boolean) : [];
|
|
35
|
-
const [title, ...paragraphs] = texts;
|
|
36
|
-
return { title, blocks: paragraphs.map((text) => ({ kind: "paragraph", text })) };
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function limitPreview(sections: DocumentSection[]) {
|
|
41
|
-
let remaining = 90_000;
|
|
42
|
-
let truncated = sections.length > maxSections;
|
|
43
|
-
const text = (value: string, maxLength: number) => {
|
|
44
|
-
const amount = Math.min(maxLength, remaining, value.length);
|
|
45
|
-
remaining -= amount;
|
|
46
|
-
truncated ||= amount < value.length;
|
|
47
|
-
return value.slice(0, amount);
|
|
48
|
-
};
|
|
49
|
-
const take = <Value>(values: Value[], count: number) => {
|
|
50
|
-
if (values.length > count) truncated = true;
|
|
51
|
-
return values.slice(0, count);
|
|
52
|
-
};
|
|
53
|
-
const limited = take(sections, maxSections).map(({ title, blocks }) => ({
|
|
54
|
-
title: title ? text(title, 250) : undefined,
|
|
55
|
-
blocks: take(blocks, maxBlocks).map((block): DocumentBlock => block.kind === "paragraph"
|
|
56
|
-
? { ...block, text: text(block.text, 8_000) }
|
|
57
|
-
: { ...block, rows: take(block.rows, maxRows).map((row) => take(row, maxColumns).map((value) => text(value, 500))) }),
|
|
58
|
-
}));
|
|
59
|
-
return { sections: limited, truncated };
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function loadStructuredDocument(root: string, path: string) {
|
|
63
|
-
const extension = extname(path).slice(1).toLowerCase();
|
|
64
|
-
return withWorkspaceFile(root, path, ["docx", "pptx"], async (file, size) => {
|
|
65
|
-
if (size > pagedOfficeFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
66
|
-
const documents = await loadOffice(await file.readFile(), (path) => importantPart.test(path));
|
|
67
|
-
return limitPreview(extension === "docx" ? wordSections(documents) : slideSections(documents));
|
|
68
|
-
});
|
|
69
|
-
}
|
|
1
|
+
import { extname } from "node:path";
|
|
2
|
+
import type { DocumentBlock, DocumentSection } from "../shared/contracts";
|
|
3
|
+
import { pagedOfficeFileLimit } from "../shared/file-limits";
|
|
4
|
+
import { children, descendants, loadOffice, plainText, relatedParts } from "./office-xml";
|
|
5
|
+
import { withWorkspaceFile } from "./workspace-file";
|
|
6
|
+
|
|
7
|
+
const maxSections = 32;
|
|
8
|
+
const maxBlocks = 180;
|
|
9
|
+
const maxRows = 120;
|
|
10
|
+
const maxColumns = 20;
|
|
11
|
+
const importantPart = /^(?:word\/document\.xml|ppt\/(?:presentation\.xml|slides\/[^/]+\.xml|_rels\/presentation\.xml\.rels))$/;
|
|
12
|
+
type XmlParts = Awaited<ReturnType<typeof loadOffice>>;
|
|
13
|
+
|
|
14
|
+
function wordSections(documents: XmlParts): DocumentSection[] {
|
|
15
|
+
const doc = documents.get("word/document.xml");
|
|
16
|
+
const body = doc && descendants(doc, "body")[0];
|
|
17
|
+
if (!body) throw new Error("Missing document body.");
|
|
18
|
+
const blocks = children(body, ["p", "tbl"]).slice(0, maxBlocks + 1).flatMap((node): DocumentBlock[] => {
|
|
19
|
+
if (node.localName === "tbl") {
|
|
20
|
+
const rows = children(node, ["tr"]).slice(0, maxRows + 1).map((row) =>
|
|
21
|
+
children(row, ["tc"]).slice(0, maxColumns + 1).map((cell) => children(cell, ["p"]).map(plainText).join("\n")),
|
|
22
|
+
);
|
|
23
|
+
return [{ kind: "table", rows }];
|
|
24
|
+
}
|
|
25
|
+
const text = plainText(node);
|
|
26
|
+
const style = descendants(node, "pStyle")[0]?.getAttribute("w:val") ?? "";
|
|
27
|
+
return text ? [{ kind: "paragraph", text, heading: /^(title|heading)/i.test(style) }] : [];
|
|
28
|
+
});
|
|
29
|
+
return [{ blocks }];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function slideSections(documents: XmlParts): DocumentSection[] {
|
|
33
|
+
return relatedParts(documents, "ppt/presentation.xml", "sldId").slice(0, maxSections + 1).map(({ content }) => {
|
|
34
|
+
const texts = content ? descendants(content, "p").slice(0, maxBlocks + 1).map(plainText).filter(Boolean) : [];
|
|
35
|
+
const [title, ...paragraphs] = texts;
|
|
36
|
+
return { title, blocks: paragraphs.map((text) => ({ kind: "paragraph", text })) };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function limitPreview(sections: DocumentSection[]) {
|
|
41
|
+
let remaining = 90_000;
|
|
42
|
+
let truncated = sections.length > maxSections;
|
|
43
|
+
const text = (value: string, maxLength: number) => {
|
|
44
|
+
const amount = Math.min(maxLength, remaining, value.length);
|
|
45
|
+
remaining -= amount;
|
|
46
|
+
truncated ||= amount < value.length;
|
|
47
|
+
return value.slice(0, amount);
|
|
48
|
+
};
|
|
49
|
+
const take = <Value>(values: Value[], count: number) => {
|
|
50
|
+
if (values.length > count) truncated = true;
|
|
51
|
+
return values.slice(0, count);
|
|
52
|
+
};
|
|
53
|
+
const limited = take(sections, maxSections).map(({ title, blocks }) => ({
|
|
54
|
+
title: title ? text(title, 250) : undefined,
|
|
55
|
+
blocks: take(blocks, maxBlocks).map((block): DocumentBlock => block.kind === "paragraph"
|
|
56
|
+
? { ...block, text: text(block.text, 8_000) }
|
|
57
|
+
: { ...block, rows: take(block.rows, maxRows).map((row) => take(row, maxColumns).map((value) => text(value, 500))) }),
|
|
58
|
+
}));
|
|
59
|
+
return { sections: limited, truncated };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function loadStructuredDocument(root: string, path: string) {
|
|
63
|
+
const extension = extname(path).slice(1).toLowerCase();
|
|
64
|
+
return withWorkspaceFile(root, path, ["docx", "pptx"], async (file, size) => {
|
|
65
|
+
if (size > pagedOfficeFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
66
|
+
const documents = await loadOffice(await file.readFile(), (path) => importantPart.test(path));
|
|
67
|
+
return limitPreview(extension === "docx" ? wordSections(documents) : slideSections(documents));
|
|
68
|
+
});
|
|
69
|
+
}
|
package/server/text-search.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import type { MarkdownSearchOptions } from "../shared/contracts";
|
|
2
|
-
|
|
3
|
-
export function searchExpression(query: string, options: MarkdownSearchOptions, flexibleWhitespace = false) {
|
|
4
|
-
let pattern = options.regex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5
|
-
if (!options.regex && flexibleWhitespace) pattern = pattern.replace(/\s+/g, "\\s+");
|
|
6
|
-
if (options.wholeWord) {
|
|
7
|
-
const word = "[\\p{L}\\p{M}\\p{N}_]";
|
|
8
|
-
pattern = `(?<!${word})(?:${pattern})(?!${word})`;
|
|
9
|
-
}
|
|
10
|
-
try {
|
|
11
|
-
return new RegExp(pattern, options.matchCase ? "gu" : "giu");
|
|
12
|
-
} catch (error) {
|
|
13
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
1
|
+
import type { MarkdownSearchOptions } from "../shared/contracts";
|
|
2
|
+
|
|
3
|
+
export function searchExpression(query: string, options: MarkdownSearchOptions, flexibleWhitespace = false) {
|
|
4
|
+
let pattern = options.regex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5
|
+
if (!options.regex && flexibleWhitespace) pattern = pattern.replace(/\s+/g, "\\s+");
|
|
6
|
+
if (options.wholeWord) {
|
|
7
|
+
const word = "[\\p{L}\\p{M}\\p{N}_]";
|
|
8
|
+
pattern = `(?<!${word})(?:${pattern})(?!${word})`;
|
|
9
|
+
}
|
|
10
|
+
try {
|
|
11
|
+
return new RegExp(pattern, options.matchCase ? "gu" : "giu");
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
14
|
+
}
|
|
15
|
+
}
|
package/server/worker-entry.ts
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
import { parentPort } from "node:worker_threads";
|
|
2
|
-
import type { EngineRequest, EngineResponse, EngineResults } from "./worker-protocol";
|
|
3
|
-
|
|
4
|
-
async function handle(request: EngineRequest): Promise<EngineResults[keyof EngineResults]> {
|
|
5
|
-
switch (request.kind) {
|
|
6
|
-
case "pdf":
|
|
7
|
-
return (await import("./pdf-engine")).rasterizePdf(request.root, request.path, request.page, request.pixels);
|
|
8
|
-
case "pdf-layout":
|
|
9
|
-
return (await import("./pdf-engine")).inspectPdf(request.root, request.path);
|
|
10
|
-
case "pdf-text":
|
|
11
|
-
return (await import("./pdf-engine")).pdfText(request.root, request.path, request.page);
|
|
12
|
-
case "pdf-search":
|
|
13
|
-
return (await import("./pdf-engine")).searchPdf(request.root, request.path, request.query, request.options);
|
|
14
|
-
case "office":
|
|
15
|
-
return (await import("./pdf-engine")).rasterizePdfPage(request.key, async () => request.data, request.page, request.pixels);
|
|
16
|
-
case "office-layout":
|
|
17
|
-
return (await import("./pdf-engine")).inspectPdfPages(request.key, async () => request.data);
|
|
18
|
-
case "office-text":
|
|
19
|
-
return (await import("./pdf-engine")).readPdfText(request.key, async () => request.data, request.page);
|
|
20
|
-
case "office-search":
|
|
21
|
-
return (await import("./pdf-engine")).findPageTextMatches(request.key, async () => request.data, request.query, request.options);
|
|
22
|
-
case "markdown-search":
|
|
23
|
-
return (await import("./markdown-index")).findMarkdownLines(request.root, request.path, request.query, request.options, request.offset);
|
|
24
|
-
case "document":
|
|
25
|
-
return (await import("./structured-document")).loadStructuredDocument(request.root, request.path);
|
|
26
|
-
case "worksheet":
|
|
27
|
-
return (await import("./worksheet")).loadWorksheet(request.root, request.path, request.sheet);
|
|
28
|
-
case "worksheet-search":
|
|
29
|
-
return (await import("./worksheet")).searchWorksheet(request.root, request.path, request.sheet, request.query, request.options);
|
|
30
|
-
default:
|
|
31
|
-
throw new Error("Invalid document request.");
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
parentPort?.on("message", async (request: EngineRequest) => {
|
|
36
|
-
try {
|
|
37
|
-
parentPort?.postMessage({ result: await handle(request) } satisfies EngineResponse);
|
|
38
|
-
} catch (error) {
|
|
39
|
-
const message = error instanceof Error ? error.message : "Could not render the document.";
|
|
40
|
-
parentPort?.postMessage({ error: message } satisfies EngineResponse);
|
|
41
|
-
}
|
|
42
|
-
});
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
|
+
import type { EngineRequest, EngineResponse, EngineResults } from "./worker-protocol";
|
|
3
|
+
|
|
4
|
+
async function handle(request: EngineRequest): Promise<EngineResults[keyof EngineResults]> {
|
|
5
|
+
switch (request.kind) {
|
|
6
|
+
case "pdf":
|
|
7
|
+
return (await import("./pdf-engine")).rasterizePdf(request.root, request.path, request.page, request.pixels);
|
|
8
|
+
case "pdf-layout":
|
|
9
|
+
return (await import("./pdf-engine")).inspectPdf(request.root, request.path);
|
|
10
|
+
case "pdf-text":
|
|
11
|
+
return (await import("./pdf-engine")).pdfText(request.root, request.path, request.page);
|
|
12
|
+
case "pdf-search":
|
|
13
|
+
return (await import("./pdf-engine")).searchPdf(request.root, request.path, request.query, request.options);
|
|
14
|
+
case "office":
|
|
15
|
+
return (await import("./pdf-engine")).rasterizePdfPage(request.key, async () => request.data, request.page, request.pixels);
|
|
16
|
+
case "office-layout":
|
|
17
|
+
return (await import("./pdf-engine")).inspectPdfPages(request.key, async () => request.data);
|
|
18
|
+
case "office-text":
|
|
19
|
+
return (await import("./pdf-engine")).readPdfText(request.key, async () => request.data, request.page);
|
|
20
|
+
case "office-search":
|
|
21
|
+
return (await import("./pdf-engine")).findPageTextMatches(request.key, async () => request.data, request.query, request.options);
|
|
22
|
+
case "markdown-search":
|
|
23
|
+
return (await import("./markdown-index")).findMarkdownLines(request.root, request.path, request.query, request.options, request.offset);
|
|
24
|
+
case "document":
|
|
25
|
+
return (await import("./structured-document")).loadStructuredDocument(request.root, request.path);
|
|
26
|
+
case "worksheet":
|
|
27
|
+
return (await import("./worksheet")).loadWorksheet(request.root, request.path, request.sheet);
|
|
28
|
+
case "worksheet-search":
|
|
29
|
+
return (await import("./worksheet")).searchWorksheet(request.root, request.path, request.sheet, request.query, request.options);
|
|
30
|
+
default:
|
|
31
|
+
throw new Error("Invalid document request.");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
parentPort?.on("message", async (request: EngineRequest) => {
|
|
36
|
+
try {
|
|
37
|
+
parentPort?.postMessage({ result: await handle(request) } satisfies EngineResponse);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const message = error instanceof Error ? error.message : "Could not render the document.";
|
|
40
|
+
parentPort?.postMessage({ error: message } satisfies EngineResponse);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
import type { RpcOutput } from "@getpaseo/plugin";
|
|
2
|
-
import type {
|
|
3
|
-
MarkdownSearchOptions, PageRun, findDocumentText, findWorksheetText, readDocumentText, searchMarkdownFile,
|
|
4
|
-
readStructuredDocument, readWorksheet, renderPdfPage,
|
|
5
|
-
} from "../shared/contracts";
|
|
6
|
-
|
|
7
|
-
export type EngineRequest =
|
|
8
|
-
| { kind: "pdf"; root: string; path: string; page: number; pixels: number }
|
|
9
|
-
| { kind: "office"; key: string; data: Uint8Array; page: number; pixels: number }
|
|
10
|
-
| { kind: "pdf-layout"; root: string; path: string }
|
|
11
|
-
| { kind: "office-layout"; key: string; data: Uint8Array }
|
|
12
|
-
| { kind: "pdf-text"; root: string; path: string; page: number }
|
|
13
|
-
| { kind: "pdf-search"; root: string; path: string; query: string; options: MarkdownSearchOptions }
|
|
14
|
-
| { kind: "office-text"; key: string; data: Uint8Array; page: number }
|
|
15
|
-
| { kind: "office-search"; key: string; data: Uint8Array; query: string; options: MarkdownSearchOptions }
|
|
16
|
-
| { kind: "markdown-search"; root: string; path: string; query: string; options: MarkdownSearchOptions; offset: number }
|
|
17
|
-
| { kind: "document"; root: string; path: string }
|
|
18
|
-
| { kind: "worksheet"; root: string; path: string; sheet: number }
|
|
19
|
-
| { kind: "worksheet-search"; root: string; path: string; sheet: number; query: string; options: MarkdownSearchOptions };
|
|
20
|
-
|
|
21
|
-
export interface EngineResults {
|
|
22
|
-
pdf: RpcOutput<typeof renderPdfPage>;
|
|
23
|
-
office: EngineResults["pdf"];
|
|
24
|
-
"pdf-layout": PageRun[];
|
|
25
|
-
"office-layout": EngineResults["pdf-layout"];
|
|
26
|
-
"pdf-text": NonNullable<RpcOutput<typeof readDocumentText>>;
|
|
27
|
-
"pdf-search": NonNullable<RpcOutput<typeof findDocumentText>>;
|
|
28
|
-
"office-text": EngineResults["pdf-text"];
|
|
29
|
-
"office-search": EngineResults["pdf-search"];
|
|
30
|
-
"markdown-search": RpcOutput<typeof searchMarkdownFile>;
|
|
31
|
-
document: RpcOutput<typeof readStructuredDocument>;
|
|
32
|
-
worksheet: RpcOutput<typeof readWorksheet>;
|
|
33
|
-
"worksheet-search": RpcOutput<typeof findWorksheetText>;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export type EngineResponse =
|
|
37
|
-
| { result: EngineResults[keyof EngineResults] }
|
|
38
|
-
| { error: string };
|
|
1
|
+
import type { RpcOutput } from "@getpaseo/plugin";
|
|
2
|
+
import type {
|
|
3
|
+
MarkdownSearchOptions, PageRun, findDocumentText, findWorksheetText, readDocumentText, searchMarkdownFile,
|
|
4
|
+
readStructuredDocument, readWorksheet, renderPdfPage,
|
|
5
|
+
} from "../shared/contracts";
|
|
6
|
+
|
|
7
|
+
export type EngineRequest =
|
|
8
|
+
| { kind: "pdf"; root: string; path: string; page: number; pixels: number }
|
|
9
|
+
| { kind: "office"; key: string; data: Uint8Array; page: number; pixels: number }
|
|
10
|
+
| { kind: "pdf-layout"; root: string; path: string }
|
|
11
|
+
| { kind: "office-layout"; key: string; data: Uint8Array }
|
|
12
|
+
| { kind: "pdf-text"; root: string; path: string; page: number }
|
|
13
|
+
| { kind: "pdf-search"; root: string; path: string; query: string; options: MarkdownSearchOptions }
|
|
14
|
+
| { kind: "office-text"; key: string; data: Uint8Array; page: number }
|
|
15
|
+
| { kind: "office-search"; key: string; data: Uint8Array; query: string; options: MarkdownSearchOptions }
|
|
16
|
+
| { kind: "markdown-search"; root: string; path: string; query: string; options: MarkdownSearchOptions; offset: number }
|
|
17
|
+
| { kind: "document"; root: string; path: string }
|
|
18
|
+
| { kind: "worksheet"; root: string; path: string; sheet: number }
|
|
19
|
+
| { kind: "worksheet-search"; root: string; path: string; sheet: number; query: string; options: MarkdownSearchOptions };
|
|
20
|
+
|
|
21
|
+
export interface EngineResults {
|
|
22
|
+
pdf: RpcOutput<typeof renderPdfPage>;
|
|
23
|
+
office: EngineResults["pdf"];
|
|
24
|
+
"pdf-layout": PageRun[];
|
|
25
|
+
"office-layout": EngineResults["pdf-layout"];
|
|
26
|
+
"pdf-text": NonNullable<RpcOutput<typeof readDocumentText>>;
|
|
27
|
+
"pdf-search": NonNullable<RpcOutput<typeof findDocumentText>>;
|
|
28
|
+
"office-text": EngineResults["pdf-text"];
|
|
29
|
+
"office-search": EngineResults["pdf-search"];
|
|
30
|
+
"markdown-search": RpcOutput<typeof searchMarkdownFile>;
|
|
31
|
+
document: RpcOutput<typeof readStructuredDocument>;
|
|
32
|
+
worksheet: RpcOutput<typeof readWorksheet>;
|
|
33
|
+
"worksheet-search": RpcOutput<typeof findWorksheetText>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type EngineResponse =
|
|
37
|
+
| { result: EngineResults[keyof EngineResults] }
|
|
38
|
+
| { error: string };
|
package/server/worksheet.ts
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
|
-
import { posix } from "node:path";
|
|
2
|
-
import type { MarkdownSearchOptions, Worksheet, WorksheetMatch } from "../shared/contracts";
|
|
3
|
-
import { worksheetFileLimit } from "../shared/file-limits";
|
|
4
|
-
import { loadOfficeSources } from "./office-xml";
|
|
5
|
-
import { rustReader } from "./rust-reader";
|
|
6
|
-
import { searchExpression } from "./text-search";
|
|
7
|
-
import { withWorkspaceFile } from "./workspace-file";
|
|
8
|
-
|
|
9
|
-
const workbookParts = /^xl\/(?:workbook\.xml|styles\.xml|sharedStrings\.xml|_rels\/workbook\.xml\.rels)$/;
|
|
10
|
-
const worksheetPart = /^xl\/worksheets\/[^/]+\.xml$/;
|
|
11
|
-
let cached: {
|
|
12
|
-
key: string;
|
|
13
|
-
workbook: Awaited<ReturnType<typeof loadWorkbook>>;
|
|
14
|
-
sheet?: { index: number; data: Worksheet };
|
|
15
|
-
} | undefined;
|
|
16
|
-
|
|
17
|
-
async function loadWorkbook(bytes: Buffer) {
|
|
18
|
-
const [reader, sources] = await Promise.all([rustReader(), loadOfficeSources(bytes, (path) => workbookParts.test(path))]);
|
|
19
|
-
const workbook = sources.get("xl/workbook.xml");
|
|
20
|
-
const relationships = sources.get("xl/_rels/workbook.xml.rels");
|
|
21
|
-
if (!workbook || !relationships) throw new Error("Missing document parts.");
|
|
22
|
-
const parsed = new reader.Workbook(workbook, relationships,
|
|
23
|
-
sources.get("xl/styles.xml") ?? "", sources.get("xl/sharedStrings.xml") ?? "");
|
|
24
|
-
const sheets: [name: string, target: string | null][] = JSON.parse(parsed.sheetFiles());
|
|
25
|
-
return { bytes, parsed, sheets };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function loadWorksheet(root: string, path: string, selected: number) {
|
|
29
|
-
return withWorkspaceFile(root, path, ["xlsx"], async (file, size, revision) => {
|
|
30
|
-
if (size > worksheetFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
31
|
-
const key = JSON.stringify([root, path, revision]);
|
|
32
|
-
if (cached?.key !== key) cached = { key, workbook: await loadWorkbook(await file.readFile()) };
|
|
33
|
-
const current = cached;
|
|
34
|
-
const { sheets, bytes, parsed } = current.workbook;
|
|
35
|
-
const index = Math.min(selected, sheets.length - 1);
|
|
36
|
-
if (current.sheet?.index !== index) {
|
|
37
|
-
const selectedSheet = sheets[index];
|
|
38
|
-
let source = "";
|
|
39
|
-
if (selectedSheet) {
|
|
40
|
-
const [, target] = selectedSheet;
|
|
41
|
-
if (!target) throw new Error("Unsupported worksheet part.");
|
|
42
|
-
const path = target.startsWith("/") ? target.slice(1) : posix.normalize(`xl/${target}`);
|
|
43
|
-
if (!worksheetPart.test(path)) throw new Error("Unsupported worksheet part.");
|
|
44
|
-
source = (await loadOfficeSources(bytes, (name) => name === path)).get(path) ?? "";
|
|
45
|
-
if (!source) throw new Error("Missing worksheet part.");
|
|
46
|
-
}
|
|
47
|
-
current.sheet = { index, data: JSON.parse(parsed.previewSheet(source)) as Worksheet };
|
|
48
|
-
}
|
|
49
|
-
return { names: sheets.map(([name]) => name), sheet: current.sheet.data };
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export async function searchWorksheet(root: string, path: string, index: number, query: string, options: MarkdownSearchOptions) {
|
|
54
|
-
const expression = searchExpression(query, options);
|
|
55
|
-
const matches: WorksheetMatch[] = [];
|
|
56
|
-
if (!expression) return { matches, limited: false, invalidPattern: true };
|
|
57
|
-
const { sheet } = await loadWorksheet(root, path, index);
|
|
58
|
-
for (const [row, column, text] of sheet.cells) {
|
|
59
|
-
if (!sheet.rows[row] || !sheet.columns[column]) continue;
|
|
60
|
-
for (const match of text.matchAll(expression)) {
|
|
61
|
-
if (!match[0].length) continue;
|
|
62
|
-
if (matches.length >= 10_000) return { matches, limited: true, invalidPattern: false };
|
|
63
|
-
matches.push([row, column, match.index, match.index + match[0].length]);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
return { matches, limited: sheet.truncated, invalidPattern: false };
|
|
67
|
-
}
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import type { MarkdownSearchOptions, Worksheet, WorksheetMatch } from "../shared/contracts";
|
|
3
|
+
import { worksheetFileLimit } from "../shared/file-limits";
|
|
4
|
+
import { loadOfficeSources } from "./office-xml";
|
|
5
|
+
import { rustReader } from "./rust-reader";
|
|
6
|
+
import { searchExpression } from "./text-search";
|
|
7
|
+
import { withWorkspaceFile } from "./workspace-file";
|
|
8
|
+
|
|
9
|
+
const workbookParts = /^xl\/(?:workbook\.xml|styles\.xml|sharedStrings\.xml|_rels\/workbook\.xml\.rels)$/;
|
|
10
|
+
const worksheetPart = /^xl\/worksheets\/[^/]+\.xml$/;
|
|
11
|
+
let cached: {
|
|
12
|
+
key: string;
|
|
13
|
+
workbook: Awaited<ReturnType<typeof loadWorkbook>>;
|
|
14
|
+
sheet?: { index: number; data: Worksheet };
|
|
15
|
+
} | undefined;
|
|
16
|
+
|
|
17
|
+
async function loadWorkbook(bytes: Buffer) {
|
|
18
|
+
const [reader, sources] = await Promise.all([rustReader(), loadOfficeSources(bytes, (path) => workbookParts.test(path))]);
|
|
19
|
+
const workbook = sources.get("xl/workbook.xml");
|
|
20
|
+
const relationships = sources.get("xl/_rels/workbook.xml.rels");
|
|
21
|
+
if (!workbook || !relationships) throw new Error("Missing document parts.");
|
|
22
|
+
const parsed = new reader.Workbook(workbook, relationships,
|
|
23
|
+
sources.get("xl/styles.xml") ?? "", sources.get("xl/sharedStrings.xml") ?? "");
|
|
24
|
+
const sheets: [name: string, target: string | null][] = JSON.parse(parsed.sheetFiles());
|
|
25
|
+
return { bytes, parsed, sheets };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function loadWorksheet(root: string, path: string, selected: number) {
|
|
29
|
+
return withWorkspaceFile(root, path, ["xlsx"], async (file, size, revision) => {
|
|
30
|
+
if (size > worksheetFileLimit) throw new Error("Document exceeds the preview limit.");
|
|
31
|
+
const key = JSON.stringify([root, path, revision]);
|
|
32
|
+
if (cached?.key !== key) cached = { key, workbook: await loadWorkbook(await file.readFile()) };
|
|
33
|
+
const current = cached;
|
|
34
|
+
const { sheets, bytes, parsed } = current.workbook;
|
|
35
|
+
const index = Math.min(selected, sheets.length - 1);
|
|
36
|
+
if (current.sheet?.index !== index) {
|
|
37
|
+
const selectedSheet = sheets[index];
|
|
38
|
+
let source = "";
|
|
39
|
+
if (selectedSheet) {
|
|
40
|
+
const [, target] = selectedSheet;
|
|
41
|
+
if (!target) throw new Error("Unsupported worksheet part.");
|
|
42
|
+
const path = target.startsWith("/") ? target.slice(1) : posix.normalize(`xl/${target}`);
|
|
43
|
+
if (!worksheetPart.test(path)) throw new Error("Unsupported worksheet part.");
|
|
44
|
+
source = (await loadOfficeSources(bytes, (name) => name === path)).get(path) ?? "";
|
|
45
|
+
if (!source) throw new Error("Missing worksheet part.");
|
|
46
|
+
}
|
|
47
|
+
current.sheet = { index, data: JSON.parse(parsed.previewSheet(source)) as Worksheet };
|
|
48
|
+
}
|
|
49
|
+
return { names: sheets.map(([name]) => name), sheet: current.sheet.data };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function searchWorksheet(root: string, path: string, index: number, query: string, options: MarkdownSearchOptions) {
|
|
54
|
+
const expression = searchExpression(query, options);
|
|
55
|
+
const matches: WorksheetMatch[] = [];
|
|
56
|
+
if (!expression) return { matches, limited: false, invalidPattern: true };
|
|
57
|
+
const { sheet } = await loadWorksheet(root, path, index);
|
|
58
|
+
for (const [row, column, text] of sheet.cells) {
|
|
59
|
+
if (!sheet.rows[row] || !sheet.columns[column]) continue;
|
|
60
|
+
for (const match of text.matchAll(expression)) {
|
|
61
|
+
if (!match[0].length) continue;
|
|
62
|
+
if (matches.length >= 10_000) return { matches, limited: true, invalidPattern: false };
|
|
63
|
+
matches.push([row, column, match.index, match.index + match[0].length]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { matches, limited: sheet.truncated, invalidPattern: false };
|
|
67
|
+
}
|