@life-os/obsidian-web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.cjs ADDED
@@ -0,0 +1,299 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const http = require('node:http');
4
+ const { createHmac } = require('node:crypto');
5
+ const { pipeline } = require('node:stream/promises');
6
+ const { createRequestUrl } = require('./request-url.cjs');
7
+ const { openVault } = require('./vault-switch.cjs');
8
+ const { metadata } = require('./fs-queue.cjs');
9
+ const { revision, writeMarkdown } = require('./markdown-write.cjs');
10
+
11
+ const { VAULT_UI_VAULT: vault, VAULT_UI_ASSETS: assets, VAULT_UI_KEY: keyFile } = process.env;
12
+ const port = Number(process.env.PORT);
13
+ const host = '127.0.0.1:' + port;
14
+ const origin = 'http://' + host;
15
+ const key = fs.readFileSync(keyFile);
16
+ const sign = value => createHmac('sha256', key).update(value).digest('hex');
17
+ // This file belongs to the local operator, outside the browser-accessible vault.
18
+ function vaultOrigins(filename) {
19
+ const file = path.join(path.dirname(keyFile), filename);
20
+ const origins = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : [];
21
+ if (!Array.isArray(origins) || !origins.every(s => typeof s === 'string' && !s.includes(','))) {
22
+ throw Error('Expected an array of exact origins in ' + filename);
23
+ }
24
+ return origins.join(',');
25
+ }
26
+ const requestUrl = createRequestUrl(
27
+ [process.env.VAULT_UI_NETWORK_ORIGINS, vaultOrigins('full-origins.json')].filter(Boolean).join(','),
28
+ vaultOrigins('read-origins.json'), vaultOrigins('sync-origins.json'));
29
+ const version = require(path.join(assets, 'package.json')).version;
30
+ const index = fs.readFileSync(path.join(assets, 'index.html'), 'utf8')
31
+ .replace('</head>', '<link rel="icon" type="image/png" sizes="512x512" href="/icon.png"></head>')
32
+ .replace('<body class="theme-dark">', '<body class="theme-dark"><script src="/vault-ui.js"></script>');
33
+ const virtualRoot = '/vault/' + path.basename(vault);
34
+ const mime = { '.js': 'application/javascript', '.css': 'text/css', '.json': 'application/json',
35
+ '.html': 'text/html', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',
36
+ '.woff2': 'font/woff2', '.pdf': 'application/pdf', '.webp': 'image/webp' };
37
+
38
+ function inside(root, file) {
39
+ const relative = path.relative(root, file);
40
+ return !path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep);
41
+ }
42
+
43
+ function localFile(input) {
44
+ if (typeof input !== 'string' || !(input === virtualRoot || input.startsWith(virtualRoot + '/'))) {
45
+ throw Object.assign(Error('Path must be inside the vault'), { code: 'EACCES' });
46
+ }
47
+ const parts = input.slice(virtualRoot.length).split('/').filter(Boolean);
48
+ if (parts.some(part => part === '.' || part === '..' || part.includes('\\') || part.includes('\0'))) {
49
+ throw Object.assign(Error('Invalid file path'), { code: 'EACCES' });
50
+ }
51
+ let target = vault;
52
+ for (const part of parts) {
53
+ target = path.join(target, part);
54
+ const stat = fs.lstatSync(target, { throwIfNoEntry: false });
55
+ if (stat?.isSymbolicLink()) throw Object.assign(Error('Symlinks are unavailable'), { code: 'EACCES' });
56
+ }
57
+ return target;
58
+ }
59
+
60
+ function watchSnapshot(directory, recursive) {
61
+ const entries = fs.readdirSync(directory, { withFileTypes: true, recursive });
62
+ const snapshot = Object.create(null);
63
+ for (const entry of entries) {
64
+ if (entry.isSymbolicLink()) continue;
65
+ const target = path.join(entry.parentPath, entry.name);
66
+ const stat = fs.lstatSync(target, { throwIfNoEntry: false });
67
+ if (!stat || stat.isSymbolicLink()) continue;
68
+ const relative = path.relative(directory, target).split(path.sep).join('/');
69
+ snapshot[relative] = stat.mtimeMs + ':' + stat.size;
70
+ }
71
+ return snapshot;
72
+ }
73
+
74
+ async function fsCall(operation, args, expectedRevision) {
75
+ if (!Array.isArray(args)) throw Error('Expected filesystem arguments');
76
+ let file;
77
+ try { file = localFile(args[0]); }
78
+ catch (error) { if (operation === 'exists') return false; throw error; }
79
+ switch (operation) {
80
+ case 'exists': return fs.existsSync(file);
81
+ case 'access': await fs.promises.access(file); return null;
82
+ case 'realpath': await fs.promises.access(file); return args[0];
83
+ case 'stat':
84
+ case 'lstat': {
85
+ const stat = await fs.promises.stat(file);
86
+ return { size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, birthtimeMs: stat.birthtimeMs,
87
+ file: stat.isFile(), directory: stat.isDirectory() };
88
+ }
89
+ case 'readdir': {
90
+ const entries = (await fs.promises.readdir(file, { withFileTypes: true })).filter(entry => !entry.isSymbolicLink());
91
+ return args[1]?.withFileTypes
92
+ ? entries.map(entry => ({ name: entry.name, file: entry.isFile(), directory: entry.isDirectory() }))
93
+ : entries.map(entry => entry.name);
94
+ }
95
+ case 'watchSnapshot':
96
+ return watchSnapshot(file, args[1] === true);
97
+ case 'readFile': {
98
+ const bytes = await fs.promises.readFile(file);
99
+ return { value: bytes.toString('base64'), revision: /\.md$/i.test(file) ? revision(bytes) : undefined };
100
+ }
101
+ case 'writeFile': {
102
+ const bytes = Buffer.from(args[1], 'base64');
103
+ if (/\.md$/i.test(file)) {
104
+ const conflicts = path.join(path.dirname(keyFile), 'conflicts');
105
+ return { value: null, revision: writeMarkdown(file, bytes, expectedRevision, conflicts) };
106
+ }
107
+ fs.writeFileSync(file, bytes);
108
+ return { value: null };
109
+ }
110
+ case 'appendFile': fs.appendFileSync(file, Buffer.from(args[1], 'base64')); return null;
111
+ case 'mkdir': fs.mkdirSync(file, { recursive: args[1]?.recursive === true }); return null;
112
+ case 'rename': fs.renameSync(file, localFile(args[1])); return null;
113
+ case 'copyFile': fs.copyFileSync(file, localFile(args[1])); return null;
114
+ case 'unlink': fs.unlinkSync(file); return null;
115
+ case 'rmdir': fs.rmdirSync(file); return null;
116
+ case 'utimes': fs.utimesSync(file, Number(args[1]), Number(args[2])); return null;
117
+ default: throw Object.assign(Error('Unsupported filesystem operation ' + operation), { code: 'ENOSYS' });
118
+ }
119
+ }
120
+
121
+ async function jsonBody(req) {
122
+ const chunks = [];
123
+ let bytes = 0;
124
+ for await (const chunk of req) {
125
+ bytes += chunk.length;
126
+ if (bytes > 32 * 1024 * 1024) throw Error('Request too large');
127
+ chunks.push(chunk);
128
+ }
129
+ return JSON.parse(Buffer.concat(chunks).toString());
130
+ }
131
+
132
+ function json(res, payload) {
133
+ res.setHeader('Content-Type', 'application/json');
134
+ res.end(JSON.stringify(payload));
135
+ }
136
+
137
+ function checkReadable(file) {
138
+ if (!fs.statSync(file).isFile()) throw Error('Expected a file');
139
+ const fd = fs.openSync(file, 'r');
140
+ try { fs.readSync(fd, Buffer.alloc(1), 0, 1, 0); }
141
+ finally { fs.closeSync(fd); }
142
+ }
143
+
144
+ const server = http.createServer(async (req, res) => {
145
+ res.setHeader('Cache-Control', 'no-store');
146
+ res.setHeader('X-Content-Type-Options', 'nosniff');
147
+ res.setHeader('Referrer-Policy', 'no-referrer');
148
+ if (req.headers.host !== host || (req.headers.origin && req.headers.origin !== origin) ||
149
+ (req.headers['sec-fetch-site'] === 'cross-site' && req.headers['sec-fetch-mode'] !== 'navigate')) {
150
+ res.writeHead(403).end();
151
+ return;
152
+ }
153
+ try {
154
+ const url = new URL(req.url, origin);
155
+ switch (url.pathname) {
156
+ case '/_local/identity':
157
+ res.end(sign('identify:' + url.searchParams.get('challenge'))); return;
158
+ case '/_local/stop':
159
+ if (req.method !== 'POST' || req.headers.authorization !== sign('stop')) {
160
+ res.writeHead(403).end(); return;
161
+ }
162
+ res.setHeader('Connection', 'close');
163
+ res.end('stopping', () => { server.close(); server.closeAllConnections(); }); return;
164
+ case '/_local/config':
165
+ json(res, { version, vault: virtualRoot, markdownRevisions: true, readinessCheck: true, metadataBatch: true, readBatch: true, nativeWatch: true, pathSwitch: true }); return;
166
+ case '/_local/ready': {
167
+ if (req.method !== 'GET' || req.headers.authorization !== sign('ready')) {
168
+ res.writeHead(403).end(); return;
169
+ }
170
+ try {
171
+ checkReadable(path.join(assets, 'vault-ui.js'));
172
+ checkReadable(path.join(assets, 'app.js'));
173
+ fs.readdirSync(vault);
174
+ const file = url.searchParams.get('file');
175
+ if (file !== null) checkReadable(localFile(virtualRoot + '/' + file));
176
+ res.writeHead(204).end();
177
+ } catch {
178
+ res.writeHead(503).end();
179
+ }
180
+ return;
181
+ }
182
+ case '/_local/request-url': {
183
+ if (req.method !== 'POST' || req.headers.origin !== origin || req.headers['x-vault-ui'] !== '1') {
184
+ res.writeHead(403).end(); return;
185
+ }
186
+ try { json(res, { value: await requestUrl(await jsonBody(req)) }); }
187
+ catch (error) { json(res, { error: error.message }); }
188
+ return;
189
+ }
190
+ case '/_local/open-vault': {
191
+ if (req.method !== 'POST' || req.headers.origin !== origin || req.headers['x-vault-ui'] !== '1') {
192
+ res.writeHead(403).end(); return;
193
+ }
194
+ const { folder } = await jsonBody(req);
195
+ try { json(res, { url: await openVault(folder, vault, origin) }); }
196
+ catch (error) { json(res, { error: error.message }); }
197
+ return;
198
+ }
199
+ case '/_local/events': {
200
+ if (req.method !== 'GET' || req.headers.accept !== 'text/event-stream') {
201
+ res.writeHead(403).end(); return;
202
+ }
203
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
204
+ const unavailable = () => res.end('event: watch-unavailable\ndata: {}\n\n');
205
+ try {
206
+ const watcher = fs.watch(vault, { recursive: true }, (event, file) => {
207
+ if (file && !res.destroyed) res.write('data: ' + JSON.stringify([event, file.split(path.sep).join('/')]) + '\n\n');
208
+ });
209
+ watcher.once('error', unavailable);
210
+ res.on('close', () => watcher.close());
211
+ res.write(': ready\n\n');
212
+ } catch {
213
+ unavailable();
214
+ }
215
+ return;
216
+ }
217
+ case '/_local/read-batch': {
218
+ if (req.method !== 'POST' || req.headers['x-vault-ui'] !== '1') {
219
+ res.writeHead(403).end(); return;
220
+ }
221
+ const paths = await jsonBody(req);
222
+ if (!Array.isArray(paths) || paths.length > 32) { res.writeHead(400).end(); return; }
223
+ json(res, await Promise.all(paths.map(async name => {
224
+ let handle;
225
+ try {
226
+ if (typeof name !== 'string' || !/\.md$/i.test(name)) return { error: 'EINVAL' };
227
+ handle = await fs.promises.open(localFile(name), 'r');
228
+ const stat = await handle.stat();
229
+ if (!stat.isFile()) return { error: 'EINVAL' };
230
+ if (stat.size > 65536) return { single: true };
231
+ const buffer = Buffer.alloc(stat.size + 1);
232
+ let length = 0;
233
+ while (length < buffer.length) {
234
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
235
+ if (!bytesRead) break;
236
+ length += bytesRead;
237
+ }
238
+ if (length !== stat.size) return { single: true };
239
+ const bytes = buffer.subarray(0, length);
240
+ return { text: bytes.toString('utf8'), revision: revision(bytes) };
241
+ } catch (error) { return { error: error.code || 'EIO' }; }
242
+ finally { await handle?.close(); }
243
+ })));
244
+ return;
245
+ }
246
+ case '/_local/metadata': {
247
+ if (req.method !== 'POST' || req.headers['x-vault-ui'] !== '1') {
248
+ res.writeHead(403).end(); return;
249
+ }
250
+ const batch = await jsonBody(req);
251
+ if (!Array.isArray(batch) || batch.length > 128) { res.writeHead(400).end(); return; }
252
+ const results = [];
253
+ for (let i = 0; i < batch.length; i += 8) {
254
+ results.push(...await Promise.all(batch.slice(i, i + 8).map(async ({ operation, args }) => {
255
+ if (!metadata.has(operation)) return { error: { code: 'EINVAL', message: 'Expected metadata operation' } };
256
+ try { return { value: await fsCall(operation, args) }; }
257
+ catch (e) { return { error: { code: e.code, message: e.code || 'Could not read metadata' } }; }
258
+ })));
259
+ }
260
+ json(res, results);
261
+ return;
262
+ }
263
+ case '/_local/fs': {
264
+ if (req.method !== 'POST' || req.headers['x-vault-ui'] !== '1') {
265
+ res.writeHead(403).end(); return;
266
+ }
267
+ const { operation, args, expectedRevision } = await jsonBody(req);
268
+ try {
269
+ const result = await fsCall(operation, args, expectedRevision);
270
+ json(res, operation === 'readFile' || operation === 'writeFile' ? result : { value: result });
271
+ } catch (error) {
272
+ json(res, { error: { code: error.code, message: error.code === 'ESTALE' ? error.message : error.code ?? error.message } });
273
+ }
274
+ return;
275
+ }
276
+ case '/':
277
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
278
+ res.setHeader('Content-Security-Policy', "frame-ancestors 'self'; object-src 'none'; base-uri 'self'");
279
+ res.end(index); return;
280
+ }
281
+ const resource = url.pathname.startsWith('/_local/resource/');
282
+ const file = resource ? localFile('/' + decodeURIComponent(url.pathname.slice('/_local/resource/'.length)))
283
+ : path.resolve(assets, '.' + decodeURIComponent(url.pathname));
284
+ if ((!resource && (!inside(assets, file) || ['main.js', 'starter.js', 'package.json'].includes(path.basename(file)))) ||
285
+ !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
286
+ res.writeHead(404).end(); return;
287
+ }
288
+ const extension = path.extname(file);
289
+ const media = mime[extension];
290
+ const safeResource = resource && media && (media.startsWith('image/') && extension !== '.svg' || extension === '.pdf');
291
+ res.setHeader('Content-Type', (resource ? (safeResource && media) : media) || 'application/octet-stream');
292
+ if (resource && !safeResource) res.setHeader('Content-Disposition', 'attachment');
293
+ await pipeline(fs.createReadStream(file), res);
294
+ } catch {
295
+ if (!res.headersSent) res.writeHead(404);
296
+ res.end();
297
+ }
298
+ });
299
+ server.listen(port, '127.0.0.1');
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: obsidian-web
3
+ description: Open the original Obsidian editor in the current AI client to browse a local vault or edit a specific Markdown note.
4
+ ---
5
+
6
+ Use English by default. Follow an explicit request for a different language.
7
+
8
+ Use the user-specified absolute vault path when provided. Otherwise use the current project directory. The vault switcher accepts an absolute directory path directly. For a specific note, pass its path relative to the vault root and preserve spaces and Unicode. If the user asks you to organize content first, save the Markdown before opening it.
9
+
10
+ ```sh
11
+ "$HOME/.local/bin/obsidian-web" connect --vault "$vault" --file "$file" --json
12
+ ```
13
+
14
+ Omit `--file` to open the entire vault. On success, read `url` from the CLI output. In WorkBuddy, call the built-in `present_files` tool with the HTTP URL as the sole entry in `files` and the absolute vault path as `cwd`. Follow the current tool schema for any description. In other clients, use their built-in browser if available. Include a clickable link in the response. If the client has no built-in preview, provide the link directly. Keep the preview in the client or at the provided URL.
15
+
16
+ If the service is stopped, put the full terminal command returned by `connect` in a code block. Ask the user to run it in their system terminal, then return to the same chat. From a WorkBuddy task, use `connect` to open the vault. The system terminal handles `open` and `serve`.
17
+
18
+ If the CLI cannot read an asset or the note, or the user reports a blank panel, ask them to save any notes that are still editable. Have them run `obsidian-web stop` and `obsidian-web open` for the same vault in their system terminal. Once the service is running, use `connect` again to get the URL and open the panel.
19
+
20
+ When the user asks to stop the service, run `"$HOME/.local/bin/obsidian-web" stop --vault "$vault"`. Before revising a note the user edited in the panel, reread it from disk.
@@ -0,0 +1,54 @@
1
+ const fs = require('node:fs/promises');
2
+ const path = require('node:path');
3
+ const { execFile } = require('node:child_process');
4
+ const { promisify } = require('node:util');
5
+ const exec = promisify(execFile);
6
+ const cli = path.join(__dirname, 'vault-ui.mjs');
7
+
8
+ async function launch(command, vault) {
9
+ const { stdout } = await exec(process.execPath, [cli, command, '--vault', vault, '--json']);
10
+ return JSON.parse(stdout).url;
11
+ }
12
+
13
+ async function confirmDirectory(vault) {
14
+ // Confirmation belongs to the OS. Code running in the current vault cannot
15
+ // grant itself access to a different folder by posting its path.
16
+ let program, args;
17
+ if (process.platform === 'darwin') {
18
+ program = '/usr/bin/osascript';
19
+ args = ['-e', 'on run argv', '-e',
20
+ 'POSIX path of (choose folder with prompt "Open this folder in Obsidian Web" default location (POSIX file (item 1 of argv)))',
21
+ '-e', 'end run', vault];
22
+ } else {
23
+ program = 'zenity';
24
+ args = ['--file-selection', '--directory', '--title=Open this folder in Obsidian Web', '--filename=' + vault + path.sep];
25
+ }
26
+ let selected;
27
+ try { selected = (await exec(program, args)).stdout.replace(/\r?\n$/, ''); }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT') throw Error('Open this folder from a system terminal with obsidian-web.');
30
+ throw Error('Folder selection was cancelled or unavailable.');
31
+ }
32
+ if (await fs.realpath(selected) !== vault) throw Error('Select the same folder as the path you entered.');
33
+ }
34
+
35
+ let choosing = false;
36
+ async function openVault(input, current, currentOrigin) {
37
+ if (typeof input !== 'string' || !path.isAbsolute(input) || /[\x00-\x1f]/.test(input)) {
38
+ throw Error('Enter an absolute folder path.');
39
+ }
40
+ const vault = await fs.realpath(input).catch(() => { throw Error('Folder not found. Check the path.'); });
41
+ if (vault === path.parse(vault).root || !(await fs.stat(vault)).isDirectory()) throw Error('Choose a vault folder.');
42
+ if (vault === current) return currentOrigin + '/';
43
+ try { return await launch('connect', vault); }
44
+ catch (error) {
45
+ if (!error.stderr?.startsWith('Obsidian Web is stopped for this vault.')) throw Error('Could not connect to this vault. Check its local service.');
46
+ }
47
+ if (choosing) throw Error('A folder selection is already open.');
48
+ choosing = true;
49
+ try {
50
+ await confirmDirectory(vault);
51
+ return await launch('open', vault).catch(() => { throw Error('Could not start the vault. Try the same path with obsidian-web in a terminal.'); });
52
+ } finally { choosing = false; }
53
+ }
54
+ module.exports = { openVault };
package/vault-ui.mjs ADDED
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
6
+ import { spawn } from 'node:child_process';
7
+ import { parseArgs } from 'node:util';
8
+ import { setTimeout as delay } from 'node:timers/promises';
9
+
10
+ function shellQuote(value) {
11
+ return "'" + value.replaceAll("'", "'\\''") + "'";
12
+ }
13
+
14
+ async function main() {
15
+ const args = process.argv.slice(2);
16
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
17
+ console.log('Usage: obsidian-web <absolute-vault-directory> [--file <note>] [--json]\n obsidian-web setup [archive]\n obsidian-web open|connect|serve|stop --vault <directory> [--file <note>] [--json]');
18
+ return;
19
+ }
20
+ if (args.length === 1 && args[0] === '--version') {
21
+ console.log(JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url))).version);
22
+ return;
23
+ }
24
+ if (args[0] === 'setup') {
25
+ const child = spawn(process.execPath, [path.join(import.meta.dirname, 'install.mjs'), ...args.slice(1)], { stdio: 'inherit' });
26
+ process.exitCode = await new Promise((resolve, reject) => {
27
+ child.once('error', reject);
28
+ child.once('exit', code => resolve(code ?? 1));
29
+ });
30
+ return;
31
+ }
32
+ const { positionals: [command, ...extra], values } = parseArgs({
33
+ allowPositionals: true,
34
+ options: { vault: { type: 'string' }, file: { type: 'string' }, json: { type: 'boolean' } },
35
+ });
36
+ const direct = typeof command === 'string' && path.isAbsolute(command);
37
+ const action = direct ? 'open' : command;
38
+ const positionalVault = direct ? command : extra[0];
39
+ if (!['open', 'connect', 'serve', 'stop'].includes(action) || extra.length > (direct ? 0 : 1) ||
40
+ (positionalVault && (values.vault || !path.isAbsolute(positionalVault))) || !(values.vault || positionalVault)) {
41
+ throw Error('Choose a vault with obsidian-web <absolute-directory> or use open --vault <directory>.');
42
+ }
43
+ const vault = fs.realpathSync(values.vault || positionalVault);
44
+ if (!fs.statSync(vault).isDirectory() || vault === path.parse(vault).root) throw Error('Choose a vault directory');
45
+ const home = path.resolve(process.env.VAULT_UI_HOME || path.join(os.homedir(), '.local/share/vault-ui'));
46
+ const assets = path.join(home, 'obsidian-1.14.4');
47
+ const entry = path.join(import.meta.dirname, 'server.cjs');
48
+ if (['open', 'serve'].includes(action) && !fs.existsSync(path.join(assets, 'vault-ui.js'))) {
49
+ throw Error('Run obsidian-web setup to install the local runtime first');
50
+ }
51
+ const hash = createHash('sha256').update('browser-v1:' + vault).digest();
52
+ const dir = path.join(home, 'sessions', hash.toString('hex'));
53
+ const port = 20000 + hash.readUInt32BE() % 30000;
54
+ const base = 'http://127.0.0.1:' + port;
55
+ const url = new URL(base);
56
+ let file;
57
+ if (values.file) {
58
+ if (path.isAbsolute(values.file)) throw Error('--file requires a relative path');
59
+ const target = fs.realpathSync(path.resolve(vault, values.file));
60
+ file = path.relative(vault, target);
61
+ if (file.startsWith('..' + path.sep) || !/\.md$/i.test(file) || !fs.statSync(target).isFile()) {
62
+ throw Error('Choose an existing Markdown note inside the vault');
63
+ }
64
+ file = file.split(path.sep).join('/');
65
+ url.searchParams.set('file', file);
66
+ }
67
+ function startInTerminal() {
68
+ const args = file ? ' --file ' + shellQuote(file) : '';
69
+ return Error('Obsidian Web is stopped for this vault. Run the following command in your system terminal.\n' +
70
+ '"$HOME/.local/bin/obsidian-web" open --vault ' + shellQuote(vault) + args + ' --json');
71
+ }
72
+ const keyPath = path.join(dir, 'key');
73
+ if (action !== 'connect') {
74
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
75
+ try { fs.writeFileSync(keyPath, randomBytes(32), { mode: 0o600, flag: 'wx' }); }
76
+ catch (e) { if (e.code !== 'EEXIST') throw e; }
77
+ }
78
+ let key;
79
+ try { key = fs.readFileSync(keyPath); }
80
+ catch (error) {
81
+ if (action === 'connect' && error.code === 'ENOENT') throw startInTerminal();
82
+ throw error;
83
+ }
84
+ if (key.length !== 32) throw Error('The service key is still being created. Try again.');
85
+ const sign = value => createHmac('sha256', key).update(value).digest('hex');
86
+ async function running() {
87
+ const challenge = randomBytes(16).toString('hex');
88
+ let identity;
89
+ try {
90
+ const response = await fetch(base + '/_local/identity?challenge=' + challenge, {
91
+ signal: AbortSignal.timeout(10000), redirect: 'error', headers: { connection: 'close' },
92
+ });
93
+ identity = await response.text();
94
+ } catch (e) { if (e.cause?.code === 'ECONNREFUSED') return false;
95
+ throw e; }
96
+ if (identity !== sign('identify:' + challenge)) throw Error('The port is already in use by another service');
97
+ return true;
98
+ }
99
+ const environment = { VAULT_UI_VAULT: vault, VAULT_UI_ASSETS: assets, PORT: String(port), VAULT_UI_KEY: keyPath };
100
+ if (action === 'serve') {
101
+ Object.assign(process.env, environment);
102
+ await import(entry);
103
+ return;
104
+ }
105
+ const reused = await running();
106
+ if (action === 'stop') {
107
+ if (reused) {
108
+ const res = await fetch(base + '/_local/stop', {
109
+ method: 'POST', headers: { authorization: sign('stop'), connection: 'close' },
110
+ redirect: 'error', signal: AbortSignal.timeout(10000),
111
+ });
112
+ if (!res.ok) throw Error('Could not stop the service');
113
+ for (let i = 0; i < 100; i++) {
114
+ try {
115
+ if (!await running()) return { stopped: true, vault };
116
+ } catch (error) {
117
+ // A probe can connect just before the server finishes closing its sockets.
118
+ if (!['ECONNRESET', 'UND_ERR_SOCKET'].includes(error.cause?.code)) throw error;
119
+ }
120
+ await delay(100);
121
+ }
122
+ throw Error('The service is still shutting down');
123
+ }
124
+ return { stopped: true, vault };
125
+ }
126
+ if (!reused) {
127
+ if (action === 'connect') throw startInTerminal();
128
+ const gate = path.join(os.homedir(), '.local/bin/dev-gate');
129
+ const remoteGate = path.join(os.homedir(), '.local/share/omarchy-node/gate.py');
130
+ let executable = process.execPath;
131
+ let args = [entry];
132
+ if (fs.existsSync(gate)) {
133
+ executable = gate;
134
+ args = ['run', '--kind', 'service', '--label', 'vault-ui', '--port', String(port), '--', process.execPath, entry];
135
+ } else if (process.platform === 'linux' && fs.existsSync(remoteGate)) {
136
+ executable = 'python3';
137
+ args = [remoteGate, 'run', '--kind', 'service', '--label', 'vault-ui', '--', process.execPath, entry];
138
+ }
139
+ const log = path.join(dir, 'server.log');
140
+ const fd = fs.openSync(log, 'a', 0o600);
141
+ const child = spawn(executable, args, {
142
+ detached: true, stdio: ['ignore', fd, fd],
143
+ env: { ...process.env, ...environment },
144
+ });
145
+ fs.closeSync(fd);
146
+ let failure;
147
+ child.on('error', error => { failure = error; });
148
+ child.unref();
149
+ for (let i = 0; i < 650; i++) {
150
+ if (await running()) break;
151
+ if (failure || child.exitCode !== null || child.signalCode) throw Error('The service failed to start. Check ' + log);
152
+ await delay(200);
153
+ }
154
+ if (!await running()) throw Error('The service is still starting. Check ' + log);
155
+ }
156
+ const response = await fetch(base + '/_local/config', { signal: AbortSignal.timeout(10000), redirect: 'error' });
157
+ const config = response.ok && await response.json();
158
+ if (!config || config.markdownRevisions !== true || config.readinessCheck !== true) {
159
+ throw Error('The vault is running an older version. Save your notes, run obsidian-web stop for this vault, then reopen it.');
160
+ }
161
+ const readyUrl = new URL('/_local/ready', base);
162
+ if (file) readyUrl.searchParams.set('file', file);
163
+ const ready = await fetch(readyUrl, {
164
+ headers: { authorization: sign('ready') }, signal: AbortSignal.timeout(10000), redirect: 'error',
165
+ });
166
+ if (!ready.ok) {
167
+ throw Error('The local service could not read the Obsidian runtime or note. If you started it from WorkBuddy, stop and reopen the vault from your system terminal.');
168
+ }
169
+ if (direct && !values.json) {
170
+ const opener = process.platform === 'darwin' ? 'open' : 'xdg-open';
171
+ const browser = spawn(opener, [url.href], { stdio: 'ignore' });
172
+ await new Promise((resolve, reject) => {
173
+ browser.once('error', reject);
174
+ browser.once('exit', code => code === 0 ? resolve() : reject(Error('Could not open the browser: ' + url.href)));
175
+ });
176
+ console.log(vault);
177
+ return;
178
+ }
179
+ return { url: url.href, vault, file, reused };
180
+ }
181
+ main().then(result => { if (result) console.log(JSON.stringify(result)); }).catch(error => {
182
+ console.error(error.message);
183
+ process.exitCode = 1;
184
+ });