farseer-cli 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -33
- package/dist/commands/app.js +9 -35
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/apps.js +3 -9
- package/dist/commands/apps.js.map +2 -2
- package/dist/commands/cells.js +3 -11
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/config.js +4 -4
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/dashboards.js +3 -11
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/diff.js +3 -7
- package/dist/commands/diff.js.map +2 -2
- package/dist/commands/dimensions.js +9 -31
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/files.js +4 -9
- package/dist/commands/files.js.map +2 -2
- package/dist/commands/formula.js +2 -6
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/list.js +4 -9
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/model.js +2 -8
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/pull.js +16 -9
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/push.js +5 -9
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/refresh.js +3 -8
- package/dist/commands/refresh.js.map +2 -2
- package/dist/commands/run.js +3 -6
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/sheets.js +5 -21
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/status.js +4 -9
- package/dist/commands/status.js.map +2 -2
- package/dist/commands/variables.js +8 -30
- package/dist/commands/variables.js.map +2 -2
- package/dist/commands/whoami.js +11 -0
- package/dist/commands/whoami.js.map +2 -2
- package/dist/index.js +22 -23
- package/dist/index.js.map +2 -2
- package/dist/mcp/resources/documentation.js +1 -1
- package/dist/mcp/resources/documentation.js.map +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/tools/appTools.js +10 -30
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +2 -6
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +22 -66
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +9 -25
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +4 -12
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +30 -84
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +4 -12
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +20 -60
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +8 -30
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +4 -17
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/mcp/utils/launchPin.js.map +2 -2
- package/dist/services/configService.js +0 -45
- package/dist/services/configService.js.map +2 -2
- package/dist/services/farseerFactory.js +79 -0
- package/dist/services/farseerFactory.js.map +3 -3
- package/dist/services/preflight.js +115 -0
- package/dist/services/preflight.js.map +7 -0
- package/dist/utils/fileValidation.js +1 -0
- package/dist/utils/fileValidation.js.map +2 -2
- package/dist/utils/helpers.js +42 -48
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/workspace.js +1 -1
- package/dist/utils/workspace.js.map +2 -2
- package/docs/api-reference.md +3 -3
- package/docs/arquero-patterns.md +1 -1
- package/docs/cli-guide.md +14 -9
- package/docs/how-farseer-works.md +1 -1
- package/docs/import-workflows.md +3 -3
- package/docs/new-app-template.md +1 -1
- package/docs/query-formulas.md +1 -1
- package/package.json +1 -1
- package/dist/commands/checkout.js +0 -189
- package/dist/commands/checkout.js.map +0 -7
|
@@ -30,22 +30,40 @@ var farseerFactory_exports = {};
|
|
|
30
30
|
__export(farseerFactory_exports, {
|
|
31
31
|
DEFAULT_SCRIPT_EXTENSIONS: () => DEFAULT_SCRIPT_EXTENSIONS,
|
|
32
32
|
DEFAULT_SYNC_EXTENSIONS: () => DEFAULT_SYNC_EXTENSIONS,
|
|
33
|
+
checkTenantAtOrganisation: () => checkTenantAtOrganisation,
|
|
33
34
|
ensureFreshToken: () => ensureFreshToken,
|
|
35
|
+
fetchOrganizationTenants: () => fetchOrganizationTenants,
|
|
34
36
|
getAvailableAuth: () => getAvailableAuth,
|
|
35
37
|
getFarseerClient: () => getFarseerClient,
|
|
36
38
|
getFarseerClientWithFallback: () => getFarseerClientWithFallback,
|
|
39
|
+
getFreshAccessToken: () => getFreshAccessToken,
|
|
37
40
|
getNativeFarseerClient: () => getNativeFarseerClient,
|
|
38
41
|
isAuthError: () => isAuthError,
|
|
42
|
+
isTenantNotFoundError: () => isTenantNotFoundError,
|
|
39
43
|
showLoginPrompt: () => showLoginPrompt
|
|
40
44
|
});
|
|
41
45
|
module.exports = __toCommonJS(farseerFactory_exports);
|
|
46
|
+
var import_axios = __toESM(require("axios"));
|
|
42
47
|
var farseer = __toESM(require("farseer-client"));
|
|
43
48
|
var import_farseerService = require("./farseerService");
|
|
44
49
|
var import_farseerApi = require("./farseerApi");
|
|
45
50
|
var import_configService = require("./configService");
|
|
46
51
|
var import_farseerService2 = require("./farseerService");
|
|
47
52
|
var import_logger = require("../utils/logger");
|
|
53
|
+
function isTenantNotFoundError(error) {
|
|
54
|
+
return error instanceof Error && mentionsUnknownTenant(error.message);
|
|
55
|
+
}
|
|
56
|
+
function mentionsUnknownTenant(text) {
|
|
57
|
+
if (!text) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const msg = text.toLowerCase();
|
|
61
|
+
return msg.includes("does not exist") && msg.includes("tenant");
|
|
62
|
+
}
|
|
48
63
|
function isAuthError(error) {
|
|
64
|
+
if (isTenantNotFoundError(error)) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
49
67
|
if (error instanceof Error) {
|
|
50
68
|
const msg = error.message.toLowerCase();
|
|
51
69
|
return msg.includes("401") || msg.includes("403") || msg.includes("unauthorized") || msg.includes("forbidden");
|
|
@@ -74,6 +92,63 @@ const DEFAULT_SYNC_EXTENSIONS = [
|
|
|
74
92
|
// Docs
|
|
75
93
|
".md"
|
|
76
94
|
];
|
|
95
|
+
async function getFreshAccessToken() {
|
|
96
|
+
const auth = (0, import_configService.getUserAuth)();
|
|
97
|
+
if (!auth) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
if ((0, import_configService.isUserAuthValid)()) {
|
|
101
|
+
return auth.accessToken;
|
|
102
|
+
}
|
|
103
|
+
import_logger.logger.dim("Token expired, refreshing...");
|
|
104
|
+
const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
105
|
+
if (!refreshed) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
(0, import_configService.setUserAuth)({
|
|
109
|
+
accessToken: refreshed.accessToken,
|
|
110
|
+
refreshToken: refreshed.refreshToken,
|
|
111
|
+
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
112
|
+
realm: auth.realm
|
|
113
|
+
});
|
|
114
|
+
import_logger.logger.dim("Token refreshed");
|
|
115
|
+
return refreshed.accessToken;
|
|
116
|
+
}
|
|
117
|
+
async function checkTenantAtOrganisation(organisation, tenant, accessToken) {
|
|
118
|
+
try {
|
|
119
|
+
await import_axios.default.get(`${(0, import_configService.generateBasePath)(organisation)}/organization`, {
|
|
120
|
+
headers: { Authorization: `Bearer ${accessToken}`, "X-TENANT-ID": tenant },
|
|
121
|
+
timeout: 3e4
|
|
122
|
+
});
|
|
123
|
+
return { status: "ok" };
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (import_axios.default.isAxiosError(error)) {
|
|
126
|
+
if (error.response?.status === 401) {
|
|
127
|
+
return { status: "unauthorized" };
|
|
128
|
+
}
|
|
129
|
+
if (error.response?.status === 404) {
|
|
130
|
+
return { status: "no-such-org" };
|
|
131
|
+
}
|
|
132
|
+
const body = error.response?.data;
|
|
133
|
+
const detail = typeof body === "string" ? body : body?.message;
|
|
134
|
+
if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {
|
|
135
|
+
return { status: "tenant-unknown" };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { status: "unreachable", message: error instanceof Error ? error.message : String(error) };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function fetchOrganizationTenants(organisation, accessToken) {
|
|
142
|
+
try {
|
|
143
|
+
const response = await import_axios.default.get(`${(0, import_configService.generateBasePath)(organisation)}/organization`, {
|
|
144
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
145
|
+
timeout: 3e4
|
|
146
|
+
});
|
|
147
|
+
return (response.data.tenants ?? []).map((t) => t.name);
|
|
148
|
+
} catch {
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
77
152
|
async function getFarseerClient(organisation, tenant) {
|
|
78
153
|
const auth = (0, import_configService.getUserAuth)();
|
|
79
154
|
if (auth) {
|
|
@@ -236,12 +311,16 @@ async function getNativeFarseerClient(organisation, tenant) {
|
|
|
236
311
|
0 && (module.exports = {
|
|
237
312
|
DEFAULT_SCRIPT_EXTENSIONS,
|
|
238
313
|
DEFAULT_SYNC_EXTENSIONS,
|
|
314
|
+
checkTenantAtOrganisation,
|
|
239
315
|
ensureFreshToken,
|
|
316
|
+
fetchOrganizationTenants,
|
|
240
317
|
getAvailableAuth,
|
|
241
318
|
getFarseerClient,
|
|
242
319
|
getFarseerClientWithFallback,
|
|
320
|
+
getFreshAccessToken,
|
|
243
321
|
getNativeFarseerClient,
|
|
244
322
|
isAuthError,
|
|
323
|
+
isTenantNotFoundError,
|
|
245
324
|
showLoginPrompt
|
|
246
325
|
});
|
|
247
326
|
//# sourceMappingURL=farseerFactory.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/farseerFactory.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Factory for creating Farseer API client based on available authentication\n *\n * Priority:\n * 1. JWT token (from browser login) - try first\n * 2. API key (from config) - fallback if JWT fails or unavailable\n * 3. Prompt user to login - if nothing works\n */\n\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * Check if an error is an authentication error (401/403)\n */\nexport function isAuthError(error: unknown): boolean {\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\n */\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(itemNodeId: number): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n // 1. Try JWT token from browser login first (supports apps sync)\n const auth = getUserAuth();\n if (auth) {\n // Check if token needs refresh\n let accessToken = auth.accessToken;\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n // Fall through to API key\n } else {\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n return {\n client: new FarseerApi(accessToken, organisation, tenant),\n authType: 'jwt',\n };\n }\n }\n\n // 2. Fall back to API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n client: new FarseerService(credential),\n authType: 'apiKey',\n };\n }\n\n return null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Get a Farseer client with automatic fallback and connection testing.\n * This is the recommended way to get a client for commands.\n *\n * Flow:\n * 1. Try JWT if available and valid\n * 2. If JWT fails or unavailable, try API key\n * 3. If nothing works, return null (caller should show login prompt)\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClientWithFallback(\n organisation: string,\n tenant: string,\n): Promise<FarseerClientResult | null> {\n const auth = getUserAuth();\n const credential = getCredential(tenant);\n\n // 1. Try JWT token first\n if (auth) {\n let accessToken = auth.accessToken;\n\n // Refresh token if needed\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n const jwtClient = new FarseerApi(accessToken, organisation, tenant);\n\n // Test JWT connection\n try {\n const connected = await jwtClient.testConnection();\n if (connected) {\n return { client: jwtClient, authType: 'jwt' };\n }\n } catch (error) {\n // JWT failed, will try API key\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n }\n }\n\n // 2. Try API key\n if (credential) {\n const apiKeyClient = new FarseerService(credential);\n\n try {\n const connected = await apiKeyClient.testConnection();\n if (connected) {\n return { client: apiKeyClient, authType: 'apiKey' };\n }\n } catch {\n // API key also failed\n logger.dim('API key auth failed.');\n }\n }\n\n // 3. Nothing worked\n return null;\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n\n/**\n * Get a native farseer-client FarseerClient instance.\n * This provides access to the full farseer-client API (export, import jobs, file creation, etc.)\n * that isn't available through the simplified IFarseerClient interface.\n *\n * Tries JWT first, then API key. Handles token refresh automatically.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header\n */\nexport async function getNativeFarseerClient(\n organisation: string,\n tenant: string,\n): Promise<farseer.FarseerClient | null> {\n const basePath = generateBasePath(organisation);\n\n // 1. Try JWT token first\n const auth = getUserAuth();\n if (auth) {\n let accessToken = auth.accessToken;\n\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n }\n }\n\n if (isUserAuthValid()) {\n return new farseer.FarseerClient({\n basePath,\n headers: {\n 'X-TENANT-ID': tenant,\n Authorization: `Bearer ${accessToken}`,\n },\n });\n }\n }\n\n // 2. Try API key\n const credential = getCredential(tenant);\n if (credential) {\n return new farseer.FarseerClient({\n basePath: credential.basePath,\n headers: {\n 'X-TENANT-ID': credential.tenantId,\n 'X-API-KEY': credential.apiKey,\n },\n });\n }\n\n return null;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,cAAyB;AACzB,4BAA+B;AAC/B,wBAA2B;AAC3B,2BAA2F;AAC3F,IAAAA,yBAAmC;AACnC,oBAAuB;
|
|
6
|
-
"names": ["import_farseerService"]
|
|
4
|
+
"sourcesContent": ["/**\n * Factory for creating Farseer API client based on available authentication\n *\n * Priority:\n * 1. JWT token (from browser login) - try first\n * 2. API key (from config) - fallback if JWT fails or unavailable\n * 3. Prompt user to login - if nothing works\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\n */\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(itemNodeId: number): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n // 1. Try JWT token from browser login first (supports apps sync)\n const auth = getUserAuth();\n if (auth) {\n // Check if token needs refresh\n let accessToken = auth.accessToken;\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n // Fall through to API key\n } else {\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n return {\n client: new FarseerApi(accessToken, organisation, tenant),\n authType: 'jwt',\n };\n }\n }\n\n // 2. Fall back to API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n client: new FarseerService(credential),\n authType: 'apiKey',\n };\n }\n\n return null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Get a Farseer client with automatic fallback and connection testing.\n * This is the recommended way to get a client for commands.\n *\n * Flow:\n * 1. Try JWT if available and valid\n * 2. If JWT fails or unavailable, try API key\n * 3. If nothing works, return null (caller should show login prompt)\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClientWithFallback(\n organisation: string,\n tenant: string,\n): Promise<FarseerClientResult | null> {\n const auth = getUserAuth();\n const credential = getCredential(tenant);\n\n // 1. Try JWT token first\n if (auth) {\n let accessToken = auth.accessToken;\n\n // Refresh token if needed\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n const jwtClient = new FarseerApi(accessToken, organisation, tenant);\n\n // Test JWT connection\n try {\n const connected = await jwtClient.testConnection();\n if (connected) {\n return { client: jwtClient, authType: 'jwt' };\n }\n } catch (error) {\n // JWT failed, will try API key\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n }\n }\n\n // 2. Try API key\n if (credential) {\n const apiKeyClient = new FarseerService(credential);\n\n try {\n const connected = await apiKeyClient.testConnection();\n if (connected) {\n return { client: apiKeyClient, authType: 'apiKey' };\n }\n } catch {\n // API key also failed\n logger.dim('API key auth failed.');\n }\n }\n\n // 3. Nothing worked\n return null;\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n\n/**\n * Get a native farseer-client FarseerClient instance.\n * This provides access to the full farseer-client API (export, import jobs, file creation, etc.)\n * that isn't available through the simplified IFarseerClient interface.\n *\n * Tries JWT first, then API key. Handles token refresh automatically.\n *\n * TECH DEBT \u2014 two parallel client stacks. `getFarseerClientWithFallback`\n * returns an `IFarseerClient` (a curated facade over the hand-rolled axios\n * `FarseerApi` for JWT and the SDK-wrapping `FarseerService` for API keys),\n * while this returns the raw SDK client for the richer read/query surface. The\n * duality is historical (the JWT path was hand-rolled instead of using the\n * SDK), not necessary \u2014 the SDK handles JWT fine. Because of it, `preflight`\n * runs its guard with the IFarseerClient and read/query commands then build a\n * second (native) client here from the same validated pair. Collapsing these\n * into one authenticated SDK client is planned as a follow-up; until then the\n * extra construction is deliberate.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header\n */\nexport async function getNativeFarseerClient(\n organisation: string,\n tenant: string,\n): Promise<farseer.FarseerClient | null> {\n const basePath = generateBasePath(organisation);\n\n // 1. Try JWT token first\n const auth = getUserAuth();\n if (auth) {\n let accessToken = auth.accessToken;\n\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n }\n }\n\n if (isUserAuthValid()) {\n return new farseer.FarseerClient({\n basePath,\n headers: {\n 'X-TENANT-ID': tenant,\n Authorization: `Bearer ${accessToken}`,\n },\n });\n }\n }\n\n // 2. Try API key\n const credential = getCredential(tenant);\n if (credential) {\n return new farseer.FarseerClient({\n basePath: credential.basePath,\n headers: {\n 'X-TENANT-ID': credential.tenantId,\n 'X-API-KEY': credential.apiKey,\n },\n });\n }\n\n return null;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,mBAAkB;AAClB,cAAyB;AACzB,4BAA+B;AAC/B,wBAA2B;AAC3B,2BAA2F;AAC3F,IAAAA,yBAAmC;AACnC,oBAAuB;AAWhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAQA,SAAS,sBAAsB,MAAmC;AAC9D,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AASO,SAAS,YAAY,OAAyB;AACjD,MAAI,sBAAsB,KAAK,GAAG;AAC9B,WAAO;AAAA,EACX;AACA,MAAI,iBAAiB,OAAO;AACxB,UAAM,M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AAkB,UAAU,WAAW;AAC9C,yBAAO,IAAI,iBAAiB;AAC5B,WAAO;AAAA,EACX;AAEA,SAAO;AACX;AAuBA,eAAsB,uBAClB,cACA,QACqC;AACrC,QAAM,eAAW,uCAAiB,YAAY;AAG9C,QAAM,WAAO,kCAAY;AACzB,MAAI,MAAM;AACN,QAAI,cAAc,KAAK;AAEvB,QAAI,KAAC,sCAAgB,GAAG;AACpB,YAAM,YAAY,UAAM,2CAAmB,KAAK,cAAc,KAAK,SAAS,QAAQ;AACpF,UAAI,WAAW;AACX,8CAAY;AAAA,UACR,aAAa,UAAU;AAAA,UACvB,cAAc,UAAU;AAAA,UACxB,WAAW,IAAI,KAAK,KAAK,IAAI,IAAI,UAAU,YAAY,GAAI,EAAE,YAAY;AAAA,UACzE,OAAO,KAAK;AAAA,QAChB,CAAC;AACD,sBAAc,UAAU;AAAA,MAC5B;AAAA,IACJ;AAEA,YAAI,sCAAgB,GAAG;AACnB,aAAO,IAAI,QAAQ,cAAc;AAAA,QAC7B;AAAA,QACA,SAAS;AAAA,UACL,eAAe;AAAA,UACf,eAAe,UAAU,WAAW;AAAA,QACxC;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ;AAGA,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,WAAO,IAAI,QAAQ,cAAc;AAAA,MAC7B,UAAU,WAAW;AAAA,MACrB,SAAS;AAAA,QACL,eAAe,WAAW;AAAA,QAC1B,aAAa,WAAW;AAAA,MAC5B;AAAA,IACJ,CAAC;AAAA,EACL;AAEA,SAAO;AACX;",
|
|
6
|
+
"names": ["import_farseerService", "axios"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var preflight_exports = {};
|
|
30
|
+
__export(preflight_exports, {
|
|
31
|
+
preflight: () => preflight,
|
|
32
|
+
preflightForPair: () => preflightForPair
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(preflight_exports);
|
|
35
|
+
var fs = __toESM(require("fs"));
|
|
36
|
+
var import_farseerFactory = require("./farseerFactory");
|
|
37
|
+
var import_configService = require("./configService");
|
|
38
|
+
var import_helpers = require("../utils/helpers");
|
|
39
|
+
var import_logger = require("../utils/logger");
|
|
40
|
+
async function preflight(arg1, arg2, opts = {}) {
|
|
41
|
+
const { organisation, tenant } = (0, import_helpers.resolveTenantWithOrgMapping)(arg1, arg2);
|
|
42
|
+
return preflightForPair(organisation, tenant, opts);
|
|
43
|
+
}
|
|
44
|
+
async function preflightForPair(organisation, tenant, opts = {}) {
|
|
45
|
+
const validation = await validatePairing(organisation, tenant);
|
|
46
|
+
const routeIsDead = validation.status === "pair-refuted" || validation.status === "org-unknown";
|
|
47
|
+
if (routeIsDead && !(0, import_configService.getCredential)(tenant)) {
|
|
48
|
+
reportDeadRoute(validation, organisation, tenant);
|
|
49
|
+
process.exit(1);
|
|
50
|
+
}
|
|
51
|
+
const clientResult = validation.status === "jwt-validated" ? await (0, import_farseerFactory.getFarseerClient)(organisation, tenant) : await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
|
|
52
|
+
if (!clientResult) {
|
|
53
|
+
if (routeIsDead) {
|
|
54
|
+
reportDeadRoute(validation, organisation, tenant);
|
|
55
|
+
} else {
|
|
56
|
+
(0, import_farseerFactory.showLoginPrompt)(tenant);
|
|
57
|
+
}
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
if (validation.status === "jwt-validated") {
|
|
61
|
+
(0, import_configService.saveTenantOrgMapping)(tenant, organisation);
|
|
62
|
+
}
|
|
63
|
+
if (opts.requiresWorkspace) {
|
|
64
|
+
ensureWorkspaceOrExit(tenant);
|
|
65
|
+
}
|
|
66
|
+
return { organisation, tenant, client: clientResult.client, authType: clientResult.authType };
|
|
67
|
+
}
|
|
68
|
+
async function validatePairing(organisation, tenant) {
|
|
69
|
+
const accessToken = await (0, import_farseerFactory.getFreshAccessToken)();
|
|
70
|
+
if (!accessToken) {
|
|
71
|
+
return { status: "unvalidated" };
|
|
72
|
+
}
|
|
73
|
+
const check = await (0, import_farseerFactory.checkTenantAtOrganisation)(organisation, tenant, accessToken);
|
|
74
|
+
switch (check.status) {
|
|
75
|
+
case "ok":
|
|
76
|
+
return { status: "jwt-validated" };
|
|
77
|
+
case "tenant-unknown":
|
|
78
|
+
return { status: "pair-refuted", orgTenants: await (0, import_farseerFactory.fetchOrganizationTenants)(organisation, accessToken) };
|
|
79
|
+
case "no-such-org":
|
|
80
|
+
return { status: "org-unknown" };
|
|
81
|
+
case "unauthorized":
|
|
82
|
+
return { status: "unvalidated" };
|
|
83
|
+
case "unreachable":
|
|
84
|
+
import_logger.logger.dim(`Could not verify that "${tenant}" belongs to "${organisation}"; proceeding.`);
|
|
85
|
+
return { status: "unvalidated" };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function reportDeadRoute(validation, organisation, tenant) {
|
|
89
|
+
if (validation.status === "org-unknown") {
|
|
90
|
+
import_logger.logger.error(`No Farseer organisation at "${organisation}".`);
|
|
91
|
+
import_logger.logger.dim("Check the spelling, then pass the pair explicitly:");
|
|
92
|
+
import_logger.logger.dim(` farseer <command> <organisation> ${tenant}`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
import_logger.logger.error(`Tenant "${tenant}" is not available under organisation "${organisation}".`);
|
|
96
|
+
if (validation.status === "pair-refuted" && validation.orgTenants.length > 0) {
|
|
97
|
+
import_logger.logger.dim(`Tenants you can access under ${organisation}: ${validation.orgTenants.join(", ")}`);
|
|
98
|
+
}
|
|
99
|
+
import_logger.logger.dim("Either the organisation is wrong for this tenant (set FARSEER_ORG or pass <org> <tenant>),");
|
|
100
|
+
import_logger.logger.dim("or you don't have access to it \u2014 check you're logged in with the right account.");
|
|
101
|
+
}
|
|
102
|
+
function ensureWorkspaceOrExit(tenant) {
|
|
103
|
+
const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
|
|
104
|
+
if (!fs.existsSync(filesDir)) {
|
|
105
|
+
import_logger.logger.error(`No local workspace for tenant "${tenant}".`);
|
|
106
|
+
import_logger.logger.dim(`Run "farseer pull ${tenant}" to set it up first.`);
|
|
107
|
+
process.exit(1);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
111
|
+
0 && (module.exports = {
|
|
112
|
+
preflight,
|
|
113
|
+
preflightForPair
|
|
114
|
+
});
|
|
115
|
+
//# sourceMappingURL=preflight.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/preflight.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Shared per-command preflight: resolve the target, confirm the organisation has\n * that tenant, return an authenticated client, and \u2014 for commands that touch\n * local files \u2014 check the workspace exists. Every command that talks to a tenant\n * runs it; `install` is the exception (local npm only).\n *\n * The contract: if this returns, the credentials work and the org/tenant pair is\n * real. It does not prove the caller may perform a given operation \u2014 that\n * surfaces on the command's own first call \u2014 and on the API-key path the\n * organisation is never checked at all, since the credential carries its own host.\n *\n * Nothing is cached. A remembered \"this pair was fine once\" would hide a tenant\n * that moved organisations, and the check is already paid for: see\n * checkTenantAtOrganisation, which is where the org question is actually asked.\n *\n * TECH DEBT: returns an `IFarseerClient`, which suits the sync commands; the\n * read/query commands need the native SDK client and build a second one from the\n * validated pair. Unifying the two stacks is a follow-up \u2014 see\n * getNativeFarseerClient.\n */\n\nimport * as fs from 'fs';\nimport type { IFarseerClient } from './farseerFactory';\nimport {\n checkTenantAtOrganisation,\n fetchOrganizationTenants,\n getFarseerClient,\n getFarseerClientWithFallback,\n getFreshAccessToken,\n showLoginPrompt,\n} from './farseerFactory';\nimport { getCredential, saveTenantOrgMapping } from './configService';\nimport { resolveTenantWithOrgMapping, getTenantFilesDir } from '../utils/helpers';\nimport { logger } from '../utils/logger';\n\nexport interface PreflightResult {\n organisation: string;\n tenant: string;\n client: IFarseerClient;\n authType: 'jwt' | 'apiKey';\n}\n\nexport interface PreflightOpts {\n // Set by commands that read or write local files. `pull` leaves it unset \u2014\n // it creates the workspace itself.\n requiresWorkspace?: boolean;\n}\n\n/**\n * Entry point for commands whose positional args are `[org] [tenant]`. Variadic\n * ones (run/app) resolve the pair themselves and call preflightForPair.\n */\nexport async function preflight(arg1?: string, arg2?: string, opts: PreflightOpts = {}): Promise<PreflightResult> {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n return preflightForPair(organisation, tenant, opts);\n}\n\n/**\n * Same checks for an already-resolved pair, and the only place that exits.\n */\nexport async function preflightForPair(\n organisation: string,\n tenant: string,\n opts: PreflightOpts = {},\n): Promise<PreflightResult> {\n const validation = await validatePairing(organisation, tenant);\n const routeIsDead = validation.status === 'pair-refuted' || validation.status === 'org-unknown';\n\n // An API key carries its own host, so it's the one thing that still works\n // once the org route is dead. Without one, refuse now rather than spend a\n // round trip confirming what the org already said.\n if (routeIsDead && !getCredential(tenant)) {\n reportDeadRoute(validation, organisation, tenant);\n process.exit(1);\n }\n\n // A 200 already proved the token, so that path needs no second probe.\n const clientResult =\n validation.status === 'jwt-validated'\n ? await getFarseerClient(organisation, tenant)\n : await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n // Reaching here with a dead route means the API key we deferred to also\n // failed; a login prompt would point at the one thing that isn't broken.\n if (routeIsDead) {\n reportDeadRoute(validation, organisation, tenant);\n } else {\n showLoginPrompt(tenant);\n }\n process.exit(1);\n }\n\n // Only what the org confirmed. The other outcomes can still succeed on an\n // API key, which ignores the org \u2014 so success there proves nothing about the\n // org that was typed, and recording it would pin a bad host to this tenant.\n if (validation.status === 'jwt-validated') {\n saveTenantOrgMapping(tenant, organisation);\n }\n\n if (opts.requiresWorkspace) {\n ensureWorkspaceOrExit(tenant);\n }\n\n return { organisation, tenant, client: clientResult.client, authType: clientResult.authType };\n}\n\n// `orgTenants` is what the org does have, for the error message \u2014 empty when the\n// caller isn't allowed to enumerate them, which weakens the hint, not the\n// refusal. `unvalidated` means we couldn't ask, not that the answer was no.\ntype ValidationOutcome =\n | { status: 'jwt-validated' }\n | { status: 'pair-refuted'; orgTenants: string[] }\n | { status: 'org-unknown' }\n | { status: 'unvalidated' };\n\n/**\n * Ask the organisation whether it has this tenant. Browser-login only \u2014 an API\n * key ignores the org, so there is nothing to ask about.\n *\n * Reports, never decides: no path here exits. The answer is definitive both ways\n * \u2014 see checkTenantAtOrganisation for why the tenant header is what makes it so.\n */\nasync function validatePairing(organisation: string, tenant: string): Promise<ValidationOutcome> {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n return { status: 'unvalidated' };\n }\n\n const check = await checkTenantAtOrganisation(organisation, tenant, accessToken);\n\n switch (check.status) {\n case 'ok':\n return { status: 'jwt-validated' };\n\n case 'tenant-unknown':\n // Only now spend a second request, to name what the org does have.\n return { status: 'pair-refuted', orgTenants: await fetchOrganizationTenants(organisation, accessToken) };\n\n case 'no-such-org':\n return { status: 'org-unknown' };\n\n case 'unauthorized':\n // Say nothing \u2014 let the client factory try an API key, or prompt.\n return { status: 'unvalidated' };\n\n case 'unreachable':\n logger.dim(`Could not verify that \"${tenant}\" belongs to \"${organisation}\"; proceeding.`);\n return { status: 'unvalidated' };\n }\n}\n\n/** Says which way the org route is dead, and what to do about it. */\nfunction reportDeadRoute(validation: ValidationOutcome, organisation: string, tenant: string): void {\n if (validation.status === 'org-unknown') {\n logger.error(`No Farseer organisation at \"${organisation}\".`);\n logger.dim('Check the spelling, then pass the pair explicitly:');\n logger.dim(` farseer <command> <organisation> ${tenant}`);\n return;\n }\n\n logger.error(`Tenant \"${tenant}\" is not available under organisation \"${organisation}\".`);\n if (validation.status === 'pair-refuted' && validation.orgTenants.length > 0) {\n logger.dim(`Tenants you can access under ${organisation}: ${validation.orgTenants.join(', ')}`);\n }\n logger.dim('Either the organisation is wrong for this tenant (set FARSEER_ORG or pass <org> <tenant>),');\n logger.dim(\"or you don't have access to it \u2014 check you're logged in with the right account.\");\n}\n\n/** For commands that read or write local files. */\nfunction ensureWorkspaceOrExit(tenant: string): void {\n const filesDir = getTenantFilesDir(tenant);\n if (!fs.existsSync(filesDir)) {\n logger.error(`No local workspace for tenant \"${tenant}\".`);\n logger.dim(`Run \"farseer pull ${tenant}\" to set it up first.`);\n process.exit(1);\n }\n}\n"],
|
|
5
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["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'webp',\n // Archives / columnar data\n 'zip',\n 'parquet',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment, lowercased. This means:\n * - `foo.ts` \u2192 `ts`\n * - `Foo.TS` \u2192 `ts` (case-insensitive \u2014 backend folds case before lookup)\n * - `.gitignore` \u2192 `gitignore` (rejected, not in whitelist)\n * - `Makefile` \u2192 `makefile` (rejected \u2014 no `.`, returns the basename lowercased)\n * - `archive.tar.gz` \u2192 `gz` (rejected)\n */\nexport function getBackendExtension(fileName: string): string {\n const base = path.basename(fileName);\n const parts = base.split('.');\n return parts[parts.length - 1].toLowerCase();\n}\n\nexport function isExtensionAllowed(fileName: string): boolean {\n return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));\n}\n\nexport interface ValidatedFile {\n filePath: string;\n size: number;\n /**\n * Optional file content. When provided, the validator additionally\n * checks for unresolved git-style conflict markers (left behind by a\n * `merge_markers` pull resolution that the user hasn't cleaned up).\n * Push pre-flight passes content; tests/abstract callers can omit it.\n */\n content?: Buffer;\n}\n\n/**\n * Validate a single file the CLI is about to upload. Returns null when the\n * file would pass the backend's create/update validation, otherwise a\n * `ValidationFailure` describing the rule that would reject it.\n *\n * `size` is required so we can also flag empty files: the backend's\n * multipart parser tends to surface a content-less request as the cryptic\n * `{\"code\":\"BadRequest\"}` body that field reports point to.\n */\nexport function validateFileForUpload(file: ValidatedFile): ValidationFailure | null {\n const baseName = path.basename(file.filePath);\n const trimmed = baseName.trim();\n\n if (trimmed.length === 0) {\n return {\n filePath: file.filePath,\n reason: 'name_empty',\n detail: 'Filename is empty after trimming whitespace',\n hint: 'Rename the file to a non-empty name before pushing.',\n };\n }\n\n if (trimmed.length > MAX_FILE_NAME_LENGTH) {\n return {\n filePath: file.filePath,\n reason: 'name_too_long',\n detail: `Filename is ${trimmed.length} characters; backend rejects names longer than ${MAX_FILE_NAME_LENGTH}`,\n hint: 'Shorten the filename and try again.',\n };\n }\n\n if (!isExtensionAllowed(baseName)) {\n const ext = getBackendExtension(baseName);\n return {\n filePath: file.filePath,\n reason: 'extension_not_allowed',\n detail: `Extension \".${ext}\" is not in the backend whitelist`,\n hint: `Allowed: ${[...BACKEND_EXTENSION_WHITELIST]\n .map((e) => '.' + e)\n .sort()\n .join(', ')}`,\n };\n }\n\n if (file.size === 0) {\n return {\n filePath: file.filePath,\n reason: 'empty_content',\n detail: 'File is empty (0 bytes)',\n hint: 'Empty files often come back as opaque \"BadRequest\" from the upload endpoint. Add at least one byte before pushing.',\n };\n }\n\n if (file.content && hasUnresolvedConflictMarkers(file.content)) {\n return {\n filePath: file.filePath,\n reason: 'unresolved_conflict_markers',\n detail: 'File contains unresolved git-style conflict markers (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE)',\n hint: \"Open the file, pick which version to keep, remove the marker lines, then 'farseer push' again.\",\n };\n }\n\n return null;\n}\n\n/**\n * Validate a batch and split into pushable + rejected. The push command uses\n * this to render a single grouped message (\"4 file(s) skipped: \u2026\") and exit\n * cleanly without sending any request that we know will fail.\n */\nexport function partitionForUpload(files: ValidatedFile[]): {\n valid: ValidatedFile[];\n rejected: ValidationFailure[];\n} {\n const valid: ValidatedFile[] = [];\n const rejected: ValidationFailure[] = [];\n for (const file of files) {\n const failure = validateFileForUpload(file);\n if (failure) rejected.push(failure);\n else valid.push(file);\n }\n return { valid, rejected };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAsB;AAoBf,MAAM,8BAAmD,oBAAI,IAAI;AAAA;AAAA,EAEpE;AAAA,EACA;AAAA,EACA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,OAAM,KAAK,IAAI;AAAA,EACxB;AACA,SAAO,EAAE,OAAO,SAAS;AAC7B;",
|
|
4
|
+
"sourcesContent": ["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'svg',\n 'webp',\n // Archives / columnar data\n 'zip',\n 'parquet',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment, lowercased. This means:\n * - `foo.ts` \u2192 `ts`\n * - `Foo.TS` \u2192 `ts` (case-insensitive \u2014 backend folds case before lookup)\n * - `.gitignore` \u2192 `gitignore` (rejected, not in whitelist)\n * - `Makefile` \u2192 `makefile` (rejected \u2014 no `.`, returns the basename lowercased)\n * - `archive.tar.gz` \u2192 `gz` (rejected)\n */\nexport function getBackendExtension(fileName: string): string {\n const base = path.basename(fileName);\n const parts = base.split('.');\n return parts[parts.length - 1].toLowerCase();\n}\n\nexport function isExtensionAllowed(fileName: string): boolean {\n return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));\n}\n\nexport interface ValidatedFile {\n filePath: string;\n size: number;\n /**\n * Optional file content. When provided, the validator additionally\n * checks for unresolved git-style conflict markers (left behind by a\n * `merge_markers` pull resolution that the user hasn't cleaned up).\n * Push pre-flight passes content; tests/abstract callers can omit it.\n */\n content?: Buffer;\n}\n\n/**\n * Validate a single file the CLI is about to upload. Returns null when the\n * file would pass the backend's create/update validation, otherwise a\n * `ValidationFailure` describing the rule that would reject it.\n *\n * `size` is required so we can also flag empty files: the backend's\n * multipart parser tends to surface a content-less request as the cryptic\n * `{\"code\":\"BadRequest\"}` body that field reports point to.\n */\nexport function validateFileForUpload(file: ValidatedFile): ValidationFailure | null {\n const baseName = path.basename(file.filePath);\n const trimmed = baseName.trim();\n\n if (trimmed.length === 0) {\n return {\n filePath: file.filePath,\n reason: 'name_empty',\n detail: 'Filename is empty after trimming whitespace',\n hint: 'Rename the file to a non-empty name before pushing.',\n };\n }\n\n if (trimmed.length > MAX_FILE_NAME_LENGTH) {\n return {\n filePath: file.filePath,\n reason: 'name_too_long',\n detail: `Filename is ${trimmed.length} characters; backend rejects names longer than ${MAX_FILE_NAME_LENGTH}`,\n hint: 'Shorten the filename and try again.',\n };\n }\n\n if (!isExtensionAllowed(baseName)) {\n const ext = getBackendExtension(baseName);\n return {\n filePath: file.filePath,\n reason: 'extension_not_allowed',\n detail: `Extension \".${ext}\" is not in the backend whitelist`,\n hint: `Allowed: ${[...BACKEND_EXTENSION_WHITELIST]\n .map((e) => '.' + e)\n .sort()\n .join(', ')}`,\n };\n }\n\n if (file.size === 0) {\n return {\n filePath: file.filePath,\n reason: 'empty_content',\n detail: 'File is empty (0 bytes)',\n hint: 'Empty files often come back as opaque \"BadRequest\" from the upload endpoint. Add at least one byte before pushing.',\n };\n }\n\n if (file.content && hasUnresolvedConflictMarkers(file.content)) {\n return {\n filePath: file.filePath,\n reason: 'unresolved_conflict_markers',\n detail: 'File contains unresolved git-style conflict markers (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE)',\n hint: \"Open the file, pick which version to keep, remove the marker lines, then 'farseer push' again.\",\n };\n }\n\n return null;\n}\n\n/**\n * Validate a batch and split into pushable + rejected. The push command uses\n * this to render a single grouped message (\"4 file(s) skipped: \u2026\") and exit\n * cleanly without sending any request that we know will fail.\n */\nexport function partitionForUpload(files: ValidatedFile[]): {\n valid: ValidatedFile[];\n rejected: ValidationFailure[];\n} {\n const valid: ValidatedFile[] = [];\n const rejected: ValidationFailure[] = [];\n for (const file of files) {\n const failure = validateFileForUpload(file);\n if (failure) rejected.push(failure);\n else valid.push(file);\n }\n return { valid, rejected };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAC;AACvC,aAAW,QAAQ,OAAO;AACtB,UAAM,UAAU,sBAAsB,IAAI;AAC1C,QAAI,QAAS,UAAS,KAAK,OAAO;AAAA,QAC7B,OAAM,KAAK,IAAI;AAAA,EACxB;AACA,SAAO,EAAE,OAAO,SAAS;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/utils/helpers.js
CHANGED
|
@@ -40,6 +40,7 @@ __export(helpers_exports, {
|
|
|
40
40
|
getAppsDir: () => getAppsDir,
|
|
41
41
|
getAuditLogPath: () => getAuditLogPath,
|
|
42
42
|
getCredentialsHint: () => getCredentialsHint,
|
|
43
|
+
getEnvCheckout: () => getEnvCheckout,
|
|
43
44
|
getRelativePath: () => getRelativePath,
|
|
44
45
|
getSyncFilePath: () => getSyncFilePath,
|
|
45
46
|
getTenantAppsDir: () => getTenantAppsDir,
|
|
@@ -253,20 +254,22 @@ function getCredentialsHint(tenant) {
|
|
|
253
254
|
return `Use: farseer login
|
|
254
255
|
Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;
|
|
255
256
|
}
|
|
257
|
+
function getEnvCheckout() {
|
|
258
|
+
const tenant = process.env.FARSEER_TENANT;
|
|
259
|
+
if (!tenant) return null;
|
|
260
|
+
const organisation = process.env.FARSEER_ORG || (0, import_configService.getTenantOrg)(tenant) || tenant;
|
|
261
|
+
if (organisation === tenant) {
|
|
262
|
+
import_logger.logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);
|
|
263
|
+
} else {
|
|
264
|
+
import_logger.logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);
|
|
265
|
+
}
|
|
266
|
+
return { organisation, tenant };
|
|
267
|
+
}
|
|
256
268
|
function resolveOrgAndTenant(tenantArg) {
|
|
257
269
|
if (tenantArg) {
|
|
258
270
|
return { organisation: tenantArg, tenant: tenantArg };
|
|
259
271
|
}
|
|
260
|
-
|
|
261
|
-
if (checkout) {
|
|
262
|
-
if (checkout.organisation === checkout.tenant) {
|
|
263
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant}`);
|
|
264
|
-
} else {
|
|
265
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);
|
|
266
|
-
}
|
|
267
|
-
return checkout;
|
|
268
|
-
}
|
|
269
|
-
return null;
|
|
272
|
+
return getEnvCheckout();
|
|
270
273
|
}
|
|
271
274
|
function resolveTenant(tenantArg) {
|
|
272
275
|
const resolved = resolveOrgAndTenant(tenantArg);
|
|
@@ -276,8 +279,8 @@ function resolveTenantOrExit(tenantArg) {
|
|
|
276
279
|
const tenant = resolveTenant(tenantArg);
|
|
277
280
|
if (!tenant) {
|
|
278
281
|
import_logger.logger.error("No tenant specified.");
|
|
279
|
-
import_logger.logger.dim("
|
|
280
|
-
import_logger.logger.dim("Or
|
|
282
|
+
import_logger.logger.dim("Pass it: farseer <command> <tenant>");
|
|
283
|
+
import_logger.logger.dim("Or set it (per shell): export FARSEER_TENANT=<tenant>");
|
|
281
284
|
process.exit(1);
|
|
282
285
|
}
|
|
283
286
|
return tenant;
|
|
@@ -286,7 +289,6 @@ function resolveTenantWithOrgMapping(arg1, arg2) {
|
|
|
286
289
|
if (arg1 && arg2) {
|
|
287
290
|
const org = arg1;
|
|
288
291
|
const tenant = arg2;
|
|
289
|
-
(0, import_configService.saveTenantOrgMapping)(tenant, org);
|
|
290
292
|
if (org === tenant) {
|
|
291
293
|
import_logger.logger.dim(`Using tenant: ${tenant}`);
|
|
292
294
|
} else {
|
|
@@ -296,44 +298,40 @@ function resolveTenantWithOrgMapping(arg1, arg2) {
|
|
|
296
298
|
}
|
|
297
299
|
if (arg1) {
|
|
298
300
|
const tenant = arg1;
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
301
|
+
const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : void 0;
|
|
302
|
+
const org = envOrg || (0, import_configService.getTenantOrg)(tenant);
|
|
303
|
+
if (org) {
|
|
304
|
+
if (org === tenant) {
|
|
305
|
+
import_logger.logger.dim(`Using tenant: ${tenant}`);
|
|
303
306
|
} else {
|
|
304
|
-
import_logger.logger.dim(`Using tenant: ${tenant} (org: ${
|
|
307
|
+
import_logger.logger.dim(`Using tenant: ${tenant} (org: ${org})`);
|
|
305
308
|
}
|
|
306
|
-
return { organisation:
|
|
309
|
+
return { organisation: org, tenant };
|
|
310
|
+
}
|
|
311
|
+
if ((0, import_configService.getCredential)(tenant)) {
|
|
312
|
+
import_logger.logger.dim(`Using tenant: ${tenant}`);
|
|
313
|
+
return { organisation: tenant, tenant };
|
|
307
314
|
}
|
|
308
315
|
import_logger.logger.error(`Organisation unknown for tenant "${tenant}".`);
|
|
309
|
-
import_logger.logger.dim("
|
|
310
|
-
import_logger.logger.dim(`
|
|
311
|
-
import_logger.logger.dim(` Example: farseer pull jgl tt-hotels-hr-dev`);
|
|
312
|
-
import_logger.logger.dim("");
|
|
313
|
-
import_logger.logger.dim("Or checkout the tenant first:");
|
|
314
|
-
import_logger.logger.dim(` farseer checkout <organisation> <tenant>`);
|
|
316
|
+
import_logger.logger.dim("Pass both: farseer <command> <organisation> <tenant>");
|
|
317
|
+
import_logger.logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);
|
|
315
318
|
process.exit(1);
|
|
316
319
|
}
|
|
317
|
-
const
|
|
318
|
-
if (
|
|
319
|
-
|
|
320
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant}`);
|
|
321
|
-
} else {
|
|
322
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);
|
|
323
|
-
}
|
|
324
|
-
return checkout;
|
|
320
|
+
const envCheckout = getEnvCheckout();
|
|
321
|
+
if (envCheckout) {
|
|
322
|
+
return envCheckout;
|
|
325
323
|
}
|
|
326
324
|
import_logger.logger.error("No tenant specified.");
|
|
327
|
-
import_logger.logger.dim("
|
|
328
|
-
import_logger.logger.dim("Or
|
|
325
|
+
import_logger.logger.dim("Pass it: farseer <command> <tenant>");
|
|
326
|
+
import_logger.logger.dim("Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)");
|
|
329
327
|
process.exit(1);
|
|
330
328
|
}
|
|
331
329
|
function resolveOrgAndTenantOrExit(tenantArg) {
|
|
332
330
|
const resolved = resolveOrgAndTenant(tenantArg);
|
|
333
331
|
if (!resolved) {
|
|
334
332
|
import_logger.logger.error("No tenant specified.");
|
|
335
|
-
import_logger.logger.dim("
|
|
336
|
-
import_logger.logger.dim("Or
|
|
333
|
+
import_logger.logger.dim("Pass it: farseer <command> <tenant>");
|
|
334
|
+
import_logger.logger.dim("Or set it (per shell): export FARSEER_TENANT=<tenant>");
|
|
337
335
|
process.exit(1);
|
|
338
336
|
}
|
|
339
337
|
return resolved;
|
|
@@ -358,16 +356,11 @@ function parseAppArgs(args) {
|
|
|
358
356
|
};
|
|
359
357
|
}
|
|
360
358
|
}
|
|
361
|
-
const
|
|
362
|
-
if (
|
|
363
|
-
if (checkout.organisation === checkout.tenant) {
|
|
364
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant}`);
|
|
365
|
-
} else {
|
|
366
|
-
import_logger.logger.dim(`Using checked-out tenant: ${checkout.tenant} (org: ${checkout.organisation})`);
|
|
367
|
-
}
|
|
359
|
+
const envCheckout = getEnvCheckout();
|
|
360
|
+
if (envCheckout) {
|
|
368
361
|
return {
|
|
369
|
-
organisation:
|
|
370
|
-
tenant:
|
|
362
|
+
organisation: envCheckout.organisation,
|
|
363
|
+
tenant: envCheckout.tenant,
|
|
371
364
|
appName: args.join(" ")
|
|
372
365
|
};
|
|
373
366
|
}
|
|
@@ -379,8 +372,8 @@ function parseAppArgs(args) {
|
|
|
379
372
|
};
|
|
380
373
|
}
|
|
381
374
|
import_logger.logger.error("No tenant specified.");
|
|
382
|
-
import_logger.logger.dim("
|
|
383
|
-
import_logger.logger.dim("Or
|
|
375
|
+
import_logger.logger.dim("Pass it: farseer app show <tenant> <app-name>");
|
|
376
|
+
import_logger.logger.dim("Or set it (per shell): export FARSEER_TENANT=<tenant>");
|
|
384
377
|
process.exit(1);
|
|
385
378
|
}
|
|
386
379
|
const EMPTY_CLIENT_PATTERNS = [
|
|
@@ -491,6 +484,7 @@ function appendToAuditLog(tenant, entries) {
|
|
|
491
484
|
getAppsDir,
|
|
492
485
|
getAuditLogPath,
|
|
493
486
|
getCredentialsHint,
|
|
487
|
+
getEnvCheckout,
|
|
494
488
|
getRelativePath,
|
|
495
489
|
getSyncFilePath,
|
|
496
490
|
getTenantAppsDir,
|