farseer-cli 1.0.9 → 1.0.10

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 (81) hide show
  1. package/dist/commands/app.js +344 -316
  2. package/dist/commands/apps.js +83 -103
  3. package/dist/commands/checkout.js +156 -134
  4. package/dist/commands/config.js +126 -124
  5. package/dist/commands/diff.js +194 -169
  6. package/dist/commands/dimensions.js +122 -137
  7. package/dist/commands/files.js +77 -88
  8. package/dist/commands/install.js +77 -74
  9. package/dist/commands/list.js +74 -89
  10. package/dist/commands/login.js +101 -126
  11. package/dist/commands/logout.js +42 -57
  12. package/dist/commands/mcp-server.js +24 -39
  13. package/dist/commands/model.js +176 -184
  14. package/dist/commands/pull.js +276 -248
  15. package/dist/commands/push.js +222 -200
  16. package/dist/commands/run.js +322 -274
  17. package/dist/commands/status.js +170 -147
  18. package/dist/commands/variables.js +192 -168
  19. package/dist/commands/whoami.js +45 -61
  20. package/dist/index.js +115 -117
  21. package/dist/mcp/index.js +17 -33
  22. package/dist/mcp/prompts/workflows.js +146 -191
  23. package/dist/mcp/resources/documentation.js +149 -158
  24. package/dist/mcp/server.js +34 -50
  25. package/dist/mcp/tools/appTools.js +278 -307
  26. package/dist/mcp/tools/authTools.js +123 -130
  27. package/dist/mcp/tools/dataTools.js +271 -275
  28. package/dist/mcp/tools/modelTools.js +233 -265
  29. package/dist/mcp/tools/runTools.js +205 -199
  30. package/dist/mcp/tools/syncTools.js +315 -341
  31. package/dist/mcp/utils/helpers.js +124 -117
  32. package/dist/services/appSyncService.js +438 -379
  33. package/dist/services/configService.js +144 -154
  34. package/dist/services/farseerApi.js +401 -401
  35. package/dist/services/farseerFactory.js +274 -208
  36. package/dist/services/farseerService.js +488 -455
  37. package/dist/services/syncService.js +732 -657
  38. package/dist/utils/constants.js +20 -45
  39. package/dist/utils/helpers.js +366 -333
  40. package/dist/utils/logger.js +43 -74
  41. package/package.json +8 -1
  42. package/dist/commands/app.js.map +0 -7
  43. package/dist/commands/apps.js.map +0 -7
  44. package/dist/commands/checkout.js.map +0 -7
  45. package/dist/commands/config.js.map +0 -7
  46. package/dist/commands/diff.js.map +0 -7
  47. package/dist/commands/dimensions.js.map +0 -7
  48. package/dist/commands/files.js.map +0 -7
  49. package/dist/commands/install.js.map +0 -7
  50. package/dist/commands/list.js.map +0 -7
  51. package/dist/commands/login.js.map +0 -7
  52. package/dist/commands/logout.js.map +0 -7
  53. package/dist/commands/mcp-server.js.map +0 -7
  54. package/dist/commands/model.js.map +0 -7
  55. package/dist/commands/pull.js.map +0 -7
  56. package/dist/commands/push.js.map +0 -7
  57. package/dist/commands/run.js.map +0 -7
  58. package/dist/commands/status.js.map +0 -7
  59. package/dist/commands/variables.js.map +0 -7
  60. package/dist/commands/whoami.js.map +0 -7
  61. package/dist/index.js.map +0 -7
  62. package/dist/mcp/index.js.map +0 -7
  63. package/dist/mcp/prompts/workflows.js.map +0 -7
  64. package/dist/mcp/resources/documentation.js.map +0 -7
  65. package/dist/mcp/server.js.map +0 -7
  66. package/dist/mcp/tools/appTools.js.map +0 -7
  67. package/dist/mcp/tools/authTools.js.map +0 -7
  68. package/dist/mcp/tools/dataTools.js.map +0 -7
  69. package/dist/mcp/tools/modelTools.js.map +0 -7
  70. package/dist/mcp/tools/runTools.js.map +0 -7
  71. package/dist/mcp/tools/syncTools.js.map +0 -7
  72. package/dist/mcp/utils/helpers.js.map +0 -7
  73. package/dist/services/appSyncService.js.map +0 -7
  74. package/dist/services/configService.js.map +0 -7
  75. package/dist/services/farseerApi.js.map +0 -7
  76. package/dist/services/farseerFactory.js.map +0 -7
  77. package/dist/services/farseerService.js.map +0 -7
  78. package/dist/services/syncService.js.map +0 -7
  79. package/dist/utils/constants.js.map +0 -7
  80. package/dist/utils/helpers.js.map +0 -7
  81. package/dist/utils/logger.js.map +0 -7
@@ -1,351 +1,382 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
- var farseerService_exports = {};
29
- __export(farseerService_exports, {
30
- FarseerService: () => FarseerService,
31
- loginWithBrowser: () => loginWithBrowser,
32
- loginWithPassword: () => loginWithPassword,
33
- refreshAccessToken: () => refreshAccessToken
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;
34
17
  });
35
- module.exports = __toCommonJS(farseerService_exports);
36
- var farseer = __toESM(require("farseer-client"));
37
- var import_configService = require("./configService");
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.FarseerService = void 0;
37
+ exports.loginWithPassword = loginWithPassword;
38
+ exports.loginWithBrowser = loginWithBrowser;
39
+ exports.refreshAccessToken = refreshAccessToken;
40
+ const farseer = __importStar(require("farseer-client"));
41
+ const configService_1 = require("./configService");
38
42
  class FarseerService {
39
- constructor(credential) {
40
- this.credential = credential;
41
- this.client = new farseer.FarseerClient({
42
- basePath: credential.basePath,
43
- headers: {
44
- "X-TENANT-ID": credential.tenantId,
45
- "X-API-KEY": credential.apiKey
46
- }
47
- });
48
- }
49
- static fromUserAuth(tenant, basePath) {
50
- const auth = (0, import_configService.getUserAuth)();
51
- if (!auth) return null;
52
- const service = new FarseerService({
53
- type: "apiKey",
54
- tenantId: tenant,
55
- apiKey: "",
56
- basePath
57
- });
58
- service.client = new farseer.FarseerClient({
59
- basePath,
60
- headers: {
61
- "X-TENANT-ID": tenant
62
- },
63
- accessToken: auth.accessToken
64
- });
65
- return service;
66
- }
67
- async testConnection() {
68
- try {
69
- await this.client.getItemByPath(["Files"]);
70
- return true;
71
- } catch {
72
- return false;
43
+ constructor(credential) {
44
+ this.credential = credential;
45
+ this.client = new farseer.FarseerClient({
46
+ basePath: credential.basePath,
47
+ headers: {
48
+ 'X-TENANT-ID': credential.tenantId,
49
+ 'X-API-KEY': credential.apiKey,
50
+ },
51
+ });
73
52
  }
74
- }
75
- async getFilesFolder() {
76
- try {
77
- const item = await this.client.getItemByPath(["Files"]);
78
- return {
79
- id: item.id,
80
- name: item.name,
81
- type: item.type
82
- };
83
- } catch {
84
- return null;
53
+ static fromUserAuth(tenant, basePath) {
54
+ const auth = (0, configService_1.getUserAuth)();
55
+ if (!auth)
56
+ return null;
57
+ const service = new FarseerService({
58
+ type: 'apiKey',
59
+ tenantId: tenant,
60
+ apiKey: '',
61
+ basePath: basePath,
62
+ });
63
+ // Override with access token
64
+ service.client = new farseer.FarseerClient({
65
+ basePath: basePath,
66
+ headers: {
67
+ 'X-TENANT-ID': tenant,
68
+ },
69
+ accessToken: auth.accessToken,
70
+ });
71
+ return service;
85
72
  }
86
- }
87
- async listFiles(folderPath = ["Files"]) {
88
- const files = [];
89
- try {
90
- const folder = await this.client.getItemByPath(folderPath);
91
- const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
92
- for (const item of folderContent[0]?.items || []) {
93
- const itemPath = [...folderPath.slice(1), item.name].join("/");
94
- if (item.type === farseer.FolderItemType.Folder) {
95
- const subFiles = await this.listFiles([...folderPath, item.name]);
96
- files.push(...subFiles);
97
- } else if (item.type === farseer.FolderItemType.FarseerFile && "reference" in item) {
98
- files.push({
99
- name: item.name,
100
- path: itemPath,
101
- reference: item.reference
102
- });
73
+ async testConnection() {
74
+ try {
75
+ // Try to get the Files folder to test connection
76
+ await this.client.getItemByPath(['Files']);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
103
81
  }
104
- }
105
- } catch (error) {
106
- return [];
107
82
  }
108
- return files;
109
- }
110
- async getFileContent(reference) {
111
- const blob = await this.client.farseerFiles.get(reference);
112
- return await blob.text();
113
- }
114
- async createFile(content, fileName, folderPath = ["Files"]) {
115
- await this.ensureFolderPath(folderPath);
116
- const folder = await this.client.getItemByPath(folderPath);
117
- const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
118
- const file = new farseer.WebFile([blob], fileName);
119
- await this.client.farseerFiles.create(file, "GENERAL", folder.id.toString());
120
- }
121
- async updateFile(reference, content, fileName) {
122
- const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
123
- const file = new farseer.WebFile([blob], fileName);
124
- await this.client.farseerFiles.update(reference, file);
125
- }
126
- async deleteFile(reference) {
127
- await this.client.farseerFiles.remove(reference);
128
- }
129
- async ensureFolderPath(folderPath) {
130
- let currentPath = [];
131
- for (const segment of folderPath) {
132
- currentPath.push(segment);
133
- try {
134
- await this.client.getItemByPath(currentPath);
135
- } catch {
136
- if (currentPath.length > 1) {
137
- const parentPath = currentPath.slice(0, -1);
138
- const parent = await this.client.getItemByPath(parentPath);
139
- await this.client.folders.create({
140
- parentId: parent.id,
141
- name: segment,
142
- allowedTypes: []
143
- });
83
+ async getFilesFolder() {
84
+ try {
85
+ const item = await this.client.getItemByPath(['Files']);
86
+ return {
87
+ id: item.id,
88
+ name: item.name,
89
+ type: item.type,
90
+ };
91
+ }
92
+ catch {
93
+ return null;
144
94
  }
145
- }
146
95
  }
147
- }
148
- async getFileByPath(filePath) {
149
- const pathParts = ["Files", ...filePath.split("/")];
150
- const fileName = pathParts.pop();
151
- const folderPath = pathParts;
152
- try {
153
- const folder = await this.client.getItemByPath(folderPath);
154
- const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
155
- for (const item of folderContent[0]?.items || []) {
156
- if (item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && "reference" in item) {
157
- return {
158
- name: item.name,
159
- path: filePath,
160
- reference: item.reference
161
- };
96
+ async listFiles(folderPath = ['Files']) {
97
+ const files = [];
98
+ try {
99
+ const folder = await this.client.getItemByPath(folderPath);
100
+ const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
101
+ for (const item of folderContent[0]?.items || []) {
102
+ // Build path relative to Files folder
103
+ const itemPath = [...folderPath.slice(1), item.name].join('/');
104
+ if (item.type === farseer.FolderItemType.Folder) {
105
+ // Recursively get files from subfolders
106
+ const subFiles = await this.listFiles([...folderPath, item.name]);
107
+ files.push(...subFiles);
108
+ }
109
+ else if (item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {
110
+ // Accept all file types
111
+ files.push({
112
+ name: item.name,
113
+ path: itemPath,
114
+ reference: item.reference,
115
+ });
116
+ }
117
+ }
118
+ }
119
+ catch (error) {
120
+ // Folder might not exist
121
+ return [];
162
122
  }
163
- }
164
- } catch {
165
- return null;
123
+ return files;
166
124
  }
167
- return null;
168
- }
169
- async getFileMetadata(reference) {
170
- try {
171
- const metadata = await this.client.farseerFiles.getMetadata(reference);
172
- return {
173
- uploadTime: metadata.uploadTime?.toISOString(),
174
- uploader: metadata.uploader ? {
175
- id: metadata.uploader.id,
176
- email: metadata.uploader.email || "",
177
- firstName: metadata.uploader.firstName || "",
178
- lastName: metadata.uploader.lastName || ""
179
- } : void 0,
180
- size: metadata.size
181
- };
182
- } catch (error) {
183
- return null;
125
+ async getFileContent(reference) {
126
+ const blob = await this.client.farseerFiles.get(reference);
127
+ return await blob.text();
184
128
  }
185
- }
186
- async getFileContentAsBuffer(reference) {
187
- const blob = await this.client.farseerFiles.get(reference);
188
- const arrayBuffer = await blob.arrayBuffer();
189
- return Buffer.from(arrayBuffer);
190
- }
191
- isTextFile(filename) {
192
- const ext = filename.toLowerCase().split(".").pop() || "";
193
- return ["ts", "js", "mjs", "cjs", "json", "txt", "md", "csv", "xml", "html", "css", "yaml", "yml"].includes(ext);
194
- }
195
- isBinaryFile(filename) {
196
- return !this.isTextFile(filename);
197
- }
198
- // ==================== Apps (Remote Jobs) API ====================
199
- /**
200
- * List all apps (Remote Jobs) on the tenant
201
- */
202
- async listApps() {
203
- const response = await this.apiRequest("/remoteJobs", "GET");
204
- return response.map((app) => ({
205
- id: app.id,
206
- name: app.name,
207
- type: "REMOTE_JOB",
208
- reference: String(app.id)
209
- }));
210
- }
211
- /**
212
- * Get app details by reference ID
213
- */
214
- async getApp(referenceId) {
215
- try {
216
- return await this.apiRequest(`/remoteJobs/${referenceId}`, "GET");
217
- } catch {
218
- return null;
129
+ async createFile(content, fileName, folderPath = ['Files']) {
130
+ // Ensure folder structure exists
131
+ await this.ensureFolderPath(folderPath);
132
+ const folder = await this.client.getItemByPath(folderPath);
133
+ const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
134
+ const file = new farseer.WebFile([blob], fileName);
135
+ await this.client.farseerFiles.create(file, 'GENERAL', folder.id.toString());
219
136
  }
220
- }
221
- /**
222
- * Get app by name
223
- */
224
- async getAppByName(name) {
225
- const apps = await this.listApps();
226
- const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
227
- if (!app) {
228
- return null;
137
+ async updateFile(reference, content, fileName) {
138
+ const blob = content instanceof Buffer ? new Blob([content]) : new Blob([content]);
139
+ const file = new farseer.WebFile([blob], fileName);
140
+ await this.client.farseerFiles.update(reference, file);
229
141
  }
230
- return this.getApp(app.reference);
231
- }
232
- /**
233
- * Create a new app
234
- */
235
- async createApp(name) {
236
- const appsFolderId = await this.getAppsFolderId();
237
- if (!appsFolderId) {
238
- throw new Error("Apps folder not found");
142
+ async deleteFile(reference) {
143
+ await this.client.farseerFiles.remove(reference);
239
144
  }
240
- return await this.apiRequest("/remoteJobs", "POST", {
241
- folderId: appsFolderId,
242
- name
243
- });
244
- }
245
- /**
246
- * Update an app
247
- */
248
- async updateApp(referenceId, update) {
249
- await this.apiRequest(`/remoteJobs/${referenceId}`, "PUT", {
250
- ...update,
251
- schedule: null,
252
- runnerName: null,
253
- predefinedActions: []
254
- });
255
- const app = await this.getApp(referenceId);
256
- if (!app) {
257
- throw new Error("Failed to fetch updated app");
145
+ async ensureFolderPath(folderPath) {
146
+ const currentPath = [];
147
+ for (const segment of folderPath) {
148
+ currentPath.push(segment);
149
+ try {
150
+ await this.client.getItemByPath(currentPath);
151
+ }
152
+ catch {
153
+ // Folder doesn't exist, create it
154
+ if (currentPath.length > 1) {
155
+ const parentPath = currentPath.slice(0, -1);
156
+ const parent = await this.client.getItemByPath(parentPath);
157
+ await this.client.folders.create({
158
+ parentId: parent.id,
159
+ name: segment,
160
+ allowedTypes: [],
161
+ });
162
+ }
163
+ }
164
+ }
258
165
  }
259
- return app;
260
- }
261
- /**
262
- * Delete an app
263
- */
264
- async deleteApp(referenceId) {
265
- await this.apiRequest(`/remoteJobs/${referenceId}`, "DELETE");
266
- }
267
- /**
268
- * Get script files available for apps
269
- */
270
- async getScriptFiles() {
271
- const allFiles = await this.listFiles(["Files"]);
272
- return allFiles.filter((f) => f.name.endsWith(".ts") || f.name.endsWith(".js")).map((f) => ({
273
- id: f.reference,
274
- name: f.name
275
- }));
276
- }
277
- /**
278
- * Export the entire model structure
279
- */
280
- async exportModel() {
281
- return this.apiRequest("/model/export", "POST");
282
- }
283
- /**
284
- * Get the Apps folder ID
285
- */
286
- async getAppsFolderId() {
287
- try {
288
- const item = await this.client.getItemByPath(["Apps"]);
289
- return item.id;
290
- } catch {
291
- return null;
166
+ async getFileByPath(filePath) {
167
+ const pathParts = ['Files', ...filePath.split('/')];
168
+ const fileName = pathParts.pop();
169
+ const folderPath = pathParts;
170
+ try {
171
+ const folder = await this.client.getItemByPath(folderPath);
172
+ const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);
173
+ for (const item of folderContent[0]?.items || []) {
174
+ if (item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {
175
+ return {
176
+ name: item.name,
177
+ path: filePath,
178
+ reference: item.reference,
179
+ };
180
+ }
181
+ }
182
+ }
183
+ catch {
184
+ return null;
185
+ }
186
+ return null;
292
187
  }
293
- }
294
- /**
295
- * Make a direct API request (for endpoints not in farseer-client)
296
- */
297
- async apiRequest(endpoint, method, body) {
298
- const url = `${this.credential.basePath}${endpoint}`;
299
- const headers = {
300
- "Content-Type": "application/json",
301
- "X-TENANT-ID": this.credential.tenantId,
302
- "X-API-KEY": this.credential.apiKey,
303
- "x-api-version": "3.3.0"
304
- };
305
- const response = await fetch(url, {
306
- method,
307
- headers,
308
- body: body ? JSON.stringify(body) : void 0
309
- });
310
- if (!response.ok) {
311
- throw new Error(`HTTP ${response.status}: ${await response.text()}`);
188
+ async getFileMetadata(reference) {
189
+ try {
190
+ const metadata = await this.client.farseerFiles.getMetadata(reference);
191
+ return {
192
+ uploadTime: metadata.uploadTime?.toISOString(),
193
+ uploader: metadata.uploader
194
+ ? {
195
+ id: metadata.uploader.id,
196
+ email: metadata.uploader.email || '',
197
+ firstName: metadata.uploader.firstName || '',
198
+ lastName: metadata.uploader.lastName || '',
199
+ }
200
+ : undefined,
201
+ size: metadata.size,
202
+ };
203
+ }
204
+ catch (error) {
205
+ // Metadata fetch failed - non-critical, continue without it
206
+ return null;
207
+ }
312
208
  }
313
- if (response.status === 204) {
314
- return void 0;
209
+ async getFileContentAsBuffer(reference) {
210
+ const blob = await this.client.farseerFiles.get(reference);
211
+ const arrayBuffer = await blob.arrayBuffer();
212
+ return Buffer.from(arrayBuffer);
213
+ }
214
+ isTextFile(filename) {
215
+ const ext = filename.toLowerCase().split('.').pop() || '';
216
+ return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);
217
+ }
218
+ isBinaryFile(filename) {
219
+ return !this.isTextFile(filename);
220
+ }
221
+ // ==================== Apps (Remote Jobs) API ====================
222
+ /**
223
+ * List all apps (Remote Jobs) on the tenant
224
+ */
225
+ async listApps() {
226
+ const response = await this.apiRequest('/remoteJobs', 'GET');
227
+ return response.map((app) => ({
228
+ id: app.id,
229
+ name: app.name,
230
+ type: 'REMOTE_JOB',
231
+ reference: String(app.id),
232
+ }));
233
+ }
234
+ /**
235
+ * Get app details by reference ID
236
+ */
237
+ async getApp(referenceId) {
238
+ try {
239
+ return await this.apiRequest(`/remoteJobs/${referenceId}`, 'GET');
240
+ }
241
+ catch {
242
+ return null;
243
+ }
244
+ }
245
+ /**
246
+ * Get app by name
247
+ */
248
+ async getAppByName(name) {
249
+ const apps = await this.listApps();
250
+ const app = apps.find((a) => a.name.toLowerCase() === name.toLowerCase());
251
+ if (!app) {
252
+ return null;
253
+ }
254
+ return this.getApp(app.reference);
255
+ }
256
+ /**
257
+ * Create a new app
258
+ */
259
+ async createApp(name) {
260
+ // Get Apps folder ID first
261
+ const appsFolderId = await this.getAppsFolderId();
262
+ if (!appsFolderId) {
263
+ throw new Error('Apps folder not found');
264
+ }
265
+ return await this.apiRequest('/remoteJobs', 'POST', {
266
+ folderId: appsFolderId,
267
+ name,
268
+ });
269
+ }
270
+ /**
271
+ * Update an app
272
+ */
273
+ async updateApp(referenceId, update) {
274
+ await this.apiRequest(`/remoteJobs/${referenceId}`, 'PUT', {
275
+ ...update,
276
+ schedule: null,
277
+ runnerName: null,
278
+ predefinedActions: [],
279
+ });
280
+ // API returns 204 No Content, so fetch the updated app
281
+ const app = await this.getApp(referenceId);
282
+ if (!app) {
283
+ throw new Error('Failed to fetch updated app');
284
+ }
285
+ return app;
286
+ }
287
+ /**
288
+ * Delete an app
289
+ */
290
+ async deleteApp(referenceId) {
291
+ await this.apiRequest(`/remoteJobs/${referenceId}`, 'DELETE');
292
+ }
293
+ /**
294
+ * Get script files available for apps
295
+ */
296
+ async getScriptFiles() {
297
+ const allFiles = await this.listFiles(['Files']);
298
+ return allFiles
299
+ .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))
300
+ .map((f) => ({
301
+ id: f.reference,
302
+ name: f.name,
303
+ }));
304
+ }
305
+ /**
306
+ * Export the entire model structure
307
+ */
308
+ async exportModel() {
309
+ return this.apiRequest('/model/export', 'POST');
310
+ }
311
+ /**
312
+ * Get the Apps folder ID
313
+ */
314
+ async getAppsFolderId() {
315
+ try {
316
+ const item = await this.client.getItemByPath(['Apps']);
317
+ return item.id;
318
+ }
319
+ catch {
320
+ return null;
321
+ }
322
+ }
323
+ /**
324
+ * Make a direct API request (for endpoints not in farseer-client)
325
+ */
326
+ async apiRequest(endpoint, method, body) {
327
+ const url = `${this.credential.basePath}${endpoint}`;
328
+ const headers = {
329
+ 'Content-Type': 'application/json',
330
+ 'X-TENANT-ID': this.credential.tenantId,
331
+ 'X-API-KEY': this.credential.apiKey,
332
+ 'x-api-version': '3.3.0',
333
+ };
334
+ const response = await fetch(url, {
335
+ method,
336
+ headers,
337
+ body: body ? JSON.stringify(body) : undefined,
338
+ });
339
+ if (!response.ok) {
340
+ throw new Error(`HTTP ${response.status}: ${await response.text()}`);
341
+ }
342
+ if (response.status === 204) {
343
+ return undefined;
344
+ }
345
+ return response.json();
315
346
  }
316
- return response.json();
317
- }
318
347
  }
348
+ exports.FarseerService = FarseerService;
319
349
  async function loginWithPassword(email, password) {
320
- const tokenUrl = "https://login.farseer.io/auth/realms/master/protocol/openid-connect/token";
321
- try {
322
- const response = await fetch(tokenUrl, {
323
- method: "POST",
324
- headers: {
325
- "Content-Type": "application/x-www-form-urlencoded"
326
- },
327
- body: new URLSearchParams({
328
- grant_type: "password",
329
- client_id: "security-admin-console",
330
- username: email,
331
- password
332
- })
333
- });
334
- if (!response.ok) {
335
- return null;
350
+ const tokenUrl = 'https://login.farseer.io/auth/realms/master/protocol/openid-connect/token';
351
+ try {
352
+ const response = await fetch(tokenUrl, {
353
+ method: 'POST',
354
+ headers: {
355
+ 'Content-Type': 'application/x-www-form-urlencoded',
356
+ },
357
+ body: new URLSearchParams({
358
+ grant_type: 'password',
359
+ client_id: 'security-admin-console',
360
+ username: email,
361
+ password: password,
362
+ }),
363
+ });
364
+ if (!response.ok) {
365
+ return null;
366
+ }
367
+ const data = (await response.json());
368
+ return {
369
+ accessToken: data.access_token,
370
+ refreshToken: data.refresh_token,
371
+ expiresIn: data.expires_in,
372
+ };
373
+ }
374
+ catch {
375
+ return null;
336
376
  }
337
- const data = await response.json();
338
- return {
339
- accessToken: data.access_token,
340
- refreshToken: data.refresh_token,
341
- expiresIn: data.expires_in
342
- };
343
- } catch {
344
- return null;
345
- }
346
377
  }
347
378
  function getErrorPage(title, message) {
348
- return `
379
+ return `
349
380
  <html>
350
381
  <head>
351
382
  <title>Farseer CLI - Error</title>
@@ -408,60 +439,64 @@ function getErrorPage(title, message) {
408
439
  </html>
409
440
  `;
410
441
  }
411
- async function loginWithBrowser(realm = "master") {
412
- const http = await import("http");
413
- const crypto = await import("crypto");
414
- const { exec } = await import("child_process");
415
- const { promisify } = await import("util");
416
- const execAsync = promisify(exec);
417
- const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;
418
- const CLIENT_ID = "auth";
419
- const REDIRECT_PORT = 8787;
420
- const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;
421
- const codeVerifier = crypto.randomBytes(32).toString("base64url");
422
- const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
423
- const state = crypto.randomBytes(16).toString("hex");
424
- return new Promise((resolve) => {
425
- const server = http.createServer(async (req, res) => {
426
- const url = new URL(req.url || "", `http://localhost:${REDIRECT_PORT}`);
427
- if (url.pathname === "/callback") {
428
- const code = url.searchParams.get("code");
429
- const returnedState = url.searchParams.get("state");
430
- const error = url.searchParams.get("error");
431
- if (error) {
432
- res.writeHead(200, { "Content-Type": "text/html" });
433
- res.end(getErrorPage("Login Failed", `Error: ${error}`));
434
- server.close();
435
- resolve(null);
436
- return;
437
- }
438
- if (!code || returnedState !== state) {
439
- res.writeHead(400, { "Content-Type": "text/html" });
440
- res.end(getErrorPage("Invalid Response", "Missing code or state mismatch."));
441
- server.close();
442
- resolve(null);
443
- return;
444
- }
445
- try {
446
- const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {
447
- method: "POST",
448
- headers: {
449
- "Content-Type": "application/x-www-form-urlencoded"
450
- },
451
- body: new URLSearchParams({
452
- grant_type: "authorization_code",
453
- client_id: CLIENT_ID,
454
- code,
455
- redirect_uri: REDIRECT_URI,
456
- code_verifier: codeVerifier
457
- })
458
- });
459
- if (!tokenResponse.ok) {
460
- throw new Error("Token exchange failed");
461
- }
462
- const data = await tokenResponse.json();
463
- res.writeHead(200, { "Content-Type": "text/html" });
464
- res.end(`
442
+ // Browser-based OAuth login with PKCE
443
+ async function loginWithBrowser(realm = 'master') {
444
+ const http = await Promise.resolve().then(() => __importStar(require('http')));
445
+ const crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
446
+ const { exec } = await Promise.resolve().then(() => __importStar(require('child_process')));
447
+ const { promisify } = await Promise.resolve().then(() => __importStar(require('util')));
448
+ const execAsync = promisify(exec);
449
+ const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;
450
+ const CLIENT_ID = 'auth'; // Use auth client with full scope access
451
+ const REDIRECT_PORT = 8787;
452
+ const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;
453
+ // Generate PKCE code verifier and challenge
454
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
455
+ const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
456
+ // Generate state for CSRF protection
457
+ const state = crypto.randomBytes(16).toString('hex');
458
+ return new Promise((resolve) => {
459
+ const server = http.createServer(async (req, res) => {
460
+ const url = new URL(req.url || '', `http://localhost:${REDIRECT_PORT}`);
461
+ if (url.pathname === '/callback') {
462
+ const code = url.searchParams.get('code');
463
+ const returnedState = url.searchParams.get('state');
464
+ const error = url.searchParams.get('error');
465
+ if (error) {
466
+ res.writeHead(200, { 'Content-Type': 'text/html' });
467
+ res.end(getErrorPage('Login Failed', `Error: ${error}`));
468
+ server.close();
469
+ resolve(null);
470
+ return;
471
+ }
472
+ if (!code || returnedState !== state) {
473
+ res.writeHead(400, { 'Content-Type': 'text/html' });
474
+ res.end(getErrorPage('Invalid Response', 'Missing code or state mismatch.'));
475
+ server.close();
476
+ resolve(null);
477
+ return;
478
+ }
479
+ // Exchange code for tokens
480
+ try {
481
+ const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {
482
+ method: 'POST',
483
+ headers: {
484
+ 'Content-Type': 'application/x-www-form-urlencoded',
485
+ },
486
+ body: new URLSearchParams({
487
+ grant_type: 'authorization_code',
488
+ client_id: CLIENT_ID,
489
+ code: code,
490
+ redirect_uri: REDIRECT_URI,
491
+ code_verifier: codeVerifier,
492
+ }),
493
+ });
494
+ if (!tokenResponse.ok) {
495
+ throw new Error('Token exchange failed');
496
+ }
497
+ const data = (await tokenResponse.json());
498
+ res.writeHead(200, { 'Content-Type': 'text/html' });
499
+ res.end(`
465
500
  <html>
466
501
  <head>
467
502
  <title>Farseer CLI - Login</title>
@@ -532,83 +567,81 @@ async function loginWithBrowser(realm = "master") {
532
567
  </body>
533
568
  </html>
534
569
  `);
535
- server.close();
536
- resolve({
537
- accessToken: data.access_token,
538
- refreshToken: data.refresh_token,
539
- expiresIn: data.expires_in
540
- });
541
- } catch {
542
- res.writeHead(500, { "Content-Type": "text/html" });
543
- res.end(getErrorPage("Token Exchange Failed", "Could not complete login."));
544
- server.close();
545
- resolve(null);
546
- }
547
- }
548
- });
549
- server.listen(REDIRECT_PORT, async () => {
550
- const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);
551
- authUrl.searchParams.set("client_id", CLIENT_ID);
552
- authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
553
- authUrl.searchParams.set("response_type", "code");
554
- authUrl.searchParams.set("scope", "openid offline_access");
555
- authUrl.searchParams.set("state", state);
556
- authUrl.searchParams.set("code_challenge", codeChallenge);
557
- authUrl.searchParams.set("code_challenge_method", "S256");
558
- const url = authUrl.toString();
559
- try {
560
- if (process.platform === "darwin") {
561
- await execAsync(`open "${url}"`);
562
- } else if (process.platform === "win32") {
563
- await execAsync(`start "${url}"`);
564
- } else {
565
- await execAsync(`xdg-open "${url}"`);
566
- }
567
- } catch {
568
- console.log(`
569
- Open this URL in your browser:
570
- ${url}
571
- `);
572
- }
570
+ server.close();
571
+ resolve({
572
+ accessToken: data.access_token,
573
+ refreshToken: data.refresh_token,
574
+ expiresIn: data.expires_in,
575
+ });
576
+ }
577
+ catch {
578
+ res.writeHead(500, { 'Content-Type': 'text/html' });
579
+ res.end(getErrorPage('Token Exchange Failed', 'Could not complete login.'));
580
+ server.close();
581
+ resolve(null);
582
+ }
583
+ }
584
+ });
585
+ server.listen(REDIRECT_PORT, async () => {
586
+ // Build authorization URL
587
+ const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);
588
+ authUrl.searchParams.set('client_id', CLIENT_ID);
589
+ authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
590
+ authUrl.searchParams.set('response_type', 'code');
591
+ authUrl.searchParams.set('scope', 'openid offline_access');
592
+ authUrl.searchParams.set('state', state);
593
+ authUrl.searchParams.set('code_challenge', codeChallenge);
594
+ authUrl.searchParams.set('code_challenge_method', 'S256');
595
+ // Open browser
596
+ const url = authUrl.toString();
597
+ try {
598
+ if (process.platform === 'darwin') {
599
+ await execAsync(`open "${url}"`);
600
+ }
601
+ else if (process.platform === 'win32') {
602
+ await execAsync(`start "${url}"`);
603
+ }
604
+ else {
605
+ await execAsync(`xdg-open "${url}"`);
606
+ }
607
+ }
608
+ catch {
609
+ // If we can't open browser, show URL to user
610
+ console.log(`\nOpen this URL in your browser:\n${url}\n`);
611
+ }
612
+ });
613
+ // Timeout after 5 minutes
614
+ setTimeout(() => {
615
+ server.close();
616
+ resolve(null);
617
+ }, 5 * 60 * 1000);
573
618
  });
574
- setTimeout(() => {
575
- server.close();
576
- resolve(null);
577
- }, 5 * 60 * 1e3);
578
- });
579
619
  }
580
- async function refreshAccessToken(refreshToken, realm = "master") {
581
- const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
582
- try {
583
- const response = await fetch(tokenUrl, {
584
- method: "POST",
585
- headers: {
586
- "Content-Type": "application/x-www-form-urlencoded"
587
- },
588
- body: new URLSearchParams({
589
- grant_type: "refresh_token",
590
- client_id: "auth",
591
- refresh_token: refreshToken
592
- })
593
- });
594
- if (!response.ok) {
595
- return null;
620
+ async function refreshAccessToken(refreshToken, realm = 'master') {
621
+ const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
622
+ try {
623
+ const response = await fetch(tokenUrl, {
624
+ method: 'POST',
625
+ headers: {
626
+ 'Content-Type': 'application/x-www-form-urlencoded',
627
+ },
628
+ body: new URLSearchParams({
629
+ grant_type: 'refresh_token',
630
+ client_id: 'auth',
631
+ refresh_token: refreshToken,
632
+ }),
633
+ });
634
+ if (!response.ok) {
635
+ return null;
636
+ }
637
+ const data = (await response.json());
638
+ return {
639
+ accessToken: data.access_token,
640
+ refreshToken: data.refresh_token,
641
+ expiresIn: data.expires_in,
642
+ };
643
+ }
644
+ catch {
645
+ return null;
596
646
  }
597
- const data = await response.json();
598
- return {
599
- accessToken: data.access_token,
600
- refreshToken: data.refresh_token,
601
- expiresIn: data.expires_in
602
- };
603
- } catch {
604
- return null;
605
- }
606
647
  }
607
- // Annotate the CommonJS export names for ESM import in node:
608
- 0 && (module.exports = {
609
- FarseerService,
610
- loginWithBrowser,
611
- loginWithPassword,
612
- refreshAccessToken
613
- });
614
- //# sourceMappingURL=farseerService.js.map