scrivener-mcp 0.1.4
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 +21 -0
- package/README.md +109 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +796 -0
- package/dist/index.js.map +1 -0
- package/dist/rtf-handler.d.ts +121 -0
- package/dist/rtf-handler.d.ts.map +1 -0
- package/dist/rtf-handler.js +583 -0
- package/dist/rtf-handler.js.map +1 -0
- package/dist/scrivener-project.d.ts +199 -0
- package/dist/scrivener-project.d.ts.map +1 -0
- package/dist/scrivener-project.js +855 -0
- package/dist/scrivener-project.js.map +1 -0
- package/dist/types/internal.d.ts +86 -0
- package/dist/types/internal.d.ts.map +1 -0
- package/dist/types/internal.js +7 -0
- package/dist/types/internal.js.map +1 -0
- package/package.json +82 -0
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
import * as fs from 'fs/promises';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { parseStringPromise, Builder } from 'xml2js';
|
|
4
|
+
import * as crypto from 'crypto';
|
|
5
|
+
import { RTFHandler } from './rtf-handler.js';
|
|
6
|
+
export class ScrivenerProject {
|
|
7
|
+
projectPath;
|
|
8
|
+
scrivxPath;
|
|
9
|
+
projectStructure;
|
|
10
|
+
rtfHandler;
|
|
11
|
+
documentCache;
|
|
12
|
+
cacheTimestamps;
|
|
13
|
+
/**
|
|
14
|
+
* Constructs a new ScrivenerProject instance.
|
|
15
|
+
* @param projectPath The absolute path to the `.scriv` project directory.
|
|
16
|
+
*/
|
|
17
|
+
constructor(projectPath) {
|
|
18
|
+
this.projectPath = path.resolve(projectPath);
|
|
19
|
+
const projectName = path.basename(projectPath, path.extname(projectPath));
|
|
20
|
+
this.scrivxPath = path.join(this.projectPath, `${projectName}.scrivx`);
|
|
21
|
+
this.rtfHandler = new RTFHandler();
|
|
22
|
+
this.documentCache = new Map();
|
|
23
|
+
this.cacheTimestamps = new Map();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Loads the Scrivener project's main `.scrivx` file into memory.
|
|
27
|
+
* @throws {Error} If the project file cannot be read or parsed.
|
|
28
|
+
*/
|
|
29
|
+
async loadProject() {
|
|
30
|
+
try {
|
|
31
|
+
const scrivxContent = await fs.readFile(this.scrivxPath, 'utf-8');
|
|
32
|
+
this.projectStructure = await parseStringPromise(scrivxContent, {
|
|
33
|
+
explicitArray: false,
|
|
34
|
+
mergeAttrs: true,
|
|
35
|
+
});
|
|
36
|
+
if (!this.projectStructure?.ScrivenerProject) {
|
|
37
|
+
throw new Error('Invalid Scrivener project structure: Missing ScrivenerProject element.');
|
|
38
|
+
}
|
|
39
|
+
// Binder might be an empty string if it was saved as <Binder/>, convert to object
|
|
40
|
+
if (this.projectStructure.ScrivenerProject.Binder === '') {
|
|
41
|
+
this.projectStructure.ScrivenerProject.Binder = {};
|
|
42
|
+
}
|
|
43
|
+
if (!this.projectStructure.ScrivenerProject.Binder) {
|
|
44
|
+
this.projectStructure.ScrivenerProject.Binder = {};
|
|
45
|
+
}
|
|
46
|
+
// Track when the project was loaded for modification detection
|
|
47
|
+
this.projectStructure._loadTime = Date.now();
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
const err = error;
|
|
51
|
+
if (err.code === 'ENOENT') {
|
|
52
|
+
throw new Error(`Scrivener project file not found at "${this.scrivxPath}". Ensure the path is correct.`);
|
|
53
|
+
}
|
|
54
|
+
else if (err.code === 'EACCES') {
|
|
55
|
+
throw new Error(`Permission denied reading project file at "${this.scrivxPath}".`);
|
|
56
|
+
}
|
|
57
|
+
else if (err.message?.includes('Invalid')) {
|
|
58
|
+
throw err; // Re-throw validation errors as-is
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
throw new Error(`Failed to load Scrivener project from "${this.scrivxPath}": ${err.message || String(error)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Saves the current project structure back to the `.scrivx` file.
|
|
67
|
+
* @throws {Error} If no project is currently loaded.
|
|
68
|
+
*/
|
|
69
|
+
async saveProject() {
|
|
70
|
+
if (!this.projectStructure) {
|
|
71
|
+
throw new Error('No project loaded to save.');
|
|
72
|
+
}
|
|
73
|
+
// Create a clean structure for saving (without internal properties)
|
|
74
|
+
const cleanProjectStructure = JSON.parse(JSON.stringify(this.projectStructure.ScrivenerProject));
|
|
75
|
+
const saveStructure = {
|
|
76
|
+
ScrivenerProject: cleanProjectStructure,
|
|
77
|
+
};
|
|
78
|
+
const builder = new Builder({
|
|
79
|
+
xmldec: { version: '1.0', encoding: 'UTF-8' },
|
|
80
|
+
renderOpts: { pretty: true, indent: ' ' },
|
|
81
|
+
});
|
|
82
|
+
const xml = builder.buildObject(saveStructure);
|
|
83
|
+
await fs.writeFile(this.scrivxPath, xml);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Retrieves the hierarchical structure of the entire project binder.
|
|
87
|
+
* @returns A promise that resolves to an array of ScrivenerDocument objects.
|
|
88
|
+
*/
|
|
89
|
+
async getProjectStructure() {
|
|
90
|
+
if (!this.projectStructure)
|
|
91
|
+
await this.loadProject();
|
|
92
|
+
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
93
|
+
if (!binder)
|
|
94
|
+
return [];
|
|
95
|
+
return this.parseBinderItems(binder.BinderItem || []);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Reads the plain text content of a specific document.
|
|
99
|
+
* Uses caching to improve performance for repeated reads.
|
|
100
|
+
* @param documentId The UUID of the document.
|
|
101
|
+
* @returns A promise that resolves to the document's plain text content.
|
|
102
|
+
* @throws {Error} If the document file cannot be read.
|
|
103
|
+
*/
|
|
104
|
+
async readDocument(documentId) {
|
|
105
|
+
const docPath = this.getDocumentPath(documentId);
|
|
106
|
+
try {
|
|
107
|
+
const rtfContent = await fs.readFile(docPath, 'utf-8');
|
|
108
|
+
return rtfContent;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
const err = error;
|
|
112
|
+
if (err.code === 'ENOENT') {
|
|
113
|
+
throw new Error(`[ENOENT] Document file not found for ${documentId} at "${docPath}". The document may have been deleted or moved.`);
|
|
114
|
+
}
|
|
115
|
+
else if (err.code === 'EACCES') {
|
|
116
|
+
throw new Error(`[EACCES] Permission denied reading document ${documentId} at "${docPath}".`);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
throw new Error(`Failed to read document ${documentId}: ${err.message || String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Reads the rich text formatted content of a specific document.
|
|
125
|
+
* Uses caching to improve performance for repeated reads.
|
|
126
|
+
* Cache entries expire after 5 minutes to balance performance with freshness.
|
|
127
|
+
* @param documentId The UUID of the document.
|
|
128
|
+
* @returns A promise that resolves to an RTFContent object.
|
|
129
|
+
* @throws {Error} If the document file cannot be read.
|
|
130
|
+
*/
|
|
131
|
+
async readDocumentFormatted(documentId) {
|
|
132
|
+
// Check cache first
|
|
133
|
+
const cached = this.documentCache.get(documentId);
|
|
134
|
+
const cacheTimestamp = this.cacheTimestamps.get(documentId);
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const CACHE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
|
|
137
|
+
if (cached && cacheTimestamp && now - cacheTimestamp < CACHE_EXPIRY_MS) {
|
|
138
|
+
return cached;
|
|
139
|
+
}
|
|
140
|
+
// Read from disk if not cached or expired
|
|
141
|
+
const docPath = this.getDocumentPath(documentId);
|
|
142
|
+
try {
|
|
143
|
+
const rtfContent = await this.rtfHandler.readRTF(docPath);
|
|
144
|
+
// Update cache
|
|
145
|
+
this.documentCache.set(documentId, rtfContent);
|
|
146
|
+
this.cacheTimestamps.set(documentId, now);
|
|
147
|
+
return rtfContent;
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
// Provide specific error messages based on error type
|
|
151
|
+
const err = error;
|
|
152
|
+
if (err.code === 'ENOENT') {
|
|
153
|
+
throw new Error(`[ENOENT] Document file not found for ${documentId} at "${docPath}". The document may have been deleted or moved.`);
|
|
154
|
+
}
|
|
155
|
+
else if (err.code === 'EACCES') {
|
|
156
|
+
throw new Error(`[EACCES] Permission denied reading document ${documentId} at "${docPath}".`);
|
|
157
|
+
}
|
|
158
|
+
else if (err.message?.includes('RTF')) {
|
|
159
|
+
throw new Error(`Invalid RTF format in document ${documentId} at "${docPath}": ${err.message}`);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
throw new Error(`Failed to read document ${documentId} at "${docPath}": ${err.message || String(error)}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Writes content to a specific document.
|
|
168
|
+
* Invalidates the cache for the modified document.
|
|
169
|
+
* @param documentId The UUID of the document.
|
|
170
|
+
* @param content The plain text or RTFContent object to write.
|
|
171
|
+
* @throws {Error} If the document file cannot be written.
|
|
172
|
+
*/
|
|
173
|
+
async writeDocument(documentId, content) {
|
|
174
|
+
if (!documentId || documentId.trim() === '') {
|
|
175
|
+
throw new Error(`[EINVAL] Invalid document ID: cannot be empty`);
|
|
176
|
+
}
|
|
177
|
+
const docPath = this.getDocumentPath(documentId);
|
|
178
|
+
try {
|
|
179
|
+
await this.rtfHandler.writeRTF(docPath, content);
|
|
180
|
+
// Invalidate cache for this document
|
|
181
|
+
this.documentCache.delete(documentId);
|
|
182
|
+
this.cacheTimestamps.delete(documentId);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
const err = error;
|
|
186
|
+
if (err.code === 'ENOENT') {
|
|
187
|
+
throw new Error(`[ENOENT] Directory not found for document ${documentId}. Ensure the project structure is valid.`);
|
|
188
|
+
}
|
|
189
|
+
else if (err.code === 'EACCES') {
|
|
190
|
+
throw new Error(`[EACCES] Permission denied writing document ${documentId} at "${docPath}".`);
|
|
191
|
+
}
|
|
192
|
+
else if (err.code === 'ENOSPC') {
|
|
193
|
+
throw new Error(`[ENOSPC] No space left on device to write document ${documentId}.`);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
throw new Error(`Failed to write document ${documentId} at "${docPath}": ${err.message || String(error)}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Creates a new document or folder and adds it to the project.
|
|
202
|
+
* @param parentId The UUID of the parent folder, or null to add to the root.
|
|
203
|
+
* @param title The title of the new item.
|
|
204
|
+
* @param type The type of item to create ('Text' or 'Folder').
|
|
205
|
+
* @returns A promise that resolves to the UUID of the newly created item.
|
|
206
|
+
* @throws {Error} If the parent document is not found.
|
|
207
|
+
*/
|
|
208
|
+
async createDocument(parentId, title, type = 'Text') {
|
|
209
|
+
if (!this.projectStructure)
|
|
210
|
+
await this.loadProject();
|
|
211
|
+
const uuid = crypto.randomUUID().toUpperCase();
|
|
212
|
+
const newItem = {
|
|
213
|
+
UUID: uuid,
|
|
214
|
+
Type: type,
|
|
215
|
+
Title: title,
|
|
216
|
+
MetaData: {
|
|
217
|
+
IncludeInCompile: 'Yes',
|
|
218
|
+
Created: new Date().toISOString(),
|
|
219
|
+
Modified: new Date().toISOString(),
|
|
220
|
+
},
|
|
221
|
+
Children: type === 'Folder' ? { BinderItem: [] } : undefined,
|
|
222
|
+
};
|
|
223
|
+
if (type === 'Text') {
|
|
224
|
+
const docPath = this.getDocumentPath(uuid);
|
|
225
|
+
// Create directory structure for the document
|
|
226
|
+
await fs.mkdir(path.dirname(docPath), { recursive: true });
|
|
227
|
+
await this.rtfHandler.writeRTF(docPath, '');
|
|
228
|
+
}
|
|
229
|
+
let targetContainer = this.projectStructure?.ScrivenerProject?.Binder;
|
|
230
|
+
if (!targetContainer) {
|
|
231
|
+
throw new Error('Project structure is invalid.');
|
|
232
|
+
}
|
|
233
|
+
if (parentId) {
|
|
234
|
+
const parent = this.findBinderItem(targetContainer, parentId);
|
|
235
|
+
if (!parent || parent?.Type !== 'Folder') {
|
|
236
|
+
throw new Error(`Parent ${parentId} not found or is not a folder.`);
|
|
237
|
+
}
|
|
238
|
+
targetContainer = parent.Children;
|
|
239
|
+
}
|
|
240
|
+
if (!targetContainer) {
|
|
241
|
+
throw new Error('Target container is not available.');
|
|
242
|
+
}
|
|
243
|
+
this.addToBinderContainer(targetContainer, newItem);
|
|
244
|
+
await this.saveProject();
|
|
245
|
+
return uuid;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Deletes a document or folder from the project.
|
|
249
|
+
* @param documentId The UUID of the item to delete.
|
|
250
|
+
* @throws {Error} If the document is not found.
|
|
251
|
+
*/
|
|
252
|
+
async deleteDocument(documentId) {
|
|
253
|
+
if (!this.projectStructure)
|
|
254
|
+
await this.loadProject();
|
|
255
|
+
const docPath = this.getDocumentPath(documentId);
|
|
256
|
+
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
257
|
+
if (!binder) {
|
|
258
|
+
throw new Error('Project structure is invalid.');
|
|
259
|
+
}
|
|
260
|
+
if (!this.deleteBinderItem(binder, documentId, true)) {
|
|
261
|
+
throw new Error(`Document ${documentId} not found.`);
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
await fs.unlink(docPath);
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
const err = error;
|
|
268
|
+
if (err.code !== 'ENOENT') {
|
|
269
|
+
console.error(`Warning: Could not delete RTF file for document ${documentId}: ${err.message || String(error)}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
await this.saveProject();
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Renames a document in the binder.
|
|
276
|
+
* @param documentId The UUID of the document to rename.
|
|
277
|
+
* @param newTitle The new title for the document.
|
|
278
|
+
* @throws {Error} If the document is not found.
|
|
279
|
+
*/
|
|
280
|
+
async renameDocument(documentId, newTitle) {
|
|
281
|
+
if (!this.projectStructure)
|
|
282
|
+
await this.loadProject();
|
|
283
|
+
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
284
|
+
if (!binder) {
|
|
285
|
+
throw new Error('Project structure is invalid.');
|
|
286
|
+
}
|
|
287
|
+
const item = this.findBinderItem(binder, documentId);
|
|
288
|
+
if (!item) {
|
|
289
|
+
throw new Error(`Document with ID "${documentId}" not found.`);
|
|
290
|
+
}
|
|
291
|
+
item.Title = newTitle;
|
|
292
|
+
this.updateModifiedDate(item);
|
|
293
|
+
await this.saveProject();
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Moves a document or folder to a new parent folder.
|
|
297
|
+
* @param documentId The UUID of the item to move.
|
|
298
|
+
* @param newParentId The UUID of the new parent folder, or null to move to the root.
|
|
299
|
+
* @throws {Error} If the document or new parent is not found.
|
|
300
|
+
*/
|
|
301
|
+
async moveDocument(documentId, newParentId) {
|
|
302
|
+
if (!this.projectStructure)
|
|
303
|
+
await this.loadProject();
|
|
304
|
+
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
305
|
+
if (!binder) {
|
|
306
|
+
throw new Error('Project structure is invalid.');
|
|
307
|
+
}
|
|
308
|
+
// Check if trying to move item to itself (no-op)
|
|
309
|
+
if (documentId === newParentId) {
|
|
310
|
+
return; // No operation needed
|
|
311
|
+
}
|
|
312
|
+
const extractedItem = this.extractBinderItem(binder, documentId);
|
|
313
|
+
if (!extractedItem) {
|
|
314
|
+
throw new Error(`Document ${documentId} not found.`);
|
|
315
|
+
}
|
|
316
|
+
if (newParentId) {
|
|
317
|
+
const newParent = this.findBinderItem(binder, newParentId);
|
|
318
|
+
if (!newParent || newParent?.Type !== 'Folder') {
|
|
319
|
+
throw new Error(`Parent ${newParentId} not found or is not a folder.`);
|
|
320
|
+
}
|
|
321
|
+
if (!newParent.Children) {
|
|
322
|
+
newParent.Children = { BinderItem: [] };
|
|
323
|
+
}
|
|
324
|
+
this.addToBinderContainer(newParent.Children, extractedItem);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
// Move to the root
|
|
328
|
+
this.addToBinderContainer(binder, extractedItem);
|
|
329
|
+
}
|
|
330
|
+
this.updateModifiedDate(extractedItem);
|
|
331
|
+
await this.saveProject();
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Refreshes the in-memory project state by reloading the .scrivx file.
|
|
335
|
+
* WARNING: This will overwrite any unsaved in-memory changes.
|
|
336
|
+
* Also clears the document cache to ensure fresh reads.
|
|
337
|
+
*/
|
|
338
|
+
async refreshProject() {
|
|
339
|
+
// Refreshing project from disk
|
|
340
|
+
// Clear all caches
|
|
341
|
+
this.documentCache.clear();
|
|
342
|
+
this.cacheTimestamps.clear();
|
|
343
|
+
// Reload project structure
|
|
344
|
+
await this.loadProject();
|
|
345
|
+
// Project refresh complete. Cache cleared.
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Checks if the project file has been modified since last load.
|
|
349
|
+
* @returns True if the project file has been modified externally.
|
|
350
|
+
*/
|
|
351
|
+
async isProjectModified() {
|
|
352
|
+
try {
|
|
353
|
+
const stats = await fs.stat(this.scrivxPath);
|
|
354
|
+
const lastLoadTime = this.projectStructure?._loadTime;
|
|
355
|
+
if (!lastLoadTime) {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
return stats.mtime.getTime() > lastLoadTime;
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Clears the document cache for a specific document or all documents.
|
|
366
|
+
* @param documentId Optional document ID to clear. If not provided, clears all.
|
|
367
|
+
*/
|
|
368
|
+
clearCache(documentId) {
|
|
369
|
+
if (documentId) {
|
|
370
|
+
this.documentCache.delete(documentId);
|
|
371
|
+
this.cacheTimestamps.delete(documentId);
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
this.documentCache.clear();
|
|
375
|
+
this.cacheTimestamps.clear();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Updates the metadata for a specific document.
|
|
380
|
+
* @param documentId The UUID of the document.
|
|
381
|
+
* @param metadata The partial metadata object to update.
|
|
382
|
+
* @throws {Error} If the document is not found.
|
|
383
|
+
*/
|
|
384
|
+
async updateMetadata(documentId, metadata) {
|
|
385
|
+
if (!this.projectStructure)
|
|
386
|
+
await this.loadProject();
|
|
387
|
+
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
388
|
+
if (!binder) {
|
|
389
|
+
throw new Error('Project structure is invalid.');
|
|
390
|
+
}
|
|
391
|
+
const item = this.findBinderItem(binder, documentId);
|
|
392
|
+
if (!item) {
|
|
393
|
+
throw new Error(`Document ${documentId} not found.`);
|
|
394
|
+
}
|
|
395
|
+
if (!item.MetaData) {
|
|
396
|
+
item.MetaData = {};
|
|
397
|
+
}
|
|
398
|
+
const metaData = item.MetaData;
|
|
399
|
+
if (metadata.title !== undefined) {
|
|
400
|
+
item.Title = metadata.title;
|
|
401
|
+
}
|
|
402
|
+
if (metadata.keywords) {
|
|
403
|
+
metaData.Keywords = metadata.keywords.join(',');
|
|
404
|
+
}
|
|
405
|
+
if (metadata.customFields) {
|
|
406
|
+
if (!metaData.CustomMetaData) {
|
|
407
|
+
metaData.CustomMetaData = { MetaDataItem: [] };
|
|
408
|
+
}
|
|
409
|
+
const customMetaItems = Array.isArray(metaData.CustomMetaData.MetaDataItem)
|
|
410
|
+
? metaData.CustomMetaData.MetaDataItem
|
|
411
|
+
: metaData.CustomMetaData.MetaDataItem
|
|
412
|
+
? [metaData.CustomMetaData.MetaDataItem]
|
|
413
|
+
: [];
|
|
414
|
+
Object.entries(metadata.customFields).forEach(([key, value]) => {
|
|
415
|
+
const existing = customMetaItems.find((mdItem) => mdItem?.ID === key);
|
|
416
|
+
if (existing) {
|
|
417
|
+
existing.Value = value;
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
customMetaItems.push({
|
|
421
|
+
ID: key,
|
|
422
|
+
Value: value,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
metaData.CustomMetaData.MetaDataItem = customMetaItems;
|
|
427
|
+
}
|
|
428
|
+
this.updateModifiedDate(item);
|
|
429
|
+
await this.saveProject();
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Retrieves the combined word and character count for a specific document or the entire project.
|
|
433
|
+
* @param documentId The UUID of the document. If not provided, the entire project is counted.
|
|
434
|
+
* @returns An object with `words` and `characters` counts.
|
|
435
|
+
*/
|
|
436
|
+
async getWordCount(documentId) {
|
|
437
|
+
let content = '';
|
|
438
|
+
if (documentId) {
|
|
439
|
+
content = await this.readDocument(documentId);
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
const docs = await this.getAllDocuments();
|
|
443
|
+
const textDocs = docs.filter((doc) => doc.type === 'Text');
|
|
444
|
+
const promises = textDocs.map((doc) => this.readDocument(doc.id).catch(() => ''));
|
|
445
|
+
const allContents = await Promise.all(promises);
|
|
446
|
+
content = allContents.join(' ');
|
|
447
|
+
}
|
|
448
|
+
const words = content
|
|
449
|
+
.trim()
|
|
450
|
+
.split(/\s+/)
|
|
451
|
+
.filter((word) => word.length > 0).length;
|
|
452
|
+
const characters = content.length;
|
|
453
|
+
return { words, characters };
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Compiles the content of multiple documents into a single string or formatted object.
|
|
457
|
+
* @param documentIds An array of UUIDs for the documents to compile.
|
|
458
|
+
* @param separator The string to use between documents.
|
|
459
|
+
* @param outputFormat The desired output format ('text', 'markdown', or 'html').
|
|
460
|
+
* @returns A promise that resolves to the compiled content.
|
|
461
|
+
*/
|
|
462
|
+
async compileDocuments(documentIds, separator = '\n\n', outputFormat = 'text') {
|
|
463
|
+
const promises = documentIds.map((id) => this.readDocumentFormatted(id).catch(() => null));
|
|
464
|
+
const rtfContents = (await Promise.all(promises)).filter(Boolean);
|
|
465
|
+
if (outputFormat === 'text') {
|
|
466
|
+
const plainTexts = rtfContents.map((c) => c.plainText).filter((text) => text.trim());
|
|
467
|
+
return plainTexts.join(separator);
|
|
468
|
+
}
|
|
469
|
+
if (outputFormat === 'json') {
|
|
470
|
+
// Return structured JSON representation
|
|
471
|
+
return JSON.stringify({
|
|
472
|
+
documents: rtfContents.map((content, index) => ({
|
|
473
|
+
id: documentIds[index],
|
|
474
|
+
plainText: content.plainText,
|
|
475
|
+
formattedText: content.formattedText,
|
|
476
|
+
})),
|
|
477
|
+
totalWordCount: rtfContents.reduce((sum, c) => sum + c.plainText.split(/\s+/).length, 0),
|
|
478
|
+
}, null, 2);
|
|
479
|
+
}
|
|
480
|
+
let compiledContent = '';
|
|
481
|
+
for (let i = 0; i < rtfContents.length; i++) {
|
|
482
|
+
const content = rtfContents[i];
|
|
483
|
+
if (content.plainText.trim()) {
|
|
484
|
+
if (outputFormat === 'markdown') {
|
|
485
|
+
content.formattedText.forEach((part) => {
|
|
486
|
+
let text = part.text;
|
|
487
|
+
if (part.style?.bold)
|
|
488
|
+
text = `**${text}**`;
|
|
489
|
+
if (part.style?.italic)
|
|
490
|
+
text = `*${text}*`;
|
|
491
|
+
compiledContent += text;
|
|
492
|
+
});
|
|
493
|
+
if (i < rtfContents.length - 1)
|
|
494
|
+
compiledContent += separator;
|
|
495
|
+
}
|
|
496
|
+
else if (outputFormat === 'html') {
|
|
497
|
+
content.formattedText.forEach((part) => {
|
|
498
|
+
let text = part.text;
|
|
499
|
+
if (part.style?.bold)
|
|
500
|
+
text = `<b>${text}</b>`;
|
|
501
|
+
if (part.style?.italic)
|
|
502
|
+
text = `<i>${text}</i>`;
|
|
503
|
+
compiledContent += text;
|
|
504
|
+
});
|
|
505
|
+
if (i < rtfContents.length - 1)
|
|
506
|
+
compiledContent += separator;
|
|
507
|
+
}
|
|
508
|
+
else if (outputFormat === 'latex') {
|
|
509
|
+
// LaTeX output format
|
|
510
|
+
content.formattedText.forEach((part) => {
|
|
511
|
+
let text = part.text
|
|
512
|
+
.replace(/\\/g, '\\textbackslash{}')
|
|
513
|
+
.replace(/[{}]/g, '\\$&')
|
|
514
|
+
.replace(/[_%#&$]/g, '\\$&');
|
|
515
|
+
if (part.style?.bold && part.style?.italic) {
|
|
516
|
+
text = `\\textbf{\\textit{${text}}}`;
|
|
517
|
+
}
|
|
518
|
+
else if (part.style?.bold) {
|
|
519
|
+
text = `\\textbf{${text}}`;
|
|
520
|
+
}
|
|
521
|
+
else if (part.style?.italic) {
|
|
522
|
+
text = `\\textit{${text}}`;
|
|
523
|
+
}
|
|
524
|
+
compiledContent += text;
|
|
525
|
+
});
|
|
526
|
+
if (i < rtfContents.length - 1) {
|
|
527
|
+
compiledContent += '\n\n\\par\n\n';
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return compiledContent;
|
|
533
|
+
}
|
|
534
|
+
async searchContent(query, options) {
|
|
535
|
+
if (!this.projectStructure)
|
|
536
|
+
await this.loadProject();
|
|
537
|
+
const results = [];
|
|
538
|
+
const documents = await this.getAllDocuments();
|
|
539
|
+
for (const doc of documents) {
|
|
540
|
+
if (doc.type === 'Text') {
|
|
541
|
+
const matches = [];
|
|
542
|
+
let content = '';
|
|
543
|
+
try {
|
|
544
|
+
// Read content for text search
|
|
545
|
+
content = await this.readDocument(doc.id);
|
|
546
|
+
matches.push(...this.findMatches(content, query, options));
|
|
547
|
+
}
|
|
548
|
+
catch {
|
|
549
|
+
// Skip documents that can't be read
|
|
550
|
+
}
|
|
551
|
+
// Search in metadata if requested
|
|
552
|
+
if (options?.searchMetadata) {
|
|
553
|
+
if (doc.title.toLowerCase().includes(query.toLowerCase())) {
|
|
554
|
+
matches.push(`Title match: ${doc.title}`);
|
|
555
|
+
}
|
|
556
|
+
if (doc.label?.toLowerCase().includes(query.toLowerCase())) {
|
|
557
|
+
matches.push(`Label match: ${doc.label}`);
|
|
558
|
+
}
|
|
559
|
+
if (doc.status?.toLowerCase().includes(query.toLowerCase())) {
|
|
560
|
+
matches.push(`Status match: ${doc.status}`);
|
|
561
|
+
}
|
|
562
|
+
if (doc.synopsis?.toLowerCase().includes(query.toLowerCase())) {
|
|
563
|
+
matches.push(`Synopsis match: ${doc.synopsis}`);
|
|
564
|
+
}
|
|
565
|
+
if (doc.keywords) {
|
|
566
|
+
for (const keyword of doc.keywords) {
|
|
567
|
+
if (keyword.toLowerCase().includes(query.toLowerCase())) {
|
|
568
|
+
matches.push(`Keyword match: ${keyword}`);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (matches.length > 0) {
|
|
574
|
+
results.push({
|
|
575
|
+
documentId: doc.id,
|
|
576
|
+
title: doc.title,
|
|
577
|
+
matches,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return results;
|
|
583
|
+
}
|
|
584
|
+
findMatches(content, query, options) {
|
|
585
|
+
const matches = [];
|
|
586
|
+
if (options?.regex) {
|
|
587
|
+
const flags = options.caseSensitive ? 'g' : 'gi';
|
|
588
|
+
const regex = new RegExp(query, flags);
|
|
589
|
+
const found = content.match(regex);
|
|
590
|
+
if (found)
|
|
591
|
+
matches.push(...found);
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
const searchContent = options?.caseSensitive ? content : content.toLowerCase();
|
|
595
|
+
const searchQuery = options?.caseSensitive ? query : query.toLowerCase();
|
|
596
|
+
let index = searchContent.indexOf(searchQuery);
|
|
597
|
+
while (index !== -1) {
|
|
598
|
+
const contextStart = Math.max(0, index - 50);
|
|
599
|
+
const contextEnd = Math.min(content.length, index + query.length + 50);
|
|
600
|
+
matches.push(content.substring(contextStart, contextEnd));
|
|
601
|
+
index = searchContent.indexOf(searchQuery, index + 1);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return matches;
|
|
605
|
+
}
|
|
606
|
+
parseBinderItems(items) {
|
|
607
|
+
if (!items)
|
|
608
|
+
return [];
|
|
609
|
+
if (Array.isArray(items) && items.length === 0)
|
|
610
|
+
return [];
|
|
611
|
+
const itemArray = Array.isArray(items) ? items : [items];
|
|
612
|
+
return itemArray.map((item) => this.parseBinderItem(item));
|
|
613
|
+
}
|
|
614
|
+
parseBinderItem(item) {
|
|
615
|
+
// With mergeAttrs: true, attributes are directly on the item
|
|
616
|
+
const uuid = item?.UUID || item?.ID || '';
|
|
617
|
+
const itemType = item?.Type;
|
|
618
|
+
const docType = itemType === 'Text' || itemType === 'Folder' ? itemType : 'Other';
|
|
619
|
+
const doc = {
|
|
620
|
+
id: uuid,
|
|
621
|
+
title: item.Title || 'Untitled',
|
|
622
|
+
type: docType,
|
|
623
|
+
path: this.getDocumentPath(uuid),
|
|
624
|
+
children: [],
|
|
625
|
+
};
|
|
626
|
+
if (item.MetaData) {
|
|
627
|
+
// With explicitArray: false, MetaData is an object
|
|
628
|
+
const metadata = item.MetaData;
|
|
629
|
+
doc.includeInCompile = metadata.IncludeInCompile === 'Yes';
|
|
630
|
+
doc.label = metadata.Label;
|
|
631
|
+
doc.status = metadata.Status;
|
|
632
|
+
// Parse synopsis if present
|
|
633
|
+
if (metadata.Synopsis) {
|
|
634
|
+
doc.synopsis = metadata.Synopsis;
|
|
635
|
+
}
|
|
636
|
+
// Parse notes if present
|
|
637
|
+
if (metadata.Notes) {
|
|
638
|
+
doc.notes = metadata.Notes;
|
|
639
|
+
}
|
|
640
|
+
// Parse keywords if present
|
|
641
|
+
if (metadata.Keywords) {
|
|
642
|
+
// With explicitArray: false, Keywords is a string
|
|
643
|
+
if (typeof metadata.Keywords === 'string') {
|
|
644
|
+
doc.keywords = metadata.Keywords.split(';')
|
|
645
|
+
.map((k) => k.trim())
|
|
646
|
+
.filter((k) => k);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (metadata.CustomMetaData?.MetaDataItem) {
|
|
650
|
+
doc.customMetadata = {};
|
|
651
|
+
const metaItems = Array.isArray(metadata.CustomMetaData.MetaDataItem)
|
|
652
|
+
? metadata.CustomMetaData.MetaDataItem
|
|
653
|
+
: [metadata.CustomMetaData.MetaDataItem];
|
|
654
|
+
metaItems.forEach((mdItem) => {
|
|
655
|
+
// With mergeAttrs: true, ID is directly on the item
|
|
656
|
+
const itemId = mdItem.ID || mdItem.id;
|
|
657
|
+
const itemValue = mdItem.Value || mdItem._ || mdItem;
|
|
658
|
+
if (itemId && itemValue && typeof itemValue === 'string') {
|
|
659
|
+
doc.customMetadata[itemId] = itemValue;
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
if (item.Children?.BinderItem) {
|
|
665
|
+
// parseBinderItems handles both single items and arrays
|
|
666
|
+
doc.children = this.parseBinderItems(item.Children.BinderItem);
|
|
667
|
+
}
|
|
668
|
+
return doc;
|
|
669
|
+
}
|
|
670
|
+
getDocumentPath(uuid) {
|
|
671
|
+
return path.join(this.projectPath, 'Files', 'Data', uuid, 'content.rtf');
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Helper function to safely add an item to a BinderContainer
|
|
675
|
+
*/
|
|
676
|
+
addToBinderContainer(container, item) {
|
|
677
|
+
if (!container.BinderItem) {
|
|
678
|
+
container.BinderItem = [item];
|
|
679
|
+
}
|
|
680
|
+
else if (Array.isArray(container.BinderItem)) {
|
|
681
|
+
container.BinderItem.push(item);
|
|
682
|
+
}
|
|
683
|
+
else {
|
|
684
|
+
// If it was a single item, convert to array and add
|
|
685
|
+
container.BinderItem = [container.BinderItem, item];
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Helper function to find a binder item by its UUID.
|
|
690
|
+
*/
|
|
691
|
+
findBinderItem(container, uuid) {
|
|
692
|
+
if (!container?.BinderItem)
|
|
693
|
+
return null;
|
|
694
|
+
// Handle both single item and array cases
|
|
695
|
+
const items = Array.isArray(container.BinderItem)
|
|
696
|
+
? container.BinderItem
|
|
697
|
+
: [container.BinderItem];
|
|
698
|
+
for (const item of items) {
|
|
699
|
+
if (item?.UUID === uuid)
|
|
700
|
+
return item;
|
|
701
|
+
if (item.Children?.BinderItem) {
|
|
702
|
+
const found = this.findBinderItem(item.Children, uuid);
|
|
703
|
+
if (found)
|
|
704
|
+
return found;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Helper function to extract and return a binder item by its UUID,
|
|
711
|
+
* removing it from its current location.
|
|
712
|
+
*/
|
|
713
|
+
extractBinderItem(container, uuid) {
|
|
714
|
+
if (!container?.BinderItem)
|
|
715
|
+
return null;
|
|
716
|
+
// Handle both single item and array cases
|
|
717
|
+
const items = Array.isArray(container.BinderItem)
|
|
718
|
+
? container.BinderItem
|
|
719
|
+
: [container.BinderItem];
|
|
720
|
+
const index = items.findIndex((item) => item?.UUID === uuid);
|
|
721
|
+
if (index !== -1) {
|
|
722
|
+
if (Array.isArray(container.BinderItem)) {
|
|
723
|
+
const [item] = container.BinderItem.splice(index, 1);
|
|
724
|
+
// If array becomes empty, remove the property entirely
|
|
725
|
+
if (container.BinderItem.length === 0) {
|
|
726
|
+
delete container.BinderItem;
|
|
727
|
+
}
|
|
728
|
+
return item;
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
// If it was a single item, extract it and remove the property
|
|
732
|
+
const item = container.BinderItem;
|
|
733
|
+
delete container.BinderItem;
|
|
734
|
+
return item;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
for (const item of items) {
|
|
738
|
+
if (item.Children?.BinderItem) {
|
|
739
|
+
const extracted = this.extractBinderItem(item.Children, uuid);
|
|
740
|
+
if (extracted)
|
|
741
|
+
return extracted;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return null;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Helper function to delete a binder item by its UUID.
|
|
748
|
+
*/
|
|
749
|
+
deleteBinderItem(container, uuid, isRoot = false) {
|
|
750
|
+
if (!container?.BinderItem)
|
|
751
|
+
return false;
|
|
752
|
+
// Handle both single item and array cases
|
|
753
|
+
const items = Array.isArray(container.BinderItem)
|
|
754
|
+
? container.BinderItem
|
|
755
|
+
: [container.BinderItem];
|
|
756
|
+
const index = items.findIndex((item) => item?.UUID === uuid);
|
|
757
|
+
if (index !== -1) {
|
|
758
|
+
if (Array.isArray(container.BinderItem)) {
|
|
759
|
+
container.BinderItem.splice(index, 1);
|
|
760
|
+
// If array becomes empty, remove the property entirely (but not for root Binder)
|
|
761
|
+
if (container.BinderItem.length === 0 && !isRoot) {
|
|
762
|
+
delete container.BinderItem;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
else {
|
|
766
|
+
// If it was a single item and we're deleting it, remove the property (but not for root Binder)
|
|
767
|
+
if (!isRoot) {
|
|
768
|
+
delete container.BinderItem;
|
|
769
|
+
}
|
|
770
|
+
else {
|
|
771
|
+
container.BinderItem = [];
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
for (const item of items) {
|
|
777
|
+
if (item.Children?.BinderItem) {
|
|
778
|
+
if (this.deleteBinderItem(item.Children, uuid))
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
return false;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Helper function to get a flat list of all documents in the project.
|
|
786
|
+
*/
|
|
787
|
+
async getAllDocuments() {
|
|
788
|
+
const structure = await this.getProjectStructure();
|
|
789
|
+
const allDocs = [];
|
|
790
|
+
const traverse = (docs) => {
|
|
791
|
+
for (const doc of docs) {
|
|
792
|
+
allDocs.push(doc);
|
|
793
|
+
if (doc.children)
|
|
794
|
+
traverse(doc.children);
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
traverse(structure);
|
|
798
|
+
return allDocs;
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Helper function to update the modification date of an item.
|
|
802
|
+
*/
|
|
803
|
+
updateModifiedDate(item) {
|
|
804
|
+
if (!item.MetaData) {
|
|
805
|
+
item.MetaData = {};
|
|
806
|
+
}
|
|
807
|
+
item.MetaData.Modified = new Date().toISOString();
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Gets Scrivener annotations from a document.
|
|
811
|
+
* @param documentId The UUID of the document.
|
|
812
|
+
* @returns A Map of annotation IDs to their content.
|
|
813
|
+
*/
|
|
814
|
+
async getDocumentAnnotations(documentId) {
|
|
815
|
+
const docPath = this.getDocumentPath(documentId);
|
|
816
|
+
try {
|
|
817
|
+
const rtfContent = await fs.readFile(docPath, 'utf-8');
|
|
818
|
+
return this.rtfHandler.preserveScrivenerAnnotations(rtfContent);
|
|
819
|
+
}
|
|
820
|
+
catch (error) {
|
|
821
|
+
const err = error;
|
|
822
|
+
if (err.code === 'ENOENT') {
|
|
823
|
+
throw new Error(`Document file not found for ${documentId}. The document may not have content yet.`);
|
|
824
|
+
}
|
|
825
|
+
else {
|
|
826
|
+
throw new Error(`Failed to get annotations for document ${documentId}: ${err.message || String(error)}`);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Gets project-level metadata.
|
|
832
|
+
* @returns Project metadata including title, author, and targets.
|
|
833
|
+
*/
|
|
834
|
+
async getProjectMetadata() {
|
|
835
|
+
if (!this.projectStructure)
|
|
836
|
+
await this.loadProject();
|
|
837
|
+
const metadata = {};
|
|
838
|
+
const project = this.projectStructure?.ScrivenerProject;
|
|
839
|
+
if (project?.ProjectSettings) {
|
|
840
|
+
const settings = project.ProjectSettings;
|
|
841
|
+
metadata.title = settings.ProjectTitle;
|
|
842
|
+
metadata.author = settings.FullName || settings.Author;
|
|
843
|
+
}
|
|
844
|
+
if (project?.ProjectTargets) {
|
|
845
|
+
const targets = project.ProjectTargets;
|
|
846
|
+
metadata.projectTargets = {
|
|
847
|
+
draft: targets.DraftTarget ? parseInt(targets.DraftTarget) : undefined,
|
|
848
|
+
session: targets.SessionTarget ? parseInt(targets.SessionTarget) : undefined,
|
|
849
|
+
deadline: targets.Deadline,
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
return metadata;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
//# sourceMappingURL=scrivener-project.js.map
|