@wirecat/cli-core 0.738.0 → 0.740.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/CHANGELOG.md +59 -0
- package/dist/attachments/ocr.d.ts +2 -0
- package/dist/attachments/ocr.js +2 -1
- package/dist/attachments/tesseract.d.ts +11 -0
- package/dist/attachments/tesseract.js +82 -0
- package/dist/cli/documents/file-edit.js +79 -34
- package/dist/cli/documents/file-update.d.ts +5 -0
- package/dist/cli/documents/index.d.ts +2 -1
- package/dist/cli/documents/index.js +2 -1
- package/dist/cli/documents/library.d.ts +12 -0
- package/dist/cli/documents/library.js +33 -3
- package/dist/cli/documents/manifest/manifest.d.ts +10 -0
- package/dist/cli/documents/manifest/manifest.js +9 -1
- package/dist/cli/documents/manifest/source.d.ts +4 -1
- package/dist/cli/documents/manifest/source.js +67 -1
- package/dist/cli/documents/rekey.d.ts +22 -0
- package/dist/cli/documents/rekey.js +25 -0
- package/dist/documents/file-mirror-model.d.ts +4 -1
- package/dist/documents/index.d.ts +1 -0
- package/dist/documents/index.js +1 -0
- package/dist/documents/model.d.ts +8 -0
- package/dist/errors/reasons.js +6 -15
- package/dist/errors/sftp-reasons.d.ts +5 -0
- package/dist/errors/sftp-reasons.js +15 -0
- package/dist/office/create.d.ts +38 -7
- package/dist/office/create.js +84 -20
- package/dist/office/index.d.ts +1 -1
- package/dist/services/documents/file-text.d.ts +6 -1
- package/dist/services/documents/file-text.js +29 -11
- package/dist/services/documents/ingestion.d.ts +5 -0
- package/dist/services/documents/ingestion.js +21 -1
- package/dist/services/documents/plan.js +151 -102
- package/dist/services/documents/ports.d.ts +3 -0
- package/dist/services/documents/scans.d.ts +42 -0
- package/dist/services/documents/scans.js +136 -0
- package/dist/services/documents/sync.js +57 -4
- package/dist/services/files/guarded-write.d.ts +6 -0
- package/dist/services/files/guarded-write.js +7 -1
- package/dist/services/files/mirror.js +2 -3
- package/dist/store/sqlite/file-note-rekey.d.ts +8 -0
- package/dist/store/sqlite/file-note-rekey.js +47 -0
- package/dist/store/sqlite/notes.d.ts +7 -2
- package/dist/store/sqlite/notes.js +4 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CliError } from "@wirecat/cli-base";
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
2
|
import { answerAt as at, nextPage, parameterValue, withValue, } from "../../service-api-manifest.js";
|
|
3
3
|
import { parseDocumentManifest } from "./manifest.js";
|
|
4
4
|
const OVERLAP_MS = 10 * 60_000;
|
|
@@ -66,6 +66,7 @@ export const documentSourceFromManifest = (input, options) => {
|
|
|
66
66
|
get: manifest.get,
|
|
67
67
|
children: manifest.children,
|
|
68
68
|
changes: manifest.changes,
|
|
69
|
+
deletions: manifest.deletions,
|
|
69
70
|
content: manifest.content,
|
|
70
71
|
};
|
|
71
72
|
const callOf = (name) => {
|
|
@@ -253,5 +254,70 @@ export const documentSourceFromManifest = (input, options) => {
|
|
|
253
254
|
throw new CliError("configuration_error", "source manifest: a change feed needs both startToken and changes", {
|
|
254
255
|
reason: "manifest.invalid",
|
|
255
256
|
});
|
|
257
|
+
const { deletions } = manifest;
|
|
258
|
+
if (deletions) {
|
|
259
|
+
const changesOf = source.changes;
|
|
260
|
+
if (!changesOf)
|
|
261
|
+
throw new CliError("configuration_error", "source manifest: deletions needs a change feed to read them in", {
|
|
262
|
+
reason: "manifest.invalid",
|
|
263
|
+
});
|
|
264
|
+
const warn = options.warn;
|
|
265
|
+
// A refused feed with no one told would answer a sync that never checked deletions as a whole one.
|
|
266
|
+
if (!warn)
|
|
267
|
+
throw new CliError("configuration_error", "source manifest: deletions needs the run's warn", {
|
|
268
|
+
reason: "manifest.invalid",
|
|
269
|
+
});
|
|
270
|
+
const overlap = deletions.overlapMs ?? changes?.overlapMs ?? OVERLAP_MS;
|
|
271
|
+
const deletedSince = async (sinceMs) => {
|
|
272
|
+
const since = SINCE[deletions.since](sinceMs);
|
|
273
|
+
const items = [];
|
|
274
|
+
let cursor;
|
|
275
|
+
for (let pages = 0; pages < MOST_PAGES; pages++) {
|
|
276
|
+
let listed;
|
|
277
|
+
try {
|
|
278
|
+
listed = await page(deletions, { since }, cursor);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
// The provider may keep this feed to admins or a higher plan; the changes still hold, and a full walk finds
|
|
282
|
+
// the trash.
|
|
283
|
+
if (!isCliError(error) || error.code !== "permission_error")
|
|
284
|
+
throw error;
|
|
285
|
+
warn({
|
|
286
|
+
code: "permission_error",
|
|
287
|
+
reason: "source.deletions-unchecked",
|
|
288
|
+
message: `${manifest.provider} refused its list of deleted documents to this sign-in, so documents deleted ` +
|
|
289
|
+
"since the last sync were not checked; sync --rescan finds them",
|
|
290
|
+
});
|
|
291
|
+
return items;
|
|
292
|
+
}
|
|
293
|
+
for (const row of listed.rows) {
|
|
294
|
+
const deleted = Date.parse(time(at(row, deletions.time)) ?? "");
|
|
295
|
+
if (Number.isFinite(deleted) && deleted < sinceMs)
|
|
296
|
+
continue;
|
|
297
|
+
const id = text(at(row, deletions.id));
|
|
298
|
+
if (!id)
|
|
299
|
+
throw new CliError("invalid_response", `a ${manifest.provider} deletion has no id at ${deletions.id}`, {
|
|
300
|
+
reason: "source.no-id",
|
|
301
|
+
});
|
|
302
|
+
items.push({ id, removed: true, gone: "deleted" });
|
|
303
|
+
}
|
|
304
|
+
if (!listed.next)
|
|
305
|
+
return items;
|
|
306
|
+
cursor = listed.next;
|
|
307
|
+
}
|
|
308
|
+
throw new CliError("invalid_response", `more than ${MOST_PAGES} pages of ${manifest.provider} deletions since one sync; run sync --rescan`, { reason: "source.changes-too-many" });
|
|
309
|
+
};
|
|
310
|
+
source.changes = async (token) => {
|
|
311
|
+
const from = Number(token);
|
|
312
|
+
if (!Number.isSafeInteger(from))
|
|
313
|
+
throw new CliError("validation_error", `not a change token of ${manifest.provider}: ${token}`, {
|
|
314
|
+
reason: "source.token-invalid",
|
|
315
|
+
});
|
|
316
|
+
const deleted = await deletedSince(from - overlap);
|
|
317
|
+
// Read after the deletions and listed after them, a row of the changes is the newer word and wins.
|
|
318
|
+
const round = await changesOf.call(source, token);
|
|
319
|
+
return { ...round, items: [...deleted, ...round.items] };
|
|
320
|
+
};
|
|
321
|
+
}
|
|
256
322
|
return source;
|
|
257
323
|
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ProviderEntry } from "../../domain/providers.js";
|
|
2
|
+
import type { AppIdentity } from "../../ports/app.js";
|
|
3
|
+
import type { MessageStore } from "../../store/index.js";
|
|
4
|
+
export interface SyncedDocumentRekey {
|
|
5
|
+
env: NodeJS.ProcessEnv;
|
|
6
|
+
app: Pick<AppIdentity, "command" | "version">;
|
|
7
|
+
provider: ProviderEntry;
|
|
8
|
+
/** The same ingestion the CLI's documents commands file documents with. */
|
|
9
|
+
ingestion(store: MessageStore): {
|
|
10
|
+
rekey(principal: string, from: string, to: string): Promise<boolean>;
|
|
11
|
+
};
|
|
12
|
+
/** The account's principal, as the documents sync names it. */
|
|
13
|
+
account: string;
|
|
14
|
+
from: string;
|
|
15
|
+
to: string;
|
|
16
|
+
warn(message: string): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* After a write that gave a file a new id at the provider, moves its synced copy to that id, so the owner's tags and
|
|
20
|
+
* notes follow the file. The write already happened, so a failure only warns; a store never opened stays unopened.
|
|
21
|
+
*/
|
|
22
|
+
export declare const rekeySyncedDocument: (input: SyncedDocumentRekey) => Promise<boolean>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { storePath } from "../../store/path.js";
|
|
3
|
+
import { openAppStore } from "../app-store.js";
|
|
4
|
+
/**
|
|
5
|
+
* After a write that gave a file a new id at the provider, moves its synced copy to that id, so the owner's tags and
|
|
6
|
+
* notes follow the file. The write already happened, so a failure only warns; a store never opened stays unopened.
|
|
7
|
+
*/
|
|
8
|
+
export const rekeySyncedDocument = async (input) => {
|
|
9
|
+
if (!existsSync(storePath(input.env)))
|
|
10
|
+
return false;
|
|
11
|
+
try {
|
|
12
|
+
const store = await openAppStore(input.env, { app: input.app, provider: input.provider });
|
|
13
|
+
try {
|
|
14
|
+
return await input.ingestion(store).rekey(input.account, input.from, input.to);
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
await store.close();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
22
|
+
input.warn(`the synced copy keeps its tags and notes under the old id ${input.from}: ${why}`);
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
export interface RemoteFile {
|
|
3
3
|
/** Relative to the listed folder, with `/` separators. */
|
|
4
4
|
path: string;
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Stays the same across a move, so a remote rename is found by it. A replace may give a new one (Yandex Disk's
|
|
7
|
+
* replace through a temporary file); the mirror records what the upload returns.
|
|
8
|
+
*/
|
|
6
9
|
id: string;
|
|
7
10
|
size: number;
|
|
8
11
|
/** The plain sha256 of the content. A file without one (still being processed) is left for the next run. */
|
|
@@ -9,6 +9,7 @@ export { conflictReport, fileMirrorState, type HeldLock, type Mirror, type Mirro
|
|
|
9
9
|
export type { SyncOptions } from "../services/documents/ports.js";
|
|
10
10
|
export { extractDocumentMemories, type ImportedSource, type ProposalOptions } from "../services/documents/proposals.js";
|
|
11
11
|
export { type MirrorAction, type PushConflict, type PushOptions, type PushResult, planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
|
|
12
|
+
export { SCAN_READERS, type ScanReader, type ScanReaderChoice, scanReader, scanRetry, scanSkipReason, } from "../services/documents/scans.js";
|
|
12
13
|
export { KEEP_VERSIONS_FOR_DAYS, type SyncResult, syncDocuments } from "../services/documents/sync.js";
|
|
13
14
|
export { type FileConflictResolution, type FileConflictResolveOptions, type FileConflictVersion, type FileConflictView, listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
|
|
14
15
|
export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
|
package/dist/documents/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export { watchMirrors, } from "../services/documents/mirror-watch.js";
|
|
|
8
8
|
export { conflictReport, fileMirrorState, mirrorId, mirrorStatus, syncMirrors, } from "../services/documents/mirrors.js";
|
|
9
9
|
export { extractDocumentMemories } from "../services/documents/proposals.js";
|
|
10
10
|
export { planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
|
|
11
|
+
export { SCAN_READERS, scanReader, scanRetry, scanSkipReason, } from "../services/documents/scans.js";
|
|
11
12
|
export { KEEP_VERSIONS_FOR_DAYS, syncDocuments } from "../services/documents/sync.js";
|
|
12
13
|
export { listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
|
|
13
14
|
export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
|
|
@@ -67,6 +67,12 @@ export interface FeedlessDocumentSource<M extends SourceFile = SourceFile> {
|
|
|
67
67
|
}>;
|
|
68
68
|
content(id: string, maxChars?: number, file?: M): Promise<SourceContent<M>>;
|
|
69
69
|
bytes(id: string, file?: M): Promise<Uint8Array>;
|
|
70
|
+
/**
|
|
71
|
+
* How many folders a sync lists at once, for a provider whose one listing takes seconds (Yandex Disk): a whole
|
|
72
|
+
* number up to 8; one when unset or anything else. Each listing takes its own request from the run's budget; a source that paces its requests keeps pacing
|
|
73
|
+
* them, so stay within the provider's rate limit.
|
|
74
|
+
*/
|
|
75
|
+
parallelListings?: number;
|
|
70
76
|
/**
|
|
71
77
|
* Whether a saved document is read again though it did not change: one saved before the source learned to read
|
|
72
78
|
* something (a page's authors). The sync reads at most `REREAD_BATCH` of them a pass, so new edits are not held back;
|
|
@@ -91,6 +97,8 @@ export interface IndexedSource<M extends SourceFile = SourceFile> {
|
|
|
91
97
|
tabs: number;
|
|
92
98
|
notRead?: string;
|
|
93
99
|
picture?: "saved" | "too-large";
|
|
100
|
+
/** The OCR reading its text came from (`ScanReader.extractor`); absent for text a reader found in the file. */
|
|
101
|
+
ocr?: string;
|
|
94
102
|
}
|
|
95
103
|
export interface SourceWork<M extends SourceFile = SourceFile> {
|
|
96
104
|
id: string;
|
package/dist/errors/reasons.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { QUERY_REASONS } from "@wirecat/cli-base/query";
|
|
2
2
|
import { defineReasons } from "@wirecat/cli-base/standards";
|
|
3
3
|
import { CHAT_SENDING_ASK_DETAILS } from "../models/chat-sending.js";
|
|
4
|
-
|
|
4
|
+
import { SFTP, validation } from "./sftp-reasons.js";
|
|
5
5
|
/** The query reasons only message search raises; the shared ones are cli-base's `QUERY_REASONS`. */
|
|
6
6
|
const QUERY = [
|
|
7
7
|
["query.aborted", "the search was stopped before it finished"],
|
|
@@ -87,6 +87,7 @@ const PROVIDER_API = [
|
|
|
87
87
|
"invalid_response",
|
|
88
88
|
"more changed since one sync than a round reads, and the provider does not list changes oldest first",
|
|
89
89
|
],
|
|
90
|
+
["source.deletions-unchecked", "permission_error", "the provider refused its deletions; sync --rescan finds them"],
|
|
90
91
|
["verify.no-id", "provider_error", "the answer to the sign-in check holds no account id where auth.verify says"],
|
|
91
92
|
["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
|
|
92
93
|
["access.denied", "permission_error", "the provider refused this account access to the item"],
|
|
@@ -97,20 +98,6 @@ const PROVIDER_API = [
|
|
|
97
98
|
validation("file.too-large", "the file is larger than the limit set for this read"),
|
|
98
99
|
validation("file.not-plain-text", "the file's text is extracted on a read; writing it back would replace the file"),
|
|
99
100
|
];
|
|
100
|
-
/** The read-only SFTP client (`./sftp`). */
|
|
101
|
-
const SFTP = [
|
|
102
|
-
["sftp.host-key-missing", "configuration_error", "no host key is pinned for the SFTP server"],
|
|
103
|
-
["sftp.host-key-mismatch", "authentication_error", "the SFTP server's host key is not the pinned one"],
|
|
104
|
-
["sftp.auth-missing", "configuration_error", "an SFTP connection needs a password or a private key"],
|
|
105
|
-
["sftp.key-invalid", "configuration_error", "the SFTP private key or its passphrase cannot be read"],
|
|
106
|
-
["sftp.library-missing", "configuration_error", "SFTP needs the ssh2 package in the CLI's dependencies"],
|
|
107
|
-
["sftp.timeout", "timeout", "the SFTP server did not answer in time"],
|
|
108
|
-
validation("sftp.too-large", "the file is larger than the read's byte limit"),
|
|
109
|
-
validation("sftp.closed", "the SFTP connection was closed before the operation"),
|
|
110
|
-
validation("sftp.file-changed", "the file changed on the server while a stream read it; read it again"),
|
|
111
|
-
["ssh.forward-refused", "permission_error", "the SSH server does not allow forwarding to that address"],
|
|
112
|
-
["ssh.forward-failed", "network_error", "the SSH server could not reach the address behind it"],
|
|
113
|
-
];
|
|
114
101
|
/** The read-only SQL reader (`./sql`). */
|
|
115
102
|
const SQL = [
|
|
116
103
|
validation("sql.bad-identifier", "a table or column name is not a plain identifier"),
|
|
@@ -240,6 +227,9 @@ const OTHERS = [
|
|
|
240
227
|
],
|
|
241
228
|
validation("agent.cost-unknown", "the agent reports no cost, so a cost cap cannot stop it"),
|
|
242
229
|
validation("document.changed", "the document changed while it was read; nothing was saved"),
|
|
230
|
+
validation("document.needs-ocr", "the PDF has no text layer; a documents sync reads it with OCR (read_scans)"),
|
|
231
|
+
validation("document.scan-unread", "OCR could not read the scan or picture; a sync tries again once the file changes"),
|
|
232
|
+
validation("document.scan-later", "OCR stopped at its page limit or a busy model; the next sync goes on"),
|
|
243
233
|
["document.not-imported", "not_found", "the document is not imported in this source account"],
|
|
244
234
|
["document.version-missing", "not_found", "the local copy holds no such version of the document"],
|
|
245
235
|
["document.not-found", "not_found", "no listed document has that reference"],
|
|
@@ -307,6 +297,7 @@ const OTHERS = [
|
|
|
307
297
|
["mirror.remote-changed", "conflict", "the remote file changed since the listing; the next sync settles it"],
|
|
308
298
|
["mirror.local-changed", "conflict", "the local file changed since the conflict was found; nothing was written"],
|
|
309
299
|
["mirror.no-conflict", "not_found", "the path has no recorded conflict; the last sync settled it or never saw one"],
|
|
300
|
+
["upload.replace-interrupted", "conflict", "another file took the path during a replace; the new content is kept"],
|
|
310
301
|
["upload.mismatch", "conflict", "the uploaded file reads back with other content; the local file changed meanwhile"],
|
|
311
302
|
["download.mismatch", "invalid_response", "the downloaded file has other content than the listing said"],
|
|
312
303
|
["catalog.unavailable", "configuration_error", "the store has no shared catalog for this account"],
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ErrorReason } from "@wirecat/cli-base/standards";
|
|
2
|
+
export type Entry = [reason: string, code: ErrorReason["code"], message: string];
|
|
3
|
+
export declare const validation: (reason: string, message: string) => Entry;
|
|
4
|
+
/** The read-only SFTP client (`./sftp`). */
|
|
5
|
+
export declare const SFTP: Entry[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const validation = (reason, message) => [reason, "validation_error", message];
|
|
2
|
+
/** The read-only SFTP client (`./sftp`). */
|
|
3
|
+
export const SFTP = [
|
|
4
|
+
["sftp.host-key-missing", "configuration_error", "no host key is pinned for the SFTP server"],
|
|
5
|
+
["sftp.host-key-mismatch", "authentication_error", "the SFTP server's host key is not the pinned one"],
|
|
6
|
+
["sftp.auth-missing", "configuration_error", "an SFTP connection needs a password or a private key"],
|
|
7
|
+
["sftp.key-invalid", "configuration_error", "the SFTP private key or its passphrase cannot be read"],
|
|
8
|
+
["sftp.library-missing", "configuration_error", "SFTP needs the ssh2 package in the CLI's dependencies"],
|
|
9
|
+
["sftp.timeout", "timeout", "the SFTP server did not answer in time"],
|
|
10
|
+
validation("sftp.too-large", "the file is larger than the read's byte limit"),
|
|
11
|
+
validation("sftp.closed", "the SFTP connection was closed before the operation"),
|
|
12
|
+
validation("sftp.file-changed", "the file changed on the server while a stream read it; read it again"),
|
|
13
|
+
["ssh.forward-refused", "permission_error", "the SSH server does not allow forwarding to that address"],
|
|
14
|
+
["ssh.forward-failed", "network_error", "the SSH server could not reach the address behind it"],
|
|
15
|
+
];
|
package/dist/office/create.d.ts
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
import type { CellValue } from "./xlsx.js";
|
|
2
|
+
/** A formula without a cached result, computed when the file opens; `=` in front is optional. */
|
|
3
|
+
export interface NewFormulaCell {
|
|
4
|
+
readonly formula: string;
|
|
5
|
+
readonly bold?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** A value with formatting; a text that starts with `=` stays text here too. */
|
|
8
|
+
export interface NewValueCell {
|
|
9
|
+
readonly value: CellValue;
|
|
10
|
+
readonly bold?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export type NewCell = CellValue | NewFormulaCell | NewValueCell;
|
|
2
13
|
export interface NewSheet {
|
|
3
14
|
/** 1 to 31 characters, none of `[]:*?/\`, not starting or ending with `'`; unique in the workbook, ignoring case. */
|
|
4
15
|
readonly name: string;
|
|
5
16
|
/** Rows from A1 down; `null` leaves a cell empty. */
|
|
6
|
-
readonly rows: readonly (readonly
|
|
17
|
+
readonly rows: readonly (readonly NewCell[])[];
|
|
18
|
+
/** This sheet's first row in bold. */
|
|
19
|
+
readonly header?: boolean;
|
|
7
20
|
}
|
|
8
21
|
export interface CreateXlsxOptions {
|
|
9
22
|
readonly sheets: readonly NewSheet[];
|
|
@@ -12,23 +25,41 @@ export interface CreateXlsxOptions {
|
|
|
12
25
|
}
|
|
13
26
|
/**
|
|
14
27
|
* A new workbook with these sheets and values: strings in a shared strings part (a string that starts with `=` stays
|
|
15
|
-
* text), numbers and booleans typed. No document properties, so the same input gives the same
|
|
28
|
+
* text), numbers and booleans typed, `{formula}` a formula. No document properties, so the same input gives the same
|
|
29
|
+
* bytes.
|
|
16
30
|
*/
|
|
17
31
|
export declare const createXlsx: (options: CreateXlsxOptions) => Uint8Array;
|
|
18
32
|
export declare const NEW_PARAGRAPH_STYLES: readonly ["Title", "Heading1", "Heading2", "Heading3", "Normal", "ListBullet"];
|
|
19
33
|
export type NewParagraphStyle = (typeof NEW_PARAGRAPH_STYLES)[number];
|
|
20
|
-
export interface
|
|
34
|
+
export interface NewRun {
|
|
21
35
|
/** A tab is `\t`, a line break `\n`. */
|
|
22
36
|
readonly text: string;
|
|
37
|
+
readonly bold?: boolean;
|
|
38
|
+
readonly italic?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export type NewParagraph = ({
|
|
41
|
+
readonly text: string;
|
|
42
|
+
readonly bold?: boolean;
|
|
43
|
+
readonly italic?: boolean;
|
|
44
|
+
} | {
|
|
45
|
+
readonly runs: readonly NewRun[];
|
|
46
|
+
}) & {
|
|
23
47
|
/** `Normal` when absent. */
|
|
24
48
|
readonly style?: NewParagraphStyle;
|
|
49
|
+
};
|
|
50
|
+
export interface NewTable {
|
|
51
|
+
/** Rows of cell texts; a shorter row is filled with empty cells. */
|
|
52
|
+
readonly table: readonly (readonly string[])[];
|
|
53
|
+
/** The first row in bold, repeated at the top of each page. */
|
|
54
|
+
readonly header?: boolean;
|
|
25
55
|
}
|
|
26
56
|
export interface CreateDocxOptions {
|
|
27
|
-
|
|
57
|
+
/** The body in order: paragraphs and tables. */
|
|
58
|
+
readonly paragraphs: readonly (NewParagraph | NewTable)[];
|
|
28
59
|
}
|
|
29
60
|
/**
|
|
30
|
-
* A new Word document with these paragraphs, on A4 with 2.5 cm margins, and a styles part that defines
|
|
31
|
-
* Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
32
|
-
* same bytes.
|
|
61
|
+
* A new Word document with these paragraphs and tables, on A4 with 2.5 cm margins, and a styles part that defines
|
|
62
|
+
* Title, Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
63
|
+
* the same bytes.
|
|
33
64
|
*/
|
|
34
65
|
export declare const createDocx: (options: CreateDocxOptions) => Uint8Array;
|
package/dist/office/create.js
CHANGED
|
@@ -6,6 +6,8 @@ import { escapeText } from "./xml.js";
|
|
|
6
6
|
const MAX_ROW = 1_048_576;
|
|
7
7
|
const MAX_COLUMN = 16_384;
|
|
8
8
|
const MAX_CELL_TEXT = 32_767;
|
|
9
|
+
const MAX_FORMULA = 8_192;
|
|
10
|
+
const MAX_TABLE_COLUMNS = 63;
|
|
9
11
|
const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
|
|
10
12
|
const CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
11
13
|
const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
@@ -64,6 +66,14 @@ class SharedStrings {
|
|
|
64
66
|
return `<sst xmlns="${SHEET_NS}" count="${this.count}" uniqueCount="${this.size}">${items.join("")}</sst>`;
|
|
65
67
|
}
|
|
66
68
|
}
|
|
69
|
+
const formulaXml = (address, formula, style) => {
|
|
70
|
+
const text = formula.startsWith("=") ? formula.slice(1) : formula;
|
|
71
|
+
if (!text.trim())
|
|
72
|
+
throw refuse(`${address}: a formula cannot be empty`, "office.invalid-value");
|
|
73
|
+
if (text.length > MAX_FORMULA)
|
|
74
|
+
throw refuse(`${address}: a formula holds at most 8,192 characters`, "office.invalid-value");
|
|
75
|
+
return `<c r="${address}"${style}><f>${escapeText(text)}</f></c>`;
|
|
76
|
+
};
|
|
67
77
|
const cellXml = (address, value, style, strings) => {
|
|
68
78
|
if (typeof value === "boolean")
|
|
69
79
|
return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
|
|
@@ -76,7 +86,7 @@ const cellXml = (address, value, style, strings) => {
|
|
|
76
86
|
throw refuse(`${address}: a cell holds at most 32,767 characters`, "office.invalid-value");
|
|
77
87
|
return `<c r="${address}"${style} t="s"><v>${strings.index(value)}</v></c>`;
|
|
78
88
|
};
|
|
79
|
-
const worksheetXml = (sheet, strings, boldHeader) => {
|
|
89
|
+
const worksheetXml = (sheet, strings, boldHeader, formulas) => {
|
|
80
90
|
if (sheet.rows.length > MAX_ROW)
|
|
81
91
|
throw refuse(`sheet "${sheet.name}" has more than 1,048,576 rows`, "office.invalid-cell");
|
|
82
92
|
let right = 0;
|
|
@@ -84,12 +94,20 @@ const worksheetXml = (sheet, strings, boldHeader) => {
|
|
|
84
94
|
const rows = sheet.rows.flatMap((values, down) => {
|
|
85
95
|
if (values.length > MAX_COLUMN)
|
|
86
96
|
throw refuse(`row ${down + 1} of "${sheet.name}" has more than 16,384 cells`, "office.invalid-cell");
|
|
87
|
-
const
|
|
88
|
-
const cells = values.flatMap((
|
|
97
|
+
const header = (boldHeader || sheet.header === true) && down === 0;
|
|
98
|
+
const cells = values.flatMap((cell, across) => {
|
|
99
|
+
const formatted = cell !== null && typeof cell === "object";
|
|
100
|
+
const value = formatted ? ("formula" in cell ? undefined : cell.value) : cell;
|
|
89
101
|
if (value === null)
|
|
90
102
|
return [];
|
|
91
103
|
right = Math.max(right, across + 1);
|
|
92
|
-
|
|
104
|
+
const address = `${columnName(across + 1)}${down + 1}`;
|
|
105
|
+
const style = header || (formatted && cell.bold === true) ? ' s="1"' : "";
|
|
106
|
+
if (formatted && "formula" in cell) {
|
|
107
|
+
formulas.count++;
|
|
108
|
+
return [formulaXml(address, cell.formula, style)];
|
|
109
|
+
}
|
|
110
|
+
return [cellXml(address, value, style, strings)];
|
|
93
111
|
});
|
|
94
112
|
if (!cells.length)
|
|
95
113
|
return [];
|
|
@@ -113,16 +131,18 @@ const STYLES = `<styleSheet xmlns="${SHEET_NS}">` +
|
|
|
113
131
|
"</styleSheet>";
|
|
114
132
|
/**
|
|
115
133
|
* A new workbook with these sheets and values: strings in a shared strings part (a string that starts with `=` stays
|
|
116
|
-
* text), numbers and booleans typed. No document properties, so the same input gives the same
|
|
134
|
+
* text), numbers and booleans typed, `{formula}` a formula. No document properties, so the same input gives the same
|
|
135
|
+
* bytes.
|
|
117
136
|
*/
|
|
118
137
|
export const createXlsx = (options) => {
|
|
119
138
|
const { sheets, boldHeader = false } = options;
|
|
120
139
|
checkSheetNames(sheets);
|
|
121
140
|
const strings = new SharedStrings();
|
|
141
|
+
const formulas = { count: 0 };
|
|
122
142
|
const parts = {};
|
|
123
143
|
const types = { "xl/workbook.xml": "spreadsheetml.sheet.main+xml" };
|
|
124
144
|
sheets.forEach((sheet, index) => {
|
|
125
|
-
parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader);
|
|
145
|
+
parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader, formulas);
|
|
126
146
|
types[`xl/worksheets/sheet${index + 1}.xml`] = "spreadsheetml.worksheet+xml";
|
|
127
147
|
});
|
|
128
148
|
types["xl/styles.xml"] = "spreadsheetml.styles+xml";
|
|
@@ -137,10 +157,12 @@ export const createXlsx = (options) => {
|
|
|
137
157
|
const listed = sheets
|
|
138
158
|
.map((sheet, index) => `<sheet name="${escapeAttribute(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`)
|
|
139
159
|
.join("");
|
|
160
|
+
// No cached results are written, so Excel and LibreOffice must compute every formula as the file opens.
|
|
161
|
+
const calculation = formulas.count ? '<calcPr calcId="191029" fullCalcOnLoad="1"/>' : "";
|
|
140
162
|
return packed({
|
|
141
163
|
"[Content_Types].xml": contentTypes(types),
|
|
142
164
|
"_rels/.rels": relationships([["officeDocument", "xl/workbook.xml"]]),
|
|
143
|
-
"xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets
|
|
165
|
+
"xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets>${calculation}</workbook>`,
|
|
144
166
|
"xl/_rels/workbook.xml.rels": relationships(links),
|
|
145
167
|
"xl/styles.xml": STYLES,
|
|
146
168
|
...(strings.size ? { "xl/sharedStrings.xml": strings.xml() } : {}),
|
|
@@ -173,29 +195,71 @@ const NUMBERING = `<w:numbering xmlns:w="${WORD_NS}"><w:abstractNum w:abstractNu
|
|
|
173
195
|
'<w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/>' +
|
|
174
196
|
'<w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>' +
|
|
175
197
|
'</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>';
|
|
176
|
-
const
|
|
177
|
-
if (!NEW_PARAGRAPH_STYLES.includes(style))
|
|
178
|
-
throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
|
|
179
|
-
// The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
|
|
180
|
-
const properties = style === "Normal"
|
|
181
|
-
? ""
|
|
182
|
-
: `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
|
|
198
|
+
const runXml = ({ text, bold, italic }) => {
|
|
183
199
|
const content = text
|
|
184
200
|
.replace(/\r\n?/gu, "\n")
|
|
185
201
|
.split(/(\n|\t)/u)
|
|
186
202
|
.filter((piece) => piece !== "")
|
|
187
203
|
.map((piece) => piece === "\n" ? "<w:br/>" : piece === "\t" ? "<w:tab/>" : `<w:t xml:space="preserve">${escapeText(piece)}</w:t>`)
|
|
188
204
|
.join("");
|
|
189
|
-
|
|
205
|
+
if (!content)
|
|
206
|
+
return "";
|
|
207
|
+
const properties = (bold ? "<w:b/><w:bCs/>" : "") + (italic ? "<w:i/><w:iCs/>" : "");
|
|
208
|
+
return `<w:r>${properties ? `<w:rPr>${properties}</w:rPr>` : ""}${content}</w:r>`;
|
|
209
|
+
};
|
|
210
|
+
const paragraphXml = (paragraph) => {
|
|
211
|
+
const { style = "Normal" } = paragraph;
|
|
212
|
+
if (!NEW_PARAGRAPH_STYLES.includes(style))
|
|
213
|
+
throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
|
|
214
|
+
// The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
|
|
215
|
+
const properties = style === "Normal"
|
|
216
|
+
? ""
|
|
217
|
+
: `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
|
|
218
|
+
const runs = "runs" in paragraph ? paragraph.runs : [paragraph];
|
|
219
|
+
return `<w:p>${properties}${runs.map(runXml).join("")}</w:p>`;
|
|
220
|
+
};
|
|
221
|
+
// The text width of the A4 page between its margins, in twentieths of a point.
|
|
222
|
+
const TEXT_WIDTH = 11_906 - 2 * 1_417;
|
|
223
|
+
const BORDER = 'w:val="single" w:sz="4" w:space="0" w:color="auto"';
|
|
224
|
+
const tableXml = ({ table, header = false }) => {
|
|
225
|
+
const columns = table.reduce((widest, row) => Math.max(widest, row.length), 1);
|
|
226
|
+
if (columns > MAX_TABLE_COLUMNS)
|
|
227
|
+
throw refuse("a Word table has at most 63 columns", "office.invalid-value");
|
|
228
|
+
const width = Math.floor(TEXT_WIDTH / columns);
|
|
229
|
+
const borders = ["top", "left", "bottom", "right", "insideH", "insideV"].map((side) => `<w:${side} ${BORDER}/>`);
|
|
230
|
+
const rows = (table.length ? table : [[]]).map((cells, down) => {
|
|
231
|
+
const bold = header && down === 0;
|
|
232
|
+
const tcs = Array.from({ length: columns }, (_, across) => {
|
|
233
|
+
const text = cells[across] ?? "";
|
|
234
|
+
return `<w:tc><w:tcPr><w:tcW w:w="${width}" w:type="dxa"/></w:tcPr><w:p>${runXml({ text, bold })}</w:p></w:tc>`;
|
|
235
|
+
});
|
|
236
|
+
return `<w:tr>${bold ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${tcs.join("")}</w:tr>`;
|
|
237
|
+
});
|
|
238
|
+
return (`<w:tbl><w:tblPr><w:tblW w:w="${width * columns}" w:type="dxa"/><w:tblBorders>${borders.join("")}</w:tblBorders>` +
|
|
239
|
+
`</w:tblPr><w:tblGrid>${`<w:gridCol w:w="${width}"/>`.repeat(columns)}</w:tblGrid>` +
|
|
240
|
+
`${rows.join("")}</w:tbl>`);
|
|
241
|
+
};
|
|
242
|
+
// Word merges two tables that touch and needs a paragraph to end the body, so a table is never last or next to another.
|
|
243
|
+
const bodyXml = (blocks) => {
|
|
244
|
+
let previousTable = false;
|
|
245
|
+
const parts = blocks.flatMap((block) => {
|
|
246
|
+
const isTable = "table" in block;
|
|
247
|
+
const xml = isTable ? tableXml(block) : paragraphXml(block);
|
|
248
|
+
const between = isTable && previousTable ? ["<w:p/>"] : [];
|
|
249
|
+
previousTable = isTable;
|
|
250
|
+
return [...between, xml];
|
|
251
|
+
});
|
|
252
|
+
if (!parts.length || previousTable)
|
|
253
|
+
parts.push("<w:p/>");
|
|
254
|
+
return parts.join("");
|
|
190
255
|
};
|
|
191
256
|
/**
|
|
192
|
-
* A new Word document with these paragraphs, on A4 with 2.5 cm margins, and a styles part that defines
|
|
193
|
-
* Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
194
|
-
* same bytes.
|
|
257
|
+
* A new Word document with these paragraphs and tables, on A4 with 2.5 cm margins, and a styles part that defines
|
|
258
|
+
* Title, Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
259
|
+
* the same bytes.
|
|
195
260
|
*/
|
|
196
261
|
export const createDocx = (options) => {
|
|
197
|
-
|
|
198
|
-
const body = options.paragraphs.length ? options.paragraphs.map(paragraphXml).join("") : "<w:p/>";
|
|
262
|
+
const body = bodyXml(options.paragraphs);
|
|
199
263
|
const section = '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1417" w:right="1417" w:bottom="1417" w:left="1417" ' +
|
|
200
264
|
'w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>';
|
|
201
265
|
return packed({
|
package/dist/office/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewParagraph, type NewParagraphStyle, type NewSheet, } from "./create.js";
|
|
1
|
+
export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewCell, type NewFormulaCell, type NewParagraph, type NewParagraphStyle, type NewRun, type NewSheet, type NewTable, type NewValueCell, } from "./create.js";
|
|
2
2
|
export { type DocxEdit, type DocxParagraph, type EditDocxResult, editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
|
|
3
3
|
export { type CellType, type CellValue, type EditXlsxOptions, type EditXlsxResult, editXlsxCells, type ReadXlsxOptions, readXlsxCells, type XlsxCell, type XlsxEdit, type XlsxSheet, } from "./xlsx.js";
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
|
|
3
|
+
* EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
|
|
4
|
+
*/
|
|
2
5
|
export declare const readableFile: ({ name, mime }: {
|
|
3
6
|
name: string;
|
|
4
7
|
mime: string;
|
|
5
8
|
}) => boolean;
|
|
9
|
+
/** The start of the reason a file with no text layer is kept by name only, before and after OCR was offered. */
|
|
10
|
+
export declare const NO_TEXT_LAYER = "file has no text layer (a scan or images only)";
|
|
6
11
|
/**
|
|
7
12
|
* The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
|
|
8
13
|
* words a person acts on. `command` names the CLI in the hint for a missing reader.
|
|
@@ -3,15 +3,31 @@ import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../att
|
|
|
3
3
|
import { attachmentMaxBytes } from "../../attachments/limits.js";
|
|
4
4
|
const READABLE = new Set([
|
|
5
5
|
"application/pdf",
|
|
6
|
+
"application/msword",
|
|
6
7
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
7
8
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
9
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
10
|
+
"application/vnd.oasis.opendocument.text",
|
|
11
|
+
"application/vnd.oasis.opendocument.spreadsheet",
|
|
12
|
+
"application/vnd.oasis.opendocument.presentation",
|
|
13
|
+
"application/epub+zip",
|
|
14
|
+
"application/rtf",
|
|
15
|
+
"text/rtf",
|
|
16
|
+
"text/html",
|
|
17
|
+
"application/xhtml+xml",
|
|
8
18
|
"text/csv",
|
|
9
19
|
"text/tab-separated-values",
|
|
10
20
|
"text/plain",
|
|
11
21
|
"text/markdown",
|
|
12
22
|
]);
|
|
13
|
-
/**
|
|
14
|
-
|
|
23
|
+
/**
|
|
24
|
+
* A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
|
|
25
|
+
* EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
|
|
26
|
+
*/
|
|
27
|
+
export const readableFile = ({ name, mime }) => READABLE.has(mime) ||
|
|
28
|
+
/\.(md|markdown|txt|pdf|doc|docx|rtf|odt|ods|odp|xlsx|pptx|epub|html?|xhtml|csv|tsv)$/iu.test(name);
|
|
29
|
+
/** The start of the reason a file with no text layer is kept by name only, before and after OCR was offered. */
|
|
30
|
+
export const NO_TEXT_LAYER = "file has no text layer (a scan or images only)";
|
|
15
31
|
/**
|
|
16
32
|
* The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
|
|
17
33
|
* words a person acts on. `command` names the CLI in the hint for a missing reader.
|
|
@@ -20,14 +36,16 @@ export const fileText = async (bytes, file, command, env = process.env) => {
|
|
|
20
36
|
const read = await extractText(bytes, { kind: "document", name: file.name, mime: file.mime, path: file.name }, importEngine, undefined, env);
|
|
21
37
|
if (read.status === "extracted")
|
|
22
38
|
return read.text;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
39
|
+
if (read.status === "needs-agent")
|
|
40
|
+
throw new CliError("validation_error", `${NO_TEXT_LAYER}; a documents sync reads it with OCR (read_scans)`, {
|
|
41
|
+
reason: "document.needs-ocr",
|
|
42
|
+
});
|
|
43
|
+
const reason = read.status === "engine-missing"
|
|
44
|
+
? engineHint(read.engine, command)
|
|
45
|
+
: read.status === "unreadable"
|
|
46
|
+
? "file could not be read as text; it may be damaged or protected"
|
|
47
|
+
: read.status === "unsupported"
|
|
48
|
+
? "file contents do not match its type"
|
|
49
|
+
: `file is too large for the document readers (over ${Math.round(attachmentMaxBytes(env) / 1024 / 1024)} MB, or over ${MAX_TEXT_CHARS} characters of text)`;
|
|
32
50
|
throw new CliError("validation_error", reason);
|
|
33
51
|
};
|
|
@@ -35,6 +35,11 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
|
|
|
35
35
|
until: () => boolean;
|
|
36
36
|
}) => Promise<number>;
|
|
37
37
|
save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
|
|
38
|
+
/**
|
|
39
|
+
* Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
|
|
40
|
+
* its tags, the notes about it and its links stay with it. False when the file was never synced.
|
|
41
|
+
*/
|
|
42
|
+
rekey: (principal: string, from: string, to: string) => Promise<boolean>;
|
|
38
43
|
remove: (principal: string, id: string, reason?: SourceRemoval) => Promise<void>;
|
|
39
44
|
prune: (principal: string, before: string) => Promise<{
|
|
40
45
|
versions: number;
|