farseer-cli 1.0.6 → 1.0.9

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 (50) hide show
  1. package/dist/commands/checkout.js +2 -1
  2. package/dist/commands/checkout.js.map +2 -2
  3. package/dist/commands/diff.js +3 -1
  4. package/dist/commands/diff.js.map +2 -2
  5. package/dist/commands/dimensions.js +1 -1
  6. package/dist/commands/dimensions.js.map +2 -2
  7. package/dist/commands/files.js +1 -1
  8. package/dist/commands/files.js.map +2 -2
  9. package/dist/commands/install.js +3 -3
  10. package/dist/commands/install.js.map +2 -2
  11. package/dist/commands/pull.js +48 -2
  12. package/dist/commands/pull.js.map +3 -3
  13. package/dist/commands/push.js +14 -2
  14. package/dist/commands/push.js.map +2 -2
  15. package/dist/commands/status.js +12 -2
  16. package/dist/commands/status.js.map +2 -2
  17. package/dist/commands/variables.js +1 -1
  18. package/dist/commands/variables.js.map +2 -2
  19. package/dist/index.js +1 -0
  20. package/dist/index.js.map +2 -2
  21. package/dist/mcp/prompts/workflows.js +24 -13
  22. package/dist/mcp/prompts/workflows.js.map +2 -2
  23. package/dist/mcp/tools/appTools.js +77 -77
  24. package/dist/mcp/tools/appTools.js.map +3 -3
  25. package/dist/mcp/tools/authTools.js +3 -2
  26. package/dist/mcp/tools/authTools.js.map +2 -2
  27. package/dist/mcp/tools/dataTools.js +43 -47
  28. package/dist/mcp/tools/dataTools.js.map +2 -2
  29. package/dist/mcp/tools/modelTools.js +15 -19
  30. package/dist/mcp/tools/modelTools.js.map +2 -2
  31. package/dist/mcp/tools/runTools.js +28 -26
  32. package/dist/mcp/tools/runTools.js.map +2 -2
  33. package/dist/mcp/tools/syncTools.js +36 -8
  34. package/dist/mcp/tools/syncTools.js.map +2 -2
  35. package/dist/services/syncService.js +386 -112
  36. package/dist/services/syncService.js.map +3 -3
  37. package/dist/utils/constants.js +1 -1
  38. package/dist/utils/constants.js.map +1 -1
  39. package/dist/utils/helpers.js +3 -3
  40. package/dist/utils/helpers.js.map +1 -1
  41. package/docs/api-reference.md +372 -0
  42. package/docs/arquero-patterns.md +158 -0
  43. package/docs/cli-guide.md +160 -0
  44. package/docs/how-farseer-works.md +113 -0
  45. package/docs/import-workflows.md +306 -0
  46. package/docs/model-export.md +95 -0
  47. package/docs/new-app-template.md +240 -0
  48. package/docs/query-formulas.md +97 -0
  49. package/docs/troubleshooting.md +140 -0
  50. package/package.json +2 -1
@@ -0,0 +1,240 @@
1
+ # Creating Farseer Apps
2
+
3
+ ## What is a Farseer App?
4
+
5
+ A Farseer App is a TypeScript script that runs on the Farseer platform. Apps use the `farseer-client` library to interact with the Farseer API - importing data, exporting reports, syncing dimensions, managing sheets, etc.
6
+
7
+ **Key concept:** When you run an app via `farseer run`, the CLI automatically injects authentication credentials (API key or JWT) as environment variables. The `FarseerClient()` constructor picks these up automatically - **you never hardcode credentials in your scripts**.
8
+
9
+ ## End-to-End Workflow
10
+
11
+ ### Step 1: Write the Script
12
+
13
+ Create a TypeScript file in `farseer-apps/<tenant>/files/Scripts/`:
14
+
15
+ ```typescript
16
+ import * as farseer from 'farseer-client';
17
+
18
+ // FarseerClient auto-configures from environment variables
19
+ // injected by "farseer run" (TENANT_ID, FARSEER_URL, FARSEER_API_KEY/FARSEER_ACCESS_TOKEN)
20
+ const client = new farseer.FarseerClient();
21
+
22
+ async function main() {
23
+ // Initialize tag map (loads dimensions, variables, etc.)
24
+ await client.initTagMap();
25
+
26
+ // Your logic here
27
+ console.log('App running!');
28
+ }
29
+
30
+ main().catch(farseer.handleUnknownError);
31
+ ```
32
+
33
+ ### Step 2: Push the Script to Remote
34
+
35
+ ```bash
36
+ farseer push
37
+ ```
38
+
39
+ This uploads the script file to the Farseer server.
40
+
41
+ ### Step 3: Create the App
42
+
43
+ ```bash
44
+ farseer app create "My App Name"
45
+ ```
46
+
47
+ ### Step 4: Configure the App
48
+
49
+ ```bash
50
+ farseer app configure "My App Name" --entrypoint myScript.ts --scripts myScript.ts
51
+ ```
52
+
53
+ Optionally add arguments:
54
+ ```bash
55
+ farseer app configure "My App Name" --add-arg "Year=2025" --add-arg "Version=Plan"
56
+ ```
57
+
58
+ ### Step 5: Run the App
59
+
60
+ ```bash
61
+ # Run with default arguments
62
+ farseer run "My App Name"
63
+
64
+ # Override arguments
65
+ farseer run "My App Name" --arg "Year=2026"
66
+ ```
67
+
68
+ The CLI:
69
+ 1. Looks up the app config to find the entrypoint script
70
+ 2. Injects your credentials as environment variables
71
+ 3. Runs the script with `npx tsx`
72
+ 4. Passes arguments via command line (in order defined by app config)
73
+
74
+ ## How Authentication Works
75
+
76
+ You **never** put credentials in your scripts. The flow is:
77
+
78
+ 1. You authenticate once: `farseer login` (browser OAuth) or `farseer config set <tenant> --api-key <key>`
79
+ 2. When you run `farseer run "My App"`, the CLI injects these env vars:
80
+ - `TENANT_ID` - tenant identifier
81
+ - `FARSEER_URL` - API base URL (e.g., `https://myorg.farseer.io/api/v3`)
82
+ - `FARSEER_API_KEY` or `FARSEER_ACCESS_TOKEN` - credentials
83
+ 3. `new FarseerClient()` reads these env vars automatically
84
+
85
+ **Your script just does `new FarseerClient()` - that's it.**
86
+
87
+ ## Script Template
88
+
89
+ ### Basic App (no arguments)
90
+
91
+ ```typescript
92
+ import * as farseer from 'farseer-client';
93
+
94
+ const client = new farseer.FarseerClient();
95
+
96
+ async function main() {
97
+ await client.initTagMap();
98
+
99
+ // Example: list all variables
100
+ const tagMap = client.getTagMap();
101
+ const variables = Array.from(tagMap.variableMapByName.values());
102
+ console.log(`Found ${variables.length} variables`);
103
+ for (const v of variables) {
104
+ console.log(` - ${v.name}`);
105
+ }
106
+ }
107
+
108
+ main().catch(farseer.handleUnknownError);
109
+ ```
110
+
111
+ ### App with Arguments
112
+
113
+ Arguments are passed via `process.argv`:
114
+
115
+ ```typescript
116
+ import * as farseer from 'farseer-client';
117
+
118
+ const client = new farseer.FarseerClient();
119
+
120
+ // Arguments come in order defined by app config
121
+ const args = process.argv.slice(2);
122
+ const year = args[0] || '2025';
123
+ const version = args[1] || 'Plan';
124
+
125
+ async function main() {
126
+ await client.initTagMap();
127
+ console.log(`Processing ${year} ${version}...`);
128
+
129
+ // Export variable data filtered by year and version
130
+ const blob = await client.export.exportFormula({
131
+ format: farseer.ExportRequestFormatEnum.Csv,
132
+ formula: `sum("Revenue", "${year}", "${version}")`,
133
+ });
134
+
135
+ const csv = await blob.text();
136
+ console.log(csv);
137
+ }
138
+
139
+ main().catch(farseer.handleUnknownError);
140
+ ```
141
+
142
+ ### Data Import App
143
+
144
+ ```typescript
145
+ import * as farseer from 'farseer-client';
146
+
147
+ const client = new farseer.FarseerClient();
148
+
149
+ async function main() {
150
+ await client.initTagMap();
151
+
152
+ const importJob = await client.createImportJob({
153
+ title: 'My Import',
154
+ columns: [
155
+ { type: 'DIMENSION_TABLE', dimensionTableName: 'Product' },
156
+ { type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },
157
+ { type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },
158
+ { type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },
159
+ { type: 'VARIABLE', variableName: 'Revenue' },
160
+ ],
161
+ labels: ['auto', 'my-import'],
162
+ });
163
+
164
+ // Add data rows (columns in same order as above)
165
+ await importJob.addRows([
166
+ ['ProductA', 'Y2025', 'M1', 'Plan', 1000],
167
+ ['ProductA', 'Y2025', 'M2', 'Plan', 1200],
168
+ ['ProductB', 'Y2025', 'M1', 'Plan', 800],
169
+ ]);
170
+
171
+ await importJob.flushRows();
172
+ await importJob.undoPrevious(); // Remove previous import with same labels
173
+ await importJob.commit();
174
+
175
+ console.log('Import complete!');
176
+ }
177
+
178
+ main().catch(farseer.handleUnknownError);
179
+ ```
180
+
181
+ ## MCP Workflow (AI Agents)
182
+
183
+ When using MCP tools, the workflow is the same:
184
+
185
+ 1. **Write script**: Create/edit the file at `farseer-apps/<tenant>/files/Scripts/`
186
+ 2. **Push**: Use `farseer_push` tool to upload to remote
187
+ 3. **Create app**: Use `farseer_create_app` tool
188
+ 4. **Configure**: Use `farseer_configure_app` to set entrypoint and scripts
189
+ 5. **Run**: Use `farseer_run_app` to execute
190
+
191
+ ## File Structure
192
+
193
+ ```
194
+ farseer-apps/<tenant>/
195
+ ├── package.json # Dependencies (farseer-client, etc.)
196
+ ├── node_modules/ # Installed deps (farseer install)
197
+ ├── files/
198
+ │ └── Scripts/
199
+ │ ├── myScript.ts # Your scripts go here
200
+ │ └── utils.ts # Helper scripts
201
+ └── apps/
202
+ └── My App.json # App config (auto-managed by CLI)
203
+ ```
204
+
205
+ ## Common APIs
206
+
207
+ | API | Usage |
208
+ |-----|-------|
209
+ | `client.initTagMap()` | Load dimensions/variables metadata |
210
+ | `client.export.exportFormula({...})` | Export variable data as CSV/JSON |
211
+ | `client.createImportJob({...})` | Create data import job |
212
+ | `client.getDimensionTable(name)` | Get dimension table metadata |
213
+ | `client.data.loadFarseerDimensionTable(name)` | Load dimension as Arquero table |
214
+ | `client.sheets.getData({...})` | Get sheet data (columns + rows) |
215
+ | `client.findItemNode(name, type)` | Find item by name |
216
+ | `client.versions.list()` | List all versions |
217
+ | `client.cells.calculateOnDemandCells()` | Trigger on-demand calculations |
218
+ | `client.model.load({...})` | Sync dimension table structure |
219
+
220
+ ## Error Handling
221
+
222
+ Always use the standard error handler:
223
+
224
+ ```typescript
225
+ main().catch(farseer.handleUnknownError);
226
+ ```
227
+
228
+ Or custom:
229
+
230
+ ```typescript
231
+ main().catch(async (error: any) => {
232
+ console.error('Error:');
233
+ if (error && typeof error.text === 'function') {
234
+ console.error(await error.text());
235
+ } else {
236
+ console.error(error);
237
+ }
238
+ process.exit(1);
239
+ });
240
+ ```
@@ -0,0 +1,97 @@
1
+ # Query and Formula Guide
2
+
3
+ ## Exporting Data with Formulas
4
+
5
+ The primary way to query data from Farseer is through `export.exportFormula()`:
6
+
7
+ ```typescript
8
+ const blob = await client.export.exportFormula({
9
+ format: ExportRequestFormatEnum.Csv, // or Json, Xlsx
10
+ formula: 'sum("Revenue", "Y2025", "Plan")',
11
+ });
12
+
13
+ const csvText = await blob.text();
14
+ ```
15
+
16
+ ### Formula Syntax
17
+
18
+ ```
19
+ sum("VariableName", "DimensionMember1", "DimensionMember2", ...)
20
+ ```
21
+
22
+ - First argument is always the variable name
23
+ - Additional arguments filter by dimension members
24
+ - Members are matched by name across all dimensions
25
+ - Unspecified dimensions return all members (expanded)
26
+
27
+ ### Examples
28
+
29
+ ```typescript
30
+ // All revenue data for 2025 Plan
31
+ formula: 'sum("Revenue", "Y2025", "Plan")'
32
+
33
+ // Revenue for a specific product
34
+ formula: 'sum("Revenue", "Y2025", "Plan", "Product A")'
35
+
36
+ // Revenue across all years for Actual version
37
+ formula: 'sum("Revenue", "Actual")'
38
+ ```
39
+
40
+ ### Output Format
41
+
42
+ CSV output includes columns for each dimension plus a `value` column:
43
+
44
+ ```csv
45
+ Product,Months,Years,Versions,value,valueType
46
+ Product A,M1,Y2025,Plan,10000,Input
47
+ Product A,M2,Y2025,Plan,12000,Input
48
+ Product B,M1,Y2025,Plan,8000,Calculated
49
+ ```
50
+
51
+ The `valueType` column indicates whether the value is `Input` (manually entered or imported) or `Calculated` (from a formula).
52
+
53
+ ## Loading Variable Data
54
+
55
+ Alternative method using the data API:
56
+
57
+ ```typescript
58
+ const result = await client.data.loadFarseerVariable(
59
+ 'Revenue',
60
+ 'Product', 'Months', 'Years' // dimensions to include as columns
61
+ );
62
+
63
+ // Returns an Arquero table
64
+ result.table.print();
65
+ ```
66
+
67
+ ## Loading Dimension Tables
68
+
69
+ ```typescript
70
+ const productTable = await client.data.loadFarseerDimensionTable('Product');
71
+ productTable.table.print();
72
+
73
+ // Filter
74
+ const filtered = productTable.table
75
+ .filter(d => d?.['Category'][0] === 'Electronics')
76
+ .reify();
77
+ ```
78
+
79
+ ## Getting Variable Metadata
80
+
81
+ ```typescript
82
+ // Get variable info (dimensions, formula, roll-up type)
83
+ const revenue = await client.getVariable('Revenue');
84
+ console.log(revenue.dimensionTagIds); // IDs of dimension tables
85
+ console.log(revenue.expression); // Formula if calculated
86
+ console.log(revenue.rollupType); // SUM, AVERAGE, etc.
87
+ ```
88
+
89
+ ## Getting Dimension Members
90
+
91
+ ```typescript
92
+ // Get all members of a dimension
93
+ const members = client.getDimensionMembersForTable('Product');
94
+ for (const member of members) {
95
+ console.log(member.name);
96
+ }
97
+ ```
@@ -0,0 +1,140 @@
1
+ # Troubleshooting & Common Errors
2
+
3
+ This document covers common errors and their solutions when working with farseer-client.
4
+
5
+ ## Common Errors
6
+
7
+ ### Error: Dimension connections not filtering correctly
8
+
9
+ When filtering Arquero tables loaded from Farseer dimension tables, connections to other dimension tables are **arrays/lists**, not single values.
10
+
11
+ ```typescript
12
+ // WRONG - Won't work, connections are arrays
13
+ const productTable = await client.data.loadFarseerDimensionTable('Product');
14
+ const electronics = productTable.table.filter(d => d?.['Category'] === 'Electronics');
15
+ // Returns empty or incorrect results
16
+
17
+ // CORRECT - Use [0] to access first element
18
+ const electronics = productTable.table.filter(d => d?.['Category'][0] === 'Electronics');
19
+ // Works correctly
20
+ ```
21
+
22
+ **Why:** In Farseer, dimension table connections (foreign keys) are stored as arrays to support potential multiple connections in the future. Always access the first element with `[0]` when filtering or transforming.
23
+
24
+ **Solution:** Always use `[0]` when accessing connected dimension columns:
25
+
26
+ ```typescript
27
+ const productTable = await client.data.loadFarseerDimensionTable('Product');
28
+
29
+ // Filtering by connection
30
+ const filtered = productTable.table.filter(d => d?.['Category'][0] === 'Electronics');
31
+
32
+ // Deriving new columns from connections
33
+ const enriched = productTable.table.derive({
34
+ CategoryName: d => d?.['Category'][0] || 'Unknown',
35
+ SupplierName: d => d?.['Supplier'][0] || 'N/A'
36
+ });
37
+
38
+ // Grouping by connection
39
+ const grouped = productTable.table
40
+ .groupby(d => d?.['Category'][0])
41
+ .count();
42
+ ```
43
+
44
+ ---
45
+
46
+ ### Error: Unsupported expression construct: ChainExpression
47
+
48
+ When using optional chaining (`?.`) or other modern JavaScript syntax in Arquero filter/derive expressions, you may encounter this error:
49
+
50
+ ```
51
+ Error: Unsupported expression construct: ChainExpression
52
+ at visit (/node_modules/arquero/dist/arquero.node.js:2907:7)
53
+ ```
54
+
55
+ **The Problem:**
56
+
57
+ ```typescript
58
+ // WRONG - Optional chaining not supported in Arquero's parser
59
+ const filtered = table.filter((d: any) => d?.value !== null && d?.value !== 0);
60
+ // Error: Unsupported expression construct: ChainExpression
61
+ ```
62
+
63
+ **Why:** Arquero parses filter/derive expressions to optimize performance. It doesn't support all modern JavaScript syntax, including optional chaining (`?.`), nullish coalescing (`??`), and some other ES2020+ features.
64
+
65
+ **Solution:** Wrap the expression in `aq.escape()` to use the function as-is without parsing:
66
+
67
+ ```typescript
68
+ import * as aq from 'arquero';
69
+
70
+ // CORRECT - Use aq.escape() for expressions with optional chaining
71
+ const filtered = table.filter(aq.escape((d: any) => d?.value !== null && d?.value !== 0));
72
+ // Works correctly
73
+
74
+ // CORRECT - Also use aq.escape() in derive
75
+ const transformed = table.derive({
76
+ Years: aq.escape((d: any) => d.Years?.substring(1)),
77
+ Months: aq.escape((d: any) => d.Months?.substring(1))
78
+ });
79
+ ```
80
+
81
+ **When to use `aq.escape()`:**
82
+ - Optional chaining: `d?.value`, `d?.property?.nested`
83
+ - Nullish coalescing: `d.value ?? 0`
84
+ - Other modern syntax that causes parse errors
85
+ - Complex logic that Arquero's parser rejects
86
+
87
+ **When NOT to use `aq.escape()`:**
88
+ - Simple expressions: `d => d.value > 0` (works without escape)
89
+ - After `.objects()`: Standard JavaScript array methods don't need escape
90
+ ```typescript
91
+ // No escape needed - this is a plain JavaScript array
92
+ const rows = table.objects().filter((d: any) => d?.value > 0);
93
+ ```
94
+
95
+ **Related:** See Arquero documentation on `aq.escape()` at https://uwdata.github.io/arquero/api/op#escape
96
+
97
+ ---
98
+
99
+
100
+ ### Error: TAG_IDs are incorrect/outdated
101
+
102
+ **Problem:** Import fails because hardcoded tag IDs no longer match Farseer.
103
+
104
+ **Solution:**
105
+ 1. Log into Farseer UI
106
+ 2. Inspect dimension/variable properties to get correct IDs
107
+ 3. Update `tagIds.ts` with correct values
108
+
109
+ ---
110
+
111
+ ## Debugging Tips
112
+
113
+ ### Check existing dimension members
114
+ ```typescript
115
+ await client.initTagMap();
116
+ const products = client.getDimensionMembersForTable('Product');
117
+ console.log('Existing products:', Array.from(products.keys()));
118
+ ```
119
+
120
+ ### Validate data before import
121
+ ```typescript
122
+ const validProducts = Array.from(products.keys());
123
+ const validData = data.filter(row => validProducts.includes(row.product));
124
+ const invalidCount = data.length - validData.length;
125
+ if (invalidCount > 0) {
126
+ console.log(`${invalidCount} rows with invalid products were skipped`);
127
+ }
128
+ ```
129
+
130
+ ### Dry run model.load
131
+ ```typescript
132
+ await client.model.load({
133
+ model: { tables: [...] },
134
+ options: {
135
+ dryRun: true // Preview changes without applying
136
+ }
137
+ });
138
+ ```
139
+
140
+ When you resolve an error which is not documented, ask the developer if he wants to add it to the list. Do not add without asking!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "farseer-cli",
3
- "version": "1.0.6",
3
+ "version": "1.0.9",
4
4
  "description": "CLI tool for syncing Farseer App scripts between local folder and Farseer instances",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "files": [
10
10
  "dist",
11
+ "docs",
11
12
  "README.md",
12
13
  "LICENSE"
13
14
  ],