farseer-cli 1.0.6 → 1.0.9

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.
Files changed (50) hide show
  1. package/dist/commands/checkout.js +2 -1
  2. package/dist/commands/checkout.js.map +2 -2
  3. package/dist/commands/diff.js +3 -1
  4. package/dist/commands/diff.js.map +2 -2
  5. package/dist/commands/dimensions.js +1 -1
  6. package/dist/commands/dimensions.js.map +2 -2
  7. package/dist/commands/files.js +1 -1
  8. package/dist/commands/files.js.map +2 -2
  9. package/dist/commands/install.js +3 -3
  10. package/dist/commands/install.js.map +2 -2
  11. package/dist/commands/pull.js +48 -2
  12. package/dist/commands/pull.js.map +3 -3
  13. package/dist/commands/push.js +14 -2
  14. package/dist/commands/push.js.map +2 -2
  15. package/dist/commands/status.js +12 -2
  16. package/dist/commands/status.js.map +2 -2
  17. package/dist/commands/variables.js +1 -1
  18. package/dist/commands/variables.js.map +2 -2
  19. package/dist/index.js +1 -0
  20. package/dist/index.js.map +2 -2
  21. package/dist/mcp/prompts/workflows.js +24 -13
  22. package/dist/mcp/prompts/workflows.js.map +2 -2
  23. package/dist/mcp/tools/appTools.js +77 -77
  24. package/dist/mcp/tools/appTools.js.map +3 -3
  25. package/dist/mcp/tools/authTools.js +3 -2
  26. package/dist/mcp/tools/authTools.js.map +2 -2
  27. package/dist/mcp/tools/dataTools.js +43 -47
  28. package/dist/mcp/tools/dataTools.js.map +2 -2
  29. package/dist/mcp/tools/modelTools.js +15 -19
  30. package/dist/mcp/tools/modelTools.js.map +2 -2
  31. package/dist/mcp/tools/runTools.js +28 -26
  32. package/dist/mcp/tools/runTools.js.map +2 -2
  33. package/dist/mcp/tools/syncTools.js +36 -8
  34. package/dist/mcp/tools/syncTools.js.map +2 -2
  35. package/dist/services/syncService.js +386 -112
  36. package/dist/services/syncService.js.map +3 -3
  37. package/dist/utils/constants.js +1 -1
  38. package/dist/utils/constants.js.map +1 -1
  39. package/dist/utils/helpers.js +3 -3
  40. package/dist/utils/helpers.js.map +1 -1
  41. package/docs/api-reference.md +372 -0
  42. package/docs/arquero-patterns.md +158 -0
  43. package/docs/cli-guide.md +160 -0
  44. package/docs/how-farseer-works.md +113 -0
  45. package/docs/import-workflows.md +306 -0
  46. package/docs/model-export.md +95 -0
  47. package/docs/new-app-template.md +240 -0
  48. package/docs/query-formulas.md +97 -0
  49. package/docs/troubleshooting.md +140 -0
  50. package/package.json +2 -1
@@ -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 { calculateHash, getTenantFilesDir, getSyncFilePath, ensureDirectoryExists, getAllFilesInDir, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\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}\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?: { all?: boolean }): 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 to scripts only unless --all is specified\n if (!options?.all) {\n localFiles = localFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))\n );\n }\n\n // Get remote file list only (no content download)\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter to scripts only unless --all is specified\n if (!options?.all) {\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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 };\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 status.modifiedRemotely.push(localFile);\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?: { all?: boolean }): 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 to scripts only unless --all is specified\n if (!options?.all) {\n localFiles = localFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))\n );\n }\n\n const localFileHashes: Record<string, string> = {};\n\n for (const file of localFiles) {\n const fullPath = path.join(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localFileHashes[file] = calculateHash(content);\n }\n\n // Get remote files\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter to scripts only unless --all is specified\n if (!options?.all) {\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\n }\n\n const remoteFileHashes: Record<string, string> = {};\n\n // Fetch file contents in parallel with concurrency limit\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\n for (const { path, hash } of fileContents) {\n remoteFileHashes[path] = hash;\n }\n\n const status: SyncStatus = {\n modifiedLocally: [],\n modifiedRemotely: [],\n onlyLocal: [],\n onlyRemote: [],\n inSync: [],\n };\n\n const allFiles = new Set([...Object.keys(localFileHashes), ...Object.keys(remoteFileHashes)]);\n\n for (const file of allFiles) {\n const localHash = localFileHashes[file];\n const remoteHash = remoteFileHashes[file];\n const syncInfo = syncState.files[file];\n\n if (localHash && remoteHash) {\n // File exists both locally and remotely\n if (localHash === remoteHash) {\n status.inSync.push(file);\n } else if (syncInfo) {\n // We have sync state to compare\n const localChanged = localHash !== syncInfo.localHash;\n const remoteChanged = remoteHash !== syncInfo.remoteHash;\n\n if (localChanged && remoteChanged) {\n // Both changed - conflict (treat as modified locally for now)\n status.modifiedLocally.push(file);\n status.modifiedRemotely.push(file);\n } else if (localChanged) {\n status.modifiedLocally.push(file);\n } else if (remoteChanged) {\n status.modifiedRemotely.push(file);\n } else {\n status.inSync.push(file);\n }\n } else {\n // No sync state - files are different, treat as conflict\n status.modifiedLocally.push(file);\n }\n } else if (localHash && !remoteHash) {\n // Only exists locally\n if (syncInfo && syncInfo.remoteHash) {\n // Was synced before, deleted on remote\n status.modifiedRemotely.push(file);\n } else {\n status.onlyLocal.push(file);\n }\n } else if (!localHash && remoteHash) {\n // Only exists remotely\n if (syncInfo && syncInfo.localHash) {\n // Was synced before, deleted locally\n status.modifiedLocally.push(file);\n } else {\n status.onlyRemote.push(file);\n }\n }\n }\n\n return status;\n }\n\n async pull(options?: { all?: boolean }): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: 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 to scripts only unless --all is specified\n if (!options?.all) {\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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 };\n\n const remoteFilePaths = new Set(remoteFiles.map(f => f.path));\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 // Process downloaded files\n for (const { file, content } of fileContents) {\n const localPath = path.join(filesDir, file.path);\n const remoteHash = calculateHash(content);\n\n let needsUpdate = true;\n\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n\n if (localHash === remoteHash) {\n needsUpdate = false;\n result.unchanged.push(file.path);\n }\n }\n\n if (needsUpdate) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, content);\n result.downloaded.push(file.path);\n }\n\n // Update sync state with metadata\n syncState.files[file.path] = {\n localHash: remoteHash,\n remoteHash: remoteHash,\n metadata: file.metadata ? {\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 } : undefined,\n };\n }\n\n // Check for files that were deleted on remote\n const localFiles = getAllFilesInDir(filesDir);\n for (const localFile of localFiles) {\n if (!remoteFilePaths.has(localFile)) {\n // File exists locally but not on remote\n const syncInfo = syncState.files[localFile];\n if (syncInfo) {\n // Was synced before, now deleted on remote - delete locally\n const localPath = path.join(filesDir, localFile);\n fs.unlinkSync(localPath);\n result.deleted.push(localFile);\n delete syncState.files[localFile];\n }\n // If no sync info, it's a new local file - don't delete\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n async push(): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\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 };\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\n const localFiles = getAllFilesInDir(filesDir);\n\n // Determine which files need to be pushed by comparing with sync state\n const filesToUpload: string[] = [];\n const filesToUpdate: { localFile: string; remoteFile: RemoteFile; content: Buffer; localHash: string }[] = [];\n const filesUnchanged: string[] = [];\n\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\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 // Local file hasn't changed since last sync - skip\n filesUnchanged.push(localFile);\n } else {\n // Local file changed - needs update\n filesToUpdate.push({ localFile, remoteFile, content, localHash });\n }\n } else {\n // File doesn't exist on remote - needs upload\n filesToUpload.push(localFile);\n }\n }\n\n // Upload new files\n for (const localFile of filesToUpload) {\n const localPath = path.join(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n const localHash = calculateHash(content);\n\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n\n // Update changed files\n for (const { localFile, remoteFile, content, localHash } of filesToUpdate) {\n await this.farseerClient.updateFile(remoteFile.reference, content, path.basename(localFile));\n result.updated.push(localFile);\n\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n }\n\n // Mark unchanged files\n result.unchanged = filesUnchanged;\n\n // Delete files on remote that were deleted locally\n const localFileSet = new Set(localFiles);\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (!localFileSet.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(): Promise<boolean> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter to scripts only (same as pull/status) to avoid false positives\n // from non-script files like .json, .png, etc.\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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 script files\n const isScript = DEFAULT_SCRIPT_EXTENSIONS.some(ext => filePath.toLowerCase().endsWith(ext));\n if (!isScript) 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 * 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(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 return files;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAsE;AACtE,qBAAiI;AACjI,oBAAuB;AA0BhB,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,aAAa,cAAc,OAAO;AACrD,aAAO,KAAK,MAAM,OAAO;AAAA,IAC7B,QAAQ;AACJ,aAAO;AAAA,QACH,UAAU;AAAA,QACV,OAAO,CAAC;AAAA,MACZ;AAAA,IACJ;AAAA,EACJ;AAAA,EAEA,cAAc,OAAwB;AAClC,UAAM,mBAAe,gCAAgB,KAAK,MAAM;AAChD,8CAAsB,KAAK,QAAQ,YAAY,CAAC;AAChD,OAAG,cAAc,cAAc,KAAK,UAAU,OAAO,MAAM,CAAC,GAAG,OAAO;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAc,SAAkD;AAClE,UAAM,YAAY,KAAK,cAAc;AACrC,UAAM,eAAW,kCAAkB,KAAK,MAAM;AAG9C,QAAI,iBA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J;AAKA,WAAO;AAAA,EACX;AAAA,EAEA,MAAM,YAAY,UAGf;AACC,UAAM,eAAW,kCAAkB,KAAK,MAAM;AAC9C,UAAM,YAAY,KAAK,KAAK,UAAU,QAAQ;AAE9C,QAAI,eAA8B;AAClC,QAAI,gBAA+B;AAEnC,QAAI,GAAG,WAAW,SAAS,GAAG;AAE1B,qBAAe,GAAG,aAAa,WAAW,OAAO;AAAA,IACrD;AAEA,UAAM,aAAa,MAAM,KAAK,cAAc,cAAc,QAAQ;AAClE,QAAI,YAAY;AACZ,sBAAgB,MAAM,KAAK,cAAc,eAAe,WAAW,SAAS;AAAA,IAChF;AAEA,WAAO,EAAE,cAAc,cAAc;AAAA,EACzC;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,IAAI,MAAM,IAAI,OAAO,SAAS;AACxC,YAAI;AACA,gBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,cAAI,UAAU;AACV,iBAAK,WAAW;AAAA,UACpB;AAAA,QACJ,QAAQ;AAAA,QAER;AAAA,MACJ,CAAC,CAAC;AAAA,IACN;AAEA,WAAO;AAAA,EACX;AACJ;",
6
- "names": ["path"]
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { calculateHash, getTenantFilesDir, getSyncFilePath, ensureDirectoryExists, getAllFilesInDir, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\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?: { all?: boolean }): 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 to scripts only unless --all is specified\n if (!options?.all) {\n localFiles = localFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))\n );\n }\n\n // Get remote file list only (no content download)\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter to scripts only unless --all is specified\n if (!options?.all) {\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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?: { all?: boolean }): 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 =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.toLowerCase().endsWith(ext))\n );\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 =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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({ localHashes, remoteHashes, syncState, all: options?.all });\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(\n SyncService.buildConflicts([c])[0]\n );\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: {\n all?: boolean;\n force?: boolean;\n conflictResolutions?: ConflictResolutions;\n }): 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 to scripts only unless --all is specified\n if (!options?.all) {\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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 && !DEFAULT_SCRIPT_EXTENSIONS.some(ext => localFile.toLowerCase().endsWith(ext))) {\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({ localHashes, remoteHashes, syncState, all: options?.all });\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\n .filter(f => remoteFileMap.has(f))\n .map(f => remoteFileMap.get(f)!);\n\n const fetched = await fetchWithConcurrency(toFetch, async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n }, 15);\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(): Promise<boolean> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter to scripts only (same as pull/status) to avoid false positives\n // from non-script files like .json, .png, etc.\n remoteFiles = remoteFiles.filter(f =>\n DEFAULT_SCRIPT_EXTENSIONS.some(ext => f.name.toLowerCase().endsWith(ext))\n );\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 script files\n const isScript = DEFAULT_SCRIPT_EXTENSIONS.some(ext => filePath.toLowerCase().endsWith(ext));\n if (!isScript) 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 }): 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 non-script files unless --all\n if (!options.all) {\n if (!DEFAULT_SCRIPT_EXTENSIONS.some(ext => filePath.toLowerCase().endsWith(ext))) {\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(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 return files;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAsE;AACtE,qBAAiI;AACjI,oBAAuB;AA4DhB,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,aAAa,cAAc,OAAO;AACrD,aAAO,KAAK,MAAM,OAAO;AAAA,IAC7B,QAAQ;AACJ,aAAO;AAAA,QACH,UAAU;AAAA,QACV,OAAO,CAAC;AAAA,MACZ;AAAA,IACJ;AAAA,EACJ;AAAA,EAEA,cAAc,OAAwB;AAClC,UAAM,mBAAe,gCAAgB,KAAK,MAAM;AAChD,8CAAsB,KAAK,QAAQ,YAAY,CAAC;AAChD,OAAG,cAAc,cAAc,KAAK,UAAU,OAAO,MAAM,CAAC,GAAG,OAAO;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAc,SAAkD;AAClE,UAAM,YAAY,KAAK,cAAc;AACrC,UAAM,eAAW,kCAAkB,KAAK,MAAM;AAG9C,QAAI,iBAAa,iCAAiB,QAAQ;AAG1C,QAAI,CAAC,SAAS,KAAK;AACf,mBAAa,WAAW;AAAA,QAAO,OAC3B,gDAA0B,KAAK,SAAO,EAAE,YAAY,EAAE,SAAS,GAAG,CAAC;AAAA,MACvE;AAAA,IACJ;AAGA,QAAI,cAAc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IONS
27
27
  });
28
28
  module.exports = __toCommonJS(constants_exports);
29
- const CLI_VERSION = "1.0.6";
29
+ const CLI_VERSION = "1.0.9";
30
30
  const FARSEER_CLIENT_URL = "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar";
31
31
  const FARSEER_CLIENT_AXIOS_URL = "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar";
32
32
  const KEYCLOAK_TOKEN_URL = "https://login.farseer.io/auth/realms/master/protocol/openid-connect/token";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/constants.ts"],
4
- "sourcesContent": ["// CLI version - update this when publishing new version\nexport const CLI_VERSION = '1.0.6';\n\n// Farseer client package URLs - update these when new versions are released\nexport const FARSEER_CLIENT_URL = 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar';\nexport const FARSEER_CLIENT_AXIOS_URL = 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar';\n\n// Keycloak auth configuration\nexport const KEYCLOAK_TOKEN_URL = 'https://login.farseer.io/auth/realms/master/protocol/openid-connect/token';\nexport const KEYCLOAK_CLIENT_ID = 'security-admin-console';\n\n// Default paths\nexport const SCRIPTS_FOLDER_PATH = ['Files', 'Scripts'];\n\n// Supported script file extensions\nexport const SCRIPT_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs'];\n"],
4
+ "sourcesContent": ["// CLI version - update this when publishing new version\nexport const CLI_VERSION = '1.0.9';\n\n// Farseer client package URLs - update these when new versions are released\nexport const FARSEER_CLIENT_URL = 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar';\nexport const FARSEER_CLIENT_AXIOS_URL = 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar';\n\n// Keycloak auth configuration\nexport const KEYCLOAK_TOKEN_URL = 'https://login.farseer.io/auth/realms/master/protocol/openid-connect/token';\nexport const KEYCLOAK_CLIENT_ID = 'security-admin-console';\n\n// Default paths\nexport const SCRIPTS_FOLDER_PATH = ['Files', 'Scripts'];\n\n// Supported script file extensions\nexport const SCRIPT_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs'];\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,MAAM,cAAc;AAGpB,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AAGjC,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAG3B,MAAM,sBAAsB,CAAC,SAAS,SAAS;AAG/C,MAAM,oBAAoB,CAAC,OAAO,OAAO,QAAQ,MAAM;",
6
6
  "names": []
7
7
  }
@@ -280,10 +280,10 @@ function parseAppArgs(args) {
280
280
  process.exit(1);
281
281
  }
282
282
  const EMPTY_CLIENT_PATTERNS = [
283
- /const farseerClient = new farseer\.FarseerClient\(\s*\);/g,
284
- /const fClient = new farseer\.FarseerClient\(\s*\);/g
283
+ /const farseerClient = new farseer\.FarseerClient\(\s*\);/,
284
+ /const fClient = new farseer\.FarseerClient\(\s*\);/
285
285
  ];
286
- const INJECTED_CLIENT_PATTERN = /const (farseerClient|fClient) = new farseer\.FarseerClient\(\{[\s\S]*?basePath:[\s\S]*?headers:[\s\S]*?'X-TENANT-ID':[\s\S]*?'X-API-KEY':[\s\S]*?\}\);/g;
286
+ const INJECTED_CLIENT_PATTERN = /const (farseerClient|fClient) = new farseer\.FarseerClient\(\{[\s\S]*?basePath:[\s\S]*?headers:[\s\S]*?'X-TENANT-ID':[\s\S]*?'X-API-KEY':[\s\S]*?\}\);/;
287
287
  function injectCredentials(code, credential) {
288
288
  const clientConfig = `{
289
289
  basePath: '${credential.basePath}',
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/helpers.ts"],
4
- "sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCurrentTenant, getCurrentCheckout, getCurrentOrganisation, getTenantOrg, saveTenantOrgMapping } from '../services/configService';\nimport { logger } from './logger';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath);\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n// Get all files in directory (not just scripts)\nexport function getAllFilesInDir(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFilesInDir(fullPath, base));\n } else if (item.isFile()) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * Resolve tenant from argument or checkout.\n * If tenant is provided, use it. Otherwise, use checked-out tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Resolve organisation and tenant from argument or checkout.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (User can use checkout for different org/tenant)\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return checkout;\n }\n\n return null;\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer <command> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant, saves mapping for future use\n * - <tenant>: Look up org from saved mapping or use checkout\n * - (no args): Use current checkout\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n // Save mapping for future use\n saveTenantOrgMapping(tenant, org);\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // Try to get org from saved mapping\n const savedOrg = getTenantOrg(tenant);\n if (savedOrg) {\n if (savedOrg === tenant) {\n logger.dim(`Using tenant: ${tenant} (from saved mapping)`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${savedOrg}, from saved mapping)`);\n }\n return { organisation: savedOrg, tenant };\n }\n\n // No saved mapping - show error with helpful message\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Please specify both organisation and tenant:');\n logger.dim(` farseer <command> <organisation> <tenant>`);\n logger.dim(` Example: farseer pull jgl tt-hotels-hr-dev`);\n logger.dim('');\n logger.dim('Or checkout the tenant first:');\n logger.dim(` farseer checkout <organisation> <tenant>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - use current checkout\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return checkout;\n }\n\n // No checkout either\n logger.error('No tenant specified.');\n logger.dim('Either specify organisation and tenant: farseer <command> <org> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <org> <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer <command> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n // Import here to avoid circular dependency\n const { getCredential } = require('../services/configService');\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(args: string[]): ParsedAppArgs {\n if (args.length === 0) {\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // Check if first argument is a known tenant\n if (args.length >= 2 && isKnownTenant(args[0])) {\n // First arg is tenant, rest is app name\n // Assume organisation = tenant when specified via command line\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' ')\n };\n }\n\n // Use checked-out tenant, all args are app name\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return {\n organisation: checkout.organisation,\n tenant: checkout.tenant,\n appName: args.join(' ')\n };\n }\n\n // No checked-out tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' ')\n };\n }\n\n // Only one arg and no checkout - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> <app-name>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline)\nconst INJECTED_CLIENT_PATTERN = /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();'\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();'\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some(pattern => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(\n chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex))\n );\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime\n ? new Date(entry.uploadTime).toLocaleString()\n : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
4
+ "sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCurrentTenant, getCurrentCheckout, getCurrentOrganisation, getTenantOrg, saveTenantOrgMapping } from '../services/configService';\nimport { logger } from './logger';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath);\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n// Get all files in directory (not just scripts)\nexport function getAllFilesInDir(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFilesInDir(fullPath, base));\n } else if (item.isFile()) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * Resolve tenant from argument or checkout.\n * If tenant is provided, use it. Otherwise, use checked-out tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Resolve organisation and tenant from argument or checkout.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (User can use checkout for different org/tenant)\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return checkout;\n }\n\n return null;\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer <command> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant, saves mapping for future use\n * - <tenant>: Look up org from saved mapping or use checkout\n * - (no args): Use current checkout\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n // Save mapping for future use\n saveTenantOrgMapping(tenant, org);\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // Try to get org from saved mapping\n const savedOrg = getTenantOrg(tenant);\n if (savedOrg) {\n if (savedOrg === tenant) {\n logger.dim(`Using tenant: ${tenant} (from saved mapping)`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${savedOrg}, from saved mapping)`);\n }\n return { organisation: savedOrg, tenant };\n }\n\n // No saved mapping - show error with helpful message\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Please specify both organisation and tenant:');\n logger.dim(` farseer <command> <organisation> <tenant>`);\n logger.dim(` Example: farseer pull jgl tt-hotels-hr-dev`);\n logger.dim('');\n logger.dim('Or checkout the tenant first:');\n logger.dim(` farseer checkout <organisation> <tenant>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - use current checkout\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return checkout;\n }\n\n // No checkout either\n logger.error('No tenant specified.');\n logger.dim('Either specify organisation and tenant: farseer <command> <org> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <org> <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer <command> <tenant>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n // Import here to avoid circular dependency\n const { getCredential } = require('../services/configService');\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(args: string[]): ParsedAppArgs {\n if (args.length === 0) {\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // Check if first argument is a known tenant\n if (args.length >= 2 && isKnownTenant(args[0])) {\n // First arg is tenant, rest is app name\n // Assume organisation = tenant when specified via command line\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' ')\n };\n }\n\n // Use checked-out tenant, all args are app name\n const checkout = getCurrentCheckout();\n if (checkout) {\n if (checkout.organisation === checkout.tenant) {\n logger.dim(`Using checked-out tenant: ${checkout.tenant}`);\n } else {\n logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);\n }\n return {\n organisation: checkout.organisation,\n tenant: checkout.tenant,\n appName: args.join(' ')\n };\n }\n\n // No checked-out tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' ')\n };\n }\n\n // Only one arg and no checkout - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> <app-name>');\n logger.dim('Or checkout a tenant: farseer checkout <tenant>');\n process.exit(1);\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN = /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();'\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();'\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some(pattern => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(\n chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex))\n );\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime\n ? new Date(entry.uploadTime).toLocaleString()\n : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAAiH;AACjH,oBAAuB;AAEhB,SAAS,cAAc,SAAkC;AAC5D,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAChE;AAEO,SAAS,aAAqB;AACjC,SAAO,KAAK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