@triplef/obsidian-api 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,106 @@
1
+ # PolyForm Strict License 1.0.0
2
+
3
+ Copyright (c) 2026 Eugen Hildt
4
+
5
+ https://polyformproject.org/licenses/strict/1.0.0
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree
10
+ to them as both strict obligations and conditions to all
11
+ your licenses.
12
+
13
+ ## Copyright License
14
+
15
+ The licensor grants you a copyright license for the software
16
+ to do everything you might do with the software that would
17
+ otherwise infringe the licensor's copyright in it for any
18
+ permitted purpose, other than distributing the software or
19
+ making changes or new works based on the software.
20
+
21
+ ## Patent License
22
+
23
+ The licensor grants you a patent license for the software that
24
+ covers patent claims the licensor can license, or becomes able
25
+ to license, that you would infringe by using the software.
26
+
27
+ ## Noncommercial Purposes
28
+
29
+ Any noncommercial purpose is a permitted purpose.
30
+
31
+ ## Personal Uses
32
+
33
+ Personal use for research, experiment, and testing for
34
+ the benefit of public knowledge, personal study, private
35
+ entertainment, hobby projects, amateur pursuits, or religious
36
+ observance, without any anticipated commercial application,
37
+ is use for a permitted purpose.
38
+
39
+ ## Noncommercial Organizations
40
+
41
+ Use by any charitable organization, educational institution,
42
+ public research organization, public safety or health
43
+ organization, environmental protection organization,
44
+ or government institution is use for a permitted purpose
45
+ regardless of the source of funding or obligations resulting
46
+ from the funding.
47
+
48
+ ## Fair Use
49
+
50
+ You may have "fair use" rights for the software under the
51
+ law. These terms do not limit them.
52
+
53
+ ## No Other Rights
54
+
55
+ These terms do not allow you to sublicense or transfer any of
56
+ your licenses to anyone else, or prevent the licensor from
57
+ granting licenses to anyone else. These terms do not imply
58
+ any other licenses.
59
+
60
+ ## Patent Defense
61
+
62
+ If you make any written claim that the software infringes or
63
+ contributes to infringement of any patent, your patent license
64
+ for the software granted under these terms ends immediately. If
65
+ your company makes such a claim, your patent license ends
66
+ immediately for work on behalf of your company.
67
+
68
+ ## Violations
69
+
70
+ The first time you are notified in writing that you have
71
+ violated any of these terms, or done anything with the software
72
+ not covered by your licenses, your licenses can nonetheless
73
+ continue if you come into full compliance with these terms,
74
+ and take practical steps to correct past violations, within
75
+ 32 days of receiving notice. Otherwise, all your licenses
76
+ end immediately.
77
+
78
+ ## No Liability
79
+
80
+ ***As far as the law allows, the software comes as is, without
81
+ any warranty or condition, and the licensor will not be liable
82
+ to you for any damages arising out of these terms or the use
83
+ or nature of the software, under any kind of legal claim.***
84
+
85
+ ## Definitions
86
+
87
+ The **licensor** is the individual or entity offering these
88
+ terms, and the **software** is the software the licensor makes
89
+ available under these terms.
90
+
91
+ **You** refers to the individual or entity agreeing to these
92
+ terms.
93
+
94
+ **Your company** is any legal entity, sole proprietorship,
95
+ or other kind of organization that you work for, plus all
96
+ organizations that have control over, are under the control of,
97
+ or are under common control with that organization. **Control**
98
+ means ownership of substantially all the assets of an entity,
99
+ or the power to direct its management and policies by vote,
100
+ contract, or otherwise. Control can be direct or indirect.
101
+
102
+ **Your licenses** are all the licenses granted to you for the
103
+ software under these terms.
104
+
105
+ **Use** means anything you do with the software requiring one
106
+ of your licenses.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @triplef/obsidian-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A lean Node.js client for the Obsidian Local REST API plugin.
4
+
5
+ ## Features
6
+
7
+ - Typed server-info, search, read, create, update, delete, and open operations.
8
+ - Bounded HTTP(S) transport with request deadlines, cancellation, and response-size limits.
9
+ - Per-request custom CA support for the plugin's self-signed certificate.
10
+ - Conditional writes using note revisions and non-overwriting creation.
11
+ - Vault-relative path validation and Markdown note-content construction.
12
+ - Structured, non-sensitive errors suitable for agent tools and health checks.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pnpm add @triplef/obsidian-api
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ Create an `ObsidianClient` with the effective connection configuration supplied by the consuming application. The package does not read environment variables or own provider configuration.
23
+
24
+ The client exposes `getServerInfo`, `search`, `read`, `create`, `update`, `delete`, and `open`. Each operation accepts an optional `AbortSignal`; mutation results include the exact vault path and operation-specific confirmation fields.
25
+
26
+ Both the package root and `@triplef/obsidian-api/obsidian-api` expose the same public API.
27
+
28
+ ## Compatibility
29
+
30
+ The client targets the Obsidian Local REST API plugin. Consumers remain responsible for checking plugin and Obsidian desktop versions before enabling operations that require a specific API level.
@@ -0,0 +1,491 @@
1
+ import { request as request$1 } from 'http';
2
+ import { request } from 'https';
3
+
4
+ // src/obsidian-api/obsidian-client-error.constant.ts
5
+ var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
6
+ "CERT_SIGNATURE_FAILURE",
7
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
8
+ "ERR_TLS_CERT_ALTNAME_INVALID",
9
+ "ERR_TLS_CERT_ALTNAME_FORMAT",
10
+ "SELF_SIGNED_CERT_IN_CHAIN",
11
+ "UNABLE_TO_GET_ISSUER_CERT",
12
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
13
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE"
14
+ ]);
15
+
16
+ // src/obsidian-api/obsidian-client-error.ts
17
+ var ObsidianClientError = class _ObsidianClientError extends Error {
18
+ constructor(code, message, status, path) {
19
+ super(message);
20
+ this.code = code;
21
+ this.status = status;
22
+ this.path = path;
23
+ this.name = "ObsidianClientError";
24
+ }
25
+ code;
26
+ status;
27
+ path;
28
+ static from(error, path) {
29
+ if (error instanceof _ObsidianClientError) return error;
30
+ const candidate = error;
31
+ const code = typeof candidate?.code === "string" ? candidate.code : "";
32
+ const message = typeof candidate?.message === "string" ? candidate.message : String(error);
33
+ if (/invalid url/i.test(message)) {
34
+ return new _ObsidianClientError("invalid_input", "Obsidian base URL is invalid", void 0, path);
35
+ }
36
+ if (code === "ETIMEDOUT" || code === "ESOCKETTIMEDOUT") {
37
+ return new _ObsidianClientError("timeout", "Obsidian request timed out", void 0, path);
38
+ }
39
+ if (TLS_ERROR_CODES.has(code) || /certificate|tls|altname/i.test(message)) {
40
+ return new _ObsidianClientError("tls_error", "Obsidian TLS certificate validation failed", void 0, path);
41
+ }
42
+ return new _ObsidianClientError("unreachable", "Obsidian is unreachable", void 0, path);
43
+ }
44
+ };
45
+
46
+ // src/obsidian-api/helpers/has-obsidian-control-characters.helper.ts
47
+ function hasObsidianControlCharacters(value) {
48
+ for (const character of value) {
49
+ if (character.charCodeAt(0) <= 31) return true;
50
+ }
51
+ return false;
52
+ }
53
+
54
+ // src/obsidian-api/helpers/normalize-obsidian-folder.helper.ts
55
+ function normalizeObsidianFolder(value) {
56
+ const raw = value.trim();
57
+ if (raw.includes("\\") || raw.startsWith("/") || /^[a-z]:[\\/]/i.test(raw)) {
58
+ throw new ObsidianClientError(
59
+ "invalid_path",
60
+ "A safe vault-relative destination folder is required",
61
+ void 0,
62
+ value
63
+ );
64
+ }
65
+ const input = raw.replace(/^\/+|\/+$/g, "");
66
+ if (!input) return "";
67
+ const segments = input.split("/");
68
+ if (segments.some(
69
+ (segment) => !segment || segment === "." || segment === ".." || segment.toLowerCase() === ".obsidian" || hasObsidianControlCharacters(segment)
70
+ )) {
71
+ throw new ObsidianClientError(
72
+ "invalid_path",
73
+ "A safe vault-relative destination folder is required",
74
+ void 0,
75
+ value
76
+ );
77
+ }
78
+ if (input.length > 512) {
79
+ throw new ObsidianClientError("invalid_path", "Obsidian folders are limited to 512 characters", void 0, value);
80
+ }
81
+ return input;
82
+ }
83
+
84
+ // src/obsidian-api/helpers/normalize-obsidian-note-path.helper.ts
85
+ function normalizeObsidianNotePath(value) {
86
+ const input = value.trim();
87
+ const invalid = !input || input.includes("\\") || !input.toLowerCase().endsWith(".md") || input.startsWith("/") || /^[a-z]:[\\/]/i.test(input) || input.split("/").some(
88
+ (segment) => !segment || segment === "." || segment === ".." || segment.toLowerCase() === ".obsidian" || hasObsidianControlCharacters(segment)
89
+ );
90
+ if (invalid) {
91
+ throw new ObsidianClientError(
92
+ "invalid_path",
93
+ "A safe vault-relative Markdown note path is required",
94
+ void 0,
95
+ value
96
+ );
97
+ }
98
+ if (input.length > 512) {
99
+ throw new ObsidianClientError(
100
+ "invalid_path",
101
+ "Obsidian note paths are limited to 512 characters",
102
+ void 0,
103
+ value
104
+ );
105
+ }
106
+ return input;
107
+ }
108
+
109
+ // src/obsidian-api/helpers/build-obsidian-note-content.helper.ts
110
+ function buildObsidianNoteContent(content, tags = []) {
111
+ const frontmatter = tags.length ? `---
112
+ tags:
113
+ ${tags.map((tag) => ` - ${JSON.stringify(tag)}`).join("\n")}
114
+ ---
115
+
116
+ ` : "";
117
+ const body = content.trim();
118
+ return `${frontmatter}${body ? `${body}
119
+ ` : ""}`;
120
+ }
121
+
122
+ // src/obsidian-api/helpers/build-obsidian-note-path.helper.ts
123
+ function buildObsidianNotePath(title, folder) {
124
+ const filename = Array.from(title.trim()).filter((character) => !hasObsidianControlCharacters(character)).join("").replace(/[<>:"/\\|?*]/g, "-").replace(/\s+/g, " ").replace(/[. ]+$/g, "").slice(0, 200).trim();
125
+ if (!filename) {
126
+ return normalizeObsidianNotePath("Untitled.md");
127
+ }
128
+ const normalizedFolder = normalizeObsidianFolder(folder);
129
+ return normalizeObsidianNotePath(`${normalizedFolder ? `${normalizedFolder}/` : ""}${filename}.md`);
130
+ }
131
+
132
+ // src/obsidian-api/helpers/encode-obsidian-path.helper.ts
133
+ function encodeObsidianPath(path) {
134
+ return path.split("/").map(encodeURIComponent).join("/");
135
+ }
136
+
137
+ // src/obsidian-api/helpers/normalize-obsidian-version.helper.ts
138
+ function normalizeObsidianVersion(value) {
139
+ const version = value?.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
140
+ if (!version || /[\r\n]/.test(version)) {
141
+ throw new ObsidianClientError("invalid_response", "Obsidian did not return a usable note revision");
142
+ }
143
+ return version;
144
+ }
145
+
146
+ // src/obsidian-api/helpers/resolve-obsidian-status-error.helper.ts
147
+ function resolveObsidianStatusError(status, conflictCode) {
148
+ if (status === 400) return "invalid_input";
149
+ if (status === 401) return "unauthorized";
150
+ if (status === 403) return "forbidden";
151
+ if (status === 404) return "not_found";
152
+ if (status === 409 || status === 412) return conflictCode;
153
+ return "http_error";
154
+ }
155
+
156
+ // src/obsidian-api/obsidian-client.constant.ts
157
+ var MAX_NOTE_CHARS = 2e5;
158
+ var MAX_METADATA_RESPONSE_BYTES = 1e5;
159
+ var MAX_READ_RESPONSE_BYTES = 1e6;
160
+ var DEFAULT_SEARCH_MAX_RESULTS = 20;
161
+ var DEFAULT_SEARCH_MAX_MATCHES_PER_FILE = 5;
162
+ var DEFAULT_SEARCH_CONTEXT_LENGTH = 200;
163
+ var OBSIDIAN_STATUS_ERROR_MESSAGES = {
164
+ invalid_input: "Obsidian rejected the request",
165
+ unauthorized: "Obsidian rejected the API key",
166
+ forbidden: "Obsidian refused access to this path",
167
+ not_found: "Obsidian note was not found",
168
+ already_exists: "Obsidian note already exists",
169
+ revision_conflict: "Obsidian note changed; re-read it before retrying"
170
+ };
171
+
172
+ // src/obsidian-api/obsidian-request.constant.ts
173
+ var DEFAULT_MAX_RESPONSE_BYTES = 1e6;
174
+
175
+ // src/obsidian-api/obsidian-request.transport.ts
176
+ function obsidianRequest(config, options) {
177
+ const url = new URL(config.baseUrl);
178
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) {
179
+ return Promise.reject(
180
+ new ObsidianClientError(
181
+ "invalid_input",
182
+ "Obsidian base URL must be an HTTP(S) URL without credentials or fragments"
183
+ )
184
+ );
185
+ }
186
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${options.path}`;
187
+ for (const [key, value] of Object.entries(options.query ?? {})) {
188
+ if (value !== void 0) url.searchParams.set(key, String(value));
189
+ }
190
+ if (options.signal?.aborted) {
191
+ return Promise.reject(new ObsidianClientError("unreachable", "Obsidian request was aborted"));
192
+ }
193
+ const headers = {
194
+ Accept: "application/json, text/markdown",
195
+ Authorization: `Bearer ${config.apiKey ?? ""}`,
196
+ ...options.headers
197
+ };
198
+ if (options.body !== void 0) {
199
+ headers["Content-Length"] = String(Buffer.byteLength(options.body));
200
+ }
201
+ return new Promise((resolve, reject) => {
202
+ const fail = (error) => {
203
+ if (totalTimeout) clearTimeout(totalTimeout);
204
+ reject(ObsidianClientError.from(error));
205
+ };
206
+ const request$2 = (url.protocol === "https:" ? request : request$1)(
207
+ url,
208
+ {
209
+ method: options.method,
210
+ headers,
211
+ timeout: config.requestTimeoutMs,
212
+ signal: options.signal,
213
+ agent: false,
214
+ ...url.protocol === "https:" && config.caCertificate ? { ca: config.caCertificate } : {}
215
+ },
216
+ (response) => {
217
+ const chunks = [];
218
+ let bytes = 0;
219
+ response.on("data", (chunk) => {
220
+ if (options.discardBody) return;
221
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
222
+ bytes += buffer.length;
223
+ if (bytes > (options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES)) {
224
+ fail(new ObsidianClientError("response_too_large", "Obsidian response exceeded the safe size limit"));
225
+ response.destroy();
226
+ return;
227
+ }
228
+ chunks.push(buffer);
229
+ });
230
+ response.on("error", fail);
231
+ response.on("aborted", () => fail(new ObsidianClientError("unreachable", "Obsidian response was interrupted")));
232
+ response.on("end", () => {
233
+ if (totalTimeout) clearTimeout(totalTimeout);
234
+ if (!response.complete) {
235
+ fail(new ObsidianClientError("unreachable", "Obsidian response was incomplete"));
236
+ return;
237
+ }
238
+ resolve({
239
+ status: response.statusCode ?? 0,
240
+ headers: response.headers,
241
+ body: Buffer.concat(chunks).toString("utf8")
242
+ });
243
+ });
244
+ }
245
+ );
246
+ request$2.on("timeout", () => {
247
+ request$2.destroy(new ObsidianClientError("timeout", "Obsidian request timed out"));
248
+ });
249
+ request$2.on("error", fail);
250
+ const totalTimeout = setTimeout(() => {
251
+ request$2.destroy(new ObsidianClientError("timeout", "Obsidian request timed out"));
252
+ }, config.requestTimeoutMs);
253
+ if (options.body !== void 0) request$2.write(options.body);
254
+ request$2.end();
255
+ });
256
+ }
257
+
258
+ // src/obsidian-api/obsidian-client.ts
259
+ var ObsidianClient = class {
260
+ constructor(config) {
261
+ this.config = config;
262
+ }
263
+ config;
264
+ /** Fetch plugin identity, authentication, and version information. */
265
+ async getServerInfo(signal) {
266
+ const response = await obsidianRequest(this.config, {
267
+ method: "GET",
268
+ path: "/",
269
+ signal,
270
+ maxResponseBytes: MAX_METADATA_RESPONSE_BYTES
271
+ });
272
+ this.assertStatus(response, 200);
273
+ return this.parseJson(response);
274
+ }
275
+ /** Execute a bounded simple search and normalize its matches. */
276
+ async search(input, signal) {
277
+ const response = await obsidianRequest(this.config, {
278
+ method: "POST",
279
+ path: "/search/simple/",
280
+ signal,
281
+ query: {
282
+ query: input.query,
283
+ maxResults: input.maxResults ?? DEFAULT_SEARCH_MAX_RESULTS,
284
+ maxMatchesPerFile: input.maxMatchesPerFile ?? DEFAULT_SEARCH_MAX_MATCHES_PER_FILE,
285
+ contextLength: input.contextLength ?? DEFAULT_SEARCH_CONTEXT_LENGTH
286
+ }
287
+ });
288
+ this.assertStatus(response, 200);
289
+ const data = this.parseJson(response);
290
+ const valid = Array.isArray(data) && data.every(
291
+ (entry) => entry && typeof entry.filename === "string" && typeof entry.score === "number" && (entry.matches ?? []).every(
292
+ (match) => typeof match.context === "string" && Number.isFinite(match.match?.start) && Number.isFinite(match.match?.end)
293
+ )
294
+ );
295
+ if (!valid) {
296
+ throw new ObsidianClientError(
297
+ "invalid_response",
298
+ "Obsidian returned an invalid search response",
299
+ response.status
300
+ );
301
+ }
302
+ const allResults = data.map((entry) => ({
303
+ path: entry.filename,
304
+ score: entry.score,
305
+ totalMatches: entry.totalMatches,
306
+ matches: (entry.matches ?? []).map((match) => ({
307
+ context: match.context,
308
+ start: match.match.start,
309
+ end: match.match.end
310
+ }))
311
+ }));
312
+ const results = allResults.filter((entry) => entry.path.toLowerCase().endsWith(".md"));
313
+ const reportedTotal = Number(this.header(response, "total-results"));
314
+ const totalResults = Number.isFinite(reportedTotal) && reportedTotal >= 0 ? reportedTotal : results.length;
315
+ return {
316
+ ok: true,
317
+ query: input.query,
318
+ results,
319
+ totalResults,
320
+ limited: totalResults > results.length || results.some((entry) => entry.totalMatches !== void 0 && entry.totalMatches > entry.matches.length)
321
+ };
322
+ }
323
+ /** Read bounded note content with an optional revision-checked document map. */
324
+ async read(input, signal) {
325
+ const path = normalizeObsidianNotePath(input.path);
326
+ const response = await this.readResponse(path, input.heading, input.scope, signal);
327
+ if (response.body.length > MAX_NOTE_CHARS) {
328
+ throw new ObsidianClientError(
329
+ "response_too_large",
330
+ "Obsidian note exceeds the safe whole-read limit",
331
+ void 0,
332
+ path
333
+ );
334
+ }
335
+ const version = normalizeObsidianVersion(this.header(response, "etag"));
336
+ let documentMap;
337
+ if (input.includeDocumentMap) {
338
+ const mapResponse = await obsidianRequest(this.config, {
339
+ method: "GET",
340
+ path: `/vault/${encodeObsidianPath(path)}`,
341
+ headers: { Accept: "application/vnd.olrapi.document-map+json" },
342
+ signal
343
+ });
344
+ this.assertStatus(mapResponse, 200, path);
345
+ const map = this.parseJson(mapResponse);
346
+ documentMap = {
347
+ headings: map.headings ?? {},
348
+ blocks: map.blocks ?? [],
349
+ frontmatterFields: map.frontmatterFields ?? [],
350
+ version: normalizeObsidianVersion(map.version)
351
+ };
352
+ if (documentMap.version !== version) {
353
+ throw new ObsidianClientError(
354
+ "revision_conflict",
355
+ "Obsidian note changed while it was being read; retry the read",
356
+ 412,
357
+ path
358
+ );
359
+ }
360
+ }
361
+ return { ok: true, path, content: response.body, version, documentMap };
362
+ }
363
+ /** Create one note without overwriting an existing path. */
364
+ async create(input, signal) {
365
+ const path = buildObsidianNotePath(input.title, input.folder ?? this.config.vaultFolder);
366
+ const response = await obsidianRequest(this.config, {
367
+ method: "PUT",
368
+ path: `/vault/${encodeObsidianPath(path)}`,
369
+ signal,
370
+ headers: {
371
+ "Content-Type": "text/markdown; charset=utf-8",
372
+ "If-None-Match": "*"
373
+ },
374
+ body: buildObsidianNoteContent(input.content, input.tags)
375
+ });
376
+ this.assertStatus(response, 204, path, "already_exists");
377
+ return {
378
+ ok: true,
379
+ created: true,
380
+ path,
381
+ version: normalizeObsidianVersion(this.header(response, "etag"))
382
+ };
383
+ }
384
+ /** Replace note content or apply a conditional structured patch. */
385
+ async update(input, signal) {
386
+ const path = normalizeObsidianNotePath(input.path);
387
+ const version = normalizeObsidianVersion(input.version);
388
+ const isReplace = input.mode === "replaceNote";
389
+ const instruction = input.mode === "patchHeading" ? {
390
+ targetType: "heading",
391
+ target: input.target,
392
+ operation: input.operation,
393
+ scope: input.scope ?? "content",
394
+ content: input.content,
395
+ createTargetIfMissing: input.createTargetIfMissing
396
+ } : input.mode === "patchFrontmatter" ? {
397
+ targetType: "frontmatter",
398
+ target: input.target,
399
+ operation: input.operation,
400
+ value: input.value,
401
+ createTargetIfMissing: input.createTargetIfMissing
402
+ } : void 0;
403
+ const response = await obsidianRequest(this.config, {
404
+ method: isReplace ? "PUT" : "PATCH",
405
+ discardBody: !isReplace,
406
+ path: `/vault/${encodeObsidianPath(path)}`,
407
+ signal,
408
+ headers: {
409
+ "Content-Type": isReplace ? "text/markdown; charset=utf-8" : "application/json",
410
+ "If-Match": `"${version}"`
411
+ },
412
+ body: isReplace ? input.content : JSON.stringify(instruction)
413
+ });
414
+ this.assertStatus(response, isReplace ? 204 : 200, path);
415
+ return {
416
+ ok: true,
417
+ updated: true,
418
+ path,
419
+ version: normalizeObsidianVersion(this.header(response, "etag"))
420
+ };
421
+ }
422
+ /** Move an existing note to trash using its current revision. */
423
+ async delete(pathInput, versionInput, signal) {
424
+ const path = normalizeObsidianNotePath(pathInput);
425
+ const version = normalizeObsidianVersion(versionInput);
426
+ const response = await obsidianRequest(this.config, {
427
+ method: "DELETE",
428
+ path: `/vault/${encodeObsidianPath(path)}`,
429
+ signal,
430
+ query: { permanent: "false" },
431
+ headers: { "If-Match": `"${version}"` }
432
+ });
433
+ this.assertStatus(response, 204, path);
434
+ return { ok: true, deleted: true, path, permanent: false };
435
+ }
436
+ /** Verify a note exists before opening it in the Obsidian UI. */
437
+ async open(pathInput, newLeaf = false, signal) {
438
+ const path = normalizeObsidianNotePath(pathInput);
439
+ const existing = await obsidianRequest(this.config, {
440
+ method: "GET",
441
+ path: `/vault/${encodeObsidianPath(path)}`,
442
+ headers: { Accept: "application/vnd.olrapi.document-map+json" },
443
+ maxResponseBytes: MAX_METADATA_RESPONSE_BYTES,
444
+ discardBody: true,
445
+ signal
446
+ });
447
+ this.assertStatus(existing, 200, path);
448
+ const response = await obsidianRequest(this.config, {
449
+ method: "POST",
450
+ path: `/open/${encodeObsidianPath(path)}`,
451
+ signal,
452
+ query: { newLeaf }
453
+ });
454
+ this.assertStatus(response, 200, path);
455
+ return { ok: true, opened: true, path, newLeaf };
456
+ }
457
+ async readResponse(path, heading, scope = "content", signal) {
458
+ const suffix = heading?.length ? `/heading/${heading.map(encodeURIComponent).join("/")}` : "";
459
+ const response = await obsidianRequest(this.config, {
460
+ method: "GET",
461
+ path: `/vault/${encodeObsidianPath(path)}${suffix}`,
462
+ headers: {
463
+ Accept: "text/markdown",
464
+ ...heading?.length ? { "Target-Scope": scope } : {}
465
+ },
466
+ maxResponseBytes: MAX_READ_RESPONSE_BYTES,
467
+ signal
468
+ });
469
+ this.assertStatus(response, 200, path);
470
+ return response;
471
+ }
472
+ header(response, name) {
473
+ const value = response.headers[name];
474
+ return Array.isArray(value) ? value[0] : value;
475
+ }
476
+ parseJson(response) {
477
+ try {
478
+ return JSON.parse(response.body);
479
+ } catch {
480
+ throw new ObsidianClientError("invalid_response", "Obsidian returned invalid JSON", response.status);
481
+ }
482
+ }
483
+ assertStatus(response, expected, path, conflictCode = "revision_conflict") {
484
+ if (response.status === expected) return;
485
+ const code = resolveObsidianStatusError(response.status, conflictCode);
486
+ const message = code === "http_error" ? `Obsidian returned HTTP ${response.status}` : OBSIDIAN_STATUS_ERROR_MESSAGES[code];
487
+ throw new ObsidianClientError(code, message, response.status, path);
488
+ }
489
+ };
490
+
491
+ export { ObsidianClient, ObsidianClientError, normalizeObsidianFolder, normalizeObsidianNotePath };
@@ -0,0 +1 @@
1
+ export { ObsidianClient, ObsidianClientError, ObsidianConfig, ObsidianCreateInput, ObsidianCreateSuccess, ObsidianCreateToolResult, ObsidianDeleteSuccess, ObsidianDeleteToolResult, ObsidianDocumentMap, ObsidianErrorCode, ObsidianErrorResult, ObsidianHttpMethod, ObsidianOpenSuccess, ObsidianOpenToolResult, ObsidianPatchFrontmatterInput, ObsidianPatchHeadingInput, ObsidianReadInput, ObsidianReadScope, ObsidianReadSuccess, ObsidianReadToolResult, ObsidianReplaceNoteInput, ObsidianRequestOptions, ObsidianResponse, ObsidianSearchInput, ObsidianSearchMatch, ObsidianSearchResult, ObsidianSearchSuccess, ObsidianSearchToolResult, ObsidianServerInfo, ObsidianServerVersions, ObsidianUpdateInput, ObsidianUpdateSuccess, ObsidianUpdateToolResult, normalizeObsidianFolder, normalizeObsidianNotePath } from './obsidian-api/index.js';
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { ObsidianClient, ObsidianClientError, normalizeObsidianFolder, normalizeObsidianNotePath } from './chunk-R6I5X4OC.mjs';
@@ -0,0 +1,185 @@
1
+ type ObsidianErrorCode = 'disabled' | 'invalid_input' | 'invalid_path' | 'not_found' | 'already_exists' | 'revision_conflict' | 'unauthorized' | 'forbidden' | 'unsupported_version' | 'timeout' | 'unreachable' | 'tls_error' | 'response_too_large' | 'invalid_response' | 'http_error';
2
+ interface ObsidianErrorResult {
3
+ ok: false;
4
+ code: ObsidianErrorCode;
5
+ message: string;
6
+ path?: string;
7
+ status?: number;
8
+ }
9
+
10
+ interface ObsidianCreateSuccess {
11
+ ok: true;
12
+ created: true;
13
+ path: string;
14
+ version: string;
15
+ }
16
+ type ObsidianCreateToolResult = ObsidianCreateSuccess | ObsidianErrorResult;
17
+
18
+ interface ObsidianDeleteSuccess {
19
+ ok: true;
20
+ deleted: true;
21
+ path: string;
22
+ permanent: false;
23
+ }
24
+ type ObsidianDeleteToolResult = ObsidianDeleteSuccess | ObsidianErrorResult;
25
+
26
+ declare function normalizeObsidianFolder(value: string): string;
27
+
28
+ declare function normalizeObsidianNotePath(value: string): string;
29
+
30
+ interface ObsidianUpdateBase {
31
+ path: string;
32
+ version: string;
33
+ }
34
+ interface ObsidianReplaceNoteInput extends ObsidianUpdateBase {
35
+ mode: 'replaceNote';
36
+ content: string;
37
+ }
38
+ interface ObsidianPatchHeadingInput extends ObsidianUpdateBase {
39
+ mode: 'patchHeading';
40
+ target: string[];
41
+ operation: 'append' | 'prepend' | 'replace' | 'delete';
42
+ scope?: 'content' | 'markerAndContent';
43
+ content?: string;
44
+ createTargetIfMissing?: boolean;
45
+ }
46
+ interface ObsidianPatchFrontmatterInput extends ObsidianUpdateBase {
47
+ mode: 'patchFrontmatter';
48
+ target: string;
49
+ operation: 'append' | 'prepend' | 'replace' | 'delete';
50
+ value?: unknown;
51
+ createTargetIfMissing?: boolean;
52
+ }
53
+ type ObsidianUpdateInput = ObsidianReplaceNoteInput | ObsidianPatchHeadingInput | ObsidianPatchFrontmatterInput;
54
+ interface ObsidianUpdateSuccess {
55
+ ok: true;
56
+ updated: true;
57
+ path: string;
58
+ version: string;
59
+ }
60
+ type ObsidianUpdateToolResult = ObsidianUpdateSuccess | ObsidianErrorResult;
61
+
62
+ interface ObsidianConfig {
63
+ enabled: boolean;
64
+ baseUrl: string;
65
+ apiKey?: string;
66
+ caCertificate?: string;
67
+ vaultFolder: string;
68
+ requestTimeoutMs: number;
69
+ }
70
+ interface ObsidianSearchMatch {
71
+ context: string;
72
+ start: number;
73
+ end: number;
74
+ }
75
+ interface ObsidianSearchResult {
76
+ path: string;
77
+ score: number;
78
+ totalMatches?: number;
79
+ matches: ObsidianSearchMatch[];
80
+ }
81
+ interface ObsidianDocumentMap {
82
+ headings: Record<string, unknown>;
83
+ blocks: string[];
84
+ frontmatterFields: string[];
85
+ version: string;
86
+ }
87
+ interface ObsidianServerVersions {
88
+ obsidian?: string;
89
+ self?: string;
90
+ }
91
+ interface ObsidianServerInfo {
92
+ status?: string;
93
+ service?: string;
94
+ authenticated?: boolean;
95
+ versions?: ObsidianServerVersions;
96
+ }
97
+ interface ObsidianSearchInput {
98
+ query: string;
99
+ maxResults?: number;
100
+ maxMatchesPerFile?: number;
101
+ contextLength?: number;
102
+ }
103
+ type ObsidianReadScope = NonNullable<ObsidianPatchHeadingInput['scope']>;
104
+ interface ObsidianReadInput {
105
+ path: string;
106
+ heading?: string[];
107
+ scope?: ObsidianReadScope;
108
+ includeDocumentMap?: boolean;
109
+ }
110
+ interface ObsidianCreateInput {
111
+ title: string;
112
+ content: string;
113
+ folder?: string;
114
+ tags?: string[];
115
+ }
116
+
117
+ interface ObsidianOpenSuccess {
118
+ ok: true;
119
+ opened: true;
120
+ path: string;
121
+ newLeaf: boolean;
122
+ }
123
+ type ObsidianOpenToolResult = ObsidianOpenSuccess | ObsidianErrorResult;
124
+
125
+ interface ObsidianReadSuccess {
126
+ ok: true;
127
+ path: string;
128
+ content: string;
129
+ version: string;
130
+ documentMap?: ObsidianDocumentMap;
131
+ }
132
+ type ObsidianReadToolResult = ObsidianReadSuccess | ObsidianErrorResult;
133
+
134
+ interface ObsidianSearchSuccess {
135
+ ok: true;
136
+ query: string;
137
+ results: ObsidianSearchResult[];
138
+ totalResults: number;
139
+ limited: boolean;
140
+ }
141
+ type ObsidianSearchToolResult = ObsidianSearchSuccess | ObsidianErrorResult;
142
+
143
+ declare class ObsidianClient {
144
+ private readonly config;
145
+ constructor(config: ObsidianConfig);
146
+ getServerInfo(signal?: AbortSignal): Promise<ObsidianServerInfo>;
147
+ search(input: ObsidianSearchInput, signal?: AbortSignal): Promise<ObsidianSearchSuccess>;
148
+ read(input: ObsidianReadInput, signal?: AbortSignal): Promise<ObsidianReadSuccess>;
149
+ create(input: ObsidianCreateInput, signal?: AbortSignal): Promise<ObsidianCreateSuccess>;
150
+ update(input: ObsidianUpdateInput, signal?: AbortSignal): Promise<ObsidianUpdateSuccess>;
151
+ delete(pathInput: string, versionInput: string, signal?: AbortSignal): Promise<ObsidianDeleteSuccess>;
152
+ open(pathInput: string, newLeaf?: boolean, signal?: AbortSignal): Promise<ObsidianOpenSuccess>;
153
+ private readResponse;
154
+ private header;
155
+ private parseJson;
156
+ private assertStatus;
157
+ }
158
+
159
+ declare class ObsidianClientError extends Error {
160
+ readonly code: ObsidianErrorCode;
161
+ readonly status?: number | undefined;
162
+ readonly path?: string | undefined;
163
+ constructor(code: ObsidianErrorCode, message: string, status?: number | undefined, path?: string | undefined);
164
+ static from(error: unknown, path?: string): ObsidianClientError;
165
+ }
166
+
167
+ type ObsidianHttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
168
+ interface ObsidianRequestOptions {
169
+ method: ObsidianHttpMethod;
170
+ path: string;
171
+ query?: Record<string, string | number | boolean | undefined>;
172
+ headers?: Record<string, string>;
173
+ body?: string;
174
+ signal?: AbortSignal;
175
+ discardBody?: boolean;
176
+ maxResponseBytes?: number;
177
+ }
178
+ interface ObsidianResponse {
179
+ status: number;
180
+ headers: Record<string, string | string[] | undefined>;
181
+ body: string;
182
+ }
183
+
184
+ export { ObsidianClient, ObsidianClientError, normalizeObsidianFolder, normalizeObsidianNotePath };
185
+ export type { ObsidianConfig, ObsidianCreateInput, ObsidianCreateSuccess, ObsidianCreateToolResult, ObsidianDeleteSuccess, ObsidianDeleteToolResult, ObsidianDocumentMap, ObsidianErrorCode, ObsidianErrorResult, ObsidianHttpMethod, ObsidianOpenSuccess, ObsidianOpenToolResult, ObsidianPatchFrontmatterInput, ObsidianPatchHeadingInput, ObsidianReadInput, ObsidianReadScope, ObsidianReadSuccess, ObsidianReadToolResult, ObsidianReplaceNoteInput, ObsidianRequestOptions, ObsidianResponse, ObsidianSearchInput, ObsidianSearchMatch, ObsidianSearchResult, ObsidianSearchSuccess, ObsidianSearchToolResult, ObsidianServerInfo, ObsidianServerVersions, ObsidianUpdateInput, ObsidianUpdateSuccess, ObsidianUpdateToolResult };
@@ -0,0 +1 @@
1
+ export { ObsidianClient, ObsidianClientError, normalizeObsidianFolder, normalizeObsidianNotePath } from '../chunk-R6I5X4OC.mjs';
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@triplef/obsidian-api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "A lean Node.js client for the Obsidian Local REST API — typed note CRUD, search, document maps, conditional writes, and bounded HTTP transport.",
4
+ "version": "1.0.0",
5
+ "packageManager": "pnpm@12.26.0",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs"
12
+ },
13
+ "./obsidian-api": {
14
+ "types": "./dist/obsidian-api/index.d.ts",
15
+ "import": "./dist/obsidian-api/index.mjs"
16
+ }
17
+ },
18
+ "main": "dist/index.mjs",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/ehildt/tripleF.git"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "author": {
30
+ "email": "eugen.hildt@gmail.com"
31
+ },
32
+ "bugs": {
33
+ "email": "eugen.hildt@gmail.com"
34
+ },
35
+ "scripts": {
36
+ "prepare": "husky",
37
+ "build": "pnpm tsup",
38
+ "depcheck": "npx depcheck .",
39
+ "depcruise": "npx dependency-cruiser -c .depcruise.mjs --ts-config tsconfig.json src",
40
+ "format": "prettier --write .",
41
+ "lint": "eslint ./src",
42
+ "lint-staged": "npx lint-staged --allow-empty",
43
+ "ncu:update": "npx npm-check-updates -u --format group --dep prod,dev,optional,packageManager,peer",
44
+ "ncu:interactive": "npx npm-check-updates -u --interactive --format group",
45
+ "ncu:validate": "npx npm-check-updates -e 2 --packageFile=./package.json",
46
+ "prebuild": "rimraf dist",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "test:cov": "vitest run --coverage",
50
+ "lint:unused": "npx ts-unused-exports ./tsconfig.exclude.json --maxIssues=6"
51
+ },
52
+ "devDependencies": {
53
+ "@changesets/cli": "^3.1.0",
54
+ "@eslint/js": "^10.0.1",
55
+ "@types/eslint": "^9.6.1",
56
+ "@types/node": "^26.6.11",
57
+ "@vitest/coverage-v8": "5.1.2",
58
+ "depcheck": "^1.4.7",
59
+ "dependency-cruiser": "^18.9.0",
60
+ "eslint": "^10.16.0",
61
+ "eslint-config-prettier": "^10.1.9",
62
+ "eslint-plugin-prettier": "^5.5.7",
63
+ "eslint-plugin-simple-import-sort": "^14.0.0",
64
+ "eslint-plugin-sonarjs": "^4.2.3",
65
+ "globals": "^17.15.0",
66
+ "husky": "^9.1.7",
67
+ "jiti": "^2.7.0",
68
+ "lint-staged": "^17.6.3",
69
+ "npm-check-updates": "^23.1.1",
70
+ "prettier": "^3.10.1",
71
+ "rimraf": "^6.1.4",
72
+ "ts-unused-exports": "^11.0.1",
73
+ "tsup": "^9.0.0",
74
+ "typescript": "^6.0.3",
75
+ "typescript-eslint": "^8.74.0",
76
+ "vitest": "^5.1.2"
77
+ }
78
+ }