scrivener-mcp 0.3.0 → 0.3.2
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 +207 -15
- package/dist/analysis/advanced-readability.d.ts +168 -0
- package/dist/analysis/advanced-readability.d.ts.map +1 -0
- package/dist/analysis/advanced-readability.js +730 -0
- package/dist/analysis/advanced-readability.js.map +1 -0
- package/dist/analysis/base-analyzer.d.ts +188 -0
- package/dist/analysis/base-analyzer.d.ts.map +1 -0
- package/dist/analysis/base-analyzer.js +846 -0
- package/dist/analysis/base-analyzer.js.map +1 -0
- package/dist/analysis/context-analyzer.d.ts +183 -0
- package/dist/analysis/context-analyzer.d.ts.map +1 -0
- package/dist/analysis/context-analyzer.js +582 -0
- package/dist/analysis/context-analyzer.js.map +1 -0
- package/dist/analysis/index.d.ts +8 -0
- package/dist/analysis/index.d.ts.map +1 -0
- package/dist/analysis/index.js +6 -0
- package/dist/analysis/index.js.map +1 -0
- package/dist/analysis/ml-word-classifier-pro.d.ts +108 -0
- package/dist/analysis/ml-word-classifier-pro.d.ts.map +1 -0
- package/dist/analysis/ml-word-classifier-pro.js +475 -0
- package/dist/analysis/ml-word-classifier-pro.js.map +1 -0
- package/dist/cli/setup-wizard.d.ts +34 -0
- package/dist/cli/setup-wizard.d.ts.map +1 -0
- package/dist/cli/setup-wizard.js +150 -0
- package/dist/cli/setup-wizard.js.map +1 -0
- package/dist/content-analyzer.d.ts +85 -1
- package/dist/content-analyzer.d.ts.map +1 -1
- package/dist/content-analyzer.js +515 -111
- package/dist/content-analyzer.js.map +1 -1
- package/dist/core/cache.d.ts +90 -0
- package/dist/core/cache.d.ts.map +1 -0
- package/dist/core/cache.js +240 -0
- package/dist/core/cache.js.map +1 -0
- package/dist/core/constants.d.ts +222 -0
- package/dist/core/constants.d.ts.map +1 -0
- package/dist/core/constants.js +178 -0
- package/dist/core/constants.js.map +1 -0
- package/dist/core/errors.d.ts +118 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +184 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/logger.d.ts +40 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +116 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/validation.d.ts +82 -0
- package/dist/core/validation.d.ts.map +1 -0
- package/dist/core/validation.js +208 -0
- package/dist/core/validation.js.map +1 -0
- package/dist/database/auto-installer.d.ts +99 -0
- package/dist/database/auto-installer.d.ts.map +1 -0
- package/dist/database/auto-installer.js +574 -0
- package/dist/database/auto-installer.js.map +1 -0
- package/dist/database/config.d.ts +29 -0
- package/dist/database/config.d.ts.map +1 -0
- package/dist/database/config.js +24 -0
- package/dist/database/config.js.map +1 -0
- package/dist/database/connection-pool.d.ts +87 -0
- package/dist/database/connection-pool.d.ts.map +1 -0
- package/dist/database/connection-pool.js +253 -0
- package/dist/database/connection-pool.js.map +1 -0
- package/dist/database/database-service.d.ts +223 -0
- package/dist/database/database-service.d.ts.map +1 -0
- package/dist/database/database-service.js +691 -0
- package/dist/database/database-service.js.map +1 -0
- package/dist/database/database-setup.d.ts +53 -0
- package/dist/database/database-setup.d.ts.map +1 -0
- package/dist/database/database-setup.js +257 -0
- package/dist/database/database-setup.js.map +1 -0
- package/dist/database/graph-analytics.d.ts +87 -0
- package/dist/database/graph-analytics.d.ts.map +1 -0
- package/dist/database/graph-analytics.js +317 -0
- package/dist/database/graph-analytics.js.map +1 -0
- package/dist/database/index.d.ts +5 -0
- package/dist/database/index.d.ts.map +1 -0
- package/dist/database/index.js +5 -0
- package/dist/database/index.js.map +1 -0
- package/dist/database/migrations.d.ts +58 -0
- package/dist/database/migrations.d.ts.map +1 -0
- package/dist/database/migrations.js +351 -0
- package/dist/database/migrations.js.map +1 -0
- package/dist/database/neo4j-manager.d.ts +120 -0
- package/dist/database/neo4j-manager.d.ts.map +1 -0
- package/dist/database/neo4j-manager.js +450 -0
- package/dist/database/neo4j-manager.js.map +1 -0
- package/dist/database/query-builder.d.ts +87 -0
- package/dist/database/query-builder.d.ts.map +1 -0
- package/dist/database/query-builder.js +265 -0
- package/dist/database/query-builder.js.map +1 -0
- package/dist/database/search-service.d.ts +80 -0
- package/dist/database/search-service.d.ts.map +1 -0
- package/dist/database/search-service.js +343 -0
- package/dist/database/search-service.js.map +1 -0
- package/dist/database/sqlite-manager.d.ts +81 -0
- package/dist/database/sqlite-manager.d.ts.map +1 -0
- package/dist/database/sqlite-manager.js +356 -0
- package/dist/database/sqlite-manager.js.map +1 -0
- package/dist/database/story-intelligence.d.ts +88 -0
- package/dist/database/story-intelligence.d.ts.map +1 -0
- package/dist/database/story-intelligence.js +457 -0
- package/dist/database/story-intelligence.js.map +1 -0
- package/dist/database/writing-analytics.d.ts +95 -0
- package/dist/database/writing-analytics.d.ts.map +1 -0
- package/dist/database/writing-analytics.js +387 -0
- package/dist/database/writing-analytics.js.map +1 -0
- package/dist/handlers/analysis-handlers.d.ts +12 -0
- package/dist/handlers/analysis-handlers.d.ts.map +1 -0
- package/dist/handlers/analysis-handlers.js +611 -0
- package/dist/handlers/analysis-handlers.js.map +1 -0
- package/dist/handlers/compilation-handlers.d.ts +6 -0
- package/dist/handlers/compilation-handlers.d.ts.map +1 -0
- package/dist/handlers/compilation-handlers.js +141 -0
- package/dist/handlers/compilation-handlers.js.map +1 -0
- package/dist/handlers/document-handlers.d.ts +13 -0
- package/dist/handlers/document-handlers.d.ts.map +1 -0
- package/dist/handlers/document-handlers.js +353 -0
- package/dist/handlers/document-handlers.js.map +1 -0
- package/dist/handlers/index.d.ts +26 -0
- package/dist/handlers/index.d.ts.map +1 -0
- package/dist/handlers/index.js +85 -0
- package/dist/handlers/index.js.map +1 -0
- package/dist/handlers/project-handlers.d.ts +10 -0
- package/dist/handlers/project-handlers.d.ts.map +1 -0
- package/dist/handlers/project-handlers.js +163 -0
- package/dist/handlers/project-handlers.js.map +1 -0
- package/dist/handlers/search-handlers.d.ts +8 -0
- package/dist/handlers/search-handlers.d.ts.map +1 -0
- package/dist/handlers/search-handlers.js +185 -0
- package/dist/handlers/search-handlers.js.map +1 -0
- package/dist/handlers/types.d.ts +40 -0
- package/dist/handlers/types.d.ts.map +1 -0
- package/dist/handlers/types.js +26 -0
- package/dist/handlers/types.js.map +1 -0
- package/dist/handlers/validation-schemas.d.ts +23 -0
- package/dist/handlers/validation-schemas.d.ts.map +1 -0
- package/dist/handlers/validation-schemas.js +90 -0
- package/dist/handlers/validation-schemas.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +75 -1246
- package/dist/index.js.map +1 -1
- package/dist/memory-manager.d.ts +20 -4
- package/dist/memory-manager.d.ts.map +1 -1
- package/dist/memory-manager.js +265 -33
- package/dist/memory-manager.js.map +1 -1
- package/dist/scrivener-project.d.ts +96 -166
- package/dist/scrivener-project.d.ts.map +1 -1
- package/dist/scrivener-project.js +386 -766
- package/dist/scrivener-project.js.map +1 -1
- package/dist/services/compilation-service.d.ts +71 -0
- package/dist/services/compilation-service.d.ts.map +1 -0
- package/dist/services/compilation-service.js +438 -0
- package/dist/services/compilation-service.js.map +1 -0
- package/dist/services/document-manager.d.ts +70 -0
- package/dist/services/document-manager.d.ts.map +1 -0
- package/dist/services/document-manager.js +429 -0
- package/dist/services/document-manager.js.map +1 -0
- package/dist/{content-enhancer.d.ts → services/enhancements/content-enhancer.d.ts} +58 -19
- package/dist/services/enhancements/content-enhancer.d.ts.map +1 -0
- package/dist/services/enhancements/content-enhancer.js +1869 -0
- package/dist/services/enhancements/content-enhancer.js.map +1 -0
- package/dist/services/enhancements/filter-words.d.ts +15 -0
- package/dist/services/enhancements/filter-words.d.ts.map +1 -0
- package/dist/services/enhancements/filter-words.js +158 -0
- package/dist/services/enhancements/filter-words.js.map +1 -0
- package/dist/services/metadata-manager.d.ts +79 -0
- package/dist/services/metadata-manager.d.ts.map +1 -0
- package/dist/services/metadata-manager.js +442 -0
- package/dist/services/metadata-manager.js.map +1 -0
- package/dist/services/openai-service.d.ts +199 -0
- package/dist/services/openai-service.d.ts.map +1 -0
- package/dist/services/openai-service.js +825 -0
- package/dist/services/openai-service.js.map +1 -0
- package/dist/services/parsers/rtf-handler.d.ts.map +1 -0
- package/dist/{rtf-handler.js → services/parsers/rtf-handler.js} +3 -3
- package/dist/services/parsers/rtf-handler.js.map +1 -0
- package/dist/services/project-loader.d.ts +78 -0
- package/dist/services/project-loader.d.ts.map +1 -0
- package/dist/services/project-loader.js +344 -0
- package/dist/services/project-loader.js.map +1 -0
- package/dist/services/web-content-parser.d.ts +138 -0
- package/dist/services/web-content-parser.d.ts.map +1 -0
- package/dist/services/web-content-parser.js +516 -0
- package/dist/services/web-content-parser.js.map +1 -0
- package/dist/sync/context-sync.d.ts +116 -0
- package/dist/sync/context-sync.d.ts.map +1 -0
- package/dist/sync/context-sync.js +490 -0
- package/dist/sync/context-sync.js.map +1 -0
- package/dist/types/database.d.ts +158 -0
- package/dist/types/database.d.ts.map +1 -0
- package/dist/types/database.js +5 -0
- package/dist/types/database.js.map +1 -0
- package/dist/types/enhancements.d.ts +74 -0
- package/dist/types/enhancements.d.ts.map +1 -0
- package/dist/types/enhancements.js +5 -0
- package/dist/types/enhancements.js.map +1 -0
- package/dist/types/index.d.ts +314 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +5 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/internal.d.ts.map +1 -1
- package/dist/types/internal.js.map +1 -1
- package/dist/utils/common.d.ts +197 -0
- package/dist/utils/common.d.ts.map +1 -0
- package/dist/utils/common.js +535 -0
- package/dist/utils/common.js.map +1 -0
- package/dist/utils/database.d.ts +148 -0
- package/dist/utils/database.d.ts.map +1 -0
- package/dist/utils/database.js +424 -0
- package/dist/utils/database.js.map +1 -0
- package/dist/utils/scrivener-utils.d.ts +246 -0
- package/dist/utils/scrivener-utils.d.ts.map +1 -0
- package/dist/utils/scrivener-utils.js +485 -0
- package/dist/utils/scrivener-utils.js.map +1 -0
- package/package.json +34 -8
- package/scripts/config-template.json +8 -0
- package/scripts/setup.cjs +94 -0
- package/scripts/setup.js +15 -0
- package/dist/content-enhancer.d.ts.map +0 -1
- package/dist/content-enhancer.js +0 -745
- package/dist/content-enhancer.js.map +0 -1
- package/dist/rtf-handler.d.ts.map +0 -1
- package/dist/rtf-handler.js.map +0 -1
- /package/dist/{rtf-handler.d.ts → services/parsers/rtf-handler.d.ts} +0 -0
|
@@ -1,855 +1,475 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Scrivener Project class using modular services
|
|
3
|
+
*/
|
|
2
4
|
import * as path from 'path';
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import {
|
|
5
|
+
import { DatabaseService } from './database/index.js';
|
|
6
|
+
import { ContentAnalyzer, ContextAnalyzer } from './analysis/index.js';
|
|
7
|
+
import { ContextSyncService } from './sync/context-sync.js';
|
|
8
|
+
import { CleanupManager } from './utils/common.js';
|
|
9
|
+
import { getLogger } from './core/logger.js';
|
|
10
|
+
import { createError, ErrorCode } from './core/errors.js';
|
|
11
|
+
import { DOCUMENT_TYPES } from './core/constants.js';
|
|
12
|
+
// Import service modules
|
|
13
|
+
import { DocumentManager } from './services/document-manager.js';
|
|
14
|
+
import { ProjectLoader } from './services/project-loader.js';
|
|
15
|
+
import { CompilationService } from './services/compilation-service.js';
|
|
16
|
+
import { MetadataManager } from './services/metadata-manager.js';
|
|
17
|
+
const logger = getLogger('scrivener-project');
|
|
6
18
|
export class ScrivenerProject {
|
|
7
19
|
projectPath;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
20
|
+
documentManager;
|
|
21
|
+
projectLoader;
|
|
22
|
+
compilationService;
|
|
23
|
+
metadataManager;
|
|
24
|
+
databaseService;
|
|
25
|
+
contentAnalyzer;
|
|
26
|
+
contextAnalyzer;
|
|
27
|
+
contextSync;
|
|
28
|
+
cleanupManager;
|
|
29
|
+
options;
|
|
30
|
+
constructor(projectPath, options = {}) {
|
|
18
31
|
this.projectPath = path.resolve(projectPath);
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
32
|
+
this.options = {
|
|
33
|
+
autoSave: false,
|
|
34
|
+
autoBackup: false,
|
|
35
|
+
cacheSize: 50,
|
|
36
|
+
syncInterval: 30000,
|
|
37
|
+
...options,
|
|
38
|
+
};
|
|
39
|
+
// Initialize services
|
|
40
|
+
this.documentManager = new DocumentManager(this.projectPath);
|
|
41
|
+
this.projectLoader = new ProjectLoader(this.projectPath, {
|
|
42
|
+
autoBackup: this.options.autoBackup,
|
|
43
|
+
});
|
|
44
|
+
this.compilationService = new CompilationService();
|
|
45
|
+
this.metadataManager = new MetadataManager();
|
|
46
|
+
this.databaseService = new DatabaseService(this.projectPath);
|
|
47
|
+
this.contentAnalyzer = new ContentAnalyzer();
|
|
48
|
+
this.cleanupManager = new CleanupManager();
|
|
49
|
+
// Register cleanup
|
|
50
|
+
this.cleanupManager.register(async () => {
|
|
51
|
+
await this.close();
|
|
52
|
+
});
|
|
24
53
|
}
|
|
25
54
|
/**
|
|
26
|
-
*
|
|
27
|
-
* @throws {Error} If the project file cannot be read or parsed.
|
|
55
|
+
* Load the project
|
|
28
56
|
*/
|
|
29
57
|
async loadProject() {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
}
|
|
58
|
+
logger.info('Loading Scrivener project');
|
|
59
|
+
// Load project structure
|
|
60
|
+
const structure = await this.projectLoader.loadProject();
|
|
61
|
+
this.documentManager.setProjectStructure(structure);
|
|
62
|
+
// Initialize database
|
|
63
|
+
await this.databaseService.initialize();
|
|
64
|
+
// Initialize enhanced services
|
|
65
|
+
this.contextAnalyzer = new ContextAnalyzer(this.databaseService, this.contentAnalyzer);
|
|
66
|
+
this.contextSync = new ContextSyncService(this.projectPath, this.databaseService, this.contextAnalyzer, {
|
|
67
|
+
autoSync: true,
|
|
68
|
+
syncInterval: this.options.syncInterval || 30000,
|
|
69
|
+
contextFileFormat: 'both',
|
|
70
|
+
includeAnalysis: true,
|
|
71
|
+
includeRelationships: true,
|
|
72
|
+
});
|
|
73
|
+
// Perform initial sync
|
|
74
|
+
await this.performInitialSync();
|
|
75
|
+
logger.info('Project loaded successfully');
|
|
64
76
|
}
|
|
65
77
|
/**
|
|
66
|
-
*
|
|
67
|
-
* @throws {Error} If no project is currently loaded.
|
|
78
|
+
* Save the project
|
|
68
79
|
*/
|
|
69
80
|
async saveProject() {
|
|
70
|
-
|
|
71
|
-
|
|
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);
|
|
81
|
+
const structure = this.projectLoader.getProjectStructure();
|
|
82
|
+
await this.projectLoader.saveProject(structure);
|
|
84
83
|
}
|
|
85
84
|
/**
|
|
86
|
-
*
|
|
87
|
-
* @returns A promise that resolves to an array of ScrivenerDocument objects.
|
|
85
|
+
* Get project structure
|
|
88
86
|
*/
|
|
89
|
-
async getProjectStructure() {
|
|
90
|
-
|
|
91
|
-
await this.loadProject();
|
|
92
|
-
const binder = this.projectStructure?.ScrivenerProject?.Binder;
|
|
93
|
-
if (!binder)
|
|
94
|
-
return [];
|
|
95
|
-
return this.parseBinderItems(binder.BinderItem || []);
|
|
87
|
+
async getProjectStructure(includeTrash = false) {
|
|
88
|
+
return await this.documentManager.getProjectStructure(includeTrash);
|
|
96
89
|
}
|
|
97
90
|
/**
|
|
98
|
-
*
|
|
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.
|
|
91
|
+
* Get all documents
|
|
103
92
|
*/
|
|
93
|
+
async getAllDocuments(includeTrash = false) {
|
|
94
|
+
return await this.documentManager.getAllDocuments(includeTrash);
|
|
95
|
+
}
|
|
96
|
+
// Document operations
|
|
104
97
|
async readDocument(documentId) {
|
|
105
|
-
|
|
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
|
-
}
|
|
98
|
+
return await this.documentManager.readDocument(documentId);
|
|
122
99
|
}
|
|
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
100
|
async readDocumentFormatted(documentId) {
|
|
132
|
-
|
|
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
|
-
}
|
|
101
|
+
return await this.documentManager.readDocumentFormatted(documentId);
|
|
165
102
|
}
|
|
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
103
|
async writeDocument(documentId, content) {
|
|
174
|
-
|
|
175
|
-
|
|
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
|
-
}
|
|
104
|
+
await this.documentManager.writeDocument(documentId, content);
|
|
105
|
+
this.markDocumentChanged(documentId);
|
|
199
106
|
}
|
|
200
|
-
|
|
201
|
-
|
|
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);
|
|
107
|
+
async createDocument(title, content = '', parentId, type = DOCUMENT_TYPES.TEXT) {
|
|
108
|
+
const id = await this.documentManager.createDocument(title, content, parentId, type);
|
|
244
109
|
await this.saveProject();
|
|
245
|
-
return
|
|
110
|
+
return id;
|
|
246
111
|
}
|
|
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
112
|
async deleteDocument(documentId) {
|
|
253
|
-
|
|
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
|
-
}
|
|
113
|
+
await this.documentManager.deleteDocument(documentId);
|
|
272
114
|
await this.saveProject();
|
|
273
115
|
}
|
|
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
116
|
async renameDocument(documentId, newTitle) {
|
|
281
|
-
|
|
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);
|
|
117
|
+
await this.documentManager.renameDocument(documentId, newTitle);
|
|
293
118
|
await this.saveProject();
|
|
294
119
|
}
|
|
295
|
-
|
|
296
|
-
|
|
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);
|
|
120
|
+
async moveDocument(documentId, newParentId, _position) {
|
|
121
|
+
await this.documentManager.moveDocument(documentId, newParentId);
|
|
331
122
|
await this.saveProject();
|
|
332
123
|
}
|
|
333
|
-
|
|
334
|
-
|
|
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.
|
|
124
|
+
async getWordCount(documentId) {
|
|
125
|
+
return await this.documentManager.getWordCount(documentId);
|
|
346
126
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
-
}
|
|
127
|
+
async getTotalWordCount() {
|
|
128
|
+
const count = await this.documentManager.getWordCount();
|
|
129
|
+
return count.words;
|
|
363
130
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
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: [] };
|
|
131
|
+
// Compilation operations
|
|
132
|
+
async compileDocuments(documentIds, separator = '\n\n---\n\n', outputFormat = 'text') {
|
|
133
|
+
const documents = [];
|
|
134
|
+
for (const id of documentIds) {
|
|
135
|
+
try {
|
|
136
|
+
const content = await this.documentManager.readDocumentFormatted(id);
|
|
137
|
+
const doc = await this.getDocumentInfo(id);
|
|
138
|
+
documents.push({
|
|
139
|
+
id,
|
|
140
|
+
content,
|
|
141
|
+
title: doc.document?.title || 'Untitled',
|
|
142
|
+
});
|
|
408
143
|
}
|
|
409
|
-
|
|
410
|
-
|
|
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
|
-
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
logger.warn(`Failed to read document ${id}:`, error);
|
|
530
146
|
}
|
|
531
147
|
}
|
|
532
|
-
return
|
|
148
|
+
return await this.compilationService.compileDocuments(documents, {
|
|
149
|
+
separator,
|
|
150
|
+
outputFormat,
|
|
151
|
+
});
|
|
533
152
|
}
|
|
534
153
|
async searchContent(query, options) {
|
|
535
|
-
if (!this.projectStructure)
|
|
536
|
-
await this.loadProject();
|
|
537
|
-
const results = [];
|
|
538
154
|
const documents = await this.getAllDocuments();
|
|
155
|
+
const docsWithContent = [];
|
|
539
156
|
for (const doc of documents) {
|
|
540
|
-
if (doc.type ===
|
|
541
|
-
const matches = [];
|
|
542
|
-
let content = '';
|
|
157
|
+
if (doc.type === DOCUMENT_TYPES.TEXT) {
|
|
543
158
|
try {
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
159
|
+
const content = await this.readDocument(doc.id);
|
|
160
|
+
docsWithContent.push({
|
|
161
|
+
id: doc.id,
|
|
162
|
+
title: doc.title,
|
|
163
|
+
content,
|
|
164
|
+
metadata: {
|
|
165
|
+
synopsis: doc.synopsis,
|
|
166
|
+
notes: doc.notes,
|
|
167
|
+
keywords: doc.keywords,
|
|
168
|
+
},
|
|
169
|
+
});
|
|
547
170
|
}
|
|
548
171
|
catch {
|
|
549
172
|
// Skip documents that can't be read
|
|
550
173
|
}
|
|
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
174
|
}
|
|
581
175
|
}
|
|
582
|
-
return
|
|
176
|
+
return this.compilationService.searchInDocuments(docsWithContent, query, options);
|
|
177
|
+
}
|
|
178
|
+
async exportProject(format, outputPath, options) {
|
|
179
|
+
const structure = await this.getProjectStructure();
|
|
180
|
+
return await this.compilationService.exportProject(structure, format, options);
|
|
181
|
+
}
|
|
182
|
+
async getStatistics() {
|
|
183
|
+
const documents = await this.getAllDocuments();
|
|
184
|
+
return this.compilationService.getStatistics(documents);
|
|
583
185
|
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
const found = content.match(regex);
|
|
590
|
-
if (found)
|
|
591
|
-
matches.push(...found);
|
|
186
|
+
// Metadata operations
|
|
187
|
+
async updateMetadata(documentId, metadata) {
|
|
188
|
+
const structure = this.projectLoader.getProjectStructure();
|
|
189
|
+
if (!structure) {
|
|
190
|
+
throw createError(ErrorCode.INVALID_STATE, 'Project not loaded');
|
|
592
191
|
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
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
|
-
}
|
|
192
|
+
const item = this.findBinderItem(structure, documentId);
|
|
193
|
+
if (!item) {
|
|
194
|
+
throw createError(ErrorCode.NOT_FOUND, `Document ${documentId} not found`);
|
|
603
195
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
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
|
-
}
|
|
196
|
+
this.metadataManager.updateDocumentMetadata(item, metadata);
|
|
197
|
+
await this.saveProject();
|
|
198
|
+
}
|
|
199
|
+
async updateDocumentMetadata(documentId, metadata) {
|
|
200
|
+
await this.updateMetadata(documentId, metadata);
|
|
201
|
+
}
|
|
202
|
+
async updateSynopsisAndNotes(documentId, synopsis, notes) {
|
|
203
|
+
await this.updateMetadata(documentId, { synopsis, notes });
|
|
204
|
+
}
|
|
205
|
+
async batchUpdateSynopsisAndNotes(updates) {
|
|
206
|
+
const results = [];
|
|
207
|
+
for (const update of updates) {
|
|
208
|
+
try {
|
|
209
|
+
await this.updateSynopsisAndNotes(update.documentId, update.synopsis, update.notes);
|
|
210
|
+
results.push({ documentId: update.documentId, success: true });
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
results.push({
|
|
214
|
+
documentId: update.documentId,
|
|
215
|
+
success: false,
|
|
216
|
+
error: error instanceof Error ? error.message : String(error),
|
|
661
217
|
});
|
|
662
218
|
}
|
|
663
219
|
}
|
|
664
|
-
|
|
665
|
-
// parseBinderItems handles both single items and arrays
|
|
666
|
-
doc.children = this.parseBinderItems(item.Children.BinderItem);
|
|
667
|
-
}
|
|
668
|
-
return doc;
|
|
220
|
+
return results;
|
|
669
221
|
}
|
|
670
|
-
|
|
671
|
-
|
|
222
|
+
async getProjectMetadata() {
|
|
223
|
+
const structure = this.projectLoader.getProjectStructure();
|
|
224
|
+
return this.metadataManager.getProjectMetadata(structure);
|
|
672
225
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
226
|
+
// Project management
|
|
227
|
+
async refreshProject() {
|
|
228
|
+
this.documentManager.clearCache();
|
|
229
|
+
const structure = await this.projectLoader.reloadProject();
|
|
230
|
+
this.documentManager.setProjectStructure(structure);
|
|
231
|
+
}
|
|
232
|
+
async isProjectModified() {
|
|
233
|
+
return await this.projectLoader.isProjectModified();
|
|
234
|
+
}
|
|
235
|
+
clearCache(documentId) {
|
|
236
|
+
this.documentManager.clearCache(documentId);
|
|
237
|
+
}
|
|
238
|
+
// Database and analysis
|
|
239
|
+
getDatabaseService() {
|
|
240
|
+
return this.databaseService;
|
|
241
|
+
}
|
|
242
|
+
getContextAnalyzer() {
|
|
243
|
+
return this.contextAnalyzer;
|
|
244
|
+
}
|
|
245
|
+
getContextSync() {
|
|
246
|
+
return this.contextSync;
|
|
247
|
+
}
|
|
248
|
+
async analyzeChapterEnhanced(documentId) {
|
|
249
|
+
if (!this.contextAnalyzer) {
|
|
250
|
+
throw createError(ErrorCode.INVALID_STATE, 'Context analyzer not initialized');
|
|
682
251
|
}
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
252
|
+
const document = await this.getDocumentInfo(documentId);
|
|
253
|
+
if (!document.document) {
|
|
254
|
+
throw createError(ErrorCode.NOT_FOUND, `Document ${documentId} not found`);
|
|
686
255
|
}
|
|
256
|
+
const content = await this.readDocument(documentId);
|
|
257
|
+
const allDocuments = await this.getAllDocuments();
|
|
258
|
+
return await this.contextAnalyzer.analyzeChapter(document.document, content, allDocuments);
|
|
687
259
|
}
|
|
688
|
-
|
|
689
|
-
|
|
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
|
-
}
|
|
260
|
+
async buildStoryContext() {
|
|
261
|
+
if (!this.contextAnalyzer) {
|
|
262
|
+
throw createError(ErrorCode.INVALID_STATE, 'Context analyzer not initialized');
|
|
706
263
|
}
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
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;
|
|
264
|
+
const documents = await this.getAllDocuments();
|
|
265
|
+
const contexts = [];
|
|
266
|
+
for (const doc of documents) {
|
|
267
|
+
if (doc.type === DOCUMENT_TYPES.TEXT) {
|
|
268
|
+
const context = await this.contextAnalyzer.getChapterContext(doc.id);
|
|
269
|
+
if (context) {
|
|
270
|
+
contexts.push(context);
|
|
727
271
|
}
|
|
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
272
|
}
|
|
736
273
|
}
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
274
|
+
return await this.contextAnalyzer.buildStoryContext(documents, contexts);
|
|
275
|
+
}
|
|
276
|
+
getSyncStatus() {
|
|
277
|
+
if (!this.contextSync) {
|
|
278
|
+
return {
|
|
279
|
+
enabled: false,
|
|
280
|
+
message: 'Context sync not initialized',
|
|
281
|
+
};
|
|
743
282
|
}
|
|
744
|
-
return
|
|
283
|
+
return this.contextSync.getSyncStatus();
|
|
745
284
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
285
|
+
markDocumentChanged(documentId) {
|
|
286
|
+
if (this.contextSync) {
|
|
287
|
+
this.contextSync.markDocumentChanged(documentId);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
async exportContextFiles(exportPath) {
|
|
291
|
+
if (!this.contextSync) {
|
|
292
|
+
throw createError(ErrorCode.INVALID_STATE, 'Context sync not initialized');
|
|
293
|
+
}
|
|
294
|
+
await this.contextSync.exportContextFiles(exportPath);
|
|
295
|
+
}
|
|
296
|
+
// Additional methods
|
|
297
|
+
async getDocumentInfo(documentId) {
|
|
298
|
+
const structure = await this.getProjectStructure(true);
|
|
299
|
+
let foundDoc = null;
|
|
300
|
+
let path = [];
|
|
301
|
+
let location = 'unknown';
|
|
302
|
+
const searchInDocs = (docs, currentPath) => {
|
|
303
|
+
for (const doc of docs) {
|
|
304
|
+
const newPath = [...currentPath, { id: doc.id, title: doc.title, type: doc.type }];
|
|
305
|
+
if (doc.id === documentId) {
|
|
306
|
+
foundDoc = doc;
|
|
307
|
+
path = newPath;
|
|
308
|
+
return true;
|
|
769
309
|
}
|
|
770
|
-
|
|
771
|
-
|
|
310
|
+
if (doc.children && searchInDocs(doc.children, newPath)) {
|
|
311
|
+
return true;
|
|
772
312
|
}
|
|
773
313
|
}
|
|
774
|
-
return
|
|
314
|
+
return false;
|
|
315
|
+
};
|
|
316
|
+
if (searchInDocs(structure, [])) {
|
|
317
|
+
location = 'active';
|
|
775
318
|
}
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
319
|
+
const metadata = {};
|
|
320
|
+
if (foundDoc) {
|
|
321
|
+
const doc = foundDoc;
|
|
322
|
+
Object.assign(metadata, {
|
|
323
|
+
synopsis: doc.synopsis,
|
|
324
|
+
notes: doc.notes,
|
|
325
|
+
label: doc.label,
|
|
326
|
+
status: doc.status,
|
|
327
|
+
keywords: doc.keywords,
|
|
328
|
+
includeInCompile: doc.includeInCompile,
|
|
329
|
+
...doc.customMetadata,
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
return { document: foundDoc, path, metadata, location };
|
|
333
|
+
}
|
|
334
|
+
async getTrashDocuments() {
|
|
335
|
+
const allDocs = await this.getProjectStructure(true);
|
|
336
|
+
const trashDocs = [];
|
|
337
|
+
// Find trash folder
|
|
338
|
+
for (const doc of allDocs) {
|
|
339
|
+
if (doc.path && doc.path.startsWith('Trash/')) {
|
|
340
|
+
trashDocs.push(doc);
|
|
780
341
|
}
|
|
781
342
|
}
|
|
782
|
-
return
|
|
343
|
+
return trashDocs;
|
|
783
344
|
}
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
345
|
+
async searchTrash(query, options) {
|
|
346
|
+
const trashDocs = await this.getTrashDocuments();
|
|
347
|
+
const docsWithContent = [];
|
|
348
|
+
for (const doc of trashDocs) {
|
|
349
|
+
if (doc.type === DOCUMENT_TYPES.TEXT) {
|
|
350
|
+
try {
|
|
351
|
+
const content = await this.readDocument(doc.id);
|
|
352
|
+
docsWithContent.push({
|
|
353
|
+
id: doc.id,
|
|
354
|
+
title: `[TRASH] ${doc.title}`,
|
|
355
|
+
content,
|
|
356
|
+
metadata: {},
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
// Skip
|
|
361
|
+
}
|
|
795
362
|
}
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
return allDocs;
|
|
363
|
+
}
|
|
364
|
+
return this.compilationService.searchInDocuments(docsWithContent, query, options);
|
|
799
365
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
366
|
+
async recoverFromTrash(documentId, targetParentId) {
|
|
367
|
+
// This would need special handling in DocumentManager
|
|
368
|
+
// TODO: Implement actual trash recovery using documentId and targetParentId
|
|
369
|
+
throw createError(ErrorCode.NOT_IMPLEMENTED, `Trash recovery not yet implemented in modular version (document: ${documentId}, target: ${targetParentId})`);
|
|
370
|
+
}
|
|
371
|
+
async getProjectStructureLimited(options) {
|
|
372
|
+
const structure = await this.getProjectStructure(options?.includeTrash);
|
|
373
|
+
if (options?.summaryOnly) {
|
|
374
|
+
const stats = this.compilationService.getStatistics(structure);
|
|
375
|
+
return {
|
|
376
|
+
...stats,
|
|
377
|
+
tree: structure.slice(0, 3), // Just top level items
|
|
378
|
+
};
|
|
806
379
|
}
|
|
807
|
-
|
|
380
|
+
return structure;
|
|
808
381
|
}
|
|
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
382
|
async getDocumentAnnotations(documentId) {
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
383
|
+
// Would need RTF handler access
|
|
384
|
+
// TODO: Implement actual annotation retrieval for documentId
|
|
385
|
+
const annotations = new Map();
|
|
386
|
+
// Placeholder - would fetch annotations for specific document
|
|
387
|
+
if (documentId) {
|
|
388
|
+
// Implementation would go here
|
|
819
389
|
}
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
390
|
+
return annotations;
|
|
391
|
+
}
|
|
392
|
+
// Private helpers
|
|
393
|
+
async performInitialSync() {
|
|
394
|
+
try {
|
|
395
|
+
logger.info('Performing initial sync');
|
|
396
|
+
const allDocs = await this.getAllDocuments();
|
|
397
|
+
for (const doc of allDocs) {
|
|
398
|
+
await this.syncDocumentToDatabase(doc);
|
|
824
399
|
}
|
|
825
|
-
|
|
826
|
-
|
|
400
|
+
if (this.contextSync) {
|
|
401
|
+
await this.contextSync.performSync();
|
|
827
402
|
}
|
|
403
|
+
logger.info('Initial sync completed');
|
|
404
|
+
}
|
|
405
|
+
catch (error) {
|
|
406
|
+
logger.error('Initial sync failed:', error);
|
|
828
407
|
}
|
|
829
408
|
}
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
409
|
+
async syncDocumentToDatabase(doc) {
|
|
410
|
+
try {
|
|
411
|
+
let wordCount = 0;
|
|
412
|
+
let characterCount = 0;
|
|
413
|
+
if (doc.type === DOCUMENT_TYPES.TEXT) {
|
|
414
|
+
try {
|
|
415
|
+
const content = await this.readDocument(doc.id);
|
|
416
|
+
const words = content
|
|
417
|
+
.trim()
|
|
418
|
+
.split(/\s+/)
|
|
419
|
+
.filter((w) => w.length > 0);
|
|
420
|
+
wordCount = words.length;
|
|
421
|
+
characterCount = content.length;
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
// Document might not have content yet
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
await this.databaseService.syncDocumentData({
|
|
428
|
+
id: doc.id,
|
|
429
|
+
title: doc.title,
|
|
430
|
+
type: doc.type,
|
|
431
|
+
synopsis: doc.synopsis,
|
|
432
|
+
notes: doc.notes,
|
|
433
|
+
wordCount,
|
|
434
|
+
characterCount,
|
|
435
|
+
});
|
|
843
436
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
metadata.projectTargets = {
|
|
847
|
-
draft: targets.DraftTarget ? parseInt(targets.DraftTarget) : undefined,
|
|
848
|
-
session: targets.SessionTarget ? parseInt(targets.SessionTarget) : undefined,
|
|
849
|
-
deadline: targets.Deadline,
|
|
850
|
-
};
|
|
437
|
+
catch (error) {
|
|
438
|
+
logger.warn(`Failed to sync document ${doc.id}:`, error);
|
|
851
439
|
}
|
|
852
|
-
|
|
440
|
+
}
|
|
441
|
+
findBinderItem(structure, documentId) {
|
|
442
|
+
if (!structure?.ScrivenerProject?.Binder)
|
|
443
|
+
return null;
|
|
444
|
+
const searchInBinder = (container) => {
|
|
445
|
+
if (!container)
|
|
446
|
+
return null;
|
|
447
|
+
const items = container.BinderItem || container.Children?.BinderItem;
|
|
448
|
+
if (!items)
|
|
449
|
+
return null;
|
|
450
|
+
const itemArray = Array.isArray(items) ? items : [items];
|
|
451
|
+
for (const item of itemArray) {
|
|
452
|
+
if (item.UUID === documentId)
|
|
453
|
+
return item;
|
|
454
|
+
if (item.Children?.BinderItem) {
|
|
455
|
+
const found = searchInBinder(item.Children);
|
|
456
|
+
if (found)
|
|
457
|
+
return found;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return null;
|
|
461
|
+
};
|
|
462
|
+
return searchInBinder(structure.ScrivenerProject.Binder);
|
|
463
|
+
}
|
|
464
|
+
// Cleanup
|
|
465
|
+
async close() {
|
|
466
|
+
logger.info('Closing Scrivener project');
|
|
467
|
+
if (this.contextSync) {
|
|
468
|
+
this.contextSync.close();
|
|
469
|
+
}
|
|
470
|
+
await this.databaseService.close();
|
|
471
|
+
await this.documentManager.close();
|
|
472
|
+
logger.info('Project closed');
|
|
853
473
|
}
|
|
854
474
|
}
|
|
855
475
|
//# sourceMappingURL=scrivener-project.js.map
|