farseer-cli 1.10.1 → 1.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/commands/cells.js +2 -4
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/dashboards.js +2 -4
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -6
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/formula.js +1 -2
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/sheets.js +4 -8
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +3 -6
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/tools/appTools.js +27 -57
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +12 -9
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +4 -6
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +34 -56
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +13 -37
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +7 -11
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +59 -111
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +5 -11
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +31 -51
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +27 -57
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +22 -7
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/mcp/utils/session.js +97 -0
- package/dist/mcp/utils/session.js.map +7 -0
- package/dist/mcp/utils/tenantPin.js.map +2 -2
- package/dist/services/farseerApi.js +7 -5
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/farseerFactory.js +66 -116
- package/dist/services/farseerFactory.js.map +2 -2
- package/dist/services/preflight.js +78 -24
- package/dist/services/preflight.js.map +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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 { getCredential, 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 creationType: string;\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 tenant: string;\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 constructor(accessToken: string, tenant: string, tenantId?: string) {\n this.tenant = tenant;\n this.tenantId = tenantId || tenant;\n this.accessToken = accessToken;\n\n // Try to get basePath from existing config, or generate from tenant name\n const credential = getCredential(tenant);\n const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;\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,2BAAwD;AACxD,4BAAmC;AACnC,4BAAwB;AACxB,oBAAuB;AAwFhB,SAAS,eAAe,SAAoB,SAA6C;AAC5F,SAAO;AAAA,IACH,MAAM,QAAQ,QAAQ,QAAQ;AAAA,IAC9B,aAAa,QAAQ,eAAe,QAAQ,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ACA,OAAO,CAAC,QAAQ,WAAW,cAAc;AAAA,IACzC,OAAO;AAAA,EACX,CAAC;AACD,MAAI,aAAa,SAAS,GAAG;AACzB,WAAO;AAAA,EACX;AAKA,QAAM,SAAS,MAAM,aAAa,KAAK,0BAA0B,IAAI;AACrE,QAAM,UAAU,OAAO,MAAM,QAAQ;AACrC,QAAM,UAAU,OAAO,SAAS,IAAI,CAAC,OAAO;AAAA,IACxC,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,qBAAsB,EAAuC;AAAA,EACjE,EAAE;AACF,QAAM,OAAO,QAAQ,IAAI,CAAC,QAAQ,QAAQ,IAAI,CAAC,QAAQ,IAAI,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC3E,SAAO,EAAE,MAAM,SAAS,KAAK;AACjC;",
|
|
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;AA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A,WAAO,EAAE,QAAQ,WAAW,cAAc,EAAE,QAAQ,CAAC,GAAG,SAAS,CAAC,GAAG,WAAW,CAAC,EAAE,EAAE;AAAA,EACzF;AACJ;AAeA,eAAsB,iCAClB,cACA,MACgC;AAChC,QAAM,eAAe,MAAM,aAAa,SAAS,OAAO;AAAA,IACpD;AAAA,IACA,OAAO,CAAC,QAAQ,WAAW,cAAc;AAAA,IACzC,OAAO;AAAA,EACX,CAAC;AACD,MAAI,aAAa,SAAS,GAAG;AACzB,WAAO;AAAA,EACX;AAKA,QAAM,SAAS,MAAM,aAAa,KAAK,0BAA0B,IAAI;AACrE,QAAM,UAAU,OAAO,MAAM,QAAQ;AACrC,QAAM,UAAU,OAAO,SAAS,IAAI,CAAC,OAAO;AAAA,IACxC,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,qBAAsB,EAAuC;AAAA,EACjE,EAAE;AACF,QAAM,OAAO,QAAQ,IAAI,CAAC,QAAQ,QAAQ,IAAI,CAAC,QAAQ,IAAI,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC3E,SAAO,EAAE,MAAM,SAAS,KAAK;AACjC;",
|
|
6
6
|
"names": ["chalk", "item", "axios"]
|
|
7
7
|
}
|
|
@@ -30,16 +30,19 @@ var farseerFactory_exports = {};
|
|
|
30
30
|
__export(farseerFactory_exports, {
|
|
31
31
|
DEFAULT_SCRIPT_EXTENSIONS: () => DEFAULT_SCRIPT_EXTENSIONS,
|
|
32
32
|
DEFAULT_SYNC_EXTENSIONS: () => DEFAULT_SYNC_EXTENSIONS,
|
|
33
|
+
buildClient: () => buildClient,
|
|
34
|
+
buildNativeClient: () => buildNativeClient,
|
|
33
35
|
checkTenantAtOrganisation: () => checkTenantAtOrganisation,
|
|
34
36
|
ensureFreshToken: () => ensureFreshToken,
|
|
35
37
|
fetchOrganizationTenants: () => fetchOrganizationTenants,
|
|
36
38
|
getAvailableAuth: () => getAvailableAuth,
|
|
37
39
|
getFarseerClient: () => getFarseerClient,
|
|
38
|
-
getFarseerClientWithFallback: () => getFarseerClientWithFallback,
|
|
39
40
|
getFreshAccessToken: () => getFreshAccessToken,
|
|
40
|
-
getNativeFarseerClient: () => getNativeFarseerClient,
|
|
41
41
|
isAuthError: () => isAuthError,
|
|
42
42
|
isTenantNotFoundError: () => isTenantNotFoundError,
|
|
43
|
+
refreshAuth: () => refreshAuth,
|
|
44
|
+
resolveAuth: () => resolveAuth,
|
|
45
|
+
resolveAuthByProbe: () => resolveAuthByProbe,
|
|
43
46
|
showLoginPrompt: () => showLoginPrompt
|
|
44
47
|
});
|
|
45
48
|
module.exports = __toCommonJS(farseerFactory_exports);
|
|
@@ -149,42 +152,69 @@ async function fetchOrganizationTenants(organisation, accessToken) {
|
|
|
149
152
|
return [];
|
|
150
153
|
}
|
|
151
154
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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;
|
|
177
187
|
}
|
|
188
|
+
import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
|
|
178
189
|
}
|
|
179
190
|
const credential = (0, import_configService.getCredential)(tenant);
|
|
180
191
|
if (credential) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
192
|
+
const auth = { kind: "apiKey", credential };
|
|
193
|
+
if (await connects(auth)) {
|
|
194
|
+
return auth;
|
|
195
|
+
}
|
|
196
|
+
import_logger.logger.dim("API key auth failed.");
|
|
185
197
|
}
|
|
186
198
|
return null;
|
|
187
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
|
+
}
|
|
188
218
|
function getAvailableAuth(tenant) {
|
|
189
219
|
const credential = (0, import_configService.getCredential)(tenant);
|
|
190
220
|
const auth = (0, import_configService.getUserAuth)();
|
|
@@ -194,50 +224,6 @@ function getAvailableAuth(tenant) {
|
|
|
194
224
|
jwtValid: (0, import_configService.isUserAuthValid)()
|
|
195
225
|
};
|
|
196
226
|
}
|
|
197
|
-
async function getFarseerClientWithFallback(organisation, tenant) {
|
|
198
|
-
const auth = (0, import_configService.getUserAuth)();
|
|
199
|
-
const credential = (0, import_configService.getCredential)(tenant);
|
|
200
|
-
if (auth) {
|
|
201
|
-
let accessToken = auth.accessToken;
|
|
202
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
203
|
-
import_logger.logger.dim("Token expired, refreshing...");
|
|
204
|
-
const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
205
|
-
if (refreshed) {
|
|
206
|
-
(0, import_configService.setUserAuth)({
|
|
207
|
-
accessToken: refreshed.accessToken,
|
|
208
|
-
refreshToken: refreshed.refreshToken,
|
|
209
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
210
|
-
realm: auth.realm
|
|
211
|
-
});
|
|
212
|
-
accessToken = refreshed.accessToken;
|
|
213
|
-
import_logger.logger.dim("Token refreshed");
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if ((0, import_configService.isUserAuthValid)()) {
|
|
217
|
-
const jwtClient = new import_farseerApi.FarseerApi(accessToken, organisation, tenant);
|
|
218
|
-
try {
|
|
219
|
-
const connected = await jwtClient.testConnection();
|
|
220
|
-
if (connected) {
|
|
221
|
-
return { client: jwtClient, authType: "jwt" };
|
|
222
|
-
}
|
|
223
|
-
} catch (error) {
|
|
224
|
-
import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
if (credential) {
|
|
229
|
-
const apiKeyClient = new import_farseerService.FarseerService(credential);
|
|
230
|
-
try {
|
|
231
|
-
const connected = await apiKeyClient.testConnection();
|
|
232
|
-
if (connected) {
|
|
233
|
-
return { client: apiKeyClient, authType: "apiKey" };
|
|
234
|
-
}
|
|
235
|
-
} catch {
|
|
236
|
-
import_logger.logger.dim("API key auth failed.");
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return null;
|
|
240
|
-
}
|
|
241
227
|
async function ensureFreshToken(client) {
|
|
242
228
|
const auth = (0, import_configService.getUserAuth)();
|
|
243
229
|
if (!auth) {
|
|
@@ -268,59 +254,23 @@ async function ensureFreshToken(client) {
|
|
|
268
254
|
}
|
|
269
255
|
return false;
|
|
270
256
|
}
|
|
271
|
-
async function getNativeFarseerClient(organisation, tenant) {
|
|
272
|
-
const basePath = (0, import_configService.generateBasePath)(organisation);
|
|
273
|
-
const auth = (0, import_configService.getUserAuth)();
|
|
274
|
-
if (auth) {
|
|
275
|
-
let accessToken = auth.accessToken;
|
|
276
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
277
|
-
const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
278
|
-
if (refreshed) {
|
|
279
|
-
(0, import_configService.setUserAuth)({
|
|
280
|
-
accessToken: refreshed.accessToken,
|
|
281
|
-
refreshToken: refreshed.refreshToken,
|
|
282
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
283
|
-
realm: auth.realm
|
|
284
|
-
});
|
|
285
|
-
accessToken = refreshed.accessToken;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if ((0, import_configService.isUserAuthValid)()) {
|
|
289
|
-
return new farseer.FarseerClient({
|
|
290
|
-
basePath,
|
|
291
|
-
headers: {
|
|
292
|
-
"X-TENANT-ID": tenant,
|
|
293
|
-
Authorization: `Bearer ${accessToken}`
|
|
294
|
-
}
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
const credential = (0, import_configService.getCredential)(tenant);
|
|
299
|
-
if (credential) {
|
|
300
|
-
return new farseer.FarseerClient({
|
|
301
|
-
basePath: credential.basePath,
|
|
302
|
-
headers: {
|
|
303
|
-
"X-TENANT-ID": credential.tenantId,
|
|
304
|
-
"X-API-KEY": credential.apiKey
|
|
305
|
-
}
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
return null;
|
|
309
|
-
}
|
|
310
257
|
// Annotate the CommonJS export names for ESM import in node:
|
|
311
258
|
0 && (module.exports = {
|
|
312
259
|
DEFAULT_SCRIPT_EXTENSIONS,
|
|
313
260
|
DEFAULT_SYNC_EXTENSIONS,
|
|
261
|
+
buildClient,
|
|
262
|
+
buildNativeClient,
|
|
314
263
|
checkTenantAtOrganisation,
|
|
315
264
|
ensureFreshToken,
|
|
316
265
|
fetchOrganizationTenants,
|
|
317
266
|
getAvailableAuth,
|
|
318
267
|
getFarseerClient,
|
|
319
|
-
getFarseerClientWithFallback,
|
|
320
268
|
getFreshAccessToken,
|
|
321
|
-
getNativeFarseerClient,
|
|
322
269
|
isAuthError,
|
|
323
270
|
isTenantNotFoundError,
|
|
271
|
+
refreshAuth,
|
|
272
|
+
resolveAuth,
|
|
273
|
+
resolveAuthByProbe,
|
|
324
274
|
showLoginPrompt
|
|
325
275
|
});
|
|
326
276
|
//# sourceMappingURL=farseerFactory.js.map
|