brain-memory 0.1.0-beta.3 → 0.1.0-beta.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.
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Brain Memory — Sync Provider Base Class & Factory
3
+ *
4
+ * Unified interface for cloud storage providers.
5
+ * All paths are relative to the brain root (e.g. 'index.json', 'professional/skills/ts.md').
6
+ */
7
+
8
+ /**
9
+ * Abstract base class for sync providers.
10
+ * Each provider translates relative brain paths to its own addressing model.
11
+ */
12
+ class SyncProvider {
13
+ /**
14
+ * @param {Object} config
15
+ * @param {string} config.accessToken - OAuth access token
16
+ * @param {Object} [config.options] - Provider-specific options
17
+ */
18
+ constructor(config) {
19
+ if (new.target === SyncProvider) {
20
+ throw new Error('SyncProvider is abstract and cannot be instantiated directly');
21
+ }
22
+ this.accessToken = config.accessToken;
23
+ this.options = config.options || {};
24
+ }
25
+
26
+ /**
27
+ * List all files in the remote brain folder.
28
+ *
29
+ * @param {string|null} cursor - Pagination/delta cursor from previous call, or null for full listing
30
+ * @returns {Promise<{files: Array<{path: string, rev: string, hash: string, modified: string, size: number}>, cursor: string, hasMore: boolean}>}
31
+ */
32
+ async listFiles(_cursor) {
33
+ throw new Error('listFiles() not implemented');
34
+ }
35
+
36
+ /**
37
+ * Download a single file.
38
+ *
39
+ * @param {string} remotePath - Relative path (e.g. 'index.json')
40
+ * @returns {Promise<{content: Buffer, rev: string, hash: string}>}
41
+ */
42
+ async downloadFile(_remotePath) {
43
+ throw new Error('downloadFile() not implemented');
44
+ }
45
+
46
+ /**
47
+ * Upload a single file. Uses rev for optimistic concurrency (409 = conflict).
48
+ *
49
+ * @param {string} remotePath - Relative path
50
+ * @param {Buffer} content - File content
51
+ * @param {Object} [options]
52
+ * @param {string} [options.rev] - Expected revision for conditional write
53
+ * @param {string} [options.mode] - 'add' for new files, 'update' for existing
54
+ * @returns {Promise<{rev: string, hash: string}>}
55
+ */
56
+ async uploadFile(_remotePath, _content, _options) {
57
+ throw new Error('uploadFile() not implemented');
58
+ }
59
+
60
+ /**
61
+ * Delete a single file.
62
+ *
63
+ * @param {string} remotePath - Relative path
64
+ * @returns {Promise<{success: boolean}>}
65
+ */
66
+ async deleteFile(_remotePath) {
67
+ throw new Error('deleteFile() not implemented');
68
+ }
69
+
70
+ /**
71
+ * Get metadata for a single file.
72
+ *
73
+ * @param {string} remotePath - Relative path
74
+ * @returns {Promise<{rev: string, hash: string, modified: string, size: number}|null>}
75
+ */
76
+ async getFileMetadata(_remotePath) {
77
+ throw new Error('getFileMetadata() not implemented');
78
+ }
79
+
80
+ /**
81
+ * Create a folder (some providers require explicit creation).
82
+ *
83
+ * @param {string} remotePath - Relative folder path
84
+ * @returns {Promise<void>}
85
+ */
86
+ async createFolder(_remotePath) {
87
+ // Default no-op — providers that need explicit folder creation override this
88
+ }
89
+
90
+ /**
91
+ * Test the connection and return account info.
92
+ *
93
+ * @returns {Promise<{ok: boolean, account: string}>}
94
+ */
95
+ async testConnection() {
96
+ throw new Error('testConnection() not implemented');
97
+ }
98
+
99
+ /**
100
+ * Refresh auth tokens if needed. Called before operations.
101
+ */
102
+ async refreshAuth() {
103
+ // Default no-op — subclasses override if needed
104
+ }
105
+
106
+ /**
107
+ * Compute a provider-specific content hash for a buffer.
108
+ * Used to compare local and remote file content.
109
+ *
110
+ * @param {Buffer} buffer - File content
111
+ * @returns {string} Hash string
112
+ */
113
+ computeContentHash(_buffer) {
114
+ throw new Error('computeContentHash() not implemented');
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Factory function to create a provider instance.
120
+ *
121
+ * @param {string} name - Provider name: 'dropbox', 'google-drive', 'onedrive'
122
+ * @param {Object} config - Provider configuration (accessToken, options)
123
+ * @returns {SyncProvider} Provider instance
124
+ */
125
+ function createProvider(name, config) {
126
+ switch (name) {
127
+ case 'dropbox': {
128
+ const { DropboxProvider } = require('./providers/dropbox');
129
+ return new DropboxProvider(config);
130
+ }
131
+ case 'google-drive': {
132
+ const { GoogleDriveProvider } = require('./providers/google-drive');
133
+ return new GoogleDriveProvider(config);
134
+ }
135
+ case 'onedrive': {
136
+ const { OneDriveProvider } = require('./providers/onedrive');
137
+ return new OneDriveProvider(config);
138
+ }
139
+ default:
140
+ throw new Error(`Unknown sync provider: ${name}`);
141
+ }
142
+ }
143
+
144
+ module.exports = { SyncProvider, createProvider };
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Brain Memory — Dropbox Sync Provider
3
+ *
4
+ * Dropbox API v2 integration using App Folder permissions.
5
+ * Paths are relative to /Apps/BrainMemory/ but API treats them as root.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+ const { SyncProvider } = require('../provider');
10
+
11
+ const API_BASE = 'https://api.dropboxapi.com/2';
12
+ const CONTENT_BASE = 'https://content.dropboxapi.com/2';
13
+
14
+ // Dropbox content hash block size: 4 MB
15
+ const BLOCK_SIZE = 4 * 1024 * 1024;
16
+
17
+ class DropboxProvider extends SyncProvider {
18
+ constructor(config) {
19
+ super(config);
20
+ }
21
+
22
+ /**
23
+ * Compute Dropbox content hash.
24
+ * Algorithm: split into 4MB blocks, SHA-256 each block,
25
+ * concatenate block hashes, SHA-256 the result.
26
+ *
27
+ * @param {Buffer} buffer - File content
28
+ * @returns {string} Hex-encoded content hash
29
+ */
30
+ computeContentHash(buffer) {
31
+ return computeDropboxHash(buffer);
32
+ }
33
+
34
+ async listFiles(cursor) {
35
+ if (cursor) {
36
+ return this._listContinue(cursor);
37
+ }
38
+ return this._listFolder();
39
+ }
40
+
41
+ async _listFolder() {
42
+ const response = await fetch(`${API_BASE}/files/list_folder`, {
43
+ method: 'POST',
44
+ headers: {
45
+ 'Authorization': `Bearer ${this.accessToken}`,
46
+ 'Content-Type': 'application/json',
47
+ },
48
+ body: JSON.stringify({
49
+ path: '',
50
+ recursive: true,
51
+ include_deleted: false,
52
+ }),
53
+ });
54
+
55
+ if (!response.ok) {
56
+ const text = await response.text();
57
+ throw new Error(`Dropbox list_folder failed (${response.status}): ${text}`);
58
+ }
59
+
60
+ const data = await response.json();
61
+ return this._parseListResponse(data);
62
+ }
63
+
64
+ async _listContinue(cursor) {
65
+ const response = await fetch(`${API_BASE}/files/list_folder/continue`, {
66
+ method: 'POST',
67
+ headers: {
68
+ 'Authorization': `Bearer ${this.accessToken}`,
69
+ 'Content-Type': 'application/json',
70
+ },
71
+ body: JSON.stringify({ cursor }),
72
+ });
73
+
74
+ if (!response.ok) {
75
+ const text = await response.text();
76
+ throw new Error(`Dropbox list_folder/continue failed (${response.status}): ${text}`);
77
+ }
78
+
79
+ const data = await response.json();
80
+ return this._parseListResponse(data);
81
+ }
82
+
83
+ _parseListResponse(data) {
84
+ const files = data.entries
85
+ .filter((e) => e['.tag'] === 'file')
86
+ .map((e) => ({
87
+ path: e.path_display.replace(/^\//, ''), // Remove leading slash
88
+ rev: e.rev,
89
+ hash: e.content_hash,
90
+ modified: e.server_modified,
91
+ size: e.size,
92
+ }));
93
+
94
+ return {
95
+ files,
96
+ cursor: data.cursor,
97
+ hasMore: data.has_more,
98
+ };
99
+ }
100
+
101
+ async downloadFile(remotePath) {
102
+ const apiArg = JSON.stringify({ path: `/${remotePath}` });
103
+
104
+ const response = await fetch(`${CONTENT_BASE}/files/download`, {
105
+ method: 'POST',
106
+ headers: {
107
+ 'Authorization': `Bearer ${this.accessToken}`,
108
+ 'Dropbox-API-Arg': apiArg,
109
+ },
110
+ });
111
+
112
+ if (!response.ok) {
113
+ const text = await response.text();
114
+ throw new Error(`Dropbox download failed (${response.status}): ${text}`);
115
+ }
116
+
117
+ const resultHeader = response.headers.get('Dropbox-API-Result');
118
+ const metadata = resultHeader ? JSON.parse(resultHeader) : {};
119
+ const buffer = Buffer.from(await response.arrayBuffer());
120
+
121
+ return {
122
+ content: buffer,
123
+ rev: metadata.rev,
124
+ hash: metadata.content_hash,
125
+ };
126
+ }
127
+
128
+ async uploadFile(remotePath, content, options = {}) {
129
+ const { rev, mode = 'add' } = options;
130
+
131
+ let uploadMode;
132
+ if (mode === 'update' && rev) {
133
+ uploadMode = { '.tag': 'update', update: rev };
134
+ } else if (mode === 'overwrite') {
135
+ uploadMode = { '.tag': 'overwrite' };
136
+ } else {
137
+ uploadMode = { '.tag': 'add' };
138
+ }
139
+
140
+ const apiArg = JSON.stringify({
141
+ path: `/${remotePath}`,
142
+ mode: uploadMode,
143
+ autorename: false,
144
+ mute: true,
145
+ });
146
+
147
+ const response = await fetch(`${CONTENT_BASE}/files/upload`, {
148
+ method: 'POST',
149
+ headers: {
150
+ 'Authorization': `Bearer ${this.accessToken}`,
151
+ 'Dropbox-API-Arg': apiArg,
152
+ 'Content-Type': 'application/octet-stream',
153
+ },
154
+ body: content,
155
+ });
156
+
157
+ if (response.status === 409) {
158
+ const text = await response.text();
159
+ const err = new Error(`Conflict: file was modified remotely`);
160
+ err.code = 'CONFLICT';
161
+ err.details = text;
162
+ throw err;
163
+ }
164
+
165
+ if (!response.ok) {
166
+ const text = await response.text();
167
+ throw new Error(`Dropbox upload failed (${response.status}): ${text}`);
168
+ }
169
+
170
+ const data = await response.json();
171
+ return {
172
+ rev: data.rev,
173
+ hash: data.content_hash,
174
+ };
175
+ }
176
+
177
+ async deleteFile(remotePath) {
178
+ const response = await fetch(`${API_BASE}/files/delete_v2`, {
179
+ method: 'POST',
180
+ headers: {
181
+ 'Authorization': `Bearer ${this.accessToken}`,
182
+ 'Content-Type': 'application/json',
183
+ },
184
+ body: JSON.stringify({ path: `/${remotePath}` }),
185
+ });
186
+
187
+ if (!response.ok) {
188
+ const text = await response.text();
189
+ // 409 with path/not_found is OK — file already deleted
190
+ if (response.status === 409 && text.includes('not_found')) {
191
+ return { success: true };
192
+ }
193
+ throw new Error(`Dropbox delete failed (${response.status}): ${text}`);
194
+ }
195
+
196
+ return { success: true };
197
+ }
198
+
199
+ async getFileMetadata(remotePath) {
200
+ const response = await fetch(`${API_BASE}/files/get_metadata`, {
201
+ method: 'POST',
202
+ headers: {
203
+ 'Authorization': `Bearer ${this.accessToken}`,
204
+ 'Content-Type': 'application/json',
205
+ },
206
+ body: JSON.stringify({ path: `/${remotePath}` }),
207
+ });
208
+
209
+ if (!response.ok) {
210
+ if (response.status === 409) return null; // Not found
211
+ const text = await response.text();
212
+ throw new Error(`Dropbox get_metadata failed (${response.status}): ${text}`);
213
+ }
214
+
215
+ const data = await response.json();
216
+ if (data['.tag'] !== 'file') return null;
217
+
218
+ return {
219
+ rev: data.rev,
220
+ hash: data.content_hash,
221
+ modified: data.server_modified,
222
+ size: data.size,
223
+ };
224
+ }
225
+
226
+ async createFolder(remotePath) {
227
+ const response = await fetch(`${API_BASE}/files/create_folder_v2`, {
228
+ method: 'POST',
229
+ headers: {
230
+ 'Authorization': `Bearer ${this.accessToken}`,
231
+ 'Content-Type': 'application/json',
232
+ },
233
+ body: JSON.stringify({ path: `/${remotePath}`, autorename: false }),
234
+ });
235
+
236
+ // 409 with path/conflict means folder already exists — that's fine
237
+ if (response.status === 409) return;
238
+
239
+ if (!response.ok) {
240
+ const text = await response.text();
241
+ throw new Error(`Dropbox create_folder failed (${response.status}): ${text}`);
242
+ }
243
+ }
244
+
245
+ async testConnection() {
246
+ const response = await fetch(`${API_BASE}/users/get_current_account`, {
247
+ method: 'POST',
248
+ headers: {
249
+ 'Authorization': `Bearer ${this.accessToken}`,
250
+ },
251
+ });
252
+
253
+ if (!response.ok) {
254
+ return { ok: false, account: null };
255
+ }
256
+
257
+ const data = await response.json();
258
+ return {
259
+ ok: true,
260
+ account: data.email || data.name?.display_name || 'Unknown',
261
+ };
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Compute Dropbox content hash for a buffer (exported for testing).
267
+ *
268
+ * @param {Buffer} buffer - File content
269
+ * @returns {string} Hex-encoded content hash
270
+ */
271
+ function computeDropboxHash(buffer) {
272
+ const blockHashes = [];
273
+ for (let offset = 0; offset < buffer.length; offset += BLOCK_SIZE) {
274
+ const end = Math.min(offset + BLOCK_SIZE, buffer.length);
275
+ const block = buffer.subarray(offset, end);
276
+ blockHashes.push(crypto.createHash('sha256').update(block).digest());
277
+ }
278
+
279
+ // Handle empty file
280
+ if (blockHashes.length === 0) {
281
+ blockHashes.push(crypto.createHash('sha256').update(Buffer.alloc(0)).digest());
282
+ }
283
+
284
+ const combined = Buffer.concat(blockHashes);
285
+ return crypto.createHash('sha256').update(combined).digest('hex');
286
+ }
287
+
288
+ module.exports = { DropboxProvider, computeDropboxHash, BLOCK_SIZE };