farseer-cli 1.0.10 → 1.1.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 (98) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/app.js +348 -344
  3. package/dist/commands/app.js.map +7 -0
  4. package/dist/commands/apps.js +110 -82
  5. package/dist/commands/apps.js.map +7 -0
  6. package/dist/commands/cells.js +161 -0
  7. package/dist/commands/cells.js.map +7 -0
  8. package/dist/commands/checkout.js +140 -155
  9. package/dist/commands/checkout.js.map +7 -0
  10. package/dist/commands/config.js +128 -126
  11. package/dist/commands/config.js.map +7 -0
  12. package/dist/commands/dashboards.js +130 -0
  13. package/dist/commands/dashboards.js.map +7 -0
  14. package/dist/commands/diff.js +171 -193
  15. package/dist/commands/diff.js.map +7 -0
  16. package/dist/commands/dimensions.js +222 -119
  17. package/dist/commands/dimensions.js.map +7 -0
  18. package/dist/commands/files.js +96 -77
  19. package/dist/commands/files.js.map +7 -0
  20. package/dist/commands/formula.js +116 -0
  21. package/dist/commands/formula.js.map +7 -0
  22. package/dist/commands/install.js +74 -76
  23. package/dist/commands/install.js.map +7 -0
  24. package/dist/commands/list.js +91 -73
  25. package/dist/commands/list.js.map +7 -0
  26. package/dist/commands/login.js +137 -98
  27. package/dist/commands/login.js.map +7 -0
  28. package/dist/commands/logout.js +59 -41
  29. package/dist/commands/logout.js.map +7 -0
  30. package/dist/commands/mcp-server.js +36 -23
  31. package/dist/commands/mcp-server.js.map +7 -0
  32. package/dist/commands/model.js +186 -175
  33. package/dist/commands/model.js.map +7 -0
  34. package/dist/commands/pull.js +264 -274
  35. package/dist/commands/pull.js.map +7 -0
  36. package/dist/commands/push.js +209 -221
  37. package/dist/commands/push.js.map +7 -0
  38. package/dist/commands/run.js +276 -321
  39. package/dist/commands/run.js.map +7 -0
  40. package/dist/commands/sheets.js +200 -0
  41. package/dist/commands/sheets.js.map +7 -0
  42. package/dist/commands/status.js +149 -169
  43. package/dist/commands/status.js.map +7 -0
  44. package/dist/commands/variables.js +247 -188
  45. package/dist/commands/variables.js.map +7 -0
  46. package/dist/commands/whoami.js +65 -44
  47. package/dist/commands/whoami.js.map +7 -0
  48. package/dist/index.js +179 -115
  49. package/dist/index.js.map +7 -0
  50. package/dist/mcp/index.js +33 -16
  51. package/dist/mcp/index.js.map +7 -0
  52. package/dist/mcp/prompts/workflows.js +191 -145
  53. package/dist/mcp/prompts/workflows.js.map +7 -0
  54. package/dist/mcp/resources/documentation.js +158 -148
  55. package/dist/mcp/resources/documentation.js.map +7 -0
  56. package/dist/mcp/server.js +56 -33
  57. package/dist/mcp/server.js.map +7 -0
  58. package/dist/mcp/tools/appTools.js +309 -277
  59. package/dist/mcp/tools/appTools.js.map +7 -0
  60. package/dist/mcp/tools/authTools.js +130 -121
  61. package/dist/mcp/tools/authTools.js.map +7 -0
  62. package/dist/mcp/tools/cellTools.js +148 -0
  63. package/dist/mcp/tools/cellTools.js.map +7 -0
  64. package/dist/mcp/tools/dashboardTools.js +133 -0
  65. package/dist/mcp/tools/dashboardTools.js.map +7 -0
  66. package/dist/mcp/tools/dataTools.js +270 -267
  67. package/dist/mcp/tools/dataTools.js.map +7 -0
  68. package/dist/mcp/tools/modelTools.js +575 -229
  69. package/dist/mcp/tools/modelTools.js.map +7 -0
  70. package/dist/mcp/tools/runTools.js +201 -203
  71. package/dist/mcp/tools/runTools.js.map +7 -0
  72. package/dist/mcp/tools/sheetTools.js +240 -0
  73. package/dist/mcp/tools/sheetTools.js.map +7 -0
  74. package/dist/mcp/tools/syncTools.js +335 -314
  75. package/dist/mcp/tools/syncTools.js.map +7 -0
  76. package/dist/mcp/utils/helpers.js +117 -123
  77. package/dist/mcp/utils/helpers.js.map +7 -0
  78. package/dist/services/appSyncService.js +381 -437
  79. package/dist/services/appSyncService.js.map +7 -0
  80. package/dist/services/configService.js +154 -143
  81. package/dist/services/configService.js.map +7 -0
  82. package/dist/services/farseerApi.js +422 -399
  83. package/dist/services/farseerApi.js.map +7 -0
  84. package/dist/services/farseerFactory.js +208 -273
  85. package/dist/services/farseerFactory.js.map +7 -0
  86. package/dist/services/farseerService.js +467 -486
  87. package/dist/services/farseerService.js.map +7 -0
  88. package/dist/services/syncService.js +661 -731
  89. package/dist/services/syncService.js.map +7 -0
  90. package/dist/utils/constants.js +52 -19
  91. package/dist/utils/constants.js.map +7 -0
  92. package/dist/utils/entityResolver.js +78 -0
  93. package/dist/utils/entityResolver.js.map +7 -0
  94. package/dist/utils/helpers.js +331 -365
  95. package/dist/utils/helpers.js.map +7 -0
  96. package/dist/utils/logger.js +74 -42
  97. package/dist/utils/logger.js.map +7 -0
  98. package/package.json +3 -2
@@ -1,336 +1,291 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var run_exports = {};
30
+ __export(run_exports, {
31
+ registerRunCommand: () => registerRunCommand
17
32
  });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.registerRunCommand = registerRunCommand;
37
- const logger_1 = require("../utils/logger");
38
- const configService_1 = require("../services/configService");
39
- const farseerService_1 = require("../services/farseerService");
40
- const farseerFactory_1 = require("../services/farseerFactory");
41
- const helpers_1 = require("../utils/helpers");
42
- const fs = __importStar(require("fs"));
43
- const path = __importStar(require("path"));
44
- const child_process_1 = require("child_process");
45
- /**
46
- * Find a script file recursively in a directory.
47
- * Returns the relative path from baseDir if found, null otherwise.
48
- */
33
+ module.exports = __toCommonJS(run_exports);
34
+ var import_logger = require("../utils/logger");
35
+ var import_configService = require("../services/configService");
36
+ var import_farseerService = require("../services/farseerService");
37
+ var import_farseerFactory = require("../services/farseerFactory");
38
+ var import_helpers = require("../utils/helpers");
39
+ var fs = __toESM(require("fs"));
40
+ var path = __toESM(require("path"));
41
+ var import_child_process = require("child_process");
49
42
  function findScriptRecursively(baseDir, scriptName) {
50
- if (!fs.existsSync(baseDir)) {
51
- return null;
43
+ if (!fs.existsSync(baseDir)) {
44
+ return null;
45
+ }
46
+ const search = (dir, relativePath = "") => {
47
+ const items = fs.readdirSync(dir, { withFileTypes: true });
48
+ for (const item of items) {
49
+ const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;
50
+ if (item.isFile() && item.name === scriptName) {
51
+ return itemRelPath;
52
+ }
53
+ if (item.isDirectory()) {
54
+ const found = search(path.join(dir, item.name), itemRelPath);
55
+ if (found) return found;
56
+ }
52
57
  }
53
- const search = (dir, relativePath = '') => {
54
- const items = fs.readdirSync(dir, { withFileTypes: true });
55
- for (const item of items) {
56
- const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;
57
- if (item.isFile() && item.name === scriptName) {
58
- return itemRelPath;
59
- }
60
- if (item.isDirectory()) {
61
- const found = search(path.join(dir, item.name), itemRelPath);
62
- if (found)
63
- return found;
64
- }
65
- }
66
- return null;
67
- };
68
- return search(baseDir);
58
+ return null;
59
+ };
60
+ return search(baseDir);
69
61
  }
70
62
  async function getRunCredentials(tenant, tenantId) {
71
- // First try API key config
72
- const credential = (0, configService_1.getCredential)(tenant);
73
- if (credential) {
74
- return {
75
- tenantId: credential.tenantId,
76
- apiKey: credential.apiKey,
77
- basePath: credential.basePath,
78
- };
79
- }
80
- // Try user auth (browser login)
81
- const auth = (0, configService_1.getUserAuth)();
82
- if (!auth) {
83
- return null;
84
- }
85
- // Check if token needs refresh
86
- if (!(0, configService_1.isUserAuthValid)()) {
87
- logger_1.logger.dim('Token expired, refreshing...');
88
- const refreshed = await (0, farseerService_1.refreshAccessToken)(auth.refreshToken, auth.realm || 'master');
89
- if (!refreshed) {
90
- logger_1.logger.warning('Could not refresh token. Please login again with: farseer login');
91
- return null;
92
- }
93
- // Save refreshed token
94
- (0, configService_1.setUserAuth)({
95
- accessToken: refreshed.accessToken,
96
- refreshToken: refreshed.refreshToken,
97
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),
98
- realm: auth.realm,
99
- });
100
- logger_1.logger.success('Token refreshed');
101
- }
102
- const updatedAuth = (0, configService_1.getUserAuth)();
103
- if (!updatedAuth)
104
- return null;
105
- // Use tenant name as organisation for basePath, tenantId for TENANT_ID env var
63
+ const credential = (0, import_configService.getCredential)(tenant);
64
+ if (credential) {
106
65
  return {
107
- tenantId: tenantId || tenant,
108
- accessToken: updatedAuth.accessToken,
109
- basePath: (0, configService_1.generateBasePath)(tenant),
66
+ tenantId: credential.tenantId,
67
+ apiKey: credential.apiKey,
68
+ basePath: credential.basePath
110
69
  };
70
+ }
71
+ const auth = (0, import_configService.getUserAuth)();
72
+ if (!auth) {
73
+ return null;
74
+ }
75
+ if (!(0, import_configService.isUserAuthValid)()) {
76
+ import_logger.logger.dim("Token expired, refreshing...");
77
+ const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
78
+ if (!refreshed) {
79
+ import_logger.logger.warning("Could not refresh token. Please login again with: farseer login");
80
+ return null;
81
+ }
82
+ (0, import_configService.setUserAuth)({
83
+ accessToken: refreshed.accessToken,
84
+ refreshToken: refreshed.refreshToken,
85
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
86
+ realm: auth.realm
87
+ });
88
+ import_logger.logger.success("Token refreshed");
89
+ }
90
+ const updatedAuth = (0, import_configService.getUserAuth)();
91
+ if (!updatedAuth) return null;
92
+ return {
93
+ tenantId: tenantId || tenant,
94
+ accessToken: updatedAuth.accessToken,
95
+ basePath: (0, import_configService.generateBasePath)(tenant)
96
+ };
111
97
  }
112
- // Helper to collect multiple --arg options
113
98
  function collectArgs(value, previous) {
114
- return previous.concat([value]);
99
+ return previous.concat([value]);
115
100
  }
116
101
  function registerRunCommand(program) {
117
- program
118
- .command('run <args...>')
119
- .description('Run an app locally with injected credentials')
120
- .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')
121
- .option('--arg <value>', 'Pass argument in format "Name=Value" (can be used multiple times)', collectArgs, [])
122
- .action(async (args, options) => {
123
- const { tenant, appName } = (0, helpers_1.parseAppArgs)(args);
124
- // First, get the app details to find the entrypoint script
125
- const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(tenant, options.tenantId);
126
- if (!clientResult) {
127
- (0, farseerFactory_1.showLoginPrompt)(tenant);
128
- process.exit(1);
129
- }
130
- const api = clientResult.client;
131
- // Find the app
132
- logger_1.logger.info(`Loading app: ${appName}...`);
133
- const app = await api.getAppByName(appName);
134
- if (!app) {
135
- logger_1.logger.error(`App not found: ${appName}`);
136
- logger_1.logger.dim('List available apps with: farseer apps ' + tenant);
137
- process.exit(1);
138
- }
139
- const runScripts = app.scriptFiles ?? [];
140
- if (!app.mainScriptFileId || runScripts.length === 0) {
141
- logger_1.logger.error(`App "${appName}" has no scripts configured.`);
142
- logger_1.logger.dim('Configure the app with: farseer app configure "' + appName + '" --entrypoint <script>');
143
- process.exit(1);
144
- }
145
- // Find the entrypoint script name
146
- const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);
147
- if (!mainScript) {
148
- logger_1.logger.error(`Entrypoint script not found for app "${appName}".`);
149
- process.exit(1);
150
- }
151
- // Normalize script name - handle both "test.ts" and "Scripts/test.ts" formats
152
- let scriptName = mainScript.name;
153
- if (scriptName.toLowerCase().startsWith('scripts/')) {
154
- scriptName = scriptName.substring('scripts/'.length);
155
- }
156
- // Get credentials for running
157
- const credentials = await getRunCredentials(tenant, options.tenantId);
158
- if (!credentials) {
159
- (0, farseerFactory_1.showLoginPrompt)(tenant);
160
- process.exit(1);
161
- }
162
- const tenantDir = (0, helpers_1.getTenantDir)(tenant);
163
- const srcDir = (0, helpers_1.getTenantSrcDir)(tenant);
164
- const filesDir = (0, helpers_1.getTenantFilesDir)(tenant);
165
- // Script path is relative to files/Scripts/ folder
166
- // First try direct path, then search recursively if not found
167
- let scriptPath = path.resolve(srcDir, scriptName);
168
- let relativeScriptPath = `files/Scripts/${scriptName}`;
169
- if (!fs.existsSync(scriptPath)) {
170
- // Try to find the script recursively in the files directory
171
- const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));
172
- if (foundPath) {
173
- scriptPath = path.resolve(filesDir, foundPath);
174
- relativeScriptPath = `files/${foundPath}`;
175
- logger_1.logger.dim(`Found script at: ${foundPath}`);
176
- }
177
- }
178
- if (!fs.existsSync(scriptPath)) {
179
- logger_1.logger.error(`Script not found locally: ${scriptPath}`);
180
- logger_1.logger.dim('Run "farseer pull ' + tenant + '" to download scripts first.');
181
- process.exit(1);
182
- }
183
- // Check if node_modules exists
184
- const nodeModulesPath = path.join(tenantDir, 'node_modules');
185
- if (!fs.existsSync(nodeModulesPath)) {
186
- logger_1.logger.error(`Dependencies not installed for ${tenant}`);
187
- logger_1.logger.dim(`Run: farseer install ${tenant}`);
188
- process.exit(1);
189
- }
190
- // Parse arguments
191
- const appArgs = {};
192
- // Start with default values from app config
193
- for (const arg of app.expectedArguments) {
194
- appArgs[arg.name] = arg.defaultValue;
195
- }
196
- // Override with provided arguments
197
- for (const argStr of options.arg) {
198
- const eqIndex = argStr.indexOf('=');
199
- if (eqIndex === -1) {
200
- logger_1.logger.error(`Invalid argument format: ${argStr}`);
201
- logger_1.logger.dim('Use format: --arg "Name=Value"');
202
- process.exit(1);
203
- }
204
- const name = argStr.substring(0, eqIndex);
205
- const value = argStr.substring(eqIndex + 1);
206
- appArgs[name] = value;
207
- }
208
- const authType = credentials.apiKey ? 'API key' : 'access token';
209
- logger_1.logger.info(`Running app "${app.name}" (${scriptName}) for tenant ${tenant} (using ${authType})...`);
210
- // Show arguments being used
211
- if (Object.keys(appArgs).length > 0) {
212
- logger_1.logger.dim('Arguments:');
213
- for (const [key, value] of Object.entries(appArgs)) {
214
- logger_1.logger.dim(` ${key}: ${value}`);
215
- }
216
- }
217
- console.log();
218
- // Build environment variables based on auth type
219
- const envVars = {
220
- ...process.env,
221
- TENANT_ID: credentials.tenantId,
222
- FARSEER_URL: credentials.basePath,
223
- };
224
- if (credentials.apiKey) {
225
- envVars.FARSEER_API_KEY = credentials.apiKey;
226
- }
227
- if (credentials.accessToken) {
228
- envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
229
- }
230
- // Build command line arguments from app arguments (in order)
231
- const cmdArgs = [];
232
- for (const arg of app.expectedArguments) {
233
- cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);
234
- }
235
- // Run with credentials injected via environment variables, arguments via command line
236
- // Quote the script path to handle spaces in folder names
237
- const quotedScriptPath = `"${relativeScriptPath}"`;
238
- const child = (0, child_process_1.spawn)('npx', ['tsx', quotedScriptPath, ...cmdArgs], {
239
- stdio: 'inherit',
240
- cwd: tenantDir,
241
- shell: true,
242
- env: envVars,
243
- });
244
- child.on('close', (code) => {
245
- if (code !== 0) {
246
- logger_1.logger.error(`Script exited with code ${code}`);
247
- process.exit(code || 1);
248
- }
249
- });
250
- child.on('error', (err) => {
251
- logger_1.logger.error(`Failed to run script: ${err.message}`);
252
- logger_1.logger.dim('Make sure tsx is installed: npm install -g tsx');
253
- process.exit(1);
254
- });
102
+ program.command("run <args...>").description("Run an app locally with injected credentials").option("--tenant-id <id>", "Tenant ID for env variables (defaults to tenant name)").option("--arg <value>", 'Pass argument in format "Name=Value" (can be used multiple times)', collectArgs, []).action(async (args, options) => {
103
+ const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
104
+ const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(tenant, options.tenantId);
105
+ if (!clientResult) {
106
+ (0, import_farseerFactory.showLoginPrompt)(tenant);
107
+ process.exit(1);
108
+ }
109
+ const api = clientResult.client;
110
+ import_logger.logger.info(`Loading app: ${appName}...`);
111
+ const app = await api.getAppByName(appName);
112
+ if (!app) {
113
+ import_logger.logger.error(`App not found: ${appName}`);
114
+ import_logger.logger.dim("List available apps with: farseer apps " + tenant);
115
+ process.exit(1);
116
+ }
117
+ const runScripts = app.scriptFiles ?? [];
118
+ if (!app.mainScriptFileId || runScripts.length === 0) {
119
+ import_logger.logger.error(`App "${appName}" has no scripts configured.`);
120
+ import_logger.logger.dim('Configure the app with: farseer app configure "' + appName + '" --entrypoint <script>');
121
+ process.exit(1);
122
+ }
123
+ const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);
124
+ if (!mainScript) {
125
+ import_logger.logger.error(`Entrypoint script not found for app "${appName}".`);
126
+ process.exit(1);
127
+ }
128
+ let scriptName = mainScript.name;
129
+ if (scriptName.toLowerCase().startsWith("scripts/")) {
130
+ scriptName = scriptName.substring("scripts/".length);
131
+ }
132
+ const credentials = await getRunCredentials(tenant, options.tenantId);
133
+ if (!credentials) {
134
+ (0, import_farseerFactory.showLoginPrompt)(tenant);
135
+ process.exit(1);
136
+ }
137
+ const tenantDir = (0, import_helpers.getTenantDir)(tenant);
138
+ const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
139
+ const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
140
+ let scriptPath = path.resolve(srcDir, scriptName);
141
+ let relativeScriptPath = `files/Scripts/${scriptName}`;
142
+ if (!fs.existsSync(scriptPath)) {
143
+ const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));
144
+ if (foundPath) {
145
+ scriptPath = path.resolve(filesDir, foundPath);
146
+ relativeScriptPath = `files/${foundPath}`;
147
+ import_logger.logger.dim(`Found script at: ${foundPath}`);
148
+ }
149
+ }
150
+ if (!fs.existsSync(scriptPath)) {
151
+ import_logger.logger.error(`Script not found locally: ${scriptPath}`);
152
+ import_logger.logger.dim('Run "farseer pull ' + tenant + '" to download scripts first.');
153
+ process.exit(1);
154
+ }
155
+ const nodeModulesPath = path.join(tenantDir, "node_modules");
156
+ if (!fs.existsSync(nodeModulesPath)) {
157
+ import_logger.logger.error(`Dependencies not installed for ${tenant}`);
158
+ import_logger.logger.dim(`Run: farseer install ${tenant}`);
159
+ process.exit(1);
160
+ }
161
+ const appArgs = {};
162
+ for (const arg of app.expectedArguments) {
163
+ appArgs[arg.name] = arg.defaultValue;
164
+ }
165
+ for (const argStr of options.arg) {
166
+ const eqIndex = argStr.indexOf("=");
167
+ if (eqIndex === -1) {
168
+ import_logger.logger.error(`Invalid argument format: ${argStr}`);
169
+ import_logger.logger.dim('Use format: --arg "Name=Value"');
170
+ process.exit(1);
171
+ }
172
+ const name = argStr.substring(0, eqIndex);
173
+ const value = argStr.substring(eqIndex + 1);
174
+ appArgs[name] = value;
175
+ }
176
+ const authType = credentials.apiKey ? "API key" : "access token";
177
+ import_logger.logger.info(`Running app "${app.name}" (${scriptName}) for tenant ${tenant} (using ${authType})...`);
178
+ if (Object.keys(appArgs).length > 0) {
179
+ import_logger.logger.dim("Arguments:");
180
+ for (const [key, value] of Object.entries(appArgs)) {
181
+ import_logger.logger.dim(` ${key}: ${value}`);
182
+ }
183
+ }
184
+ console.log();
185
+ const envVars = {
186
+ ...process.env,
187
+ TENANT_ID: credentials.tenantId,
188
+ FARSEER_URL: credentials.basePath
189
+ };
190
+ if (credentials.apiKey) {
191
+ envVars.FARSEER_API_KEY = credentials.apiKey;
192
+ }
193
+ if (credentials.accessToken) {
194
+ envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
195
+ }
196
+ const cmdArgs = [];
197
+ for (const arg of app.expectedArguments) {
198
+ cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);
199
+ }
200
+ const quotedScriptPath = `"${relativeScriptPath}"`;
201
+ const child = (0, import_child_process.spawn)("npx", ["tsx", quotedScriptPath, ...cmdArgs], {
202
+ stdio: "inherit",
203
+ cwd: tenantDir,
204
+ shell: true,
205
+ env: envVars
206
+ });
207
+ child.on("close", (code) => {
208
+ if (code !== 0) {
209
+ import_logger.logger.error(`Script exited with code ${code}`);
210
+ process.exit(code || 1);
211
+ }
255
212
  });
256
- // Keep the old script-based run as a separate command
257
- program
258
- .command('run-script <args...>')
259
- .description('Run a script directly (without app wrapper)')
260
- .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')
261
- .action(async (args, options) => {
262
- const { tenant, appName } = (0, helpers_1.parseAppArgs)(args);
263
- let script = appName;
264
- const credentials = await getRunCredentials(tenant, options.tenantId);
265
- if (!credentials) {
266
- (0, farseerFactory_1.showLoginPrompt)(tenant);
267
- process.exit(1);
268
- }
269
- // Normalize script path - strip Scripts/ prefix if present
270
- if (script.toLowerCase().startsWith('scripts/')) {
271
- script = script.substring('scripts/'.length);
272
- }
273
- const tenantDir = (0, helpers_1.getTenantDir)(tenant);
274
- const srcDir = (0, helpers_1.getTenantSrcDir)(tenant);
275
- const filesDir = (0, helpers_1.getTenantFilesDir)(tenant);
276
- // Script path is relative to files/Scripts/ folder
277
- // First try direct path, then search recursively if not found
278
- let scriptPath = path.resolve(srcDir, script);
279
- let relativeScriptPath = `files/Scripts/${script}`;
280
- if (!fs.existsSync(scriptPath)) {
281
- // Try to find the script recursively in the files directory
282
- const foundPath = findScriptRecursively(filesDir, path.basename(script));
283
- if (foundPath) {
284
- scriptPath = path.resolve(filesDir, foundPath);
285
- relativeScriptPath = `files/${foundPath}`;
286
- logger_1.logger.dim(`Found script at: ${foundPath}`);
287
- }
288
- }
289
- if (!fs.existsSync(scriptPath)) {
290
- logger_1.logger.error(`Script not found: ${scriptPath}`);
291
- process.exit(1);
292
- }
293
- // Check if node_modules exists
294
- const nodeModulesPath = path.join(tenantDir, 'node_modules');
295
- if (!fs.existsSync(nodeModulesPath)) {
296
- logger_1.logger.error(`Dependencies not installed for ${tenant}`);
297
- logger_1.logger.dim(`Run: farseer install ${tenant}`);
298
- process.exit(1);
299
- }
300
- const authType = credentials.apiKey ? 'API key' : 'access token';
301
- logger_1.logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);
302
- console.log();
303
- // Build environment variables based on auth type
304
- const envVars = {
305
- ...process.env,
306
- TENANT_ID: credentials.tenantId,
307
- FARSEER_URL: credentials.basePath,
308
- };
309
- if (credentials.apiKey) {
310
- envVars.FARSEER_API_KEY = credentials.apiKey;
311
- }
312
- if (credentials.accessToken) {
313
- envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
314
- }
315
- // Run with credentials injected via environment variables
316
- // Quote the script path to handle spaces in folder names
317
- const quotedScriptPath = `"${relativeScriptPath}"`;
318
- const child = (0, child_process_1.spawn)('npx', ['tsx', quotedScriptPath], {
319
- stdio: 'inherit',
320
- cwd: tenantDir,
321
- shell: true,
322
- env: envVars,
323
- });
324
- child.on('close', (code) => {
325
- if (code !== 0) {
326
- logger_1.logger.error(`Script exited with code ${code}`);
327
- process.exit(code || 1);
328
- }
329
- });
330
- child.on('error', (err) => {
331
- logger_1.logger.error(`Failed to run script: ${err.message}`);
332
- logger_1.logger.dim('Make sure tsx is installed: npm install -g tsx');
333
- process.exit(1);
334
- });
213
+ child.on("error", (err) => {
214
+ import_logger.logger.error(`Failed to run script: ${err.message}`);
215
+ import_logger.logger.dim("Make sure tsx is installed: npm install -g tsx");
216
+ process.exit(1);
335
217
  });
218
+ });
219
+ program.command("run-script <args...>").description("Run a script directly (without app wrapper)").option("--tenant-id <id>", "Tenant ID for env variables (defaults to tenant name)").action(async (args, options) => {
220
+ const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
221
+ let script = appName;
222
+ const credentials = await getRunCredentials(tenant, options.tenantId);
223
+ if (!credentials) {
224
+ (0, import_farseerFactory.showLoginPrompt)(tenant);
225
+ process.exit(1);
226
+ }
227
+ if (script.toLowerCase().startsWith("scripts/")) {
228
+ script = script.substring("scripts/".length);
229
+ }
230
+ const tenantDir = (0, import_helpers.getTenantDir)(tenant);
231
+ const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
232
+ const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
233
+ let scriptPath = path.resolve(srcDir, script);
234
+ let relativeScriptPath = `files/Scripts/${script}`;
235
+ if (!fs.existsSync(scriptPath)) {
236
+ const foundPath = findScriptRecursively(filesDir, path.basename(script));
237
+ if (foundPath) {
238
+ scriptPath = path.resolve(filesDir, foundPath);
239
+ relativeScriptPath = `files/${foundPath}`;
240
+ import_logger.logger.dim(`Found script at: ${foundPath}`);
241
+ }
242
+ }
243
+ if (!fs.existsSync(scriptPath)) {
244
+ import_logger.logger.error(`Script not found: ${scriptPath}`);
245
+ process.exit(1);
246
+ }
247
+ const nodeModulesPath = path.join(tenantDir, "node_modules");
248
+ if (!fs.existsSync(nodeModulesPath)) {
249
+ import_logger.logger.error(`Dependencies not installed for ${tenant}`);
250
+ import_logger.logger.dim(`Run: farseer install ${tenant}`);
251
+ process.exit(1);
252
+ }
253
+ const authType = credentials.apiKey ? "API key" : "access token";
254
+ import_logger.logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);
255
+ console.log();
256
+ const envVars = {
257
+ ...process.env,
258
+ TENANT_ID: credentials.tenantId,
259
+ FARSEER_URL: credentials.basePath
260
+ };
261
+ if (credentials.apiKey) {
262
+ envVars.FARSEER_API_KEY = credentials.apiKey;
263
+ }
264
+ if (credentials.accessToken) {
265
+ envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
266
+ }
267
+ const quotedScriptPath = `"${relativeScriptPath}"`;
268
+ const child = (0, import_child_process.spawn)("npx", ["tsx", quotedScriptPath], {
269
+ stdio: "inherit",
270
+ cwd: tenantDir,
271
+ shell: true,
272
+ env: envVars
273
+ });
274
+ child.on("close", (code) => {
275
+ if (code !== 0) {
276
+ import_logger.logger.error(`Script exited with code ${code}`);
277
+ process.exit(code || 1);
278
+ }
279
+ });
280
+ child.on("error", (err) => {
281
+ import_logger.logger.error(`Failed to run script: ${err.message}`);
282
+ import_logger.logger.dim("Make sure tsx is installed: npm install -g tsx");
283
+ process.exit(1);
284
+ });
285
+ });
336
286
  }
287
+ // Annotate the CommonJS export names for ESM import in node:
288
+ 0 && (module.exports = {
289
+ registerRunCommand
290
+ });
291
+ //# sourceMappingURL=run.js.map