farseer-cli 1.14.1 → 1.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/config.js +4 -3
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/install.js +5 -0
- package/dist/commands/install.js.map +2 -2
- package/dist/commands/login.js +2 -2
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/pull.js +2 -1
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/run.js +9 -0
- package/dist/commands/run.js.map +2 -2
- package/dist/index.js +7 -2
- package/dist/index.js.map +2 -2
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +5 -3
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +3 -2
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +23 -18
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +14 -12
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +5 -4
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +27 -17
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/pipelineContract.js +5 -2
- package/dist/mcp/tools/pipelineContract.js.map +2 -2
- package/dist/mcp/tools/runTools.js +8 -3
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +21 -17
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +11 -5
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/registerTool.js +32 -0
- package/dist/mcp/utils/registerTool.js.map +7 -0
- package/dist/pipeline/generated-reference.json +3 -3
- package/dist/pipeline/operations.js +4 -1
- package/dist/pipeline/operations.js.map +2 -2
- package/dist/pipeline/query.js +58 -40
- package/dist/pipeline/query.js.map +2 -2
- package/dist/pipeline/queryDownloads.js +72 -0
- package/dist/pipeline/queryDownloads.js.map +7 -0
- package/dist/pipeline/queryWorker.js +8 -31
- package/dist/pipeline/queryWorker.js.map +2 -2
- package/dist/pipeline/readiness.js +15 -8
- package/dist/pipeline/readiness.js.map +2 -2
- package/dist/pipeline/reference.js +2 -1
- package/dist/pipeline/reference.js.map +2 -2
- package/dist/pipeline/runtime.js +4 -3
- package/dist/pipeline/runtime.js.map +2 -2
- package/dist/pipeline/service.js +110 -50
- package/dist/pipeline/service.js.map +2 -2
- package/dist/services/appSyncService.js.map +1 -1
- package/dist/services/configService.js +11 -4
- package/dist/services/configService.js.map +2 -2
- package/dist/services/farseerService.js +23 -0
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/modelExport.js.map +1 -1
- package/dist/utils/agentSandbox.js +35 -0
- package/dist/utils/agentSandbox.js.map +7 -0
- package/docs/pipeline-client-guide.md +2 -2
- package/package.json +1 -1
- package/skills/pipeline-authoring/SKILL.md +4 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/farseerService.ts"],
|
|
4
|
-
"sourcesContent": ["import { CLI_VERSION } from '../utils/constants';\nimport { pipelineFetch } from '../pipeline/requests';\nimport * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { DEFAULT_REALM, 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; realm: 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\n/**\n * Every request names the tenant and the CLI version. The backend checks the version against the\n * pipeline protocol and refuses a CLI too old to author pipelines.\n */\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n const common = { 'X-FARSEER-CLI-VERSION': CLI_VERSION };\n return auth.kind === 'jwt'\n ? { ...common, 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { ...common, '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(realm: string): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken(realm);\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 fetchApi: pipelineFetch(farseer.patchedFetchApi),\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware(auth.realm)] : [],\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 async pipelineRequest<T>(method: 'GET' | 'POST', route: string, body?: unknown): Promise<T> {\n return this.apiRequest<T>(route, method, body);\n }\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.realm)) ?? 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 pipelineFetch()(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\nexport type BrowserLoginResult =\n | { ok: true; accessToken: string; refreshToken: string; expiresIn: number }\n // `error` is Keycloak's OAuth error code when it sent one (e.g. `login_required`).\n | { ok: false; error?: string };\n\nexport interface BrowserLoginOptions {\n idpHint?: string;\n /**\n * The hinted broker only rides an existing master session (it asks master\n * with prompt=none). When it finds none, open one in the same tab and go\n * through the broker again.\n */\n viaMasterSession?: boolean;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(\n realm: string = 'master',\n { idpHint, viaMasterSession = false }: BrowserLoginOptions = {},\n): Promise<BrowserLoginResult> {\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 keycloakBase = (r: string) => `https://login.farseer.io/auth/realms/${r}/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 const authorizationUrl = (legRealm: string, scope: string, legState: string, challenge: string, hint?: string) => {\n const authUrl = new URL(`${keycloakBase(legRealm)}/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', scope);\n authUrl.searchParams.set('state', legState);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n if (hint) {\n authUrl.searchParams.set('kc_idp_hint', hint);\n }\n return authUrl.toString();\n };\n const loginUrl = authorizationUrl(realm, 'openid offline_access', state, codeChallenge, idpHint);\n\n // The master leg only has to leave a session in the browser, so its code is\n // never exchanged \u2014 and it asks for no `offline_access`: exchanging a code\n // that carries it ends the browser's session, the one thing this leg is for.\n const masterState = crypto.randomBytes(16).toString('hex');\n const masterUrl = authorizationUrl(\n DEFAULT_REALM,\n 'openid',\n masterState,\n crypto.createHash('sha256').update(crypto.randomBytes(32).toString('base64url')).digest('base64url'),\n );\n let masterSessionOpened = false;\n\n return new Promise<BrowserLoginResult>((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 === 'login_required' && returnedState === state && viaMasterSession && !masterSessionOpened) {\n masterSessionOpened = true;\n res.writeHead(302, { Location: masterUrl });\n res.end();\n return;\n }\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({ ok: false, error });\n return;\n }\n\n if (code && returnedState === masterState && masterSessionOpened) {\n // The master session exists now: back through the broker, same tab.\n res.writeHead(302, { Location: loginUrl });\n res.end();\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({ ok: false });\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${keycloakBase(realm)}/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 ok: true,\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({ ok: false });\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Open browser\n const url = loginUrl;\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({ ok: false });\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nconst refreshesInFlight = new Map<string, Promise<string | null>>();\n\n/**\n * Return a usable browser-login access token for a realm, refreshing it first\n * if it has expired. Null when there's no login for that realm, or the refresh\n * failed (caller should fall back to an API key).\n *\n * One refresh at a time per realm. 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(realm: string = DEFAULT_REALM): Promise<string | null> {\n let inFlight = refreshesInFlight.get(realm);\n if (!inFlight) {\n inFlight = mintAccessToken(realm).finally(() => refreshesInFlight.delete(realm));\n refreshesInFlight.set(realm, inFlight);\n }\n return inFlight;\n}\n\nasync function mintAccessToken(realm: string): Promise<string | null> {\n const auth = getUserAuth(realm);\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, realm);\n if (!refreshed) {\n return null;\n }\n setUserAuth(\n {\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm,\n },\n { refresh: true },\n );\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\n/**\n * End a login's session at Keycloak, so its refresh token stops working rather\n * than outliving the logout (an offline one would for weeks). False when\n * Keycloak could not be reached or refused; the caller clears it locally anyway.\n */\nexport async function revokeRefreshToken(realm: string, refreshToken: string): Promise<boolean> {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: 'auth', refresh_token: refreshToken }),\n signal: AbortSignal.timeout(10000),\n });\n return response.ok;\n } catch {\n return false;\n }\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 pipelineFetch()(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;AAAA,uBAA4B;AAC5B,sBAA8B;AAC9B,cAAyB;AACzB,wBAA4B;AAC5B,2BAAyE;AAEzE,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;AAMA,SAAS,YAAY,MAA4C;AAC7D,QAAM,SAAS,EAAE,yBAAyB,6BAAY;AACtD,SAAO,KAAK,SAAS,QACf,EAAE,GAAG,QAAQ,eAAe,KAAK,QAAQ,eAAe,UAAU,KAAK,WAAW,GAAG,IACrF,EAAE,GAAG,QAAQ,eAAe,KAAK,WAAW,UAAU,aAAa,KAAK,WAAW,OAAO;AACpG;AAOA,SAAS,cAAc,OAAmC;AACtD,MAAI,EAAE,iBAAiB,6BAAY;AAC/B,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,WAAO,yCAAsB,MAAM,OAAO,GAAG;AAC9D,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AAC9C,WAAO;AAAA,EACX;AACA,SAAO;AACX;AASA,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R,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 { CLI_VERSION } from '../utils/constants';\nimport { pipelineFetch } from '../pipeline/requests';\nimport * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { AGENT_API_KEY_PREFIX, DEFAULT_REALM, 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; realm: 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\n/**\n * Every request names the tenant and the CLI version. The backend checks the version against the\n * pipeline protocol and refuses a CLI too old to author pipelines.\n */\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n const common = { 'X-FARSEER-CLI-VERSION': CLI_VERSION };\n return auth.kind === 'jwt'\n ? { ...common, 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { ...common, '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(realm: string): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken(realm);\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 fetchApi: pipelineFetch(farseer.patchedFetchApi),\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware(auth.realm)] : [],\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): farseer.ModelObjectType | undefined => {\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 async pipelineRequest<T>(method: 'GET' | 'POST', route: string, body?: unknown): Promise<T> {\n return this.apiRequest<T>(route, method, body);\n }\n\n get agentSession(): boolean {\n return this.auth.kind === 'apiKey' && this.auth.credential.apiKey.startsWith(AGENT_API_KEY_PREFIX);\n }\n\n async downloadDatasetVersionFile(\n datasetId: string,\n versionId: string,\n filename: string,\n signal: AbortSignal,\n ): Promise<Response> {\n const route = `/labs/datasets/${encodeURIComponent(datasetId)}/versions/${encodeURIComponent(versionId)}/file?filename=${encodeURIComponent(filename)}`;\n return this.streamFromApi(route, signal, 'Dataset file read failed');\n }\n\n async downloadFarseerFile(reference: string, signal: AbortSignal): Promise<Response> {\n return this.streamFromApi(`/farseerFiles/${encodeURIComponent(reference)}`, signal, 'Farseer file read failed');\n }\n\n /** Keep the turn credential in the parent process and send it only to the configured backend. */\n private async streamFromApi(route: string, signal: AbortSignal, failure: string): Promise<Response> {\n const response = await pipelineFetch()(`${basePathOf(this.auth)}${route}`, {\n headers: { 'x-api-version': API_VERSION, ...authHeaders(this.auth) },\n redirect: 'error',\n signal,\n });\n if (!response.ok || !response.body) {\n await response.body?.cancel();\n throw new HttpError(response.status, `${failure} (${response.status})`);\n }\n return response;\n }\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.realm)) ?? 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 pipelineFetch()(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\nexport type BrowserLoginResult =\n | { ok: true; accessToken: string; refreshToken: string; expiresIn: number }\n // `error` is Keycloak's OAuth error code when it sent one (e.g. `login_required`).\n | { ok: false; error?: string };\n\nexport interface BrowserLoginOptions {\n idpHint?: string;\n /**\n * The hinted broker only rides an existing master session (it asks master\n * with prompt=none). When it finds none, open one in the same tab and go\n * through the broker again.\n */\n viaMasterSession?: boolean;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(\n realm: string = 'master',\n { idpHint, viaMasterSession = false }: BrowserLoginOptions = {},\n): Promise<BrowserLoginResult> {\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 keycloakBase = (r: string) => `https://login.farseer.io/auth/realms/${r}/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 const authorizationUrl = (legRealm: string, scope: string, legState: string, challenge: string, hint?: string) => {\n const authUrl = new URL(`${keycloakBase(legRealm)}/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', scope);\n authUrl.searchParams.set('state', legState);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n if (hint) {\n authUrl.searchParams.set('kc_idp_hint', hint);\n }\n return authUrl.toString();\n };\n const loginUrl = authorizationUrl(realm, 'openid offline_access', state, codeChallenge, idpHint);\n\n // The master leg only has to leave a session in the browser, so its code is\n // never exchanged \u2014 and it asks for no `offline_access`: exchanging a code\n // that carries it ends the browser's session, the one thing this leg is for.\n const masterState = crypto.randomBytes(16).toString('hex');\n const masterUrl = authorizationUrl(\n DEFAULT_REALM,\n 'openid',\n masterState,\n crypto.createHash('sha256').update(crypto.randomBytes(32).toString('base64url')).digest('base64url'),\n );\n let masterSessionOpened = false;\n\n return new Promise<BrowserLoginResult>((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 === 'login_required' && returnedState === state && viaMasterSession && !masterSessionOpened) {\n masterSessionOpened = true;\n res.writeHead(302, { Location: masterUrl });\n res.end();\n return;\n }\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({ ok: false, error });\n return;\n }\n\n if (code && returnedState === masterState && masterSessionOpened) {\n // The master session exists now: back through the broker, same tab.\n res.writeHead(302, { Location: loginUrl });\n res.end();\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({ ok: false });\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${keycloakBase(realm)}/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 ok: true,\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({ ok: false });\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Open browser\n const url = loginUrl;\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({ ok: false });\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nconst refreshesInFlight = new Map<string, Promise<string | null>>();\n\n/**\n * Return a usable browser-login access token for a realm, refreshing it first\n * if it has expired. Null when there's no login for that realm, or the refresh\n * failed (caller should fall back to an API key).\n *\n * One refresh at a time per realm. 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(realm: string = DEFAULT_REALM): Promise<string | null> {\n let inFlight = refreshesInFlight.get(realm);\n if (!inFlight) {\n inFlight = mintAccessToken(realm).finally(() => refreshesInFlight.delete(realm));\n refreshesInFlight.set(realm, inFlight);\n }\n return inFlight;\n}\n\nasync function mintAccessToken(realm: string): Promise<string | null> {\n const auth = getUserAuth(realm);\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, realm);\n if (!refreshed) {\n return null;\n }\n setUserAuth(\n {\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm,\n },\n { refresh: true },\n );\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\n/**\n * End a login's session at Keycloak, so its refresh token stops working rather\n * than outliving the logout (an offline one would for weeks). False when\n * Keycloak could not be reached or refused; the caller clears it locally anyway.\n */\nexport async function revokeRefreshToken(realm: string, refreshToken: string): Promise<boolean> {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: 'auth', refresh_token: refreshToken }),\n signal: AbortSignal.timeout(10000),\n });\n return response.ok;\n } catch {\n return false;\n }\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 pipelineFetch()(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;AAAA,uBAA4B;AAC5B,sBAA8B;AAC9B,cAAyB;AACzB,wBAA4B;AAC5B,2BAA+F;AAE/F,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;AAMA,SAAS,YAAY,MAA4C;AAC7D,QAAM,SAAS,EAAE,yBAAyB,6BAAY;AACtD,SAAO,KAAK,SAAS,QACf,EAAE,GAAG,QAAQ,eAAe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E,UAAU;AAAA,MAC7C,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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -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 // 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:
|
|
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: farseer.ModelDependencies;\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
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
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var agentSandbox_exports = {};
|
|
20
|
+
__export(agentSandbox_exports, {
|
|
21
|
+
LOCAL_APP_RUNS_UNAVAILABLE: () => LOCAL_APP_RUNS_UNAVAILABLE,
|
|
22
|
+
inAgentSandbox: () => inAgentSandbox
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(agentSandbox_exports);
|
|
25
|
+
var import_configService = require("../services/configService");
|
|
26
|
+
function inAgentSandbox(env = process.env) {
|
|
27
|
+
return env.FARSEER_API_KEY?.startsWith(import_configService.AGENT_API_KEY_PREFIX) ?? false;
|
|
28
|
+
}
|
|
29
|
+
const LOCAL_APP_RUNS_UNAVAILABLE = `Installing or running an app locally needs npm packages, and an agent sandbox can reach only the Farseer API. Run the app on the tenant's jobrunner instead: POST /api/v3/remoteJobs/{appId}/run with {"arguments": [...]} in the order the app defines them. That is a Farseer write, so the user approves it. Then follow the run with GET /api/v3/remoteJobs/{appId}/remoteJobRuns.`;
|
|
30
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
31
|
+
0 && (module.exports = {
|
|
32
|
+
LOCAL_APP_RUNS_UNAVAILABLE,
|
|
33
|
+
inAgentSandbox
|
|
34
|
+
});
|
|
35
|
+
//# sourceMappingURL=agentSandbox.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/agentSandbox.ts"],
|
|
4
|
+
"sourcesContent": ["import { AGENT_API_KEY_PREFIX } from '../services/configService';\n\n/** A Labs agent sandbox: the CLI runs with a turn key and can reach only the Farseer API. */\nexport function inAgentSandbox(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.FARSEER_API_KEY?.startsWith(AGENT_API_KEY_PREFIX) ?? false;\n}\n\n/** Local app runs need npm packages (tsx, farseer-client), which a sandbox cannot download. */\nexport const LOCAL_APP_RUNS_UNAVAILABLE =\n 'Installing or running an app locally needs npm packages, and an agent sandbox can reach only the Farseer API. ' +\n \"Run the app on the tenant's jobrunner instead: POST /api/v3/remoteJobs/{appId}/run with \" +\n '{\"arguments\": [...]} in the order the app defines them. That is a Farseer write, so the user approves it. ' +\n 'Then follow the run with GET /api/v3/remoteJobs/{appId}/remoteJobRuns.';\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAqC;AAG9B,SAAS,eAAe,MAAyB,QAAQ,KAAc;AAC1E,SAAO,IAAI,iBAAiB,WAAW,yCAAoB,KAAK;AACpE;AAGO,MAAM,6BACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
This page is for the tenant admin and IT team of a Farseer customer who want analysts to build data pipelines with an AI assistant. The assistant's own instructions are in the pipeline skill (`farseer pipeline guide`); this page covers what you decide and what you are agreeing to.
|
|
4
4
|
|
|
5
|
-
New repeatable pipelines use Simple Pipelines. Existing TypeScript apps remain supported through the app tools for inspection, execution, debugging and targeted fixes. A request to fix or extend an existing import does not authorize replacing or migrating it, changing its runner or schedule, or creating a duplicate pipeline. Migration requires an explicit migration request. Pipeline init, source sync and run refuse unrelated or unknown runner images;
|
|
5
|
+
New repeatable pipelines use Simple Pipelines. Existing TypeScript apps remain supported through the app tools for inspection, execution, debugging and targeted fixes. A request to fix or extend an existing import does not authorize replacing or migrating it, changing its runner or schedule, or creating a duplicate pipeline. Migration requires an explicit migration request. Pipeline init, source sync and run refuse unrelated or unknown runner images; a new pipeline is pinned to the CLI's image when init creates it, and an existing Simple Pipelines job moves to a newer image only through `farseer pipeline upgrade-runtime`.
|
|
6
6
|
|
|
7
7
|
## What data leaves your tenant
|
|
8
8
|
|
|
@@ -44,7 +44,7 @@ The permissions alone are not enough for an analyst who is not a super user: Far
|
|
|
44
44
|
|
|
45
45
|
The CLI authors for exactly one engine version: the one inside the runner image it was released with. When Farseer releases a new runner image it also releases a CLI, and for a while the backend accepts both. `check` reports a newer CLI as available; below the minimum, pipeline commands stop with "update the CLI". IT should expect to update `farseer-cli` on analysts' laptops a few times a year.
|
|
46
46
|
|
|
47
|
-
A job on an older image
|
|
47
|
+
The CLI never changes which engine a job runs on its own. A job on an older image keeps running on it. To edit it with a newer CLI, someone runs `farseer pipeline upgrade-runtime`, which moves the job to the CLI's image and says what it moved from; until then the CLI refuses to push to it. That includes pipelines Farseer consultants built for you earlier: the assistant asks before upgrading one, and if the newer engine rejects something it will say so and offer to fix it. A job set to follow `latest` is left alone.
|
|
48
48
|
|
|
49
49
|
## Moving to production
|
|
50
50
|
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@ name: pipeline-authoring
|
|
|
3
3
|
description: Author all new repeatable Farseer data pipelines with Simple Pipelines, and maintain existing Simple Pipelines. Preserve existing TypeScript apps through the app tools; migration requires an explicit migration request.
|
|
4
4
|
metadata:
|
|
5
5
|
version: "1"
|
|
6
|
-
minimum-cli: "1.14.
|
|
6
|
+
minimum-cli: "1.14.2"
|
|
7
7
|
engine-profile: "2.9"
|
|
8
8
|
---
|
|
9
9
|
|
|
@@ -46,7 +46,7 @@ Submit once after sync and save the UUID receipt. Inspect that UUID after reconn
|
|
|
46
46
|
|
|
47
47
|
`runs` lists the profile job's runs from the job history, newest first, 20 by default (`limit`). Each entry carries the run `uuid`, `status`, `startedAt`, `finishedAt` when the backend reports it, and `receipt: true` when a local receipt names that UUID. Use it to find the UUID to inspect or recover after a lost response; it never chooses a run for you.
|
|
48
48
|
|
|
49
|
-
`query` takes bindings `[{name, datasetId, versionId}]` and a single SELECT (WITH allowed); bind complete manifests to read immutable dataset versions, while a file binding `{name, file}` reads the current mutable Farseer File under `Data/` and is labeled as such, with no history guarantee. The worker downloads fixed signed HTTPS inputs to private temporary files (256 MiB total across all bindings), then runs DuckDB with 256 MB memory, 256 MB spill, two threads, 30 seconds total, at most 1,000 rows and 256 KiB of results; it gets no tenant credentials, loads no HTTP extension, cannot reach other files or URLs or change settings, is killed on cancellation or timeout, and these engine limits (not an OS memory sandbox) are fixed in this build. SQL filters do not reduce the full download, so use a smaller admitted output when capacity or network speed is insufficient; truncated results are samples, so use COUNT or SUM for whole-input claims.
|
|
49
|
+
`query` takes bindings `[{name, datasetId, versionId}]` and a single SELECT (WITH allowed); bind complete manifests to read immutable dataset versions, while a file binding `{name, file}` reads the current mutable Farseer File under `Data/` and is labeled as such, with no history guarantee. The worker downloads fixed signed HTTPS inputs to private temporary files (with an agent turn key the CLI fetches them through the API instead, because an agent sandbox can reach only the API; 256 MiB total across all bindings), then runs DuckDB with 256 MB memory, 256 MB spill, two threads, 30 seconds total, at most 1,000 rows and 256 KiB of results; it gets no tenant credentials, loads no HTTP extension, cannot reach other files or URLs or change settings, is killed on cancellation or timeout, and these engine limits (not an OS memory sandbox) are fixed in this build. SQL filters do not reduce the full download, so use a smaller admitted output when capacity or network speed is insufficient; truncated results are samples, so use COUNT or SUM for whole-input claims.
|
|
50
50
|
|
|
51
51
|
`inspect-import` reads the owning import service for a load's import ID: CREATED can still have a commit in flight, and COMMITED confirms completion. `versions` lists a dataset's retained versions. `restore(datasetId, versionId, expectedCurrentVersionId)` repairs a wrong publication of a dataset: first inspect versions and run effects, coordinate with colleagues and confirm the run has stopped. Restore selects an eligible retained publication and moves its reading position in the same transaction, cancels outstanding unpublished candidates, and refuses a stale expected current version; if its response is lost, inspect dataset state before any next action. Restore covers datasets only, not model loads: it does not reverse imports, recalculation or exports, so reconcile model results separately through existing model access. For an incremental recipe, fix the definition and reprocess from the restored cursor, then verify counts, duplicate keys and totals; historical source replay must be supported and unchanged.
|
|
52
52
|
|
|
@@ -54,7 +54,7 @@ Submit once after sync and save the UUID receipt. Inspect that UUID after reconn
|
|
|
54
54
|
|
|
55
55
|
The backend records each run before dispatch and answers with its run UUID. The tenant's jobrunner must be 3.6.0 or newer: an older one cannot keep the run id the backend assigns, so the backend refuses to send it the run and says so, and no run starts. Reading datasets, their versions and download links needs the right to run remote jobs (CLASS.REMOTE_JOB.RUN), which `init`, `check`, `query` and `versions` rely on; `restore` needs the right to update jobs (CLASS.REMOTE_JOB.UPDATE); creating or deleting datasets stays with super users and the runner. A permission refusal from `check` is a setup issue to report to the setup owner.
|
|
56
56
|
|
|
57
|
-
`check` reads the prepared job, its runner image, whether a newer CLI was released with the tenant's runner image (`cli-version`, pending means update before authoring), and the output manifests, then probes the first Parquet file using signed HTTPS access. This CLI authors for exactly one engine: the one inside the runner image it was released with. Only jobs already using a Simple Pipelines runner are eligible for image pinning. TypeScript, other runner families and an unknown or inherited image are refused by init, source sync and run; use the existing app tools and preserve the app. A Simple Pipelines job on an older image
|
|
57
|
+
`check` reads the prepared job, its runner image, whether a newer CLI was released with the tenant's runner image (`cli-version`, pending means update before authoring), and the output manifests, then probes the first Parquet file using signed HTTPS access, or through the API when the CLI runs with an agent turn key, because an agent sandbox can reach only the API. This CLI authors for exactly one engine: the one inside the runner image it was released with. Only jobs already using a Simple Pipelines runner are eligible for image pinning. TypeScript, other runner families and an unknown or inherited image are refused by init, source sync and run; use the existing app tools and preserve the app. The CLI never changes a job's image on its own. A Simple Pipelines job on an older released image is reported as failed: `run`, `pull` and reads still work on its own image, but `push` is refused (`RUNTIME_UPGRADE_REQUIRED`) until the job is upgraded with `upgrade-runtime` (CLI: `farseer pipeline upgrade-runtime`), which moves it to this CLI's image and reports where it moved from. Upgrading changes the engine for everyone on that tenant and, on a scheduled job, for the next scheduled run, so ask the user before upgrading, then `run` once and fix whatever the newer engine's preflight rejects. A job on a moving tag such as `latest`, or on a digest, is reported as pending and left as it is: `upgrade-runtime` refuses it, and each run reports the engine it started on (`engine` in `inspect`). A job on a newer released image is reported as pending: it runs and accepts pushes, but update the CLI to author what the newer engine added. No job is ever moved down. A dataset declared under `Models/` is created by the engine on the first run, so init and check report a dataset that does not exist yet as pending, not as an error; after the first run, rerun `init jobId=<id> force=true` to record the new dataset IDs (a rerun for the same job and folder keeps the setup record, declared config files and author), and the profile's `datasetIds` lists the outputs recorded so far. No published version means read verification stays pending until the first prepared run. The setup record (owner, evidence, checkedAt, retentionDays, otherWritersExcluded=true, runtimeVerified=true) is the owner's statement, not an API-verified fact: do not invent it, and reconfirm it after setup changes. `readyForAcceptance` does not establish source replay, reconciliation or real-client acceptance.
|
|
58
58
|
|
|
59
59
|
## Authoring rules
|
|
60
60
|
|
|
@@ -90,6 +90,6 @@ A pipeline is promoted the way every tenant file is: copied, then set up on the
|
|
|
90
90
|
5. `run`, then `inspect`, then `init jobId=<id> force=true` so the profile records the datasets the first run created.
|
|
91
91
|
6. Set a schedule (in the web app or with `farseer_configure_app`) once the first run is verified, then run `init jobId=<id> force=true` so the profile records it.
|
|
92
92
|
|
|
93
|
-
On a production tenant, state the effects of step 5 before running: real cells, real members if `create_missing_members` is set
|
|
93
|
+
On a production tenant, state the effects of step 5 before running: real cells, and real members if `create_missing_members` is set. A run never changes the job's image; only `upgrade-runtime` does, as its own step.
|
|
94
94
|
|
|
95
95
|
Source provisioning, self-service job creation beyond init, broad runtime compatibility, mutable Farseer Files history, automatic whole-run rollback, tenant editing sessions, mutation guards, abandoned-session recovery, finer locks and a fair or durable queue remain deferred. The legacy separate-workspace experiment is retained only for regression tests.
|