@clarionstack/notesia 0.0.4 → 0.0.6
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 +62 -6
- package/bin/notesia.mjs +16 -5
- package/package.json +2 -2
- package/src/commands.mjs +6 -0
- package/src/import.mjs +400 -0
- package/src/io.mjs +3 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Notesia CLI
|
|
2
2
|
|
|
3
|
-
Local CLI for reading
|
|
3
|
+
Local CLI for reading, updating, and bulk-importing notes in Notesia through the desktop app bridge.
|
|
4
4
|
|
|
5
5
|
## Requirements
|
|
6
6
|
|
|
@@ -27,6 +27,30 @@ npm install -g @clarionstack/notesia
|
|
|
27
27
|
- `notesia sync`
|
|
28
28
|
- `notesia auth status [--format text|json]`
|
|
29
29
|
|
|
30
|
+
### Bulk Import
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
notesia import <path> [options]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Recursively discovers files in a directory and imports them as notes into Notesia.
|
|
37
|
+
|
|
38
|
+
| Option | Description | Default |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `<path>` | Source directory or file (required) | — |
|
|
41
|
+
| `--ext <list>` | Comma-separated file extensions | `md,txt` |
|
|
42
|
+
| `--folder <name>` | Target folder name (created if absent) | — |
|
|
43
|
+
| `--tags <list>` | Comma-separated tags for all imported notes | — |
|
|
44
|
+
| `--conflict <mode>` | `skip` or `overwrite` existing notes by title | `skip` |
|
|
45
|
+
| `--dry-run` | Preview what would be imported without writing | — |
|
|
46
|
+
| `--format <fmt>` | Output format: `text` or `json` | `text` |
|
|
47
|
+
| `--quiet` | Suppress stdout output | — |
|
|
48
|
+
| `--verbose` | Print per-file progress to stderr | — |
|
|
49
|
+
|
|
50
|
+
Supported file types: `.md`, `.txt`, `.html`, `.pdf` (requires `pdfjs-dist`).
|
|
51
|
+
|
|
52
|
+
Notes exceeding 100,000 characters are automatically split into multiple parts.
|
|
53
|
+
|
|
30
54
|
### AI Knowledge Base (`kb`)
|
|
31
55
|
|
|
32
56
|
- `notesia kb search --query "<text>" [--limit <n>] [--threshold <0-1>] [--format text|json]`
|
|
@@ -38,6 +62,8 @@ npm install -g @clarionstack/notesia
|
|
|
38
62
|
|
|
39
63
|
## Examples
|
|
40
64
|
|
|
65
|
+
### Basic note operations
|
|
66
|
+
|
|
41
67
|
```bash
|
|
42
68
|
notesia get --id 42 > note.md
|
|
43
69
|
notesia get --id 42 --with-meta # prepends YAML frontmatter
|
|
@@ -49,7 +75,29 @@ notesia sync
|
|
|
49
75
|
notesia auth status
|
|
50
76
|
```
|
|
51
77
|
|
|
52
|
-
|
|
78
|
+
### Bulk import
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Import all markdown and text files from a directory
|
|
82
|
+
notesia import ~/Documents/notes
|
|
83
|
+
|
|
84
|
+
# Import into a specific folder with tags
|
|
85
|
+
notesia import ./project-docs --folder "Work" --tags "project,2026"
|
|
86
|
+
|
|
87
|
+
# Import HTML and PDF files too
|
|
88
|
+
notesia import ./archive --ext md,txt,html,pdf
|
|
89
|
+
|
|
90
|
+
# Overwrite existing notes with the same title
|
|
91
|
+
notesia import ./updated-notes --conflict overwrite
|
|
92
|
+
|
|
93
|
+
# Preview what would be imported
|
|
94
|
+
notesia import ~/notes --dry-run --verbose
|
|
95
|
+
|
|
96
|
+
# JSON output for scripting
|
|
97
|
+
notesia import ./docs --format json --quiet 2>/dev/null | jq '.created'
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### AI Knowledge Base
|
|
53
101
|
|
|
54
102
|
```bash
|
|
55
103
|
# Check auth
|
|
@@ -61,15 +109,15 @@ notesia kb folders --json
|
|
|
61
109
|
# Find relevant notes
|
|
62
110
|
notesia kb search --query "project plan" --limit 10
|
|
63
111
|
|
|
64
|
-
# Ask KB directly
|
|
65
|
-
notesia kb ask --query "what
|
|
112
|
+
# Ask KB directly (searches notes and todos)
|
|
113
|
+
notesia kb ask --query "what are my pending tasks?"
|
|
66
114
|
|
|
67
115
|
# Load full context for AI prompt (returns JSON with full content)
|
|
68
116
|
notesia kb context --query "Q1 roadmap" --limit 5
|
|
69
117
|
|
|
70
118
|
# Continue a KB conversation across calls
|
|
71
|
-
notesia kb ask --query "what did I change yesterday?"
|
|
72
|
-
notesia kb ask --query "and what about folder sync?"
|
|
119
|
+
notesia kb ask --query "what did I change yesterday?"
|
|
120
|
+
notesia kb ask --query "and what about folder sync?"
|
|
73
121
|
|
|
74
122
|
# Create a tagged note
|
|
75
123
|
echo "## Summary\n..." | notesia store --title "AI Summary" --tag ai --tag generated
|
|
@@ -78,6 +126,14 @@ echo "## Summary\n..." | notesia store --title "AI Summary" --tag ai --tag gener
|
|
|
78
126
|
notesia get --id 42 --with-meta
|
|
79
127
|
```
|
|
80
128
|
|
|
129
|
+
## Exit Codes
|
|
130
|
+
|
|
131
|
+
| Code | Meaning |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `0` | Success (including skipped items) |
|
|
134
|
+
| `1` | Runtime error (bridge unavailable, failed items, renderer error) |
|
|
135
|
+
| `2` | Invalid arguments |
|
|
136
|
+
|
|
81
137
|
## Security Notes
|
|
82
138
|
|
|
83
139
|
- **Secure notes** (encrypted vault notes) are **never** exposed through the CLI
|
package/bin/notesia.mjs
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { runCli } from '../src/commands.mjs';
|
|
3
|
+
import { runImport } from '../src/import.mjs';
|
|
3
4
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
const argv = process.argv.slice(2);
|
|
6
|
+
|
|
7
|
+
// Dispatch `notesia import` to the dedicated import handler
|
|
8
|
+
if (argv[0] === 'import') {
|
|
9
|
+
runImport(argv.slice(1)).catch((error) => {
|
|
10
|
+
process.stderr.write(`${error?.message || 'notesia import failed'}\n`);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
});
|
|
13
|
+
} else {
|
|
14
|
+
runCli(argv).catch((error) => {
|
|
15
|
+
const message = error?.message || 'notesia CLI failed';
|
|
16
|
+
process.stderr.write(`${message}\n`);
|
|
17
|
+
process.exit(1);
|
|
18
|
+
});
|
|
19
|
+
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarionstack/notesia",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"description": "Notesia desktop bridge CLI",
|
|
4
|
+
"version": "0.0.6",
|
|
5
|
+
"description": "Notesia desktop bridge CLI — read, write, and bulk-import notes",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
|
8
8
|
"bin",
|
package/src/commands.mjs
CHANGED
|
@@ -310,6 +310,11 @@ function usageText() {
|
|
|
310
310
|
' sync',
|
|
311
311
|
' auth status [--format text|json]',
|
|
312
312
|
'',
|
|
313
|
+
'Bulk Import:',
|
|
314
|
+
' import <path> [--ext md,txt] [--folder <name>] [--tags <list>]',
|
|
315
|
+
' [--conflict skip|overwrite] [--dry-run]',
|
|
316
|
+
' [--format text|json] [--quiet] [--verbose]',
|
|
317
|
+
'',
|
|
313
318
|
'AI Knowledge Base:',
|
|
314
319
|
' kb search --query <text> [--limit <n>] [--threshold <0-1>] [--format text|json]',
|
|
315
320
|
' kb ask --query <text> [--limit <n>] [--threshold <0-1>] [--conversation-id <uuid>] [--format text|json]',
|
|
@@ -321,6 +326,7 @@ function usageText() {
|
|
|
321
326
|
' notesia list --json > notes.json',
|
|
322
327
|
' cat patch.md | notesia update --id 12',
|
|
323
328
|
' echo "- bullet" | notesia append --id 12',
|
|
329
|
+
' notesia import ./notes --ext md,txt --folder "Imported" --verbose',
|
|
324
330
|
'',
|
|
325
331
|
'Note:',
|
|
326
332
|
' kb ask reuses the same conversation automatically in the same terminal session.',
|
package/src/import.mjs
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* notesia import <path> [options]
|
|
3
|
+
*
|
|
4
|
+
* Bulk-imports files from a directory into Notesia via the bridge.
|
|
5
|
+
* File discovery and content parsing happen here (in the CLI process).
|
|
6
|
+
* Dexie writes happen in the renderer via the bulk_import bridge op.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createReadStream } from 'node:fs';
|
|
10
|
+
import fs from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import readline from 'node:readline';
|
|
13
|
+
import { requestBridge } from './client.mjs';
|
|
14
|
+
|
|
15
|
+
const NOTE_CHAR_LIMIT = 100_000;
|
|
16
|
+
|
|
17
|
+
const USAGE = [
|
|
18
|
+
'Usage: notesia import <path> [options]',
|
|
19
|
+
'',
|
|
20
|
+
'Arguments:',
|
|
21
|
+
' <path> Path to directory to import (positional or --path flag)',
|
|
22
|
+
'',
|
|
23
|
+
'Options:',
|
|
24
|
+
' --path <dir> Path to directory to import',
|
|
25
|
+
' --ext <list> Comma-separated extensions to import (default: md,txt)',
|
|
26
|
+
' --folder <name> Target folder name in Notesia',
|
|
27
|
+
' --tags <list> Comma-separated tags to apply to all imported notes',
|
|
28
|
+
' --conflict <mode> Conflict resolution: skip | overwrite (default: skip)',
|
|
29
|
+
' --create-folder Create folder if it does not exist (default: yes)',
|
|
30
|
+
' --no-create-folder Do not create folder if it does not exist',
|
|
31
|
+
' --dry-run Preview without writing',
|
|
32
|
+
' --format <fmt> Output format: text | json (default: text)',
|
|
33
|
+
' --quiet Suppress stdout output',
|
|
34
|
+
' --verbose Print per-file progress to stderr',
|
|
35
|
+
'',
|
|
36
|
+
].join('\n');
|
|
37
|
+
|
|
38
|
+
// ─── Argument parsing ────────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
export function parseImportArgs(argv) {
|
|
41
|
+
const args = [...argv];
|
|
42
|
+
|
|
43
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
44
|
+
process.stderr.write(USAGE);
|
|
45
|
+
process.exit(0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const opts = {
|
|
49
|
+
importPath: null,
|
|
50
|
+
ext: ['md', 'txt'],
|
|
51
|
+
folder: null,
|
|
52
|
+
tags: [],
|
|
53
|
+
conflict: 'skip',
|
|
54
|
+
createFolder: true, // Auto-create folder by default (prompt if not exists)
|
|
55
|
+
dryRun: false,
|
|
56
|
+
format: 'text',
|
|
57
|
+
quiet: false,
|
|
58
|
+
verbose: false,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Handle positional <path> argument OR --path flag
|
|
62
|
+
const firstArg = args[0];
|
|
63
|
+
if (firstArg && !firstArg.startsWith('--')) {
|
|
64
|
+
// Positional path: notesia import ~/Downloads
|
|
65
|
+
opts.importPath = path.resolve(firstArg);
|
|
66
|
+
args.shift();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
for (let i = 0; i < args.length; i++) {
|
|
70
|
+
const token = args[i];
|
|
71
|
+
|
|
72
|
+
if (token === '--path') {
|
|
73
|
+
const val = args[++i];
|
|
74
|
+
if (!val || val.startsWith('--')) { process.stderr.write('Error: --path requires a value\n\n' + USAGE); process.exit(2); }
|
|
75
|
+
opts.importPath = path.resolve(val);
|
|
76
|
+
} else if (token === '--ext') {
|
|
77
|
+
const val = args[++i];
|
|
78
|
+
if (!val || val.startsWith('--')) { process.stderr.write('Error: --ext requires a value\n\n' + USAGE); process.exit(2); }
|
|
79
|
+
opts.folder = val;
|
|
80
|
+
} else if (token === '--tags') {
|
|
81
|
+
const val = args[++i];
|
|
82
|
+
if (!val || val.startsWith('--')) { process.stderr.write('Error: --tags requires a value\n\n' + USAGE); process.exit(2); }
|
|
83
|
+
opts.tags = val.split(',').map((t) => t.trim()).filter(Boolean);
|
|
84
|
+
} else if (token === '--conflict') {
|
|
85
|
+
const val = args[++i];
|
|
86
|
+
if (val !== 'skip' && val !== 'overwrite') { process.stderr.write('Error: --conflict must be "skip" or "overwrite"\n\n' + USAGE); process.exit(2); }
|
|
87
|
+
opts.conflict = val;
|
|
88
|
+
} else if (token === '--create-folder') {
|
|
89
|
+
opts.createFolder = true;
|
|
90
|
+
} else if (token === '--no-create-folder') {
|
|
91
|
+
opts.createFolder = false;
|
|
92
|
+
} else if (token === '--dry-run') {
|
|
93
|
+
opts.dryRun = true;
|
|
94
|
+
} else if (token === '--format') {
|
|
95
|
+
const val = args[++i];
|
|
96
|
+
if (val !== 'text' && val !== 'json') { process.stderr.write('Error: --format must be "text" or "json"\n\n' + USAGE); process.exit(2); }
|
|
97
|
+
opts.format = val;
|
|
98
|
+
} else if (token === '--quiet') {
|
|
99
|
+
opts.quiet = true;
|
|
100
|
+
} else if (token === '--verbose') {
|
|
101
|
+
opts.verbose = true;
|
|
102
|
+
} else {
|
|
103
|
+
process.stderr.write(`Error: Unknown flag: ${token}\n\n` + USAGE);
|
|
104
|
+
process.exit(2);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Validate that a path was provided
|
|
109
|
+
if (!opts.importPath) {
|
|
110
|
+
process.stderr.write('Error: <path> argument is required (use positional argument or --path flag)\n\n' + USAGE);
|
|
111
|
+
process.exit(2);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return opts;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ─── File discovery ──────────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
async function discoverFiles(rootPath, extensions) {
|
|
120
|
+
const normalizedExts = extensions.map((e) => e.toLowerCase());
|
|
121
|
+
const results = [];
|
|
122
|
+
|
|
123
|
+
async function walk(dir, relBase) {
|
|
124
|
+
let entries;
|
|
125
|
+
try {
|
|
126
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
127
|
+
} catch {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
for (const entry of entries) {
|
|
131
|
+
if (entry.isSymbolicLink()) continue;
|
|
132
|
+
const relPath = relBase ? `${relBase}/${entry.name}` : entry.name;
|
|
133
|
+
const absPath = path.join(dir, entry.name);
|
|
134
|
+
if (entry.isDirectory()) {
|
|
135
|
+
await walk(absPath, relPath);
|
|
136
|
+
} else {
|
|
137
|
+
const ext = path.extname(entry.name).slice(1).toLowerCase();
|
|
138
|
+
if (!normalizedExts.includes(ext)) continue;
|
|
139
|
+
const stat = await fs.stat(absPath).catch(() => null);
|
|
140
|
+
if (!stat) continue;
|
|
141
|
+
results.push({ absolutePath: absPath, relativePath: relPath, extension: ext, sizeBytes: stat.size });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
await walk(rootPath, '');
|
|
147
|
+
return results;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─── Content parsing ─────────────────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
function titleFromPath(filePath) {
|
|
153
|
+
const stem = path.basename(filePath, path.extname(filePath));
|
|
154
|
+
return stem.replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function stripHtml(html) {
|
|
158
|
+
return html
|
|
159
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
160
|
+
.replace(/<[^>]+>/g, '')
|
|
161
|
+
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
162
|
+
.replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, ' ')
|
|
163
|
+
.trim();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function parseFile(absolutePath, extension) {
|
|
167
|
+
const defaultTitle = titleFromPath(absolutePath);
|
|
168
|
+
try {
|
|
169
|
+
if (extension === 'md' || extension === 'txt') {
|
|
170
|
+
const body = await fs.readFile(absolutePath, 'utf8');
|
|
171
|
+
return { title: defaultTitle, body };
|
|
172
|
+
}
|
|
173
|
+
if (extension === 'html' || extension === 'htm') {
|
|
174
|
+
const raw = await fs.readFile(absolutePath, 'utf8');
|
|
175
|
+
const titleMatch = raw.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
176
|
+
const htmlTitle = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim() : null;
|
|
177
|
+
return { title: htmlTitle || defaultTitle, body: stripHtml(raw) };
|
|
178
|
+
}
|
|
179
|
+
if (extension === 'pdf') {
|
|
180
|
+
// Dynamic import so missing pdfjs-dist doesn't break non-PDF imports
|
|
181
|
+
try {
|
|
182
|
+
const { default: pdfjsLib } = await import('pdfjs-dist/legacy/build/pdf.js');
|
|
183
|
+
pdfjsLib.GlobalWorkerOptions.workerSrc = '';
|
|
184
|
+
const data = await fs.readFile(absolutePath);
|
|
185
|
+
const pdf = await pdfjsLib.getDocument({ data: new Uint8Array(data), disableWorker: true }).promise;
|
|
186
|
+
const pages = [];
|
|
187
|
+
for (let i = 1; i <= pdf.numPages; i++) {
|
|
188
|
+
const page = await pdf.getPage(i);
|
|
189
|
+
const content = await page.getTextContent();
|
|
190
|
+
pages.push(content.items.map((item) => item.str).join(' '));
|
|
191
|
+
page.cleanup();
|
|
192
|
+
}
|
|
193
|
+
let title = defaultTitle;
|
|
194
|
+
try { const meta = await pdf.getMetadata(); if (meta?.info?.Title?.trim()) title = meta.info.Title.trim(); } catch {}
|
|
195
|
+
return { title, body: pages.join('\n\n').replace(/\s+\n/g, '\n').trim() };
|
|
196
|
+
} catch (err) {
|
|
197
|
+
return { title: defaultTitle, body: '', error: err.message };
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return { title: defaultTitle, body: '', error: `Unsupported extension: ${extension}` };
|
|
201
|
+
} catch (err) {
|
|
202
|
+
return { title: defaultTitle, body: '', error: err.message };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ─── Note splitter ───────────────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
function splitContent(title, body) {
|
|
209
|
+
if (body.length <= NOTE_CHAR_LIMIT) return [{ title, content: body }];
|
|
210
|
+
|
|
211
|
+
const chunks = [];
|
|
212
|
+
let remaining = body;
|
|
213
|
+
while (remaining.length > 0) {
|
|
214
|
+
if (remaining.length <= NOTE_CHAR_LIMIT) { chunks.push(remaining); break; }
|
|
215
|
+
const searchStart = Math.max(0, NOTE_CHAR_LIMIT - 500);
|
|
216
|
+
const slice = remaining.slice(searchStart, NOTE_CHAR_LIMIT);
|
|
217
|
+
const lastBreak = slice.lastIndexOf('\n\n');
|
|
218
|
+
const splitAt = lastBreak !== -1 ? searchStart + lastBreak + 2 : NOTE_CHAR_LIMIT;
|
|
219
|
+
chunks.push(remaining.slice(0, splitAt));
|
|
220
|
+
remaining = remaining.slice(splitAt);
|
|
221
|
+
}
|
|
222
|
+
return chunks.map((content, i) => ({ title: `${title} (Part ${i + 1})`, content }));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ─── Output formatting ───────────────────────────────────────────────────────
|
|
226
|
+
|
|
227
|
+
function formatElapsed(ms) { return `${(ms / 1000).toFixed(1)}s`; }
|
|
228
|
+
|
|
229
|
+
function printResult(result, opts) {
|
|
230
|
+
const { format = 'text', quiet = false } = opts;
|
|
231
|
+
if (quiet) return;
|
|
232
|
+
if (format === 'json') { process.stdout.write(JSON.stringify(result) + '\n'); return; }
|
|
233
|
+
|
|
234
|
+
const { created, skipped, overwritten, failed, elapsedMs, items = [] } = result;
|
|
235
|
+
const parts = [`${created} created`];
|
|
236
|
+
if (overwritten > 0) parts.push(`${overwritten} overwritten`);
|
|
237
|
+
parts.push(`${skipped} skipped`, `${failed} failed`);
|
|
238
|
+
process.stdout.write(`Import complete: ${parts.join(', ')} (${formatElapsed(elapsedMs)})\n`);
|
|
239
|
+
|
|
240
|
+
// Print summary table if there are items
|
|
241
|
+
if (items.length > 0) {
|
|
242
|
+
process.stdout.write('\n');
|
|
243
|
+
process.stdout.write('─'.repeat(80) + '\n');
|
|
244
|
+
process.stdout.write(`${'Status'.padEnd(12)} | ${'Source'.padEnd(50)} | Reason\n`);
|
|
245
|
+
process.stdout.write('─'.repeat(80) + '\n');
|
|
246
|
+
|
|
247
|
+
for (const item of items) {
|
|
248
|
+
const status = (item.status || 'unknown').padEnd(12);
|
|
249
|
+
const source = (item.source_path || '').slice(0, 48).padEnd(50);
|
|
250
|
+
let reason = '';
|
|
251
|
+
|
|
252
|
+
if (item.status === 'created') {
|
|
253
|
+
reason = `noteId: ${item.noteId}`;
|
|
254
|
+
} else if (item.status === 'skipped') {
|
|
255
|
+
reason = `noteId: ${item.noteId}`;
|
|
256
|
+
} else if (item.status === 'overwritten') {
|
|
257
|
+
reason = `noteId: ${item.noteId}`;
|
|
258
|
+
} else if (item.status === 'failed') {
|
|
259
|
+
reason = item.error || 'Unknown error';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
process.stdout.write(`${status} | ${source} | ${reason}\n`);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
process.stdout.write('─'.repeat(80) + '\n');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ─── Interactive prompt ──────────────────────────────────────────────────────
|
|
270
|
+
|
|
271
|
+
function createInterface() {
|
|
272
|
+
return readline.createInterface({
|
|
273
|
+
input: process.stdin,
|
|
274
|
+
output: process.stdout,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function promptYesNo(question) {
|
|
279
|
+
return new Promise((resolve) => {
|
|
280
|
+
const rl = createInterface();
|
|
281
|
+
rl.question(question, (answer) => {
|
|
282
|
+
rl.close();
|
|
283
|
+
const normalized = answer.trim().toLowerCase();
|
|
284
|
+
resolve(normalized === 'y' || normalized === 'yes');
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// ─── Main entry point ────────────────────────────────────────────────────────
|
|
290
|
+
|
|
291
|
+
export async function runImport(argv, deps = {}) {
|
|
292
|
+
const opts = parseImportArgs(argv);
|
|
293
|
+
const bridge = deps.requestBridge || requestBridge;
|
|
294
|
+
|
|
295
|
+
// Discover files
|
|
296
|
+
let files;
|
|
297
|
+
try {
|
|
298
|
+
files = await discoverFiles(opts.importPath, opts.ext);
|
|
299
|
+
} catch (err) {
|
|
300
|
+
process.stderr.write(`[IO_ERROR] Failed to read directory: ${err.message}\n`);
|
|
301
|
+
process.exit(1);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (files.length === 0) {
|
|
305
|
+
process.stderr.write(`[NO_FILES] No files found matching [${opts.ext.join(', ')}] in: ${opts.importPath}\n`);
|
|
306
|
+
process.exit(0);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Parse and split
|
|
310
|
+
const items = [];
|
|
311
|
+
for (const file of files) {
|
|
312
|
+
if (opts.verbose) process.stderr.write(` [parsing] ${file.relativePath}\n`);
|
|
313
|
+
|
|
314
|
+
const parsed = await parseFile(file.absolutePath, file.extension);
|
|
315
|
+
|
|
316
|
+
if (parsed.error && !parsed.body) {
|
|
317
|
+
if (opts.verbose) process.stderr.write(` [failed] ${file.relativePath} — ${parsed.error}\n`);
|
|
318
|
+
items.push({ title: parsed.title, content: '', source_path: file.relativePath, _parseError: parsed.error });
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const chunks = splitContent(parsed.title, parsed.body);
|
|
323
|
+
for (const chunk of chunks) {
|
|
324
|
+
items.push({ title: chunk.title, content: chunk.content, source_path: file.relativePath });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (opts.verbose) {
|
|
328
|
+
const suffix = chunks.length > 1 ? ` (split into ${chunks.length} parts)` : '';
|
|
329
|
+
process.stderr.write(` [done] ${file.relativePath} — "${parsed.title}"${suffix}\n`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const payload = {
|
|
334
|
+
items: items.map((item) => ({
|
|
335
|
+
title: item.title,
|
|
336
|
+
content: item._parseError ? '' : item.content,
|
|
337
|
+
source_path: item.source_path,
|
|
338
|
+
_parseError: item._parseError || null,
|
|
339
|
+
})),
|
|
340
|
+
folder: opts.folder,
|
|
341
|
+
tags: opts.tags,
|
|
342
|
+
conflict: opts.conflict,
|
|
343
|
+
// Always check first - we'll prompt if needed
|
|
344
|
+
create_folder_if_missing: false,
|
|
345
|
+
dry_run: opts.dryRun,
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const timeoutMs = Number(process.env.NOTESIA_CLI_BULK_TIMEOUT_MS) || 120_000;
|
|
349
|
+
const startMs = Date.now();
|
|
350
|
+
|
|
351
|
+
let response;
|
|
352
|
+
try {
|
|
353
|
+
response = await bridge({ op: 'bulk_import', payload }, { timeoutMs });
|
|
354
|
+
} catch (err) {
|
|
355
|
+
const code = err.code || 'BRIDGE_ERROR';
|
|
356
|
+
if (code === 'NOTESIA_APP_NOT_RUNNING') {
|
|
357
|
+
process.stderr.write('NOTESIA_APP_NOT_RUNNING\n');
|
|
358
|
+
process.exit(1);
|
|
359
|
+
}
|
|
360
|
+
process.stderr.write(`[${code}] ${err.message}\n`);
|
|
361
|
+
process.exit(1);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (!response || response.ok === false) {
|
|
365
|
+
const code = response?.error?.code || 'BRIDGE_ERROR';
|
|
366
|
+
const message = response?.error?.message || 'Bridge request failed';
|
|
367
|
+
|
|
368
|
+
// Handle folder not found - prompt user to create (only if --create-folder is set)
|
|
369
|
+
if (code === 'FOLDER_NOT_FOUND' && opts.folder && opts.createFolder) {
|
|
370
|
+
const folderName = response?.error?.folderName || opts.folder;
|
|
371
|
+
process.stdout.write(`\nFolder "${folderName}" does not exist in Notesia.\n`);
|
|
372
|
+
const shouldCreate = await promptYesNo('Do you want to create it and continue import? [y/N] ');
|
|
373
|
+
if (shouldCreate) {
|
|
374
|
+
// Retry with create_folder_if_missing = true
|
|
375
|
+
const retryPayload = { ...payload, create_folder_if_missing: true };
|
|
376
|
+
response = await bridge({ op: 'bulk_import', payload: retryPayload }, { timeoutMs });
|
|
377
|
+
if (response?.ok === false) {
|
|
378
|
+
const retryCode = response?.error?.code || 'BRIDGE_ERROR';
|
|
379
|
+
const retryMessage = response?.error?.message || 'Bridge request failed';
|
|
380
|
+
process.stderr.write(`[${retryCode}] ${retryMessage}\n`);
|
|
381
|
+
process.exit(1);
|
|
382
|
+
}
|
|
383
|
+
} else {
|
|
384
|
+
process.stderr.write('Import cancelled.\n');
|
|
385
|
+
process.exit(1);
|
|
386
|
+
}
|
|
387
|
+
} else if (code === 'FOLDER_NOT_FOUND' && opts.folder && !opts.createFolder) {
|
|
388
|
+
// User specified --no-create-folder, so just show the error
|
|
389
|
+
process.stderr.write(`[${code}] ${message}\n`);
|
|
390
|
+
process.exit(1);
|
|
391
|
+
} else {
|
|
392
|
+
process.stderr.write(`[${code}] ${message}\n`);
|
|
393
|
+
process.exit(1);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const result = { ...response.data, elapsedMs: response.data?.elapsedMs ?? (Date.now() - startMs) };
|
|
398
|
+
printResult(result, { format: opts.format, quiet: opts.quiet });
|
|
399
|
+
process.exit(result.failed === 0 ? 0 : 1);
|
|
400
|
+
}
|
package/src/io.mjs
CHANGED
|
@@ -170,7 +170,9 @@ export function printKbResult(op, result, {
|
|
|
170
170
|
if (citations.length > 0) {
|
|
171
171
|
writeStdout('\n\nSources:\n');
|
|
172
172
|
for (const c of citations) {
|
|
173
|
-
|
|
173
|
+
const sourceType = c.type ? `[${c.type.toUpperCase()}] ` : '';
|
|
174
|
+
const id = c.noteId ?? c.todoId ?? 'unknown';
|
|
175
|
+
writeStdout(` - ${sourceType}[${id}] ${c.title}\n`);
|
|
174
176
|
}
|
|
175
177
|
} else {
|
|
176
178
|
writeStdout('\n');
|