obsidian-sync-mcp 0.10.0 → 0.12.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/README.md CHANGED
@@ -63,7 +63,7 @@ docker run -p 8787:8787 \
63
63
  ghcr.io/es617/obsidian-sync-mcp:latest
64
64
  ```
65
65
 
66
- Set `COUCHDB_PASSPHRASE` if you use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`, from "Show current recovery code") so the server can resolve note paths. Set `BASE_URL` to your public URL (required for OAuth callbacks when agents connect over HTTPS).
66
+ Set `COUCHDB_PASSPHRASE` if you use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`, from "Show current recovery code") so the server can resolve note paths. Unicode NFC path identity (the default for databases created with LiveSync 1.0.49+) is detected from the database automatically; a brand-new empty database gets NFC unless you set `COUCHDB_PATH_NORMALIZATION=legacy`. Set `BASE_URL` to your public URL (required for OAuth callbacks when agents connect over HTTPS).
67
67
 
68
68
  Your MCP endpoint is `https://your-app.fly.dev/mcp` (Fly.io) or `https://your-server:8787/mcp` (Docker behind HTTPS).
69
69
 
@@ -171,7 +171,7 @@ VAULT_NAME=MyVault \
171
171
  npx obsidian-sync-mcp
172
172
  ```
173
173
 
174
- Omit `COUCHDB_PASSPHRASE` if you don't use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`) so the server can resolve note paths.
174
+ Omit `COUCHDB_PASSPHRASE` if you don't use E2E encryption in LiveSync. Set `COUCHDB_OBFUSCATE_PROPERTIES=true` if "Obfuscate Properties" is also enabled in your LiveSync settings. For an existing vault the server detects the actual setting from the database at startup and corrects a mismatch with a warning; only for a brand-new empty database does the value need to match your LiveSync settings. If the vault was created with LiveSync 1.0.33+ and path obfuscation, also set `COUCHDB_ID_DERIVATION_KEY` to your LiveSync recovery code (`sls-id-v1:...`) so the server can resolve note paths. Unicode NFC path identity (the default for databases created with LiveSync 1.0.49+) is detected from the database automatically; a brand-new empty database gets NFC unless you set `COUCHDB_PATH_NORMALIZATION=legacy`.
175
175
 
176
176
  **Or with Docker:**
177
177
 
@@ -212,6 +212,27 @@ Set `BASE_URL` to the tunnel URL when using authentication.
212
212
  | `move_note` | Move or rename a note — works across folders, creates destination folders automatically |
213
213
  | `get_note_metadata` | Get frontmatter, tags, outgoing links, backlinks, size, and timestamps — navigate the knowledge graph |
214
214
 
215
+ ### Attachments (opt-in)
216
+
217
+ With `ATTACHMENTS_ENABLED=true`, agents can also store images, PDFs, audio and video in the vault. In CouchDB mode they are written through livesync-commonlib, chunked and encrypted the same way as a file added in Obsidian, so they sync to every device.
218
+
219
+ | Tool | Description |
220
+ |---|---|
221
+ | `create_attachment_upload` | Get a one-time upload URL for a vault path. The agent sends the raw bytes there with HTTP `PUT`, e.g. `curl -fsS -X PUT --data-binary @shot.png '<url>'`. Use this for anything but tiny files |
222
+ | `write_attachment` | Fallback for clients that cannot make HTTP requests: save a tiny file from base64 (default limit 32 KB). Every byte is a model output token, so a 32 KB file is already ~13k tokens and minutes of generation |
223
+ | `move_attachment` | Move or rename an attachment (embeds in notes are not rewritten; the response lists notes that still point at the old path) |
224
+ | `delete_attachment` | Delete an attachment |
225
+ | `get_attachment_metadata` | Size, timestamps, and the notes that embed or link it |
226
+ | `list_attachments` | List attachments with size, date and how many notes use each. Filter by folder, name or extension, sort by name, date or size, or pass `unreferenced=true` to find files no note embeds or links |
227
+
228
+ The agent then embeds the file in a note with `edit_note`, e.g. `![[Attachments/shot.png]]`.
229
+
230
+ Upload URLs are served by this server at `BASE_URL/attachments/upload/<token>`, so `BASE_URL` must be reachable by the agent. The token in the URL is the only credential for that request: 32 random bytes, valid for one upload, one path, and `ATTACHMENT_UPLOAD_TTL_SECONDS`. Path checks, `WRITE_FOLDERS` and the size limit are applied when the URL is created, and existing files are never replaced unless the agent passed `overwrite=true`. That last rule is checked again when the file is written, in the same step as the write, so of two concurrent uploads to one new path only the first succeeds and the other gets `409`.
231
+
232
+ **Behind a reverse proxy that allowlists paths:** match the exact upload URL, `PUT` with path `^/attachments/upload/[A-Za-z0-9_-]{43}$`, not the `/attachments/upload/` prefix. The server resolves `..` and `%2e%2e` in the path after the proxy has matched it, so with a prefix rule `/attachments/upload/../../mcp` reaches `/mcp`.
233
+
234
+ Allowed extensions: `avif`, `bmp`, `gif`, `jpeg`, `jpg`, `png`, `webp`, `flac`, `m4a`, `mp3`, `ogg`, `wav`, `3gp`, `mkv`, `mov`, `mp4`, `ogv`, `webm`, `pdf`. Text formats (`.md`, `.svg`, `.html`, `.js`, `.json`, `.canvas`, ...) and dot-folders such as `.obsidian/` are always refused. Attachments never appear in `list_notes` or `search_notes`. For `list_attachments` the server keeps their path, size and modification time in its metadata index, learned from the CouchDB change feed (from the metadata alone, so file contents are never downloaded) or, in filesystem mode, from a scan at startup and the file watcher. References are matched by file name, the way Obsidian resolves `![[shot.png]]`, from `[[wikilinks]]`, `![[embeds]]` and markdown links such as `![](Attachments/shot.png)`. Two files with the same name in different folders therefore count as referenced if either one is, which errs on the safe side when cleaning up.
235
+
215
236
  Every tool response includes an [Obsidian deep link](https://help.obsidian.md/Extending+Obsidian/Obsidian+URI) (`obsidian://open?vault=...&file=...`) that works on Mac and iOS.
216
237
 
217
238
  > "Add a bullet point to my daily note." "Find my notes about the MCP server and fix the typo in the second one."
@@ -253,6 +274,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
253
274
  | `COUCHDB_OBFUSCATE_PROPERTIES` | CouchDB mode | `false` | Set to `true` if "Obfuscate Properties" is enabled in LiveSync (obfuscates file paths, sizes, dates in the database). For existing vaults the actual setting is auto-detected at startup; this value only decides the format for a brand-new empty database |
254
275
  | `COUCHDB_ID_DERIVATION_KEY` | CouchDB mode | — | LiveSync "independent ID derivation" recovery code (`sls-id-v1:...`). Needed to read and write notes on vaults created with LiveSync 1.0.33+ that use path obfuscation; leave unset for older (passphrase-derived) vaults. Get it from LiveSync's "Show current recovery code" |
255
276
  | `COUCHDB_CASE_SENSITIVE` | CouchDB mode | `false` | Set to `true` only if your LiveSync vault has "Handle filenames as case-sensitive" enabled. It must match the vault, or obfuscated document IDs won't resolve (the server fails to start with a clear message). Leave unset otherwise |
277
+ | `COUCHDB_PATH_NORMALIZATION` | CouchDB mode | `auto` | LiveSync path identity: how file names map to document IDs. `auto` follows the database, and uses `nfc` (Unicode NFC, so `Café.md` typed on macOS or Linux is the same note) for a brand-new empty database, matching LiveSync 1.0.49+. The server declares the choice in an empty database at startup, so set `legacy` before first starting it only if your LiveSync devices use legacy identity (vaults set up before 1.0.49). An explicit value that contradicts an existing database fails startup, since changing it needs a rebuild from LiveSync |
256
278
  | `VAULT_NAME` | Both | `MyVault` | Vault name (used for deep links and index storage) |
257
279
  | `MCP_AUTH_TOKEN` | Optional | — | Password for authentication |
258
280
  | `BASE_URL` | Optional | `http://localhost:PORT` | Public URL (for OAuth callbacks when using a tunnel) |
@@ -265,6 +287,11 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
265
287
  | `MCP_REFRESH_DAYS` | Optional | `14` | Days before auth session expires |
266
288
  | `READ_ONLY` | Optional | `false` | Set to `true` to disable all write tools (`write_note`, `edit_note`, `delete_note`, `move_note`). Only read tools are exposed via MCP, and the vault backend rejects writes as well. Useful when sharing the server with multiple AI clients and write access should be opt-in. This protects the vault from MCP clients; it is not a database-level guarantee. To make CouchDB itself refuse writes, use CouchDB-side controls, such as a `validate_doc_update` function that rejects the server's CouchDB user. |
267
289
  | `WRITE_FOLDERS` | Optional | — | Comma-separated list of vault-relative folders where writes are allowed (e.g. `MCP,Inbox`). When set, the whole vault stays readable but `write_note`, `edit_note`, `delete_note`, and `move_note` refuse paths outside these folders (`move_note` requires both source and destination to be writable). Enforced server-side, unlike `MCP_INSTRUCTIONS`. Matching is case-sensitive and folder-boundary-aware (`MCP` matches `MCP/note.md` but not `MCP-private/note.md`). Ignored when `READ_ONLY=true`; unset means the whole vault is writable. |
290
+ | `ATTACHMENTS_ENABLED` | Optional | `false` | Set to `true` to enable the [attachment tools](#attachments-opt-in) and the upload endpoint. Under `READ_ONLY=true` only `get_attachment_metadata` and `list_attachments` are exposed and the endpoint is not mounted. With CouchDB, startup then always reads the change feed from the beginning to learn existing attachments (it already does so whenever notes are indexed, to rebuild the search text) |
291
+ | `ATTACHMENT_MAX_BYTES` | Optional | `20971520` (20 MB) | Largest file accepted by an upload URL. The whole file is held in memory while it is written |
292
+ | `ATTACHMENT_INLINE_MAX_BYTES` | Optional | `32768` (32 KB) | Largest decoded file accepted by `write_attachment`. Base64 costs about one output token per 2.5 bytes, so raising this mainly makes slow, error-prone calls possible |
293
+ | `ATTACHMENT_UPLOAD_TTL_SECONDS` | Optional | `600` | How long an upload URL stays valid |
294
+ | `ATTACHMENT_EXTENSIONS` | Optional | all supported | Comma-separated subset of the supported extensions to allow, e.g. `png,jpg,pdf`. Can only narrow the list; an unsupported extension is a startup error |
268
295
  | `MCP_INSTRUCTIONS` | Optional | — | Extra text appended to the server's MCP `instructions` (the string clients inject into the system prompt). Use this to bake vault-specific conventions into the server — e.g. folder structure, naming rules, folders to avoid — so they apply across every MCP client without per-client config. Best-effort: not all clients respect `instructions`. |
269
296
  | `MCP_INSTRUCTIONS_FILE` | Optional | — | Path to a file (e.g. markdown) whose contents are appended to the MCP `instructions`. Easier than `MCP_INSTRUCTIONS` for multi-line conventions. If both are set, the file wins and `MCP_INSTRUCTIONS` is ignored (with a startup warning). Missing/unreadable file or files larger than 32 KB are fatal startup errors. **Store this file somewhere only the service user can write (e.g. `chmod 600`)** — its contents land in every MCP session's system prompt, so write access to it = prompt-injection access to every client. |
270
297
 
@@ -300,7 +327,7 @@ Set transport to **Streamable HTTP**, enter `http://localhost:8787/mcp`, and con
300
327
  - **Single vault per instance.** Each server connects to one vault. For multiple vaults, run multiple instances on different ports.
301
328
  - **Single machine on Fly.io.** Auth state is in-memory, so multiple machines break the OAuth flow. The setup script enforces this automatically.
302
329
  - **No conflict resolution.** If an agent and Obsidian edit the same note simultaneously, last write wins.
303
- - **Text only.** Binary attachments are not exposed through MCP tools.
330
+ - **Attachments are write-and-describe only.** With `ATTACHMENTS_ENABLED=true` agents can store, move and delete media files, but the server does not return attachment contents to the model.
304
331
  - **Deep links depend on the client.** Obsidian `obsidian://` deep links are included in every tool response. They work on Claude Mobile and in browsers, but some clients (Claude Desktop) may not render them as clickable links.
305
332
  - **Node 22+ required.**
306
333
  - **Setup script requires bash.** The `deploy/setup.sh` script works on macOS and Linux. On Windows, use WSL or Git Bash.
@@ -329,10 +356,19 @@ This software is provided as-is under the [MIT license](https://github.com/es617
329
356
  git clone --recursive https://github.com/es617/obsidian-sync-mcp.git
330
357
  cd obsidian-sync-mcp
331
358
  npm install && npm run build
332
- npm test # unit tests
333
- npm run test:e2e # integration tests
359
+ npm test # unit tests
360
+ npm run test:e2e # integration tests
361
+ npm run test:couchdb # CouchDB harness (needs a throwaway CouchDB on localhost:5985)
362
+ npm run test:smoke # full smoke test: built server over MCP against CouchDB, all vault configurations
334
363
  ```
335
364
 
365
+ The CouchDB tests drop and recreate their own databases, so never point them at a real vault. Start a throwaway CouchDB with `docker run -d -p 5985:5984 -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=test couchdb:3`. Set `TEST_PATH_NORMALIZATION=legacy` to run the harness on legacy path identity.
366
+
367
+ ### Releasing
368
+
369
+ 1. Commit the version bump to main: `package.json`, `package-lock.json`, `server.json`, and a `## <version>` section in `CHANGELOG.md`.
370
+ 2. Either push a `v<version>` tag, or run the **Release** workflow (Actions → Release → Run workflow, which also works from a phone browser). The workflow checks the versions match, waits for CI on main's latest commit to pass, creates the tag and starts CI/CD on it, which publishes the GitHub release, the npm package and the Docker image.
371
+
336
372
  ---
337
373
 
338
374
  ## License
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ // Node polyfills for livesync-commonlib browser globals
3
+ if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
+
5
+ // src/index-sync.ts
6
+ function deriveContent(doc) {
7
+ if (doc.deleted) return null;
8
+ return "data" in doc && Array.isArray(doc.data) ? doc.data.join("") : "";
9
+ }
10
+ function applyIndexChange(index, path, content, mtime) {
11
+ if (content !== null) {
12
+ index.update(path, content, mtime);
13
+ } else {
14
+ index.remove(path);
15
+ }
16
+ }
17
+ function pruneGhosts(index, preexisting, seen) {
18
+ const removed = [];
19
+ for (const p of preexisting) {
20
+ if (!seen.has(p)) {
21
+ index.remove(p);
22
+ removed.push(p);
23
+ }
24
+ }
25
+ return removed;
26
+ }
27
+
28
+ // src/path-identity-config.ts
29
+ var NAMES = { 0: "legacy", 1: "nfc" };
30
+ function parsePathNormalization(raw) {
31
+ const value = (raw ?? "").trim().toLowerCase();
32
+ if (value === "" || value === "auto") return "auto";
33
+ if (value === "nfc" || value === "legacy") return value;
34
+ throw new Error(`COUCHDB_PATH_NORMALIZATION must be "auto", "nfc" or "legacy" (got "${raw}").`);
35
+ }
36
+ function resolvePathIdentity(setting, state) {
37
+ if (state.status === "empty") {
38
+ if (setting === "legacy") return { version: 0 };
39
+ if (setting === "nfc") return { version: 1 };
40
+ return {
41
+ version: 1,
42
+ notice: "Empty database: using Unicode NFC path identity, the default for vaults created by LiveSync 1.0.49+. If your LiveSync devices use legacy path identity (vaults set up before 1.0.49), set COUCHDB_PATH_NORMALIZATION=legacy."
43
+ };
44
+ }
45
+ const actual = state.pathNormalizationVersion;
46
+ if (setting === "auto" || setting === NAMES[actual]) return { version: actual };
47
+ throw new Error(
48
+ `COUCHDB_PATH_NORMALIZATION=${setting} but this database uses ${NAMES[actual]} path identity. An existing database can't change path identity without a rebuild from LiveSync. Unset COUCHDB_PATH_NORMALIZATION (or set it to auto) to follow the database.`
49
+ );
50
+ }
51
+
52
+ export {
53
+ deriveContent,
54
+ applyIndexChange,
55
+ pruneGhosts,
56
+ parsePathNormalization,
57
+ resolvePathIdentity
58
+ };
59
+ //# sourceMappingURL=chunk-AK3JXN67.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index-sync.ts","../src/path-identity-config.ts"],"sourcesContent":["/**\n * Shared search-index sync helpers.\n *\n * Kept dependency-free (no livesync-commonlib imports) so the delete-vs-empty\n * routing is unit-testable in isolation.\n */\n\nexport interface IndexTarget {\n update(path: string, content: string, mtime?: number): void;\n remove(path: string): void;\n}\n\n/**\n * Derive index content from a LiveSync change doc.\n *\n * Returns `null` ONLY when the note is deleted. An existing note with no body\n * yields `\"\"` so a zero-byte note stays distinguishable from a deletion —\n * without this, a note that serializes with no `data` array would look deleted.\n */\nexport function deriveContent(doc: { deleted?: boolean; data?: unknown }): string | null {\n if (doc.deleted) return null;\n return \"data\" in doc && Array.isArray(doc.data) ? doc.data.join(\"\") : \"\";\n}\n\n/**\n * Route a change into the index: `null` content removes (the note was deleted),\n * any string — including `\"\"` — upserts. Using `content !== null` (rather than a\n * truthiness check) keeps zero-byte notes indexed instead of dropping them\n * (issues #5 / #6).\n */\nexport function applyIndexChange(index: IndexTarget, path: string, content: string | null, mtime?: number): void {\n if (content !== null) {\n index.update(path, content, mtime);\n } else {\n index.remove(path);\n }\n}\n\n/**\n * After a completed from-zero catch-up, remove index entries for notes that\n * vanished while the server was down (e.g. a remote \"Rebuild database\" that\n * left no tombstones to replay). Only paths present before the pass\n * (`preexisting`) that the pass did not re-deliver (`seen`) are dropped:\n * restricting the prune to pre-existing paths means an entry the live watcher\n * adds mid-pass is never pruned. Returns the removed paths.\n */\nexport function pruneGhosts(\n index: Pick<IndexTarget, \"remove\">,\n preexisting: Iterable<string>,\n seen: ReadonlySet<string>,\n): string[] {\n const removed: string[] = [];\n for (const p of preexisting) {\n if (!seen.has(p)) {\n index.remove(p);\n removed.push(p);\n }\n }\n return removed;\n}\n","/**\n * Decide the vault's path identity (LiveSync \"path normalisation version\")\n * from COUCHDB_PATH_NORMALIZATION and what the database declares.\n *\n * Kept dependency-free so the decision is unit-testable in isolation.\n *\n * Version 1 (`nfc-path-identity-v1`) applies Unicode NFC to a path before its\n * document ID is derived, so `Café.md` typed as NFC or NFD is the same note.\n * LiveSync 1.0.49+ uses it for new vaults; older vaults use version 0. The\n * library refuses a database whose declaration differs from the setting, and\n * a database with notes cannot change version without a rebuild.\n */\n\nexport type PathNormalizationSetting = \"auto\" | \"nfc\" | \"legacy\";\n\n/** What the database declares: nothing yet, or an existing version. */\nexport type PathIdentityState = { status: \"empty\" } | { status: \"configured\"; pathNormalizationVersion: 0 | 1 };\n\nexport interface PathIdentityDecision {\n version: 0 | 1;\n /** Startup message worth logging, if any. */\n notice?: string;\n}\n\nconst NAMES: Record<0 | 1, string> = { 0: \"legacy\", 1: \"nfc\" };\n\nexport function parsePathNormalization(raw: string | undefined): PathNormalizationSetting {\n const value = (raw ?? \"\").trim().toLowerCase();\n if (value === \"\" || value === \"auto\") return \"auto\";\n if (value === \"nfc\" || value === \"legacy\") return value;\n throw new Error(`COUCHDB_PATH_NORMALIZATION must be \"auto\", \"nfc\" or \"legacy\" (got \"${raw}\").`);\n}\n\nexport function resolvePathIdentity(setting: PathNormalizationSetting, state: PathIdentityState): PathIdentityDecision {\n if (state.status === \"empty\") {\n if (setting === \"legacy\") return { version: 0 };\n if (setting === \"nfc\") return { version: 1 };\n return {\n version: 1,\n notice:\n \"Empty database: using Unicode NFC path identity, the default for vaults created by LiveSync 1.0.49+. \" +\n \"If your LiveSync devices use legacy path identity (vaults set up before 1.0.49), set COUCHDB_PATH_NORMALIZATION=legacy.\",\n };\n }\n const actual = state.pathNormalizationVersion;\n if (setting === \"auto\" || setting === NAMES[actual]) return { version: actual };\n throw new Error(\n `COUCHDB_PATH_NORMALIZATION=${setting} but this database uses ${NAMES[actual]} path identity. ` +\n \"An existing database can't change path identity without a rebuild from LiveSync. \" +\n \"Unset COUCHDB_PATH_NORMALIZATION (or set it to auto) to follow the database.\",\n );\n}\n"],"mappings":";;;;;AAmBO,SAAS,cAAc,KAA2D;AACrF,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,UAAU,OAAO,MAAM,QAAQ,IAAI,IAAI,IAAI,IAAI,KAAK,KAAK,EAAE,IAAI;AAC1E;AAQO,SAAS,iBAAiB,OAAoB,MAAc,SAAwB,OAAsB;AAC7G,MAAI,YAAY,MAAM;AAClB,UAAM,OAAO,MAAM,SAAS,KAAK;AAAA,EACrC,OAAO;AACH,UAAM,OAAO,IAAI;AAAA,EACrB;AACJ;AAUO,SAAS,YACZ,OACA,aACA,MACQ;AACR,QAAM,UAAoB,CAAC;AAC3B,aAAW,KAAK,aAAa;AACzB,QAAI,CAAC,KAAK,IAAI,CAAC,GAAG;AACd,YAAM,OAAO,CAAC;AACd,cAAQ,KAAK,CAAC;AAAA,IAClB;AAAA,EACJ;AACA,SAAO;AACX;;;ACnCA,IAAM,QAA+B,EAAE,GAAG,UAAU,GAAG,MAAM;AAEtD,SAAS,uBAAuB,KAAmD;AACtF,QAAM,SAAS,OAAO,IAAI,KAAK,EAAE,YAAY;AAC7C,MAAI,UAAU,MAAM,UAAU,OAAQ,QAAO;AAC7C,MAAI,UAAU,SAAS,UAAU,SAAU,QAAO;AAClD,QAAM,IAAI,MAAM,sEAAsE,GAAG,KAAK;AAClG;AAEO,SAAS,oBAAoB,SAAmC,OAAgD;AACnH,MAAI,MAAM,WAAW,SAAS;AAC1B,QAAI,YAAY,SAAU,QAAO,EAAE,SAAS,EAAE;AAC9C,QAAI,YAAY,MAAO,QAAO,EAAE,SAAS,EAAE;AAC3C,WAAO;AAAA,MACH,SAAS;AAAA,MACT,QACI;AAAA,IAER;AAAA,EACJ;AACA,QAAM,SAAS,MAAM;AACrB,MAAI,YAAY,UAAU,YAAY,MAAM,MAAM,EAAG,QAAO,EAAE,SAAS,OAAO;AAC9E,QAAM,IAAI;AAAA,IACN,8BAA8B,OAAO,2BAA2B,MAAM,MAAM,CAAC;AAAA,EAGjF;AACJ;","names":[]}
@@ -15,7 +15,108 @@ var __copyProps = (to, from, except, desc) => {
15
15
  };
16
16
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
17
17
 
18
+ // src/note-path.ts
19
+ var RESERVED_ROOT_FILES = /* @__PURE__ */ new Set([
20
+ "redflag.md",
21
+ "redflag2.md",
22
+ "redflag3.md",
23
+ "flag_rebuild.md",
24
+ "flag_fetch.md"
25
+ ]);
26
+ function validateVaultPathShape(path, kind) {
27
+ const problem = vaultPathShapeProblem(path);
28
+ if (problem !== null) throw new Error(`Invalid ${kind} path${problem}`);
29
+ }
30
+ function vaultPathShapeProblem(path) {
31
+ if (!path || path.length > 1e3) return "";
32
+ if (path.startsWith("/") || path.includes("\0") || path.includes("..")) return "";
33
+ if (path.includes(":")) return ": ':' is not allowed";
34
+ for (const segment of path.split(/[/\\]/)) {
35
+ if (segment === "") return ": empty path segment";
36
+ if (segment.startsWith(".")) return ": dot-folders and hidden files (e.g. .obsidian) are not allowed";
37
+ }
38
+ return null;
39
+ }
40
+ function validateNotePath(path) {
41
+ validateVaultPathShape(path, "note");
42
+ if (!path.endsWith(".md")) {
43
+ throw new Error("Invalid note path: must be a vault-relative path ending in .md");
44
+ }
45
+ if (!path.includes("/") && !path.includes("\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {
46
+ throw new Error("Invalid note path: reserved LiveSync control file");
47
+ }
48
+ }
49
+ function isValidNotePath(path) {
50
+ try {
51
+ validateNotePath(path);
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ // src/attachment-path.ts
59
+ var SUPPORTED_ATTACHMENT_EXTENSIONS = [
60
+ // images
61
+ "avif",
62
+ "bmp",
63
+ "gif",
64
+ "jpeg",
65
+ "jpg",
66
+ "png",
67
+ "webp",
68
+ // audio
69
+ "flac",
70
+ "m4a",
71
+ "mp3",
72
+ "ogg",
73
+ "wav",
74
+ "3gp",
75
+ // video
76
+ "mkv",
77
+ "mov",
78
+ "mp4",
79
+ "ogv",
80
+ "webm",
81
+ // documents
82
+ "pdf"
83
+ ];
84
+ function parseAttachmentExtensions(raw) {
85
+ if (raw === void 0 || raw.trim() === "") return new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);
86
+ const requested = raw.split(",").map((e) => e.trim().toLowerCase().replace(/^\./, "")).filter(Boolean);
87
+ const unsupported = requested.filter((e) => !SUPPORTED_ATTACHMENT_EXTENSIONS.includes(e));
88
+ if (unsupported.length > 0) {
89
+ throw new Error(
90
+ `ATTACHMENT_EXTENSIONS contains unsupported extensions: ${unsupported.join(", ")}. Supported: ${SUPPORTED_ATTACHMENT_EXTENSIONS.join(", ")}.`
91
+ );
92
+ }
93
+ return new Set(requested);
94
+ }
95
+ function attachmentExtension(path) {
96
+ const name = path.split(/[/\\]/).pop() ?? "";
97
+ const dot = name.lastIndexOf(".");
98
+ return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();
99
+ }
100
+ var SUPPORTED = new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);
101
+ function validateAttachmentPath(path, allowed = SUPPORTED) {
102
+ validateVaultPathShape(path, "attachment");
103
+ const ext = attachmentExtension(path);
104
+ if (!ext || !allowed.has(ext)) {
105
+ throw new Error(
106
+ `Invalid attachment path: extension must be one of ${[...allowed].sort().join(", ")}`
107
+ );
108
+ }
109
+ }
110
+ function isValidAttachmentPath(path, allowed = SUPPORTED) {
111
+ const ext = attachmentExtension(path);
112
+ return !!ext && allowed.has(ext) && vaultPathShapeProblem(path) === null;
113
+ }
114
+
18
115
  // src/parse.ts
116
+ var WIKILINK = /\[\[([^[\]|#\n]+)(?:#[^[\]|\n]*)?(?:\|[^[\]\n]*)?\]\]/g;
117
+ var LINK_LABEL = String.raw`[^[\]\n]|\[[^[\]\n]*\]`;
118
+ var NOTE_LINK = new RegExp(String.raw`\[(?:${LINK_LABEL})+\]\(([^()#\n]+\.md)(?:#[^()\n]*)?\)`, "g");
119
+ var ATTACHMENT_LINK = new RegExp(String.raw`\[((?:${LINK_LABEL})*)\]\((<[^<>\n]+>|[^()\s]+)(?:\s+"[^"\n]*")?\)`, "g");
19
120
  function parseFrontmatterAndLinks(content) {
20
121
  const frontmatter = {};
21
122
  const tags = /* @__PURE__ */ new Set();
@@ -58,14 +159,25 @@ function parseFrontmatterAndLinks(content) {
58
159
  if (new RegExp("^\\p{Nd}+$", "u").test(match[2])) continue;
59
160
  tags.add(match[2]);
60
161
  }
61
- for (const match of content.matchAll(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g)) {
62
- links.push(match[1]);
63
- }
64
- for (const match of content.matchAll(/\[([^\]]+)\]\(([^)]+\.md)\)/g)) {
65
- links.push(match[2]);
66
- }
162
+ for (const match of content.matchAll(WIKILINK)) links.push(match[1]);
163
+ for (const match of content.matchAll(NOTE_LINK)) links.push(match[1]);
164
+ addAttachmentLinks(content, links);
67
165
  return { frontmatter, tags: [...tags], links: [...new Set(links)] };
68
166
  }
167
+ function addAttachmentLinks(text, links, nested = false) {
168
+ for (const match of text.matchAll(ATTACHMENT_LINK)) {
169
+ if (!nested && match[1].includes("[")) addAttachmentLinks(match[1], links, true);
170
+ let target = match[2].replace(/^<|>$/g, "").replace(/#.*$/, "");
171
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.endsWith(".md")) continue;
172
+ try {
173
+ target = decodeURIComponent(target);
174
+ } catch {
175
+ continue;
176
+ }
177
+ target = target.replace(/^(\.\.?\/)+/, "");
178
+ if (isValidAttachmentPath(target)) links.push(target);
179
+ }
180
+ }
69
181
  function maskCode(content) {
70
182
  const lines = content.split("\n");
71
183
  const out = [];
@@ -135,52 +247,43 @@ function maskInlineSpans(text) {
135
247
  return result + text.slice(from);
136
248
  }
137
249
 
138
- // src/note-path.ts
139
- var RESERVED_ROOT_FILES = /* @__PURE__ */ new Set([
140
- "redflag.md",
141
- "redflag2.md",
142
- "redflag3.md",
143
- "flag_rebuild.md",
144
- "flag_fetch.md"
145
- ]);
146
- function validateNotePath(path) {
147
- if (!path || path.length > 1e3) {
148
- throw new Error("Invalid note path");
149
- }
150
- if (path.startsWith("/") || path.includes("\0") || path.includes("..")) {
151
- throw new Error("Invalid note path");
152
- }
153
- if (path.includes(":")) {
154
- throw new Error("Invalid note path: ':' is not allowed");
250
+ // src/vault-backend.ts
251
+ var AttachmentTooLargeError = class extends Error {
252
+ constructor(path, size, limit) {
253
+ super(`Attachment is ${size} bytes, over the ${limit}-byte limit for moving it: ${path}`);
254
+ this.path = path;
255
+ this.size = size;
256
+ this.limit = limit;
257
+ this.name = "AttachmentTooLargeError";
155
258
  }
156
- if (!path.endsWith(".md")) {
157
- throw new Error("Invalid note path: must be a vault-relative path ending in .md");
158
- }
159
- for (const segment of path.split(/[/\\]/)) {
160
- if (segment === "") {
161
- throw new Error("Invalid note path: empty path segment");
162
- }
163
- if (segment.startsWith(".")) {
164
- throw new Error("Invalid note path: dot-folders and hidden files (e.g. .obsidian) are not allowed");
165
- }
166
- }
167
- if (!path.includes("/") && !path.includes("\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {
168
- throw new Error("Invalid note path: reserved LiveSync control file");
259
+ };
260
+ var AttachmentMoveIncompleteError = class extends Error {
261
+ constructor(from, to) {
262
+ super(`Copied ${from} to ${to}, but could not delete ${from}`);
263
+ this.from = from;
264
+ this.to = to;
265
+ this.name = "AttachmentMoveIncompleteError";
169
266
  }
170
- }
171
- function isValidNotePath(path) {
172
- try {
173
- validateNotePath(path);
174
- return true;
175
- } catch {
176
- return false;
267
+ };
268
+ var AttachmentExistsError = class extends Error {
269
+ constructor(path) {
270
+ super(`Attachment already exists: ${path}`);
271
+ this.path = path;
272
+ this.name = "AttachmentExistsError";
177
273
  }
178
- }
274
+ };
179
275
 
180
276
  export {
181
277
  __reExport,
182
- parseFrontmatterAndLinks,
183
278
  validateNotePath,
184
- isValidNotePath
279
+ isValidNotePath,
280
+ parseAttachmentExtensions,
281
+ attachmentExtension,
282
+ validateAttachmentPath,
283
+ isValidAttachmentPath,
284
+ parseFrontmatterAndLinks,
285
+ AttachmentTooLargeError,
286
+ AttachmentMoveIncompleteError,
287
+ AttachmentExistsError
185
288
  };
186
- //# sourceMappingURL=chunk-VR63UUCB.js.map
289
+ //# sourceMappingURL=chunk-XZ4HUASL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/note-path.ts","../src/attachment-path.ts","../src/parse.ts","../src/vault-backend.ts"],"sourcesContent":["/**\n * Shared validation for note paths, applied by both the CouchDB and local\n * backends before any read, write, delete or move.\n *\n * The note model is markdown-only: `list_notes` only ever surfaces `*.md`\n * files; binary attachments have their own validator (attachment-path.ts)\n * built on validateVaultPathShape below. Enforcing that here keeps\n * the tools from reaching anything that isn't a note, which closes two real\n * problems:\n * - CouchDB mode: a path like `obsydian_livesync_version` or a `ix:`/`ps:`\n * prefixed id would otherwise become a document id and overwrite LiveSync's\n * own control documents, stopping sync on every device.\n * - Local mode: a path like `.obsidian/plugins/x/main.js` would otherwise\n * write executable plugin code into the vault, and `.obsidian/.../data.json`\n * would expose LiveSync credentials.\n *\n * Rules: vault-relative, ends in `.md`, no `..`, no leading `/`, no `:` (its\n * only use here is LiveSync's internal id prefixes), no NUL, and no path\n * segment (split on either slash) that starts with `.` (hidden files and the\n * `.obsidian` config dir). Root-level LiveSync control flag files are also\n * rejected even though they are `.md`.\n */\n\n// LiveSync's note-shaped control files, all at the vault root. Writing one and\n// letting it sync triggers a vault-wide rebuild/fetch on every device, so they\n// are not writable through the note tools. Compared lowercase because LiveSync\n// lowercases ids when case-insensitive handling is on.\nconst RESERVED_ROOT_FILES = new Set([\n \"redflag.md\",\n \"redflag2.md\",\n \"redflag3.md\",\n \"flag_rebuild.md\",\n \"flag_fetch.md\",\n]);\n\n/**\n * The rules every vault path must pass, note or attachment: vault-relative,\n * no `..`, no leading `/`, no `:`, no NUL, no empty segment and no segment\n * starting with `.`. `kind` only names the path in error messages.\n */\nexport function validateVaultPathShape(path: string, kind: string): void {\n const problem = vaultPathShapeProblem(path);\n if (problem !== null) throw new Error(`Invalid ${kind} path${problem}`);\n}\n\n/**\n * Why `path` fails validateVaultPathShape, as the suffix of its error message\n * (\"\" when there is no detail), or null when it passes. Non-throwing so hot\n * paths like link parsing don't pay for an exception per rejected target.\n */\nexport function vaultPathShapeProblem(path: string): string | null {\n if (!path || path.length > 1000) return \"\";\n if (path.startsWith(\"/\") || path.includes(\"\\0\") || path.includes(\"..\")) return \"\";\n if (path.includes(\":\")) return \": ':' is not allowed\";\n for (const segment of path.split(/[/\\\\]/)) {\n if (segment === \"\") return \": empty path segment\";\n if (segment.startsWith(\".\")) return \": dot-folders and hidden files (e.g. .obsidian) are not allowed\";\n }\n return null;\n}\n\nexport function validateNotePath(path: string): void {\n validateVaultPathShape(path, \"note\");\n if (!path.endsWith(\".md\")) {\n throw new Error(\"Invalid note path: must be a vault-relative path ending in .md\");\n }\n // Root-level control flag files (no folder segment).\n if (!path.includes(\"/\") && !path.includes(\"\\\\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {\n throw new Error(\"Invalid note path: reserved LiveSync control file\");\n }\n}\n\n/** Boolean form of validateNotePath, for filtering listings and the index. */\nexport function isValidNotePath(path: string): boolean {\n try {\n validateNotePath(path);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Validation for attachment paths (images, PDFs, audio, video).\n *\n * Attachments get the same shape rules as notes (see note-path.ts) — no `..`,\n * no `:`, no dot-folders — so they cannot reach LiveSync control documents or\n * `.obsidian/`. On top of that the extension must be on an allowlist of binary\n * media types Obsidian can embed. Text-like formats (`.md`, `.svg`, `.html`,\n * `.js`, `.json`, `.css`, `.canvas`, ...) are never attachments: they are\n * either notes, executable in Obsidian, or stored by LiveSync as plain text.\n */\n\nimport { validateVaultPathShape, vaultPathShapeProblem } from \"./note-path.js\";\n\n/** Binary formats Obsidian embeds natively. SVG is left out on purpose: it is text and can carry script. */\nexport const SUPPORTED_ATTACHMENT_EXTENSIONS: readonly string[] = [\n // images\n \"avif\", \"bmp\", \"gif\", \"jpeg\", \"jpg\", \"png\", \"webp\",\n // audio\n \"flac\", \"m4a\", \"mp3\", \"ogg\", \"wav\", \"3gp\",\n // video\n \"mkv\", \"mov\", \"mp4\", \"ogv\", \"webm\",\n // documents\n \"pdf\",\n];\n\n/**\n * Parse ATTACHMENT_EXTENSIONS into an allowlist. Unset means every supported\n * extension. The variable can only narrow the list: an unsupported entry is an\n * error rather than a silent widening of what may be written.\n */\nexport function parseAttachmentExtensions(raw: string | undefined): Set<string> {\n if (raw === undefined || raw.trim() === \"\") return new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);\n const requested = raw\n .split(\",\")\n .map((e) => e.trim().toLowerCase().replace(/^\\./, \"\"))\n .filter(Boolean);\n const unsupported = requested.filter((e) => !SUPPORTED_ATTACHMENT_EXTENSIONS.includes(e));\n if (unsupported.length > 0) {\n throw new Error(\n `ATTACHMENT_EXTENSIONS contains unsupported extensions: ${unsupported.join(\", \")}. ` +\n `Supported: ${SUPPORTED_ATTACHMENT_EXTENSIONS.join(\", \")}.`,\n );\n }\n return new Set(requested);\n}\n\n/** Lowercased extension without the dot, or \"\" when there is none. */\nexport function attachmentExtension(path: string): string {\n const name = path.split(/[/\\\\]/).pop() ?? \"\";\n const dot = name.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : name.slice(dot + 1).toLowerCase();\n}\n\nconst SUPPORTED = new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);\n\nexport function validateAttachmentPath(path: string, allowed: ReadonlySet<string> = SUPPORTED): void {\n validateVaultPathShape(path, \"attachment\");\n const ext = attachmentExtension(path);\n if (!ext || !allowed.has(ext)) {\n throw new Error(\n `Invalid attachment path: extension must be one of ${[...allowed].sort().join(\", \")}`,\n );\n }\n}\n\n/** Boolean form of validateAttachmentPath. Doesn't throw: link parsing calls it for every link target. */\nexport function isValidAttachmentPath(path: string, allowed: ReadonlySet<string> = SUPPORTED): boolean {\n const ext = attachmentExtension(path);\n return !!ext && allowed.has(ext) && vaultPathShapeProblem(path) === null;\n}\n","/**\n * Parse Obsidian markdown content for frontmatter, tags, and links.\n */\n\nimport { isValidAttachmentPath } from \"./attachment-path.js\";\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n}\n\n// Link patterns. Each part stops at a bracket, paren or newline, so a failed\n// match only scans up to the next one. Otherwise it rescans the rest of the\n// note, which is quadratic on input like \"[\".repeat(20000), and parsing is\n// synchronous and runs on every note at startup. No length cap is needed on\n// top: attachment targets are capped by isValidAttachmentPath after decoding.\n\n// [[wikilinks]]. A #heading, #^block or #page=2 suffix points into the target,\n// so [[Note#Heading]] links Note and ![[paper.pdf#page=2]] embeds paper.pdf.\n// [[#Heading]] (same note) is not a link.\nconst WIKILINK = /\\[\\[([^[\\]|#\\n]+)(?:#[^[\\]|\\n]*)?(?:\\|[^[\\]\\n]*)?\\]\\]/g;\n\n// Markdown link text: plain characters, or one level of [brackets], so\n// [see [1]](note.md) and [![thumb](t.png)](full.png) parse. The two\n// alternatives never match the same character, so this adds no backtracking.\nconst LINK_LABEL = String.raw`[^[\\]\\n]|\\[[^[\\]\\n]*\\]`;\n\n// [markdown links](path.md), also with a #heading: [x](path.md#Heading) links path.md.\nconst NOTE_LINK = new RegExp(String.raw`\\[(?:${LINK_LABEL})+\\]\\(([^()#\\n]+\\.md)(?:#[^()\\n]*)?\\)`, \"g\");\n\n// Markdown links and embeds to attachments: ![](Attachments/shot.png),\n// [report](<docs/Q1 report.pdf>), ![alt](my%20image.png \"title\").\nconst ATTACHMENT_LINK = new RegExp(String.raw`\\[((?:${LINK_LABEL})*)\\]\\((<[^<>\\n]+>|[^()\\s]+)(?:\\s+\"[^\"\\n]*\")?\\)`, \"g\");\n\nexport function parseFrontmatterAndLinks(content: string): NoteMetadata {\n const frontmatter: Record<string, any> = {};\n const tags = new Set<string>();\n const links: string[] = [];\n\n // Parse YAML frontmatter\n if (content.startsWith(\"---\\n\")) {\n const end = content.indexOf(\"\\n---\", 4);\n if (end !== -1) {\n const yaml = content.slice(4, end);\n let inTagsList = false;\n for (const line of yaml.split(\"\\n\")) {\n // Multi-line tags list item: \" - tagname\"\n if (inTagsList) {\n const listItem = line.match(/^\\s+-\\s+(.+)/);\n if (listItem) {\n const trimmed = listItem[1].trim();\n if (trimmed) tags.add(trimmed);\n continue;\n }\n inTagsList = false;\n }\n\n const match = line.match(/^([\\p{L}\\p{N}_][\\p{L}\\p{M}\\p{N}_-]*)\\s*:\\s*(.+)/u);\n if (match) {\n frontmatter[match[1]] = match[2].trim();\n }\n // Frontmatter tags (inline: [a, b] or start of multi-line list)\n if (/^tags\\s*:/.test(line)) {\n const value = line.replace(/^tags\\s*:\\s*/, \"\").trim();\n if (value) {\n // Inline: tags: [a, b] or tags: a, b\n const tagValues = value.replace(/[[\\]]/g, \"\");\n for (const t of tagValues.split(\",\")) {\n const trimmed = t.trim();\n if (trimmed) tags.add(trimmed);\n }\n } else {\n // Multi-line list follows\n inTagsList = true;\n }\n }\n }\n }\n }\n\n // Inline #tags. Obsidian does not read tags out of code, and a tag must\n // contain at least one non-numerical character (\"#1984 isn't a valid tag,\n // but #y1984 is\" — obsidian.md/help/tags), so code spans and fenced blocks\n // are masked out first and all-digit matches are dropped.\n for (const match of maskCode(content).matchAll(/(^|\\s)#([\\p{L}\\p{N}_/-][\\p{L}\\p{M}\\p{N}_/-]*)/gu)) {\n if (/^\\p{Nd}+$/u.test(match[2])) continue;\n tags.add(match[2]);\n }\n\n for (const match of content.matchAll(WIKILINK)) links.push(match[1]);\n for (const match of content.matchAll(NOTE_LINK)) links.push(match[1]);\n addAttachmentLinks(content, links);\n\n return { frontmatter, tags: [...tags], links: [...new Set(links)] };\n}\n\n/**\n * Add the attachment targets of markdown links in `text` to `links`, recorded\n * URL-decoded so list_attachments can tell which files are still used. Also\n * looks inside each link's text once, since matches don't overlap and the\n * outer link of [![thumb](t.png)](full.png) would hide the inner image.\n */\nfunction addAttachmentLinks(text: string, links: string[], nested = false): void {\n for (const match of text.matchAll(ATTACHMENT_LINK)) {\n if (!nested && match[1].includes(\"[\")) addAttachmentLinks(match[1], links, true);\n // Drop a #page=2 fragment, as for wikilinks. Before decoding, since a\n // literal # in a file name is written %23.\n let target = match[2].replace(/^<|>$/g, \"\").replace(/#.*$/, \"\");\n if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.endsWith(\".md\")) continue;\n // Obsidian URL-decodes markdown link targets (a literal % is written %25).\n try { target = decodeURIComponent(target); } catch { continue; }\n target = target.replace(/^(\\.\\.?\\/)+/, \"\");\n if (isValidAttachmentPath(target)) links.push(target);\n }\n}\n\n/**\n * Replace fenced code blocks (``` or ~~~, opener at line start with up to three\n * spaces of indent, closer of the same character and at least the same length;\n * an unclosed fence runs to the end) and inline code spans (a backtick run of\n * length n closes at the next run of exactly n within the same paragraph — a\n * span never crosses a blank line; an unmatched run is literal)\n * with dots, so offsets are preserved and nothing inside can start or extend a\n * tag. Indented code blocks, %% comments and math are not masked.\n */\nexport function maskCode(content: string): string {\n const lines = content.split(\"\\n\");\n const out: string[] = [];\n let fence: { char: string; len: number } | null = null;\n const inline: string[] = [];\n const flushInline = () => {\n if (inline.length === 0) return;\n out.push(...maskInlineSpans(inline.join(\"\\n\")).split(\"\\n\"));\n inline.length = 0;\n };\n for (const line of lines) {\n const open = line.match(/^ {0,3}(`{3,}|~{3,})/);\n if (fence) {\n const close = open && open[1][0] === fence.char && open[1].length >= fence.len && line.trim() === open[1];\n out.push(\".\".repeat(line.length));\n if (close) fence = null;\n continue;\n }\n if (open && (open[1][0] === \"~\" || !line.slice(open[0].length).includes(\"`\"))) {\n flushInline();\n fence = { char: open[1][0], len: open[1].length };\n out.push(\".\".repeat(line.length));\n continue;\n }\n if (line.trim() === \"\") {\n flushInline();\n out.push(line);\n continue;\n }\n inline.push(line);\n }\n flushInline();\n return out.join(\"\\n\");\n}\n\nfunction maskInlineSpans(text: string): string {\n // Collect backtick runs in one pass, then link each run to the next run of\n // the same length (scanning right to left) so matching stays linear.\n const runs: { at: number; len: number }[] = [];\n for (let i = 0; i < text.length; ) {\n if (text[i] !== \"`\") { i++; continue; }\n let n = 0;\n while (text[i + n] === \"`\") n++;\n runs.push({ at: i, len: n });\n i += n;\n }\n const next: number[] = [];\n const seen = new Map<number, number>();\n for (let r = runs.length - 1; r >= 0; r--) {\n next[r] = seen.get(runs[r].len) ?? -1;\n seen.set(runs[r].len, r);\n }\n let result = \"\";\n let from = 0;\n for (let r = 0; r < runs.length; ) {\n const c = next[r];\n if (c === -1) { r++; continue; }\n const start = runs[r].at;\n const end = runs[c].at + runs[c].len;\n result += text.slice(from, start) + text.slice(start, end).replace(/[^\\n]/g, \".\");\n from = end;\n r = c + 1;\n }\n return result + text.slice(from);\n}\n\nexport function extractSnippet(content: string, query: string, context = 80): string {\n const lower = content.toLowerCase();\n\n // Try exact phrase first\n let idx = lower.indexOf(query.toLowerCase());\n\n // Try to find the smallest span containing all query words\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).map((w) => w.toLowerCase());\n if (words.length > 1) {\n let bestStart = -1;\n let bestLen = Infinity;\n // For each occurrence of the first word, find the nearest span containing all words\n const first = words[0];\n let pos = 0;\n while (pos < lower.length) {\n const start = lower.indexOf(first, pos);\n if (start === -1) break;\n // Find last position needed to include all words from this start\n let spanEnd = start + first.length;\n let allFound = true;\n for (let i = 1; i < words.length; i++) {\n const wi = lower.indexOf(words[i], Math.max(0, start - 200));\n if (wi === -1) { allFound = false; break; }\n spanEnd = Math.max(spanEnd, wi + words[i].length);\n }\n if (allFound) {\n const spanStart = Math.min(start, ...words.map((w) => lower.indexOf(w, Math.max(0, start - 200))).filter((i) => i >= 0));\n const len = spanEnd - spanStart;\n if (len < bestLen) { bestStart = spanStart; bestLen = len; }\n }\n pos = start + 1;\n }\n if (bestStart >= 0 && bestLen <= 500) idx = bestStart;\n }\n }\n\n // Fall back to longest matching word\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).sort((a, b) => b.length - a.length);\n for (const word of words) {\n idx = lower.indexOf(word.toLowerCase());\n if (idx !== -1) break;\n }\n }\n\n if (idx === -1) {\n return content.slice(0, 160) + (content.length > 160 ? \"...\" : \"\");\n }\n const start = Math.max(0, idx - context);\n const end = Math.min(content.length, idx + query.length + context);\n return (start > 0 ? \"...\" : \"\") + content.slice(start, end) + (end < content.length ? \"...\" : \"\");\n}\n","import type { NoteMetadata } from \"./parse.js\";\n\nexport interface NoteInfo extends NoteMetadata {\n path: string;\n size: number;\n ctime: number;\n mtime: number;\n}\n\nexport interface NoteListing {\n path: string;\n mtime: number;\n}\n\nexport interface AttachmentInfo {\n path: string;\n size: number;\n ctime: number;\n mtime: number;\n}\n\n/** An attachment appeared or changed (info), or was deleted (null). */\nexport type AttachmentChangeCallback = (path: string, info: { size: number; mtime: number } | null) => void;\n\nexport interface WriteOptions {\n /** Replace an existing file. Default false. */\n overwrite?: boolean;\n}\n\nexport interface MoveOptions extends WriteOptions {\n /**\n * Largest file a backend may load into memory to move it. CouchDB mode\n * copies the bytes (read, write, delete); local mode renames and ignores it.\n */\n maxBytes?: number;\n}\n\n/** A move would have to load a file larger than `MoveOptions.maxBytes`. */\nexport class AttachmentTooLargeError extends Error {\n constructor(readonly path: string, readonly size: number, readonly limit: number) {\n super(`Attachment is ${size} bytes, over the ${limit}-byte limit for moving it: ${path}`);\n this.name = \"AttachmentTooLargeError\";\n }\n}\n\n/** A copying move wrote the destination but could not delete the source, so both exist. */\nexport class AttachmentMoveIncompleteError extends Error {\n constructor(readonly from: string, readonly to: string) {\n super(`Copied ${from} to ${to}, but could not delete ${from}`);\n this.name = \"AttachmentMoveIncompleteError\";\n }\n}\n\n/** A write or move without `overwrite` found a file already at the destination. */\nexport class AttachmentExistsError extends Error {\n constructor(readonly path: string) {\n super(`Attachment already exists: ${path}`);\n this.name = \"AttachmentExistsError\";\n }\n}\n\nexport interface VaultBackend {\n init(): Promise<void>;\n close(): Promise<void>;\n readNote(path: string): Promise<string | null>;\n writeNote(path: string, content: string): Promise<boolean>;\n deleteNote(path: string): Promise<boolean>;\n moveNote(from: string, to: string): Promise<boolean>;\n getMetadata(path: string): Promise<NoteInfo | null>;\n listNotes(folder?: string): Promise<string[]>;\n listNotesWithMtime(folder?: string): Promise<NoteListing[]>;\n /**\n * Binary attachments (see attachment-path.ts). Paths are validated by the backend too.\n * Without `overwrite`, writing or moving onto an existing file throws\n * AttachmentExistsError, checked in the same step as the write.\n */\n writeAttachment(path: string, data: Uint8Array, options?: WriteOptions): Promise<boolean>;\n deleteAttachment(path: string): Promise<boolean>;\n moveAttachment(from: string, to: string, options?: MoveOptions): Promise<boolean>;\n getAttachmentInfo(path: string): Promise<AttachmentInfo | null>;\n /** Every attachment in the vault. Local mode only; CouchDB mode learns them from the change feed. */\n listAttachments?(): Promise<AttachmentInfo[]>;\n /** `onAttachment` also reports attachment changes, from metadata only (no chunks are loaded). */\n watchChanges?(callback: (path: string, content: string | null, mtime?: number, seq?: string | number) => void, onAttachment?: AttachmentChangeCallback): void;\n /**\n * Catch up on changes since a sequence. Returns the new sequence. CouchDB only.\n * `stats.unreadable` counts documents that could not be decrypted or loaded\n * and were therefore skipped — the caller reports them so \"caught up\" never\n * hides a silent miss.\n */\n catchUp?(since: string, callback: (path: string, content: string | null, mtime?: number) => void, onBatch?: (since: string, processed: number) => Promise<void>, stats?: { unreadable: number }, onAttachment?: AttachmentChangeCallback): Promise<string>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAOM,SAAS,uBAAuB,MAAc,MAAoB;AACrE,QAAM,UAAU,sBAAsB,IAAI;AAC1C,MAAI,YAAY,KAAM,OAAM,IAAI,MAAM,WAAW,IAAI,QAAQ,OAAO,EAAE;AAC1E;AAOO,SAAS,sBAAsB,MAA6B;AAC/D,MAAI,CAAC,QAAQ,KAAK,SAAS,IAAM,QAAO;AACxC,MAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,IAAI,EAAG,QAAO;AAC/E,MAAI,KAAK,SAAS,GAAG,EAAG,QAAO;AAC/B,aAAW,WAAW,KAAK,MAAM,OAAO,GAAG;AACvC,QAAI,YAAY,GAAI,QAAO;AAC3B,QAAI,QAAQ,WAAW,GAAG,EAAG,QAAO;AAAA,EACxC;AACA,SAAO;AACX;AAEO,SAAS,iBAAiB,MAAoB;AACjD,yBAAuB,MAAM,MAAM;AACnC,MAAI,CAAC,KAAK,SAAS,KAAK,GAAG;AACvB,UAAM,IAAI,MAAM,gEAAgE;AAAA,EACpF;AAEA,MAAI,CAAC,KAAK,SAAS,GAAG,KAAK,CAAC,KAAK,SAAS,IAAI,KAAK,oBAAoB,IAAI,KAAK,YAAY,CAAC,GAAG;AAC5F,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACvE;AACJ;AAGO,SAAS,gBAAgB,MAAuB;AACnD,MAAI;AACA,qBAAiB,IAAI;AACrB,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;;;AClEO,IAAM,kCAAqD;AAAA;AAAA,EAE9D;AAAA,EAA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