farseer-cli 1.1.2 → 1.2.1
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 +21 -10
- package/dist/commands/dimensions.js +10 -3
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/install.js +5 -6
- package/dist/commands/install.js.map +2 -2
- package/dist/commands/pull.js +7 -1
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/push.js +12 -1
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +96 -0
- package/dist/commands/run.js.map +2 -2
- package/dist/index.js +3 -0
- package/dist/index.js.map +2 -2
- package/dist/mcp/index.js +6 -0
- package/dist/mcp/index.js.map +2 -2
- package/dist/mcp/server.js +2 -0
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/tools/appTools.js +22 -6
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +3 -54
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +646 -9
- package/dist/mcp/tools/dashboardTools.js.map +3 -3
- package/dist/mcp/tools/folderTools.js +154 -0
- package/dist/mcp/tools/folderTools.js.map +7 -0
- package/dist/mcp/tools/modelTools.js +356 -30
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +182 -3
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +419 -11
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +2 -0
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/services/appSyncService.js +4 -2
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/farseerApi.js +46 -12
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/farseerService.js +28 -5
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/syncService.js +4 -2
- package/dist/services/syncService.js.map +2 -2
- package/dist/utils/entityResolver.js +6 -8
- package/dist/utils/entityResolver.js.map +2 -2
- package/dist/utils/fileLogger.js +225 -0
- package/dist/utils/fileLogger.js.map +7 -0
- package/dist/utils/logger.js +18 -11
- package/dist/utils/logger.js.map +2 -2
- package/dist/utils/packageManager.js +78 -0
- package/dist/utils/packageManager.js.map +7 -0
- package/docs/cli-guide.md +2 -0
- package/docs/model-export.md +1 -1
- package/package.json +7 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/syncService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n}\n\n/**\n * Determines if a file should be included in sync operations.\n * A file is included if ANY of:\n * 1. --all flag is passed\n * 2. Has a default script extension (.ts, .js, .mjs, .cjs)\n * 3. Has an extension from inline includeExtensions option\n * 4. Lives under a folder from inline includeFolders option\n * 5. Has an extension from persistent syncIncludes config\n * 6. Lives under a folder from persistent syncIncludes config\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders'>,\n): boolean {\n if (options?.all) return true;\n\n const ext = path.extname(filePath).toLowerCase();\n\n // Default script extensions always included\n if (DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;\n\n // Inline extensions\n if (options?.includeExtensions?.includes(ext)) return true;\n\n // Inline folders\n if (options?.includeFolders?.some((f) => filePath.startsWith(f + '/') || filePath === f)) return true;\n\n // Persistent config\n const includes = getSyncIncludes(tenant);\n if (includes) {\n if (includes.extensions?.includes(ext)) return true;\n if (includes.folders?.some((f) => filePath.startsWith(f + '/') || filePath === f)) return true;\n }\n\n return false;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\nexport interface SyncStatus {\n modifiedLocally: string[];\n modifiedRemotely: string[];\n onlyLocal: string[];\n onlyRemote: string[];\n inSync: string[];\n conflicts?: SyncConflict[];\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Fast status check that uses sync state instead of downloading remote file content.\n * This is much faster than getStatus() but may miss changes made by others since last pull.\n * Use this for push operations where we trust the sync state.\n */\n async getStatusFast(options?: SyncOptions): Promise<SyncStatus> {\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // Get local files\n let localFiles = getAllFilesInDir(filesDir);\n\n // Filter files based on includes\n if (!options?.all) {\n localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n }\n\n // Get remote file list only (no content download)\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n const remoteFilePaths = new Set(remoteFiles.map((f) => f.path));\n\n const status: SyncStatus = {\n modifiedLocally: [],\n modifiedRemotely: [],\n onlyLocal: [],\n onlyRemote: [],\n inSync: [],\n conflicts: [],\n };\n\n // Check local files\n for (const localFile of localFiles) {\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n const localHash = calculateHash(content);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFilePaths.has(localFile)) {\n // File exists both locally and remotely\n if (syncInfo && localHash === syncInfo.localHash) {\n // Local file hasn't changed since last sync\n status.inSync.push(localFile);\n } else {\n // Local file changed (or no sync info)\n status.modifiedLocally.push(localFile);\n }\n } else {\n // File only exists locally\n if (syncInfo && syncInfo.remoteHash) {\n // Was synced before, deleted on remote\n if (localHash !== syncInfo.localHash) {\n // Local also modified - CONFLICT\n status.conflicts!.push({\n filePath: localFile,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n } else {\n // Local unchanged, safe to mark as remote change\n status.modifiedRemotely.push(localFile);\n }\n } else {\n status.onlyLocal.push(localFile);\n }\n }\n }\n\n // Check remote files that don't exist locally\n for (const remoteFile of remoteFiles) {\n if (!localFiles.includes(remoteFile.path)) {\n const syncInfo = syncState.files[remoteFile.path];\n if (syncInfo && syncInfo.localHash) {\n // Was synced before, deleted locally\n status.modifiedLocally.push(remoteFile.path);\n } else {\n status.onlyRemote.push(remoteFile.path);\n }\n }\n }\n\n return status;\n }\n\n async getStatus(options?: SyncOptions): Promise<SyncStatus> {\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // Get local files and their hashes\n let localFiles = getAllFilesInDir(filesDir);\n if (!options?.all) {\n localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n }\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = path.join(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n // Get remote files and their hashes\n let remoteFiles = await this.farseerClient.listFiles();\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n const remoteHashes = new Map<string, string>();\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n\n const status: SyncStatus = {\n modifiedLocally: [],\n modifiedRemotely: [],\n onlyLocal: [],\n onlyRemote: [],\n inSync: [],\n conflicts: [],\n };\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.onlyLocal.push(c.filePath);\n break;\n case 'remote_new':\n status.onlyRemote.push(c.filePath);\n break;\n case 'remote_deleted':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.modifiedLocally.push(c.filePath);\n break;\n default:\n // All conflict types\n status.conflicts!.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n process.stdout.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n process.stdout.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!options?.all && !shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = path.join(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n case 'local_modified':\n case 'local_new':\n result.unchanged.push(filePath);\n // Update sync state for remote side if we have remote info\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n // Local deleted, remote unchanged - skip (push will handle)\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = path.join(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: { force?: boolean }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n };\n\n // Get current remote files (just the list, not content)\n const remoteFiles = await this.farseerClient.listFiles();\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // Get local files and hashes\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n const localContents = new Map<string, Buffer>();\n for (const localFile of localFiles) {\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n localContents.set(localFile, content);\n }\n\n // Identify candidates that need remote content check for conflict detection\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n if (!syncInfo || localHash !== syncInfo.localHash) {\n // Changed or new locally\n if (remoteFileMap.has(localFile)) {\n candidateFiles.push(localFile);\n }\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions)\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localFiles.includes(f) && remoteFileMap.has(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection\n const remoteHashes = new Map<string, string>();\n if (filesToFetchRemote.length > 0 && !options?.force) {\n const toFetch = filesToFetchRemote.filter((f) => remoteFileMap.has(f)).map((f) => remoteFileMap.get(f)!);\n\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const localPath = path.join(filesDir, localFile);\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote - check if local changed since last sync\n if (syncInfo && localHash === syncInfo.localHash) {\n result.unchanged.push(localFile);\n } else {\n // Local file changed - needs update\n await this.farseerClient.updateFile(remoteFile.reference, content, path.basename(localFile));\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n } else {\n // File doesn't exist on remote\n if (syncInfo && localHash === syncInfo.localHash) {\n // Local unchanged, was deleted on remote - skip (don't re-upload)\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n }\n }\n\n // Delete files on remote that were deleted locally (non-conflicting only)\n const localFileSet = new Set(localFiles);\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (!localFileSet.has(remotePath) && !conflictPaths.has(remotePath)) {\n const syncInfo = syncState.files[remotePath];\n if (syncInfo) {\n // Was synced before, now deleted locally - delete on remote\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n async checkRemoteChanges(options?: SyncOptions): Promise<boolean> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Quick check: new files on remote that we don't have in sync state\n for (const file of remoteFiles) {\n const syncInfo = syncState.files[file.path];\n if (!syncInfo) {\n return true; // New file on remote\n }\n }\n\n // Quick check: files deleted on remote that we have in sync state\n for (const filePath of Object.keys(syncState.files)) {\n // Only check included files\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n\n const exists = remoteFiles.some((f) => f.path === filePath);\n if (!exists && syncState.files[filePath].remoteHash) {\n return true; // File was deleted on remote\n }\n }\n\n // Note: We don't check for content changes here anymore for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are a rare edge case - user should pull first.\n return false;\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = path.join(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n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AM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n}\n\n/**\n * Determines if a file should be included in sync operations.\n * A file is included if ANY of:\n * 1. --all flag is passed\n * 2. Has a default script extension (.ts, .js, .mjs, .cjs)\n * 3. Has an extension from inline includeExtensions option\n * 4. Lives under a folder from inline includeFolders option\n * 5. Has an extension from persistent syncIncludes config\n * 6. Lives under a folder from persistent syncIncludes config\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders'>,\n): boolean {\n if (options?.all) return true;\n\n const ext = path.extname(filePath).toLowerCase();\n\n // Default script extensions always included\n if (DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;\n\n // Inline extensions\n if (options?.includeExtensions?.includes(ext)) return true;\n\n // Inline folders\n if (options?.includeFolders?.some((f) => filePath.startsWith(f + '/') || filePath === f)) return true;\n\n // Persistent config\n const includes = getSyncIncludes(tenant);\n if (includes) {\n if (includes.extensions?.includes(ext)) return true;\n if (includes.folders?.some((f) => filePath.startsWith(f + '/') || filePath === f)) return true;\n }\n\n return false;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\nexport interface SyncStatus {\n modifiedLocally: string[];\n modifiedRemotely: string[];\n onlyLocal: string[];\n onlyRemote: string[];\n inSync: string[];\n conflicts?: SyncConflict[];\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Fast status check that uses sync state instead of downloading remote file content.\n * This is much faster than getStatus() but may miss changes made by others since last pull.\n * Use this for push operations where we trust the sync state.\n */\n async getStatusFast(options?: SyncOptions): Promise<SyncStatus> {\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // Get local files\n let localFiles = getAllFilesInDir(filesDir);\n\n // Filter files based on includes\n if (!options?.all) {\n localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n }\n\n // Get remote file list only (no content download)\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n const remoteFilePaths = new Set(remoteFiles.map((f) => f.path));\n\n const status: SyncStatus = {\n modifiedLocally: [],\n modifiedRemotely: [],\n onlyLocal: [],\n onlyRemote: [],\n inSync: [],\n conflicts: [],\n };\n\n // Check local files\n for (const localFile of localFiles) {\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n const localHash = calculateHash(content);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFilePaths.has(localFile)) {\n // File exists both locally and remotely\n if (syncInfo && localHash === syncInfo.localHash) {\n // Local file hasn't changed since last sync\n status.inSync.push(localFile);\n } else {\n // Local file changed (or no sync info)\n status.modifiedLocally.push(localFile);\n }\n } else {\n // File only exists locally\n if (syncInfo && syncInfo.remoteHash) {\n // Was synced before, deleted on remote\n if (localHash !== syncInfo.localHash) {\n // Local also modified - CONFLICT\n status.conflicts!.push({\n filePath: localFile,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n } else {\n // Local unchanged, safe to mark as remote change\n status.modifiedRemotely.push(localFile);\n }\n } else {\n status.onlyLocal.push(localFile);\n }\n }\n }\n\n // Check remote files that don't exist locally\n for (const remoteFile of remoteFiles) {\n if (!localFiles.includes(remoteFile.path)) {\n const syncInfo = syncState.files[remoteFile.path];\n if (syncInfo && syncInfo.localHash) {\n // Was synced before, deleted locally\n status.modifiedLocally.push(remoteFile.path);\n } else {\n status.onlyRemote.push(remoteFile.path);\n }\n }\n }\n\n return status;\n }\n\n async getStatus(options?: SyncOptions): Promise<SyncStatus> {\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // Get local files and their hashes\n let localFiles = getAllFilesInDir(filesDir);\n if (!options?.all) {\n localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n }\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = path.join(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n // Get remote files and their hashes\n let remoteFiles = await this.farseerClient.listFiles();\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n const remoteHashes = new Map<string, string>();\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n\n const status: SyncStatus = {\n modifiedLocally: [],\n modifiedRemotely: [],\n onlyLocal: [],\n onlyRemote: [],\n inSync: [],\n conflicts: [],\n };\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.onlyLocal.push(c.filePath);\n break;\n case 'remote_new':\n status.onlyRemote.push(c.filePath);\n break;\n case 'remote_deleted':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.modifiedLocally.push(c.filePath);\n break;\n default:\n // All conflict types\n status.conflicts!.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes\n if (!options?.all) {\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n }\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!options?.all && !shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = path.join(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n case 'local_modified':\n case 'local_new':\n result.unchanged.push(filePath);\n // Update sync state for remote side if we have remote info\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n // Local deleted, remote unchanged - skip (push will handle)\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = path.join(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: { force?: boolean }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n };\n\n // Get current remote files (just the list, not content)\n const remoteFiles = await this.farseerClient.listFiles();\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // Get local files and hashes\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n const localContents = new Map<string, Buffer>();\n for (const localFile of localFiles) {\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n localContents.set(localFile, content);\n }\n\n // Identify candidates that need remote content check for conflict detection\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n if (!syncInfo || localHash !== syncInfo.localHash) {\n // Changed or new locally\n if (remoteFileMap.has(localFile)) {\n candidateFiles.push(localFile);\n }\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions)\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localFiles.includes(f) && remoteFileMap.has(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection\n const remoteHashes = new Map<string, string>();\n if (filesToFetchRemote.length > 0 && !options?.force) {\n const toFetch = filesToFetchRemote.filter((f) => remoteFileMap.has(f)).map((f) => remoteFileMap.get(f)!);\n\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const localPath = path.join(filesDir, localFile);\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote - check if local changed since last sync\n if (syncInfo && localHash === syncInfo.localHash) {\n result.unchanged.push(localFile);\n } else {\n // Local file changed - needs update\n await this.farseerClient.updateFile(remoteFile.reference, content, path.basename(localFile));\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n } else {\n // File doesn't exist on remote\n if (syncInfo && localHash === syncInfo.localHash) {\n // Local unchanged, was deleted on remote - skip (don't re-upload)\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n }\n }\n\n // Delete files on remote that were deleted locally (non-conflicting only)\n const localFileSet = new Set(localFiles);\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (!localFileSet.has(remotePath) && !conflictPaths.has(remotePath)) {\n const syncInfo = syncState.files[remotePath];\n if (syncInfo) {\n // Was synced before, now deleted locally - delete on remote\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n async checkRemoteChanges(options?: SyncOptions): Promise<boolean> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Quick check: new files on remote that we don't have in sync state\n for (const file of remoteFiles) {\n const syncInfo = syncState.files[file.path];\n if (!syncInfo) {\n return true; // New file on remote\n }\n }\n\n // Quick check: files deleted on remote that we have in sync state\n for (const filePath of Object.keys(syncState.files)) {\n // Only check included files\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n\n const exists = remoteFiles.some((f) => f.path === filePath);\n if (!exists && syncState.files[filePath].remoteHash) {\n return true; // File was deleted on remote\n }\n }\n\n // Note: We don't check for content changes here anymore for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are a rare edge case - user should pull first.\n return false;\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = path.join(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n // Silently ignore metadata fetch errors - non-critical\n }\n }),\n );\n }\n\n return files;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAsE;AACtE,2BAAgC;AAChC,qBAOO;AACP,oBAAuB;AAoBhB,SAAS,kBACZ,UACA,QACA,SACO;AACP,MAAI,SAAS,IAAK,QAAO;AAEzB,QAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAG/C,MAAI,gDAA0B,SAAS,GAAG,EAAG,QAAO;AAGpD,MAAI,SAAS,mBAAmB,SAAS,GAAG,EAAG,QAAO;AAGtD,MAAI,SAAS,gBAAgB,KAAK,CAAC,MAAM,SAAS,WAAW,IAAI,GAAG,KAAK,aAAa,CAAC,EAAG,QAAO;AAGjG,QAAM,eAAW,sCAAgB,MAAM;AACvC,MAAI,UAAU;AACV,QAAI,SAAS,YAAY,SAAS,GAAG,EAAG,QAAO;AAC/C,QAAI,SAAS,SAAS,KAAK,CAAC,MAAM,SAAS,WAAW,IAAI,GAAG,KAAK,aAAa,CAAC,EAAG,QAAO;AAAA,EAC9F;AAEA,SAAO;AACX;AA4DO,MAAM,YAAY;AAAA,EAIrB,YAAY,QAAgB,eAA+B;AACvD,SAAK,SAAS;AACd,SAAK,gBAAgB;AAAA,EACzB;AAAA,EAEA,gBAA2B;AACvB,UAAM,mBAAe,gCAAgB,KAAK,MAAM;AAEhD,QAAI,CAAC,GAAG,WAAW,YAAY,GAAG;AAC9B,aAAO;AAAA,QACH,UAAU;AAAA,QACV,OAAO,CAAC;AAAA,MACZ;AAAA,IACJ;AAEA,QAAI;AACA,YAAM,UAAU,GAAG,aAA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Aa;AAAA,UACjB,CAAC;AACD;AAAA,QACJ,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,MACR;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,sBAAsB,OAA4C;AAC5E,UAAM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -43,15 +43,13 @@ async function resolveSheetId(nativeClient, nameOrId) {
|
|
|
43
43
|
return null;
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
46
|
+
const results = await nativeClient.folders.search({
|
|
47
|
+
name: nameOrId,
|
|
48
|
+
types: [farseer.FolderItemType.Sheet],
|
|
49
|
+
limit: 20
|
|
50
50
|
});
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
return null;
|
|
51
|
+
const match = results.find((s) => s.name.toLowerCase() === nameOrId.toLowerCase());
|
|
52
|
+
return match ? { id: match.id, name: match.name } : null;
|
|
55
53
|
}
|
|
56
54
|
async function resolveDashboardId(nativeClient, nameOrId) {
|
|
57
55
|
const parsed = Number(nameOrId);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/entityResolver.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Entity Resolver Utilities\n *\n * Resolve sheet/dashboard names to IDs using the native Farseer client.\n */\n\nimport * as farseer from 'farseer-client';\n\n/**\n * Resolve a sheet by name or ID.\n * - If numeric, fetches directly by ID\n * - If string,
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,cAAyB;AAOzB,eAAsB,eAClB,cACA,UAC4C;AAC5C,QAAM,SAAS,OAAO,QAAQ;AAC9B,MAAI,CAAC,MAAM,MAAM,KAAK,OAAO,MAAM,MAAM,UAAU;AAC/C,QAAI;AACA,YAAM,QAAQ,MAAM,aAAa,OAAO,IAAI,MAAM;AAClD,aAAO,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK;AAAA,IAC5C,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAGA,QAAM,
|
|
4
|
+
"sourcesContent": ["/**\n * Entity Resolver Utilities\n *\n * Resolve sheet/dashboard names to IDs using the native Farseer client.\n */\n\nimport * as farseer from 'farseer-client';\n\n/**\n * Resolve a sheet by name or ID.\n * - If numeric, fetches directly by ID\n * - If string, uses folders.search API to find by name (case-insensitive)\n */\nexport async function resolveSheetId(\n nativeClient: farseer.FarseerClient,\n nameOrId: string,\n): Promise<{ id: number; name: string } | null> {\n const parsed = Number(nameOrId);\n if (!isNaN(parsed) && String(parsed) === nameOrId) {\n try {\n const sheet = await nativeClient.sheets.get(parsed);\n return { id: sheet.id, name: sheet.name };\n } catch {\n return null;\n }\n }\n\n // Search by name using folders.search API (backend max limit is 20)\n const results = await nativeClient.folders.search({\n name: nameOrId,\n types: [farseer.FolderItemType.Sheet],\n limit: 20,\n });\n const match = results.find((s) => s.name.toLowerCase() === nameOrId.toLowerCase());\n return match ? { id: match.id, name: match.name } : null;\n}\n\n/**\n * Resolve a dashboard by name or ID.\n * - If numeric, fetches directly by ID\n * - If string, lists all dashboards and matches by name (case-insensitive)\n */\nexport async function resolveDashboardId(\n nativeClient: farseer.FarseerClient,\n nameOrId: string,\n): Promise<{ id: number; name: string } | null> {\n const parsed = Number(nameOrId);\n if (!isNaN(parsed) && String(parsed) === nameOrId) {\n try {\n const dashboard = await nativeClient.dashboards.get(parsed);\n return { id: dashboard.id, name: dashboard.name };\n } catch {\n return null;\n }\n }\n\n // Search by name\n const dashboards = await nativeClient.dashboards.list();\n const match = dashboards.find((d) => d.name.toLowerCase() === nameOrId.toLowerCase());\n\n if (match) {\n return { id: match.id, name: match.name };\n }\n\n return null;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,cAAyB;AAOzB,eAAsB,eAClB,cACA,UAC4C;AAC5C,QAAM,SAAS,OAAO,QAAQ;AAC9B,MAAI,CAAC,MAAM,MAAM,KAAK,OAAO,MAAM,MAAM,UAAU;AAC/C,QAAI;AACA,YAAM,QAAQ,MAAM,aAAa,OAAO,IAAI,MAAM;AAClD,aAAO,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK;AAAA,IAC5C,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAGA,QAAM,UAAU,MAAM,aAAa,QAAQ,OAAO;AAAA,IAC9C,MAAM;AAAA,IACN,OAAO,CAAC,QAAQ,eAAe,KAAK;AAAA,IACpC,OAAO;AAAA,EACX,CAAC;AACD,QAAM,QAAQ,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,SAAS,YAAY,CAAC;AACjF,SAAO,QAAQ,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK,IAAI;AACxD;AAOA,eAAsB,mBAClB,cACA,UAC4C;AAC5C,QAAM,SAAS,OAAO,QAAQ;AAC9B,MAAI,CAAC,MAAM,MAAM,KAAK,OAAO,MAAM,MAAM,UAAU;AAC/C,QAAI;AACA,YAAM,YAAY,MAAM,aAAa,WAAW,IAAI,MAAM;AAC1D,aAAO,EAAE,IAAI,UAAU,IAAI,MAAM,UAAU,KAAK;AAAA,IACpD,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAGA,QAAM,aAAa,MAAM,aAAa,WAAW,KAAK;AACtD,QAAM,QAAQ,WAAW,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,SAAS,YAAY,CAAC;AAEpF,MAAI,OAAO;AACP,WAAO,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK;AAAA,EAC5C;AAEA,SAAO;AACX;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var fileLogger_exports = {};
|
|
30
|
+
__export(fileLogger_exports, {
|
|
31
|
+
fileLogger: () => fileLogger
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(fileLogger_exports);
|
|
34
|
+
var fs = __toESM(require("fs"));
|
|
35
|
+
var path = __toESM(require("path"));
|
|
36
|
+
var os = __toESM(require("os"));
|
|
37
|
+
var import_constants = require("./constants");
|
|
38
|
+
const LOG_DIR = path.join(os.homedir(), ".farseer", "logs");
|
|
39
|
+
const MAX_LOG_FILES = 10;
|
|
40
|
+
let logFilePath = null;
|
|
41
|
+
let logStream = null;
|
|
42
|
+
function createLogPath() {
|
|
43
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
44
|
+
return path.join(LOG_DIR, `farseer-${ts}.log`);
|
|
45
|
+
}
|
|
46
|
+
function rotateLogFiles() {
|
|
47
|
+
try {
|
|
48
|
+
const files = fs.readdirSync(LOG_DIR).filter((f) => f.startsWith("farseer-") && f.endsWith(".log")).sort().reverse();
|
|
49
|
+
for (const file of files.slice(MAX_LOG_FILES)) {
|
|
50
|
+
try {
|
|
51
|
+
fs.unlinkSync(path.join(LOG_DIR, file));
|
|
52
|
+
} catch {
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function writeEntry(level, category, data) {
|
|
59
|
+
if (!logStream) return;
|
|
60
|
+
try {
|
|
61
|
+
const entry = {
|
|
62
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
63
|
+
level,
|
|
64
|
+
cat: category,
|
|
65
|
+
...data !== void 0 ? { data } : {}
|
|
66
|
+
};
|
|
67
|
+
logStream.write(JSON.stringify(entry) + "\n");
|
|
68
|
+
} catch {
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function writeSyncEntry(level, category, data) {
|
|
72
|
+
if (!logFilePath) return;
|
|
73
|
+
try {
|
|
74
|
+
const entry = {
|
|
75
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
76
|
+
level,
|
|
77
|
+
cat: category,
|
|
78
|
+
...data !== void 0 ? { data } : {}
|
|
79
|
+
};
|
|
80
|
+
fs.appendFileSync(logFilePath, JSON.stringify(entry) + "\n");
|
|
81
|
+
} catch {
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function serializeError(error) {
|
|
85
|
+
if (error instanceof Error) {
|
|
86
|
+
const result = {
|
|
87
|
+
name: error.name,
|
|
88
|
+
message: error.message,
|
|
89
|
+
stack: error.stack
|
|
90
|
+
};
|
|
91
|
+
if ("response" in error) {
|
|
92
|
+
const e = error;
|
|
93
|
+
result.status = e.response?.status;
|
|
94
|
+
result.statusText = e.response?.statusText;
|
|
95
|
+
result.responseData = e.response?.data;
|
|
96
|
+
result.url = e.config?.url;
|
|
97
|
+
result.method = e.config?.method;
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
if (typeof error === "object" && error !== null) {
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(JSON.stringify(error));
|
|
104
|
+
} catch {
|
|
105
|
+
return { raw: String(error) };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { raw: String(error) };
|
|
109
|
+
}
|
|
110
|
+
let initialized = false;
|
|
111
|
+
let crashHandlersInstalled = false;
|
|
112
|
+
const fileLogger = {
|
|
113
|
+
/**
|
|
114
|
+
* Initialize the file logger. Idempotent — safe to call multiple times.
|
|
115
|
+
* Creates the log directory and file, writes session header.
|
|
116
|
+
*/
|
|
117
|
+
init() {
|
|
118
|
+
if (initialized) return;
|
|
119
|
+
initialized = true;
|
|
120
|
+
try {
|
|
121
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
122
|
+
rotateLogFiles();
|
|
123
|
+
logFilePath = createLogPath();
|
|
124
|
+
logStream = fs.createWriteStream(logFilePath, { flags: "a" });
|
|
125
|
+
writeEntry("info", "session", {
|
|
126
|
+
version: import_constants.CLI_VERSION,
|
|
127
|
+
node: process.version,
|
|
128
|
+
platform: os.platform(),
|
|
129
|
+
arch: os.arch(),
|
|
130
|
+
argv: process.argv.slice(2),
|
|
131
|
+
cwd: process.cwd(),
|
|
132
|
+
pid: process.pid
|
|
133
|
+
});
|
|
134
|
+
} catch {
|
|
135
|
+
logFilePath = null;
|
|
136
|
+
logStream = null;
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
/**
|
|
140
|
+
* Log an informational entry.
|
|
141
|
+
*/
|
|
142
|
+
log(category, data) {
|
|
143
|
+
writeEntry("info", category, data);
|
|
144
|
+
},
|
|
145
|
+
/**
|
|
146
|
+
* Log a warning.
|
|
147
|
+
*/
|
|
148
|
+
warn(category, data) {
|
|
149
|
+
writeEntry("warn", category, data);
|
|
150
|
+
},
|
|
151
|
+
/**
|
|
152
|
+
* Log an error with full details.
|
|
153
|
+
* Uses async stream write (same as other entries) for correct ordering.
|
|
154
|
+
* Only crash handlers use writeSyncEntry where process.exit follows immediately.
|
|
155
|
+
*/
|
|
156
|
+
error(category, error, context) {
|
|
157
|
+
writeEntry("error", category, {
|
|
158
|
+
...serializeError(error),
|
|
159
|
+
...context || {}
|
|
160
|
+
});
|
|
161
|
+
},
|
|
162
|
+
/**
|
|
163
|
+
* Log an HTTP request/response (for debug).
|
|
164
|
+
*/
|
|
165
|
+
http(method, url, status, durationMs, error) {
|
|
166
|
+
const data = { method, url };
|
|
167
|
+
if (status !== void 0) data.status = status;
|
|
168
|
+
if (durationMs !== void 0) data.durationMs = durationMs;
|
|
169
|
+
if (error) data.error = serializeError(error);
|
|
170
|
+
writeEntry(error ? "error" : "info", "http", data);
|
|
171
|
+
},
|
|
172
|
+
/**
|
|
173
|
+
* Log an MCP tool call.
|
|
174
|
+
*/
|
|
175
|
+
toolCall(toolName, params, success, durationMs, error) {
|
|
176
|
+
const data = { tool: toolName, params, success };
|
|
177
|
+
if (durationMs !== void 0) data.durationMs = durationMs;
|
|
178
|
+
if (error) data.error = serializeError(error);
|
|
179
|
+
writeEntry(success ? "info" : "error", "mcp-tool", data);
|
|
180
|
+
},
|
|
181
|
+
/**
|
|
182
|
+
* Get the current log file path (to tell user where to find it).
|
|
183
|
+
*/
|
|
184
|
+
getLogPath() {
|
|
185
|
+
return logFilePath;
|
|
186
|
+
},
|
|
187
|
+
/**
|
|
188
|
+
* Close the log stream. Call on process exit.
|
|
189
|
+
*/
|
|
190
|
+
close() {
|
|
191
|
+
if (logStream) {
|
|
192
|
+
logStream.end();
|
|
193
|
+
logStream = null;
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
/**
|
|
197
|
+
* Install crash handlers that write to the log before exit. Idempotent.
|
|
198
|
+
*/
|
|
199
|
+
installCrashHandlers() {
|
|
200
|
+
if (crashHandlersInstalled) return;
|
|
201
|
+
crashHandlersInstalled = true;
|
|
202
|
+
process.on("uncaughtException", (err) => {
|
|
203
|
+
writeSyncEntry("fatal", "crash", {
|
|
204
|
+
source: "uncaughtException",
|
|
205
|
+
...serializeError(err)
|
|
206
|
+
});
|
|
207
|
+
if (logFilePath) {
|
|
208
|
+
console.error(`
|
|
209
|
+
Crash log written to: ${logFilePath}`);
|
|
210
|
+
}
|
|
211
|
+
process.exit(1);
|
|
212
|
+
});
|
|
213
|
+
process.on("unhandledRejection", (reason) => {
|
|
214
|
+
writeSyncEntry("fatal", "crash", {
|
|
215
|
+
source: "unhandledRejection",
|
|
216
|
+
...serializeError(reason)
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
222
|
+
0 && (module.exports = {
|
|
223
|
+
fileLogger
|
|
224
|
+
});
|
|
225
|
+
//# sourceMappingURL=fileLogger.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/fileLogger.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * File Logger\n *\n * Writes debug logs to ~/.farseer/logs/ for diagnostics.\n * On error, prints the log path so users can share the file for support.\n *\n * Log rotation: keeps last 10 log files, deletes oldest on startup.\n * Format: one JSON line per entry (JSONL) for easy parsing.\n *\n * Usage:\n * import { fileLogger } from './utils/fileLogger';\n * fileLogger.init(); // Call once at startup\n * fileLogger.log('http', { method: 'GET', url: '...' });\n * fileLogger.error('push', error);\n * fileLogger.getLogPath(); // Returns current log file path\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { CLI_VERSION } from './constants';\n\nconst LOG_DIR = path.join(os.homedir(), '.farseer', 'logs');\nconst MAX_LOG_FILES = 10;\n\nlet logFilePath: string | null = null;\nlet logStream: fs.WriteStream | null = null;\n\n/**\n * Create a timestamped log file path.\n */\nfunction createLogPath(): string {\n const ts = new Date().toISOString().replace(/[:.]/g, '-');\n return path.join(LOG_DIR, `farseer-${ts}.log`);\n}\n\n/**\n * Remove old log files, keeping only the newest MAX_LOG_FILES.\n */\nfunction rotateLogFiles(): void {\n try {\n const files = fs\n .readdirSync(LOG_DIR)\n .filter((f) => f.startsWith('farseer-') && f.endsWith('.log'))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_LOG_FILES)) {\n try {\n fs.unlinkSync(path.join(LOG_DIR, file));\n } catch {\n // Ignore deletion errors\n }\n }\n } catch {\n // Log dir might not exist yet\n }\n}\n\n/**\n * Write a structured log entry.\n */\nfunction writeEntry(level: string, category: string, data?: unknown): void {\n if (!logStream) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n logStream.write(JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Write a log entry synchronously (bypasses stream buffering).\n * Used in crash handlers where process.exit follows immediately.\n */\nfunction writeSyncEntry(level: string, category: string, data?: unknown): void {\n if (!logFilePath) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n fs.appendFileSync(logFilePath, JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Extract error details for logging.\n */\nfunction serializeError(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n const result: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n // Axios errors\n if ('response' in error) {\n const e = error as any;\n result.status = e.response?.status;\n result.statusText = e.response?.statusText;\n result.responseData = e.response?.data;\n result.url = e.config?.url;\n result.method = e.config?.method;\n }\n return result;\n }\n if (typeof error === 'object' && error !== null) {\n try {\n return JSON.parse(JSON.stringify(error));\n } catch {\n return { raw: String(error) };\n }\n }\n return { raw: String(error) };\n}\n\nlet initialized = false;\nlet crashHandlersInstalled = false;\n\nexport const fileLogger = {\n /**\n * Initialize the file logger. Idempotent \u2014 safe to call multiple times.\n * Creates the log directory and file, writes session header.\n */\n init(): void {\n if (initialized) return;\n initialized = true;\n try {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n rotateLogFiles();\n logFilePath = createLogPath();\n logStream = fs.createWriteStream(logFilePath, { flags: 'a' });\n\n // Write session header\n writeEntry('info', 'session', {\n version: CLI_VERSION,\n node: process.version,\n platform: os.platform(),\n arch: os.arch(),\n argv: process.argv.slice(2),\n cwd: process.cwd(),\n pid: process.pid,\n });\n } catch {\n // If we can't create logs, continue without file logging\n logFilePath = null;\n logStream = null;\n }\n },\n\n /**\n * Log an informational entry.\n */\n log(category: string, data?: unknown): void {\n writeEntry('info', category, data);\n },\n\n /**\n * Log a warning.\n */\n warn(category: string, data?: unknown): void {\n writeEntry('warn', category, data);\n },\n\n /**\n * Log an error with full details.\n * Uses async stream write (same as other entries) for correct ordering.\n * Only crash handlers use writeSyncEntry where process.exit follows immediately.\n */\n error(category: string, error: unknown, context?: Record<string, unknown>): void {\n writeEntry('error', category, {\n ...serializeError(error),\n ...(context || {}),\n });\n },\n\n /**\n * Log an HTTP request/response (for debug).\n */\n http(method: string, url: string, status?: number, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { method, url };\n if (status !== undefined) data.status = status;\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(error ? 'error' : 'info', 'http', data);\n },\n\n /**\n * Log an MCP tool call.\n */\n toolCall(toolName: string, params: unknown, success: boolean, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { tool: toolName, params, success };\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(success ? 'info' : 'error', 'mcp-tool', data);\n },\n\n /**\n * Get the current log file path (to tell user where to find it).\n */\n getLogPath(): string | null {\n return logFilePath;\n },\n\n /**\n * Close the log stream. Call on process exit.\n */\n close(): void {\n if (logStream) {\n logStream.end();\n logStream = null;\n }\n },\n\n /**\n * Install crash handlers that write to the log before exit. Idempotent.\n */\n installCrashHandlers(): void {\n if (crashHandlersInstalled) return;\n crashHandlersInstalled = true;\n process.on('uncaughtException', (err) => {\n // Use sync write \u2014 stream may not flush before process.exit\n writeSyncEntry('fatal', 'crash', {\n source: 'uncaughtException',\n ...serializeError(err),\n });\n if (logFilePath) {\n console.error(`\\nCrash log written to: ${logFilePath}`);\n }\n process.exit(1);\n });\n\n process.on('unhandledRejection', (reason) => {\n // Pass reason directly \u2014 serializeError handles Error, objects, and primitives.\n // Wrapping in new Error(String(reason)) would lose structured fields on plain objects.\n writeSyncEntry('fatal', 'crash', {\n source: 'unhandledRejection',\n ...serializeError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;AACX,gBAAU,IAAI;AACd,kBAAY;AAAA,IAChB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA,EAKA,uBAA6B;AACzB,QAAI,uBAAwB;AAC5B,6BAAyB;AACzB,YAAQ,GAAG,qBAAqB,CAAC,QAAQ;AAErC,qBAAe,SAAS,SAAS;AAAA,QAC7B,QAAQ;AAAA,QACR,GAAG,eAAe,GAAG;AAAA,MACzB,CAAC;AACD,UAAI,aAAa;AACb,gBAAQ,MAAM;AAAA,wBAA2B,WAAW,EAAE;AAAA,MAC1D;AACA,cAAQ,KAAK,CAAC;AAAA,IAClB,CAAC;AAED,YAAQ,GAAG,sBAAsB,CAAC,WAAW;AAGzC,qBAAe,SAAS,SAAS;AAAA,QAC7B,QAAQ;AAAA,QACR,GAAG,eAAe,MAAM;AAAA,MAC5B,CAAC;AAAA,IAEL,CAAC;AAAA,EACL;AACJ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/utils/logger.js
CHANGED
|
@@ -32,41 +32,48 @@ __export(logger_exports, {
|
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(logger_exports);
|
|
34
34
|
var import_chalk = __toESM(require("chalk"));
|
|
35
|
+
function log(...args) {
|
|
36
|
+
if (process.env.FARSEER_MCP === "1") {
|
|
37
|
+
console.error(...args);
|
|
38
|
+
} else {
|
|
39
|
+
console.log(...args);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
35
42
|
const logger = {
|
|
36
43
|
info: (message) => {
|
|
37
|
-
|
|
44
|
+
log(import_chalk.default.blue("\u2139"), message);
|
|
38
45
|
},
|
|
39
46
|
success: (message) => {
|
|
40
|
-
|
|
47
|
+
log(import_chalk.default.green("\u2713"), message);
|
|
41
48
|
},
|
|
42
49
|
warning: (message) => {
|
|
43
|
-
|
|
50
|
+
log(import_chalk.default.yellow("\u26A0"), message);
|
|
44
51
|
},
|
|
45
52
|
error: (message) => {
|
|
46
|
-
|
|
53
|
+
log(import_chalk.default.red("\u2717"), message);
|
|
47
54
|
},
|
|
48
55
|
log: (message) => {
|
|
49
|
-
|
|
56
|
+
log(message);
|
|
50
57
|
},
|
|
51
58
|
dim: (message) => {
|
|
52
|
-
|
|
59
|
+
log(import_chalk.default.dim(message));
|
|
53
60
|
},
|
|
54
61
|
header: (message) => {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
62
|
+
log();
|
|
63
|
+
log(import_chalk.default.bold.underline(message));
|
|
64
|
+
log();
|
|
58
65
|
},
|
|
59
66
|
list: (items, indent = 2) => {
|
|
60
67
|
const prefix = " ".repeat(indent);
|
|
61
68
|
items.forEach((item) => {
|
|
62
|
-
|
|
69
|
+
log(`${prefix}${item}`);
|
|
63
70
|
});
|
|
64
71
|
},
|
|
65
72
|
table: (rows) => {
|
|
66
73
|
const maxLabelLength = Math.max(...rows.map((r) => r.label.length));
|
|
67
74
|
rows.forEach((row) => {
|
|
68
75
|
const paddedLabel = row.label.padEnd(maxLabelLength);
|
|
69
|
-
|
|
76
|
+
log(` ${import_chalk.default.dim(paddedLabel)} ${row.value}`);
|
|
70
77
|
});
|
|
71
78
|
}
|
|
72
79
|
};
|