farseer-cli 1.10.3 → 1.11.0

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 (78) hide show
  1. package/README.md +5 -0
  2. package/dist/commands/app.js +15 -12
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/apps.js +3 -3
  5. package/dist/commands/apps.js.map +2 -2
  6. package/dist/commands/cells.js +3 -3
  7. package/dist/commands/cells.js.map +2 -2
  8. package/dist/commands/config.js +23 -15
  9. package/dist/commands/config.js.map +2 -2
  10. package/dist/commands/dashboards.js +3 -3
  11. package/dist/commands/dashboards.js.map +2 -2
  12. package/dist/commands/dimensions.js +3 -3
  13. package/dist/commands/dimensions.js.map +2 -2
  14. package/dist/commands/files.js +5 -4
  15. package/dist/commands/files.js.map +2 -2
  16. package/dist/commands/formula.js +3 -3
  17. package/dist/commands/formula.js.map +2 -2
  18. package/dist/commands/list.js +5 -4
  19. package/dist/commands/list.js.map +2 -2
  20. package/dist/commands/login.js +6 -5
  21. package/dist/commands/login.js.map +2 -2
  22. package/dist/commands/model.js +5 -4
  23. package/dist/commands/model.js.map +2 -2
  24. package/dist/commands/push.js +5 -7
  25. package/dist/commands/push.js.map +2 -2
  26. package/dist/commands/run.js +3 -3
  27. package/dist/commands/run.js.map +2 -2
  28. package/dist/commands/sheets.js +3 -3
  29. package/dist/commands/sheets.js.map +2 -2
  30. package/dist/commands/variables.js +5 -4
  31. package/dist/commands/variables.js.map +2 -2
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/mcp/index.js.map +2 -2
  34. package/dist/mcp/tools/appTools.js +3 -3
  35. package/dist/mcp/tools/appTools.js.map +2 -2
  36. package/dist/mcp/tools/dataTools.js +5 -2
  37. package/dist/mcp/tools/dataTools.js.map +2 -2
  38. package/dist/mcp/tools/modelTools.js +45 -48
  39. package/dist/mcp/tools/modelTools.js.map +2 -2
  40. package/dist/mcp/utils/session.js +2 -2
  41. package/dist/mcp/utils/session.js.map +2 -2
  42. package/dist/services/appSyncService.js.map +1 -1
  43. package/dist/services/apps.js +149 -0
  44. package/dist/services/apps.js.map +7 -0
  45. package/dist/services/authErrors.js +77 -0
  46. package/dist/services/authErrors.js.map +7 -0
  47. package/dist/services/configService.js +7 -4
  48. package/dist/services/configService.js.map +2 -2
  49. package/dist/services/credentials.js +87 -0
  50. package/dist/services/credentials.js.map +7 -0
  51. package/dist/services/farseerService.js +247 -112
  52. package/dist/services/farseerService.js.map +2 -2
  53. package/dist/services/httpError.js +35 -0
  54. package/dist/services/httpError.js.map +7 -0
  55. package/dist/services/modelExport.js +63 -0
  56. package/dist/services/modelExport.js.map +7 -0
  57. package/dist/services/organisation.js +88 -0
  58. package/dist/services/organisation.js.map +7 -0
  59. package/dist/services/preflight.js +10 -13
  60. package/dist/services/preflight.js.map +2 -2
  61. package/dist/services/syncService.js +2 -2
  62. package/dist/services/syncService.js.map +2 -2
  63. package/dist/utils/constants.js +2 -5
  64. package/dist/utils/constants.js.map +2 -2
  65. package/dist/utils/fileLogger.js +24 -1
  66. package/dist/utils/fileLogger.js.map +2 -2
  67. package/dist/utils/folderMatch.js +49 -0
  68. package/dist/utils/folderMatch.js.map +7 -0
  69. package/dist/utils/helpers.js +26 -0
  70. package/dist/utils/helpers.js.map +2 -2
  71. package/dist/utils/syncScope.js +44 -0
  72. package/dist/utils/syncScope.js.map +7 -0
  73. package/docs/api-reference.md +13 -1
  74. package/package.json +1 -1
  75. package/dist/services/farseerApi.js +0 -716
  76. package/dist/services/farseerApi.js.map +0 -7
  77. package/dist/services/farseerFactory.js +0 -276
  78. package/dist/services/farseerFactory.js.map +0 -7
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/services/farseerApi.ts"],
4
- "sourcesContent": ["/**\n * FarseerApi - Direct HTTP API client using JWT Bearer token authentication\n *\n * This is an alternative to FarseerService that doesn't use farseer-client library.\n * Use this when authenticating via browser login (Keycloak JWT token) instead of API key.\n */\n\nimport axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport chalk from 'chalk';\nimport * as farseer from 'farseer-client';\nimport { getUserAuth, setUserAuth } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { toError } from '../utils/errorFormatter';\nimport { logger } from '../utils/logger';\n\n// RemoteFile lives in farseerFactory.ts (canonical). Re-export so existing\n// imports (`import { RemoteFile } from './farseerApi'`) still resolve, and\n// import locally so this file's own annotations type-check.\nimport type { RemoteFile, OrganizationInfo } from './farseerFactory';\nexport type { RemoteFile };\n\ninterface FolderItem {\n id: number;\n name: string;\n type: 'folder' | 'farseer-file';\n reference?: string;\n}\n\ninterface FolderContent {\n items: FolderItem[];\n}\n\n// App (Remote Job) types \u2014 orthogonal-axes shape:\n// dataType \u2208 { 'string', 'boolean' }\n// fixed?: locked at run time (admin sets, user cannot override)\n// options?: closed allowed-value set (string dataType only)\nexport type AppArgumentDataType = 'string' | 'boolean';\n\nexport interface AppArgument {\n name: string;\n dataType: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport interface AppScriptFile {\n id: string;\n name: string;\n}\n\n// A resolved source folder: its node id (to set on the app) plus the script\n// files it contains (to validate an entrypoint lives inside it).\nexport interface SourceFolderResolution {\n id: number;\n scripts: AppScriptFile[];\n}\n\nexport interface RemoteApp {\n id: number;\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n status: string;\n lastHeartbeat: string;\n mainScriptFileId: string | null;\n scriptFiles?: AppScriptFile[];\n sourceFolderId?: number;\n schedule?: string | null;\n runnerName?: string | null;\n runnerImage?: string | null;\n predefinedActions: unknown[];\n}\n\n// The fields a Remote Job update writes. The backend PUT replaces the whole\n// row, so any field omitted here is reset to its default (args/predefined \u2192\n// empty, the rest \u2192 null). `mergeAppUpdate` exists so a caller that only wants\n// to touch one field doesn't silently wipe the others.\nexport interface UpdateAppPayload {\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n mainScriptFileId: string | null;\n sourceFolderId: number | null;\n schedule: string | null;\n runnerName: string | null;\n runnerImage: string | null;\n predefinedActions: unknown[];\n}\n\n// `scriptFileIds` is accepted from callers for backwards compatibility but is\n// never sent \u2014 the backend ignores it (scripts derive from the source folder).\nexport type AppUpdateChanges = Partial<UpdateAppPayload> & { scriptFileIds?: string[] };\n\n/**\n * Overlay a caller's changes onto an app's current state to build a full,\n * non-destructive update payload. Every field the caller leaves out keeps its\n * current value \u2014 so changing one setting never clears the others.\n */\nexport function mergeAppUpdate(current: RemoteApp, changes: AppUpdateChanges): UpdateAppPayload {\n return {\n name: changes.name ?? current.name,\n description: changes.description ?? current.description ?? '',\n expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],\n mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,\n sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,\n schedule: changes.schedule ?? current.schedule ?? null,\n runnerName: changes.runnerName ?? current.runnerName ?? null,\n runnerImage: changes.runnerImage ?? current.runnerImage ?? null,\n predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? [],\n };\n}\n\n/**\n * Find a script in a source folder's file list by its exact name. Farseer file\n * names are case-sensitive \u2014 two files differing only in case can coexist in a\n * folder \u2014 so matching is exact, never case-folded, to avoid resolving an\n * entrypoint to the wrong file. Resolution is folder-scoped, never tenant-wide,\n * so a same-named file in another folder can't be picked by accident. Returns\n * undefined when the name isn't in the folder.\n */\nexport function findScriptInFolder(folderScripts: AppScriptFile[], name: string): AppScriptFile | undefined {\n return folderScripts.find((s) => s.name === name);\n}\n\n// The one client capability applySourceFolderChange needs. Kept minimal (not the\n// whole client) so it is trivial to unit-test with a fake resolver.\nexport interface SourceFolderResolver {\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n}\n\n// Selects only how an error is presented \u2014 dimming, and `--flag` (CLI) vs param\n// (MCP) wording. It is a pure UX knob: the decision, the ids written to `changes`,\n// and the success/failure outcome are identical for both values. Never branch\n// functionality on it.\nexport type ConfigureCaller = 'cli' | 'mcp';\n\n/**\n * Resolve the source-folder / entrypoint settings for an `app configure` and\n * write the resulting ids into `changes`, applying the rule that an app's\n * scripts derive from its source folder and the entrypoint must be a file in\n * that folder. `sourceFolder` (a path under Files/) switches the folder;\n * otherwise the entrypoint is validated against the app's current folder. Moving\n * the folder must not orphan the entrypoint: if the current entrypoint isn't in\n * the new folder and the caller didn't supply one, the request is rejected \u2014 the\n * entrypoint is never silently cleared or relocated.\n *\n * Returns an error message for the caller to surface (and `changes` is left\n * untouched), or null once the ids have been written. The decision lives here so\n * the CLI and MCP paths can't drift. `caller` affects only how an error reads\n * (dimming, `--flag` vs param wording) \u2014 never which errors fire or what gets\n * written \u2014 so the two surfaces stay behaviourally identical.\n */\nexport async function applySourceFolderChange(\n client: SourceFolderResolver,\n app: Pick<RemoteApp, 'scriptFiles' | 'mainScriptFileId'>,\n changes: AppUpdateChanges,\n options: { sourceFolder?: string; entrypoint?: string },\n caller: ConfigureCaller,\n): Promise<string | null> {\n const cli = caller === 'cli';\n // Secondary guidance lines are dimmed in the terminal; plain for the MCP tool.\n const hint = (text: string) => (cli ? chalk.dim(text) : text);\n\n let folderScripts = app.scriptFiles ?? [];\n let sourceFolderId: number | undefined;\n\n if (options.sourceFolder) {\n let resolved: SourceFolderResolution;\n try {\n resolved = await client.resolveSourceFolder(options.sourceFolder);\n } catch {\n return [\n `Source folder not found under Files/: ${options.sourceFolder}`,\n hint('Use a path relative to Files/, e.g. \"Scripts/MyApp\".'),\n ].join('\\n');\n }\n sourceFolderId = resolved.id;\n folderScripts = resolved.scripts;\n\n // Moving the folder must not leave the entrypoint pointing outside it.\n if (!options.entrypoint && app.mainScriptFileId) {\n const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);\n if (!stillThere) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n return [\n \"The app's current entrypoint is not in the new source folder.\",\n hint(\n cli\n ? 'Pass --entrypoint <script> (a file in the new folder) in the same command.'\n : 'Pass \"entrypoint\" (a file in the new folder) in the same call.',\n ),\n hint(`Files in this folder: ${files}`),\n ].join('\\n');\n }\n }\n }\n\n let mainScriptFileId: string | undefined;\n if (options.entrypoint) {\n const match = findScriptInFolder(folderScripts, options.entrypoint);\n if (!match) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n const lines = [\n `Entrypoint not found in the source folder: ${options.entrypoint}`,\n hint(`Files in this folder: ${files}`),\n ];\n if (!options.sourceFolder) {\n lines.push(\n hint(\n cli\n ? 'To use a file from another folder, set it first with --source-folder <path>.'\n : 'To use a file from another folder, pass sourceFolder first.',\n ),\n );\n }\n return lines.join('\\n');\n }\n mainScriptFileId = match.id;\n }\n\n // Apply only after every check passes, so a rejected request never partially\n // mutates `changes`.\n if (sourceFolderId !== undefined) {\n changes.sourceFolderId = sourceFolderId;\n }\n if (mainScriptFileId !== undefined) {\n changes.mainScriptFileId = mainScriptFileId;\n }\n return null;\n}\n\n// `reference` (the Remote Job id) is deliberately the only id here \u2014 apps also\n// have a folder-item id, in an overlapping number space, and carrying both is\n// what let `app delete` destroy unrelated objects.\nexport interface AppListItem {\n name: string;\n type: string;\n reference: string;\n}\n\nexport const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;\n\n// A `folders.resolveItems` result: `id` is the folder-item id, `reference` the\n// id in the item's own domain (for REMOTE_JOB, the Remote Job id).\nexport interface ResolvedFolderItem {\n id: number;\n name: string;\n type: string;\n reference: string;\n}\n\nexport function remoteJobReverseReferences(remoteJobIds: readonly string[]): farseer.ReverseReference[] {\n return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));\n}\n\n// A deliberate refusal from the delete guard, as distinct from a transport\n// failure. Callers surface it as a validation error, not a retryable one:\n// nothing was deleted and retrying cannot change that.\nexport class AppDeleteRefusedError extends Error {}\n\n/**\n * Pick the folder-item id to delete for an app, from the `resolveItems` response.\n *\n * Remote Job ids and folder-item ids overlap \u2014 the low folder ids are the roots\n * (13 = Files, 15 = Apps) \u2014 so posting a Remote Job id to `deleteItems` deletes\n * whichever unrelated node owns that number. `resolveItems` is type-scoped\n * server-side; these checks make sure a server change can't widen that.\n */\nexport function resolveAppItemNodeId(remoteJobId: string, items: readonly ResolvedFolderItem[]): number {\n const matches = items.filter((item) => item.reference === remoteJobId);\n\n if (matches.length === 0) {\n throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);\n }\n if (matches.length > 1) {\n throw new AppDeleteRefusedError(\n `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`,\n );\n }\n\n const item = matches[0];\n if (item.type !== REMOTE_JOB_ITEM_TYPE) {\n throw new AppDeleteRefusedError(\n `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ` +\n `(\"${item.name}\"), not an app.`,\n );\n }\n\n return item.id;\n}\n\nexport class FarseerApi {\n private client: AxiosInstance;\n private tenantId: string;\n private basePath: string;\n private accessToken: string;\n\n private isRefreshing = false;\n private refreshSubscribers: ((token: string) => void)[] = [];\n\n // basePath is passed in rather than worked out here. It used to come from\n // `getCredential(...)?.basePath` keyed on the organisation, so a stored API\n // key named after the organisation silently decided where a browser-login\n // request went \u2014 and the SDK client for the same pair never consulted it.\n // The one decision now lives in ResolvedAuth (services/farseerFactory).\n constructor(accessToken: string, basePath: string, tenantId: string) {\n this.tenantId = tenantId;\n this.accessToken = accessToken;\n this.basePath = basePath;\n\n this.client = axios.create({\n baseURL: basePath,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'x-api-version': '3.3.0',\n 'X-TENANT-ID': this.tenantId,\n },\n });\n\n // Add response interceptor for automatic token refresh on 401\n this.client.interceptors.response.use(\n (response) => response,\n async (error) => {\n const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };\n\n // Only handle 401 errors and avoid infinite loops\n if (error.response?.status === 401 && !originalRequest._retry) {\n originalRequest._retry = true;\n\n // If already refreshing, wait for the new token\n if (this.isRefreshing) {\n return new Promise((resolve) => {\n this.refreshSubscribers.push((token: string) => {\n originalRequest.headers['Authorization'] = `Bearer ${token}`;\n resolve(this.client(originalRequest));\n });\n });\n }\n\n this.isRefreshing = true;\n\n try {\n const auth = getUserAuth();\n if (!auth?.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n throw new Error('Token refresh failed');\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update this client's token\n this.updateAccessToken(refreshed.accessToken);\n\n // Notify all waiting requests\n this.refreshSubscribers.forEach((callback) => callback(refreshed.accessToken));\n this.refreshSubscribers = [];\n\n // Retry the original request\n originalRequest.headers['Authorization'] = `Bearer ${refreshed.accessToken}`;\n return this.client(originalRequest);\n } catch (refreshError) {\n // Token refresh failed - let the error propagate\n this.refreshSubscribers = [];\n throw error;\n } finally {\n this.isRefreshing = false;\n }\n }\n\n return Promise.reject(error);\n },\n );\n }\n\n /**\n * Update the access token (used when token is refreshed)\n */\n updateAccessToken(newToken: string): void {\n this.accessToken = newToken;\n this.client.defaults.headers['Authorization'] = `Bearer ${newToken}`;\n }\n\n async testConnection(): Promise<boolean> {\n try {\n await this.getItemByPath(['Files']);\n return true;\n } catch {\n return false;\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n const response = await this.client.get('/organization');\n return response.data as OrganizationInfo;\n }\n\n async getFilesFolder(): Promise<{ id: number; name: string; type: string } | null> {\n try {\n const item = await this.getItemByPath(['Files']);\n return {\n id: item.id,\n name: item.name,\n type: item.type,\n };\n } catch {\n return null;\n }\n }\n\n private async listFolderItems(folderId: number | null): Promise<FolderContent> {\n // Body is array: [{ id: null }] for root, [{ id: folderId }] for specific folder\n const response = await this.client.post('/folders/items', [{ id: folderId }]);\n return response.data[0] || { items: [] };\n }\n\n private async findFolderByName(parentId: number | null, name: string): Promise<FolderItem | null> {\n const content = await this.listFolderItems(parentId);\n const folder = content.items?.find(\n (item) => item.name.toLowerCase() === name.toLowerCase() && item.type.toLowerCase() === 'folder',\n );\n return folder || null;\n }\n\n private async getItemByPath(path: string[]): Promise<FolderItem> {\n let currentId: number | null = null;\n\n for (const segment of path) {\n const folder = await this.findFolderByName(currentId, segment);\n if (!folder) {\n throw new Error(`Folder not found: ${segment}`);\n }\n currentId = folder.id;\n }\n\n if (currentId === null) {\n throw new Error('Path is empty');\n }\n\n // Return a minimal FolderItem with the found id\n return { id: currentId, name: path[path.length - 1], type: 'folder' };\n }\n\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const files: RemoteFile[] = [];\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'folder') {\n const subFiles = await this.listFiles([...folderPath, item.name]);\n files.push(...subFiles);\n } else if ((itemType === 'farseer-file' || itemType === 'farseer_file') && item.reference) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference,\n });\n }\n }\n } catch (error) {\n // Critical: do NOT swallow listFiles errors. Returning [] on\n // a transient 5xx / network blip / expired token would make a\n // mirror push (push --force) treat every synced file as a\n // delete candidate \u2014 silent data loss on a backend hiccup.\n // Forbidden gets a friendlier \"wrong tenant\" message;\n // everything else is rethrown via toError so the command-layer\n // formatter surfaces status + body.\n if (axios.isAxiosError(error) && error.response?.data?.code === 'Forbidden') {\n const errorMessage = error.response.data?.message || 'Access denied';\n throw new Error(\n `Access denied: ${errorMessage}\\nYou may need to use --tenant-id to specify a different tenant ID.`,\n );\n }\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n return files;\n }\n\n async getFileContent(reference: string): Promise<string> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'text',\n });\n return response.data;\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'arraybuffer',\n });\n return Buffer.from(response.data);\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.getItemByPath(folderPath);\n\n const formData = new FormData();\n // Force application/octet-stream so undici / form-data don't fall back\n // to mime.lookup(filename), which yields surprising types for source\n // files (`.ts` \u2192 video/mp2t) and can trip WAFs on the upload path.\n // Symmetric with FarseerService (API-key path).\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n formData.append('category', 'GENERAL');\n formData.append('folderId', folder.id.toString());\n\n try {\n await this.client.post('/farseerFiles', formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n // Route through the shared formatter so all the triage hints\n // (opaque BadRequest, folder allowedTypes rejection, \u2026) reach\n // the user. The previous local `extractAxiosError` produced a\n // raw \"HTTP 400 \u2014 Bad Request \u2014 {body}\" with no actionable hint.\n throw await toError(error, `Failed to create file \"${fileName}\"`);\n }\n }\n\n async updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void> {\n const formData = new FormData();\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n\n try {\n await this.client.put(`/farseerFiles/${reference}`, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n throw await toError(error, `Failed to update file \"${fileName}\" (ref: ${reference})`);\n }\n }\n\n async deleteFile(reference: string): Promise<void> {\n try {\n await this.client.delete(`/farseerFiles/${reference}`);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n private async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n try {\n await this.getItemByPath(currentPath);\n } catch {\n if (currentPath.length > 1) {\n const parentPath = currentPath.slice(0, -1);\n const parent = await this.getItemByPath(parentPath);\n // See farseerService.ts:ensureFolderPath for the long-form\n // explanation. TL;DR: backend treats `[]` as \"nothing\n // allowed in this folder\" and any subsequent createFile\n // returns HTTP 400. `null` makes the new folder inherit\n // the parent's allowedTypes (which is what the web UI\n // does). Keep the two paths in sync.\n await this.client.post('/folders', {\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n const folderPath = pathParts;\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemType = item.type.toLowerCase();\n if (\n item.name === fileName &&\n (itemType === 'farseer-file' || itemType === 'farseer_file') &&\n item.reference\n ) {\n return {\n name: item.name,\n path: filePath,\n reference: item.reference,\n };\n }\n }\n } catch {\n return null;\n }\n\n return null;\n }\n\n async getFileMetadata(reference: string): Promise<import('./farseerFactory').FileMetadata | null> {\n try {\n const response = await this.client.get(`/farseerFiles/${reference}/metadata`);\n const data = response.data;\n\n return {\n uploadTime: data.uploadTime,\n uploader: data.uploader\n ? {\n id: data.uploader.id,\n email: data.uploader.email || '',\n firstName: data.uploader.firstName || '',\n lastName: data.uploader.lastName || '',\n }\n : undefined,\n size: data.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n isTextFile(filename: string): boolean {\n const ext = filename.toLowerCase().split('.').pop() || '';\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(\n ext,\n );\n }\n\n isBinaryFile(filename: string): boolean {\n return !this.isTextFile(filename);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * Get the Apps folder ID\n */\n async getAppsFolderId(): Promise<number | null> {\n const content = await this.listFolderItems(null);\n const appsFolder = content.items?.find(\n (item) => item.name.toLowerCase() === 'apps' && item.type.toLowerCase() === 'folder',\n );\n return appsFolder?.id || null;\n }\n\n /**\n * List all apps (Remote Jobs) on the tenant, including those in subfolders\n */\n async listApps(): Promise<AppListItem[]> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n return [];\n }\n\n return this.listAppsRecursive(appsFolderId);\n }\n\n /**\n * Recursively list all apps in a folder and its subfolders\n */\n private async listAppsRecursive(folderId: number): Promise<AppListItem[]> {\n const apps: AppListItem[] = [];\n const content = await this.listFolderItems(folderId);\n\n for (const item of content.items || []) {\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'remote_job') {\n apps.push({\n name: item.name,\n type: item.type,\n reference: item.reference || '',\n });\n } else if (itemType === 'folder') {\n // Recurse into subfolder\n const subApps = await this.listAppsRecursive(item.id);\n apps.push(...subApps);\n }\n }\n\n return apps;\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const response = await this.client.get(`/remoteJobs/${referenceId}`);\n const app: RemoteApp = response.data;\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if ((!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<AppScriptFile[]> {\n try {\n const content = await this.listFolderItems(sourceFolderId);\n return (content.items || [])\n .filter((item) => {\n const t = item.type.toLowerCase();\n return (t === 'farseer-file' || t === 'farseer_file') && item.reference;\n })\n .map((item) => ({ id: item.reference!, name: item.name }));\n } catch {\n return [];\n }\n }\n\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.getItemByPath(['Files', ...segments]);\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Get app by name\n */\n async getAppByName(name: string): Promise<RemoteApp | null> {\n const apps = await this.listApps();\n const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());\n if (!app) {\n return null;\n }\n return this.getApp(app.reference);\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n const response = await this.client.post('/remoteJobs', {\n folderId: appsFolderId,\n name,\n });\n return response.data;\n }\n\n /**\n * Update an app\n */\n async updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp> {\n // The PUT replaces the whole record, so merge the changes onto currentApp.\n await this.client.put(`/remoteJobs/${referenceId}`, mergeAppUpdate(currentApp, update));\n // API returns 204 No Content, so fetch the updated app.\n const app = await this.getApp(referenceId);\n if (!app) {\n throw new Error(`Failed to fetch updated app ${referenceId}`);\n }\n return app;\n }\n\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n const response = await this.client.post<ResolvedFolderItem[]>(\n '/folders/resolveItems',\n remoteJobReverseReferences(remoteJobIds),\n );\n return response.data ?? [];\n }\n\n // Takes the Remote Job id and resolves the folder-item id itself, so no\n // caller can hand this a raw node id. See `resolveAppItemNodeId`.\n async deleteApp(remoteJobId: string): Promise<void> {\n const items = await this.resolveRemoteJobItems([remoteJobId]);\n const itemNodeId = resolveAppItemNodeId(remoteJobId, items);\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.post('/folders/deleteItems', [{ id: itemNodeId }]);\n }\n\n /**\n * Run an app with arguments\n */\n async runApp(referenceId: string, args: Record<string, string> = {}): Promise<{ executionId: string }> {\n const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {\n arguments: args,\n });\n return response.data;\n }\n\n /**\n * Get script files available for apps (searches all .ts/.js files in Files folder)\n * Returns full path relative to Files/ folder (e.g., \"Scripts/test.ts\", \"Scripts/subfolder/helper.ts\")\n */\n async getScriptFiles(): Promise<AppScriptFile[]> {\n // listFiles already searches recursively, so just filter for .ts/.js files\n const allFiles = await this.listFiles(['Files']);\n return allFiles\n .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))\n .map((f) => ({\n id: f.reference,\n name: f.path, // Use full path to support scripts in subfolders\n }));\n }\n\n // ==================== Model Export API ====================\n\n /**\n * Export the model structure. By default returns tables (without\n * members) and variables \u2014 enough for `farseer variables list` /\n * `farseer tables list` without dragging the full member matrix.\n *\n * Pass `types` to scope further. Pass `tableGids` / `variableGids`\n * to limit member/variable expansion to specific objects (used by\n * `dimension details <name>` so we hit one table's members instead\n * of all of them).\n *\n * Why this matters: an unscoped `['DTAB','DMEM','VAR']` export\n * pulls every member of every dimension over the wire. On larger\n * tenants the JSON gets big enough to exceed Cloud Run / proxy\n * response limits, so the client sees \"socket hang up\" before any\n * data arrives. The server-side filter is honoured all the way down\n * to rama (modelMapping.ts \u2192 modelService2.modelExport), so a\n * scoped request is cheap.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Never request CELL \u2014 the full cell matrix is enormous for GL-scale tenants\n // and nothing in the CLI consumes it. Tables/members/variables only.\n const types = options.types ?? ['DTAB', 'VAR'];\n const requestBody: Record<string, unknown> = { types };\n if (options.tableGids && options.tableGids.length > 0) {\n requestBody.tableGids = options.tableGids;\n }\n if (options.variableGids && options.variableGids.length > 0) {\n requestBody.variableGids = options.variableGids;\n }\n\n try {\n const response = await this.client.post('/model/export', requestBody);\n return response.data;\n } catch (err) {\n // /model/export is the right path; if it fails we fall back to\n // initTagMap so older instances and partial outages still work.\n // Log the underlying error so users don't see a phantom slow\n // initTagMap fallback hide a real backend issue.\n const message = err instanceof Error ? err.message : String(err);\n logger.dim(`/model/export failed (${message}); falling back to initTagMap.`);\n return this.buildModelFromTagMaps(options);\n }\n }\n\n /**\n * Fetch one dimension table with its members through the\n * entities API (search \u2192 getRelations \u2192 getMany). This stays\n * scoped to a single table, unlike `/model/export` with\n * `tableGids` filter which currently 500s for some tables on\n * large tenants (rama-side scoping bug, tracked separately).\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.makeNativeClient(), name);\n }\n\n private makeNativeClient(): farseer.FarseerClient {\n return new farseer.FarseerClient({\n basePath: this.basePath,\n headers: {\n 'X-TENANT-ID': this.tenantId,\n Authorization: `Bearer ${this.accessToken}`,\n },\n });\n }\n\n private async buildModelFromTagMaps(options: ModelExportOptions = {}): Promise<ModelExport> {\n const types = options.types ?? ['DTAB', 'VAR'];\n const wantTables = types.includes('DTAB');\n const wantMembers = types.includes('DMEM');\n const wantVariables = types.includes('VAR');\n\n const nativeClient = this.makeNativeClient();\n\n let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await nativeClient.initTagMap();\n } catch (err: any) {\n if (err && typeof err.status === 'number' && typeof err.url === 'string') {\n const text = typeof err.text === 'function' ? await err.text().catch(() => '') : '';\n throw new Error(`initTagMap failed: HTTP ${err.status} ${text}`.trim());\n }\n throw err;\n }\n\n // initTagMap unconditionally pulls all three entity types from\n // the server, so this fallback can't avoid the wire cost the\n // way `/model/export` can. We can at least respect `options` on\n // the way out so callers see a shape consistent with the\n // primary path (tables-only / variables-only / scoped to gids).\n const tables: ModelExportTable[] = [];\n if (wantTables) {\n const tableGidFilter =\n options.tableGids && options.tableGids.length > 0 ? new Set(options.tableGids) : null;\n for (const [name, tag] of tagMaps.dimensionTableMapByName) {\n if (tableGidFilter && !tableGidFilter.has(tag.id)) continue;\n const members = wantMembers ? tagMaps.dimensionMemberMapsByTableId.get(tag.id) : undefined;\n tables.push({\n gid: tag.id,\n name,\n columns:\n tag.columns?.map((c) => ({\n name: c.name,\n type: c.foreignKey ? 'FOREIGN_KEY' : c.primaryKey ? 'PRIMARY_KEY' : String(c.type),\n foreignKeyTableName: c.foreignKey ? tagMaps.mapById.get(c.refTableGid)?.name : undefined,\n })) ?? [],\n rows: members ? Array.from(members.values()).map((m) => [m.name]) : [],\n });\n }\n }\n\n const variables: ModelExportVariable[] = [];\n if (wantVariables) {\n const variableGidFilter =\n options.variableGids && options.variableGids.length > 0 ? new Set(options.variableGids) : null;\n for (const [name, tag] of tagMaps.variableMapByName) {\n if (variableGidFilter && !variableGidFilter.has(tag.id)) continue;\n const dimNames = (tag.dimensionTagIds ?? [])\n .map((id) => tagMaps.mapById.get(id)?.name)\n .filter((n): n is string => Boolean(n));\n variables.push({\n gid: tag.id,\n name,\n tables: dimNames,\n members: [],\n rollupType: tag.rollupType ?? 'SUM',\n dataType: tag.dataType ?? 'DECIMAL',\n readonly: tag.readonly ?? false,\n calculateOnDemand: tag.calculateOnDemand ?? false,\n formula: tag.expression ?? null,\n description: tag.description ?? null,\n });\n }\n }\n\n return { tables, variables, dependencies: { tables: [], members: [], variables: [] } };\n }\n}\n\n/**\n * Shared helper used by both `FarseerApi` (JWT auth) and `FarseerService`\n * (apiKey auth) to fetch one dimension table's members through the\n * entities API. The two clients only differ in how they're constructed,\n * so the actual fetch logic is the same \u2014 kept in one place to avoid\n * drift between auth modes.\n *\n * Resolves the table by name first via `entities.search`. The\n * \"not found\" outcome therefore comes from an empty search result\n * (`searchResult.length < 1`), not from string-matching an exception\n * message \u2014 which means renames or i18n of the underlying error\n * won't silently regress this to a thrown exception.\n */\nexport async function loadDimensionTableViaEntitiesApi(\n nativeClient: farseer.FarseerClient,\n name: string,\n): Promise<ModelExportTable | null> {\n const searchResult = await nativeClient.entities.search({\n name,\n types: [farseer.EntityType.DimensionTable],\n limit: 1,\n });\n if (searchResult.length < 1) {\n return null;\n }\n // Hand off to the library helper now that we know the table\n // exists \u2014 it does the relations + getMany walk and returns\n // an arquero table with one table's members. Bounded by that\n // single table's size, not the whole tenant.\n const loaded = await nativeClient.data.loadFarseerDimensionTable(name);\n const objects = loaded.table.objects() as Array<Record<string, unknown>>;\n const columns = loaded.metadata.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: (c as { foreignKeyTableName?: string }).foreignKeyTableName,\n }));\n const rows = objects.map((obj) => columns.map((col) => obj[col.name ?? '']));\n return { name, columns, rows };\n}\n\n// Model Export types\n\n/**\n * Scope for `exportModel`. Default (no options) = tables + variables\n * without member rows. Pass `types: ['DTAB','DMEM']` + `tableGids` to\n * fetch members for specific tables only. The server honours these\n * filters all the way down to rama, so a scoped request is cheap on\n * a larger tenant where the unscoped export would otherwise time out.\n */\nexport type ModelExportType = 'DTAB' | 'DMEM' | 'VAR';\nexport interface ModelExportOptions {\n types?: ModelExportType[];\n /**\n * Backend-supported filter, currently no in-tree caller. We chose\n * the entities-API path (`loadDimensionTableWithMembers`) over\n * `/model/export?tableGids=\u2026` because rama 500s for some tables\n * on large tenants. Kept on the type so the surface mirrors the\n * server contract \u2014 re-introduce a caller once that backend bug\n * is fixed and we can switch back. Until then, treat this field\n * as \"shape-only\" and verify any new caller against a real\n * scoped fetch on a large tenant.\n */\n tableGids?: number[];\n /**\n * Same as `tableGids`, applied to variables. No in-tree caller;\n * kept for parity with the server-side filter.\n */\n variableGids?: number[];\n}\n\nexport interface ModelExport {\n tables: ModelExportTable[];\n variables: ModelExportVariable[];\n dependencies: {\n tables: string[];\n members: string[];\n variables: string[];\n };\n}\n\nexport interface ModelExportTable {\n /** Numeric id used by `tableGids` filtering. Present on the server-side\n * `/model/export` response; absent in the initTagMap fallback path. */\n gid?: number;\n name: string;\n columns: ModelExportColumn[];\n defaultMember?: string | null;\n folderPath?: string[];\n rows: any[][];\n autoIncrementTemplate?: string | null;\n}\n\nexport interface ModelExportColumn {\n name?: string;\n type: string; // PRIMARY_KEY, FORMULA, ORDER, ACTIVE, DESCRIPTION, FOREIGN_KEY, NUMBER, TEXT, DATE, FILE\n foreignKeyTableName?: string;\n}\n\nexport interface ModelExportVariable {\n /** Numeric id used by `variableGids` filtering. Present on the\n * server-side `/model/export` response; absent in the initTagMap fallback. */\n gid?: number;\n name: string;\n description?: string | null;\n formula?: string | null;\n tables: string[];\n members: string[];\n rollupType: string; // SUM, AVERAGE, CLOSING STATE, BEGINNING STATE, FORMULA, MAX, MIN\n dataType: string; // DECIMAL, INTEGER\n numberFormat?: {\n type: string; // NUMBER, CURRENCY, PERCENTAGE, DATE, CUSTOM\n custom?: boolean;\n formatString?: string;\n decimals?: number;\n };\n numberValidation?: {\n min?: number | null;\n max?: number | null;\n };\n topDownMapping?: string | null;\n readonly: boolean;\n calculateOnDemand: boolean;\n zConstraint?: boolean;\n active?: boolean;\n optimizeCalculation?: boolean;\n useHierarchy?: boolean;\n folderPath?: string[];\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAiE;AACjE,mBAAkB;AAClB,cAAyB;AACzB,2BAAyC;AACzC,4BAAmC;AACnC,4BAAwB;AACxB,oBAAuB;AAuFhB,SAAS,eAAe,SAAoB,SAA6C;AAC5F,SAAO;AAAA,IACH,MAAM,QAAQ,QAAQ,QAAQ;AAAA,IAC9B,aAAa,QAAQ,eAAe,QAAQ,eAAe;AAAA,IAC3D,mBAAmB,QAAQ,qBAAqB,QAAQ,qBAAqB,CAAC;AAAA,IAC9E,kBAAkB,QAAQ,oBAAoB,QAAQ,oBAAoB;AAAA,IAC1E,gBAAgB,QAAQ,kBAAkB,QAAQ,kBAAkB;AAAA,IACpE,UAAU,QAAQ,YAAY,QAAQ,YAAY;AAAA,IAClD,YAAY,QAAQ,cAAc,QAAQ,cAAc;AAAA,IACxD,aAAa,QAAQ,eAAe,QAAQ,eAAe;AAAA,IAC3D,mBAAmB,QAAQ,qBAAqB,QAAQ,qBAAqB,CAAC;AAAA,EAClF;AACJ;AAU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AC3E,SAAO,EAAE,MAAM,SAAS,KAAK;AACjC;",
6
- "names": ["chalk", "item", "axios"]
7
- }
@@ -1,276 +0,0 @@
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 farseerFactory_exports = {};
30
- __export(farseerFactory_exports, {
31
- DEFAULT_SCRIPT_EXTENSIONS: () => DEFAULT_SCRIPT_EXTENSIONS,
32
- DEFAULT_SYNC_EXTENSIONS: () => DEFAULT_SYNC_EXTENSIONS,
33
- buildClient: () => buildClient,
34
- buildNativeClient: () => buildNativeClient,
35
- checkTenantAtOrganisation: () => checkTenantAtOrganisation,
36
- ensureFreshToken: () => ensureFreshToken,
37
- fetchOrganizationTenants: () => fetchOrganizationTenants,
38
- getAvailableAuth: () => getAvailableAuth,
39
- getFarseerClient: () => getFarseerClient,
40
- getFreshAccessToken: () => getFreshAccessToken,
41
- isAuthError: () => isAuthError,
42
- isTenantNotFoundError: () => isTenantNotFoundError,
43
- refreshAuth: () => refreshAuth,
44
- resolveAuth: () => resolveAuth,
45
- resolveAuthByProbe: () => resolveAuthByProbe,
46
- showLoginPrompt: () => showLoginPrompt
47
- });
48
- module.exports = __toCommonJS(farseerFactory_exports);
49
- var import_axios = __toESM(require("axios"));
50
- var farseer = __toESM(require("farseer-client"));
51
- var import_farseerService = require("./farseerService");
52
- var import_farseerApi = require("./farseerApi");
53
- var import_configService = require("./configService");
54
- var import_farseerService2 = require("./farseerService");
55
- var import_logger = require("../utils/logger");
56
- function isTenantNotFoundError(error) {
57
- return error instanceof Error && mentionsUnknownTenant(error.message);
58
- }
59
- function mentionsUnknownTenant(text) {
60
- if (!text) {
61
- return false;
62
- }
63
- const msg = text.toLowerCase();
64
- return msg.includes("does not exist") && msg.includes("tenant");
65
- }
66
- function isAuthError(error) {
67
- if (isTenantNotFoundError(error)) {
68
- return false;
69
- }
70
- if (error instanceof Error) {
71
- const msg = error.message.toLowerCase();
72
- return msg.includes("401") || msg.includes("403") || msg.includes("unauthorized") || msg.includes("forbidden");
73
- }
74
- return false;
75
- }
76
- function showLoginPrompt(tenant) {
77
- import_logger.logger.error("Authentication required.");
78
- if (tenant) {
79
- import_logger.logger.dim(`No valid credentials found for tenant "${tenant}".`);
80
- }
81
- import_logger.logger.info('Run "farseer login" to authenticate via browser.');
82
- import_logger.logger.dim('Or use "farseer config set <tenant> --api-key <key>" for API key auth.');
83
- }
84
- const DEFAULT_SCRIPT_EXTENSIONS = [".ts", ".js"];
85
- const DEFAULT_SYNC_EXTENSIONS = [
86
- // Code (frontend / scripts)
87
- ".ts",
88
- ".js",
89
- // Code (Python)
90
- ".py",
91
- // Config / data
92
- ".yml",
93
- ".yaml",
94
- ".json",
95
- // Docs
96
- ".md"
97
- ];
98
- async function getFreshAccessToken() {
99
- const auth = (0, import_configService.getUserAuth)();
100
- if (!auth) {
101
- return null;
102
- }
103
- if ((0, import_configService.isUserAuthValid)()) {
104
- return auth.accessToken;
105
- }
106
- import_logger.logger.dim("Token expired, refreshing...");
107
- const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
108
- if (!refreshed) {
109
- return null;
110
- }
111
- (0, import_configService.setUserAuth)({
112
- accessToken: refreshed.accessToken,
113
- refreshToken: refreshed.refreshToken,
114
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
115
- realm: auth.realm
116
- });
117
- import_logger.logger.dim("Token refreshed");
118
- return refreshed.accessToken;
119
- }
120
- async function checkTenantAtOrganisation(organisation, tenant, accessToken) {
121
- try {
122
- await import_axios.default.get(`${(0, import_configService.generateBasePath)(organisation)}/organization`, {
123
- headers: { Authorization: `Bearer ${accessToken}`, "X-TENANT-ID": tenant },
124
- timeout: 3e4
125
- });
126
- return { status: "ok" };
127
- } catch (error) {
128
- if (import_axios.default.isAxiosError(error)) {
129
- if (error.response?.status === 401) {
130
- return { status: "unauthorized" };
131
- }
132
- if (error.response?.status === 404) {
133
- return { status: "no-such-org" };
134
- }
135
- const body = error.response?.data;
136
- const detail = typeof body === "string" ? body : body?.message;
137
- if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {
138
- return { status: "tenant-unknown" };
139
- }
140
- }
141
- return { status: "unreachable", message: error instanceof Error ? error.message : String(error) };
142
- }
143
- }
144
- async function fetchOrganizationTenants(organisation, accessToken) {
145
- try {
146
- const response = await import_axios.default.get(`${(0, import_configService.generateBasePath)(organisation)}/organization`, {
147
- headers: { Authorization: `Bearer ${accessToken}` },
148
- timeout: 3e4
149
- });
150
- return (response.data.tenants ?? []).map((t) => t.name);
151
- } catch {
152
- return [];
153
- }
154
- }
155
- function jwtAuth(accessToken, organisation, tenant) {
156
- return { kind: "jwt", accessToken, basePath: (0, import_configService.generateBasePath)(organisation), tenant };
157
- }
158
- function buildClient(auth) {
159
- return auth.kind === "jwt" ? new import_farseerApi.FarseerApi(auth.accessToken, auth.basePath, auth.tenant) : new import_farseerService.FarseerService(auth.credential);
160
- }
161
- function buildNativeClient(auth) {
162
- if (auth.kind === "jwt") {
163
- return new farseer.FarseerClient({
164
- basePath: auth.basePath,
165
- headers: { "X-TENANT-ID": auth.tenant, Authorization: `Bearer ${auth.accessToken}` }
166
- });
167
- }
168
- return new farseer.FarseerClient({
169
- basePath: auth.credential.basePath,
170
- headers: { "X-TENANT-ID": auth.credential.tenantId, "X-API-KEY": auth.credential.apiKey }
171
- });
172
- }
173
- async function resolveAuth(organisation, tenant) {
174
- const accessToken = await getFreshAccessToken();
175
- if (accessToken) {
176
- return jwtAuth(accessToken, organisation, tenant);
177
- }
178
- const credential = (0, import_configService.getCredential)(tenant);
179
- return credential ? { kind: "apiKey", credential } : null;
180
- }
181
- async function resolveAuthByProbe(organisation, tenant) {
182
- const accessToken = await getFreshAccessToken();
183
- if (accessToken) {
184
- const auth = jwtAuth(accessToken, organisation, tenant);
185
- if (await connects(auth)) {
186
- return auth;
187
- }
188
- import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
189
- }
190
- const credential = (0, import_configService.getCredential)(tenant);
191
- if (credential) {
192
- const auth = { kind: "apiKey", credential };
193
- if (await connects(auth)) {
194
- return auth;
195
- }
196
- import_logger.logger.dim("API key auth failed.");
197
- }
198
- return null;
199
- }
200
- async function refreshAuth(auth) {
201
- if (auth.kind === "apiKey") {
202
- return auth;
203
- }
204
- const accessToken = await getFreshAccessToken();
205
- return accessToken ? { ...auth, accessToken } : null;
206
- }
207
- async function connects(auth) {
208
- try {
209
- return await buildClient(auth).testConnection();
210
- } catch {
211
- return false;
212
- }
213
- }
214
- async function getFarseerClient(organisation, tenant) {
215
- const auth = await resolveAuth(organisation, tenant);
216
- return auth ? { client: buildClient(auth), authType: auth.kind } : null;
217
- }
218
- function getAvailableAuth(tenant) {
219
- const credential = (0, import_configService.getCredential)(tenant);
220
- const auth = (0, import_configService.getUserAuth)();
221
- return {
222
- hasApiKey: !!credential,
223
- hasJwt: !!auth,
224
- jwtValid: (0, import_configService.isUserAuthValid)()
225
- };
226
- }
227
- async function ensureFreshToken(client) {
228
- const auth = (0, import_configService.getUserAuth)();
229
- if (!auth) {
230
- return false;
231
- }
232
- const expiresAt = new Date(auth.expiresAt);
233
- const now = /* @__PURE__ */ new Date();
234
- const bufferMs = 30 * 1e3;
235
- if (expiresAt.getTime() - now.getTime() > bufferMs) {
236
- return false;
237
- }
238
- import_logger.logger.dim("Refreshing token before operation...");
239
- const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
240
- if (!refreshed) {
241
- import_logger.logger.warning("Could not refresh token.");
242
- return false;
243
- }
244
- (0, import_configService.setUserAuth)({
245
- accessToken: refreshed.accessToken,
246
- refreshToken: refreshed.refreshToken,
247
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
248
- realm: auth.realm
249
- });
250
- if (client.updateAccessToken) {
251
- client.updateAccessToken(refreshed.accessToken);
252
- import_logger.logger.dim("Token refreshed");
253
- return true;
254
- }
255
- return false;
256
- }
257
- // Annotate the CommonJS export names for ESM import in node:
258
- 0 && (module.exports = {
259
- DEFAULT_SCRIPT_EXTENSIONS,
260
- DEFAULT_SYNC_EXTENSIONS,
261
- buildClient,
262
- buildNativeClient,
263
- checkTenantAtOrganisation,
264
- ensureFreshToken,
265
- fetchOrganizationTenants,
266
- getAvailableAuth,
267
- getFarseerClient,
268
- getFreshAccessToken,
269
- isAuthError,
270
- isTenantNotFoundError,
271
- refreshAuth,
272
- resolveAuth,
273
- resolveAuthByProbe,
274
- showLoginPrompt
275
- });
276
- //# sourceMappingURL=farseerFactory.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/services/farseerFactory.ts"],
4
- "sourcesContent": ["/**\n * Deciding which credential to use, and building clients from it.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and every client is\n * built from that.\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport type { ApiKeyCredential } from './configService';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\n */\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(remoteJobId: string): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n// Decided once and handed to the builders, so the credential the guard\n// validated is the one the command runs on.\nexport type ResolvedAuth =\n | { kind: 'jwt'; accessToken: string; basePath: string; tenant: string }\n | { kind: 'apiKey'; credential: ApiKeyCredential };\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant };\n}\n\n/**\n * The curated CLI-level view \u2014 file sync, apps, model export.\n *\n * TECH DEBT \u2014 two client shapes over the same credential. This one returns an\n * `IFarseerClient` (a facade over the hand-rolled axios `FarseerApi` for JWT and\n * the SDK-wrapping `FarseerService` for API keys) while `buildNativeClient`\n * returns the raw SDK client for the richer read/query surface. The split is\n * historical \u2014 the JWT path was hand-rolled instead of using the SDK, which the\n * SDK handles fine \u2014 and collapsing the two into one class is a follow-up. They\n * can no longer disagree about *which* credential they carry, which was the part\n * that mattered.\n */\nexport function buildClient(auth: ResolvedAuth): IFarseerClient {\n return auth.kind === 'jwt'\n ? new FarseerApi(auth.accessToken, auth.basePath, auth.tenant)\n : new FarseerService(auth.credential);\n}\n\n/** The full SDK surface, for the read/query commands. Constructs only \u2014 no request. */\nexport function buildNativeClient(auth: ResolvedAuth): farseer.FarseerClient {\n if (auth.kind === 'jwt') {\n return new farseer.FarseerClient({\n basePath: auth.basePath,\n headers: { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` },\n });\n }\n return new farseer.FarseerClient({\n basePath: auth.credential.basePath,\n headers: { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey },\n });\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken();\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n try {\n return await buildClient(auth).testConnection();\n } catch {\n return false;\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n const auth = await resolveAuth(organisation, tenant);\n return auth ? { client: buildClient(auth), authType: auth.kind } : null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,mBAAkB;AAClB,cAAyB;AACzB,4BAA+B;AAC/B,wBAA2B;AAE3B,2BAA2F;AAC3F,IAAAA,yBAAmC;AACnC,oBAAuB;AAWhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAQA,SAAS,sBAAsB,MAAmC;AAC9D,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AASO,SAAS,YAAY,OAAyB;AACj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