farseer-cli 1.9.1 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +37 -33
  2. package/dist/commands/app.js +11 -37
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/apps.js +3 -9
  5. package/dist/commands/apps.js.map +2 -2
  6. package/dist/commands/cells.js +3 -11
  7. package/dist/commands/cells.js.map +2 -2
  8. package/dist/commands/config.js +4 -4
  9. package/dist/commands/config.js.map +2 -2
  10. package/dist/commands/dashboards.js +3 -11
  11. package/dist/commands/dashboards.js.map +2 -2
  12. package/dist/commands/diff.js +3 -7
  13. package/dist/commands/diff.js.map +2 -2
  14. package/dist/commands/dimensions.js +9 -31
  15. package/dist/commands/dimensions.js.map +2 -2
  16. package/dist/commands/files.js +4 -9
  17. package/dist/commands/files.js.map +2 -2
  18. package/dist/commands/formula.js +2 -6
  19. package/dist/commands/formula.js.map +2 -2
  20. package/dist/commands/list.js +4 -9
  21. package/dist/commands/list.js.map +2 -2
  22. package/dist/commands/model.js +2 -8
  23. package/dist/commands/model.js.map +2 -2
  24. package/dist/commands/pull.js +16 -9
  25. package/dist/commands/pull.js.map +2 -2
  26. package/dist/commands/push.js +5 -9
  27. package/dist/commands/push.js.map +2 -2
  28. package/dist/commands/refresh.js +3 -8
  29. package/dist/commands/refresh.js.map +2 -2
  30. package/dist/commands/run.js +3 -6
  31. package/dist/commands/run.js.map +2 -2
  32. package/dist/commands/sheets.js +5 -21
  33. package/dist/commands/sheets.js.map +2 -2
  34. package/dist/commands/status.js +4 -9
  35. package/dist/commands/status.js.map +2 -2
  36. package/dist/commands/variables.js +8 -30
  37. package/dist/commands/variables.js.map +2 -2
  38. package/dist/commands/whoami.js +11 -0
  39. package/dist/commands/whoami.js.map +2 -2
  40. package/dist/index.js +22 -23
  41. package/dist/index.js.map +2 -2
  42. package/dist/mcp/resources/documentation.js +1 -1
  43. package/dist/mcp/resources/documentation.js.map +1 -1
  44. package/dist/mcp/server.js +1 -1
  45. package/dist/mcp/server.js.map +1 -1
  46. package/dist/mcp/tools/appTools.js +6 -4
  47. package/dist/mcp/tools/appTools.js.map +2 -2
  48. package/dist/mcp/tools/dataTools.js +1 -1
  49. package/dist/mcp/tools/dataTools.js.map +2 -2
  50. package/dist/mcp/utils/helpers.js.map +2 -2
  51. package/dist/mcp/utils/launchPin.js.map +2 -2
  52. package/dist/services/configService.js +0 -45
  53. package/dist/services/configService.js.map +2 -2
  54. package/dist/services/farseerApi.js +49 -7
  55. package/dist/services/farseerApi.js.map +3 -3
  56. package/dist/services/farseerFactory.js +79 -0
  57. package/dist/services/farseerFactory.js.map +3 -3
  58. package/dist/services/farseerService.js +24 -8
  59. package/dist/services/farseerService.js.map +2 -2
  60. package/dist/services/preflight.js +115 -0
  61. package/dist/services/preflight.js.map +7 -0
  62. package/dist/utils/fileValidation.js +2 -0
  63. package/dist/utils/fileValidation.js.map +2 -2
  64. package/dist/utils/helpers.js +42 -48
  65. package/dist/utils/helpers.js.map +2 -2
  66. package/dist/utils/workspace.js +1 -1
  67. package/dist/utils/workspace.js.map +2 -2
  68. package/docs/api-reference.md +3 -3
  69. package/docs/arquero-patterns.md +1 -1
  70. package/docs/cli-guide.md +14 -9
  71. package/docs/how-farseer-works.md +1 -1
  72. package/docs/import-workflows.md +3 -3
  73. package/docs/new-app-template.md +1 -1
  74. package/docs/query-formulas.md +1 -1
  75. package/package.json +1 -1
  76. package/dist/commands/checkout.js +0 -189
  77. package/dist/commands/checkout.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/utils/launchPin.ts"],
4
- "sourcesContent": ["/**\n * Launch-time tenant resolution for the MCP server.\n *\n * Precedence: --tenant flag > FARSEER_TENANT env. Org: --org > FARSEER_ORG >\n * the saved tenant->org mapping > the tenant. Env is read only on this launch\n * path (never globally), so a stray FARSEER_TENANT in the shell can't retarget\n * other `farseer` commands. FARSEER_TENANT is the channel Mindseer already\n * injects per server (bfm2000 apps/main/src/services/MCPService.ts), so honoring\n * it lets that host bind a tenant with no `--tenant` in the args.\n */\nimport type { CurrentCheckout } from '../../services/configService';\nimport { getTenantOrg } from '../../services/configService';\n\nexport interface McpServerOptions {\n /** Tenant to bind at launch (X-TENANT-ID). From --tenant, else FARSEER_TENANT. */\n tenant?: string;\n /** Organisation subdomain. From --org, else FARSEER_ORG, else the mapping/tenant. */\n org?: string;\n}\n\n/**\n * Resolve the launch-time tenant pin from flags + env, or undefined if none was\n * provided (the server then starts unbound and waits for farseer_select_tenant).\n */\nexport function resolveLaunchPin(options: McpServerOptions, env: NodeJS.ProcessEnv): CurrentCheckout | undefined {\n const tenant = options.tenant || env.FARSEER_TENANT;\n if (!tenant) {\n // An org with no tenant binds nothing; warn so it isn't a silent no-op.\n // stderr is safe here \u2014 stdout carries the MCP protocol.\n const org = options.org || env.FARSEER_ORG;\n if (org) {\n process.stderr.write(\n `farseer mcp-server: organisation \"${org}\" was provided without a tenant ` +\n `(--tenant / FARSEER_TENANT); ignoring it and starting unbound.\\n`,\n );\n }\n return undefined;\n }\n const organisation = options.org || env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n return { organisation, tenant };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,2BAA6B;AAatB,SAAS,iBAAiB,SAA2B,KAAqD;AAC7G,QAAM,SAAS,QAAQ,UAAU,IAAI;AACrC,MAAI,CAAC,QAAQ;AAGT,UAAM,MAAM,QAAQ,OAAO,IAAI;AAC/B,QAAI,KAAK;AACL,cAAQ,OAAO;AAAA,QACX,qCAAqC,GAAG;AAAA;AAAA,MAE5C;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AACA,QAAM,eAAe,QAAQ,OAAO,IAAI,mBAAe,mCAAa,MAAM,KAAK;AAC/E,SAAO,EAAE,cAAc,OAAO;AAClC;",
4
+ "sourcesContent": ["/**\n * Launch-time tenant resolution for the MCP server.\n *\n * Precedence: --tenant flag > FARSEER_TENANT env. Org: --org > FARSEER_ORG >\n * the saved tenant->org mapping > the tenant. The CLI's command resolvers read\n * the same FARSEER_TENANT/FARSEER_ORG (utils/helpers.ts getEnvCheckout), so a\n * shell that sets them targets the same tenant whether you run a `farseer`\n * command or launch this server from it \u2014 one vocabulary across both worlds.\n * This launch pin stays the ONLY place the MCP server reads the env: once\n * bound, the server is locked to that tenant for its lifetime and never\n * re-reads it. FARSEER_TENANT is also the channel Mindseer already injects per\n * server (bfm2000 apps/main/src/services/MCPService.ts), so honoring it lets\n * that host bind a tenant with no `--tenant` in the args.\n */\nimport type { CurrentCheckout } from '../../services/configService';\nimport { getTenantOrg } from '../../services/configService';\n\nexport interface McpServerOptions {\n /** Tenant to bind at launch (X-TENANT-ID). From --tenant, else FARSEER_TENANT. */\n tenant?: string;\n /** Organisation subdomain. From --org, else FARSEER_ORG, else the mapping/tenant. */\n org?: string;\n}\n\n/**\n * Resolve the launch-time tenant pin from flags + env, or undefined if none was\n * provided (the server then starts unbound and waits for farseer_select_tenant).\n */\nexport function resolveLaunchPin(options: McpServerOptions, env: NodeJS.ProcessEnv): CurrentCheckout | undefined {\n const tenant = options.tenant || env.FARSEER_TENANT;\n if (!tenant) {\n // An org with no tenant binds nothing; warn so it isn't a silent no-op.\n // stderr is safe here \u2014 stdout carries the MCP protocol.\n const org = options.org || env.FARSEER_ORG;\n if (org) {\n process.stderr.write(\n `farseer mcp-server: organisation \"${org}\" was provided without a tenant ` +\n `(--tenant / FARSEER_TENANT); ignoring it and starting unbound.\\n`,\n );\n }\n return undefined;\n }\n const organisation = options.org || env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n return { organisation, tenant };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,2BAA6B;AAatB,SAAS,iBAAiB,SAA2B,KAAqD;AAC7G,QAAM,SAAS,QAAQ,UAAU,IAAI;AACrC,MAAI,CAAC,QAAQ;AAGT,UAAM,MAAM,QAAQ,OAAO,IAAI;AAC/B,QAAI,KAAK;AACL,cAAQ,OAAO;AAAA,QACX,qCAAqC,GAAG;AAAA;AAAA,MAE5C;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AACA,QAAM,eAAe,QAAQ,OAAO,IAAI,mBAAe,mCAAa,MAAM,KAAK;AAC/E,SAAO,EAAE,cAAc,OAAO;AAClC;",
6
6
  "names": []
7
7
  }
@@ -28,13 +28,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var configService_exports = {};
30
30
  __export(configService_exports, {
31
- clearCurrentTenant: () => clearCurrentTenant,
32
31
  clearUserAuth: () => clearUserAuth,
33
32
  generateBasePath: () => generateBasePath,
34
33
  getCredential: () => getCredential,
35
- getCurrentCheckout: () => getCurrentCheckout,
36
- getCurrentOrganisation: () => getCurrentOrganisation,
37
- getCurrentTenant: () => getCurrentTenant,
38
34
  getSyncIncludes: () => getSyncIncludes,
39
35
  getTenantOrg: () => getTenantOrg,
40
36
  getUserAuth: () => getUserAuth,
@@ -45,8 +41,6 @@ __export(configService_exports, {
45
41
  saveConfig: () => saveConfig,
46
42
  saveTenantOrgMapping: () => saveTenantOrgMapping,
47
43
  setCredential: () => setCredential,
48
- setCurrentCheckout: () => setCurrentCheckout,
49
- setCurrentTenant: () => setCurrentTenant,
50
44
  setSyncIncludes: () => setSyncIncludes,
51
45
  setUserAuth: () => setUserAuth
52
46
  });
@@ -129,39 +123,6 @@ function isUserAuthValid() {
129
123
  function generateBasePath(organisation) {
130
124
  return `https://${organisation}.farseer.io/api/v3`;
131
125
  }
132
- function getCurrentCheckout() {
133
- const config = loadConfig();
134
- if (config.currentCheckout) {
135
- return config.currentCheckout;
136
- }
137
- if (config.currentTenant) {
138
- return { organisation: config.currentTenant, tenant: config.currentTenant };
139
- }
140
- return void 0;
141
- }
142
- function getCurrentTenant() {
143
- const checkout = getCurrentCheckout();
144
- return checkout?.tenant;
145
- }
146
- function getCurrentOrganisation() {
147
- const checkout = getCurrentCheckout();
148
- return checkout?.organisation;
149
- }
150
- function setCurrentCheckout(organisation, tenant) {
151
- const config = loadConfig();
152
- config.currentCheckout = { organisation, tenant };
153
- config.currentTenant = tenant;
154
- saveConfig(config);
155
- }
156
- function setCurrentTenant(tenant) {
157
- setCurrentCheckout(tenant, tenant);
158
- }
159
- function clearCurrentTenant() {
160
- const config = loadConfig();
161
- config.currentTenant = void 0;
162
- config.currentCheckout = void 0;
163
- saveConfig(config);
164
- }
165
126
  function saveTenantOrgMapping(tenant, organisation) {
166
127
  const config = loadConfig();
167
128
  if (!config.tenantOrgMapping) {
@@ -197,13 +158,9 @@ function setSyncIncludes(tenant, includes) {
197
158
  }
198
159
  // Annotate the CommonJS export names for ESM import in node:
199
160
  0 && (module.exports = {
200
- clearCurrentTenant,
201
161
  clearUserAuth,
202
162
  generateBasePath,
203
163
  getCredential,
204
- getCurrentCheckout,
205
- getCurrentOrganisation,
206
- getCurrentTenant,
207
164
  getSyncIncludes,
208
165
  getTenantOrg,
209
166
  getUserAuth,
@@ -214,8 +171,6 @@ function setSyncIncludes(tenant, includes) {
214
171
  saveConfig,
215
172
  saveTenantOrgMapping,
216
173
  setCredential,
217
- setCurrentCheckout,
218
- setCurrentTenant,
219
174
  setSyncIncludes,
220
175
  setUserAuth
221
176
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/configService.ts"],
4
- "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n userAuth?: UserAuth;\n currentTenant?: string; // Deprecated: use currentCheckout\n currentCheckout?: CurrentCheckout; // Organisation + tenant\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n userAuth: undefined,\n };\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return JSON.parse(content) as FarseerConfig;\n } catch {\n return getDefaultConfig();\n }\n}\n\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const config = loadConfig();\n return config.credentials[tenant];\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(): UserAuth | undefined {\n const config = loadConfig();\n return config.userAuth;\n}\n\nexport function setUserAuth(auth: UserAuth): void {\n const config = loadConfig();\n config.userAuth = auth;\n saveConfig(config);\n}\n\nexport function clearUserAuth(): void {\n const config = loadConfig();\n config.userAuth = undefined;\n saveConfig(config);\n}\n\nexport function isUserAuthValid(): boolean {\n const auth = getUserAuth();\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\nexport function generateBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n// Current checkout management\nexport function getCurrentCheckout(): CurrentCheckout | undefined {\n const config = loadConfig();\n // Support both new and old format\n if (config.currentCheckout) {\n return config.currentCheckout;\n }\n // Fallback to old format (tenant only, assume same as org)\n if (config.currentTenant) {\n return { organisation: config.currentTenant, tenant: config.currentTenant };\n }\n return undefined;\n}\n\nexport function getCurrentTenant(): string | undefined {\n const checkout = getCurrentCheckout();\n return checkout?.tenant;\n}\n\nexport function getCurrentOrganisation(): string | undefined {\n const checkout = getCurrentCheckout();\n return checkout?.organisation;\n}\n\nexport function setCurrentCheckout(organisation: string, tenant: string): void {\n const config = loadConfig();\n config.currentCheckout = { organisation, tenant };\n config.currentTenant = tenant; // Keep for backward compatibility\n saveConfig(config);\n}\n\nexport function setCurrentTenant(tenant: string): void {\n // Assume organisation = tenant when only tenant is specified\n setCurrentCheckout(tenant, tenant);\n}\n\nexport function clearCurrentTenant(): void {\n const config = loadConfig();\n config.currentTenant = undefined;\n config.currentCheckout = undefined;\n saveConfig(config);\n}\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAoCpB,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,cAAc,KAAK,KAAK,YAAY,aAAa;AAEvD,SAAS,kBAAwB;AAC7B,MAAI,CAAC,GAAG,WAAW,UAAU,GAAG;AAC5B,OAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,EAChD;AACJ;AAEA,SAAS,mBAAkC;AACvC,SAAO;AAAA,IACH,aAAa,CAAC;AAAA,IACd,UAAU;AAAA,EACd;AACJ;AAEO,SAAS,aAA4B;AACxC,kBAAgB;AAEhB,MAAI,CAAC,GAAG,WAAW,WAAW,GAAG;AAC7B,WAAO,iBAAiB;AAAA,EAC5B;AAEA,MAAI;AACA,UAAM,UAAU,GAAG,aAAa,aAAa,OAAO;A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CAAC,SAAS,SAAS;AAC3C,WAAO,OAAO,aAAa,MAAM;AAAA,EACrC,OAAO;AACH,WAAO,aAAa,MAAM,IAAI;AAAA,EAClC;AAEA,MAAI,OAAO,KAAK,OAAO,YAAY,EAAE,WAAW,GAAG;AAC/C,WAAO,OAAO;AAAA,EAClB;AACA,aAAW,MAAM;AACrB;",
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n userAuth?: UserAuth;\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n userAuth: undefined,\n };\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return JSON.parse(content) as FarseerConfig;\n } catch {\n return getDefaultConfig();\n }\n}\n\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const config = loadConfig();\n return config.credentials[tenant];\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(): UserAuth | undefined {\n const config = loadConfig();\n return config.userAuth;\n}\n\nexport function setUserAuth(auth: UserAuth): void {\n const config = loadConfig();\n config.userAuth = auth;\n saveConfig(config);\n}\n\nexport function clearUserAuth(): void {\n const config = loadConfig();\n config.userAuth = undefined;\n saveConfig(config);\n}\n\nexport function isUserAuthValid(): boolean {\n const auth = getUserAuth();\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\nexport function generateBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n// There is deliberately no persisted \"current tenant\" any more. A command's\n// target comes from an explicit argument or the FARSEER_TENANT env var (see\n// getEnvCheckout in utils/helpers.ts), and the CLI errors if neither is set\n// rather than falling back to a machine-global default. The tenant->org\n// mapping below is kept: it lets `export FARSEER_TENANT=<tenant>` resolve the\n// org on its own, so only new org != tenant tenants need FARSEER_ORG too.\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAsCpB,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,cAAc,KAAK,KAAK,YAAY,aAAa;AAEvD,SAAS,kBAAwB;AAC7B,MAAI,CAAC,GAAG,WAAW,UAAU,GAAG;AAC5B,OAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,EAChD;AACJ;AAEA,SAAS,mBAAkC;AACvC,SAAO;AAAA,IACH,aAAa,CAAC;AAAA,IACd,UAAU;AAAA,EACd;AACJ;AAEO,SAAS,aAA4B;AACxC,kBAAgB;AAEhB,MAAI,CAAC,GAAG,WAAW,WAAW,GAAG;AAC7B,WAAO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ClC;AAUO,SAAS,qBAAqB,QAAgB,cAA4B;AAC7E,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,OAAO,kBAAkB;AAC1B,WAAO,mBAAmB,CAAC;AAAA,EAC/B;AACA,SAAO,iBAAiB,MAAM,IAAI;AAClC,aAAW,MAAM;AACrB;AAEO,SAAS,aAAa,QAAoC;AAC7D,QAAM,SAAS,WAAW;AAC1B,SAAO,OAAO,mBAAmB,MAAM;AAC3C;AAGO,SAAS,gBAAgB,QAAqC;AACjE,QAAM,SAAS,WAAW;AAC1B,SAAO,OAAO,eAAe,MAAM,KAAK;AAC5C;AAEO,SAAS,gBAAgB,QAAgB,UAA8B;AAC1E,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,OAAO,cAAc;AACtB,WAAO,eAAe,CAAC;AAAA,EAC3B;AAEA,MAAI,SAAS,YAAY,WAAW,EAAG,QAAO,SAAS;AACvD,MAAI,SAAS,SAAS,WAAW,EAAG,QAAO,SAAS;AAEpD,MAAI,CAAC,SAAS,cAAc,CAAC,SAAS,SAAS;AAC3C,WAAO,OAAO,aAAa,MAAM;AAAA,EACrC,OAAO;AACH,WAAO,aAAa,MAAM,IAAI;AAAA,EAClC;AAEA,MAAI,OAAO,KAAK,OAAO,YAAY,EAAE,WAAW,GAAG;AAC/C,WAAO,OAAO;AAAA,EAClB;AACA,aAAW,MAAM;AACrB;",
6
6
  "names": []
7
7
  }
@@ -28,11 +28,15 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var farseerApi_exports = {};
30
30
  __export(farseerApi_exports, {
31
+ AppDeleteRefusedError: () => AppDeleteRefusedError,
31
32
  FarseerApi: () => FarseerApi,
33
+ REMOTE_JOB_ITEM_TYPE: () => REMOTE_JOB_ITEM_TYPE,
32
34
  applySourceFolderChange: () => applySourceFolderChange,
33
35
  findScriptInFolder: () => findScriptInFolder,
34
36
  loadDimensionTableViaEntitiesApi: () => loadDimensionTableViaEntitiesApi,
35
- mergeAppUpdate: () => mergeAppUpdate
37
+ mergeAppUpdate: () => mergeAppUpdate,
38
+ remoteJobReverseReferences: () => remoteJobReverseReferences,
39
+ resolveAppItemNodeId: () => resolveAppItemNodeId
36
40
  });
37
41
  module.exports = __toCommonJS(farseerApi_exports);
38
42
  var import_axios = __toESM(require("axios"));
@@ -117,6 +121,30 @@ async function applySourceFolderChange(client, app, changes, options, caller) {
117
121
  }
118
122
  return null;
119
123
  }
124
+ const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;
125
+ function remoteJobReverseReferences(remoteJobIds) {
126
+ return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));
127
+ }
128
+ class AppDeleteRefusedError extends Error {
129
+ }
130
+ function resolveAppItemNodeId(remoteJobId, items) {
131
+ const matches = items.filter((item2) => item2.reference === remoteJobId);
132
+ if (matches.length === 0) {
133
+ throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);
134
+ }
135
+ if (matches.length > 1) {
136
+ throw new AppDeleteRefusedError(
137
+ `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`
138
+ );
139
+ }
140
+ const item = matches[0];
141
+ if (item.type !== REMOTE_JOB_ITEM_TYPE) {
142
+ throw new AppDeleteRefusedError(
143
+ `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ("${item.name}"), not an app.`
144
+ );
145
+ }
146
+ return item.id;
147
+ }
120
148
  class FarseerApi {
121
149
  constructor(accessToken, tenant, tenantId) {
122
150
  this.isRefreshing = false;
@@ -419,7 +447,6 @@ You may need to use --tenant-id to specify a different tenant ID.`
419
447
  const itemType = item.type.toLowerCase();
420
448
  if (itemType === "remote_job") {
421
449
  apps.push({
422
- id: item.id,
423
450
  name: item.name,
424
451
  type: item.type,
425
452
  reference: item.reference || ""
@@ -502,10 +529,21 @@ You may need to use --tenant-id to specify a different tenant ID.`
502
529
  }
503
530
  return app;
504
531
  }
505
- /**
506
- * Delete an app
507
- */
508
- async deleteApp(itemNodeId) {
532
+ async resolveRemoteJobItems(remoteJobIds) {
533
+ if (remoteJobIds.length === 0) {
534
+ return [];
535
+ }
536
+ const response = await this.client.post(
537
+ "/folders/resolveItems",
538
+ remoteJobReverseReferences(remoteJobIds)
539
+ );
540
+ return response.data ?? [];
541
+ }
542
+ // Takes the Remote Job id and resolves the folder-item id itself, so no
543
+ // caller can hand this a raw node id. See `resolveAppItemNodeId`.
544
+ async deleteApp(remoteJobId) {
545
+ const items = await this.resolveRemoteJobItems([remoteJobId]);
546
+ const itemNodeId = resolveAppItemNodeId(remoteJobId, items);
509
547
  await this.client.post("/folders/deleteItems", [{ id: itemNodeId }]);
510
548
  }
511
549
  /**
@@ -663,10 +701,14 @@ async function loadDimensionTableViaEntitiesApi(nativeClient, name) {
663
701
  }
664
702
  // Annotate the CommonJS export names for ESM import in node:
665
703
  0 && (module.exports = {
704
+ AppDeleteRefusedError,
666
705
  FarseerApi,
706
+ REMOTE_JOB_ITEM_TYPE,
667
707
  applySourceFolderChange,
668
708
  findScriptInFolder,
669
709
  loadDimensionTableViaEntitiesApi,
670
- mergeAppUpdate
710
+ mergeAppUpdate,
711
+ remoteJobReverseReferences,
712
+ resolveAppItemNodeId
671
713
  });
672
714
  //# sourceMappingURL=farseerApi.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/farseerApi.ts"],
4
- "sourcesContent": ["/**\n * FarseerApi - Direct HTTP API client using JWT Bearer token authentication\n *\n * This is an alternative to FarseerService that doesn't use farseer-client library.\n * Use this when authenticating via browser login (Keycloak JWT token) instead of API key.\n */\n\nimport axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport chalk from 'chalk';\nimport * as farseer from 'farseer-client';\nimport { getCredential, getUserAuth, setUserAuth } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { toError } from '../utils/errorFormatter';\nimport { logger } from '../utils/logger';\n\n// RemoteFile lives in farseerFactory.ts (canonical). Re-export so existing\n// imports (`import { RemoteFile } from './farseerApi'`) still resolve, and\n// import locally so this file's own annotations type-check.\nimport type { RemoteFile, OrganizationInfo } from './farseerFactory';\nexport type { RemoteFile };\n\ninterface FolderItem {\n id: number;\n name: string;\n type: 'folder' | 'farseer-file';\n reference?: string;\n}\n\ninterface FolderContent {\n items: FolderItem[];\n}\n\n// App (Remote Job) types \u2014 orthogonal-axes shape:\n// dataType \u2208 { 'string', 'boolean' }\n// fixed?: locked at run time (admin sets, user cannot override)\n// options?: closed allowed-value set (string dataType only)\nexport type AppArgumentDataType = 'string' | 'boolean';\n\nexport interface AppArgument {\n name: string;\n dataType: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport interface AppScriptFile {\n id: string;\n name: string;\n}\n\n// A resolved source folder: its node id (to set on the app) plus the script\n// files it contains (to validate an entrypoint lives inside it).\nexport interface SourceFolderResolution {\n id: number;\n scripts: AppScriptFile[];\n}\n\nexport interface RemoteApp {\n id: number;\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n status: string;\n lastHeartbeat: string;\n mainScriptFileId: string | null;\n scriptFiles?: AppScriptFile[];\n sourceFolderId?: number;\n schedule?: string | null;\n runnerName?: string | null;\n runnerImage?: string | null;\n creationType: string;\n predefinedActions: unknown[];\n}\n\n// The fields a Remote Job update writes. The backend PUT replaces the whole\n// row, so any field omitted here is reset to its default (args/predefined \u2192\n// empty, the rest \u2192 null). `mergeAppUpdate` exists so a caller that only wants\n// to touch one field doesn't silently wipe the others.\nexport interface UpdateAppPayload {\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n mainScriptFileId: string | null;\n sourceFolderId: number | null;\n schedule: string | null;\n runnerName: string | null;\n runnerImage: string | null;\n predefinedActions: unknown[];\n}\n\n// `scriptFileIds` is accepted from callers for backwards compatibility but is\n// never sent \u2014 the backend ignores it (scripts derive from the source folder).\nexport type AppUpdateChanges = Partial<UpdateAppPayload> & { scriptFileIds?: string[] };\n\n/**\n * Overlay a caller's changes onto an app's current state to build a full,\n * non-destructive update payload. Every field the caller leaves out keeps its\n * current value \u2014 so changing one setting never clears the others.\n */\nexport function mergeAppUpdate(current: RemoteApp, changes: AppUpdateChanges): UpdateAppPayload {\n return {\n name: changes.name ?? current.name,\n description: changes.description ?? current.description ?? '',\n expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],\n mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,\n sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,\n schedule: changes.schedule ?? current.schedule ?? null,\n runnerName: changes.runnerName ?? current.runnerName ?? null,\n runnerImage: changes.runnerImage ?? current.runnerImage ?? null,\n predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? [],\n };\n}\n\n/**\n * Find a script in a source folder's file list by its exact name. Farseer file\n * names are case-sensitive \u2014 two files differing only in case can coexist in a\n * folder \u2014 so matching is exact, never case-folded, to avoid resolving an\n * entrypoint to the wrong file. Resolution is folder-scoped, never tenant-wide,\n * so a same-named file in another folder can't be picked by accident. Returns\n * undefined when the name isn't in the folder.\n */\nexport function findScriptInFolder(folderScripts: AppScriptFile[], name: string): AppScriptFile | undefined {\n return folderScripts.find((s) => s.name === name);\n}\n\n// The one client capability applySourceFolderChange needs. Kept minimal (not the\n// whole client) so it is trivial to unit-test with a fake resolver.\nexport interface SourceFolderResolver {\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n}\n\n// Selects only how an error is presented \u2014 dimming, and `--flag` (CLI) vs param\n// (MCP) wording. It is a pure UX knob: the decision, the ids written to `changes`,\n// and the success/failure outcome are identical for both values. Never branch\n// functionality on it.\nexport type ConfigureCaller = 'cli' | 'mcp';\n\n/**\n * Resolve the source-folder / entrypoint settings for an `app configure` and\n * write the resulting ids into `changes`, applying the rule that an app's\n * scripts derive from its source folder and the entrypoint must be a file in\n * that folder. `sourceFolder` (a path under Files/) switches the folder;\n * otherwise the entrypoint is validated against the app's current folder. Moving\n * the folder must not orphan the entrypoint: if the current entrypoint isn't in\n * the new folder and the caller didn't supply one, the request is rejected \u2014 the\n * entrypoint is never silently cleared or relocated.\n *\n * Returns an error message for the caller to surface (and `changes` is left\n * untouched), or null once the ids have been written. The decision lives here so\n * the CLI and MCP paths can't drift. `caller` affects only how an error reads\n * (dimming, `--flag` vs param wording) \u2014 never which errors fire or what gets\n * written \u2014 so the two surfaces stay behaviourally identical.\n */\nexport async function applySourceFolderChange(\n client: SourceFolderResolver,\n app: Pick<RemoteApp, 'scriptFiles' | 'mainScriptFileId'>,\n changes: AppUpdateChanges,\n options: { sourceFolder?: string; entrypoint?: string },\n caller: ConfigureCaller,\n): Promise<string | null> {\n const cli = caller === 'cli';\n // Secondary guidance lines are dimmed in the terminal; plain for the MCP tool.\n const hint = (text: string) => (cli ? chalk.dim(text) : text);\n\n let folderScripts = app.scriptFiles ?? [];\n let sourceFolderId: number | undefined;\n\n if (options.sourceFolder) {\n let resolved: SourceFolderResolution;\n try {\n resolved = await client.resolveSourceFolder(options.sourceFolder);\n } catch {\n return [\n `Source folder not found under Files/: ${options.sourceFolder}`,\n hint('Use a path relative to Files/, e.g. \"Scripts/MyApp\".'),\n ].join('\\n');\n }\n sourceFolderId = resolved.id;\n folderScripts = resolved.scripts;\n\n // Moving the folder must not leave the entrypoint pointing outside it.\n if (!options.entrypoint && app.mainScriptFileId) {\n const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);\n if (!stillThere) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n return [\n \"The app's current entrypoint is not in the new source folder.\",\n hint(\n cli\n ? 'Pass --entrypoint <script> (a file in the new folder) in the same command.'\n : 'Pass \"entrypoint\" (a file in the new folder) in the same call.',\n ),\n hint(`Files in this folder: ${files}`),\n ].join('\\n');\n }\n }\n }\n\n let mainScriptFileId: string | undefined;\n if (options.entrypoint) {\n const match = findScriptInFolder(folderScripts, options.entrypoint);\n if (!match) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n const lines = [\n `Entrypoint not found in the source folder: ${options.entrypoint}`,\n hint(`Files in this folder: ${files}`),\n ];\n if (!options.sourceFolder) {\n lines.push(\n hint(\n cli\n ? 'To use a file from another folder, set it first with --source-folder <path>.'\n : 'To use a file from another folder, pass sourceFolder first.',\n ),\n );\n }\n return lines.join('\\n');\n }\n mainScriptFileId = match.id;\n }\n\n // Apply only after every check passes, so a rejected request never partially\n // mutates `changes`.\n if (sourceFolderId !== undefined) {\n changes.sourceFolderId = sourceFolderId;\n }\n if (mainScriptFileId !== undefined) {\n changes.mainScriptFileId = mainScriptFileId;\n }\n return null;\n}\n\nexport interface AppListItem {\n id: number;\n name: string;\n type: string;\n reference: string;\n}\n\nexport class FarseerApi {\n private client: AxiosInstance;\n private tenant: string;\n private tenantId: string;\n private basePath: string;\n private accessToken: string;\n\n private isRefreshing = false;\n private refreshSubscribers: ((token: string) => void)[] = [];\n\n constructor(accessToken: string, tenant: string, tenantId?: string) {\n this.tenant = tenant;\n this.tenantId = tenantId || tenant;\n this.accessToken = accessToken;\n\n // Try to get basePath from existing config, or generate from tenant name\n const credential = getCredential(tenant);\n const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;\n this.basePath = basePath;\n\n this.client = axios.create({\n baseURL: basePath,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'x-api-version': '3.3.0',\n 'X-TENANT-ID': this.tenantId,\n },\n });\n\n // Add response interceptor for automatic token refresh on 401\n this.client.interceptors.response.use(\n (response) => response,\n async (error) => {\n const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };\n\n // Only handle 401 errors and avoid infinite loops\n if (error.response?.status === 401 && !originalRequest._retry) {\n originalRequest._retry = true;\n\n // If already refreshing, wait for the new token\n if (this.isRefreshing) {\n return new Promise((resolve) => {\n this.refreshSubscribers.push((token: string) => {\n originalRequest.headers['Authorization'] = `Bearer ${token}`;\n resolve(this.client(originalRequest));\n });\n });\n }\n\n this.isRefreshing = true;\n\n try {\n const auth = getUserAuth();\n if (!auth?.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n throw new Error('Token refresh failed');\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update this client's token\n this.updateAccessToken(refreshed.accessToken);\n\n // Notify all waiting requests\n this.refreshSubscribers.forEach((callback) => callback(refreshed.accessToken));\n this.refreshSubscribers = [];\n\n // Retry the original request\n originalRequest.headers['Authorization'] = `Bearer ${refreshed.accessToken}`;\n return this.client(originalRequest);\n } catch (refreshError) {\n // Token refresh failed - let the error propagate\n this.refreshSubscribers = [];\n throw error;\n } finally {\n this.isRefreshing = false;\n }\n }\n\n return Promise.reject(error);\n },\n );\n }\n\n /**\n * Update the access token (used when token is refreshed)\n */\n updateAccessToken(newToken: string): void {\n this.accessToken = newToken;\n this.client.defaults.headers['Authorization'] = `Bearer ${newToken}`;\n }\n\n async testConnection(): Promise<boolean> {\n try {\n await this.getItemByPath(['Files']);\n return true;\n } catch {\n return false;\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n const response = await this.client.get('/organization');\n return response.data as OrganizationInfo;\n }\n\n async getFilesFolder(): Promise<{ id: number; name: string; type: string } | null> {\n try {\n const item = await this.getItemByPath(['Files']);\n return {\n id: item.id,\n name: item.name,\n type: item.type,\n };\n } catch {\n return null;\n }\n }\n\n private async listFolderItems(folderId: number | null): Promise<FolderContent> {\n // Body is array: [{ id: null }] for root, [{ id: folderId }] for specific folder\n const response = await this.client.post('/folders/items', [{ id: folderId }]);\n return response.data[0] || { items: [] };\n }\n\n private async findFolderByName(parentId: number | null, name: string): Promise<FolderItem | null> {\n const content = await this.listFolderItems(parentId);\n const folder = content.items?.find(\n (item) => item.name.toLowerCase() === name.toLowerCase() && item.type.toLowerCase() === 'folder',\n );\n return folder || null;\n }\n\n private async getItemByPath(path: string[]): Promise<FolderItem> {\n let currentId: number | null = null;\n\n for (const segment of path) {\n const folder = await this.findFolderByName(currentId, segment);\n if (!folder) {\n throw new Error(`Folder not found: ${segment}`);\n }\n currentId = folder.id;\n }\n\n if (currentId === null) {\n throw new Error('Path is empty');\n }\n\n // Return a minimal FolderItem with the found id\n return { id: currentId, name: path[path.length - 1], type: 'folder' };\n }\n\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const files: RemoteFile[] = [];\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'folder') {\n const subFiles = await this.listFiles([...folderPath, item.name]);\n files.push(...subFiles);\n } else if ((itemType === 'farseer-file' || itemType === 'farseer_file') && item.reference) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference,\n });\n }\n }\n } catch (error) {\n // Critical: do NOT swallow listFiles errors. Returning [] on\n // a transient 5xx / network blip / expired token would make a\n // mirror push (push --force) treat every synced file as a\n // delete candidate \u2014 silent data loss on a backend hiccup.\n // Forbidden gets a friendlier \"wrong tenant\" message;\n // everything else is rethrown via toError so the command-layer\n // formatter surfaces status + body.\n if (axios.isAxiosError(error) && error.response?.data?.code === 'Forbidden') {\n const errorMessage = error.response.data?.message || 'Access denied';\n throw new Error(\n `Access denied: ${errorMessage}\\nYou may need to use --tenant-id to specify a different tenant ID.`,\n );\n }\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n return files;\n }\n\n async getFileContent(reference: string): Promise<string> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'text',\n });\n return response.data;\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'arraybuffer',\n });\n return Buffer.from(response.data);\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.getItemByPath(folderPath);\n\n const formData = new FormData();\n // Force application/octet-stream so undici / form-data don't fall back\n // to mime.lookup(filename), which yields surprising types for source\n // files (`.ts` \u2192 video/mp2t) and can trip WAFs on the upload path.\n // Symmetric with FarseerService (API-key path).\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n formData.append('category', 'GENERAL');\n formData.append('folderId', folder.id.toString());\n\n try {\n await this.client.post('/farseerFiles', formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n // Route through the shared formatter so all the triage hints\n // (opaque BadRequest, folder allowedTypes rejection, \u2026) reach\n // the user. The previous local `extractAxiosError` produced a\n // raw \"HTTP 400 \u2014 Bad Request \u2014 {body}\" with no actionable hint.\n throw await toError(error, `Failed to create file \"${fileName}\"`);\n }\n }\n\n async updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void> {\n const formData = new FormData();\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n\n try {\n await this.client.put(`/farseerFiles/${reference}`, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n throw await toError(error, `Failed to update file \"${fileName}\" (ref: ${reference})`);\n }\n }\n\n async deleteFile(reference: string): Promise<void> {\n try {\n await this.client.delete(`/farseerFiles/${reference}`);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n private async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n try {\n await this.getItemByPath(currentPath);\n } catch {\n if (currentPath.length > 1) {\n const parentPath = currentPath.slice(0, -1);\n const parent = await this.getItemByPath(parentPath);\n // See farseerService.ts:ensureFolderPath for the long-form\n // explanation. TL;DR: backend treats `[]` as \"nothing\n // allowed in this folder\" and any subsequent createFile\n // returns HTTP 400. `null` makes the new folder inherit\n // the parent's allowedTypes (which is what the web UI\n // does). Keep the two paths in sync.\n await this.client.post('/folders', {\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n const folderPath = pathParts;\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemType = item.type.toLowerCase();\n if (\n item.name === fileName &&\n (itemType === 'farseer-file' || itemType === 'farseer_file') &&\n item.reference\n ) {\n return {\n name: item.name,\n path: filePath,\n reference: item.reference,\n };\n }\n }\n } catch {\n return null;\n }\n\n return null;\n }\n\n async getFileMetadata(reference: string): Promise<import('./farseerFactory').FileMetadata | null> {\n try {\n const response = await this.client.get(`/farseerFiles/${reference}/metadata`);\n const data = response.data;\n\n return {\n uploadTime: data.uploadTime,\n uploader: data.uploader\n ? {\n id: data.uploader.id,\n email: data.uploader.email || '',\n firstName: data.uploader.firstName || '',\n lastName: data.uploader.lastName || '',\n }\n : undefined,\n size: data.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n isTextFile(filename: string): boolean {\n const ext = filename.toLowerCase().split('.').pop() || '';\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(\n ext,\n );\n }\n\n isBinaryFile(filename: string): boolean {\n return !this.isTextFile(filename);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * Get the Apps folder ID\n */\n async getAppsFolderId(): Promise<number | null> {\n const content = await this.listFolderItems(null);\n const appsFolder = content.items?.find(\n (item) => item.name.toLowerCase() === 'apps' && item.type.toLowerCase() === 'folder',\n );\n return appsFolder?.id || null;\n }\n\n /**\n * List all apps (Remote Jobs) on the tenant, including those in subfolders\n */\n async listApps(): Promise<AppListItem[]> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n return [];\n }\n\n return this.listAppsRecursive(appsFolderId);\n }\n\n /**\n * Recursively list all apps in a folder and its subfolders\n */\n private async listAppsRecursive(folderId: number): Promise<AppListItem[]> {\n const apps: AppListItem[] = [];\n const content = await this.listFolderItems(folderId);\n\n for (const item of content.items || []) {\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'remote_job') {\n // Found an app\n apps.push({\n id: item.id,\n name: item.name,\n type: item.type,\n reference: item.reference || '',\n });\n } else if (itemType === 'folder') {\n // Recurse into subfolder\n const subApps = await this.listAppsRecursive(item.id);\n apps.push(...subApps);\n }\n }\n\n return apps;\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const response = await this.client.get(`/remoteJobs/${referenceId}`);\n const app: RemoteApp = response.data;\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if ((!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<AppScriptFile[]> {\n try {\n const content = await this.listFolderItems(sourceFolderId);\n return (content.items || [])\n .filter((item) => {\n const t = item.type.toLowerCase();\n return (t === 'farseer-file' || t === 'farseer_file') && item.reference;\n })\n .map((item) => ({ id: item.reference!, name: item.name }));\n } catch {\n return [];\n }\n }\n\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.getItemByPath(['Files', ...segments]);\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Get app by name\n */\n async getAppByName(name: string): Promise<RemoteApp | null> {\n const apps = await this.listApps();\n const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());\n if (!app) {\n return null;\n }\n return this.getApp(app.reference);\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n const response = await this.client.post('/remoteJobs', {\n folderId: appsFolderId,\n name,\n });\n return response.data;\n }\n\n /**\n * Update an app\n */\n async updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp> {\n // The PUT replaces the whole record, so merge the changes onto currentApp.\n await this.client.put(`/remoteJobs/${referenceId}`, mergeAppUpdate(currentApp, update));\n // API returns 204 No Content, so fetch the updated app.\n const app = await this.getApp(referenceId);\n if (!app) {\n throw new Error(`Failed to fetch updated app ${referenceId}`);\n }\n return app;\n }\n\n /**\n * Delete an app\n */\n async deleteApp(itemNodeId: number): Promise<void> {\n // Apps are deleted through the folder API (remoteJobs has no DELETE).\n await this.client.post('/folders/deleteItems', [{ id: itemNodeId }]);\n }\n\n /**\n * Run an app with arguments\n */\n async runApp(referenceId: string, args: Record<string, string> = {}): Promise<{ executionId: string }> {\n const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {\n arguments: args,\n });\n return response.data;\n }\n\n /**\n * Get script files available for apps (searches all .ts/.js files in Files folder)\n * Returns full path relative to Files/ folder (e.g., \"Scripts/test.ts\", \"Scripts/subfolder/helper.ts\")\n */\n async getScriptFiles(): Promise<AppScriptFile[]> {\n // listFiles already searches recursively, so just filter for .ts/.js files\n const allFiles = await this.listFiles(['Files']);\n return allFiles\n .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))\n .map((f) => ({\n id: f.reference,\n name: f.path, // Use full path to support scripts in subfolders\n }));\n }\n\n // ==================== Model Export API ====================\n\n /**\n * Export the model structure. By default returns tables (without\n * members) and variables \u2014 enough for `farseer variables list` /\n * `farseer tables list` without dragging the full member matrix.\n *\n * Pass `types` to scope further. Pass `tableGids` / `variableGids`\n * to limit member/variable expansion to specific objects (used by\n * `dimension details <name>` so we hit one table's members instead\n * of all of them).\n *\n * Why this matters: an unscoped `['DTAB','DMEM','VAR']` export\n * pulls every member of every dimension over the wire. On larger\n * tenants the JSON gets big enough to exceed Cloud Run / proxy\n * response limits, so the client sees \"socket hang up\" before any\n * data arrives. The server-side filter is honoured all the way down\n * to rama (modelMapping.ts \u2192 modelService2.modelExport), so a\n * scoped request is cheap.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Never request CELL \u2014 the full cell matrix is enormous for GL-scale tenants\n // and nothing in the CLI consumes it. Tables/members/variables only.\n const types = options.types ?? ['DTAB', 'VAR'];\n const requestBody: Record<string, unknown> = { types };\n if (options.tableGids && options.tableGids.length > 0) {\n requestBody.tableGids = options.tableGids;\n }\n if (options.variableGids && options.variableGids.length > 0) {\n requestBody.variableGids = options.variableGids;\n }\n\n try {\n const response = await this.client.post('/model/export', requestBody);\n return response.data;\n } catch (err) {\n // /model/export is the right path; if it fails we fall back to\n // initTagMap so older instances and partial outages still work.\n // Log the underlying error so users don't see a phantom slow\n // initTagMap fallback hide a real backend issue.\n const message = err instanceof Error ? err.message : String(err);\n logger.dim(`/model/export failed (${message}); falling back to initTagMap.`);\n return this.buildModelFromTagMaps(options);\n }\n }\n\n /**\n * Fetch one dimension table with its members through the\n * entities API (search \u2192 getRelations \u2192 getMany). This stays\n * scoped to a single table, unlike `/model/export` with\n * `tableGids` filter which currently 500s for some tables on\n * large tenants (rama-side scoping bug, tracked separately).\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.makeNativeClient(), name);\n }\n\n private makeNativeClient(): farseer.FarseerClient {\n return new farseer.FarseerClient({\n basePath: this.basePath,\n headers: {\n 'X-TENANT-ID': this.tenantId,\n Authorization: `Bearer ${this.accessToken}`,\n },\n });\n }\n\n private async buildModelFromTagMaps(options: ModelExportOptions = {}): Promise<ModelExport> {\n const types = options.types ?? ['DTAB', 'VAR'];\n const wantTables = types.includes('DTAB');\n const wantMembers = types.includes('DMEM');\n const wantVariables = types.includes('VAR');\n\n const nativeClient = this.makeNativeClient();\n\n let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await nativeClient.initTagMap();\n } catch (err: any) {\n if (err && typeof err.status === 'number' && typeof err.url === 'string') {\n const text = typeof err.text === 'function' ? await err.text().catch(() => '') : '';\n throw new Error(`initTagMap failed: HTTP ${err.status} ${text}`.trim());\n }\n throw err;\n }\n\n // initTagMap unconditionally pulls all three entity types from\n // the server, so this fallback can't avoid the wire cost the\n // way `/model/export` can. We can at least respect `options` on\n // the way out so callers see a shape consistent with the\n // primary path (tables-only / variables-only / scoped to gids).\n const tables: ModelExportTable[] = [];\n if (wantTables) {\n const tableGidFilter =\n options.tableGids && options.tableGids.length > 0 ? new Set(options.tableGids) : null;\n for (const [name, tag] of tagMaps.dimensionTableMapByName) {\n if (tableGidFilter && !tableGidFilter.has(tag.id)) continue;\n const members = wantMembers ? tagMaps.dimensionMemberMapsByTableId.get(tag.id) : undefined;\n tables.push({\n gid: tag.id,\n name,\n columns:\n tag.columns?.map((c) => ({\n name: c.name,\n type: c.foreignKey ? 'FOREIGN_KEY' : c.primaryKey ? 'PRIMARY_KEY' : String(c.type),\n foreignKeyTableName: c.foreignKey ? tagMaps.mapById.get(c.refTableGid)?.name : undefined,\n })) ?? [],\n rows: members ? Array.from(members.values()).map((m) => [m.name]) : [],\n });\n }\n }\n\n const variables: ModelExportVariable[] = [];\n if (wantVariables) {\n const variableGidFilter =\n options.variableGids && options.variableGids.length > 0 ? new Set(options.variableGids) : null;\n for (const [name, tag] of tagMaps.variableMapByName) {\n if (variableGidFilter && !variableGidFilter.has(tag.id)) continue;\n const dimNames = (tag.dimensionTagIds ?? [])\n .map((id) => tagMaps.mapById.get(id)?.name)\n .filter((n): n is string => Boolean(n));\n variables.push({\n gid: tag.id,\n name,\n tables: dimNames,\n members: [],\n rollupType: tag.rollupType ?? 'SUM',\n dataType: tag.dataType ?? 'DECIMAL',\n readonly: tag.readonly ?? false,\n calculateOnDemand: tag.calculateOnDemand ?? false,\n formula: tag.expression ?? null,\n description: tag.description ?? null,\n });\n }\n }\n\n return { tables, variables, dependencies: { tables: [], members: [], variables: [] } };\n }\n}\n\n/**\n * Shared helper used by both `FarseerApi` (JWT auth) and `FarseerService`\n * (apiKey auth) to fetch one dimension table's members through the\n * entities API. The two clients only differ in how they're constructed,\n * so the actual fetch logic is the same \u2014 kept in one place to avoid\n * drift between auth modes.\n *\n * Resolves the table by name first via `entities.search`. The\n * \"not found\" outcome therefore comes from an empty search result\n * (`searchResult.length < 1`), not from string-matching an exception\n * message \u2014 which means renames or i18n of the underlying error\n * won't silently regress this to a thrown exception.\n */\nexport async function loadDimensionTableViaEntitiesApi(\n nativeClient: farseer.FarseerClient,\n name: string,\n): Promise<ModelExportTable | null> {\n const searchResult = await nativeClient.entities.search({\n name,\n types: [farseer.EntityType.DimensionTable],\n limit: 1,\n });\n if (searchResult.length < 1) {\n return null;\n }\n // Hand off to the library helper now that we know the table\n // exists \u2014 it does the relations + getMany walk and returns\n // an arquero table with one table's members. Bounded by that\n // single table's size, not the whole tenant.\n const loaded = await nativeClient.data.loadFarseerDimensionTable(name);\n const objects = loaded.table.objects() as Array<Record<string, unknown>>;\n const columns = loaded.metadata.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: (c as { foreignKeyTableName?: string }).foreignKeyTableName,\n }));\n const rows = objects.map((obj) => columns.map((col) => obj[col.name ?? '']));\n return { name, columns, rows };\n}\n\n// Model Export types\n\n/**\n * Scope for `exportModel`. Default (no options) = tables + variables\n * without member rows. Pass `types: ['DTAB','DMEM']` + `tableGids` to\n * fetch members for specific tables only. The server honours these\n * filters all the way down to rama, so a scoped request is cheap on\n * a larger tenant where the unscoped export would otherwise time out.\n */\nexport type ModelExportType = 'DTAB' | 'DMEM' | 'VAR';\nexport interface ModelExportOptions {\n types?: ModelExportType[];\n /**\n * Backend-supported filter, currently no in-tree caller. We chose\n * the entities-API path (`loadDimensionTableWithMembers`) over\n * `/model/export?tableGids=\u2026` because rama 500s for some tables\n * on large tenants. Kept on the type so the surface mirrors the\n * server contract \u2014 re-introduce a caller once that backend bug\n * is fixed and we can switch back. Until then, treat this field\n * as \"shape-only\" and verify any new caller against a real\n * scoped fetch on a large tenant.\n */\n tableGids?: number[];\n /**\n * Same as `tableGids`, applied to variables. No in-tree caller;\n * kept for parity with the server-side filter.\n */\n variableGids?: number[];\n}\n\nexport interface ModelExport {\n tables: ModelExportTable[];\n variables: ModelExportVariable[];\n dependencies: {\n tables: string[];\n members: string[];\n variables: string[];\n };\n}\n\nexport interface ModelExportTable {\n /** Numeric id used by `tableGids` filtering. Present on the server-side\n * `/model/export` response; absent in the initTagMap fallback path. */\n gid?: number;\n name: string;\n columns: ModelExportColumn[];\n defaultMember?: string | null;\n folderPath?: string[];\n rows: any[][];\n autoIncrementTemplate?: string | null;\n}\n\nexport interface ModelExportColumn {\n name?: string;\n type: string; // PRIMARY_KEY, FORMULA, ORDER, ACTIVE, DESCRIPTION, FOREIGN_KEY, NUMBER, TEXT, DATE, FILE\n foreignKeyTableName?: string;\n}\n\nexport interface ModelExportVariable {\n /** Numeric id used by `variableGids` filtering. Present on the\n * server-side `/model/export` response; absent in the initTagMap fallback. */\n gid?: number;\n name: string;\n description?: string | null;\n formula?: string | null;\n tables: string[];\n members: string[];\n rollupType: string; // SUM, AVERAGE, CLOSING STATE, BEGINNING STATE, FORMULA, MAX, MIN\n dataType: string; // DECIMAL, INTEGER\n numberFormat?: {\n type: string; // NUMBER, CURRENCY, PERCENTAGE, DATE, CUSTOM\n custom?: boolean;\n formatString?: string;\n decimals?: number;\n };\n numberValidation?: {\n min?: number | null;\n max?: number | null;\n };\n topDownMapping?: string | null;\n readonly: boolean;\n calculateOnDemand: boolean;\n zConstraint?: boolean;\n active?: boolean;\n optimizeCalculation?: boolean;\n useHierarchy?: boolean;\n folderPath?: string[];\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAiE;AACjE,mBAAkB;AAClB,cAAyB;AACzB,2BAAwD;AACxD,4BAAmC;AACnC,4BAAwB;AACxB,oBAAuB;AAwFhB,SAAS,eAAe,SAAoB,SAA6C;AAC5F,SAAO;AAAA,IACH,MAAM,QAAQ,QAAQ,QAAQ;AAAA,IAC9B,aAAa,QAAQ,eAAe,QAAQ,eAAe;AAAA,IAC3D,mBAAmB,QAAQ,qBAAqB,QAAQ,qBAAqB,CAAC;AAAA,IAC9E,kBAAkB,QAAQ,oBAAoB,QAAQ,oBAAoB;AAAA,IAC1E,gBAAgB,QAAQ,kBAAkB,QAAQ,kBAAkB;AAAA,IACpE,UAAU,QAAQ,YAAY,QAAQ,YAAY;AAAA,IAClD,YAAY,QAAQ,cAAc,QAAQ,cAAc;AAAA,IACxD,aAAa,QAAQ,eAAe,QAAQ,eAAe;AAAA,IAC3D,mBAAmB,QAAQ,qBAAqB,QAAQ,qBAAqB,CAAC;AAAA,EAClF;AACJ;AAUO,SAAS,mBAAmB,eAAgC,MAAyC;AACxG,SAAO,cAAc,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AACpD;AA8BA,eAAsB,wBAClB,QACA,KACA,SACA,SACA,QACsB;AACtB,QAAM,MAAM,WAAW;AAEvB,QAAM,OAAO,CAAC,SAAkB,MAAM,aAAAA,QAAM,IAAI,IAAI,IAAI;AAExD,MAAI,gBAAgB,IAAI,eAAe,CAAC;AACxC,MAAI;AAEJ,MAAI,QAAQ,cAAc;AACtB,QAAI;AACJ,QAAI;AACA,iBAAW,MAAM,OAAO,oBAAoB,QA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AK;AACjC;",
6
- "names": ["chalk", "axios"]
4
+ "sourcesContent": ["/**\n * FarseerApi - Direct HTTP API client using JWT Bearer token authentication\n *\n * This is an alternative to FarseerService that doesn't use farseer-client library.\n * Use this when authenticating via browser login (Keycloak JWT token) instead of API key.\n */\n\nimport axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';\nimport chalk from 'chalk';\nimport * as farseer from 'farseer-client';\nimport { getCredential, getUserAuth, setUserAuth } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { toError } from '../utils/errorFormatter';\nimport { logger } from '../utils/logger';\n\n// RemoteFile lives in farseerFactory.ts (canonical). Re-export so existing\n// imports (`import { RemoteFile } from './farseerApi'`) still resolve, and\n// import locally so this file's own annotations type-check.\nimport type { RemoteFile, OrganizationInfo } from './farseerFactory';\nexport type { RemoteFile };\n\ninterface FolderItem {\n id: number;\n name: string;\n type: 'folder' | 'farseer-file';\n reference?: string;\n}\n\ninterface FolderContent {\n items: FolderItem[];\n}\n\n// App (Remote Job) types \u2014 orthogonal-axes shape:\n// dataType \u2208 { 'string', 'boolean' }\n// fixed?: locked at run time (admin sets, user cannot override)\n// options?: closed allowed-value set (string dataType only)\nexport type AppArgumentDataType = 'string' | 'boolean';\n\nexport interface AppArgument {\n name: string;\n dataType: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport interface AppScriptFile {\n id: string;\n name: string;\n}\n\n// A resolved source folder: its node id (to set on the app) plus the script\n// files it contains (to validate an entrypoint lives inside it).\nexport interface SourceFolderResolution {\n id: number;\n scripts: AppScriptFile[];\n}\n\nexport interface RemoteApp {\n id: number;\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n status: string;\n lastHeartbeat: string;\n mainScriptFileId: string | null;\n scriptFiles?: AppScriptFile[];\n sourceFolderId?: number;\n schedule?: string | null;\n runnerName?: string | null;\n runnerImage?: string | null;\n creationType: string;\n predefinedActions: unknown[];\n}\n\n// The fields a Remote Job update writes. The backend PUT replaces the whole\n// row, so any field omitted here is reset to its default (args/predefined \u2192\n// empty, the rest \u2192 null). `mergeAppUpdate` exists so a caller that only wants\n// to touch one field doesn't silently wipe the others.\nexport interface UpdateAppPayload {\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n mainScriptFileId: string | null;\n sourceFolderId: number | null;\n schedule: string | null;\n runnerName: string | null;\n runnerImage: string | null;\n predefinedActions: unknown[];\n}\n\n// `scriptFileIds` is accepted from callers for backwards compatibility but is\n// never sent \u2014 the backend ignores it (scripts derive from the source folder).\nexport type AppUpdateChanges = Partial<UpdateAppPayload> & { scriptFileIds?: string[] };\n\n/**\n * Overlay a caller's changes onto an app's current state to build a full,\n * non-destructive update payload. Every field the caller leaves out keeps its\n * current value \u2014 so changing one setting never clears the others.\n */\nexport function mergeAppUpdate(current: RemoteApp, changes: AppUpdateChanges): UpdateAppPayload {\n return {\n name: changes.name ?? current.name,\n description: changes.description ?? current.description ?? '',\n expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],\n mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,\n sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,\n schedule: changes.schedule ?? current.schedule ?? null,\n runnerName: changes.runnerName ?? current.runnerName ?? null,\n runnerImage: changes.runnerImage ?? current.runnerImage ?? null,\n predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? [],\n };\n}\n\n/**\n * Find a script in a source folder's file list by its exact name. Farseer file\n * names are case-sensitive \u2014 two files differing only in case can coexist in a\n * folder \u2014 so matching is exact, never case-folded, to avoid resolving an\n * entrypoint to the wrong file. Resolution is folder-scoped, never tenant-wide,\n * so a same-named file in another folder can't be picked by accident. Returns\n * undefined when the name isn't in the folder.\n */\nexport function findScriptInFolder(folderScripts: AppScriptFile[], name: string): AppScriptFile | undefined {\n return folderScripts.find((s) => s.name === name);\n}\n\n// The one client capability applySourceFolderChange needs. Kept minimal (not the\n// whole client) so it is trivial to unit-test with a fake resolver.\nexport interface SourceFolderResolver {\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n}\n\n// Selects only how an error is presented \u2014 dimming, and `--flag` (CLI) vs param\n// (MCP) wording. It is a pure UX knob: the decision, the ids written to `changes`,\n// and the success/failure outcome are identical for both values. Never branch\n// functionality on it.\nexport type ConfigureCaller = 'cli' | 'mcp';\n\n/**\n * Resolve the source-folder / entrypoint settings for an `app configure` and\n * write the resulting ids into `changes`, applying the rule that an app's\n * scripts derive from its source folder and the entrypoint must be a file in\n * that folder. `sourceFolder` (a path under Files/) switches the folder;\n * otherwise the entrypoint is validated against the app's current folder. Moving\n * the folder must not orphan the entrypoint: if the current entrypoint isn't in\n * the new folder and the caller didn't supply one, the request is rejected \u2014 the\n * entrypoint is never silently cleared or relocated.\n *\n * Returns an error message for the caller to surface (and `changes` is left\n * untouched), or null once the ids have been written. The decision lives here so\n * the CLI and MCP paths can't drift. `caller` affects only how an error reads\n * (dimming, `--flag` vs param wording) \u2014 never which errors fire or what gets\n * written \u2014 so the two surfaces stay behaviourally identical.\n */\nexport async function applySourceFolderChange(\n client: SourceFolderResolver,\n app: Pick<RemoteApp, 'scriptFiles' | 'mainScriptFileId'>,\n changes: AppUpdateChanges,\n options: { sourceFolder?: string; entrypoint?: string },\n caller: ConfigureCaller,\n): Promise<string | null> {\n const cli = caller === 'cli';\n // Secondary guidance lines are dimmed in the terminal; plain for the MCP tool.\n const hint = (text: string) => (cli ? chalk.dim(text) : text);\n\n let folderScripts = app.scriptFiles ?? [];\n let sourceFolderId: number | undefined;\n\n if (options.sourceFolder) {\n let resolved: SourceFolderResolution;\n try {\n resolved = await client.resolveSourceFolder(options.sourceFolder);\n } catch {\n return [\n `Source folder not found under Files/: ${options.sourceFolder}`,\n hint('Use a path relative to Files/, e.g. \"Scripts/MyApp\".'),\n ].join('\\n');\n }\n sourceFolderId = resolved.id;\n folderScripts = resolved.scripts;\n\n // Moving the folder must not leave the entrypoint pointing outside it.\n if (!options.entrypoint && app.mainScriptFileId) {\n const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);\n if (!stillThere) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n return [\n \"The app's current entrypoint is not in the new source folder.\",\n hint(\n cli\n ? 'Pass --entrypoint <script> (a file in the new folder) in the same command.'\n : 'Pass \"entrypoint\" (a file in the new folder) in the same call.',\n ),\n hint(`Files in this folder: ${files}`),\n ].join('\\n');\n }\n }\n }\n\n let mainScriptFileId: string | undefined;\n if (options.entrypoint) {\n const match = findScriptInFolder(folderScripts, options.entrypoint);\n if (!match) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n const lines = [\n `Entrypoint not found in the source folder: ${options.entrypoint}`,\n hint(`Files in this folder: ${files}`),\n ];\n if (!options.sourceFolder) {\n lines.push(\n hint(\n cli\n ? 'To use a file from another folder, set it first with --source-folder <path>.'\n : 'To use a file from another folder, pass sourceFolder first.',\n ),\n );\n }\n return lines.join('\\n');\n }\n mainScriptFileId = match.id;\n }\n\n // Apply only after every check passes, so a rejected request never partially\n // mutates `changes`.\n if (sourceFolderId !== undefined) {\n changes.sourceFolderId = sourceFolderId;\n }\n if (mainScriptFileId !== undefined) {\n changes.mainScriptFileId = mainScriptFileId;\n }\n return null;\n}\n\n// `reference` (the Remote Job id) is deliberately the only id here \u2014 apps also\n// have a folder-item id, in an overlapping number space, and carrying both is\n// what let `app delete` destroy unrelated objects.\nexport interface AppListItem {\n name: string;\n type: string;\n reference: string;\n}\n\nexport const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;\n\n// A `folders.resolveItems` result: `id` is the folder-item id, `reference` the\n// id in the item's own domain (for REMOTE_JOB, the Remote Job id).\nexport interface ResolvedFolderItem {\n id: number;\n name: string;\n type: string;\n reference: string;\n}\n\nexport function remoteJobReverseReferences(remoteJobIds: readonly string[]): farseer.ReverseReference[] {\n return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));\n}\n\n// A deliberate refusal from the delete guard, as distinct from a transport\n// failure. Callers surface it as a validation error, not a retryable one:\n// nothing was deleted and retrying cannot change that.\nexport class AppDeleteRefusedError extends Error {}\n\n/**\n * Pick the folder-item id to delete for an app, from the `resolveItems` response.\n *\n * Remote Job ids and folder-item ids overlap \u2014 the low folder ids are the roots\n * (13 = Files, 15 = Apps) \u2014 so posting a Remote Job id to `deleteItems` deletes\n * whichever unrelated node owns that number. `resolveItems` is type-scoped\n * server-side; these checks make sure a server change can't widen that.\n */\nexport function resolveAppItemNodeId(remoteJobId: string, items: readonly ResolvedFolderItem[]): number {\n const matches = items.filter((item) => item.reference === remoteJobId);\n\n if (matches.length === 0) {\n throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);\n }\n if (matches.length > 1) {\n throw new AppDeleteRefusedError(\n `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`,\n );\n }\n\n const item = matches[0];\n if (item.type !== REMOTE_JOB_ITEM_TYPE) {\n throw new AppDeleteRefusedError(\n `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ` +\n `(\"${item.name}\"), not an app.`,\n );\n }\n\n return item.id;\n}\n\nexport class FarseerApi {\n private client: AxiosInstance;\n private tenant: string;\n private tenantId: string;\n private basePath: string;\n private accessToken: string;\n\n private isRefreshing = false;\n private refreshSubscribers: ((token: string) => void)[] = [];\n\n constructor(accessToken: string, tenant: string, tenantId?: string) {\n this.tenant = tenant;\n this.tenantId = tenantId || tenant;\n this.accessToken = accessToken;\n\n // Try to get basePath from existing config, or generate from tenant name\n const credential = getCredential(tenant);\n const basePath = credential?.basePath || `https://${tenant}.farseer.io/api/v3`;\n this.basePath = basePath;\n\n this.client = axios.create({\n baseURL: basePath,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n 'x-api-version': '3.3.0',\n 'X-TENANT-ID': this.tenantId,\n },\n });\n\n // Add response interceptor for automatic token refresh on 401\n this.client.interceptors.response.use(\n (response) => response,\n async (error) => {\n const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };\n\n // Only handle 401 errors and avoid infinite loops\n if (error.response?.status === 401 && !originalRequest._retry) {\n originalRequest._retry = true;\n\n // If already refreshing, wait for the new token\n if (this.isRefreshing) {\n return new Promise((resolve) => {\n this.refreshSubscribers.push((token: string) => {\n originalRequest.headers['Authorization'] = `Bearer ${token}`;\n resolve(this.client(originalRequest));\n });\n });\n }\n\n this.isRefreshing = true;\n\n try {\n const auth = getUserAuth();\n if (!auth?.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n throw new Error('Token refresh failed');\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update this client's token\n this.updateAccessToken(refreshed.accessToken);\n\n // Notify all waiting requests\n this.refreshSubscribers.forEach((callback) => callback(refreshed.accessToken));\n this.refreshSubscribers = [];\n\n // Retry the original request\n originalRequest.headers['Authorization'] = `Bearer ${refreshed.accessToken}`;\n return this.client(originalRequest);\n } catch (refreshError) {\n // Token refresh failed - let the error propagate\n this.refreshSubscribers = [];\n throw error;\n } finally {\n this.isRefreshing = false;\n }\n }\n\n return Promise.reject(error);\n },\n );\n }\n\n /**\n * Update the access token (used when token is refreshed)\n */\n updateAccessToken(newToken: string): void {\n this.accessToken = newToken;\n this.client.defaults.headers['Authorization'] = `Bearer ${newToken}`;\n }\n\n async testConnection(): Promise<boolean> {\n try {\n await this.getItemByPath(['Files']);\n return true;\n } catch {\n return false;\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n const response = await this.client.get('/organization');\n return response.data as OrganizationInfo;\n }\n\n async getFilesFolder(): Promise<{ id: number; name: string; type: string } | null> {\n try {\n const item = await this.getItemByPath(['Files']);\n return {\n id: item.id,\n name: item.name,\n type: item.type,\n };\n } catch {\n return null;\n }\n }\n\n private async listFolderItems(folderId: number | null): Promise<FolderContent> {\n // Body is array: [{ id: null }] for root, [{ id: folderId }] for specific folder\n const response = await this.client.post('/folders/items', [{ id: folderId }]);\n return response.data[0] || { items: [] };\n }\n\n private async findFolderByName(parentId: number | null, name: string): Promise<FolderItem | null> {\n const content = await this.listFolderItems(parentId);\n const folder = content.items?.find(\n (item) => item.name.toLowerCase() === name.toLowerCase() && item.type.toLowerCase() === 'folder',\n );\n return folder || null;\n }\n\n private async getItemByPath(path: string[]): Promise<FolderItem> {\n let currentId: number | null = null;\n\n for (const segment of path) {\n const folder = await this.findFolderByName(currentId, segment);\n if (!folder) {\n throw new Error(`Folder not found: ${segment}`);\n }\n currentId = folder.id;\n }\n\n if (currentId === null) {\n throw new Error('Path is empty');\n }\n\n // Return a minimal FolderItem with the found id\n return { id: currentId, name: path[path.length - 1], type: 'folder' };\n }\n\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const files: RemoteFile[] = [];\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'folder') {\n const subFiles = await this.listFiles([...folderPath, item.name]);\n files.push(...subFiles);\n } else if ((itemType === 'farseer-file' || itemType === 'farseer_file') && item.reference) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference,\n });\n }\n }\n } catch (error) {\n // Critical: do NOT swallow listFiles errors. Returning [] on\n // a transient 5xx / network blip / expired token would make a\n // mirror push (push --force) treat every synced file as a\n // delete candidate \u2014 silent data loss on a backend hiccup.\n // Forbidden gets a friendlier \"wrong tenant\" message;\n // everything else is rethrown via toError so the command-layer\n // formatter surfaces status + body.\n if (axios.isAxiosError(error) && error.response?.data?.code === 'Forbidden') {\n const errorMessage = error.response.data?.message || 'Access denied';\n throw new Error(\n `Access denied: ${errorMessage}\\nYou may need to use --tenant-id to specify a different tenant ID.`,\n );\n }\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n return files;\n }\n\n async getFileContent(reference: string): Promise<string> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'text',\n });\n return response.data;\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const response = await this.client.get(`/farseerFiles/${reference}`, {\n responseType: 'arraybuffer',\n });\n return Buffer.from(response.data);\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.getItemByPath(folderPath);\n\n const formData = new FormData();\n // Force application/octet-stream so undici / form-data don't fall back\n // to mime.lookup(filename), which yields surprising types for source\n // files (`.ts` \u2192 video/mp2t) and can trip WAFs on the upload path.\n // Symmetric with FarseerService (API-key path).\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n formData.append('category', 'GENERAL');\n formData.append('folderId', folder.id.toString());\n\n try {\n await this.client.post('/farseerFiles', formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n // Route through the shared formatter so all the triage hints\n // (opaque BadRequest, folder allowedTypes rejection, \u2026) reach\n // the user. The previous local `extractAxiosError` produced a\n // raw \"HTTP 400 \u2014 Bad Request \u2014 {body}\" with no actionable hint.\n throw await toError(error, `Failed to create file \"${fileName}\"`);\n }\n }\n\n async updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void> {\n const formData = new FormData();\n const blob = new Blob([content], { type: 'application/octet-stream' });\n formData.append('file', blob, fileName);\n\n try {\n await this.client.put(`/farseerFiles/${reference}`, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n },\n });\n } catch (error) {\n throw await toError(error, `Failed to update file \"${fileName}\" (ref: ${reference})`);\n }\n }\n\n async deleteFile(reference: string): Promise<void> {\n try {\n await this.client.delete(`/farseerFiles/${reference}`);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n private async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n try {\n await this.getItemByPath(currentPath);\n } catch {\n if (currentPath.length > 1) {\n const parentPath = currentPath.slice(0, -1);\n const parent = await this.getItemByPath(parentPath);\n // See farseerService.ts:ensureFolderPath for the long-form\n // explanation. TL;DR: backend treats `[]` as \"nothing\n // allowed in this folder\" and any subsequent createFile\n // returns HTTP 400. `null` makes the new folder inherit\n // the parent's allowedTypes (which is what the web UI\n // does). Keep the two paths in sync.\n await this.client.post('/folders', {\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n const folderPath = pathParts;\n\n try {\n const folder = await this.getItemByPath(folderPath);\n const folderContent = await this.listFolderItems(folder.id);\n\n for (const item of folderContent.items || []) {\n const itemType = item.type.toLowerCase();\n if (\n item.name === fileName &&\n (itemType === 'farseer-file' || itemType === 'farseer_file') &&\n item.reference\n ) {\n return {\n name: item.name,\n path: filePath,\n reference: item.reference,\n };\n }\n }\n } catch {\n return null;\n }\n\n return null;\n }\n\n async getFileMetadata(reference: string): Promise<import('./farseerFactory').FileMetadata | null> {\n try {\n const response = await this.client.get(`/farseerFiles/${reference}/metadata`);\n const data = response.data;\n\n return {\n uploadTime: data.uploadTime,\n uploader: data.uploader\n ? {\n id: data.uploader.id,\n email: data.uploader.email || '',\n firstName: data.uploader.firstName || '',\n lastName: data.uploader.lastName || '',\n }\n : undefined,\n size: data.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n isTextFile(filename: string): boolean {\n const ext = filename.toLowerCase().split('.').pop() || '';\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(\n ext,\n );\n }\n\n isBinaryFile(filename: string): boolean {\n return !this.isTextFile(filename);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * Get the Apps folder ID\n */\n async getAppsFolderId(): Promise<number | null> {\n const content = await this.listFolderItems(null);\n const appsFolder = content.items?.find(\n (item) => item.name.toLowerCase() === 'apps' && item.type.toLowerCase() === 'folder',\n );\n return appsFolder?.id || null;\n }\n\n /**\n * List all apps (Remote Jobs) on the tenant, including those in subfolders\n */\n async listApps(): Promise<AppListItem[]> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n return [];\n }\n\n return this.listAppsRecursive(appsFolderId);\n }\n\n /**\n * Recursively list all apps in a folder and its subfolders\n */\n private async listAppsRecursive(folderId: number): Promise<AppListItem[]> {\n const apps: AppListItem[] = [];\n const content = await this.listFolderItems(folderId);\n\n for (const item of content.items || []) {\n const itemType = item.type.toLowerCase();\n\n if (itemType === 'remote_job') {\n apps.push({\n name: item.name,\n type: item.type,\n reference: item.reference || '',\n });\n } else if (itemType === 'folder') {\n // Recurse into subfolder\n const subApps = await this.listAppsRecursive(item.id);\n apps.push(...subApps);\n }\n }\n\n return apps;\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const response = await this.client.get(`/remoteJobs/${referenceId}`);\n const app: RemoteApp = response.data;\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if ((!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch {\n return null;\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<AppScriptFile[]> {\n try {\n const content = await this.listFolderItems(sourceFolderId);\n return (content.items || [])\n .filter((item) => {\n const t = item.type.toLowerCase();\n return (t === 'farseer-file' || t === 'farseer_file') && item.reference;\n })\n .map((item) => ({ id: item.reference!, name: item.name }));\n } catch {\n return [];\n }\n }\n\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.getItemByPath(['Files', ...segments]);\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Get app by name\n */\n async getAppByName(name: string): Promise<RemoteApp | null> {\n const apps = await this.listApps();\n const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());\n if (!app) {\n return null;\n }\n return this.getApp(app.reference);\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n const response = await this.client.post('/remoteJobs', {\n folderId: appsFolderId,\n name,\n });\n return response.data;\n }\n\n /**\n * Update an app\n */\n async updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp> {\n // The PUT replaces the whole record, so merge the changes onto currentApp.\n await this.client.put(`/remoteJobs/${referenceId}`, mergeAppUpdate(currentApp, update));\n // API returns 204 No Content, so fetch the updated app.\n const app = await this.getApp(referenceId);\n if (!app) {\n throw new Error(`Failed to fetch updated app ${referenceId}`);\n }\n return app;\n }\n\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n const response = await this.client.post<ResolvedFolderItem[]>(\n '/folders/resolveItems',\n remoteJobReverseReferences(remoteJobIds),\n );\n return response.data ?? [];\n }\n\n // Takes the Remote Job id and resolves the folder-item id itself, so no\n // caller can hand this a raw node id. See `resolveAppItemNodeId`.\n async deleteApp(remoteJobId: string): Promise<void> {\n const items = await this.resolveRemoteJobItems([remoteJobId]);\n const itemNodeId = resolveAppItemNodeId(remoteJobId, items);\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.post('/folders/deleteItems', [{ id: itemNodeId }]);\n }\n\n /**\n * Run an app with arguments\n */\n async runApp(referenceId: string, args: Record<string, string> = {}): Promise<{ executionId: string }> {\n const response = await this.client.post(`/remoteJobs/${referenceId}/run`, {\n arguments: args,\n });\n return response.data;\n }\n\n /**\n * Get script files available for apps (searches all .ts/.js files in Files folder)\n * Returns full path relative to Files/ folder (e.g., \"Scripts/test.ts\", \"Scripts/subfolder/helper.ts\")\n */\n async getScriptFiles(): Promise<AppScriptFile[]> {\n // listFiles already searches recursively, so just filter for .ts/.js files\n const allFiles = await this.listFiles(['Files']);\n return allFiles\n .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))\n .map((f) => ({\n id: f.reference,\n name: f.path, // Use full path to support scripts in subfolders\n }));\n }\n\n // ==================== Model Export API ====================\n\n /**\n * Export the model structure. By default returns tables (without\n * members) and variables \u2014 enough for `farseer variables list` /\n * `farseer tables list` without dragging the full member matrix.\n *\n * Pass `types` to scope further. Pass `tableGids` / `variableGids`\n * to limit member/variable expansion to specific objects (used by\n * `dimension details <name>` so we hit one table's members instead\n * of all of them).\n *\n * Why this matters: an unscoped `['DTAB','DMEM','VAR']` export\n * pulls every member of every dimension over the wire. On larger\n * tenants the JSON gets big enough to exceed Cloud Run / proxy\n * response limits, so the client sees \"socket hang up\" before any\n * data arrives. The server-side filter is honoured all the way down\n * to rama (modelMapping.ts \u2192 modelService2.modelExport), so a\n * scoped request is cheap.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Never request CELL \u2014 the full cell matrix is enormous for GL-scale tenants\n // and nothing in the CLI consumes it. Tables/members/variables only.\n const types = options.types ?? ['DTAB', 'VAR'];\n const requestBody: Record<string, unknown> = { types };\n if (options.tableGids && options.tableGids.length > 0) {\n requestBody.tableGids = options.tableGids;\n }\n if (options.variableGids && options.variableGids.length > 0) {\n requestBody.variableGids = options.variableGids;\n }\n\n try {\n const response = await this.client.post('/model/export', requestBody);\n return response.data;\n } catch (err) {\n // /model/export is the right path; if it fails we fall back to\n // initTagMap so older instances and partial outages still work.\n // Log the underlying error so users don't see a phantom slow\n // initTagMap fallback hide a real backend issue.\n const message = err instanceof Error ? err.message : String(err);\n logger.dim(`/model/export failed (${message}); falling back to initTagMap.`);\n return this.buildModelFromTagMaps(options);\n }\n }\n\n /**\n * Fetch one dimension table with its members through the\n * entities API (search \u2192 getRelations \u2192 getMany). This stays\n * scoped to a single table, unlike `/model/export` with\n * `tableGids` filter which currently 500s for some tables on\n * large tenants (rama-side scoping bug, tracked separately).\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.makeNativeClient(), name);\n }\n\n private makeNativeClient(): farseer.FarseerClient {\n return new farseer.FarseerClient({\n basePath: this.basePath,\n headers: {\n 'X-TENANT-ID': this.tenantId,\n Authorization: `Bearer ${this.accessToken}`,\n },\n });\n }\n\n private async buildModelFromTagMaps(options: ModelExportOptions = {}): Promise<ModelExport> {\n const types = options.types ?? ['DTAB', 'VAR'];\n const wantTables = types.includes('DTAB');\n const wantMembers = types.includes('DMEM');\n const wantVariables = types.includes('VAR');\n\n const nativeClient = this.makeNativeClient();\n\n let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await nativeClient.initTagMap();\n } catch (err: any) {\n if (err && typeof err.status === 'number' && typeof err.url === 'string') {\n const text = typeof err.text === 'function' ? await err.text().catch(() => '') : '';\n throw new Error(`initTagMap failed: HTTP ${err.status} ${text}`.trim());\n }\n throw err;\n }\n\n // initTagMap unconditionally pulls all three entity types from\n // the server, so this fallback can't avoid the wire cost the\n // way `/model/export` can. We can at least respect `options` on\n // the way out so callers see a shape consistent with the\n // primary path (tables-only / variables-only / scoped to gids).\n const tables: ModelExportTable[] = [];\n if (wantTables) {\n const tableGidFilter =\n options.tableGids && options.tableGids.length > 0 ? new Set(options.tableGids) : null;\n for (const [name, tag] of tagMaps.dimensionTableMapByName) {\n if (tableGidFilter && !tableGidFilter.has(tag.id)) continue;\n const members = wantMembers ? tagMaps.dimensionMemberMapsByTableId.get(tag.id) : undefined;\n tables.push({\n gid: tag.id,\n name,\n columns:\n tag.columns?.map((c) => ({\n name: c.name,\n type: c.foreignKey ? 'FOREIGN_KEY' : c.primaryKey ? 'PRIMARY_KEY' : String(c.type),\n foreignKeyTableName: c.foreignKey ? tagMaps.mapById.get(c.refTableGid)?.name : undefined,\n })) ?? [],\n rows: members ? Array.from(members.values()).map((m) => [m.name]) : [],\n });\n }\n }\n\n const variables: ModelExportVariable[] = [];\n if (wantVariables) {\n const variableGidFilter =\n options.variableGids && options.variableGids.length > 0 ? new Set(options.variableGids) : null;\n for (const [name, tag] of tagMaps.variableMapByName) {\n if (variableGidFilter && !variableGidFilter.has(tag.id)) continue;\n const dimNames = (tag.dimensionTagIds ?? [])\n .map((id) => tagMaps.mapById.get(id)?.name)\n .filter((n): n is string => Boolean(n));\n variables.push({\n gid: tag.id,\n name,\n tables: dimNames,\n members: [],\n rollupType: tag.rollupType ?? 'SUM',\n dataType: tag.dataType ?? 'DECIMAL',\n readonly: tag.readonly ?? false,\n calculateOnDemand: tag.calculateOnDemand ?? false,\n formula: tag.expression ?? null,\n description: tag.description ?? null,\n });\n }\n }\n\n return { tables, variables, dependencies: { tables: [], members: [], variables: [] } };\n }\n}\n\n/**\n * Shared helper used by both `FarseerApi` (JWT auth) and `FarseerService`\n * (apiKey auth) to fetch one dimension table's members through the\n * entities API. The two clients only differ in how they're constructed,\n * so the actual fetch logic is the same \u2014 kept in one place to avoid\n * drift between auth modes.\n *\n * Resolves the table by name first via `entities.search`. The\n * \"not found\" outcome therefore comes from an empty search result\n * (`searchResult.length < 1`), not from string-matching an exception\n * message \u2014 which means renames or i18n of the underlying error\n * won't silently regress this to a thrown exception.\n */\nexport async function loadDimensionTableViaEntitiesApi(\n nativeClient: farseer.FarseerClient,\n name: string,\n): Promise<ModelExportTable | null> {\n const searchResult = await nativeClient.entities.search({\n name,\n types: [farseer.EntityType.DimensionTable],\n limit: 1,\n });\n if (searchResult.length < 1) {\n return null;\n }\n // Hand off to the library helper now that we know the table\n // exists \u2014 it does the relations + getMany walk and returns\n // an arquero table with one table's members. Bounded by that\n // single table's size, not the whole tenant.\n const loaded = await nativeClient.data.loadFarseerDimensionTable(name);\n const objects = loaded.table.objects() as Array<Record<string, unknown>>;\n const columns = loaded.metadata.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: (c as { foreignKeyTableName?: string }).foreignKeyTableName,\n }));\n const rows = objects.map((obj) => columns.map((col) => obj[col.name ?? '']));\n return { name, columns, rows };\n}\n\n// Model Export types\n\n/**\n * Scope for `exportModel`. Default (no options) = tables + variables\n * without member rows. Pass `types: ['DTAB','DMEM']` + `tableGids` to\n * fetch members for specific tables only. The server honours these\n * filters all the way down to rama, so a scoped request is cheap on\n * a larger tenant where the unscoped export would otherwise time out.\n */\nexport type ModelExportType = 'DTAB' | 'DMEM' | 'VAR';\nexport interface ModelExportOptions {\n types?: ModelExportType[];\n /**\n * Backend-supported filter, currently no in-tree caller. We chose\n * the entities-API path (`loadDimensionTableWithMembers`) over\n * `/model/export?tableGids=\u2026` because rama 500s for some tables\n * on large tenants. Kept on the type so the surface mirrors the\n * server contract \u2014 re-introduce a caller once that backend bug\n * is fixed and we can switch back. Until then, treat this field\n * as \"shape-only\" and verify any new caller against a real\n * scoped fetch on a large tenant.\n */\n tableGids?: number[];\n /**\n * Same as `tableGids`, applied to variables. No in-tree caller;\n * kept for parity with the server-side filter.\n */\n variableGids?: number[];\n}\n\nexport interface ModelExport {\n tables: ModelExportTable[];\n variables: ModelExportVariable[];\n dependencies: {\n tables: string[];\n members: string[];\n variables: string[];\n };\n}\n\nexport interface ModelExportTable {\n /** Numeric id used by `tableGids` filtering. Present on the server-side\n * `/model/export` response; absent in the initTagMap fallback path. */\n gid?: number;\n name: string;\n columns: ModelExportColumn[];\n defaultMember?: string | null;\n folderPath?: string[];\n rows: any[][];\n autoIncrementTemplate?: string | null;\n}\n\nexport interface ModelExportColumn {\n name?: string;\n type: string; // PRIMARY_KEY, FORMULA, ORDER, ACTIVE, DESCRIPTION, FOREIGN_KEY, NUMBER, TEXT, DATE, FILE\n foreignKeyTableName?: string;\n}\n\nexport interface ModelExportVariable {\n /** Numeric id used by `variableGids` filtering. Present on the\n * server-side `/model/export` response; absent in the initTagMap fallback. */\n gid?: number;\n name: string;\n description?: string | null;\n formula?: string | null;\n tables: string[];\n members: string[];\n rollupType: string; // SUM, AVERAGE, CLOSING STATE, BEGINNING STATE, FORMULA, MAX, MIN\n dataType: string; // DECIMAL, INTEGER\n numberFormat?: {\n type: string; // NUMBER, CURRENCY, PERCENTAGE, DATE, CUSTOM\n custom?: boolean;\n formatString?: string;\n decimals?: number;\n };\n numberValidation?: {\n min?: number | null;\n max?: number | null;\n };\n topDownMapping?: string | null;\n readonly: boolean;\n calculateOnDemand: boolean;\n zConstraint?: boolean;\n active?: boolean;\n optimizeCalculation?: boolean;\n useHierarchy?: boolean;\n folderPath?: string[];\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,mBAAiE;AACjE,mBAAkB;AAClB,cAAyB;AACzB,2BAAwD;AACxD,4BAAmC;AACnC,4BAAwB;AACxB,oBAAuB;AAwFhB,SAAS,eAAe,SAAoB,SAA6C;AAC5F,SAAO;AAAA,IACH,MAAM,QAAQ,QAAQ,QAAQ;AAAA,IAC9B,aAAa,QAAQ,eAAe,QAAQ,eAAe;AAAA,IAC3D,mBAAmB,QAAQ,qBAAqB,QAAQ,qBAAqB,CAAC;AAAA,IAC9E,kBAAkB,QAAQ,oBAAoB,QAAQ,oBAAoB;AAAA,IAC1E,gBAAgB,QAAQ,kBAAkB,QAAQ,kBAAkB;AAAA,IACpE,UAAU,QAAQ,YAAY,QAAQ,YAAY;A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