farseer-cli 1.11.1 → 1.12.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 (36) hide show
  1. package/README.md +60 -0
  2. package/dist/commands/app.js +56 -6
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/dashboards.js +16 -2
  5. package/dist/commands/dashboards.js.map +2 -2
  6. package/dist/commands/sheets.js +46 -34
  7. package/dist/commands/sheets.js.map +2 -2
  8. package/dist/commands/variables.js +7 -1
  9. package/dist/commands/variables.js.map +2 -2
  10. package/dist/mcp/prompts/workflows.js +2 -0
  11. package/dist/mcp/prompts/workflows.js.map +2 -2
  12. package/dist/mcp/tools/appTools.js +56 -6
  13. package/dist/mcp/tools/appTools.js.map +2 -2
  14. package/dist/mcp/tools/dashboardTools.js +79 -69
  15. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  16. package/dist/mcp/tools/sheetTools.js +48 -59
  17. package/dist/mcp/tools/sheetTools.js.map +2 -2
  18. package/dist/mcp/utils/helpers.js +39 -5
  19. package/dist/mcp/utils/helpers.js.map +2 -2
  20. package/dist/services/appSyncService.js +33 -1
  21. package/dist/services/appSyncService.js.map +2 -2
  22. package/dist/services/apps.js +199 -9
  23. package/dist/services/apps.js.map +3 -3
  24. package/dist/services/farseerService.js +11 -0
  25. package/dist/services/farseerService.js.map +2 -2
  26. package/dist/services/modelExport.js +4 -2
  27. package/dist/services/modelExport.js.map +2 -2
  28. package/dist/utils/entityResolver.js +114 -28
  29. package/dist/utils/entityResolver.js.map +2 -2
  30. package/dist/utils/helpers.js +5 -5
  31. package/dist/utils/helpers.js.map +2 -2
  32. package/dist/utils/{appResolver.js → nameResolver.js} +23 -23
  33. package/dist/utils/nameResolver.js.map +7 -0
  34. package/docs/cli-guide.md +16 -0
  35. package/package.json +1 -1
  36. package/dist/utils/appResolver.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/farseerService.ts"],
4
- "sourcesContent": ["import * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { getUserAuth, setUserAuth, isUserAuthValid } from './configService';\nimport type { ApiKeyCredential } from './configService';\nimport {\n AppListItem,\n AppUpdateChanges,\n REMOTE_JOB_ITEM_TYPE,\n RemoteApp,\n ResolvedFolderItem,\n SourceFolderResolution,\n mergeAppUpdate,\n remoteJobReverseReferences,\n resolveAppItemNodeId,\n} from './apps';\nimport {\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n ModelExportVariable,\n loadDimensionTableViaEntitiesApi,\n} from './modelExport';\nimport { toError } from '../utils/errorFormatter';\nimport { matchFolderSegment } from '../utils/folderMatch';\nimport { HttpError } from './httpError';\nimport { mentionsUnknownTenant } from './authErrors';\nimport { logger } from '../utils/logger';\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\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// 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 * Why a credential probe failed. Four reasons rather than two because the advice\n * differs for each: a rejected credential means replace it, an unknown tenant\n * means the organisation is wrong and the credential is fine, a server error\n * means the host answered and nothing is wrong locally, and unreachable means\n * nothing answered at all.\n */\nexport type ConnectionFailure = 'rejected' | 'tenant-unknown' | 'server-error' | 'unreachable';\n\nexport type ConnectionCheck = { ok: true } | { ok: false; reason: ConnectionFailure; message: string };\n\nexport interface FolderItem {\n id: number;\n name: string;\n type: string;\n reference?: string;\n}\n\n/** Where a credential's requests go, and who they say they are. */\nexport function basePathOf(auth: ResolvedAuth): string {\n return auth.kind === 'jwt' ? auth.basePath : auth.credential.basePath;\n}\n\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n return auth.kind === 'jwt'\n ? { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey };\n}\n\n/**\n * Which of the four failures a thrown probe error is. A 403 is read two ways:\n * the backend answers it both for a credential it will not accept and for a\n * tenant the organisation does not have, and only the body tells them apart.\n */\nfunction failureReason(error: unknown): ConnectionFailure {\n if (!(error instanceof HttpError)) {\n return 'unreachable';\n }\n if (error.status === 403 && mentionsUnknownTenant(error.message)) {\n return 'tenant-unknown';\n }\n if (error.status === 401 || error.status === 403) {\n return 'rejected';\n }\n return 'server-error';\n}\n\n/**\n * Re-stamp the Authorization header on every request from a browser login.\n *\n * The SDK's `accessToken` option is inert here \u2014 the spec declares no bearer\n * scheme, so the generator emitted nothing that reads it \u2014 so the token goes in\n * as a plain header, and a header fixed at construction goes stale.\n */\nfunction freshTokenMiddleware(): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n // Nothing to mint; let it go out as built and fail on its own terms.\n return { url, init };\n }\n return {\n url,\n init: { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } },\n };\n },\n };\n}\n\n/**\n * The CLI's client, over the SDK. The credential is decided upstream (see\n * ResolvedAuth) and only changes the headers.\n */\nexport class FarseerService {\n private client: farseer.FarseerClient;\n private auth: ResolvedAuth;\n\n constructor(auth: ResolvedAuth) {\n this.auth = auth;\n this.client = new farseer.FarseerClient({\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware()] : [],\n });\n }\n\n /**\n * The SDK client underneath, for the read/query surface that wants it raw.\n *\n * The same instance this class uses, deliberately: a second one would derive\n * the host and headers a second time, and the SDK caches its tag map per\n * instance, so two of them pay for it twice.\n */\n get native(): farseer.FarseerClient {\n return this.client;\n }\n\n /**\n * Is this credential good? Asked of `/organization`, which answers it\n * directly \u2014 401 for a credential the server rejects, 200 otherwise, the\n * same for both kinds. Nothing about the tenant's folders can make a valid\n * credential look invalid.\n *\n * The ways it can fail are not interchangeable: \"log in again\" is useless\n * advice for a dropped connection, and \"your key was rejected\" is worse than\n * useless for a key that works at an organisation without this tenant.\n */\n async checkConnection(): Promise<ConnectionCheck> {\n try {\n await this.getOrganizationInfo();\n return { ok: true };\n } catch (error) {\n return {\n ok: false,\n reason: failureReason(error),\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n return this.apiRequest<OrganizationInfo>('/organization', 'GET');\n }\n\n async getFilesFolder(): Promise<FolderItem | null> {\n return this.findFolder(['Files']);\n }\n\n /**\n * The folder at `folderPath`, for callers that need its id. Exposed because\n * the SDK's own getItemByPath is not a path lookup \u2014 see findFolder.\n */\n async getFolderByPath(folderPath: string[]): Promise<FolderItem | null> {\n return this.findFolder(folderPath);\n }\n\n /**\n * Every failure throws. An empty list is a claim rather than a shrug:\n * SyncService.checkRemoteChanges derives what was deleted on the server by\n * subtracting this listing from sync state, so `[]` says the tenant was\n * emptied and a mirroring pull acts on it.\n */\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const folder = await this.requireFolderForListing(folderPath);\n return this.listFilesUnder(folder.id, folderPath);\n }\n\n /**\n * Resolving the root of the walk is the only part that needs a path. Every\n * level below it recurses on the id already present in its parent's\n * listing \u2014 walking the path again per subfolder turned a four-deep tree\n * into fourteen requests where five do.\n */\n private async listFilesUnder(folderId: number, folderPath: string[]): Promise<RemoteFile[]> {\n let items: farseer.FolderItemRepresentation[];\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: folderId }]);\n items = folderContent[0]?.items ?? [];\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n const files: RemoteFile[] = [];\n\n // Recursion sits outside the read so a failure deeper in the tree keeps\n // its own folder in the message instead of being re-wrapped at each level.\n for (const item of items) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n\n if (item.type === farseer.FolderItemType.Folder) {\n const subFiles = await this.listFilesUnder(item.id, [...folderPath, item.name]);\n files.push(...subFiles);\n } else if (item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference as string,\n });\n }\n }\n\n return files;\n }\n\n /** The listing root, with the path kept in the message on failure. */\n private async requireFolderForListing(folderPath: string[]): Promise<FolderItem> {\n try {\n return await this.requireFolder(folderPath);\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n }\n\n async getFileContent(reference: string): Promise<string> {\n const blob = await this.client.farseerFiles.get(reference);\n return await blob.text();\n }\n\n /**\n * Build a WebFile with an explicit Content-Type.\n *\n * When a File-like object is appended to FormData with no `type`, undici\n * (Node's fetch backend) auto-detects MIME from the filename \u2014 `.ts`\n * resolves to `video/mp2t` (MPEG transport stream), a part-level\n * Content-Type that some WAFs and proxies reject. Setting `type` on the\n * outer WebFile is what actually changes the wire bytes; setting it on\n * an inner Blob does NOT propagate to the wrapping WebFile and is a\n * no-op for the eventual multipart serialization.\n */\n private toUploadFile(content: string | Buffer, fileName: string): farseer.WebFile {\n const parts = [content] as BlobPart[];\n return new farseer.WebFile(parts, fileName, { type: 'application/octet-stream' });\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n // Ensure folder structure exists\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.requireFolder(folderPath);\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.create(file, 'GENERAL', folder.id.toString());\n } catch (error) {\n // toError preserves the original Response (or Error) as `cause` so\n // fileLogger.serializeError can capture status/url/body into the\n // JSON log \u2014 useful for diagnosing backend 4xx/5xx after the fact.\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 file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.update(reference, file);\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.farseerFiles.remove(reference);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n if (!(await this.findFolder(currentPath))) {\n // Folder doesn't exist, create it.\n //\n // `allowedTypes: null` is critical \u2014 DO NOT pass `[]`.\n // Backend semantics (itemNodeService.ts:657-708):\n // \u2022 null \u2192 inherit parent's allowedTypes (Files root is\n // ['FARSEER_FILE', 'FOLDER'], which is what we want).\n // \u2022 [] \u2192 \"nothing allowed\". Subsequent createFile in\n // the new folder fails with HTTP 400 \"Invalid parent \u2014\n // item type 'FARSEER_FILE' is not allowed in this\n // folder (allowed types: )\".\n //\n // The web UI sends `null`, which is why folders created via\n // UI always work. The CLI used to send `[]`, producing a\n // dead-end folder that couldn't host any files. Reproduced\n // on 2026-04-29 against fs-personal/ivan-kikic.\n if (currentPath.length > 1) {\n const parent = await this.requireFolder(currentPath.slice(0, -1));\n await this.client.folders.create({\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n /**\n * The file at `filePath`, or null when there isn't one.\n *\n * Absence is a legitimate answer here \u2014 the path is user-supplied \u2014 but a\n * failed request is not: the one consumer is SyncService.getFileDiff, which\n * would read it as the file having no remote content. `findFolder` keeps the\n * two apart.\n */\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n\n const folder = await this.findFolder(pathParts);\n if (!folder) {\n return null;\n }\n\n const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);\n const match = (folderContent[0]?.items ?? []).find(\n (item) => item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && 'reference' in item,\n );\n\n return match ? { name: match.name, path: filePath, reference: match.reference as string } : null;\n }\n\n /**\n * The folder at `folderPath`, or null when a segment of it isn't there. Only\n * absence returns null; a failed listing throws.\n *\n * Not the SDK's `getItemByPath`: for a single-segment path it ignores the\n * path entirely and name-searches the whole tenant across folders,\n * dashboards, sheets, dimension tables and variables, capped at 20 results.\n * The match itself is exact, so a near-miss name is harmless \u2014 but a second\n * item named exactly `Files` anywhere in the tenant makes it refuse, and 20\n * prefix matches crowd the real folder off the only page it looks at. A path\n * is a path, so each segment is matched inside its parent's listing.\n */\n private async findFolder(folderPath: string[]): Promise<FolderItem | null> {\n let parentId: number | null = null;\n let found: FolderItem | null = null;\n\n for (const segment of folderPath) {\n const contents = await this.client.folders.listItemsBatch([{ id: parentId }]);\n const folders = (contents[0]?.items ?? []).filter((item) => item.type === farseer.FolderItemType.Folder);\n const match = matchFolderSegment(folders, segment);\n if (!match) {\n return null;\n }\n found = { id: match.id, name: match.name, type: match.type };\n parentId = match.id;\n }\n\n return found;\n }\n\n /** Same walk, for callers that can only proceed if the folder is there. */\n private async requireFolder(folderPath: string[]): Promise<FolderItem> {\n const folder = await this.findFolder(folderPath);\n if (!folder) {\n throw new Error(`Folder not found: ${folderPath.join('/')}`);\n }\n return folder;\n }\n\n async getFileMetadata(reference: string): Promise<FileMetadata | null> {\n try {\n const metadata = await this.client.farseerFiles.getMetadata(reference);\n\n return {\n uploadTime: metadata.uploadTime?.toISOString(),\n uploader: metadata.uploader\n ? {\n id: metadata.uploader.id,\n email: metadata.uploader.email || '',\n firstName: metadata.uploader.firstName || '',\n lastName: metadata.uploader.lastName || '',\n }\n : undefined,\n size: metadata.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const blob = await this.client.farseerFiles.get(reference);\n const arrayBuffer = await blob.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * List all apps (Remote Jobs) on the tenant\n */\n async listApps(): Promise<AppListItem[]> {\n const response = await this.client.remoteJobs.list();\n return response.map((app) => ({\n name: app.name,\n type: REMOTE_JOB_ITEM_TYPE,\n reference: String(app.id),\n }));\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const app = await this.apiRequest<RemoteApp>(`/remoteJobs/${referenceId}`, 'GET');\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if (app && (!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch (error) {\n // A 404 means the app is gone, which is an answer. Anything else\n // means we could not ask \u2014 and AppSyncService drops an app it cannot\n // see, so reporting that as absence quietly changes what syncs.\n if (error instanceof HttpError && error.status === 404) {\n return null;\n }\n throw await toError(error, `Failed to load app ${referenceId}`);\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<{ id: string; name: string }[]> {\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: sourceFolderId }]);\n return (folderContent[0]?.items || [])\n .filter((item) => item.type === farseer.FolderItemType.FarseerFile && 'reference' in item)\n .map((item) => ({ id: item.reference as string, name: item.name }));\n } catch (error) {\n // Gone (404) is an answer about the folder; nothing else is. A 403\n // is deliberately NOT swallowed: the backend also returns it when\n // the caller lacks the tenant-wide GET_ITEMS_BATCH permission, which\n // says nothing about this folder, and \"I may not look\" is not \"there\n // are no scripts\" either way. The empty list reaches AppSyncService\n // as `entrypoint: null` and pull saves that over the local app, so\n // guessing here silently rewrites the user's config. The SDK throws\n // the raw Response, so the status is read off the thrown value.\n const status = (error as { status?: unknown } | null)?.status;\n if (status === 404) {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Null means the folder is not there. A failed request throws, so a caller\n * reporting \"no such folder\" cannot say it about a 500 or a dropped\n * connection.\n */\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.findFolder(['Files', ...segments]);\n if (!folder) {\n return null;\n }\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n // Get Apps folder ID first\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n return await this.apiRequest<RemoteApp>('/remoteJobs', 'POST', {\n folderId: appsFolderId,\n name,\n });\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.apiRequest(`/remoteJobs/${referenceId}`, 'PUT', 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 // Never swallow a failure into an empty array: `resolveAppItemNodeId` reads\n // \"no match\" as \"this app doesn't exist\".\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n try {\n return await this.client.folders.resolveItems(remoteJobReverseReferences(remoteJobIds));\n } catch (error) {\n throw await toError(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(', ')}`);\n }\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 try {\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);\n } catch (error) {\n throw await toError(error, `Failed to delete app (Remote Job id: ${remoteJobId})`);\n }\n }\n\n /**\n * Get script files available for apps\n */\n async getScriptFiles(): Promise<{ id: string; name: string }[]> {\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, // Full path, not the file name: scripts live in subfolders.\n }));\n }\n\n /**\n * Export the entire model structure.\n * Tries the generated API first, falls back to initTagMap() for older server versions.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Default scope: tables + variables, no member rows. Pulling\n // the full member matrix is what makes the call hang on\n // larger tenants \u2014 once the response crosses the Cloud Run /\n // proxy limit the connection drops mid-flight and the client\n // sees \"socket hang up\". Callers that actually need members\n // pass { types: ['DTAB','DMEM'], tableGids: [...] }.\n const requestedTypes = options.types ?? ['DTAB', 'VAR'];\n const apiTypes = requestedTypes\n .map((t) => {\n if (t === 'DTAB') return farseer.ModelObjectType.DIMENSION_TABLE;\n if (t === 'DMEM') return farseer.ModelObjectType.DIMENSION_MEMBER;\n if (t === 'VAR') return farseer.ModelObjectType.VARIABLE;\n return undefined;\n })\n .filter((t): t is farseer.ModelObjectType => t !== undefined);\n\n try {\n const result = await this.client.model.exportModel({\n types: apiTypes,\n tableGids: options.tableGids,\n variableGids: options.variableGids,\n });\n return this.mapModelRepresentationToExport(result);\n } catch (err) {\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 private mapModelRepresentationToExport(result: farseer.ModelRepresentation): ModelExport {\n // The server actually responds with `ExportModelRepresentation`,\n // which carries `gid` per table/variable. The generated client\n // schema strips it (the OpenAPI spec uses `ModelRepresentation`\n // for the response type instead of `ExportModelRepresentation`),\n // so we read it back through a cast \u2014 needed by `dimension\n // details` to scope a follow-up DMEM fetch.\n //\n // TODO(cli): durable fix is to update the OpenAPI spec\n // (`backend/app/openapi/v3/documentation/model/export.yaml`)\n // to declare `ExportModelRepresentation` and regenerate\n // farseer-client. Tactical cast is fine for now.\n return {\n tables: result.tables.map((t) => ({\n gid: (t as unknown as { gid?: number }).gid,\n name: t.name,\n columns: t.columns.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: c.foreignKeyTableName,\n })),\n rows: t.rows,\n defaultMember: t.defaultMember,\n folderPath: t.folderPath,\n autoIncrementTemplate: t.autoIncrementTemplate,\n })),\n variables: result.variables.map((v) => ({\n gid: (v as unknown as { gid?: number }).gid,\n name: v.name,\n description: v.description,\n // `model export --json` is documented as the raw export, and the\n // browser-login client used to hand it back unmapped.\n notes: v.notes,\n formula: v.formula,\n tables: v.tables,\n members: v.members ?? [],\n rollupType: v.rollupType,\n dataType: v.dataType,\n numberFormat: v.numberFormat as ModelExportVariable['numberFormat'],\n numberValidation: v.numberValidation as ModelExportVariable['numberValidation'],\n topDownMapping: v.topDownMapping,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n zConstraint: v.zConstraint,\n active: v.active,\n optimizeCalculation: v.optimizeCalculation,\n useHierarchy: v.useHierarchy,\n folderPath: v.folderPath,\n })),\n dependencies: result.dependencies ?? { tables: [], members: [], variables: [] },\n };\n }\n\n /**\n * Scoped through the entities API rather than `exportModel({ tableGids })`,\n * which 500s for some tables on large tenants.\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.client, name);\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 let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await this.client.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. Respect `options` on the way out so\n // the shape matches the primary path.\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 * Get the Apps folder ID\n */\n private async getAppsFolderId(): Promise<number | null> {\n return (await this.findFolder(['Apps']))?.id ?? null;\n }\n\n /**\n * Make a direct API request (for endpoints not in farseer-client)\n */\n private async apiRequest<T>(\n endpoint: string,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n body?: unknown,\n ): Promise<T> {\n const url = `${basePathOf(this.auth)}${endpoint}`;\n\n // This path bypasses the SDK, so the middleware's refresh never runs.\n const auth: ResolvedAuth =\n this.auth.kind === 'jwt'\n ? { ...this.auth, accessToken: (await getFreshAccessToken()) ?? this.auth.accessToken }\n : this.auth;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // The SDK stamps this from its own generated constant, and these\n // requests have to agree with it. Deep path because the package root\n // re-exports the models but not API_VERSION.\n 'x-api-version': API_VERSION,\n ...authHeaders(auth),\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n throw new HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);\n }\n\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return response.json() as Promise<T>;\n }\n}\n\n/**\n * Resolve realm name by checking if it exists on Keycloak.\n * Tries the provided name first, then uppercase variant.\n * Returns the resolved realm name or null if not found.\n */\nexport async function resolveRealm(realm: string): Promise<string | null> {\n const candidates = [realm];\n const upper = realm.toUpperCase();\n if (upper !== realm) {\n candidates.push(upper);\n }\n const lower = realm.toLowerCase();\n if (lower !== realm && lower !== upper) {\n candidates.push(lower);\n }\n\n for (const candidate of candidates) {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${candidate}`, { method: 'GET' });\n if (response.ok) {\n return candidate;\n }\n } catch {\n // Network error, continue to next candidate\n }\n }\n\n return null;\n}\n\nfunction getErrorPage(title: string, message: string): string {\n return `\n <html>\n <head>\n <title>Farseer CLI - Error</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .error-icon {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .error-icon svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"error-icon\">\n <svg viewBox=\"0 0 24 24\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </div>\n <h1>${title}</h1>\n <p>${message}</p>\n <p style=\"margin-top: 16px;\">You can close this window.</p>\n </div>\n </body>\n </html>\n `;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(realm: string = 'master'): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const http = await import('http');\n const crypto = await import('crypto');\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n\n const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;\n const CLIENT_ID = 'auth'; // Use auth client with full scope access\n const REDIRECT_PORT = 8787;\n const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;\n\n // Generate PKCE code verifier and challenge\n const codeVerifier = crypto.randomBytes(32).toString('base64url');\n const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');\n\n // Generate state for CSRF protection\n const state = crypto.randomBytes(16).toString('hex');\n\n return new Promise((resolve) => {\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url || '', `http://localhost:${REDIRECT_PORT}`);\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const error = url.searchParams.get('error');\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Login Failed', `Error: ${error}`));\n server.close();\n resolve(null);\n return;\n }\n\n if (!code || returnedState !== state) {\n res.writeHead(400, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Invalid Response', 'Missing code or state mismatch.'));\n server.close();\n resolve(null);\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n throw new Error('Token exchange failed');\n }\n\n const data = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head>\n <title>Farseer CLI - Login</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .checkmark {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n animation: scale-in 0.3s ease-out;\n }\n .checkmark svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n animation: draw 0.4s ease-out 0.2s forwards;\n stroke-dasharray: 50;\n stroke-dashoffset: 50;\n }\n @keyframes scale-in {\n from { transform: scale(0); }\n to { transform: scale(1); }\n }\n @keyframes draw {\n to { stroke-dashoffset: 0; }\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"checkmark\">\n <svg viewBox=\"0 0 24 24\">\n <polyline points=\"20 6 9 17 4 12\"></polyline>\n </svg>\n </div>\n <h1>Login Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n });\n } catch {\n res.writeHead(500, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Token Exchange Failed', 'Could not complete login.'));\n server.close();\n resolve(null);\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Build authorization URL\n const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);\n authUrl.searchParams.set('client_id', CLIENT_ID);\n authUrl.searchParams.set('redirect_uri', REDIRECT_URI);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid offline_access');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', codeChallenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n // Open browser\n const url = authUrl.toString();\n try {\n if (process.platform === 'darwin') {\n await execAsync(`open \"${url}\"`);\n } else if (process.platform === 'win32') {\n await execAsync(`start \"${url}\"`);\n } else {\n await execAsync(`xdg-open \"${url}\"`);\n }\n } catch {\n // If we can't open browser, show URL to user\n console.log(`\\nOpen this URL in your browser:\\n${url}\\n`);\n }\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n server.close();\n resolve(null);\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nlet refreshInFlight: Promise<string | null> | null = null;\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 *\n * One refresh at a time. Requests run 15-wide (fetchWithConcurrency) and the\n * middleware asks for a token on every one of them, so without coalescing a\n * single expiry spends the same refresh token fifteen times \u2014 and on a realm\n * that rotates refresh tokens, fourteen of those lose.\n */\nexport function getFreshAccessToken(): Promise<string | null> {\n return (refreshInFlight ??= mintAccessToken().finally(() => {\n refreshInFlight = null;\n }));\n}\n\nasync function mintAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid(auth)) {\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 async function refreshAccessToken(\n refreshToken: string,\n realm: string = 'master',\n): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;\n\n try {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: 'auth',\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n return {\n accessToken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ClB,cACA,QAAgB,UAKV;AACN,QAAM,WAAW,wCAAwC,KAAK;AAE9D,MAAI;AACA,UAAM,WAAW,MAAM,MAAM,UAAU;AAAA,MACnC,QAAQ;AAAA,MACR,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,MACA,MAAM,IAAI,gBAAgB;AAAA,QACtB,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,eAAe;AAAA,MACnB,CAAC;AAAA,IACL,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AACd,aAAO;AAAA,IACX;AAEA,UAAM,OAAQ,MAAM,SAAS,KAAK;AAKlC,WAAO;AAAA,MACH,aAAa,KAAK;AAAA,MAClB,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK;AAAA,IACpB;AAAA,EACJ,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;",
4
+ "sourcesContent": ["import * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { getUserAuth, setUserAuth, isUserAuthValid } from './configService';\nimport type { ApiKeyCredential } from './configService';\nimport {\n AppListItem,\n AppUpdateChanges,\n ConnectedRunner,\n REMOTE_JOB_ITEM_TYPE,\n RemoteApp,\n ResolvedFolderItem,\n RunnerImageRepositories,\n SourceFolderResolution,\n mergeAppUpdate,\n remoteJobReverseReferences,\n resolveAppItemNodeId,\n} from './apps';\nimport {\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n ModelExportVariable,\n loadDimensionTableViaEntitiesApi,\n} from './modelExport';\nimport { toError } from '../utils/errorFormatter';\nimport { matchFolderSegment } from '../utils/folderMatch';\nimport { HttpError } from './httpError';\nimport { mentionsUnknownTenant } from './authErrors';\nimport { logger } from '../utils/logger';\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\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// 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 * Why a credential probe failed. Four reasons rather than two because the advice\n * differs for each: a rejected credential means replace it, an unknown tenant\n * means the organisation is wrong and the credential is fine, a server error\n * means the host answered and nothing is wrong locally, and unreachable means\n * nothing answered at all.\n */\nexport type ConnectionFailure = 'rejected' | 'tenant-unknown' | 'server-error' | 'unreachable';\n\nexport type ConnectionCheck = { ok: true } | { ok: false; reason: ConnectionFailure; message: string };\n\nexport interface FolderItem {\n id: number;\n name: string;\n type: string;\n reference?: string;\n}\n\n/** Where a credential's requests go, and who they say they are. */\nexport function basePathOf(auth: ResolvedAuth): string {\n return auth.kind === 'jwt' ? auth.basePath : auth.credential.basePath;\n}\n\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n return auth.kind === 'jwt'\n ? { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey };\n}\n\n/**\n * Which of the four failures a thrown probe error is. A 403 is read two ways:\n * the backend answers it both for a credential it will not accept and for a\n * tenant the organisation does not have, and only the body tells them apart.\n */\nfunction failureReason(error: unknown): ConnectionFailure {\n if (!(error instanceof HttpError)) {\n return 'unreachable';\n }\n if (error.status === 403 && mentionsUnknownTenant(error.message)) {\n return 'tenant-unknown';\n }\n if (error.status === 401 || error.status === 403) {\n return 'rejected';\n }\n return 'server-error';\n}\n\n/**\n * Re-stamp the Authorization header on every request from a browser login.\n *\n * The SDK's `accessToken` option is inert here \u2014 the spec declares no bearer\n * scheme, so the generator emitted nothing that reads it \u2014 so the token goes in\n * as a plain header, and a header fixed at construction goes stale.\n */\nfunction freshTokenMiddleware(): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n // Nothing to mint; let it go out as built and fail on its own terms.\n return { url, init };\n }\n return {\n url,\n init: { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } },\n };\n },\n };\n}\n\n/**\n * The CLI's client, over the SDK. The credential is decided upstream (see\n * ResolvedAuth) and only changes the headers.\n */\nexport class FarseerService {\n private client: farseer.FarseerClient;\n private auth: ResolvedAuth;\n\n constructor(auth: ResolvedAuth) {\n this.auth = auth;\n this.client = new farseer.FarseerClient({\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware()] : [],\n });\n }\n\n /**\n * The SDK client underneath, for the read/query surface that wants it raw.\n *\n * The same instance this class uses, deliberately: a second one would derive\n * the host and headers a second time, and the SDK caches its tag map per\n * instance, so two of them pay for it twice.\n */\n get native(): farseer.FarseerClient {\n return this.client;\n }\n\n /**\n * Is this credential good? Asked of `/organization`, which answers it\n * directly \u2014 401 for a credential the server rejects, 200 otherwise, the\n * same for both kinds. Nothing about the tenant's folders can make a valid\n * credential look invalid.\n *\n * The ways it can fail are not interchangeable: \"log in again\" is useless\n * advice for a dropped connection, and \"your key was rejected\" is worse than\n * useless for a key that works at an organisation without this tenant.\n */\n async checkConnection(): Promise<ConnectionCheck> {\n try {\n await this.getOrganizationInfo();\n return { ok: true };\n } catch (error) {\n return {\n ok: false,\n reason: failureReason(error),\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n return this.apiRequest<OrganizationInfo>('/organization', 'GET');\n }\n\n async getFilesFolder(): Promise<FolderItem | null> {\n return this.findFolder(['Files']);\n }\n\n /**\n * The folder at `folderPath`, for callers that need its id. Exposed because\n * the SDK's own getItemByPath is not a path lookup \u2014 see findFolder.\n */\n async getFolderByPath(folderPath: string[]): Promise<FolderItem | null> {\n return this.findFolder(folderPath);\n }\n\n /**\n * Every failure throws. An empty list is a claim rather than a shrug:\n * SyncService.checkRemoteChanges derives what was deleted on the server by\n * subtracting this listing from sync state, so `[]` says the tenant was\n * emptied and a mirroring pull acts on it.\n */\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const folder = await this.requireFolderForListing(folderPath);\n return this.listFilesUnder(folder.id, folderPath);\n }\n\n /**\n * Resolving the root of the walk is the only part that needs a path. Every\n * level below it recurses on the id already present in its parent's\n * listing \u2014 walking the path again per subfolder turned a four-deep tree\n * into fourteen requests where five do.\n */\n private async listFilesUnder(folderId: number, folderPath: string[]): Promise<RemoteFile[]> {\n let items: farseer.FolderItemRepresentation[];\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: folderId }]);\n items = folderContent[0]?.items ?? [];\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n const files: RemoteFile[] = [];\n\n // Recursion sits outside the read so a failure deeper in the tree keeps\n // its own folder in the message instead of being re-wrapped at each level.\n for (const item of items) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n\n if (item.type === farseer.FolderItemType.Folder) {\n const subFiles = await this.listFilesUnder(item.id, [...folderPath, item.name]);\n files.push(...subFiles);\n } else if (item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference as string,\n });\n }\n }\n\n return files;\n }\n\n /** The listing root, with the path kept in the message on failure. */\n private async requireFolderForListing(folderPath: string[]): Promise<FolderItem> {\n try {\n return await this.requireFolder(folderPath);\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n }\n\n async getFileContent(reference: string): Promise<string> {\n const blob = await this.client.farseerFiles.get(reference);\n return await blob.text();\n }\n\n /**\n * Build a WebFile with an explicit Content-Type.\n *\n * When a File-like object is appended to FormData with no `type`, undici\n * (Node's fetch backend) auto-detects MIME from the filename \u2014 `.ts`\n * resolves to `video/mp2t` (MPEG transport stream), a part-level\n * Content-Type that some WAFs and proxies reject. Setting `type` on the\n * outer WebFile is what actually changes the wire bytes; setting it on\n * an inner Blob does NOT propagate to the wrapping WebFile and is a\n * no-op for the eventual multipart serialization.\n */\n private toUploadFile(content: string | Buffer, fileName: string): farseer.WebFile {\n const parts = [content] as BlobPart[];\n return new farseer.WebFile(parts, fileName, { type: 'application/octet-stream' });\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n // Ensure folder structure exists\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.requireFolder(folderPath);\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.create(file, 'GENERAL', folder.id.toString());\n } catch (error) {\n // toError preserves the original Response (or Error) as `cause` so\n // fileLogger.serializeError can capture status/url/body into the\n // JSON log \u2014 useful for diagnosing backend 4xx/5xx after the fact.\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 file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.update(reference, file);\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.farseerFiles.remove(reference);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n if (!(await this.findFolder(currentPath))) {\n // Folder doesn't exist, create it.\n //\n // `allowedTypes: null` is critical \u2014 DO NOT pass `[]`.\n // Backend semantics (itemNodeService.ts:657-708):\n // \u2022 null \u2192 inherit parent's allowedTypes (Files root is\n // ['FARSEER_FILE', 'FOLDER'], which is what we want).\n // \u2022 [] \u2192 \"nothing allowed\". Subsequent createFile in\n // the new folder fails with HTTP 400 \"Invalid parent \u2014\n // item type 'FARSEER_FILE' is not allowed in this\n // folder (allowed types: )\".\n //\n // The web UI sends `null`, which is why folders created via\n // UI always work. The CLI used to send `[]`, producing a\n // dead-end folder that couldn't host any files. Reproduced\n // on 2026-04-29 against fs-personal/ivan-kikic.\n if (currentPath.length > 1) {\n const parent = await this.requireFolder(currentPath.slice(0, -1));\n await this.client.folders.create({\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n /**\n * The file at `filePath`, or null when there isn't one.\n *\n * Absence is a legitimate answer here \u2014 the path is user-supplied \u2014 but a\n * failed request is not: the one consumer is SyncService.getFileDiff, which\n * would read it as the file having no remote content. `findFolder` keeps the\n * two apart.\n */\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n\n const folder = await this.findFolder(pathParts);\n if (!folder) {\n return null;\n }\n\n const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);\n const match = (folderContent[0]?.items ?? []).find(\n (item) => item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && 'reference' in item,\n );\n\n return match ? { name: match.name, path: filePath, reference: match.reference as string } : null;\n }\n\n /**\n * The folder at `folderPath`, or null when a segment of it isn't there. Only\n * absence returns null; a failed listing throws.\n *\n * Not the SDK's `getItemByPath`: for a single-segment path it ignores the\n * path entirely and name-searches the whole tenant across folders,\n * dashboards, sheets, dimension tables and variables, capped at 20 results.\n * The match itself is exact, so a near-miss name is harmless \u2014 but a second\n * item named exactly `Files` anywhere in the tenant makes it refuse, and 20\n * prefix matches crowd the real folder off the only page it looks at. A path\n * is a path, so each segment is matched inside its parent's listing.\n */\n private async findFolder(folderPath: string[]): Promise<FolderItem | null> {\n let parentId: number | null = null;\n let found: FolderItem | null = null;\n\n for (const segment of folderPath) {\n const contents = await this.client.folders.listItemsBatch([{ id: parentId }]);\n const folders = (contents[0]?.items ?? []).filter((item) => item.type === farseer.FolderItemType.Folder);\n const match = matchFolderSegment(folders, segment);\n if (!match) {\n return null;\n }\n found = { id: match.id, name: match.name, type: match.type };\n parentId = match.id;\n }\n\n return found;\n }\n\n /** Same walk, for callers that can only proceed if the folder is there. */\n private async requireFolder(folderPath: string[]): Promise<FolderItem> {\n const folder = await this.findFolder(folderPath);\n if (!folder) {\n throw new Error(`Folder not found: ${folderPath.join('/')}`);\n }\n return folder;\n }\n\n async getFileMetadata(reference: string): Promise<FileMetadata | null> {\n try {\n const metadata = await this.client.farseerFiles.getMetadata(reference);\n\n return {\n uploadTime: metadata.uploadTime?.toISOString(),\n uploader: metadata.uploader\n ? {\n id: metadata.uploader.id,\n email: metadata.uploader.email || '',\n firstName: metadata.uploader.firstName || '',\n lastName: metadata.uploader.lastName || '',\n }\n : undefined,\n size: metadata.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const blob = await this.client.farseerFiles.get(reference);\n const arrayBuffer = await blob.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * List all apps (Remote Jobs) on the tenant\n */\n async listApps(): Promise<AppListItem[]> {\n const response = await this.client.remoteJobs.list();\n return response.map((app) => ({\n name: app.name,\n type: REMOTE_JOB_ITEM_TYPE,\n reference: String(app.id),\n }));\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const app = await this.apiRequest<RemoteApp>(`/remoteJobs/${referenceId}`, 'GET');\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if (app && (!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch (error) {\n // A 404 means the app is gone, which is an answer. Anything else\n // means we could not ask \u2014 and AppSyncService drops an app it cannot\n // see, so reporting that as absence quietly changes what syncs.\n if (error instanceof HttpError && error.status === 404) {\n return null;\n }\n throw await toError(error, `Failed to load app ${referenceId}`);\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<{ id: string; name: string }[]> {\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: sourceFolderId }]);\n return (folderContent[0]?.items || [])\n .filter((item) => item.type === farseer.FolderItemType.FarseerFile && 'reference' in item)\n .map((item) => ({ id: item.reference as string, name: item.name }));\n } catch (error) {\n // Gone (404) is an answer about the folder; nothing else is. A 403\n // is deliberately NOT swallowed: the backend also returns it when\n // the caller lacks the tenant-wide GET_ITEMS_BATCH permission, which\n // says nothing about this folder, and \"I may not look\" is not \"there\n // are no scripts\" either way. The empty list reaches AppSyncService\n // as `entrypoint: null` and pull saves that over the local app, so\n // guessing here silently rewrites the user's config. The SDK throws\n // the raw Response, so the status is read off the thrown value.\n const status = (error as { status?: unknown } | null)?.status;\n if (status === 404) {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Null means the folder is not there. A failed request throws, so a caller\n * reporting \"no such folder\" cannot say it about a 500 or a dropped\n * connection.\n */\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.findFolder(['Files', ...segments]);\n if (!folder) {\n return null;\n }\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n // Get Apps folder ID first\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n return await this.apiRequest<RemoteApp>('/remoteJobs', 'POST', {\n folderId: appsFolderId,\n name,\n });\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.apiRequest(`/remoteJobs/${referenceId}`, 'PUT', 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 async getRunnerImageRepositories(): Promise<RunnerImageRepositories> {\n const response = await this.apiRequest<RunnerImageRepositories>('/remoteJobs/runnerImages', 'GET');\n return {\n registryPrefix: response?.registryPrefix ?? '',\n repositories: response?.repositories ?? [],\n };\n }\n\n async getRunners(): Promise<ConnectedRunner[]> {\n const response = await this.apiRequest<{ runners?: ConnectedRunner[] }>('/remoteJobs/runners', 'GET');\n return response?.runners ?? [];\n }\n\n // Never swallow a failure into an empty array: `resolveAppItemNodeId` reads\n // \"no match\" as \"this app doesn't exist\".\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n try {\n return await this.client.folders.resolveItems(remoteJobReverseReferences(remoteJobIds));\n } catch (error) {\n throw await toError(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(', ')}`);\n }\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 try {\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);\n } catch (error) {\n throw await toError(error, `Failed to delete app (Remote Job id: ${remoteJobId})`);\n }\n }\n\n /**\n * Get script files available for apps\n */\n async getScriptFiles(): Promise<{ id: string; name: string }[]> {\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, // Full path, not the file name: scripts live in subfolders.\n }));\n }\n\n /**\n * Export the entire model structure.\n * Tries the generated API first, falls back to initTagMap() for older server versions.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Default scope: tables + variables, no member rows. Pulling\n // the full member matrix is what makes the call hang on\n // larger tenants \u2014 once the response crosses the Cloud Run /\n // proxy limit the connection drops mid-flight and the client\n // sees \"socket hang up\". Callers that actually need members\n // pass { types: ['DTAB','DMEM'], tableGids: [...] }.\n const requestedTypes = options.types ?? ['DTAB', 'VAR'];\n const apiTypes = requestedTypes\n .map((t) => {\n if (t === 'DTAB') return farseer.ModelObjectType.DIMENSION_TABLE;\n if (t === 'DMEM') return farseer.ModelObjectType.DIMENSION_MEMBER;\n if (t === 'VAR') return farseer.ModelObjectType.VARIABLE;\n return undefined;\n })\n .filter((t): t is farseer.ModelObjectType => t !== undefined);\n\n try {\n const result = await this.client.model.exportModel({\n types: apiTypes,\n tableGids: options.tableGids,\n variableGids: options.variableGids,\n });\n return this.mapModelRepresentationToExport(result);\n } catch (err) {\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 private mapModelRepresentationToExport(result: farseer.ModelRepresentation): ModelExport {\n // The server actually responds with `ExportModelRepresentation`,\n // which carries `gid` per table/variable. The generated client\n // schema strips it (the OpenAPI spec uses `ModelRepresentation`\n // for the response type instead of `ExportModelRepresentation`),\n // so we read it back through a cast \u2014 needed by `dimension\n // details` to scope a follow-up DMEM fetch.\n //\n // TODO(cli): durable fix is to update the OpenAPI spec\n // (`backend/app/openapi/v3/documentation/model/export.yaml`)\n // to declare `ExportModelRepresentation` and regenerate\n // farseer-client. Tactical cast is fine for now.\n return {\n tables: result.tables.map((t) => ({\n gid: (t as unknown as { gid?: number }).gid,\n name: t.name,\n columns: t.columns.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: c.foreignKeyTableName,\n })),\n rows: t.rows,\n defaultMember: t.defaultMember,\n folderPath: t.folderPath,\n autoIncrementTemplate: t.autoIncrementTemplate,\n })),\n variables: result.variables.map((v) => ({\n gid: (v as unknown as { gid?: number }).gid,\n name: v.name,\n description: v.description,\n // `model export --json` is documented as the raw export, and the\n // browser-login client used to hand it back unmapped.\n notes: v.notes,\n formula: v.formula,\n tables: v.tables,\n members: v.members ?? [],\n rollupType: v.rollupType,\n dataType: v.dataType,\n numberFormat: v.numberFormat as ModelExportVariable['numberFormat'],\n numberValidation: v.numberValidation as ModelExportVariable['numberValidation'],\n topDownMapping: v.topDownMapping,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n zConstraint: v.zConstraint,\n active: v.active,\n optimizeCalculation: v.optimizeCalculation,\n useHierarchy: v.useHierarchy,\n folderPath: v.folderPath,\n })),\n dependencies: result.dependencies ?? { tables: [], members: [], variables: [] },\n };\n }\n\n /**\n * Scoped through the entities API rather than `exportModel({ tableGids })`,\n * which 500s for some tables on large tenants.\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.client, name);\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 let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await this.client.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. Respect `options` on the way out so\n // the shape matches the primary path.\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 * Get the Apps folder ID\n */\n private async getAppsFolderId(): Promise<number | null> {\n return (await this.findFolder(['Apps']))?.id ?? null;\n }\n\n /**\n * Make a direct API request (for endpoints not in farseer-client)\n */\n private async apiRequest<T>(\n endpoint: string,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n body?: unknown,\n ): Promise<T> {\n const url = `${basePathOf(this.auth)}${endpoint}`;\n\n // This path bypasses the SDK, so the middleware's refresh never runs.\n const auth: ResolvedAuth =\n this.auth.kind === 'jwt'\n ? { ...this.auth, accessToken: (await getFreshAccessToken()) ?? this.auth.accessToken }\n : this.auth;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // The SDK stamps this from its own generated constant, and these\n // requests have to agree with it. Deep path because the package root\n // re-exports the models but not API_VERSION.\n 'x-api-version': API_VERSION,\n ...authHeaders(auth),\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n throw new HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);\n }\n\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return response.json() as Promise<T>;\n }\n}\n\n/**\n * Resolve realm name by checking if it exists on Keycloak.\n * Tries the provided name first, then uppercase variant.\n * Returns the resolved realm name or null if not found.\n */\nexport async function resolveRealm(realm: string): Promise<string | null> {\n const candidates = [realm];\n const upper = realm.toUpperCase();\n if (upper !== realm) {\n candidates.push(upper);\n }\n const lower = realm.toLowerCase();\n if (lower !== realm && lower !== upper) {\n candidates.push(lower);\n }\n\n for (const candidate of candidates) {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${candidate}`, { method: 'GET' });\n if (response.ok) {\n return candidate;\n }\n } catch {\n // Network error, continue to next candidate\n }\n }\n\n return null;\n}\n\nfunction getErrorPage(title: string, message: string): string {\n return `\n <html>\n <head>\n <title>Farseer CLI - Error</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .error-icon {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .error-icon svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"error-icon\">\n <svg viewBox=\"0 0 24 24\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </div>\n <h1>${title}</h1>\n <p>${message}</p>\n <p style=\"margin-top: 16px;\">You can close this window.</p>\n </div>\n </body>\n </html>\n `;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(realm: string = 'master'): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const http = await import('http');\n const crypto = await import('crypto');\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n\n const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;\n const CLIENT_ID = 'auth'; // Use auth client with full scope access\n const REDIRECT_PORT = 8787;\n const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;\n\n // Generate PKCE code verifier and challenge\n const codeVerifier = crypto.randomBytes(32).toString('base64url');\n const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');\n\n // Generate state for CSRF protection\n const state = crypto.randomBytes(16).toString('hex');\n\n return new Promise((resolve) => {\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url || '', `http://localhost:${REDIRECT_PORT}`);\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const error = url.searchParams.get('error');\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Login Failed', `Error: ${error}`));\n server.close();\n resolve(null);\n return;\n }\n\n if (!code || returnedState !== state) {\n res.writeHead(400, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Invalid Response', 'Missing code or state mismatch.'));\n server.close();\n resolve(null);\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n throw new Error('Token exchange failed');\n }\n\n const data = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head>\n <title>Farseer CLI - Login</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .checkmark {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n animation: scale-in 0.3s ease-out;\n }\n .checkmark svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n animation: draw 0.4s ease-out 0.2s forwards;\n stroke-dasharray: 50;\n stroke-dashoffset: 50;\n }\n @keyframes scale-in {\n from { transform: scale(0); }\n to { transform: scale(1); }\n }\n @keyframes draw {\n to { stroke-dashoffset: 0; }\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"checkmark\">\n <svg viewBox=\"0 0 24 24\">\n <polyline points=\"20 6 9 17 4 12\"></polyline>\n </svg>\n </div>\n <h1>Login Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n });\n } catch {\n res.writeHead(500, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Token Exchange Failed', 'Could not complete login.'));\n server.close();\n resolve(null);\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Build authorization URL\n const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);\n authUrl.searchParams.set('client_id', CLIENT_ID);\n authUrl.searchParams.set('redirect_uri', REDIRECT_URI);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid offline_access');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', codeChallenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n // Open browser\n const url = authUrl.toString();\n try {\n if (process.platform === 'darwin') {\n await execAsync(`open \"${url}\"`);\n } else if (process.platform === 'win32') {\n await execAsync(`start \"${url}\"`);\n } else {\n await execAsync(`xdg-open \"${url}\"`);\n }\n } catch {\n // If we can't open browser, show URL to user\n console.log(`\\nOpen this URL in your browser:\\n${url}\\n`);\n }\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n server.close();\n resolve(null);\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nlet refreshInFlight: Promise<string | null> | null = null;\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 *\n * One refresh at a time. Requests run 15-wide (fetchWithConcurrency) and the\n * middleware asks for a token on every one of them, so without coalescing a\n * single expiry spends the same refresh token fifteen times \u2014 and on a realm\n * that rotates refresh tokens, fourteen of those lose.\n */\nexport function getFreshAccessToken(): Promise<string | null> {\n return (refreshInFlight ??= mintAccessToken().finally(() => {\n refreshInFlight = null;\n }));\n}\n\nasync function mintAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid(auth)) {\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 async function refreshAccessToken(\n refreshToken: string,\n realm: string = 'master',\n): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;\n\n try {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: 'auth',\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n };\n } catch {\n return null;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAAyB;AACzB,wBAA4B;AAC5B,2BAA0D;AAE1D,kBAYO;AACP,yBAMO;AACP,4BAAwB;AACxB,yBAAmC;AACnC,uBAA0B;AAC1B,wBAAsC;AACtC,oBAAuB;AAkEhB,SAAS,WAAW,MAA4B;AACnD,SAAO,KAAK,SAAS,QAAQ,KAAK,WAAW,KAAK,WAAW;AACjE;AAEA,SAAS,YAA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;AAAA,MACR,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,MACA,MAAM,IAAI,gBAAgB;AAAA,QACtB,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,eAAe;AAAA,MACnB,CAAC;AAAA,IACL,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AACd,aAAO;AAAA,IACX;AAEA,UAAM,OAAQ,MAAM,SAAS,KAAK;AAKlC,WAAO;AAAA,MACH,aAAa,KAAK;AAAA,MAClB,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK;AAAA,IACpB;AAAA,EACJ,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;",
6
6
  "names": []
7
7
  }
@@ -37,9 +37,11 @@ async function loadDimensionTableViaEntitiesApi(nativeClient, name) {
37
37
  const searchResult = await nativeClient.entities.search({
38
38
  name,
39
39
  types: [farseer.EntityType.DimensionTable],
40
- limit: 1
40
+ limit: 20
41
41
  });
42
- if (searchResult.length < 1) {
42
+ const needle = name.trim().toLowerCase();
43
+ const exact = searchResult.filter((e) => (e.meta?.name ?? "").toLowerCase() === needle);
44
+ if (exact.length < 1) {
43
45
  return null;
44
46
  }
45
47
  const loaded = await nativeClient.data.loadFarseerDimensionTable(name);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/modelExport.ts"],
4
- "sourcesContent": ["/**\n * The shape the CLI reports a model in, and the one fetch narrow enough to\n * belong next to it: a single dimension table with its members, scoped through\n * the entities API rather than a whole-model export.\n */\n\nimport * as farseer from 'farseer-client';\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 // Server-side filters with no in-tree caller: the entities-API path is used\n // instead, because /model/export 500s for some tables on large tenants.\n tableGids?: number[];\n variableGids?: number[];\n}\n\n/**\n * One line for a variable's members, with the backend's grouping still visible:\n * members inside a group separated by commas, groups by semicolons. Joining the\n * lot with commas reads as a single flat list, which is what it is not.\n */\nexport function formatVariableMembers(members: string[][]): string {\n return members.map((group) => group.join(', ')).join('; ');\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 notes?: string | null;\n formula?: string | null;\n tables: string[];\n /**\n * Grouped as the backend groups them, not flattened. What the grouping\n * means is decided on the calculation-engine side and is passed through\n * untouched, so the CLI keeps the shape rather than inventing a reading of\n * it \u2014 flattening threw away the only structure there was to keep.\n */\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;AAMA,cAAyB;AAEzB,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;AAyBO,SAAS,sBAAsB,SAA6B;AAC/D,SAAO,QAAQ,IAAI,CAAC,UAAU,MAAM,KAAK,IAAI,CAAC,EAAE,KAAK,IAAI;AAC7D;",
4
+ "sourcesContent": ["/**\n * The shape the CLI reports a model in, and the one fetch narrow enough to\n * belong next to it: a single dimension table with its members, scoped through\n * the entities API rather than a whole-model export.\n */\n\nimport * as farseer from 'farseer-client';\n\nexport async function loadDimensionTableViaEntitiesApi(\n nativeClient: farseer.FarseerClient,\n name: string,\n): Promise<ModelExportTable | null> {\n // The search matches loosely, so it can only say the table might be there \u2014\n // `limit: 1` would have accepted \"Sales Detail\" as proof that \"Sales\" exists\n // and then loaded a table that doesn't. Match the name exactly.\n const searchResult = await nativeClient.entities.search({\n name,\n types: [farseer.EntityType.DimensionTable],\n limit: 20,\n });\n const needle = name.trim().toLowerCase();\n const exact = searchResult.filter((e) => ((e.meta?.name as string) ?? '').toLowerCase() === needle);\n if (exact.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 // Server-side filters with no in-tree caller: the entities-API path is used\n // instead, because /model/export 500s for some tables on large tenants.\n tableGids?: number[];\n variableGids?: number[];\n}\n\n/**\n * One line for a variable's members, with the backend's grouping still visible:\n * members inside a group separated by commas, groups by semicolons. Joining the\n * lot with commas reads as a single flat list, which is what it is not.\n */\nexport function formatVariableMembers(members: string[][]): string {\n return members.map((group) => group.join(', ')).join('; ');\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 notes?: string | null;\n formula?: string | null;\n tables: string[];\n /**\n * Grouped as the backend groups them, not flattened. What the grouping\n * means is decided on the calculation-engine side and is passed through\n * untouched, so the CLI keeps the shape rather than inventing a reading of\n * it \u2014 flattening threw away the only structure there was to keep.\n */\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;AAMA,cAAyB;AAEzB,eAAsB,iCAClB,cACA,MACgC;AAIhC,QAAM,eAAe,MAAM,aAAa,SAAS,OAAO;AAAA,IACpD;AAAA,IACA,OAAO,CAAC,QAAQ,WAAW,cAAc;AAAA,IACzC,OAAO;AAAA,EACX,CAAC;AACD,QAAM,SAAS,KAAK,KAAK,EAAE,YAAY;AACvC,QAAM,QAAQ,aAAa,OAAO,CAAC,OAAQ,EAAE,MAAM,QAAmB,IAAI,YAAY,MAAM,MAAM;AAClG,MAAI,MAAM,SAAS,GAAG;AAClB,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;AAyBO,SAAS,sBAAsB,SAA6B;AAC/D,SAAO,QAAQ,IAAI,CAAC,UAAU,MAAM,KAAK,IAAI,CAAC,EAAE,KAAK,IAAI;AAC7D;",
6
6
  "names": []
7
7
  }
@@ -28,49 +28,135 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var entityResolver_exports = {};
30
30
  __export(entityResolver_exports, {
31
- resolveDashboardId: () => resolveDashboardId,
32
- resolveSheetId: () => resolveSheetId
31
+ collectFolderItems: () => collectFolderItems,
32
+ describeAmbiguity: () => describeAmbiguity,
33
+ listSheets: () => listSheets,
34
+ resolveDashboard: () => resolveDashboard,
35
+ resolveSheet: () => resolveSheet
33
36
  });
34
37
  module.exports = __toCommonJS(entityResolver_exports);
35
38
  var farseer = __toESM(require("farseer-client"));
36
- async function resolveSheetId(nativeClient, nameOrId) {
37
- const parsed = Number(nameOrId);
38
- if (!isNaN(parsed) && String(parsed) === nameOrId) {
39
+ var import_farseer_client = require("farseer-client");
40
+ var import_nameResolver = require("./nameResolver");
41
+ async function collectFolderItems(client, itemType) {
42
+ const items = await walkFolder(client, itemType, null, []);
43
+ const seen = new Set(items.map((item) => item.id));
44
+ for (const root of await sharedRoots(client)) {
45
+ if (root.type === itemType && !seen.has(root.id)) {
46
+ items.push(asTreeItem(root, []));
47
+ } else if (root.type === farseer.FolderItemType.Folder) {
48
+ for (const item of await walkFolder(client, itemType, root.id, [root.name])) {
49
+ if (!seen.has(item.id)) {
50
+ items.push(item);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return items;
56
+ }
57
+ class SharedWithMeApi extends farseer.BaseAPI {
58
+ async roots() {
59
+ const response = await this.request({ path: "/folders/sharedWithMe", method: "GET", headers: {}, query: {} });
60
+ return await response.json();
61
+ }
62
+ }
63
+ async function sharedRoots(client) {
64
+ const { configuration } = client.folders;
65
+ try {
66
+ return await new SharedWithMeApi(configuration).roots();
67
+ } catch (error) {
68
+ if (error?.status === 404) {
69
+ return [];
70
+ }
71
+ throw error;
72
+ }
73
+ }
74
+ function asTreeItem(child, path) {
75
+ return {
76
+ id: child.id,
77
+ reference: "reference" in child ? String(child.reference) : String(child.id),
78
+ name: child.name,
79
+ folderPath: path
80
+ };
81
+ }
82
+ async function walkFolder(client, itemType, folderId, path) {
83
+ const items = [];
84
+ const results = await client.folders.listItemsBatch([{ id: folderId }]);
85
+ for (const child of results[0]?.items ?? []) {
86
+ if (child.type === itemType) {
87
+ items.push(asTreeItem(child, path));
88
+ } else if (child.type === farseer.FolderItemType.Folder) {
89
+ items.push(...await walkFolder(client, itemType, child.id, [...path, child.name]));
90
+ }
91
+ }
92
+ return items;
93
+ }
94
+ async function listSheets(client) {
95
+ try {
96
+ const entities = await client.entities.getAll([import_farseer_client.EntityType.Sheet]);
97
+ if (entities.length > 0) {
98
+ return entities.map((e) => ({ id: e.id, name: e.meta?.name ?? `Sheet ${e.id}` }));
99
+ }
100
+ } catch {
101
+ }
102
+ return (await collectFolderItems(client, farseer.FolderItemType.Sheet)).map((item) => ({
103
+ id: Number(item.reference),
104
+ name: item.name,
105
+ folderPath: item.folderPath
106
+ }));
107
+ }
108
+ function asSelector(nameOrId) {
109
+ const trimmed = nameOrId.trim();
110
+ const parsed = Number(trimmed);
111
+ return !isNaN(parsed) && String(parsed) === trimmed ? { id: trimmed } : { name: nameOrId };
112
+ }
113
+ async function resolveSheet(client, nameOrId) {
114
+ const selector = asSelector(nameOrId);
115
+ if (selector.id) {
39
116
  try {
40
- const sheet = await nativeClient.sheets.get(parsed);
41
- return { id: sheet.id, name: sheet.name };
117
+ const sheet = await client.sheets.get(Number(selector.id));
118
+ return { kind: "found", entity: { id: sheet.id, name: sheet.name } };
42
119
  } catch {
43
- return null;
120
+ return { kind: "notFound" };
44
121
  }
45
122
  }
46
- const results = await nativeClient.folders.search({
47
- name: nameOrId,
48
- types: [farseer.FolderItemType.Sheet],
49
- limit: 20
50
- });
51
- const match = results.find((s) => s.name.toLowerCase() === nameOrId.toLowerCase());
52
- return match ? { id: match.id, name: match.name } : null;
123
+ return (0, import_nameResolver.selectByNameOrId)(await listSheets(client), selector, (s) => String(s.id));
53
124
  }
54
- async function resolveDashboardId(nativeClient, nameOrId) {
55
- const parsed = Number(nameOrId);
56
- if (!isNaN(parsed) && String(parsed) === nameOrId) {
125
+ async function resolveDashboard(client, nameOrId) {
126
+ const selector = asSelector(nameOrId);
127
+ if (selector.id) {
57
128
  try {
58
- const dashboard = await nativeClient.dashboards.get(parsed);
59
- return { id: dashboard.id, name: dashboard.name };
129
+ const dashboard = await client.dashboards.get(Number(selector.id));
130
+ return { kind: "found", entity: { id: dashboard.id, name: dashboard.name } };
60
131
  } catch {
61
- return null;
132
+ return { kind: "notFound" };
62
133
  }
63
134
  }
64
- const dashboards = await nativeClient.dashboards.list();
65
- const match = dashboards.find((d) => d.name.toLowerCase() === nameOrId.toLowerCase());
66
- if (match) {
67
- return { id: match.id, name: match.name };
135
+ const dashboards = await client.dashboards.list();
136
+ return (0, import_nameResolver.selectByNameOrId)(
137
+ dashboards.map((d) => ({ id: d.id, name: d.name })),
138
+ selector,
139
+ (d) => String(d.id)
140
+ );
141
+ }
142
+ async function describeAmbiguity(client, plural, name, matches, itemType) {
143
+ let paths = /* @__PURE__ */ new Map();
144
+ try {
145
+ paths = new Map((await collectFolderItems(client, itemType)).map((i) => [i.reference, i.folderPath]));
146
+ } catch {
68
147
  }
69
- return null;
148
+ const located = matches.map((m) => ({
149
+ ...m,
150
+ name: [...paths.get(String(m.id)) ?? [], m.name].join("/")
151
+ }));
152
+ return (0, import_nameResolver.formatAmbiguous)(plural, name, located, (m) => String(m.id));
70
153
  }
71
154
  // Annotate the CommonJS export names for ESM import in node:
72
155
  0 && (module.exports = {
73
- resolveDashboardId,
74
- resolveSheetId
156
+ collectFolderItems,
157
+ describeAmbiguity,
158
+ listSheets,
159
+ resolveDashboard,
160
+ resolveSheet
75
161
  });
76
162
  //# sourceMappingURL=entityResolver.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/entityResolver.ts"],
4
- "sourcesContent": ["/**\n * Entity Resolver Utilities\n *\n * Resolve sheet/dashboard names to IDs using the native Farseer client.\n */\n\nimport * as farseer from 'farseer-client';\n\n/**\n * Resolve a sheet by name or ID.\n * - If numeric, fetches directly by ID\n * - If string, uses folders.search API to find by name (case-insensitive)\n */\nexport async function resolveSheetId(\n nativeClient: farseer.FarseerClient,\n nameOrId: string,\n): Promise<{ id: number; name: string } | null> {\n const parsed = Number(nameOrId);\n if (!isNaN(parsed) && String(parsed) === nameOrId) {\n try {\n const sheet = await nativeClient.sheets.get(parsed);\n return { id: sheet.id, name: sheet.name };\n } catch {\n return null;\n }\n }\n\n // Search by name using folders.search API (backend max limit is 20)\n const results = await nativeClient.folders.search({\n name: nameOrId,\n types: [farseer.FolderItemType.Sheet],\n limit: 20,\n });\n const match = results.find((s) => s.name.toLowerCase() === nameOrId.toLowerCase());\n return match ? { id: match.id, name: match.name } : null;\n}\n\n/**\n * Resolve a dashboard by name or ID.\n * - If numeric, fetches directly by ID\n * - If string, lists all dashboards and matches by name (case-insensitive)\n */\nexport async function resolveDashboardId(\n nativeClient: farseer.FarseerClient,\n nameOrId: string,\n): Promise<{ id: number; name: string } | null> {\n const parsed = Number(nameOrId);\n if (!isNaN(parsed) && String(parsed) === nameOrId) {\n try {\n const dashboard = await nativeClient.dashboards.get(parsed);\n return { id: dashboard.id, name: dashboard.name };\n } catch {\n return null;\n }\n }\n\n // Search by name\n const dashboards = await nativeClient.dashboards.list();\n const match = dashboards.find((d) => d.name.toLowerCase() === nameOrId.toLowerCase());\n\n if (match) {\n return { id: match.id, name: match.name };\n }\n\n return null;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,cAAyB;AAOzB,eAAsB,eAClB,cACA,UAC4C;AAC5C,QAAM,SAAS,OAAO,QAAQ;AAC9B,MAAI,CAAC,MAAM,MAAM,KAAK,OAAO,MAAM,MAAM,UAAU;AAC/C,QAAI;AACA,YAAM,QAAQ,MAAM,aAAa,OAAO,IAAI,MAAM;AAClD,aAAO,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK;AAAA,IAC5C,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAGA,QAAM,UAAU,MAAM,aAAa,QAAQ,OAAO;AAAA,IAC9C,MAAM;AAAA,IACN,OAAO,CAAC,QAAQ,eAAe,KAAK;AAAA,IACpC,OAAO;AAAA,EACX,CAAC;AACD,QAAM,QAAQ,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,SAAS,YAAY,CAAC;AACjF,SAAO,QAAQ,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK,IAAI;AACxD;AAOA,eAAsB,mBAClB,cACA,UAC4C;AAC5C,QAAM,SAAS,OAAO,QAAQ;AAC9B,MAAI,CAAC,MAAM,MAAM,KAAK,OAAO,MAAM,MAAM,UAAU;AAC/C,QAAI;AACA,YAAM,YAAY,MAAM,aAAa,WAAW,IAAI,MAAM;AAC1D,aAAO,EAAE,IAAI,UAAU,IAAI,MAAM,UAAU,KAAK;AAAA,IACpD,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAGA,QAAM,aAAa,MAAM,aAAa,WAAW,KAAK;AACtD,QAAM,QAAQ,WAAW,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,SAAS,YAAY,CAAC;AAEpF,MAAI,OAAO;AACP,WAAO,EAAE,IAAI,MAAM,IAAI,MAAM,MAAM,KAAK;AAAA,EAC5C;AAEA,SAAO;AACX;",
4
+ "sourcesContent": ["/**\n * Resolving a sheet or dashboard the user named to exactly one of them.\n *\n * Both live in the folder tree, where names are unique per folder but not per\n * tenant, and both are addressed tenant-wide. Two sheets called \"Revenue\" in\n * different folders are indistinguishable by name, so a name matching more than\n * one is reported rather than resolved \u2014 several callers write.\n */\n\nimport * as farseer from 'farseer-client';\nimport { EntityType } from 'farseer-client';\nimport { selectByNameOrId, formatAmbiguous, type Selection } from './nameResolver';\n\nexport type NamedEntity = { id: number; name: string };\nexport type ListedSheet = NamedEntity & { folderPath?: string[] };\ntype TreeItem = { id: number; reference: string; name: string; folderPath: string[] };\n\n/**\n * Every item of one type the caller can reach, with the folder path that reached\n * it.\n *\n * `id` is the folder-item id and `reference` the id in the item's own domain \u2014\n * a dashboard at folder item 87 is dashboard 1. The two spaces overlap\n * numerically, so callers matching against a dashboard or sheet id want\n * `reference`.\n *\n * Two starting points, not one. Walking down from the ordinary roots misses\n * anything shared directly with the caller whose parent folder they cannot see:\n * the backend keeps those as their own roots, and without them an accessible\n * sheet reads as missing, or drops out of a collision that it is part of.\n */\nexport async function collectFolderItems(\n client: farseer.FarseerClient,\n itemType: farseer.FolderItemType,\n): Promise<TreeItem[]> {\n const items = await walkFolder(client, itemType, null, []);\n const seen = new Set(items.map((item) => item.id));\n\n for (const root of await sharedRoots(client)) {\n if (root.type === itemType && !seen.has(root.id)) {\n items.push(asTreeItem(root, []));\n } else if (root.type === farseer.FolderItemType.Folder) {\n // The parent is invisible, so the island's own root is the whole path.\n for (const item of await walkFolder(client, itemType, root.id, [root.name])) {\n if (!seen.has(item.id)) {\n items.push(item);\n }\n }\n }\n }\n return items;\n}\n\n/**\n * `GET /folders/sharedWithMe`, which the pinned client predates. Built on the\n * client's own configuration \u2014 every API on it shares one \u2014 so the request\n * goes to the same host with the same credential, including the per-request\n * token refresh, as every other call it makes.\n */\nclass SharedWithMeApi extends farseer.BaseAPI {\n async roots(): Promise<FolderChild[]> {\n const response = await this.request({ path: '/folders/sharedWithMe', method: 'GET', headers: {}, query: {} });\n return (await response.json()) as FolderChild[];\n }\n}\n\nasync function sharedRoots(client: farseer.FarseerClient): Promise<FolderChild[]> {\n const { configuration } = client.folders as unknown as { configuration: farseer.Configuration };\n try {\n return await new SharedWithMeApi(configuration).roots();\n } catch (error) {\n // A backend that predates the route has no shared roots to report. Any\n // other failure is not an answer: reading it as \"nothing is shared\" lets\n // a name resolve uniquely past an accessible duplicate, before a write.\n // The SDK throws the raw Response, so the status is read off it.\n if ((error as { status?: unknown } | null)?.status === 404) {\n return [];\n }\n throw error;\n }\n}\n\ntype FolderChild = { id: number; name: string; type: farseer.FolderItemType };\n\nfunction asTreeItem(child: FolderChild, path: string[]): TreeItem {\n return {\n id: child.id,\n reference: 'reference' in child ? String(child.reference) : String(child.id),\n name: child.name,\n folderPath: path,\n };\n}\n\nasync function walkFolder(\n client: farseer.FarseerClient,\n itemType: farseer.FolderItemType,\n folderId: number | null,\n path: string[],\n): Promise<TreeItem[]> {\n const items: TreeItem[] = [];\n const results = await client.folders.listItemsBatch([{ id: folderId }]);\n\n for (const child of results[0]?.items ?? []) {\n if (child.type === itemType) {\n items.push(asTreeItem(child, path));\n } else if (child.type === farseer.FolderItemType.Folder) {\n items.push(...(await walkFolder(client, itemType, child.id, [...path, child.name])));\n }\n }\n return items;\n}\n\n/**\n * Every sheet in the tenant, keyed by the id the sheet API answers to.\n *\n * Not `folders.search`: that matches loosely and the backend caps it at 20 with\n * no way to page, so on a large tenant the sheet asked for can sit outside the\n * only page available and read as missing.\n *\n * The entities API is asked first and the folder tree is the fallback. That\n * order is not a detail: the tree carries two ids per item, and the sheet's own\n * is `reference` \u2014 `id` belongs to the folder entry holding it. The two number\n * spaces overlap, so handing the folder-entry id to a caller does not fail, it\n * quietly addresses a different sheet. One exported list so every surface that\n * shows an id shows the same one.\n */\nexport async function listSheets(client: farseer.FarseerClient): Promise<ListedSheet[]> {\n try {\n const entities = await client.entities.getAll([EntityType.Sheet]);\n if (entities.length > 0) {\n return entities.map((e) => ({ id: e.id, name: (e.meta?.name as string) ?? `Sheet ${e.id}` }));\n }\n } catch {\n // Fall through to the tree walk.\n }\n return (await collectFolderItems(client, farseer.FolderItemType.Sheet)).map((item) => ({\n id: Number(item.reference),\n name: item.name,\n folderPath: item.folderPath,\n }));\n}\n\nfunction asSelector(nameOrId: string): { name?: string; id?: string } {\n const trimmed = nameOrId.trim();\n const parsed = Number(trimmed);\n return !isNaN(parsed) && String(parsed) === trimmed ? { id: trimmed } : { name: nameOrId };\n}\n\nexport async function resolveSheet(client: farseer.FarseerClient, nameOrId: string): Promise<Selection<NamedEntity>> {\n const selector = asSelector(nameOrId);\n if (selector.id) {\n try {\n const sheet = await client.sheets.get(Number(selector.id));\n return { kind: 'found', entity: { id: sheet.id, name: sheet.name } };\n } catch {\n return { kind: 'notFound' };\n }\n }\n return selectByNameOrId(await listSheets(client), selector, (s) => String(s.id));\n}\n\nexport async function resolveDashboard(\n client: farseer.FarseerClient,\n nameOrId: string,\n): Promise<Selection<NamedEntity>> {\n const selector = asSelector(nameOrId);\n if (selector.id) {\n try {\n const dashboard = await client.dashboards.get(Number(selector.id));\n return { kind: 'found', entity: { id: dashboard.id, name: dashboard.name } };\n } catch {\n return { kind: 'notFound' };\n }\n }\n const dashboards = await client.dashboards.list();\n return selectByNameOrId(\n dashboards.map((d) => ({ id: d.id, name: d.name })),\n selector,\n (d) => String(d.id),\n );\n}\n\n/**\n * Candidates with the folder each one is in, since that is what tells them\n * apart. The walk costs a request per folder, so it only runs once a name has\n * already turned out to be ambiguous.\n */\nexport async function describeAmbiguity(\n client: farseer.FarseerClient,\n plural: string,\n name: string,\n matches: readonly NamedEntity[],\n itemType: farseer.FolderItemType,\n): Promise<string> {\n // Keyed by the item's own domain id, which is what every caller now holds and\n // what the id printed below has to be \u2014 the folder-entry id the tree also\n // carries addresses a different item of the same type.\n let paths = new Map<string, string[]>();\n try {\n paths = new Map((await collectFolderItems(client, itemType)).map((i) => [i.reference, i.folderPath]));\n } catch {\n // A bare id list is still enough to pick one.\n }\n const located = matches.map((m) => ({\n ...m,\n name: [...(paths.get(String(m.id)) ?? []), m.name].join('/'),\n }));\n return formatAmbiguous(plural, name, located, (m) => String(m.id));\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,cAAyB;AACzB,4BAA2B;AAC3B,0BAAkE;AAoBlE,eAAsB,mBAClB,QACA,UACmB;AACnB,QAAM,QAAQ,MAAM,WAAW,QAAQ,UAAU,MAAM,CAAC,CAAC;AACzD,QAAM,OAAO,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,KAAK,EAAE,CAAC;AAEjD,aAAW,QAAQ,MAAM,YAAY,MAAM,GAAG;AAC1C,QAAI,KAAK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