@wirecat/cli-core 0.720.0 → 0.721.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 (63) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/config-command.js +8 -2
  4. package/dist/cli/config-issues.d.ts +3 -1
  5. package/dist/cli/config-issues.js +9 -2
  6. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  7. package/dist/cli/documents/file-conflicts.js +102 -0
  8. package/dist/cli/documents/file-edit.d.ts +29 -0
  9. package/dist/cli/documents/file-edit.js +352 -0
  10. package/dist/cli/documents/file-update.d.ts +43 -0
  11. package/dist/cli/documents/file-update.js +95 -0
  12. package/dist/cli/documents/history.d.ts +34 -0
  13. package/dist/cli/documents/history.js +89 -0
  14. package/dist/cli/documents/index.d.ts +9 -2
  15. package/dist/cli/documents/index.js +9 -2
  16. package/dist/cli/documents/library.js +10 -0
  17. package/dist/cli/permission-keys.d.ts +6 -0
  18. package/dist/cli/permission-keys.js +15 -3
  19. package/dist/cli/service-api.d.ts +1 -1
  20. package/dist/cli/service-api.js +16 -34
  21. package/dist/documents/file-mirror-model.d.ts +18 -1
  22. package/dist/documents/index.d.ts +7 -4
  23. package/dist/documents/index.js +4 -1
  24. package/dist/documents/model.d.ts +16 -1
  25. package/dist/errors/reasons.js +4 -0
  26. package/dist/services/documents/block-diff.d.ts +13 -3
  27. package/dist/services/documents/block-diff.js +13 -7
  28. package/dist/services/documents/ingestion.d.ts +21 -2
  29. package/dist/services/documents/ingestion.js +29 -2
  30. package/dist/services/documents/plan.js +16 -7
  31. package/dist/services/documents/ports.d.ts +2 -0
  32. package/dist/services/documents/sync.d.ts +1 -0
  33. package/dist/services/documents/sync.js +9 -4
  34. package/dist/services/files/conflicts.d.ts +78 -0
  35. package/dist/services/files/conflicts.js +183 -0
  36. package/dist/services/files/guarded-write.d.ts +34 -0
  37. package/dist/services/files/guarded-write.js +42 -0
  38. package/dist/services/files/listing.d.ts +8 -0
  39. package/dist/services/files/listing.js +1 -1
  40. package/dist/services/files/local-files.d.ts +54 -0
  41. package/dist/services/files/local-files.js +143 -0
  42. package/dist/services/files/mirror-state.d.ts +14 -0
  43. package/dist/services/files/mirror-state.js +65 -0
  44. package/dist/services/files/mirror.d.ts +3 -13
  45. package/dist/services/files/mirror.js +163 -204
  46. package/dist/services/files/text-merge.d.ts +27 -0
  47. package/dist/services/files/text-merge.js +134 -0
  48. package/dist/services/files/versions.d.ts +36 -9
  49. package/dist/services/files/versions.js +40 -12
  50. package/dist/services/metadata.d.ts +1 -1
  51. package/dist/store/index.d.ts +1 -0
  52. package/dist/store/index.js +1 -0
  53. package/dist/store/sqlite/document-history.d.ts +84 -0
  54. package/dist/store/sqlite/document-history.js +158 -0
  55. package/dist/store/sqlite/manifest.js +2 -0
  56. package/dist/store/sqlite/migrations.generated.js +17 -0
  57. package/dist/store/sqlite/notes.d.ts +9 -10
  58. package/dist/store/sqlite/notes.js +33 -21
  59. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  60. package/dist/store/sqlite/schema/document-changes.js +11 -0
  61. package/dist/store/sqlite/schema.d.ts +65 -0
  62. package/dist/store/sqlite/schema.js +5 -0
  63. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,42 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.721.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A file written only at the hash it was read at.** `guardedFileWrite` writes over a provider's file through its
13
+ `FileTarget` only while the file still has the sha256 the caller read: the current content is downloaded into the
14
+ profile's version store and hashed, another hash is `conflict` (`mirror.remote-changed`) with nothing uploaded, and
15
+ the target checks it again just before the upload. What it replaced stays in the version store. The shared builder
16
+ `addFileUpdateCommand` adds `files update <path> (--text | stdin) [--expected-fingerprint <sha256>]` to a CLI's files
17
+ group, a remote write that asks the delete key when it replaces a file
18
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#write-one-file-at-the-hash-read)).
19
+ - **A file mirror merges text files both sides changed, and its conflicts can be resolved.** A `.md`, `.markdown`,
20
+ `.txt`, `.csv` or `.tsv` file up to 1 MB that changed on both sides since the last sync is merged line by line
21
+ (Markdown also by blocks, so a checklist tick and an edit of the same item merge) and written to both sides, in
22
+ every mirror; CRLF, a byte-order mark and other encodings pass through byte for byte. Lines both sides changed
23
+ differently stay a conflict, now recorded in the mirror's state: `listFileConflicts`, `showFileConflict` (the three
24
+ versions, the conflicting lines and the file with conflict markers) and `resolveFileConflict` (keep a side, both,
25
+ or a final file, refused with nothing written when either side changed since), mounted by `fileConflictsCommand`
26
+ as `mirrors conflicts list|show|resolve`. The contents of every merge, conflict and resolution are kept for good,
27
+ and `versions list` names each one's role ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways)).
28
+
29
+ ### Changed — may break callers
30
+
31
+ - **A file mirror writes a merged text file to both sides where it used to report a conflict.** A caller that counted
32
+ on every both-sides change waiting for `keep` now finds the file in the new `FileMirrorResult.merged`, and a plan
33
+ step of the new kind `merge`; `VersionDirection` gains `both` and `VersionEvent.event` gains `merged`, `conflict`
34
+ and `resolved`, so a switch over them needs the new cases. `FileVersions` gains `read(sha256)`, and `prune` takes
35
+ the contents to keep (`pinned`): an implementation of its own adds both. `versions.has` is false for anything but a
36
+ sha256.
37
+ - **An old flat `api` key is refused, not honoured: rename it to the key the refusal names.** A config that still names
38
+ `api.contacts-list` after the generated `api` group put that command under `api contacts list` no longer has the key
39
+ checked beside the new one. Every command refuses to run, `mcp serve` refuses to start, and `config set` refuses the
40
+ key, each with `configuration_error` or `validation_error` saying "its command moved, so rename it to
41
+ permissions.api.contacts.list". A moved path keeps no alias, its key included (WC-CMD-8). Until a CLI regenerates
42
+ with groups, no key moved and nothing changes.
43
+
8
44
  ## 0.720.0 — 23.11.2026
9
45
 
10
46
  ### Added
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
+ action?: undefined;
27
28
  name: string;
28
29
  installed: boolean;
29
30
  active: boolean;
30
31
  servicePath: string;
31
32
  timerPath: string;
32
- action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -11,7 +11,7 @@ import { fixVerb } from "./config-issues.js";
11
11
  import { baseContext, environmentOf } from "./context.js";
12
12
  import { grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "./effects.js";
13
13
  import { itemOf, renderAnswer } from "./envelope.js";
14
- import { knownBeside, knownPermissionKeys, unknownPermissionIssues, } from "./permission-keys.js";
14
+ import { knownBeside, knownPermissionKeys, renamedPermissionKeys, unknownPermissionIssues, } from "./permission-keys.js";
15
15
  import { profileFree } from "./profile.js";
16
16
  import { fromFile, NONE_NAMED } from "./settings.js";
17
17
  import { nextStep } from "./steps.js";
@@ -232,12 +232,18 @@ export const refuseUnknownKey = (command, setting, value, permissionKey) => {
232
232
  if (keys.length === 0)
233
233
  return;
234
234
  const known = knownPermissionKeys(command, permissionKey);
235
+ const renamed = renamedPermissionKeys(command);
235
236
  for (const key of keys) {
236
237
  if (known.has(key))
237
238
  continue;
238
239
  const beside = knownBeside(key, known);
240
+ const now = renamed.get(key);
239
241
  throw new CliError("validation_error", `permissions.${key} names no command` +
240
- (beside.length > 0 ? ` — the known ones there are ${beside.join(", ")}` : ""));
242
+ (now !== undefined
243
+ ? `: its command moved, so use permissions.${now}`
244
+ : beside.length > 0
245
+ ? ` — the known ones there are ${beside.join(", ")}`
246
+ : ""));
241
247
  }
242
248
  };
243
249
  /**
@@ -43,7 +43,9 @@ export declare const permissionIssues: (saved: readonly {
43
43
  }[], known: ReadonlySet<string>, context: {
44
44
  file: string;
45
45
  tool: string;
46
- }) => LocatedIssue[];
46
+ },
47
+ /** Old key → the key of the command it moved to, so the refusal names what to rename it to. */
48
+ renamed?: ReadonlyMap<string, string>) => LocatedIssue[];
47
49
  /** The file without the settings the issues name: what still loads, and what `config unset` would leave. */
48
50
  export declare const withoutIssues: (raw: unknown, issues: readonly LocatedIssue[]) => unknown;
49
51
  /** The path `config unset <setting>` names: a permission key keeps its dots; a number is a list item. */
@@ -237,9 +237,16 @@ export const savedPermissionKeys = (raw) => scopes(raw).flatMap(([path, scope])
237
237
  ? Object.keys(scope.permissions).map((key) => ({ key, at: [...path, "permissions", key] }))
238
238
  : []);
239
239
  /** A saved key no command checks would do nothing (BUG-137): one issue per key, wherever it is saved. */
240
- export const permissionIssues = (saved, known, context) => saved
240
+ export const permissionIssues = (saved, known, context,
241
+ /** Old key → the key of the command it moved to, so the refusal names what to rename it to. */
242
+ renamed = new Map()) => saved
241
243
  .filter(({ key }) => !known.has(key))
242
- .map(({ at }) => locate("unknown_permission", at, context, (key) => `${key} names no command`));
244
+ .map(({ key: name, at }) => locate("unknown_permission", at, context, (key) => {
245
+ const now = renamed.get(name);
246
+ return now === undefined
247
+ ? `${key} names no command`
248
+ : `${key} names no command: its command moved, so rename it to permissions.${now}`;
249
+ }));
243
250
  const pathId = (path) => path.join("\u0000");
244
251
  /**
245
252
  * The file without the parts at `paths`, through objects and lists alike, and a map from a path in what is left
@@ -0,0 +1,25 @@
1
+ import { Command } from "commander";
2
+ import { type FileConflictResolveOptions, type FileMirrorStatePort, type FileVersions, type Mirror } from "../../documents.js";
3
+ import type { AppIdentity } from "../../ports/app.js";
4
+ import { type Body } from "../envelope.js";
5
+ /** What a file-mirror CLI gives `fileConflictsCommand`: its mirrors, their state and stores, and its remote. */
6
+ export interface FileConflictCommands {
7
+ /** Who the app is: its command names the examples, its folders are never read by `--file`. */
8
+ identity: AppIdentity;
9
+ /** How the app names the remote side, `disk` for Yandex Disk: `--keep`'s other choice and a kept copy's name. */
10
+ remote: string;
11
+ output(command: Command, body: Body): void;
12
+ /** The profile's mirrors, or the one with `id`; unknown ids and a profile without mirrors are refused. */
13
+ mirrors(command: Command, id?: string): Mirror[];
14
+ /** A path as the owner typed it (relative, or absolute inside the mirror), as a path inside the mirror. */
15
+ pathOf(mirror: Mirror, input: string): string;
16
+ stateOf(command: Command, mirror: Mirror): FileMirrorStatePort;
17
+ versionsOf(command: Command, mirror: Mirror): FileVersions;
18
+ /** The remote signed in for the mirror's account, the write guard and the mirrors' sync lock. */
19
+ connect(command: Command, mirror: Mirror): Promise<Pick<FileConflictResolveOptions, "target" | "principal" | "guard" | "operationId" | "lock" | "signal">>;
20
+ }
21
+ /**
22
+ * `mirrors conflicts list|show|resolve` for a file mirror: the conflicts the last sync left, each with its three
23
+ * versions and the line merge that failed, and a resolution that writes one final content to both sides.
24
+ */
25
+ export declare const fileConflictsCommand: (helpers: FileConflictCommands) => Command;
@@ -0,0 +1,102 @@
1
+ import { resolve } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { Command, Option } from "commander";
5
+ import { listFileConflicts, resolveFileConflict, showFileConflict, } from "../../documents.js";
6
+ import { refusedPlace } from "../../sends/upload.js";
7
+ import { environmentOf } from "../context.js";
8
+ import { LOCAL_READ, ownerOnlyOption, REMOTE_WRITE } from "../effects.js";
9
+ import { itemOf, listOf, snakeKeys } from "../envelope.js";
10
+ const ID = "mirror id from mirrors list";
11
+ const PATH = "the file's path inside the mirror, like notes/plan.md";
12
+ /**
13
+ * `mirrors conflicts list|show|resolve` for a file mirror: the conflicts the last sync left, each with its three
14
+ * versions and the line merge that failed, and a resolution that writes one final content to both sides.
15
+ */
16
+ export const fileConflictsCommand = (helpers) => {
17
+ const { remote, identity } = helpers;
18
+ const app = identity.command;
19
+ const one = (command, id) => helpers.mirrors(command, id)[0];
20
+ return annotate(new Command("conflicts"), { effects: LOCAL_READ })
21
+ .summary("files changed on both sides that a sync could not merge")
22
+ .description(`files changed on both sides that a sync could not merge: list them, show the three versions and the lines ` +
23
+ `that conflict, and resolve each by keeping a side or giving the final file`)
24
+ .addCommand(annotate(new Command("list"), {
25
+ effects: LOCAL_READ,
26
+ examples: [`${app} personal mirrors conflicts list --json`],
27
+ })
28
+ .summary("list the conflicts the last sync left")
29
+ .description("list the conflicts each mirror's last sync left, with why and when it found them")
30
+ .argument("[id]", `${ID}; every mirror of the profile when omitted`)
31
+ .action(function (id) {
32
+ const items = listFileConflicts(helpers.mirrors(this, id), (mirror) => helpers.stateOf(this, mirror));
33
+ helpers.output(this, listOf("mirrors conflicts list", {
34
+ items: items.map((item) => snakeKeys(item)),
35
+ limit: Math.max(1, items.length),
36
+ has_more: false,
37
+ }));
38
+ }))
39
+ .addCommand(annotate(new Command("show"), {
40
+ effects: LOCAL_READ,
41
+ examples: [`${app} personal mirrors conflicts show 1a2b3c4d notes/plan.md --json`],
42
+ })
43
+ .summary("show a conflict's three versions and the lines that conflict")
44
+ .description("show a conflict's three versions (the last sync's, the local and the remote) and each changed stretch " +
45
+ "of the line merge; merged is the whole file with conflict markers, a start for resolve --file")
46
+ .argument("<id>", ID)
47
+ .argument("<path>", PATH)
48
+ .action(async function (id, input) {
49
+ const mirror = one(this, id);
50
+ const view = await showFileConflict({
51
+ root: mirror.path,
52
+ path: helpers.pathOf(mirror, input),
53
+ state: helpers.stateOf(this, mirror),
54
+ versions: helpers.versionsOf(this, mirror),
55
+ remote,
56
+ });
57
+ helpers.output(this, itemOf(snakeKeys({ id, ...view })));
58
+ }))
59
+ .addCommand(annotate(new Command("resolve"), {
60
+ effects: REMOTE_WRITE,
61
+ offline: false,
62
+ examples: [
63
+ `${app} personal mirrors conflicts resolve 1a2b3c4d notes/plan.md --keep ${remote}`,
64
+ `${app} personal mirrors conflicts resolve 1a2b3c4d notes/plan.md --file ~/plan-final.md`,
65
+ ],
66
+ })
67
+ .summary("settle a conflict on both sides: keep a side, both, or the final file")
68
+ .description(`settle a conflict on both sides at once: keep the local file, the ${remote}'s, or both (the ${remote}'s ` +
69
+ `beside the local one), or give the final file. Refused with nothing written when either side changed ` +
70
+ "since the conflict was found; every replaced version is kept")
71
+ .argument("<id>", ID)
72
+ .argument("<path>", PATH)
73
+ .addOption(new Option("--keep <side>", `keep the local file, the ${remote}'s, or both`).choices([
74
+ "local",
75
+ remote,
76
+ "both",
77
+ ]))
78
+ .addOption(ownerOnlyOption("--file <file>", "the final content, written to both sides"))
79
+ .action(async function (id, input, args) {
80
+ if ((args.keep === undefined) === (args.file === undefined))
81
+ throw new CliError("validation_error", "give either --keep or --file", { param: "--keep" });
82
+ const file = args.file === undefined ? undefined : resolve(args.file);
83
+ if (file && refusedPlace(file, identity, environmentOf(this).env ?? process.env))
84
+ throw new CliError("validation_error", `--file may not read ${file}: it holds sign-ins or state`, {
85
+ param: "--file",
86
+ });
87
+ const mirror = one(this, id);
88
+ const keep = (args.keep === remote ? "remote" : args.keep);
89
+ const resolved = await resolveFileConflict({
90
+ ...(await helpers.connect(this, mirror)),
91
+ root: mirror.path,
92
+ folder: mirror.folder,
93
+ path: helpers.pathOf(mirror, input),
94
+ state: helpers.stateOf(this, mirror),
95
+ versions: helpers.versionsOf(this, mirror),
96
+ remote,
97
+ choice: keep ? { keep } : { file: file },
98
+ });
99
+ const resolution = resolved.resolution === "remote" ? remote : resolved.resolution;
100
+ helpers.output(this, itemOf(snakeKeys({ id, ...resolved, resolution })));
101
+ }));
102
+ };
@@ -0,0 +1,29 @@
1
+ import type { Command } from "commander";
2
+ import { type CellValue, type XlsxEdit } from "../../office/index.js";
3
+ import { type FileUpdateCommands, type FileUpdatePort } from "./file-update.js";
4
+ export interface FileEditCommands extends FileUpdateCommands {
5
+ /**
6
+ * The CLI's read path, signed in: the target and the profile's version store, for a command that changes nothing.
7
+ * `command` is the one running.
8
+ */
9
+ read(act: (port: FileUpdatePort) => Promise<object>, command: Command): Promise<object>;
10
+ /**
11
+ * `restore <path>` with no version: the CLI's own restore from the provider's trash, which answers what it did. A
12
+ * CLI without one leaves it out, and the version is then required.
13
+ */
14
+ restoreFromTrash?(input: string, command: Command): Promise<object>;
15
+ }
16
+ /** `Sheet1!A1:C10`, `'My sheet'!B2`, `Sheet1` or `A1:C10`, as the sheet and the cells. */
17
+ export declare const sheetRangeOf: (input: string | undefined) => {
18
+ sheet?: string;
19
+ range?: string;
20
+ };
21
+ /** The cells `values` fills from the range's top-left cell; a range of more than one cell must have their shape. */
22
+ export declare const cellEditsOf: (sheet: string, range: string, values: CellValue[][]) => XlsxEdit[];
23
+ /**
24
+ * Mounts `<files> update`, `sheets show|update`, `documents show|update`, `history` and `restore` under the CLI's own
25
+ * files group: Office files edited in place and earlier versions put back, every write at the sha256 it was read at
26
+ * and with the replaced content kept (`guardedFileWrite`). The CLI keeps no `restore` of its own; a trash restore
27
+ * goes in as `restoreFromTrash`.
28
+ */
29
+ export declare const addFileEditCommands: (files: Command, helpers: FileEditCommands) => void;
@@ -0,0 +1,352 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { CliError, isCliError } from "@wirecat/cli-base";
6
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
7
+ import * as v from "valibot";
8
+ import { editDocxParagraphs, editXlsxCells, readDocxParagraphs, readXlsxCells, } from "../../office/index.js";
9
+ import { guardedFileWrite, remoteChanged } from "../../services/files/guarded-write.js";
10
+ import { honoursDryRun } from "../dry-run-guard.js";
11
+ import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
12
+ import { itemOf } from "../envelope.js";
13
+ import { addFileUpdateCommand, replacedOf, sha256Of, } from "./file-update.js";
14
+ import { examples, wordsOf } from "./words.js";
15
+ /** The whole file is held in memory to edit it. */
16
+ const MAX_OFFICE_BYTES = 64 * 1024 * 1024;
17
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
18
+ const inTemp = async (act) => {
19
+ const folder = await mkdtemp(join(tmpdir(), "wirecat-office-"));
20
+ try {
21
+ return await act(folder);
22
+ }
23
+ finally {
24
+ await rm(folder, { recursive: true, force: true });
25
+ }
26
+ };
27
+ const downloaded = ({ target, signal }, path) => inTemp(async (folder) => {
28
+ const into = join(folder, "file");
29
+ await target.download(path, into, signal);
30
+ const { size } = await stat(into);
31
+ if (size > MAX_OFFICE_BYTES)
32
+ throw new CliError("validation_error", `${path} is ${size} bytes; an Office file is read up to 64 MiB`, {
33
+ reason: "file.too-large",
34
+ });
35
+ const bytes = new Uint8Array(await readFile(into));
36
+ return { bytes, sha256: sha256(bytes) };
37
+ });
38
+ const jsonOf = (input, flag, schema, shape) => {
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(input);
42
+ }
43
+ catch {
44
+ throw new CliError("validation_error", `${flag} is not JSON; give ${shape}`, { param: flag });
45
+ }
46
+ const checked = v.safeParse(schema, parsed);
47
+ if (!checked.success)
48
+ throw new CliError("validation_error", `${flag} takes ${shape}`, { param: flag });
49
+ return checked.output;
50
+ };
51
+ const ADDRESS = /^([A-Z]{1,3})([1-9]\d{0,6})$/u;
52
+ const CELLS = /^[A-Z]{1,3}[1-9]\d*(:[A-Z]{1,3}[1-9]\d*)?$/iu;
53
+ const columnName = (column) => {
54
+ let name = "";
55
+ for (let left = column; left > 0; left = Math.floor((left - 1) / 26))
56
+ name = String.fromCharCode(65 + ((left - 1) % 26)) + name;
57
+ return name;
58
+ };
59
+ const cornerOf = (address) => {
60
+ const match = ADDRESS.exec(address.toUpperCase());
61
+ if (!match)
62
+ throw new CliError("validation_error", `${address} is not a cell like B7`, { reason: "office.invalid_cell" });
63
+ const letters = match[1];
64
+ return {
65
+ column: [...letters].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0),
66
+ row: Number(match[2]),
67
+ };
68
+ };
69
+ /** `Sheet1!A1:C10`, `'My sheet'!B2`, `Sheet1` or `A1:C10`, as the sheet and the cells. */
70
+ export const sheetRangeOf = (input) => {
71
+ if (!input)
72
+ return {};
73
+ const bang = input.lastIndexOf("!");
74
+ const quoted = (name) => (/^'.*'$/u.test(name) ? name.slice(1, -1).replaceAll("''", "'") : name);
75
+ if (bang >= 0) {
76
+ const range = input.slice(bang + 1);
77
+ return { sheet: quoted(input.slice(0, bang)), ...(range ? { range } : {}) };
78
+ }
79
+ return CELLS.test(input) ? { range: input } : { sheet: quoted(input) };
80
+ };
81
+ const VALUES = v.pipe(v.array(v.pipe(v.array(v.union([v.string(), v.number(), v.boolean(), v.null()])), v.minLength(1))), v.minLength(1));
82
+ const VALUES_SHAPE = 'rows of cell values as JSON, such as [["Total", 42], [null, true]]';
83
+ /** The cells `values` fills from the range's top-left cell; a range of more than one cell must have their shape. */
84
+ export const cellEditsOf = (sheet, range, values) => {
85
+ const [from, to] = range.split(":");
86
+ const start = cornerOf(from);
87
+ if (to !== undefined) {
88
+ const end = cornerOf(to);
89
+ const rows = end.row - start.row + 1;
90
+ const columns = end.column - start.column + 1;
91
+ if (rows < 1 || columns < 1 || values.length !== rows || values.some((row) => row.length !== columns))
92
+ throw new CliError("validation_error", `${range} is ${rows} rows by ${columns} columns; --values must have that shape, or name only its first cell`, { param: "--values" });
93
+ }
94
+ return values.flatMap((row, down) => row.map((value, across) => ({ sheet, cell: `${columnName(start.column + across)}${start.row + down}`, value })));
95
+ };
96
+ const PAYLOAD = v.pipe(v.array(v.union([
97
+ v.strictObject({ index: v.pipe(v.number(), v.integer()), text: v.string() }),
98
+ v.strictObject({
99
+ insert_after: v.pipe(v.number(), v.integer()),
100
+ text: v.string(),
101
+ style_from: v.optional(v.pipe(v.number(), v.integer())),
102
+ }),
103
+ v.strictObject({ delete: v.pipe(v.number(), v.integer()) }),
104
+ ])), v.minLength(1));
105
+ const PAYLOAD_SHAPE = 'paragraph edits as JSON: [{"index": 3, "text": "…"}, {"insert_after": 5, "text": "…"}, {"delete": 7}]';
106
+ const docxEditsOf = (payload) => payload.map((edit) => {
107
+ if ("insert_after" in edit)
108
+ return {
109
+ insertAfter: edit.insert_after,
110
+ text: edit.text,
111
+ ...(edit.style_from === undefined ? {} : { styleFrom: edit.style_from }),
112
+ };
113
+ return edit;
114
+ });
115
+ const addFileEditCommandsDefinition = (files, helpers) => {
116
+ const { prefix, place } = wordsOf(helpers.words);
117
+ const group = files.name();
118
+ const deleteKey = helpers.deleteKey ?? "files.delete";
119
+ const show = (kind, input) => `${prefix} ${group} ${kind} show ${input}`;
120
+ /** Downloads the file, edits it only at the sha256 it was read at, and writes it back as `files update` does. */
121
+ const editInPlace = async (command, kind, input, fingerprint, edit) => {
122
+ const reread = show(kind, input);
123
+ const expected = sha256Of(fingerprint);
124
+ if (expected === undefined)
125
+ throw new CliError("validation_error", `read the file first (${reread}) and pass its sha256 as --expected-fingerprint`, {
126
+ param: "--expected-fingerprint",
127
+ });
128
+ const path = helpers.path(input);
129
+ const answer = await helpers.write([deleteKey], async (port) => {
130
+ const read = await downloaded(port, path);
131
+ if (read.sha256 !== expected)
132
+ throw remoteChanged(path, "changed since it was read", reread);
133
+ const edited = await edit(read.bytes);
134
+ return inTemp(async (folder) => {
135
+ const from = join(folder, "edited");
136
+ await writeFile(from, edited.bytes, { mode: 0o600 });
137
+ const { target, versions, signal } = port;
138
+ const done = await guardedFileWrite({
139
+ target,
140
+ versions,
141
+ path,
142
+ from,
143
+ expected,
144
+ reread,
145
+ ...(signal ? { signal } : {}),
146
+ });
147
+ return { path, sha256: done.file.sha256 ?? null, replaced: replacedOf(done, versions), ...edited.answer };
148
+ });
149
+ }, command);
150
+ helpers.output(itemOf(answer), command);
151
+ };
152
+ const readOffice = async (command, input, answer) => {
153
+ const path = helpers.path(input);
154
+ const item = await helpers.read(async (port) => {
155
+ const read = await downloaded(port, path);
156
+ return { path, sha256: read.sha256, ...(await answer(read.bytes)) };
157
+ }, command);
158
+ helpers.output(itemOf(item), command);
159
+ };
160
+ const sheets = annotate(files.command("sheets"), { effects: REMOTE_READ }).description(`the cells of an Excel workbook (.xlsx) on ${place}, read and changed in place`);
161
+ examples(annotate(sheets.command("show"), { effects: REMOTE_READ, offline: false })
162
+ .summary("show a workbook's cells and the sha256 to edit them at")
163
+ .description("show a workbook's stored cells, each with its value, type, formula and format, and the file's sha256 to pass " +
164
+ "as --expected-fingerprint to sheets update. Formulas show the value Excel saved last")
165
+ .argument("<path>", `the .xlsx file on ${place}`)
166
+ .argument("[range]", "the cells to show: Sheet1!A1:C10, a sheet's name, or A1:C10 on every sheet; all without it"), [`${prefix} ${group} sheets show /budget.xlsx "Sheet1!A1:C10"`, `${prefix} ${group} sheets show /budget.xlsx`]).action(async function (input, range) {
167
+ const wanted = sheetRangeOf(range);
168
+ await readOffice(this, input, async (bytes) => ({
169
+ sheets: (await readXlsxCells(bytes, wanted)).map((sheet) => ({
170
+ name: sheet.name,
171
+ cells: sheet.cells.map((cell) => ({
172
+ address: cell.address,
173
+ row: cell.row,
174
+ column: cell.column,
175
+ value: cell.value,
176
+ type: cell.type,
177
+ ...(cell.formula === undefined ? {} : { formula: cell.formula }),
178
+ style: cell.style,
179
+ })),
180
+ })),
181
+ }));
182
+ });
183
+ examples(annotate(sheets.command("update"), { effects: REMOTE_WRITE, offline: false })
184
+ .summary("write values into a workbook's cells, at the sha256 it was read at")
185
+ .description("write values into a workbook's cells in place: the rest of the file, its formatting and its other sheets " +
186
+ `stay as they are. It needs --expected-fingerprint from sheets show and asks as ${deleteKey} does; what it ` +
187
+ "replaced is kept on this computer (see history). A text is written as text, even one that starts with =. " +
188
+ "A formula cell is refused unless --replace")
189
+ .argument("<path>", `the .xlsx file on ${place}`)
190
+ .argument("<range>", "where the values go: Sheet1!B2:C3, or its first cell Sheet1!B2; the sheet may be left out when there is one")
191
+ .option("--values <json>", "the cell values as JSON rows; null empties a cell")
192
+ .option("--expected-fingerprint <hash>", "the sha256 sheets show gave for the file")
193
+ .option("--replace", "replace a formula with the value instead of refusing it"), [
194
+ `${prefix} ${group} sheets update /budget.xlsx "Sheet1!B2:C2" --values '[[120, "paid"]]' --expected-fingerprint 9f86d081…`,
195
+ ]).action(async function (input, range, args) {
196
+ if (args.values === undefined)
197
+ throw new CliError("validation_error", `give the cells' values with --values: ${VALUES_SHAPE}`, {
198
+ param: "--values",
199
+ });
200
+ const values = jsonOf(args.values, "--values", VALUES, VALUES_SHAPE);
201
+ const wanted = sheetRangeOf(range);
202
+ if (wanted.range === undefined)
203
+ throw new CliError("validation_error", `${range} names no cell; give one like Sheet1!B2`, {
204
+ reason: "office.invalid_cell",
205
+ });
206
+ cellEditsOf("", wanted.range, values);
207
+ await editInPlace(this, "sheets", input, args.expectedFingerprint, async (bytes) => {
208
+ let sheet = wanted.sheet;
209
+ if (sheet === undefined) {
210
+ const names = (await readXlsxCells(bytes, { range: "A1" })).map((one) => one.name);
211
+ if (names.length !== 1)
212
+ throw new CliError("validation_error", `the workbook has ${names.length} sheets (${names.map((name) => `"${name}"`).join(", ")}); name one, like ${names[0] ?? "Sheet1"}!${wanted.range}`, { reason: "office.no_sheet" });
213
+ sheet = names[0];
214
+ }
215
+ try {
216
+ const done = await editXlsxCells(bytes, cellEditsOf(sheet, wanted.range, values), {
217
+ overwriteFormulas: args.replace === true,
218
+ });
219
+ return {
220
+ bytes: done.bytes,
221
+ answer: {
222
+ changed: done.changed,
223
+ calc_chain_dropped: done.calcChainDropped,
224
+ warnings: done.calcChainDropped
225
+ ? ["a formula was replaced, so Excel rebuilds the workbook's calculation order when it opens it"]
226
+ : [],
227
+ },
228
+ };
229
+ }
230
+ catch (error) {
231
+ if (isCliError(error) && error.details?.reason === "office.formula_cell")
232
+ throw new CliError("validation_error", error.message.replace("pass overwriteFormulas", "pass --replace"), error.details);
233
+ throw error;
234
+ }
235
+ });
236
+ });
237
+ const documents = annotate(files.command("documents"), { effects: REMOTE_READ }).description(`the paragraphs of a Word document (.docx) on ${place}, read and changed in place`);
238
+ examples(annotate(documents.command("show"), { effects: REMOTE_READ, offline: false })
239
+ .summary("show a document's paragraphs and the sha256 to edit them at")
240
+ .description("show a Word document's paragraphs by index, with their style, whether each can be edited and why not, and " +
241
+ "the file's sha256 to pass as --expected-fingerprint to documents update")
242
+ .argument("<path>", `the .docx file on ${place}`), [`${prefix} ${group} documents show /report.docx`]).action(async function (input) {
243
+ await readOffice(this, input, async (bytes) => ({
244
+ paragraphs: (await readDocxParagraphs(bytes)).map((paragraph) => ({
245
+ index: paragraph.index,
246
+ text: paragraph.text,
247
+ ...(paragraph.styleId === undefined ? {} : { style_id: paragraph.styleId }),
248
+ ...(paragraph.style === undefined ? {} : { style: paragraph.style }),
249
+ location: paragraph.location,
250
+ editable: paragraph.editable,
251
+ ...(paragraph.reason === undefined ? {} : { reason: paragraph.reason }),
252
+ mixed_formatting: paragraph.mixedFormatting,
253
+ })),
254
+ }));
255
+ });
256
+ examples(annotate(documents.command("update"), { effects: REMOTE_WRITE, offline: false })
257
+ .summary("replace, insert or delete paragraphs, at the sha256 it was read at")
258
+ .description("replace, insert or delete a Word document's paragraphs in place; the rest of the file stays as it is. " +
259
+ "Indexes are the ones documents show gave. It needs --expected-fingerprint from documents show and asks as " +
260
+ `${deleteKey} does; what it replaced is kept on this computer (see history). A paragraph that is not ` +
261
+ "editable is refused with its reason, and a replaced one with mixed formatting takes its first run's")
262
+ .argument("<path>", `the .docx file on ${place}`)
263
+ .option("--payload <json>", "the edits as JSON: {index, text}, {insert_after, text, style_from?} or {delete}")
264
+ .option("--expected-fingerprint <hash>", "the sha256 documents show gave for the file"), [
265
+ `${prefix} ${group} documents update /report.docx --payload '[{"index": 2, "text": "Revenue grew 12%."}]' --expected-fingerprint 9f86d081…`,
266
+ ]).action(async function (input, args) {
267
+ if (args.payload === undefined)
268
+ throw new CliError("validation_error", `give the edits with --payload: ${PAYLOAD_SHAPE}`, { param: "--payload" });
269
+ const edits = docxEditsOf(jsonOf(args.payload, "--payload", PAYLOAD, PAYLOAD_SHAPE));
270
+ await editInPlace(this, "documents", input, args.expectedFingerprint, async (bytes) => {
271
+ const done = await editDocxParagraphs(bytes, edits);
272
+ return {
273
+ bytes: done.bytes,
274
+ answer: {
275
+ paragraphs: { replaced: done.replaced, inserted: done.inserted, deleted: done.deleted },
276
+ warnings: done.collapsed.map((index) => `paragraph ${index} had mixed formatting; its new text has its first run's formatting`),
277
+ },
278
+ };
279
+ });
280
+ });
281
+ examples(annotate(files.command("history"), { effects: REMOTE_READ, offline: false })
282
+ .summary("list the earlier versions of a file kept on this computer")
283
+ .description("list what the writes and syncs of this profile replaced in a file, newest last. Each entry's version is the " +
284
+ `sha256 of the content it replaced, kept on this computer while available is true; ${group} restore puts it back`)
285
+ .argument("<path>", `the file on ${place}`), [`${prefix} ${group} history /budget.xlsx`]).action(async function (input) {
286
+ const path = helpers.path(input);
287
+ const item = await helpers.read(async ({ versions }) => ({
288
+ path,
289
+ versions: versions.list(path).map((event) => ({
290
+ at: event.at,
291
+ event: event.event,
292
+ direction: event.direction,
293
+ version: event.old ?? null,
294
+ available: event.available,
295
+ ...(event.new === undefined ? {} : { new: event.new }),
296
+ ...(event.size === undefined ? {} : { size: event.size }),
297
+ ...(event.to === undefined ? {} : { to: event.to }),
298
+ ...(event.oldIn === undefined ? {} : { old_in: event.oldIn }),
299
+ })),
300
+ }), this);
301
+ helpers.output(itemOf(item), this);
302
+ });
303
+ const trash = helpers.restoreFromTrash;
304
+ examples(annotate(files.command("restore"), { effects: REMOTE_WRITE, offline: false })
305
+ .summary(trash
306
+ ? "bring a file back from the trash, or put back a version kept here"
307
+ : "put back a version of a file kept here")
308
+ .description(`${trash ? `with no version, bring a file or folder back from ${place}'s trash. With one, put` : "put"} back ` +
309
+ `a version history lists: it is written as ${group} update writes, so a file there needs ` +
310
+ `--expected-fingerprint, asks as ${deleteKey} does, and is kept first`)
311
+ .argument("<path>", trash ? `the file on ${place}, or its path in the trash` : `the file on ${place}`)
312
+ .argument(trash ? "[version]" : "<version>", "the version's sha256, from history")
313
+ .option("--expected-fingerprint <hash>", "the sha256 the file has now; required when it exists"), [`${prefix} ${group} restore /budget.xlsx 2c26b46b… --expected-fingerprint 9f86d081…`]).action(async function (input, versionInput, args) {
314
+ if (versionInput === undefined) {
315
+ if (!trash)
316
+ throw new CliError("validation_error", `give the version from ${group} history`, { param: "version" });
317
+ helpers.output(itemOf(await trash(input, this)), this);
318
+ return;
319
+ }
320
+ const version = sha256Of(versionInput, "the version");
321
+ const expected = sha256Of(args.expectedFingerprint);
322
+ const path = helpers.path(input);
323
+ const reread = helpers.reread(input);
324
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => inTemp(async (folder) => {
325
+ const from = join(folder, "version");
326
+ if (!(await versions.write(version, from)))
327
+ throw new CliError("not_found", `version ${version} of ${path} is no longer kept here; see ${group} history`, {
328
+ reason: "item.not-found",
329
+ });
330
+ const done = await guardedFileWrite({
331
+ target,
332
+ versions,
333
+ path,
334
+ from,
335
+ reread,
336
+ direction: "restored",
337
+ ...(expected ? { expected } : {}),
338
+ ...(signal ? { signal } : {}),
339
+ });
340
+ return { path, sha256: done.file.sha256 ?? null, restored: version, replaced: replacedOf(done, versions) };
341
+ }), this);
342
+ helpers.output(itemOf(answer), this);
343
+ });
344
+ addFileUpdateCommand(files, helpers);
345
+ };
346
+ /**
347
+ * Mounts `<files> update`, `sheets show|update`, `documents show|update`, `history` and `restore` under the CLI's own
348
+ * files group: Office files edited in place and earlier versions put back, every write at the sha256 it was read at
349
+ * and with the replaced content kept (`guardedFileWrite`). The CLI keeps no `restore` of its own; a trash restore
350
+ * goes in as `restoreFromTrash`.
351
+ */
352
+ export const addFileEditCommands = honoursDryRun(sharedCommand(addFileEditCommandsDefinition));