@wirecat/files-cli 0.0.0-stage → 0.1.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 (85) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +204 -0
  3. package/README.md +68 -2
  4. package/contracts/wirecat.json +751 -0
  5. package/dist/answer.js +60 -0
  6. package/dist/app.js +6 -0
  7. package/dist/author.js +87 -0
  8. package/dist/bin/files.js +40 -0
  9. package/dist/bundle/chunk-GNDPV4HK.js +263 -0
  10. package/dist/bundle/files.js +21 -0
  11. package/dist/bundle/program-EN7Z757N.js +12291 -0
  12. package/dist/config.js +65 -0
  13. package/dist/entities.js +103 -0
  14. package/dist/failure.js +21 -0
  15. package/dist/identity.js +27 -0
  16. package/dist/import/audio.js +96 -0
  17. package/dist/import/command.js +156 -0
  18. package/dist/import/external-id.js +44 -0
  19. package/dist/import/files.js +206 -0
  20. package/dist/import/readers.js +80 -0
  21. package/dist/index.js +3 -0
  22. package/dist/migrate.js +192 -0
  23. package/dist/notes/about.js +55 -0
  24. package/dist/notes/bound.js +39 -0
  25. package/dist/notes/command.js +241 -0
  26. package/dist/notes/dates.js +15 -0
  27. package/dist/notes/dialects/common.js +79 -0
  28. package/dist/notes/dialects/index.js +6 -0
  29. package/dist/notes/dialects/markdown.js +51 -0
  30. package/dist/notes/dialects/obsidian.js +33 -0
  31. package/dist/notes/dialects/types.js +2 -0
  32. package/dist/notes/embed.js +97 -0
  33. package/dist/notes/export.js +76 -0
  34. package/dist/notes/files.js +81 -0
  35. package/dist/notes/folders-command.js +172 -0
  36. package/dist/notes/folders.js +88 -0
  37. package/dist/notes/import.js +234 -0
  38. package/dist/notes/internal.js +51 -0
  39. package/dist/notes/links.js +44 -0
  40. package/dist/notes/list.js +23 -0
  41. package/dist/notes/renames.js +24 -0
  42. package/dist/notes/search.js +16 -0
  43. package/dist/notes/state.js +33 -0
  44. package/dist/options.js +9 -0
  45. package/dist/output.js +4 -0
  46. package/dist/paths.js +5 -0
  47. package/dist/people/identity.js +19 -0
  48. package/dist/people/notes-map.js +58 -0
  49. package/dist/people/owner.js +14 -0
  50. package/dist/people/subject.js +19 -0
  51. package/dist/program.js +98 -0
  52. package/dist/progress.js +19 -0
  53. package/dist/reasons.js +187 -0
  54. package/dist/records/input.js +114 -0
  55. package/dist/records/receipt.js +25 -0
  56. package/dist/records/source.js +12 -0
  57. package/dist/refs.js +28 -0
  58. package/dist/run/lock.js +21 -0
  59. package/dist/save-help.js +3 -0
  60. package/dist/search.js +63 -0
  61. package/dist/sources/command.js +295 -0
  62. package/dist/sources/copy.js +32 -0
  63. package/dist/sources/mentions.js +78 -0
  64. package/dist/sources/read.js +261 -0
  65. package/dist/sources/readers/ai-model.js +74 -0
  66. package/dist/sources/readers/api.js +48 -0
  67. package/dist/sources/readers/claude-code.js +74 -0
  68. package/dist/sources/readers/codex.js +72 -0
  69. package/dist/sources/readers/index.js +10 -0
  70. package/dist/sources/readers/keys.js +31 -0
  71. package/dist/sources/readers/ollama.js +84 -0
  72. package/dist/sources/readers/process.js +49 -0
  73. package/dist/sources/readers/types.js +2 -0
  74. package/dist/sources/suggest-command.js +253 -0
  75. package/dist/sources/suggest.js +142 -0
  76. package/dist/sources/transcript.js +52 -0
  77. package/dist/store/group.js +8 -0
  78. package/dist/store/scope.js +25 -0
  79. package/dist/store/source-list.js +22 -0
  80. package/dist/sync.js +156 -0
  81. package/dist/terminal.js +16 -0
  82. package/dist/version.js +2 -0
  83. package/dist/wcat.js +4 -0
  84. package/package.json +89 -4
  85. package/skills/files-cli/SKILL.md +41 -0
@@ -0,0 +1,81 @@
1
+ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
2
+ import { join, relative, sep } from "node:path";
3
+ export const NOTE_EXTENSIONS = [
4
+ ".md",
5
+ ".markdown",
6
+ ".txt",
7
+ ".csv",
8
+ ".tsv",
9
+ ".pdf",
10
+ ".docx",
11
+ ".xlsx",
12
+ ".odt",
13
+ ".ods",
14
+ ".pptx",
15
+ ".epub",
16
+ ".doc",
17
+ ".xls",
18
+ ".html",
19
+ ".htm",
20
+ ];
21
+ const MEMO_ID = /^---\r?\n(?:[^\n]*\n)*?memo-id:[ \t]*["']?([^"'\s]+)/;
22
+ const HEAD = 1024;
23
+ /** The `memo-id` of a file files exported, read from the front matter at its start; `null` for any other file. */
24
+ export const readMemoId = (path) => {
25
+ const buffer = Buffer.alloc(HEAD);
26
+ const descriptor = openSync(path, "r");
27
+ try {
28
+ const head = buffer.subarray(0, readSync(descriptor, buffer, 0, HEAD, 0)).toString("utf8");
29
+ const end = head.indexOf("\n---", 3);
30
+ return MEMO_ID.exec(end < 0 ? head : head.slice(0, end + 1))?.[1] ?? null;
31
+ }
32
+ finally {
33
+ closeSync(descriptor);
34
+ }
35
+ };
36
+ const TEXT_NOTE = /\.(md|markdown)$/i;
37
+ export const isExported = (path) => TEXT_NOTE.test(path) && readMemoId(path) !== null;
38
+ const pattern = (rule) => {
39
+ const glob = rule.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
40
+ const body = glob
41
+ .split(/(\*\*\/?|\*|\?)/)
42
+ .map((part) => part === "**/" || part === "**"
43
+ ? ".*"
44
+ : part === "*"
45
+ ? "[^/]*"
46
+ : part === "?"
47
+ ? "[^/]"
48
+ : part.replace(/[.+^${}()|[\]\\]/g, "\\$&"))
49
+ .join("");
50
+ // A rule names a path inside the folder, and everything under it when it is a folder.
51
+ return new RegExp(`^${body}(/.*)?$`, "i");
52
+ };
53
+ /** Whether a path inside the folder, `/`-separated, matches one of the ignore rules. */
54
+ export const matcher = (rules) => {
55
+ const patterns = rules.map(pattern);
56
+ return (inside) => patterns.some((rule) => rule.test(inside));
57
+ };
58
+ /**
59
+ * Note files under `folder`, as absolute paths. Hidden entries (`.obsidian`, `.trash`) are skipped, and
60
+ * so is whatever an `ignore` rule names — a path inside the folder (`Psychology/Personal Notes.md`,
61
+ * `Archive`) or a glob (`**\/Private*`, `*.txt`). A note files exported is skipped too: it is already in
62
+ * the store, and importing it would make it a second note.
63
+ */
64
+ export const noteFiles = (folder, ignore = [], extensions = NOTE_EXTENSIONS, { skipExported = true } = {}) => {
65
+ const matches = matcher(ignore);
66
+ const ignored = (path) => matches(relative(folder, path).split(sep).join("/"));
67
+ const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
68
+ if (entry.name.startsWith("."))
69
+ return [];
70
+ const path = join(dir, entry.name);
71
+ if (ignored(path))
72
+ return [];
73
+ if (entry.isDirectory())
74
+ return walk(path);
75
+ if (!entry.isFile() || !extensions.some((ext) => entry.name.toLowerCase().endsWith(ext)))
76
+ return [];
77
+ return skipExported && isExported(path) ? [] : [path];
78
+ });
79
+ return walk(folder);
80
+ };
81
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1,172 @@
1
+ import { statSync } from "node:fs";
2
+ import { basename, resolve } from "node:path";
3
+ import { CliError } from "@wirecat/cli-base";
4
+ import { annotate } from "@wirecat/cli-base/commands";
5
+ import { grantsAuthority, LOCAL_READ, LOCAL_WRITE, notLocalPaths, queryTerms, withQuery, } from "@wirecat/cli-core";
6
+ import { InvalidArgumentError } from "commander";
7
+ import { answers, itemAnswer, wholeList, withStore } from "../answer.js";
8
+ import { loadConfig, updateConfig } from "../config.js";
9
+ import { withImportLock } from "../run/lock.js";
10
+ import { DIALECTS } from "./dialects/index.js";
11
+ import { attachFolder, bindFolder, detectFormat, noteFolders, overlapping, unbindFolder, } from "./folders.js";
12
+ import { folderNotes } from "./import.js";
13
+ import { dropFolderState, formatChanged } from "./state.js";
14
+ const formatOf = (value) => {
15
+ if (!DIALECTS.includes(value))
16
+ throw new InvalidArgumentError(`choose ${DIALECTS.join(", ")}`);
17
+ return value;
18
+ };
19
+ const directory = (path) => {
20
+ const at = resolve(path);
21
+ let isDirectory = false;
22
+ try {
23
+ isDirectory = statSync(at).isDirectory();
24
+ }
25
+ catch { }
26
+ if (!isDirectory)
27
+ throw new CliError("not_found", `${at} is not a folder`);
28
+ return at;
29
+ };
30
+ /** files' own entity: a notes folder, here or known to the store from another computer. */
31
+ const FOLDERS_QUERY = { entity: "notes_folder", backend: "native", fields: [] };
32
+ // drive-cli owns these; bound to a disk folder, an import would delete the Drive documents missing there.
33
+ // Store version 31 moved them from a folder named `google-drive:<principal>` to a documents account of that name.
34
+ const keptByDrive = (name) => name.startsWith("google-drive:");
35
+ const storedFolders = async (store) => [
36
+ ...(await store.notes.folders()),
37
+ ...(await store.notes.documentsAccounts()),
38
+ ];
39
+ const line = (folder) => `${folder.id ?? "(no id — files folders add <path>)"} ${folder.format} ${folder.path}`;
40
+ export const foldersCommand = (program, streams, env) => {
41
+ const { print } = answers(program, streams, env);
42
+ const folders = program
43
+ .command("folders")
44
+ .description("folders of notes: the id links and the store use, and the path on this computer");
45
+ grantsAuthority(annotate(folders.command("add"), { effects: LOCAL_WRITE }))
46
+ .description("give a folder of notes an id, or show the one it has")
47
+ .argument("<path>", "the folder on this computer")
48
+ .option("--format <format>", `how its notes are written: ${DIALECTS.join(", ")} (default for a new folder: obsidian in an Obsidian vault, ` +
49
+ "one with a .obsidian folder in it or above it, markdown otherwise)", formatOf)
50
+ .action(async (path, options) => {
51
+ const at = directory(path);
52
+ const answer = await withStore(env, async (store) => {
53
+ const known = new Set((await store.notes.folders()).map(({ id }) => id));
54
+ const current = noteFolders(loadConfig(env).notes).find((folder) => folder.path === at);
55
+ if (current?.id && known.has(current.id)) {
56
+ const folder = { ...current, id: current.id, format: options.format ?? current.format };
57
+ if (folder.format !== current.format) {
58
+ updateConfig((config) => bindFolder(config, folder), env);
59
+ formatChanged(env, folder.id, current.format);
60
+ }
61
+ return { ...folder, format_from: options.format ? "option" : "saved", created: false };
62
+ }
63
+ const clash = overlapping(noteFolders(loadConfig(env).notes).filter((folder) => folder.path !== at), at)[0];
64
+ if (clash)
65
+ throw new CliError("validation_error", `${at} is inside or around ${clash.path}, which files already reads — one file would be two notes; ` +
66
+ `remove one of them first (files folders remove "${clash.path}")`, { reason: "folder.overlap", path: at, other: clash.path });
67
+ // A bare path written before folder ids never chose a format; only an entry with an id saved one.
68
+ const saved = current?.id === null ? undefined : current?.format;
69
+ const format = options.format ?? saved ?? detectFormat(at);
70
+ const made = await store.notes.addFolder({ name: basename(at) || at, format });
71
+ const folder = { id: made.id, path: at, format };
72
+ updateConfig((config) => bindFolder(config, folder), env);
73
+ const from = options.format ? "option" : saved ? "saved" : "detected";
74
+ return { ...folder, format_from: from, created: true };
75
+ });
76
+ print(options.json, itemAnswer(answer), answer.id);
77
+ });
78
+ grantsAuthority(annotate(folders.command("update"), { effects: LOCAL_WRITE }))
79
+ .description("bind a folder id from another computer to the folder's path on this one")
80
+ .argument("<id>", "the folder's id, as files folders add printed it")
81
+ .argument("<path>", "the same folder on this computer")
82
+ .option("--format <format>", `how its notes are written: ${DIALECTS.join(", ")}`, formatOf)
83
+ .action(async (id, path, options) => {
84
+ const at = directory(path);
85
+ const folder = await withStore(env, async (store) => {
86
+ const stored = (await storedFolders(store)).find((candidate) => candidate.id === id);
87
+ if (!stored)
88
+ throw new CliError("not_found", `the store has no folder ${id} — files folders list shows those it has`, {
89
+ reason: "folder.not-found",
90
+ });
91
+ if (keptByDrive(stored.name))
92
+ throw new CliError("validation_error", `folder ${id} is Google Drive's (${stored.name}) — drive keeps it, and wcat search already reads it`);
93
+ const previous = noteFolders(loadConfig(env).notes).find((candidate) => candidate.id === id)?.format ?? stored.format;
94
+ let bound;
95
+ updateConfig((config) => {
96
+ const result = attachFolder(config, id, at, options.format ?? stored.format);
97
+ bound = result.folder;
98
+ return result.config;
99
+ }, env);
100
+ if (bound && bound.format !== previous)
101
+ formatChanged(env, id, previous);
102
+ return bound;
103
+ });
104
+ print(options.json, itemAnswer(folder), line(folder));
105
+ });
106
+ grantsAuthority(notLocalPaths(annotate(folders.command("remove"), {
107
+ effects: LOCAL_WRITE,
108
+ examples: ["files folders remove ~/notes", "files folders remove 3 --allow-delete --yes --json"],
109
+ }), "folder"))
110
+ .description("stop reading a notes folder here; its notes stay unless --allow-delete")
111
+ .argument("<folder>", "the folder's id or its path, as files folders list prints them")
112
+ .option("--allow-delete", "also delete the folder's notes from the store, their text included")
113
+ .option("--yes", "confirm --allow-delete")
114
+ .action(async (target, options) => {
115
+ const here = noteFolders(loadConfig(env).notes);
116
+ const bound = here.find(({ id }) => id !== null && id === target) ?? here.find(({ path }) => path === resolve(target));
117
+ const removed = await withImportLock(env, () => withStore(env, async (store) => {
118
+ // A folder kept for another computer has no path here; only its notes can go.
119
+ const elsewhere = bound
120
+ ? undefined
121
+ : (await store.notes.folders()).find(({ id, name }) => id === target && !keptByDrive(name));
122
+ if (!bound && !(elsewhere && options.allowDelete))
123
+ throw new CliError("not_found", elsewhere
124
+ ? `folder ${target} is not on this computer; files folders remove ${target} --allow-delete --yes deletes its notes`
125
+ : `no notes folder ${target} on this computer — files folders list shows them`, { reason: "folder.not-found" });
126
+ const id = bound ? bound.id : target;
127
+ let notesDeleted = 0;
128
+ if (options.allowDelete && id !== null) {
129
+ const paths = (await folderNotes(store, id)).map((note) => note.path);
130
+ if (options.yes !== true)
131
+ throw new CliError("confirmation_required", `this deletes ${paths.length} notes of folder ${id} from the store, their text included; ` +
132
+ "nothing was changed — add --yes", { reason: "folder.delete-notes", notes: paths.length });
133
+ if (paths.length)
134
+ notesDeleted = await store.notes.deleteFileNotes(id, paths);
135
+ dropFolderState(env, id);
136
+ }
137
+ if (bound)
138
+ updateConfig((config) => unbindFolder(config, bound.path), env);
139
+ return {
140
+ id,
141
+ path: bound?.path ?? null,
142
+ format: bound?.format ?? elsewhere?.format ?? "obsidian",
143
+ removed: true,
144
+ notesDeleted,
145
+ };
146
+ }));
147
+ const kept = removed.id === null ? "" : ` (files folders remove ${removed.id} --allow-delete --yes deletes them)`;
148
+ print(options.json, itemAnswer(removed), options.allowDelete
149
+ ? `${removed.path ?? `folder ${removed.id}`}: ${removed.notesDeleted} notes deleted from the store`
150
+ : `${removed.path} removed from this computer; its notes stay in the store${kept}`);
151
+ });
152
+ withQuery(annotate(folders.command("list"), { effects: LOCAL_READ, output: { entity: "notes_folder" } }).description("folders of notes on this computer, and those the store knows from another"), FOLDERS_QUERY).action(async (words, options) => {
153
+ queryTerms(words, FOLDERS_QUERY, "folders list");
154
+ const here = noteFolders(loadConfig(env).notes);
155
+ const elsewhere = await withStore(env, async (store) => (await storedFolders(store))
156
+ .filter((folder) => !here.some((entry) => entry.id === folder.id))
157
+ .map(({ id, name, format }) => ({
158
+ id,
159
+ name,
160
+ format,
161
+ path: null,
162
+ ...(keptByDrive(name) ? { keptBy: "drive" } : {}),
163
+ })));
164
+ print(options.json, wholeList("folders list", [...here, ...elsewhere]), [
165
+ ...here.map(line),
166
+ ...elsewhere.map(({ id, name, keptBy }) => keptBy
167
+ ? `${id} kept by drive (${name})`
168
+ : `${id} not on this computer (${name}) — files folders update ${id} <path>`),
169
+ ].join("\n") || "no folders: files folders add <path>");
170
+ });
171
+ };
172
+ //# sourceMappingURL=folders-command.js.map
@@ -0,0 +1,88 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { dirname, join, resolve, sep } from "node:path";
3
+ import { CliError } from "@wirecat/cli-base";
4
+ const entryOf = (entry) => typeof entry === "string"
5
+ ? { id: null, path: resolve(entry), format: "obsidian" }
6
+ : { id: entry.id, path: resolve(entry.path), format: entry.format ?? "obsidian" };
7
+ export const noteFolders = (notes) => (notes?.folders ?? []).map(entryOf);
8
+ export const folderPaths = (notes) => noteFolders(notes).map(({ path }) => path);
9
+ const written = (folder) => ({
10
+ id: folder.id,
11
+ path: folder.path,
12
+ ...(folder.format === "obsidian" ? {} : { format: folder.format }),
13
+ });
14
+ const withFolders = (config, folders) => ({
15
+ ...config,
16
+ notes: {
17
+ ...config.notes,
18
+ folders: folders.map((folder) => (folder.id === null ? folder.path : written(folder))),
19
+ },
20
+ });
21
+ /** Writes `folder` at its path, in place of whatever entry had that path or that id. */
22
+ export const bindFolder = (config, folder) => {
23
+ const at = resolve(folder.path);
24
+ const folders = noteFolders(config.notes);
25
+ const index = folders.findIndex((other) => other.path === at);
26
+ const bound = { ...folder, path: at };
27
+ const kept = folders
28
+ .map((other, position) => (position === index ? bound : other))
29
+ .filter((other, position) => position === index || (other.id !== folder.id && other.path !== at));
30
+ return withFolders(config, index < 0 ? [...kept, bound] : kept);
31
+ };
32
+ /**
33
+ * Binds a folder id made elsewhere to its path on this computer. An id already here moves to the new
34
+ * path; a path already bound to another id is refused, since its notes would change identity.
35
+ */
36
+ export const attachFolder = (config, id, path, format) => {
37
+ const at = resolve(path);
38
+ const folders = noteFolders(config.notes);
39
+ const taken = folders.find((folder) => folder.path === at && folder.id !== null && folder.id !== id);
40
+ if (taken)
41
+ throw new CliError("validation_error", `${at} is already folder ${taken.id} — attach that id elsewhere first, or remove it from the config`);
42
+ const previous = folders.find((folder) => folder.id === id);
43
+ const folder = { id, path: at, format: format ?? previous?.format ?? "obsidian" };
44
+ const kept = folders.filter((other) => other.id !== id && other.path !== at);
45
+ return { config: withFolders(config, [...kept, folder]), folder };
46
+ };
47
+ export const unbindFolder = (config, path) => withFolders(config, noteFolders(config.notes).filter((folder) => folder.path !== resolve(path)));
48
+ /** The folder with every link followed, or as written when it cannot be resolved. */
49
+ const real = (path) => {
50
+ try {
51
+ return realpathSync(path);
52
+ }
53
+ catch {
54
+ return resolve(path);
55
+ }
56
+ };
57
+ /**
58
+ * The format a folder is written in when no one said: `obsidian` when it or a folder above it has Obsidian's own
59
+ * `.obsidian` folder, so it is a vault or inside one, `markdown` otherwise. WireCat Desktop picks the same way. The
60
+ * folders above are those of its real path, so a link to a folder inside a vault reads as the vault's. A `.obsidian`
61
+ * in the home folder makes every folder under it a vault's, as Obsidian itself would see it.
62
+ */
63
+ export const detectFormat = (path) => {
64
+ for (let at = real(path);; at = dirname(at)) {
65
+ try {
66
+ if (statSync(join(at, ".obsidian")).isDirectory())
67
+ return "obsidian";
68
+ }
69
+ catch { }
70
+ if (dirname(at) === at)
71
+ return "markdown";
72
+ }
73
+ };
74
+ /** macOS and Windows disks ignore case by default, so `~/Notes` and `~/notes` there are one folder. */
75
+ const comparable = (path) => process.platform === "darwin" || process.platform === "win32" ? real(path).toLowerCase() : real(path);
76
+ const inside = (child, parent) => child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);
77
+ /**
78
+ * The folders files reads that `path` is inside of or holds, compared by real path: one file read under both would be
79
+ * two notes with their own tags and links.
80
+ */
81
+ export const overlapping = (folders, path) => {
82
+ const at = comparable(path);
83
+ return folders.filter((folder) => {
84
+ const other = comparable(folder.path);
85
+ return other !== at && (inside(at, other) || inside(other, at));
86
+ });
87
+ };
88
+ //# sourceMappingURL=folders.js.map
@@ -0,0 +1,234 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, statSync } from "node:fs";
3
+ import { basename, extname, relative, sep } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { normalizeTag } from "@wirecat/cli-core";
6
+ import { attachmentMaxBytes, extractText, importEngine, readWhole } from "@wirecat/cli-core/documents";
7
+ import { noteFileTime } from "./dates.js";
8
+ import { dialectOf } from "./dialects/index.js";
9
+ import { matcher, NOTE_EXTENSIONS, noteFiles, readMemoId } from "./files.js";
10
+ import { documentOf, fileLinks } from "./links.js";
11
+ import { detectRenames } from "./renames.js";
12
+ import { loadFolderState, saveFolderState } from "./state.js";
13
+ const MAX_TEXT = 200_000;
14
+ const MAX_DELETED_SHARE = 0.2;
15
+ const MIN_DELETIONS_CAPPED = 5;
16
+ const PAGE = 500;
17
+ const TEXT_NOTE = /\.(md|markdown|txt)$/i;
18
+ const MEMO = "files:";
19
+ export const missingFolder = (path) => `the notes folder ${path} is missing — connect its disk; if it moved, files folders update <id> <new path>`;
20
+ const inside = (folder, path) => relative(folder, path).split(sep).join("/");
21
+ export const folderNotes = async (store, folderId) => {
22
+ const notes = [];
23
+ for (let offset = 0;; offset += PAGE) {
24
+ const page = await store.notes.notes({ folderId, source: "file", limit: PAGE, offset });
25
+ notes.push(...page.items);
26
+ if (!page.hasMore)
27
+ return notes;
28
+ }
29
+ };
30
+ /** Tags as the store takes them; a nested Obsidian tag (`area/work`) or any other spelling it refuses is left out. */
31
+ const storable = (tags) => [
32
+ ...new Set(tags.flatMap((tag) => {
33
+ try {
34
+ return [normalizeTag(tag)];
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ })),
40
+ ].sort();
41
+ /**
42
+ * Each file is one note of its folder, named by its path inside the folder. What this computer last saw of
43
+ * each file is kept beside the config (`state.ts`), so an untouched file is not even opened; the store's own
44
+ * content hash keeps an unchanged file from being saved again on a computer importing it for the first time.
45
+ * A file gone from one path whose content appears at a new one is a move. A file files exported is not a note.
46
+ * `ignore` keeps files out of the store, so a note stored before is dropped; `skip` only leaves them alone this run.
47
+ */
48
+ export const importNotes = async (store, folder, { ignore = [], skip = [], env = process.env, loadEngine = importEngine, onFile = () => { }, } = {}) => {
49
+ if (!existsSync(folder.path))
50
+ throw new CliError("not_found", missingFolder(folder.path), {
51
+ reason: "notes.folder-missing",
52
+ path: folder.path,
53
+ });
54
+ const before = loadFolderState(env, folder.id);
55
+ const after = { files: {}, documents: { ...before?.documents }, notRead: {} };
56
+ // A folder whose format changed parses its text notes again even when their bytes did not change.
57
+ const reparse = (id) => before?.format !== undefined && before.format !== folder.format && TEXT_NOTE.test(id);
58
+ const notReadNow = after.notRead;
59
+ const skipped = matcher(skip);
60
+ const held = new Set();
61
+ const dialect = dialectOf(folder.format);
62
+ const stored = new Map((await folderNotes(store, folder.id)).map((note) => [note.path, note]));
63
+ const notRead = [];
64
+ const truncated = [];
65
+ const unreadable = [];
66
+ const read = [];
67
+ const mtimes = new Map();
68
+ const notReadAs = (path, status, engine) => {
69
+ const entry = { status, ...(engine === undefined ? {} : { engine }) };
70
+ notRead.push({ path, ...entry });
71
+ notReadNow[path] = entry;
72
+ unreadable.push(path);
73
+ };
74
+ const files = noteFiles(folder.path, ignore, NOTE_EXTENSIONS, { skipExported: false });
75
+ onFile(0, files.length);
76
+ for (const [index, path] of files.entries()) {
77
+ if (index > 0)
78
+ onFile(index - read.length, files.length);
79
+ const id = inside(folder.path, path);
80
+ const previous = before?.files[id];
81
+ const wasNotRead = before?.notRead?.[id];
82
+ if (skipped(id)) {
83
+ held.add(id);
84
+ if (previous !== undefined)
85
+ after.files[id] = previous;
86
+ if (wasNotRead)
87
+ notReadNow[id] = wasNotRead;
88
+ continue;
89
+ }
90
+ const stat = statSync(path);
91
+ mtimes.set(id, stat.mtimeMs);
92
+ const stamp = `${stat.mtimeMs}:${stat.size}:`;
93
+ const exported = previous?.startsWith(`${MEMO}${stamp}`);
94
+ // A missing reader may have been installed since, or the file budget raised, so that file is read again; so is an
95
+ // unstored file an older state file did not mark as not read.
96
+ const settled = stored.has(id) ||
97
+ (wasNotRead !== undefined && wasNotRead.status !== "engine-missing" && wasNotRead.status !== "too-large");
98
+ if (exported || (previous?.startsWith(stamp) && settled && !reparse(id))) {
99
+ after.files[id] = previous;
100
+ if (wasNotRead)
101
+ notReadAs(id, wasNotRead.status, wasNotRead.engine);
102
+ continue;
103
+ }
104
+ if (stat.size > attachmentMaxBytes()) {
105
+ after.files[id] = stamp;
106
+ notReadAs(id, "too-large");
107
+ continue;
108
+ }
109
+ // Only a file that changed is opened, so this check costs nothing on an untouched folder.
110
+ if (TEXT_NOTE.test(id) && readMemoId(path) !== null) {
111
+ after.files[id] = `${MEMO}${stamp}`;
112
+ continue;
113
+ }
114
+ const bytes = await readWhole(path);
115
+ const hash = createHash("sha256").update(bytes).digest("hex");
116
+ after.files[id] = `${stamp}${hash}`;
117
+ read.push({ id, path, bytes, hash });
118
+ }
119
+ const listed = new Set([
120
+ ...Object.keys(after.files).filter((id) => !after.files[id]?.startsWith(MEMO)),
121
+ ...[...held].filter((id) => stored.has(id)),
122
+ ]);
123
+ const goneHashes = Object.fromEntries([...stored.values()]
124
+ .filter((note) => !listed.has(note.path) && note.contentHash !== null)
125
+ .map((note) => [note.path, note.contentHash]));
126
+ const newHashes = Object.fromEntries(read.filter(({ id }) => !stored.has(id)).map(({ id, hash }) => [id, hash]));
127
+ let renamed = 0;
128
+ for (const move of detectRenames(goneHashes, newHashes)) {
129
+ const note = await store.notes.renameFileNote(folder.id, move.from, move.to);
130
+ stored.delete(move.from);
131
+ stored.set(move.to, note);
132
+ renamed++;
133
+ }
134
+ const parsed = new Map();
135
+ let changed = 0;
136
+ let added = 0;
137
+ for (const [index, { id, path, bytes, hash }] of read.entries()) {
138
+ onFile(files.length - read.length + index, files.length);
139
+ if (stored.get(id)?.contentHash === hash && !reparse(id))
140
+ continue;
141
+ const extraction = await extractText(bytes, { kind: "file", name: basename(path), mime: null, path }, loadEngine);
142
+ if (extraction.status !== "extracted") {
143
+ notReadAs(id, extraction.status, "engine" in extraction ? extraction.engine : undefined);
144
+ continue;
145
+ }
146
+ const text = extraction.text.replace(/\r\n?/g, "\n");
147
+ if (extraction.truncated || text.length > MAX_TEXT)
148
+ truncated.push(id);
149
+ const note = TEXT_NOTE.test(id) ? dialect.parse(text, id) : undefined;
150
+ const saved = await store.notes.saveFileNote({
151
+ folderId: folder.id,
152
+ path: id,
153
+ title: note?.title ?? basename(id).replace(/\.[^.]+$/, ""),
154
+ text: text.slice(0, MAX_TEXT),
155
+ ...(note && Object.keys(note.frontMatter).length ? { frontMatter: note.frontMatter } : {}),
156
+ contentHash: hash,
157
+ });
158
+ if (!stored.has(id))
159
+ added++;
160
+ stored.set(id, saved.note);
161
+ if (note)
162
+ parsed.set(id, note);
163
+ after.documents[id] = {
164
+ extractor: extraction.extractor,
165
+ format: extname(id),
166
+ provenance: extname(id).toLowerCase() === ".xlsx" ? "sheet-cell" : "source-text",
167
+ truncated: truncated.includes(id),
168
+ ...("spans" in extraction && extraction.spans ? { spans: extraction.spans } : {}),
169
+ ...("cells" in extraction && extraction.cells ? { cells: extraction.cells } : {}),
170
+ };
171
+ if (saved.changed)
172
+ changed++;
173
+ }
174
+ onFile(files.length, files.length);
175
+ const gone = [...stored.keys()].filter((id) => !listed.has(id));
176
+ let deleted = 0;
177
+ let deletionsSkipped;
178
+ if (gone.length >= MIN_DELETIONS_CAPPED && gone.length > stored.size * MAX_DELETED_SHARE) {
179
+ deletionsSkipped = `${gone.length} of ${stored.size} stored notes are missing from the folder — too many to trust; nothing deleted`;
180
+ }
181
+ else if (gone.length > 0) {
182
+ deleted = await store.notes.deleteFileNotes(folder.id, gone);
183
+ for (const id of gone) {
184
+ stored.delete(id);
185
+ delete after.documents[id];
186
+ }
187
+ }
188
+ const dropped = unreadable.filter((id) => stored.has(id));
189
+ if (dropped.length) {
190
+ deleted += await store.notes.deleteFileNotes(folder.id, dropped);
191
+ for (const id of dropped)
192
+ stored.delete(id);
193
+ }
194
+ // Every run, not only for changed files: a note imported before notes were dated, or a file only touched, is fixed
195
+ // without being read or embedded again.
196
+ const dates = [...stored].flatMap(([id, note]) => {
197
+ const mtime = mtimes.get(id);
198
+ const modifiedAt = mtime === undefined ? undefined : noteFileTime(note.frontMatter, mtime);
199
+ return modifiedAt === undefined || modifiedAt === note.modifiedAt ? [] : [{ path: id, modifiedAt }];
200
+ });
201
+ if (dates.length)
202
+ await store.notes.dateFileNotes(folder.id, dates);
203
+ const documents = [...stored.values()].map(documentOf);
204
+ const relink = new Map(parsed);
205
+ if (renamed + deleted + added > 0) {
206
+ // A note added or moved can be what an older note's unresolved link was waiting for.
207
+ const waiting = new Set((await store.notes.links({ unresolved: true })).map(({ from }) => from.replace(/^note:/, "")));
208
+ for (const note of stored.values())
209
+ if (waiting.has(note.id) && !relink.has(note.path) && TEXT_NOTE.test(note.path))
210
+ relink.set(note.path, dialect.parse(note.text, note.path));
211
+ }
212
+ for (const [id, note] of relink) {
213
+ const record = stored.get(id);
214
+ if (record)
215
+ await store.notes.replaceFileLinks(record.id, fileLinks(id, note.links, documents));
216
+ }
217
+ for (const [id, note] of parsed)
218
+ await store.notes.replaceFileTags(stored.get(id).id, storable(note.tags));
219
+ // A note this run held back is still in the old format, so the next run parses it again.
220
+ const heldBack = [...held].some((id) => reparse(id) && stored.has(id));
221
+ saveFolderState(env, folder.id, { ...after, format: heldBack ? before?.format : folder.format });
222
+ return {
223
+ folder: folder.path,
224
+ folderId: folder.id,
225
+ notes: listed.size - Object.keys(notReadNow).filter((id) => listed.has(id)).length,
226
+ changed,
227
+ renamed,
228
+ deleted,
229
+ ...(notRead.length ? { notRead } : {}),
230
+ ...(truncated.length ? { truncated } : {}),
231
+ ...(deletionsSkipped === undefined ? {} : { deletionsSkipped }),
232
+ };
233
+ };
234
+ //# sourceMappingURL=import.js.map
@@ -0,0 +1,51 @@
1
+ import { resolve } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { dialectOf } from "./dialects/index.js";
4
+ import { exportNotes } from "./export.js";
5
+ const PAGE = 500;
6
+ const MAX_TITLE = 80;
7
+ export const internalNotes = async (store) => {
8
+ const notes = [];
9
+ for (let offset = 0;; offset += PAGE) {
10
+ const page = await store.notes.notes({ source: "internal", limit: PAGE, offset });
11
+ notes.push(...page.items);
12
+ if (!page.hasMore)
13
+ return notes;
14
+ }
15
+ };
16
+ const titleOf = (note) => note.title ??
17
+ (note.text
18
+ .split("\n")
19
+ .find((line) => line.trim())
20
+ ?.trim()
21
+ .slice(0, MAX_TITLE) ||
22
+ note.id);
23
+ /** Where an export goes: the folder given, else the config's `notes.export`. */
24
+ export const exportTarget = (config, dir, format) => {
25
+ const chosen = typeof dir === "string" ? dir : config.notes?.export?.dir;
26
+ if (chosen === undefined)
27
+ throw new CliError("configuration_error", "name a folder — --output-dir <dir>, --export <dir>, or notes.export.dir in the config");
28
+ return { dir: resolve(chosen), format: format ?? config.notes?.export?.format ?? "obsidian" };
29
+ };
30
+ /**
31
+ * Writes internal notes as files, each with what it is about as links and its tags. The store keeps a note's first
32
+ * subject on the note, not among its links, so it leads the list.
33
+ */
34
+ export const exportInternal = async (store, { dir, format, notes }) => {
35
+ const exported = [];
36
+ for (const note of notes) {
37
+ const linked = (await store.notes.links({ from: note.ref })).filter((link) => link.to !== null);
38
+ const about = [...(note.subject === null ? [] : [{ to: note.subject, anchor: null }]), ...linked];
39
+ exported.push({
40
+ id: note.id,
41
+ title: titleOf(note),
42
+ text: note.text,
43
+ aliases: [],
44
+ tags: (await store.notes.noteTags(note.ref)).map(({ tag }) => tag),
45
+ links: about.map((link) => ({ target: link.to, anchor: link.anchor, label: null })),
46
+ frontMatter: {},
47
+ });
48
+ }
49
+ return exportNotes({ dir, dialect: dialectOf(format), notes: exported });
50
+ };
51
+ //# sourceMappingURL=internal.js.map