obsidian-sync-mcp 0.12.1 → 0.13.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
@@ -227,7 +227,7 @@ With `ATTACHMENTS_ENABLED=true`, agents can also store images, PDFs, audio and v
227
227
 
228
228
  The agent then embeds the file in a note with `edit_note`, e.g. `![[Attachments/shot.png]]`.
229
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`.
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` (which also needs the `update` permission under `WRITE_FOLDERS`). 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
231
 
232
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
233
 
@@ -286,7 +286,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
286
286
  | `DISPLAY_TIMEZONE` | Optional | server's zone | IANA time zone for the human-readable half of the server time in `search_notes` status lines (UTC is always printed beside it), e.g. `Europe/Berlin`. An invalid zone falls back to UTC with a warning at startup |
287
287
  | `MCP_REFRESH_DAYS` | Optional | `14` | Days before auth session expires |
288
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. |
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. |
289
+ | `WRITE_FOLDERS` | Optional | — | Comma-separated list of vault-relative folders where agents may write (e.g. `MCP,Inbox`). The whole vault stays readable; paths outside the listed folders are read-only. Add permissions after a colon to limit a folder: `create` (add new files), `update` (change existing files) and `delete` (delete files or move them away), joined with `+`. A folder without permissions gets all three. For example `MCP,Raw:create,Notes:create+update`: anything goes in `MCP`, agents can add to `Raw` but never overwrite, edit, move or delete what is there, and can add and edit in `Notes` but not delete. `move_note` and `move_attachment` need `delete` at the source and `create` at the destination, and never replace an existing note. An attachment is replaced only with `overwrite=true`, which needs both `create` and `update`, so attachments can't be replaced in an `update`-only folder. The most specific folder applies, so `Raw:create,Raw/scratch` makes `Raw/scratch` fully writable; `/` stands for the vault root (`/,Raw:create` makes everything writable except `Raw`). Matching is folder-boundary-aware (`MCP` matches `MCP/note.md` but not `MCP-private/note.md`). Paths are compared the way the vault resolves them: `\` counts as `/`, and a case variant of a folder (`raw/`) gets only what both spellings allow, since LiveSync, macOS and Windows treat them as one folder. The server refuses to start on an unknown permission, a folder listed twice (case variants included) or a folder that can never match. Enforced server-side, unlike `MCP_INSTRUCTIONS`; in local mode, writes, deletes and moves through a symlink (to a file or a folder) are refused while it is set, since the check sees the requested path; reads still follow symlinks. Ignored when `READ_ONLY=true`; unset or empty means the whole vault is writable. |
290
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
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
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 |
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+ // Node polyfills for livesync-commonlib browser globals
3
+ if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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
+
115
+ // src/parse.ts
116
+ import MarkdownIt from "markdown-it";
117
+ import { isAlias, isMap, isScalar, isSeq, parseDocument, visit } from "yaml";
118
+ var PARSER_VERSION = `4:${SUPPORTED_ATTACHMENT_EXTENSIONS.join(",")}`;
119
+ var FRONTMATTER = /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(?:\n|$)/;
120
+ var WIKILINK = /\[\[([^[\]|#\n]+)(?:#[^[\]|\n]*)?(?:\|[^[\]\n]*)?\]\]/g;
121
+ var TAG = /(^|\s)#([\p{L}\p{N}_/-][\p{L}\p{M}\p{N}_/-]*)/gu;
122
+ var markdown = new MarkdownIt({ html: true, linkify: false });
123
+ var backticksAt = markdown.inline.ruler.__find__("backticks");
124
+ if (backticksAt === -1) console.warn("markdown-it has no backticks rule: links and tags inside `code` will be indexed.");
125
+ else wrapBackticks(markdown.inline.ruler.__rules__[backticksAt].fn);
126
+ function wrapBackticks(backticks) {
127
+ markdown.inline.ruler.at("backticks", (state, silent) => {
128
+ const start = state.pos;
129
+ const tokens = state.tokens.length;
130
+ if (!backticks(state, silent)) return false;
131
+ if (!silent && state.tokens.length > tokens && state.tokens.at(-1)?.type === "code_inline") {
132
+ const spans = state.env.codeSpans;
133
+ if (!spans.has(state.src)) spans.set(state.src, /* @__PURE__ */ new Map());
134
+ spans.get(state.src).set(start, state.pos);
135
+ }
136
+ return true;
137
+ });
138
+ }
139
+ function parseFrontmatterAndLinks(content) {
140
+ content = content.replace(/\r\n/g, "\n");
141
+ const fm = content.match(FRONTMATTER);
142
+ const yaml = fm?.[1] ?? "";
143
+ const body = fm ? content.slice(fm[0].length) : content;
144
+ const { frontmatter, tags: yamlTags, error } = readFrontmatter(yaml);
145
+ const { text, links } = readBody(body);
146
+ const tags = new Set(yamlTags);
147
+ for (const match of (yaml + "\n" + text).matchAll(WIKILINK)) {
148
+ links.push(match[1].replace(/\\$/, ""));
149
+ }
150
+ for (const match of text.matchAll(TAG)) {
151
+ if (!new RegExp("^\\p{Nd}+$", "u").test(match[2])) tags.add(match[2]);
152
+ }
153
+ const metadata = { frontmatter, tags: [...tags], links: [...new Set(links)] };
154
+ if (error) metadata.frontmatterError = error;
155
+ return metadata;
156
+ }
157
+ function readFrontmatter(yaml) {
158
+ const frontmatter = {};
159
+ const tags = [];
160
+ const doc = parseDocument(yaml, { schema: "failsafe", uniqueKeys: false });
161
+ if (doc.errors.length > 0) return { frontmatter, tags, error: doc.errors[0].message.split("\n")[0].replace(/:$/, "") };
162
+ if (!isMap(doc.contents)) return { frontmatter, tags };
163
+ const resolve = aliasResolver(doc);
164
+ for (const pair of doc.contents.items) {
165
+ const key = resolve(pair.key);
166
+ if (!isScalar(key)) continue;
167
+ const value = resolve(pair.value);
168
+ const shown = showValue(value, resolve, yaml);
169
+ if (shown) frontmatter[String(key.value)] = shown;
170
+ if (key.value !== "tags") continue;
171
+ const raw = isScalar(value) ? String(value.value).split(/[,\n]/) : isSeq(value) ? scalars(value, resolve) : [];
172
+ for (const tag of raw) if (tag.trim()) tags.push(tag.trim());
173
+ }
174
+ return { frontmatter, tags };
175
+ }
176
+ function aliasResolver(doc) {
177
+ const anchors = /* @__PURE__ */ new Map();
178
+ const targets = /* @__PURE__ */ new Map();
179
+ visit(doc, {
180
+ Node(_, node) {
181
+ if (isAlias(node)) targets.set(node, anchors.get(node.source));
182
+ else if (node.anchor) anchors.set(node.anchor, node);
183
+ }
184
+ });
185
+ return (node) => isAlias(node) ? targets.get(node) : node;
186
+ }
187
+ function scalars(seq, resolve) {
188
+ return seq.items.map(resolve).filter(isScalar).map((item) => String(item.value ?? ""));
189
+ }
190
+ function showValue(value, resolve, yaml) {
191
+ if (isScalar(value)) return String(value.value ?? "");
192
+ if (isSeq(value) && value.items.every((item) => isScalar(resolve(item)))) return scalars(value, resolve).join(", ");
193
+ if ((isMap(value) || isSeq(value)) && value.range) return yaml.slice(value.range[0], value.range[1]).trim();
194
+ return "";
195
+ }
196
+ var CONTAINERS = /* @__PURE__ */ new Set(["blockquote_open", "bullet_list_open", "ordered_list_open", "list_item_open"]);
197
+ function readBody(body) {
198
+ const env = { codeSpans: /* @__PURE__ */ new Map() };
199
+ const tokens = markdown.parse(body, env);
200
+ const lines = body.split("\n");
201
+ const parts = [];
202
+ const links = [];
203
+ const claimed = /* @__PURE__ */ new Set();
204
+ let row = { line: 0, cells: 0 };
205
+ for (const token of tokens) {
206
+ if (token.map && !CONTAINERS.has(token.type)) {
207
+ for (let line = token.map[0]; line < token.map[1]; line++) claimed.add(line);
208
+ }
209
+ switch (token.type) {
210
+ case "inline":
211
+ parts.push(blankOut(token.content, env.codeSpans.get(token.content)));
212
+ addTargets(token.children ?? [], links);
213
+ break;
214
+ case "html_block":
215
+ parts.push(token.content);
216
+ addTargets(markdown.parseInline(token.content, env)[0].children ?? [], links);
217
+ break;
218
+ case "code_block":
219
+ parts.push(token.content);
220
+ break;
221
+ case "tr_open":
222
+ row = { line: token.map[0], cells: 0 };
223
+ break;
224
+ case "th_open":
225
+ case "td_open":
226
+ row.cells++;
227
+ break;
228
+ case "tr_close":
229
+ if (countCells(lines[row.line]) > row.cells) {
230
+ parts.push(lines[row.line]);
231
+ addTargets(markdown.parseInline(lines[row.line], env)[0].children ?? [], links);
232
+ }
233
+ break;
234
+ }
235
+ }
236
+ lines.forEach((line, i) => {
237
+ if (!claimed.has(i)) parts.push(line);
238
+ });
239
+ return { text: parts.join("\n"), links };
240
+ }
241
+ function countCells(line) {
242
+ return line.trim().replace(/^\||(?<!\\)\|$/g, "").split(/(?<!\\)\|/).length;
243
+ }
244
+ function blankOut(text, spans = /* @__PURE__ */ new Map()) {
245
+ let out = "";
246
+ let from = 0;
247
+ for (const [start, end] of [...spans].sort((a, b) => a[0] - b[0])) {
248
+ out += text.slice(from, start) + text.slice(start, end).replace(/[^\n]/g, "|");
249
+ from = end;
250
+ }
251
+ return out + text.slice(from);
252
+ }
253
+ function addTargets(tokens, links) {
254
+ for (const token of tokens) {
255
+ if (token.type === "link_open") addTarget(token.attrGet("href"), links);
256
+ if (token.type === "image") {
257
+ addTarget(token.attrGet("src"), links);
258
+ addTargets(token.children ?? [], links);
259
+ }
260
+ }
261
+ }
262
+ function addTarget(href, links) {
263
+ let target = String(href ?? "").replace(/#.*$/, "");
264
+ if (!target || /^[a-z][a-z0-9+.-]*:/i.test(target)) return;
265
+ try {
266
+ target = decodeURIComponent(target);
267
+ } catch {
268
+ return;
269
+ }
270
+ target = target.replace(/^(\.\.?\/)+/, "");
271
+ if (target.endsWith(".md") || isValidAttachmentPath(target)) links.push(target);
272
+ }
273
+
274
+ // src/vault-backend.ts
275
+ var NoteExistsError = class extends Error {
276
+ constructor(path) {
277
+ super(`Note already exists: ${path}`);
278
+ this.path = path;
279
+ this.name = "NoteExistsError";
280
+ }
281
+ };
282
+ var NoteNotFoundError = class extends Error {
283
+ constructor(path) {
284
+ super(`Note not found: ${path}`);
285
+ this.path = path;
286
+ this.name = "NoteNotFoundError";
287
+ }
288
+ };
289
+ var AttachmentTooLargeError = class extends Error {
290
+ constructor(path, size, limit) {
291
+ super(`Attachment is ${size} bytes, over the ${limit}-byte limit for moving it: ${path}`);
292
+ this.path = path;
293
+ this.size = size;
294
+ this.limit = limit;
295
+ this.name = "AttachmentTooLargeError";
296
+ }
297
+ };
298
+ var AttachmentMoveIncompleteError = class extends Error {
299
+ constructor(from, to) {
300
+ super(`Copied ${from} to ${to}, but could not delete ${from}`);
301
+ this.from = from;
302
+ this.to = to;
303
+ this.name = "AttachmentMoveIncompleteError";
304
+ }
305
+ };
306
+ var AttachmentExistsError = class extends Error {
307
+ constructor(path) {
308
+ super(`Attachment already exists: ${path}`);
309
+ this.path = path;
310
+ this.name = "AttachmentExistsError";
311
+ }
312
+ };
313
+
314
+ export {
315
+ __reExport,
316
+ validateNotePath,
317
+ isValidNotePath,
318
+ parseAttachmentExtensions,
319
+ attachmentExtension,
320
+ validateAttachmentPath,
321
+ isValidAttachmentPath,
322
+ PARSER_VERSION,
323
+ parseFrontmatterAndLinks,
324
+ NoteExistsError,
325
+ NoteNotFoundError,
326
+ AttachmentTooLargeError,
327
+ AttachmentMoveIncompleteError,
328
+ AttachmentExistsError
329
+ };
330
+ //# sourceMappingURL=chunk-IQ2E4UFT.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 MarkdownIt, { type StateInline, type Token } from \"markdown-it\";\nimport { isAlias, isMap, isScalar, isSeq, parseDocument, visit, type Document, type YAMLSeq } from \"yaml\";\nimport { SUPPORTED_ATTACHMENT_EXTENSIONS, isValidAttachmentPath } from \"./attachment-path.js\";\n\n/**\n * Changes whenever parseFrontmatterAndLinks may return something different for\n * the same note, so metadata the search index saved from an older parser is\n * parsed again, not reused. Bump the number when changing the parser; the\n * attachment extensions are part of it because they decide which link targets\n * count.\n */\nexport const PARSER_VERSION = `4:${SUPPORTED_ATTACHMENT_EXTENSIONS.join(\",\")}`;\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n /** Why the frontmatter was ignored, when it isn't valid YAML. */\n frontmatterError?: string;\n}\n\n// Frontmatter: a \"---\" first line up to the next line that is just \"---\".\nconst FRONTMATTER = /^---[ \\t]*\\n(?:([\\s\\S]*?)\\n)?---[ \\t]*(?:\\n|$)/;\n\n// [[wikilinks]] and ![[embeds]], which markdown doesn't know. A #heading,\n// #^block or #page=2 suffix points into the target, so [[Note#Heading]] links\n// Note; [[#Heading]] (same note) is not a link. Each part stops at a bracket\n// or newline, so a failed match only scans up to the next one.\nconst WIKILINK = /\\[\\[([^[\\]|#\\n]+)(?:#[^[\\]|\\n]*)?(?:\\|[^[\\]\\n]*)?\\]\\]/g;\n\n// Inline #tags. A tag must contain at least one non-numerical character\n// (\"#1984 isn't a valid tag, but #y1984 is\" — obsidian.md/help/tags).\nconst TAG = /(^|\\s)#([\\p{L}\\p{N}_/-][\\p{L}\\p{M}\\p{N}_/-]*)/gu;\n\n// CommonMark plus GFM tables. Raw HTML is recognised, so a backtick inside a\n// tag's attribute can't open a code span.\nconst markdown = new MarkdownIt({ html: true, linkify: false });\n\n// markdown-it doesn't say where a code span sits in its block's text, so its\n// backticks rule is wrapped to record that: env.codeSpans maps a block's\n// inline source to its code spans, start offset to end. Blocks with the same\n// text have the same spans and share an entry. __rules__ and __find__ are\n// internal, which is why markdown-it is pinned to an exact version; should the\n// rule go missing, links in code spans are indexed rather than failing startup.\ntype Env = { codeSpans: Map<string, Map<number, number>> };\nconst backticksAt = markdown.inline.ruler.__find__(\"backticks\");\nif (backticksAt === -1) console.warn(\"markdown-it has no backticks rule: links and tags inside `code` will be indexed.\");\nelse wrapBackticks(markdown.inline.ruler.__rules__[backticksAt].fn);\n\nfunction wrapBackticks(backticks: (state: StateInline, silent: boolean) => boolean): void {\n markdown.inline.ruler.at(\"backticks\", (state, silent) => {\n const start = state.pos;\n const tokens = state.tokens.length;\n if (!backticks(state, silent)) return false;\n // A run with no closing run is literal text (no token is pushed), and the\n // rule also runs silently while markdown-it scans ahead; neither is a span.\n if (!silent && state.tokens.length > tokens && state.tokens.at(-1)?.type === \"code_inline\") {\n const spans = (state.env as Env).codeSpans;\n if (!spans.has(state.src)) spans.set(state.src, new Map());\n spans.get(state.src)!.set(start, state.pos);\n }\n return true;\n });\n}\n\nexport function parseFrontmatterAndLinks(content: string): NoteMetadata {\n content = content.replace(/\\r\\n/g, \"\\n\");\n const fm = content.match(FRONTMATTER);\n const yaml = fm?.[1] ?? \"\";\n const body = fm ? content.slice(fm[0].length) : content;\n\n const { frontmatter, tags: yamlTags, error } = readFrontmatter(yaml);\n const { text, links } = readBody(body);\n const tags = new Set(yamlTags);\n // Wikilinks in properties (related: \"[[Note]]\") count too.\n for (const match of (yaml + \"\\n\" + text).matchAll(WIKILINK)) {\n // [[note\\|alias]] outside a table: the backslash escapes the pipe.\n links.push(match[1].replace(/\\\\$/, \"\"));\n }\n for (const match of text.matchAll(TAG)) {\n if (!/^\\p{Nd}+$/u.test(match[2])) tags.add(match[2]);\n }\n const metadata: NoteMetadata = { frontmatter, tags: [...tags], links: [...new Set(links)] };\n if (error) metadata.frontmatterError = error;\n return metadata;\n}\n\n/**\n * Frontmatter as YAML (\"failsafe\": every value is a string as written, so 1.10\n * stays 1.10 and dates aren't converted). A list of plain values is joined\n * with \", \", anything else is kept as written. Tags come from `tags`: a list,\n * or a string of comma- or line-separated tags. Frontmatter that isn't valid\n * YAML is ignored, as Obsidian does.\n */\nfunction readFrontmatter(yaml: string): { frontmatter: Record<string, string>; tags: string[]; error?: string } {\n const frontmatter: Record<string, string> = {};\n const tags: string[] = [];\n const doc = parseDocument(yaml, { schema: \"failsafe\", uniqueKeys: false });\n // The first line of yaml's message, without the snippet it introduces:\n // \"Invalid escape sequence \\Users\\me\" at line 1, column 10\".\n if (doc.errors.length > 0) return { frontmatter, tags, error: doc.errors[0].message.split(\"\\n\")[0].replace(/:$/, \"\") };\n if (!isMap(doc.contents)) return { frontmatter, tags };\n\n const resolve = aliasResolver(doc);\n for (const pair of doc.contents.items) {\n const key = resolve(pair.key);\n if (!isScalar(key)) continue;\n const value = resolve(pair.value);\n const shown = showValue(value, resolve, yaml);\n if (shown) frontmatter[String(key.value)] = shown;\n if (key.value !== \"tags\") continue;\n const raw = isScalar(value) ? String(value.value).split(/[,\\n]/) : isSeq(value) ? scalars(value, resolve) : [];\n for (const tag of raw) if (tag.trim()) tags.push(tag.trim());\n }\n return { frontmatter, tags };\n}\n\ntype Resolve = (node: unknown) => unknown;\n\n/**\n * Resolve aliases (*name) to the node they point to: the last node before\n * them with that anchor. Worked out in one pass, since yaml's Alias.resolve\n * rescans the whole document on every call.\n */\nfunction aliasResolver(doc: Document): Resolve {\n const anchors = new Map<string, unknown>();\n const targets = new Map<unknown, unknown>();\n visit(doc, {\n Node(_, node) {\n if (isAlias(node)) targets.set(node, anchors.get(node.source));\n else if (node.anchor) anchors.set(node.anchor, node);\n },\n });\n return (node) => (isAlias(node) ? targets.get(node) : node);\n}\n\n/** The plain values in a list, skipping nested lists and maps. */\nfunction scalars(seq: YAMLSeq, resolve: Resolve): string[] {\n return seq.items.map(resolve).filter(isScalar).map((item) => String(item.value ?? \"\"));\n}\n\n/** A value as get_note_info shows it: as is, a plain list joined, else as written. */\nfunction showValue(value: unknown, resolve: Resolve, yaml: string): string {\n if (isScalar(value)) return String(value.value ?? \"\");\n if (isSeq(value) && value.items.every((item) => isScalar(resolve(item)))) return scalars(value, resolve).join(\", \");\n if ((isMap(value) || isSeq(value)) && value.range) return yaml.slice(value.range[0], value.range[1]).trim();\n return \"\";\n}\n\n// Blocks that only hold other blocks; their lines are claimed by what's inside.\nconst CONTAINERS = new Set([\"blockquote_open\", \"bullet_list_open\", \"ordered_list_open\", \"list_item_open\"]);\n\n/**\n * The note's markdown link and image targets, and its source text with code\n * left out, for the wikilink and tag patterns: each block's raw text with its\n * code spans blanked out, and as written, raw HTML blocks (whose markdown\n * links count too), indented code, table rows with more cells than the header\n * (markdown-it drops the extra ones) and the lines no block claims (reference\n * and footnote definitions). Indented code is read because markdown-it\n * doesn't know footnotes, whose continuation lines are indented. Fenced code\n * is left out, as Obsidian doesn't link or tag inside code.\n */\nfunction readBody(body: string): { text: string; links: string[] } {\n const env: Env = { codeSpans: new Map() };\n const tokens = markdown.parse(body, env);\n const lines = body.split(\"\\n\");\n const parts: string[] = [];\n const links: string[] = [];\n const claimed = new Set<number>();\n let row = { line: 0, cells: 0 };\n for (const token of tokens) {\n if (token.map && !CONTAINERS.has(token.type)) {\n for (let line = token.map[0]; line < token.map[1]; line++) claimed.add(line);\n }\n switch (token.type) {\n case \"inline\":\n parts.push(blankOut(token.content, env.codeSpans.get(token.content)));\n addTargets(token.children ?? [], links);\n break;\n case \"html_block\":\n // Markdown inside HTML isn't rendered, but a ![](img.png)\n // there still marks the file as used.\n parts.push(token.content);\n addTargets(markdown.parseInline(token.content, env)[0].children ?? [], links);\n break;\n case \"code_block\":\n parts.push(token.content);\n break;\n case \"tr_open\":\n row = { line: token.map![0], cells: 0 };\n break;\n case \"th_open\":\n case \"td_open\":\n row.cells++;\n break;\n case \"tr_close\":\n if (countCells(lines[row.line]) > row.cells) {\n parts.push(lines[row.line]);\n addTargets(markdown.parseInline(lines[row.line], env)[0].children ?? [], links);\n }\n break;\n }\n }\n lines.forEach((line, i) => {\n if (!claimed.has(i)) parts.push(line);\n });\n return { text: parts.join(\"\\n\"), links };\n}\n\n/** The cells in a table row as written: split at unescaped pipes, outer pipes optional. */\nfunction countCells(line: string): number {\n return line.trim().replace(/^\\||(?<!\\\\)\\|$/g, \"\").split(/(?<!\\\\)\\|/).length;\n}\n\n/**\n * Replace the code spans in `text` with \"|\", which can't start a tag or a\n * wikilink target, so `x`#tag isn't a tag and [[`Note`]] isn't a link while\n * [[note|`alias`]] still links note. Newlines are kept.\n */\nfunction blankOut(text: string, spans: Map<number, number> = new Map()): string {\n let out = \"\";\n let from = 0;\n for (const [start, end] of [...spans].sort((a, b) => a[0] - b[0])) {\n out += text.slice(from, start) + text.slice(start, end).replace(/[^\\n]/g, \"|\");\n from = end;\n }\n return out + text.slice(from);\n}\n\n/**\n * Add the targets of the markdown links and images among `tokens` to `links`.\n * A link's text is among its siblings, but an image's alt text is in its\n * children, where another image can be.\n */\nfunction addTargets(tokens: Token[], links: string[]): void {\n for (const token of tokens) {\n if (token.type === \"link_open\") addTarget(token.attrGet(\"href\"), links);\n if (token.type === \"image\") {\n addTarget(token.attrGet(\"src\"), links);\n addTargets(token.children ?? [], links);\n }\n }\n}\n\n/**\n * Record a markdown link target: a note (.md) or an attachment, URL-decoded as\n * Obsidian does, so list_attachments can tell which files are still used.\n * External URLs and same-note #heading links are skipped.\n */\nfunction addTarget(href: string | number | null, links: string[]): void {\n // Drop a #heading or #page=2 fragment. Before decoding, since a literal #\n // in a file name is written %23.\n let target = String(href ?? \"\").replace(/#.*$/, \"\");\n if (!target || /^[a-z][a-z0-9+.-]*:/i.test(target)) return;\n try { target = decodeURIComponent(target); } catch { return; }\n target = target.replace(/^(\\.\\.?\\/)+/, \"\");\n if (target.endsWith(\".md\") || isValidAttachmentPath(target)) links.push(target);\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 NoteWriteOptions {\n /**\n * \"upsert\" (default) creates or replaces. \"create\" refuses an existing note\n * (NoteExistsError) and \"update\" refuses a missing one (NoteNotFoundError),\n * each checked in the same step as the write.\n */\n mode?: \"upsert\" | \"create\" | \"update\";\n}\n\n/** A create-only write or a move found a note already at the path. */\nexport class NoteExistsError extends Error {\n constructor(readonly path: string) {\n super(`Note already exists: ${path}`);\n this.name = \"NoteExistsError\";\n }\n}\n\n/** An update-only write found no note at the path. */\nexport class NoteNotFoundError extends Error {\n constructor(readonly path: string) {\n super(`Note not found: ${path}`);\n this.name = \"NoteNotFoundError\";\n }\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, options?: NoteWriteOptions): Promise<boolean>;\n deleteNote(path: string): Promise<boolean>;\n /** Never replaces a note at `to`: throws NoteExistsError instead, checked in the same step as the move. */\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;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