farseer-cli 1.14.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/model.js +14 -4
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/pull.js +7 -2
- package/dist/commands/pull.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +1 -1
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/pipeline/generated-reference.json +30 -30
- package/dist/pipeline/service.js +1 -1
- package/dist/pipeline/service.js.map +1 -1
- package/dist/utils/constants.js +4 -7
- package/dist/utils/constants.js.map +2 -2
- package/dist/utils/packageManager.js +40 -11
- package/dist/utils/packageManager.js.map +2 -2
- package/dist/utils/updateCheck.js +4 -2
- package/dist/utils/updateCheck.js.map +2 -2
- package/docs/pipeline-client-guide.md +3 -3
- package/docs/pipeline-reference.md +156 -99
- package/package.json +2 -2
- package/skills/pipeline-authoring/SKILL.md +10 -8
- package/skills/pipeline-authoring/practices.md +39 -25
package/dist/commands/model.js
CHANGED
|
@@ -25,6 +25,7 @@ var import_logger = require("../utils/logger");
|
|
|
25
25
|
var import_authErrors = require("../services/authErrors");
|
|
26
26
|
var import_preflight = require("../services/preflight");
|
|
27
27
|
var import_modelExport = require("../services/modelExport");
|
|
28
|
+
var import_nameResolver = require("../utils/nameResolver");
|
|
28
29
|
function registerModelCommand(program) {
|
|
29
30
|
program.command("model [tenant]").description("Export and display the model structure (dimensions, variables)").option("--json", "Output raw JSON").option("--tables", "Show only dimension tables").option("--variables", "Show only variables").option("--variable <name>", "Show details for specific variable").option("--table <name>", "Show details for specific dimension table").action(async (tenantArg, options) => {
|
|
30
31
|
const { tenant, client: api } = await (0, import_preflight.preflight)(tenantArg);
|
|
@@ -54,14 +55,19 @@ function registerModelCommand(program) {
|
|
|
54
55
|
} else {
|
|
55
56
|
model = await api.exportModel({ types: ["DTAB", "VAR"] });
|
|
56
57
|
}
|
|
57
|
-
if (options.json) {
|
|
58
|
+
if (options.json && !options.variable) {
|
|
58
59
|
console.log(JSON.stringify(model, null, 2));
|
|
59
60
|
return;
|
|
60
61
|
}
|
|
61
62
|
if (options.variable) {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
const matches = (0, import_nameResolver.matchByName)(model.variables, options.variable);
|
|
64
|
+
if (matches.length > 1) {
|
|
65
|
+
import_logger.logger.error(
|
|
66
|
+
(0, import_nameResolver.formatAmbiguous)("variables", options.variable, matches, (v) => String(v.gid ?? v.name))
|
|
67
|
+
);
|
|
68
|
+
process.exit(1);
|
|
69
|
+
}
|
|
70
|
+
const variable = matches[0];
|
|
65
71
|
if (!variable) {
|
|
66
72
|
import_logger.logger.error(`Variable "${options.variable}" not found.`);
|
|
67
73
|
import_logger.logger.dim("Available variables:");
|
|
@@ -71,6 +77,10 @@ function registerModelCommand(program) {
|
|
|
71
77
|
}
|
|
72
78
|
process.exit(1);
|
|
73
79
|
}
|
|
80
|
+
if (options.json) {
|
|
81
|
+
console.log(JSON.stringify(variable, null, 2));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
74
84
|
import_logger.logger.header(`Variable: ${variable.name}`);
|
|
75
85
|
console.log();
|
|
76
86
|
if (variable.description) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/model.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\nimport { formatVariableMembers } from '../services/modelExport';\n\nexport function registerModelCommand(program: Command): void {\n program\n .command('model [tenant]')\n .description('Export and display the model structure (dimensions, variables)')\n .option('--json', 'Output raw JSON')\n .option('--tables', 'Show only dimension tables')\n .option('--variables', 'Show only variables')\n .option('--variable <name>', 'Show details for specific variable')\n .option('--table <name>', 'Show details for specific dimension table')\n .action(async (tenantArg, options) => {\n const { tenant, client: api } = await preflight(tenantArg);\n\n try {\n // Pick the smallest scope that satisfies the requested\n // output. An unscoped DTAB+DMEM+VAR fetch breaks the\n // response limit on large tenants; `--json` is the\n // worst case because it asks for the whole thing.\n let model;\n if (options.variable || options.variables) {\n model = await api.exportModel({ types: ['VAR'] });\n } else if (options.table) {\n // Single-table member fetch via entities API.\n // `/model/export` with `tableGids` 500s for some\n // tables on large tenants (separate backend bug);\n // the entities path is reliable.\n const table = await api.loadDimensionTableWithMembers(options.table);\n if (!table) {\n logger.error(`Table \"${options.table}\" not found.`);\n const summary = await api.exportModel({ types: ['DTAB'] });\n logger.dim('Available tables:');\n summary.tables.slice(0, 10).forEach((t) => logger.dim(` - ${t.name}`));\n if (summary.tables.length > 10) {\n logger.dim(` ... and ${summary.tables.length - 10} more`);\n }\n process.exit(1);\n }\n model = {\n tables: [table],\n variables: [],\n dependencies: { tables: [], members: [], variables: [] },\n };\n } else if (options.tables) {\n model = await api.exportModel({ types: ['DTAB'] });\n } else {\n // Default summary view \u2014 counts of tables /\n // variables and a name preview, no member rows.\n model = await api.exportModel({ types: ['DTAB', 'VAR'] });\n }\n\n // Raw JSON output\n if (options.json) {\n console.log(JSON.stringify(model, null, 2));\n return;\n }\n\n // Specific variable details\n if (options.variable) {\n const variable = model.variables.find(\n (v) => v.name.toLowerCase() === options.variable.toLowerCase(),\n );\n if (!variable) {\n logger.error(`Variable \"${options.variable}\" not found.`);\n logger.dim('Available variables:');\n model.variables.slice(0, 10).forEach((v) => logger.dim(` - ${v.name}`));\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n process.exit(1);\n }\n\n logger.header(`Variable: ${variable.name}`);\n console.log();\n if (variable.description) {\n console.log(` Description: ${variable.description}`);\n }\n if (variable.formula) {\n console.log(` Formula: ${variable.formula}`);\n }\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.members.length > 0) {\n console.log(` Specific members: ${formatVariableMembers(variable.members)}`);\n }\n console.log(` Roll-up type: ${variable.rollupType}`);\n console.log(` Data type: ${variable.dataType}`);\n if (variable.numberFormat) {\n console.log(\n ` Format: ${variable.numberFormat.type}${variable.numberFormat.formatString ? ` (${variable.numberFormat.formatString})` : ''}`,\n );\n }\n console.log(` Readonly: ${variable.readonly}`);\n console.log(` Calculate on demand: ${variable.calculateOnDemand}`);\n if (variable.folderPath) {\n console.log(` Folder: ${variable.folderPath.join(' / ')}`);\n }\n return;\n }\n\n // Specific table details. The dispatch above already\n // resolved name \u2192 single-table fetch and exited if the\n // table didn't exist, so model.tables is exactly [target].\n if (options.table) {\n const table = model.tables[0];\n\n logger.header(`Dimension Table: ${table.name}`);\n console.log();\n console.log(` Columns:`);\n table.columns.forEach((col, i) => {\n let colInfo = ` ${i + 1}. ${col.type}`;\n if (col.name) colInfo += ` (${col.name})`;\n if (col.foreignKeyTableName) colInfo += ` \u2192 ${col.foreignKeyTableName}`;\n console.log(colInfo);\n });\n console.log(` Members: ${table.rows.length}`);\n if (table.folderPath) {\n console.log(` Folder: ${table.folderPath.join(' / ')}`);\n }\n if (table.rows.length > 0) {\n console.log(` Sample members:`);\n table.rows.slice(0, 5).forEach((row) => {\n console.log(` - ${row[0]}`);\n });\n if (table.rows.length > 5) {\n console.log(` ... and ${table.rows.length - 5} more`);\n }\n }\n return;\n }\n\n // Tables only\n if (options.tables) {\n logger.header(`Dimension Tables (${model.tables.length})`);\n console.log();\n for (const table of model.tables) {\n const fkColumns = table.columns.filter((c) => c.type === 'FOREIGN_KEY');\n let info = ` \uD83D\uDCCB ${table.name}`;\n if (fkColumns.length > 0) {\n info += ` \u2192 ${fkColumns.map((c) => c.foreignKeyTableName).join(', ')}`;\n }\n console.log(info);\n }\n logger.dim('Run with --table <name> to see members for a specific table.');\n return;\n }\n\n // Variables only\n if (options.variables) {\n logger.header(`Variables (${model.variables.length})`);\n console.log();\n for (const variable of model.variables) {\n console.log(` \uD83D\uDCCA ${variable.name}`);\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.formula) {\n console.log(\n ` Formula: ${variable.formula.substring(0, 50)}${variable.formula.length > 50 ? '...' : ''}`,\n );\n }\n console.log();\n }\n return;\n }\n\n // Default: summary\n logger.header(`Model Summary for ${tenant}`);\n console.log();\n console.log(` Dimension Tables: ${model.tables.length}`);\n console.log(` Variables: ${model.variables.length}`);\n console.log();\n\n logger.dim('Dimension Tables:');\n model.tables.slice(0, 10).forEach((t) => {\n logger.dim(` - ${t.name}`);\n });\n if (model.tables.length > 10) {\n logger.dim(` ... and ${model.tables.length - 10} more`);\n }\n console.log();\n\n logger.dim('Variables (first 10):');\n model.variables.slice(0, 10).forEach((v) => {\n logger.dim(` - ${v.name} [${v.tables.join(', ')}]`);\n });\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n console.log();\n\n logger.dim('Use --tables, --variables, --table <name>, or --variable <name> for details.');\n logger.dim('Use --json for raw JSON output.');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error(`Tenant \"${tenant}\" not found or not accessible.`);\n logger.dim('Check that the tenant name is correct.');\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n logger.dim('Check your network connection.');\n } else {\n logger.error('Failed to export model.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n }\n });\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,wBAA6C;AAC7C,uBAA0B;AAC1B,yBAAsC;
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\nimport { formatVariableMembers } from '../services/modelExport';\nimport { formatAmbiguous, matchByName } from '../utils/nameResolver';\n\nexport function registerModelCommand(program: Command): void {\n program\n .command('model [tenant]')\n .description('Export and display the model structure (dimensions, variables)')\n .option('--json', 'Output raw JSON')\n .option('--tables', 'Show only dimension tables')\n .option('--variables', 'Show only variables')\n .option('--variable <name>', 'Show details for specific variable')\n .option('--table <name>', 'Show details for specific dimension table')\n .action(async (tenantArg, options) => {\n const { tenant, client: api } = await preflight(tenantArg);\n\n try {\n // Pick the smallest scope that satisfies the requested\n // output. An unscoped DTAB+DMEM+VAR fetch breaks the\n // response limit on large tenants; `--json` is the\n // worst case because it asks for the whole thing.\n let model;\n if (options.variable || options.variables) {\n model = await api.exportModel({ types: ['VAR'] });\n } else if (options.table) {\n // Single-table member fetch via entities API.\n // `/model/export` with `tableGids` 500s for some\n // tables on large tenants (separate backend bug);\n // the entities path is reliable.\n const table = await api.loadDimensionTableWithMembers(options.table);\n if (!table) {\n logger.error(`Table \"${options.table}\" not found.`);\n const summary = await api.exportModel({ types: ['DTAB'] });\n logger.dim('Available tables:');\n summary.tables.slice(0, 10).forEach((t) => logger.dim(` - ${t.name}`));\n if (summary.tables.length > 10) {\n logger.dim(` ... and ${summary.tables.length - 10} more`);\n }\n process.exit(1);\n }\n model = {\n tables: [table],\n variables: [],\n dependencies: { tables: [], members: [], variables: [] },\n };\n } else if (options.tables) {\n model = await api.exportModel({ types: ['DTAB'] });\n } else {\n // Default summary view \u2014 counts of tables /\n // variables and a name preview, no member rows.\n model = await api.exportModel({ types: ['DTAB', 'VAR'] });\n }\n\n // Raw JSON output; a requested variable is narrowed to first, below.\n if (options.json && !options.variable) {\n console.log(JSON.stringify(model, null, 2));\n return;\n }\n\n // Specific variable details\n if (options.variable) {\n const matches = matchByName(model.variables, options.variable);\n if (matches.length > 1) {\n logger.error(\n formatAmbiguous('variables', options.variable, matches, (v) => String(v.gid ?? v.name)),\n );\n process.exit(1);\n }\n const variable = matches[0];\n if (!variable) {\n logger.error(`Variable \"${options.variable}\" not found.`);\n logger.dim('Available variables:');\n model.variables.slice(0, 10).forEach((v) => logger.dim(` - ${v.name}`));\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n process.exit(1);\n }\n if (options.json) {\n console.log(JSON.stringify(variable, null, 2));\n return;\n }\n\n logger.header(`Variable: ${variable.name}`);\n console.log();\n if (variable.description) {\n console.log(` Description: ${variable.description}`);\n }\n if (variable.formula) {\n console.log(` Formula: ${variable.formula}`);\n }\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.members.length > 0) {\n console.log(` Specific members: ${formatVariableMembers(variable.members)}`);\n }\n console.log(` Roll-up type: ${variable.rollupType}`);\n console.log(` Data type: ${variable.dataType}`);\n if (variable.numberFormat) {\n console.log(\n ` Format: ${variable.numberFormat.type}${variable.numberFormat.formatString ? ` (${variable.numberFormat.formatString})` : ''}`,\n );\n }\n console.log(` Readonly: ${variable.readonly}`);\n console.log(` Calculate on demand: ${variable.calculateOnDemand}`);\n if (variable.folderPath) {\n console.log(` Folder: ${variable.folderPath.join(' / ')}`);\n }\n return;\n }\n\n // Specific table details. The dispatch above already\n // resolved name \u2192 single-table fetch and exited if the\n // table didn't exist, so model.tables is exactly [target].\n if (options.table) {\n const table = model.tables[0];\n\n logger.header(`Dimension Table: ${table.name}`);\n console.log();\n console.log(` Columns:`);\n table.columns.forEach((col, i) => {\n let colInfo = ` ${i + 1}. ${col.type}`;\n if (col.name) colInfo += ` (${col.name})`;\n if (col.foreignKeyTableName) colInfo += ` \u2192 ${col.foreignKeyTableName}`;\n console.log(colInfo);\n });\n console.log(` Members: ${table.rows.length}`);\n if (table.folderPath) {\n console.log(` Folder: ${table.folderPath.join(' / ')}`);\n }\n if (table.rows.length > 0) {\n console.log(` Sample members:`);\n table.rows.slice(0, 5).forEach((row) => {\n console.log(` - ${row[0]}`);\n });\n if (table.rows.length > 5) {\n console.log(` ... and ${table.rows.length - 5} more`);\n }\n }\n return;\n }\n\n // Tables only\n if (options.tables) {\n logger.header(`Dimension Tables (${model.tables.length})`);\n console.log();\n for (const table of model.tables) {\n const fkColumns = table.columns.filter((c) => c.type === 'FOREIGN_KEY');\n let info = ` \uD83D\uDCCB ${table.name}`;\n if (fkColumns.length > 0) {\n info += ` \u2192 ${fkColumns.map((c) => c.foreignKeyTableName).join(', ')}`;\n }\n console.log(info);\n }\n logger.dim('Run with --table <name> to see members for a specific table.');\n return;\n }\n\n // Variables only\n if (options.variables) {\n logger.header(`Variables (${model.variables.length})`);\n console.log();\n for (const variable of model.variables) {\n console.log(` \uD83D\uDCCA ${variable.name}`);\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.formula) {\n console.log(\n ` Formula: ${variable.formula.substring(0, 50)}${variable.formula.length > 50 ? '...' : ''}`,\n );\n }\n console.log();\n }\n return;\n }\n\n // Default: summary\n logger.header(`Model Summary for ${tenant}`);\n console.log();\n console.log(` Dimension Tables: ${model.tables.length}`);\n console.log(` Variables: ${model.variables.length}`);\n console.log();\n\n logger.dim('Dimension Tables:');\n model.tables.slice(0, 10).forEach((t) => {\n logger.dim(` - ${t.name}`);\n });\n if (model.tables.length > 10) {\n logger.dim(` ... and ${model.tables.length - 10} more`);\n }\n console.log();\n\n logger.dim('Variables (first 10):');\n model.variables.slice(0, 10).forEach((v) => {\n logger.dim(` - ${v.name} [${v.tables.join(', ')}]`);\n });\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n console.log();\n\n logger.dim('Use --tables, --variables, --table <name>, or --variable <name> for details.');\n logger.dim('Use --json for raw JSON output.');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error(`Tenant \"${tenant}\" not found or not accessible.`);\n logger.dim('Check that the tenant name is correct.');\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n logger.dim('Check your network connection.');\n } else {\n logger.error('Failed to export model.');\n logger.dim(error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AAO,MAAM,+BAA+B;AAC5C,6BAAO,IAAI,gCAAgC;AAAA,MAC/C,OAAO;AACH,6BAAO,MAAM,yBAAyB;AACtC,6BAAO,IAAI,YAAY;AAAA,MAC3B;AACA,cAAQ,KAAK,CAAC;AAAA,IAClB;AAAA,EACJ,CAAC;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/commands/pull.js
CHANGED
|
@@ -44,6 +44,7 @@ var import_fileValidation = require("../utils/fileValidation");
|
|
|
44
44
|
var import_cliOptions = require("../utils/cliOptions");
|
|
45
45
|
var import_constants = require("../utils/constants");
|
|
46
46
|
var import_workspace = require("../utils/workspace");
|
|
47
|
+
var import_packageManager = require("../utils/packageManager");
|
|
47
48
|
var fs = __toESM(require("fs"));
|
|
48
49
|
var path = __toESM(require("path"));
|
|
49
50
|
function registerPullCommand(program) {
|
|
@@ -66,6 +67,11 @@ function registerPullCommand(program) {
|
|
|
66
67
|
(0, import_helpers.ensureDirectoryExists)(tenantDir);
|
|
67
68
|
(0, import_workspace.ensureGitignoreEntries)(path.join(tenantDir, ".gitignore"));
|
|
68
69
|
await createDefaultPackageJson(tenantDir, tenant);
|
|
70
|
+
const packageChanges = (0, import_packageManager.updatePackageJson)(tenantDir);
|
|
71
|
+
if (packageChanges.length > 0) {
|
|
72
|
+
import_logger.logger.info(`Updated package.json: ${packageChanges.join(", ")}`);
|
|
73
|
+
import_logger.logger.dim(`Run "farseer install ${tenant}" to update node_modules.`);
|
|
74
|
+
}
|
|
69
75
|
const includeExtensions = (0, import_cliOptions.normalizeExtensions)(options.includeExt);
|
|
70
76
|
const includeFolders = options.includeFolder;
|
|
71
77
|
const filterOptions = {
|
|
@@ -400,8 +406,7 @@ async function createDefaultPackageJson(tenantDir, tenant) {
|
|
|
400
406
|
dotenv: "^16.4.5",
|
|
401
407
|
"draft-js": "^0.11.7",
|
|
402
408
|
exceljs: "^4.4.0",
|
|
403
|
-
"farseer-client": import_constants.
|
|
404
|
-
"farseer-client-axios": import_constants.FARSEER_CLIENT_AXIOS_URL,
|
|
409
|
+
"farseer-client": import_constants.FARSEER_CLIENT_DEPENDENCY,
|
|
405
410
|
"fast-xml-parser": "^4.5.0",
|
|
406
411
|
"form-data": "^4.0.0",
|
|
407
412
|
googleapis: "^144.0.0",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/pull.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { fileLogger } from '../utils/fileLogger';\nimport { preflight } from '../services/preflight';\nimport { SyncService, ConflictResolutions, SyncStatus } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantDir,\n getTenantFilesDir,\n ensureDirectoryExists,\n appendToAuditLog,\n AuditLogEntry,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { isLikelyTextFile } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport { FARSEER_CLIENT_URL, FARSEER_CLIENT_AXIOS_URL } from '../utils/constants';\nimport { ensureGitignoreEntries } from '../utils/workspace';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Pull semantics:\n *\n * farseer pull\n * 1. Show local-vs-remote diff. If you have unsynced local edits OR\n * remote has deletions that would remove local files/apps, the\n * command stops here and asks for confirmation before doing\n * anything (we don't merge or delete silently).\n * 2. Apply remote-side changes (downloads, deletions, modifications).\n * Per-file conflicts are resolved interactively.\n *\n * farseer pull --force\n * Hard reset to remote. After it runs, the working tree mirrors what's\n * on remote: any file that exists locally but not on remote is deleted,\n * remote versions overwrite local edits, deletions are accepted. Always\n * asks for confirmation because the operation is destructive.\n */\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description(\n 'Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)',\n )\n .option(\n '--all',\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in via --include-ext .csv or `farseer config include --ext .csv`.',\n )\n .option(\n '--force',\n 'Hard reset local to remote within the current sync scope: overwrite local edits, delete local-only files. Files outside scope (data files like .csv on a default run without --include-ext .csv) are NOT touched. Always asks for confirmation.',\n )\n .option(\n '-y, --yes',\n 'Skip confirmation when local has uncommitted changes OR remote has deletions that would remove local files/apps (ignored under --force)',\n )\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .action(async (arg1, arg2, options) => {\n // preflight resolves the target, authenticates, and confirms the\n // org owns the tenant (the guard that used to live only in\n // `checkout`). pull is the setup path now, so scaffolding follows.\n const target = await preflight(arg1, arg2);\n const { organisation, tenant, client } = target;\n\n const syncService = new SyncService(tenant, client);\n\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Ensure .gitignore covers `.farseer-sync.json` on the first pull\n // into a fresh workspace. Without it, a workspace initialized by\n // `farseer pull` would commit the per-machine baseline and\n // reproduce the cross-machine drift bug the gitignore prevents.\n ensureGitignoreEntries(path.join(tenantDir, '.gitignore'));\n\n await createDefaultPackageJson(tenantDir, tenant);\n\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const filterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\n const syncOptions = {\n all: options.all,\n force: options.force,\n ...filterOptions,\n };\n\n // Step 1: Inspect current state. We do this BEFORE mutating\n // anything so the user can decide whether to bail.\n const filesDir = getTenantFilesDir(tenant);\n const folderInitialised = fs.existsSync(filesDir);\n\n // With `checkout` gone, a first pull IS the setup \u2014 so it has to\n // close by naming the one step the CLI can't do itself: a child\n // process can't export into the shell that launched it. Gated on a\n // fresh workspace; on every routine pull this would just be noise.\n const printShellHint = (): void => {\n if (folderInitialised) return;\n console.log();\n logger.success(`Workspace ready for ${chalk.bold(tenant)}.`);\n logger.dim('To target this tenant in this shell, set:');\n logger.info(\n organisation === tenant\n ? ` export FARSEER_TENANT=${tenant}`\n : ` export FARSEER_TENANT=${tenant} FARSEER_ORG=${organisation}`,\n );\n logger.dim(`Or pass it explicitly each time: farseer status ${tenant}`);\n };\n\n let preStatus: SyncStatus | null = null;\n let preStatusError: Error | null = null;\n if (folderInitialised) {\n try {\n preStatus = await syncService.getStatus({ ...filterOptions, all: options.all, deep: false });\n } catch (error) {\n preStatusError = error as Error;\n logger.dim(`Could not compute pre-pull status: ${preStatusError.message}`);\n }\n }\n\n // Preview app deletions too. Without this the destructive\n // prompt only covers files and the user discovers (post-pull)\n // that an app JSON was wiped because someone deleted the app\n // on remote. Uses listApps only \u2014 no per-app fetch \u2014 so this\n // doesn't double the network cost of the apps pull below.\n //\n // Best-effort: a failure here shouldn't block the pull. Worst\n // case the user gets the legacy behaviour (silent app\n // deletion) on this run.\n const appSyncService = new AppSyncService(tenant, client);\n let appDeletions: string[] = [];\n try {\n appDeletions = await appSyncService.getRemoteDeletions();\n } catch (error) {\n logger.dim(`Could not compute pre-pull app deletions: ${(error as Error).message}`);\n }\n\n const localChanges = preStatus\n ? preStatus.addedLocally.length +\n preStatus.modifiedLocally.length +\n preStatus.deletedLocally.length +\n preStatus.conflicts.length\n : 0;\n const remoteDeletions = (preStatus?.deletedRemotely.length ?? 0) + appDeletions.length;\n\n // Step 2: Decide whether to confirm. The matrix:\n // --force \u2192 always confirm (destructive reset).\n // local edits OR remote deletions \u2192 confirm unless -y.\n // clean tree, no deletes \u2192 just go.\n //\n // Remote deletions are gated because pull would silently\n // remove a previously-synced local file/app if someone deleted\n // it on remote \u2014 a real script could vanish without warning.\n // Local edits stay gated for the existing reason: we don't\n // want to merge into a dirty tree without an opt-in.\n if (options.force) {\n console.log();\n console.log(chalk.red.bold('--force will hard-reset local to match remote.'));\n if (preStatus) {\n summarisePreStatus(preStatus);\n } else if (preStatusError) {\n // Without a local diff we'd be confirming a destructive\n // mirror operation blind. Refuse rather than press on \u2014\n // the cost of failing here is one re-run; the cost of\n // pressing on is silent loss of in-progress files.\n console.log(\n chalk.red(\n 'Cannot show what will be lost \u2014 pre-pull status failed (see line above). Refusing to --force without visibility.',\n ),\n );\n logger.dim('Re-run after the underlying issue clears, or use a non-force pull to merge.');\n process.exit(1);\n } else {\n // Folder isn't initialised yet \u2014 first --force pull on a\n // brand-new tenant. Nothing local to lose; proceed.\n logger.dim('No local files yet \u2014 nothing to discard.');\n }\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Discard local changes and reset ${tenant} to remote?`,\n default: false,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n } else if ((localChanges > 0 || remoteDeletions > 0) && !options.yes) {\n console.log();\n if (localChanges > 0) {\n logger.warning(`Local has ${localChanges} unsynced change(s).`);\n summarisePreStatus(preStatus!);\n logger.dim('Pull will keep your edits and merge remote-side changes around them.');\n }\n if (remoteDeletions > 0) {\n logger.warning(`Pull will remove ${remoteDeletions} local item(s) that were deleted on remote:`);\n summariseRemoteDeletions(preStatus?.deletedRemotely ?? [], appDeletions);\n logger.dim('Decline to abort and keep your local copies (you can push them back to restore).');\n }\n if (localChanges > 0 && remoteDeletions === 0) {\n logger.dim('To wipe local and reset to remote: re-run with --force.');\n }\n const promptMessage =\n remoteDeletions > 0 && localChanges > 0\n ? `Continue pull (merge into dirty tree AND delete ${remoteDeletions} local item(s))?`\n : remoteDeletions > 0\n ? `Continue pull and delete ${remoteDeletions} local item(s)?`\n : `Continue pulling into a dirty working tree?`;\n // Dirty-tree-only keeps the soft default (Enter = continue\n // merge). The moment remote deletions are on the table we\n // flip to default-false: a wrong \"yes\" wipes local items\n // for good, same calculus as `pull --force` below.\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: promptMessage,\n default: remoteDeletions === 0,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull(syncOptions);\n\n // Conflicts: prompt per file (only when not --force).\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: \"Keep deleted (don't restore file)\", value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n // Only offer git-style merge for files we know\n // are text. Binary blobs would just get\n // corrupted by UTF-8 splicing. The service has\n // a defensive fallback for binary anyway, but\n // not showing the option avoids the confusing\n // \"I picked merge_markers but got keep_both\"\n // experience.\n if (isLikelyTextFile(conflict.filePath)) {\n choices.push({\n name: 'Merge with markers (git-style \u2014 edit file, then push to finish)',\n value: 'merge_markers',\n });\n }\n }\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n },\n ]);\n resolutions[conflict.filePath] = answer.resolution;\n }\n result = await syncService.pull({ ...syncOptions, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) console.log(chalk.green(` + ${file}`));\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) console.log(chalk.red(` - ${file}`));\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) console.log(chalk.yellow(` ~ ${file}`));\n if (result.conflictFilesWritten.some((f) => f.includes('(merge markers)'))) {\n console.log();\n logger.dim('Files marked with \"(merge markers)\" contain git-style <<<<<<</=======/>>>>>>>');\n logger.dim('blocks. Open them, pick which version to keep, remove the marker lines,');\n logger.dim(`then run \\`farseer push ${tenant}\\` to upload the resolved version.`);\n }\n }\n\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // --force extra: also delete any local-only files. The\n // service-level pull keeps `local_new` files unchanged\n // (it's the right default for a non-destructive pull),\n // but --force at the command layer means \"mirror remote\",\n // so remove those locally.\n let extraLocalDeletes: string[] = [];\n if (options.force) {\n // Forward `--all` so `pull --force --all` wipes every\n // local-only file in scope, not just those that match\n // the default sync scope.\n extraLocalDeletes = await wipeLocalOnly(syncService, filesDir, {\n ...filterOptions,\n all: options.all,\n });\n if (extraLocalDeletes.length > 0) {\n console.log(chalk.red('Local-only files removed (mirror remote):'));\n for (const file of extraLocalDeletes) console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Audit log\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map((filePath) => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges =\n result.downloaded.length > 0 || result.deleted.length > 0 || extraLocalDeletes.length > 0;\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) console.log(chalk.green(` + ${app}`));\n }\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) console.log(chalk.yellow(` ~ ${app}`));\n }\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) console.log(chalk.red(` - ${app}`));\n }\n\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n hasChanges =\n hasChanges ||\n appResult.created.length > 0 ||\n appResult.updated.length > 0 ||\n appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n printShellHint();\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} ${\n extraLocalDeletes.length > 0 ? `(${extraLocalDeletes.length} local-only removed) ` : ''\n }(${result.unchanged.length} unchanged)`,\n );\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n printShellHint();\n } catch (error) {\n fileLogger.error('pull', error);\n logger.error('Pull failed.');\n logger.error(await formatClientError(error));\n const logPath = fileLogger.getLogPath();\n if (logPath) {\n logger.dim(`Debug log: ${logPath}`);\n }\n process.exit(1);\n }\n });\n}\n\n/**\n * Print actual paths (not just counts) so the user can see what local\n * changes a `pull --force` is about to overwrite. Counts alone hid the\n * destructive blast radius: under `--force --all` someone could lose\n * dozens of in-progress files without knowing which ones. Cap at\n * MAX_PATHS_PER_SECTION per section to avoid scrollback floods on huge\n * trees \u2014 anything beyond that collapses into \"+ N more\".\n */\nfunction summarisePreStatus(status: SyncStatus): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[], color: (s: string) => string) => {\n if (paths.length === 0) return;\n console.log(color(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(color(` ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('+ new local file(s)', status.addedLocally, chalk.green);\n renderSection('M locally modified file(s)', status.modifiedLocally, chalk.yellow);\n renderSection('- locally deleted file(s)', status.deletedLocally, chalk.red);\n if (status.conflicts.length > 0) {\n const conflictPaths = status.conflicts.map((c) => c.filePath);\n renderSection('! conflict(s)', conflictPaths, chalk.red.bold);\n }\n console.log();\n}\n\n/**\n * Print the file + app paths that pull is about to delete because remote\n * removed them. Same cap as `summarisePreStatus` so a huge purge doesn't\n * flood the scrollback \u2014 the user still gets the count above.\n */\nfunction summariseRemoteDeletions(deletedFiles: string[], deletedApps: string[]): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[]) => {\n if (paths.length === 0) return;\n console.log(chalk.red(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(chalk.red(` - ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('file(s) deleted on remote', deletedFiles);\n renderSection('app(s) deleted on remote', deletedApps);\n console.log();\n}\n\n/**\n * Hard-reset helper for `pull --force`. Removes local files that have no\n * remote counterpart (the regular pull keeps them \u2014 see service comment).\n * Cleans up the syncState entry too so the next status doesn't show ghosts.\n */\nasync function wipeLocalOnly(\n syncService: SyncService,\n filesDir: string,\n filterOptions: { all?: boolean; includeExtensions?: string[]; includeFolders?: string[] },\n): Promise<string[]> {\n // `all` matters: under `pull --force --all` the user expects every\n // local-only file to be wiped, not just files in the default sync\n // scope. Without it, getStatus filters down to the curated developer\n // files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden\n // directories and the folder blocklist, so the wipe loop never sees\n // anything those rules exclude.\n const status = await syncService.getStatus({ ...filterOptions, deep: false });\n const removed: string[] = [];\n const failed: { file: string; reason: string }[] = [];\n const syncState = syncService.loadSyncState();\n for (const file of status.addedLocally) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n if (fs.existsSync(fullPath)) {\n // Wrap each unlink so a single permission error / file lock\n // doesn't strand the rest of the wipe. syncState is saved\n // incrementally as each unlink succeeds so a mid-run failure\n // leaves a consistent record for the next run, and the failed\n // list is surfaced at the end for manual cleanup.\n try {\n fs.unlinkSync(fullPath);\n removed.push(file);\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n } catch (err) {\n failed.push({ file, reason: err instanceof Error ? err.message : String(err) });\n }\n } else {\n // File was already gone \u2014 just drop the syncState entry.\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n }\n }\n if (failed.length > 0) {\n logger.warning(`${failed.length} local-only file(s) could not be removed:`);\n for (const f of failed) logger.dim(` ${f.file} \u2014 ${f.reason}`);\n }\n return removed;\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n arquero: '^5.4.1',\n axios: '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n dotenv: '^16.4.5',\n 'draft-js': '^0.11.7',\n exceljs: '^4.4.0',\n 'farseer-client': FARSEER_CLIENT_URL,\n 'farseer-client-axios': FARSEER_CLIENT_AXIOS_URL,\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,uBAA0B;AAC1B,yBAA6D;AAC7D,4BAA+B;AAC/B,qBAOO;AACP,4BAAkC;AAClC,4BAAiC;AACjC,wBAAmD;AACnD,uBAA6D;AAC7D,uBAAuC;AACvC,SAAoB;AACpB,WAAsB;AAmBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG,OAAO,OAAO,MAAM,MAAM,YAAY;AAInC,UAAM,SAAS,UAAM,4BAAU,MAAM,IAAI;AACzC,UAAM,EAAE,cAAc,QAAQ,OAAO,IAAI;AAEzC,UAAM,cAAc,IAAI,+BAAY,QAAQ,MAAM;AAElD,UAAM,gBAAY,6BAAa,MAAM;AACrC,8CAAsB,SAAS;AAM/B,iDAAuB,KAAK,KAAK,WAAW,YAAY,CAAC;AAEzD,UAAM,yBAAyB,WAAW,MAAM;AAEhD,UAAM,wBAAoB,uCAAoB,QAAQ,UAAU;AAChE,UAAM,iBAAiB,QAAQ;AAC/B,UAAM,gBAAgB;AAAA,MAClB,mBAAmB,kBAAkB,SAAS,IAAI,oBAAoB;AAAA,MACtE,gBAAgB,eAAe,SAAS,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AAAA,MACvB,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,YAAY;AAAA,IAChB;AAAA,EACJ;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,OAAO;AAC/E,uBAAO,IAAI,4BAA4B,MAAM,EAAE;AACnD;",
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { fileLogger } from '../utils/fileLogger';\nimport { preflight } from '../services/preflight';\nimport { SyncService, ConflictResolutions, SyncStatus } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantDir,\n getTenantFilesDir,\n ensureDirectoryExists,\n appendToAuditLog,\n AuditLogEntry,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { isLikelyTextFile } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport { FARSEER_CLIENT_DEPENDENCY } from '../utils/constants';\nimport { ensureGitignoreEntries } from '../utils/workspace';\nimport { updatePackageJson } from '../utils/packageManager';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Pull semantics:\n *\n * farseer pull\n * 1. Show local-vs-remote diff. If you have unsynced local edits OR\n * remote has deletions that would remove local files/apps, the\n * command stops here and asks for confirmation before doing\n * anything (we don't merge or delete silently).\n * 2. Apply remote-side changes (downloads, deletions, modifications).\n * Per-file conflicts are resolved interactively.\n *\n * farseer pull --force\n * Hard reset to remote. After it runs, the working tree mirrors what's\n * on remote: any file that exists locally but not on remote is deleted,\n * remote versions overwrite local edits, deletions are accepted. Always\n * asks for confirmation because the operation is destructive.\n */\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description(\n 'Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)',\n )\n .option(\n '--all',\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in via --include-ext .csv or `farseer config include --ext .csv`.',\n )\n .option(\n '--force',\n 'Hard reset local to remote within the current sync scope: overwrite local edits, delete local-only files. Files outside scope (data files like .csv on a default run without --include-ext .csv) are NOT touched. Always asks for confirmation.',\n )\n .option(\n '-y, --yes',\n 'Skip confirmation when local has uncommitted changes OR remote has deletions that would remove local files/apps (ignored under --force)',\n )\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .action(async (arg1, arg2, options) => {\n // preflight resolves the target, authenticates, and confirms the\n // org owns the tenant (the guard that used to live only in\n // `checkout`). pull is the setup path now, so scaffolding follows.\n const target = await preflight(arg1, arg2);\n const { organisation, tenant, client } = target;\n\n const syncService = new SyncService(tenant, client);\n\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Ensure .gitignore covers `.farseer-sync.json` on the first pull\n // into a fresh workspace. Without it, a workspace initialized by\n // `farseer pull` would commit the per-machine baseline and\n // reproduce the cross-machine drift bug the gitignore prevents.\n ensureGitignoreEntries(path.join(tenantDir, '.gitignore'));\n\n await createDefaultPackageJson(tenantDir, tenant);\n const packageChanges = updatePackageJson(tenantDir);\n if (packageChanges.length > 0) {\n logger.info(`Updated package.json: ${packageChanges.join(', ')}`);\n logger.dim(`Run \"farseer install ${tenant}\" to update node_modules.`);\n }\n\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const filterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\n const syncOptions = {\n all: options.all,\n force: options.force,\n ...filterOptions,\n };\n\n // Step 1: Inspect current state. We do this BEFORE mutating\n // anything so the user can decide whether to bail.\n const filesDir = getTenantFilesDir(tenant);\n const folderInitialised = fs.existsSync(filesDir);\n\n // With `checkout` gone, a first pull IS the setup \u2014 so it has to\n // close by naming the one step the CLI can't do itself: a child\n // process can't export into the shell that launched it. Gated on a\n // fresh workspace; on every routine pull this would just be noise.\n const printShellHint = (): void => {\n if (folderInitialised) return;\n console.log();\n logger.success(`Workspace ready for ${chalk.bold(tenant)}.`);\n logger.dim('To target this tenant in this shell, set:');\n logger.info(\n organisation === tenant\n ? ` export FARSEER_TENANT=${tenant}`\n : ` export FARSEER_TENANT=${tenant} FARSEER_ORG=${organisation}`,\n );\n logger.dim(`Or pass it explicitly each time: farseer status ${tenant}`);\n };\n\n let preStatus: SyncStatus | null = null;\n let preStatusError: Error | null = null;\n if (folderInitialised) {\n try {\n preStatus = await syncService.getStatus({ ...filterOptions, all: options.all, deep: false });\n } catch (error) {\n preStatusError = error as Error;\n logger.dim(`Could not compute pre-pull status: ${preStatusError.message}`);\n }\n }\n\n // Preview app deletions too. Without this the destructive\n // prompt only covers files and the user discovers (post-pull)\n // that an app JSON was wiped because someone deleted the app\n // on remote. Uses listApps only \u2014 no per-app fetch \u2014 so this\n // doesn't double the network cost of the apps pull below.\n //\n // Best-effort: a failure here shouldn't block the pull. Worst\n // case the user gets the legacy behaviour (silent app\n // deletion) on this run.\n const appSyncService = new AppSyncService(tenant, client);\n let appDeletions: string[] = [];\n try {\n appDeletions = await appSyncService.getRemoteDeletions();\n } catch (error) {\n logger.dim(`Could not compute pre-pull app deletions: ${(error as Error).message}`);\n }\n\n const localChanges = preStatus\n ? preStatus.addedLocally.length +\n preStatus.modifiedLocally.length +\n preStatus.deletedLocally.length +\n preStatus.conflicts.length\n : 0;\n const remoteDeletions = (preStatus?.deletedRemotely.length ?? 0) + appDeletions.length;\n\n // Step 2: Decide whether to confirm. The matrix:\n // --force \u2192 always confirm (destructive reset).\n // local edits OR remote deletions \u2192 confirm unless -y.\n // clean tree, no deletes \u2192 just go.\n //\n // Remote deletions are gated because pull would silently\n // remove a previously-synced local file/app if someone deleted\n // it on remote \u2014 a real script could vanish without warning.\n // Local edits stay gated for the existing reason: we don't\n // want to merge into a dirty tree without an opt-in.\n if (options.force) {\n console.log();\n console.log(chalk.red.bold('--force will hard-reset local to match remote.'));\n if (preStatus) {\n summarisePreStatus(preStatus);\n } else if (preStatusError) {\n // Without a local diff we'd be confirming a destructive\n // mirror operation blind. Refuse rather than press on \u2014\n // the cost of failing here is one re-run; the cost of\n // pressing on is silent loss of in-progress files.\n console.log(\n chalk.red(\n 'Cannot show what will be lost \u2014 pre-pull status failed (see line above). Refusing to --force without visibility.',\n ),\n );\n logger.dim('Re-run after the underlying issue clears, or use a non-force pull to merge.');\n process.exit(1);\n } else {\n // Folder isn't initialised yet \u2014 first --force pull on a\n // brand-new tenant. Nothing local to lose; proceed.\n logger.dim('No local files yet \u2014 nothing to discard.');\n }\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Discard local changes and reset ${tenant} to remote?`,\n default: false,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n } else if ((localChanges > 0 || remoteDeletions > 0) && !options.yes) {\n console.log();\n if (localChanges > 0) {\n logger.warning(`Local has ${localChanges} unsynced change(s).`);\n summarisePreStatus(preStatus!);\n logger.dim('Pull will keep your edits and merge remote-side changes around them.');\n }\n if (remoteDeletions > 0) {\n logger.warning(`Pull will remove ${remoteDeletions} local item(s) that were deleted on remote:`);\n summariseRemoteDeletions(preStatus?.deletedRemotely ?? [], appDeletions);\n logger.dim('Decline to abort and keep your local copies (you can push them back to restore).');\n }\n if (localChanges > 0 && remoteDeletions === 0) {\n logger.dim('To wipe local and reset to remote: re-run with --force.');\n }\n const promptMessage =\n remoteDeletions > 0 && localChanges > 0\n ? `Continue pull (merge into dirty tree AND delete ${remoteDeletions} local item(s))?`\n : remoteDeletions > 0\n ? `Continue pull and delete ${remoteDeletions} local item(s)?`\n : `Continue pulling into a dirty working tree?`;\n // Dirty-tree-only keeps the soft default (Enter = continue\n // merge). The moment remote deletions are on the table we\n // flip to default-false: a wrong \"yes\" wipes local items\n // for good, same calculus as `pull --force` below.\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: promptMessage,\n default: remoteDeletions === 0,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull(syncOptions);\n\n // Conflicts: prompt per file (only when not --force).\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: \"Keep deleted (don't restore file)\", value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n // Only offer git-style merge for files we know\n // are text. Binary blobs would just get\n // corrupted by UTF-8 splicing. The service has\n // a defensive fallback for binary anyway, but\n // not showing the option avoids the confusing\n // \"I picked merge_markers but got keep_both\"\n // experience.\n if (isLikelyTextFile(conflict.filePath)) {\n choices.push({\n name: 'Merge with markers (git-style \u2014 edit file, then push to finish)',\n value: 'merge_markers',\n });\n }\n }\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n },\n ]);\n resolutions[conflict.filePath] = answer.resolution;\n }\n result = await syncService.pull({ ...syncOptions, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) console.log(chalk.green(` + ${file}`));\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) console.log(chalk.red(` - ${file}`));\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) console.log(chalk.yellow(` ~ ${file}`));\n if (result.conflictFilesWritten.some((f) => f.includes('(merge markers)'))) {\n console.log();\n logger.dim('Files marked with \"(merge markers)\" contain git-style <<<<<<</=======/>>>>>>>');\n logger.dim('blocks. Open them, pick which version to keep, remove the marker lines,');\n logger.dim(`then run \\`farseer push ${tenant}\\` to upload the resolved version.`);\n }\n }\n\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // --force extra: also delete any local-only files. The\n // service-level pull keeps `local_new` files unchanged\n // (it's the right default for a non-destructive pull),\n // but --force at the command layer means \"mirror remote\",\n // so remove those locally.\n let extraLocalDeletes: string[] = [];\n if (options.force) {\n // Forward `--all` so `pull --force --all` wipes every\n // local-only file in scope, not just those that match\n // the default sync scope.\n extraLocalDeletes = await wipeLocalOnly(syncService, filesDir, {\n ...filterOptions,\n all: options.all,\n });\n if (extraLocalDeletes.length > 0) {\n console.log(chalk.red('Local-only files removed (mirror remote):'));\n for (const file of extraLocalDeletes) console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Audit log\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map((filePath) => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges =\n result.downloaded.length > 0 || result.deleted.length > 0 || extraLocalDeletes.length > 0;\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) console.log(chalk.green(` + ${app}`));\n }\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) console.log(chalk.yellow(` ~ ${app}`));\n }\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) console.log(chalk.red(` - ${app}`));\n }\n\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n hasChanges =\n hasChanges ||\n appResult.created.length > 0 ||\n appResult.updated.length > 0 ||\n appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n printShellHint();\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} ${\n extraLocalDeletes.length > 0 ? `(${extraLocalDeletes.length} local-only removed) ` : ''\n }(${result.unchanged.length} unchanged)`,\n );\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n printShellHint();\n } catch (error) {\n fileLogger.error('pull', error);\n logger.error('Pull failed.');\n logger.error(await formatClientError(error));\n const logPath = fileLogger.getLogPath();\n if (logPath) {\n logger.dim(`Debug log: ${logPath}`);\n }\n process.exit(1);\n }\n });\n}\n\n/**\n * Print actual paths (not just counts) so the user can see what local\n * changes a `pull --force` is about to overwrite. Counts alone hid the\n * destructive blast radius: under `--force --all` someone could lose\n * dozens of in-progress files without knowing which ones. Cap at\n * MAX_PATHS_PER_SECTION per section to avoid scrollback floods on huge\n * trees \u2014 anything beyond that collapses into \"+ N more\".\n */\nfunction summarisePreStatus(status: SyncStatus): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[], color: (s: string) => string) => {\n if (paths.length === 0) return;\n console.log(color(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(color(` ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('+ new local file(s)', status.addedLocally, chalk.green);\n renderSection('M locally modified file(s)', status.modifiedLocally, chalk.yellow);\n renderSection('- locally deleted file(s)', status.deletedLocally, chalk.red);\n if (status.conflicts.length > 0) {\n const conflictPaths = status.conflicts.map((c) => c.filePath);\n renderSection('! conflict(s)', conflictPaths, chalk.red.bold);\n }\n console.log();\n}\n\n/**\n * Print the file + app paths that pull is about to delete because remote\n * removed them. Same cap as `summarisePreStatus` so a huge purge doesn't\n * flood the scrollback \u2014 the user still gets the count above.\n */\nfunction summariseRemoteDeletions(deletedFiles: string[], deletedApps: string[]): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[]) => {\n if (paths.length === 0) return;\n console.log(chalk.red(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(chalk.red(` - ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('file(s) deleted on remote', deletedFiles);\n renderSection('app(s) deleted on remote', deletedApps);\n console.log();\n}\n\n/**\n * Hard-reset helper for `pull --force`. Removes local files that have no\n * remote counterpart (the regular pull keeps them \u2014 see service comment).\n * Cleans up the syncState entry too so the next status doesn't show ghosts.\n */\nasync function wipeLocalOnly(\n syncService: SyncService,\n filesDir: string,\n filterOptions: { all?: boolean; includeExtensions?: string[]; includeFolders?: string[] },\n): Promise<string[]> {\n // `all` matters: under `pull --force --all` the user expects every\n // local-only file to be wiped, not just files in the default sync\n // scope. Without it, getStatus filters down to the curated developer\n // files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden\n // directories and the folder blocklist, so the wipe loop never sees\n // anything those rules exclude.\n const status = await syncService.getStatus({ ...filterOptions, deep: false });\n const removed: string[] = [];\n const failed: { file: string; reason: string }[] = [];\n const syncState = syncService.loadSyncState();\n for (const file of status.addedLocally) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n if (fs.existsSync(fullPath)) {\n // Wrap each unlink so a single permission error / file lock\n // doesn't strand the rest of the wipe. syncState is saved\n // incrementally as each unlink succeeds so a mid-run failure\n // leaves a consistent record for the next run, and the failed\n // list is surfaced at the end for manual cleanup.\n try {\n fs.unlinkSync(fullPath);\n removed.push(file);\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n } catch (err) {\n failed.push({ file, reason: err instanceof Error ? err.message : String(err) });\n }\n } else {\n // File was already gone \u2014 just drop the syncState entry.\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n }\n }\n if (failed.length > 0) {\n logger.warning(`${failed.length} local-only file(s) could not be removed:`);\n for (const f of failed) logger.dim(` ${f.file} \u2014 ${f.reason}`);\n }\n return removed;\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n arquero: '^5.4.1',\n axios: '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n dotenv: '^16.4.5',\n 'draft-js': '^0.11.7',\n exceljs: '^4.4.0',\n 'farseer-client': FARSEER_CLIENT_DEPENDENCY,\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,uBAA0B;AAC1B,yBAA6D;AAC7D,4BAA+B;AAC/B,qBAOO;AACP,4BAAkC;AAClC,4BAAiC;AACjC,wBAAmD;AACnD,uBAA0C;AAC1C,uBAAuC;AACvC,4BAAkC;AAClC,SAAoB;AACpB,WAAsB;AAmBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG,OAAO,OAAO,MAAM,MAAM,YAAY;AAInC,UAAM,SAAS,UAAM,4BAAU,MAAM,IAAI;AACzC,UAAM,EAAE,cAAc,QAAQ,OAAO,IAAI;AAEzC,UAAM,cAAc,IAAI,+BAAY,QAAQ,MAAM;AAElD,UAAM,gBAAY,6BAAa,MAAM;AACrC,8CAAsB,SAAS;AAM/B,iDAAuB,KAAK,KAAK,WAAW,YAAY,CAAC;AAEzD,UAAM,yBAAyB,WAAW,MAAM;AAChD,UAAM,qBAAiB,yCAAkB,SAAS;AAClD,QAAI,eAAe,SAAS,GAAG;AAC3B,2BAAO,KAAK,yBAAyB,eAAe,KAAK,IAAI,CAA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A,MACnB,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,kBAAkB;AAAA,MAClB,eAAe;AAAA,MACf,2BAA2B;AAAA,MAC3B,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,YAAY;AAAA,IAChB;AAAA,EACJ;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,OAAO;AAC/E,uBAAO,IAAI,4BAA4B,MAAM,EAAE;AACnD;",
|
|
6
6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
|
@@ -361,7 +361,7 @@ async function exportVariableAsCsv(client, variableName, limit, filters) {
|
|
|
361
361
|
}
|
|
362
362
|
const blob = await client.export.exportFormula({
|
|
363
363
|
formula,
|
|
364
|
-
format: farseer.
|
|
364
|
+
format: farseer.ExportFormat.Csv,
|
|
365
365
|
limit
|
|
366
366
|
});
|
|
367
367
|
return await blob.text();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/dataTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Data Operation Tools\n *\n * MCP tools for data export, import jobs, and file management on Farseer instances.\n * These use the native farseer-client for full API access.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { registerTool } from '../utils/registerTool';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as farseer from 'farseer-client';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst exportVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to export'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe(\n 'Dimension filters as [tableName, memberName] pairs (e.g., [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]). Filters the export to specific dimension members.',\n ),\n format: z.enum(['csv', 'json']).optional().describe('Output format (default: csv)'),\n limit: z.number().optional().describe('Maximum number of rows to return'),\n};\n\nconst loadVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to load'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names to include as columns in the export'),\n};\n\nconst createImportJobSchema = {\n title: z.string().describe('Import job title (shown in import history)'),\n columns: z\n .array(\n z.object({\n type: z.enum(['DIMENSION_TABLE', 'VARIABLE', 'DATE', 'DESCRIPTION']).describe('Column type'),\n dimensionTableName: z.string().optional().describe('For DIMENSION_TABLE: name of the dimension table'),\n variableName: z.string().optional().describe('For VARIABLE: name of the variable'),\n columnName: z.string().optional().describe('Column header name'),\n dateFormat: z.string().optional().describe('For DATE: date format string'),\n dimensionsNames: z\n .array(\n z.object({\n tableName: z.string(),\n memberName: z.string(),\n }),\n )\n .optional()\n .describe('For VARIABLE: fixed dimension members (filters) for this variable column'),\n }),\n )\n .describe('Column definitions matching the data structure'),\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.null()])))\n .describe('Data rows - each row is an array of values matching column order'),\n labels: z\n .array(z.string())\n .optional()\n .describe('Labels for grouping import jobs (used by undoPrevious to revert jobs with same labels)'),\n undoPrevious: z\n .boolean()\n .optional()\n .describe('Revert previous import jobs with the same labels before committing (default: false)'),\n importDimensions: z\n .boolean()\n .optional()\n .describe('Auto-create any missing dimension members before committing (default: false)'),\n overwriteCells: z\n .boolean()\n .optional()\n .describe('Overwrite existing cell values (default: false - adds to existing values)'),\n};\n\nconst createFileSchema = {\n fileName: z.string().describe('Name of the file to create or update'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path as array (e.g., [\"Files\", \"Reports\"]). Default: [\"Files\"]'),\n content: z.string().describe('File content as text string'),\n};\n\nexport function registerDataTools(server: McpServer): void {\n // farseer_export_variable_data - Export variable data\n registerTool(\n server,\n 'farseer_export_variable_data',\n `Export data from a Farseer variable as CSV.\n\nBuilds an export configuration from the variable's dimensions and uses\nthe evaluator export endpoint. Works on all server versions.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp file and returns the path \u2014\nuse the Read tool to inspect the file contents.\n\nUse the 'limit' parameter to restrict row count for large variables.`,\n exportVariableDataSchema,\n async (params: {\n variableName: string;\n filters?: Array<Array<string>>;\n format?: 'csv' | 'json';\n limit?: number;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName, params.limit, params.filters);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to file. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Export variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_load_variable_data - Load variable data with specific dimensions\n registerTool(\n server,\n 'farseer_load_variable_data',\n `Load data from a Farseer variable into a structured CSV format.\n\nExports all data cells for the variable. You can optionally filter to\nspecific dimensions only.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp CSV file and returns the path.\n\nExample usage:\n- Load \"Revenue\" data (all dimensions)\n- Load \"Revenue\" with dimensions [\"Product\", \"Years\", \"Months\"]`,\n loadVariableDataSchema,\n async (params: { variableName: string; dimensions?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}_data.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to CSV. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Load variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_import_job - Create and execute import job\n registerTool(\n server,\n 'farseer_create_import_job',\n `Create and execute a complete data import job on a Farseer instance.\n\nFor repeatable data extraction, transformation and loading, start with farseer_pipeline operation=guide topic=method. Use this tool for a direct import the user requested. If pipeline setup is missing, explain what needs preparing before choosing a different workflow.\n\nThis tool handles the full import workflow in a single call:\n1. Builds import metadata from column definitions\n2. Creates the import job\n3. Adds all data rows\n4. Optionally creates missing dimension members (importDimensions)\n5. Optionally reverts previous imports with same labels (undoPrevious)\n6. Commits the import\n\nColumn types:\n- DIMENSION_TABLE: Maps to a dimension table (e.g., Product, Years, Months)\n- VARIABLE: Maps to a variable that will receive data values\n - Can include dimensionsNames to fix specific dimension members for this column\n- DATE: Date column with format string\n- DESCRIPTION: Cell description/comment\n\nThe 'labels' parameter is important for the undoPrevious feature:\nwhen undoPrevious is true, all previously committed imports with the\nsame labels will be reverted before this import is committed.\nThis is useful for idempotent re-imports.\n\nThe 'overwriteCells' parameter controls whether existing values are\noverwritten (true) or accumulated (false, default).\n\nExample columns for importing revenue data:\n[\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Product\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Years\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Months\" },\n { \"type\": \"VARIABLE\", \"variableName\": \"Revenue\",\n \"dimensionsNames\": [\n { \"tableName\": \"Versions\", \"memberName\": \"Actual\" }\n ]\n }\n]`,\n createImportJobSchema,\n async (params: {\n title: string;\n columns: Array<{\n type: 'DIMENSION_TABLE' | 'VARIABLE' | 'DATE' | 'DESCRIPTION';\n dimensionTableName?: string;\n variableName?: string;\n columnName?: string;\n dateFormat?: string;\n dimensionsNames?: Array<{ tableName: string; memberName: string }>;\n }>;\n rows: Array<Array<string | number | null>>;\n labels?: string[];\n undoPrevious?: boolean;\n importDimensions?: boolean;\n overwriteCells?: boolean;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const {\n title,\n columns,\n rows,\n labels,\n undoPrevious = false,\n importDimensions = false,\n overwriteCells = false,\n } = params;\n\n // Build metadata columns\n const metadataColumns = columns.map((col) => {\n switch (col.type) {\n case 'DIMENSION_TABLE':\n return {\n type: 'DIMENSION_TABLE' as const,\n dimensionTableName: col.dimensionTableName!,\n columnName: col.columnName,\n };\n case 'VARIABLE':\n return {\n type: 'VARIABLE' as const,\n variableName: col.variableName!,\n columnName: col.columnName || col.variableName!,\n dimensionsNames: col.dimensionsNames,\n };\n case 'DATE':\n return {\n type: 'DATE' as const,\n dateFormat: col.dateFormat!,\n columnName: col.columnName,\n };\n case 'DESCRIPTION':\n return {\n type: 'DESCRIPTION' as const,\n columnName: col.columnName,\n };\n default:\n return {\n type: 'NONE' as const,\n columnName: col.columnName,\n };\n }\n });\n\n // Build metadata\n const metadata = await nativeClient.buildImportJobMetadata(metadataColumns as any);\n\n if (overwriteCells) {\n (metadata as any).overwriteCells = true;\n }\n\n // Create import job\n const importActions = await nativeClient.createImportJob({\n title,\n metadata,\n labels,\n });\n\n // Add rows\n await importActions.addRows(rows as any);\n await importActions.flushRows();\n\n // Import dimensions if needed\n if (importDimensions) {\n await importActions.importDimensions();\n }\n\n // Undo previous if needed\n if (undoPrevious) {\n await importActions.undoPrevious();\n }\n\n // Commit\n const report = await importActions.commit();\n\n return successResponse({\n tenant,\n title,\n rowCount: rows.length,\n labels: labels || [],\n undoPrevious,\n importDimensions,\n overwriteCells,\n commitReport: report,\n });\n } catch (error) {\n return errorResponse(`Import job failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_file - Create or update file on instance\n registerTool(\n server,\n 'farseer_create_file',\n `Create or update a file on a Farseer instance.\n\nThis creates a file in the specified folder on the Farseer file system.\nIf a file with the same name already exists in that folder, it will be updated.\n\nThe folderPath is an array of folder names, starting from the root.\nDefault is [\"Files\"] which is the standard files folder.\n\nCommon use cases:\n- Creating CSV report files\n- Uploading configuration files\n- Saving processed data outputs`,\n createFileSchema,\n async (params: { fileName: string; folderPath?: string[]; content: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n const folderPath = params.folderPath || ['Files'];\n // Not nativeClient.getItemByPath: for a single-segment path that\n // name-searches the whole tenant and refuses on more than one\n // loose match, so a second folder called \"Files\" breaks it.\n const folder = await client.getFolderByPath(folderPath);\n if (!folder) {\n return errorResponse(`Folder \"${folderPath.join('/')}\" not found`, 'NOT_FOUND');\n }\n const buffer = Buffer.from(params.content, 'utf-8');\n\n // The SDK creates a new file through a signed Cloud Storage upload, which an agent\n // sandbox cannot reach. Its update path and the CLI's create both use the API, the\n // same multipart create `push` uses, so every login takes this one path.\n const items = await nativeClient.getFolderItems(folder.id);\n const existing = items.find((item) => item.name === params.fileName);\n if (existing) await nativeClient.createOrUpdateFarseerFile(existing, buffer);\n else await client.createFile(buffer, params.fileName, folderPath);\n\n return successResponse({\n tenant,\n fileName: params.fileName,\n folderPath,\n size: buffer.length,\n message: `File \"${params.fileName}\" created/updated in ${folderPath.join('/')}`,\n });\n } catch (error) {\n return errorResponse(`Create file failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n\n/**\n * Export variable data as CSV using evaluatorExport (works on all server versions).\n * Falls back to exportFormula if evaluatorExport fails.\n */\n/**\n * Export variable data as CSV using exportFormula.\n * Wraps the variable name in quotes as required by the API.\n * Supports dimension filters: [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]\n * becomes sum(\"VarName\", \"Months\">\"M1\", \"Brand\">\"0000032\")\n */\nasync function exportVariableAsCsv(\n client: farseer.FarseerClient,\n variableName: string,\n limit?: number,\n filters?: Array<Array<string>>,\n): Promise<string> {\n let formula: string;\n if (filters && filters.length > 0) {\n const filterParts = filters.map(([table, member]) => `\"${table}\">\"${member}\"`).join(', ');\n formula = `sum(\"${variableName}\", ${filterParts})`;\n } else {\n formula = `\"${variableName}\"`;\n }\n\n const blob = await client.export.exportFormula({\n formula,\n format: farseer.ExportRequestFormatEnum.Csv,\n limit,\n });\n return await blob.text();\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,0BAA6B;AAC7B,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,cAAyB;AACzB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAGlC,MAAM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AAI,KAAK,MAAM,MAAM,GAAG,EAAE,KAAK,IAAI;AACxF,cAAU,QAAQ,YAAY,MAAM,WAAW;AAAA,EACnD,OAAO;AACH,cAAU,IAAI,YAAY;AAAA,EAC9B;AAEA,QAAM,OAAO,MAAM,OAAO,OAAO,cAAc;AAAA,IAC3C;AAAA,IACA,QAAQ,QAAQ,
|
|
4
|
+
"sourcesContent": ["/**\n * Data Operation Tools\n *\n * MCP tools for data export, import jobs, and file management on Farseer instances.\n * These use the native farseer-client for full API access.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { registerTool } from '../utils/registerTool';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as farseer from 'farseer-client';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst exportVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to export'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe(\n 'Dimension filters as [tableName, memberName] pairs (e.g., [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]). Filters the export to specific dimension members.',\n ),\n format: z.enum(['csv', 'json']).optional().describe('Output format (default: csv)'),\n limit: z.number().optional().describe('Maximum number of rows to return'),\n};\n\nconst loadVariableDataSchema = {\n variableName: z.string().describe('Name of the variable to load'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names to include as columns in the export'),\n};\n\nconst createImportJobSchema = {\n title: z.string().describe('Import job title (shown in import history)'),\n columns: z\n .array(\n z.object({\n type: z.enum(['DIMENSION_TABLE', 'VARIABLE', 'DATE', 'DESCRIPTION']).describe('Column type'),\n dimensionTableName: z.string().optional().describe('For DIMENSION_TABLE: name of the dimension table'),\n variableName: z.string().optional().describe('For VARIABLE: name of the variable'),\n columnName: z.string().optional().describe('Column header name'),\n dateFormat: z.string().optional().describe('For DATE: date format string'),\n dimensionsNames: z\n .array(\n z.object({\n tableName: z.string(),\n memberName: z.string(),\n }),\n )\n .optional()\n .describe('For VARIABLE: fixed dimension members (filters) for this variable column'),\n }),\n )\n .describe('Column definitions matching the data structure'),\n rows: z\n .array(z.array(z.union([z.string(), z.number(), z.null()])))\n .describe('Data rows - each row is an array of values matching column order'),\n labels: z\n .array(z.string())\n .optional()\n .describe('Labels for grouping import jobs (used by undoPrevious to revert jobs with same labels)'),\n undoPrevious: z\n .boolean()\n .optional()\n .describe('Revert previous import jobs with the same labels before committing (default: false)'),\n importDimensions: z\n .boolean()\n .optional()\n .describe('Auto-create any missing dimension members before committing (default: false)'),\n overwriteCells: z\n .boolean()\n .optional()\n .describe('Overwrite existing cell values (default: false - adds to existing values)'),\n};\n\nconst createFileSchema = {\n fileName: z.string().describe('Name of the file to create or update'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path as array (e.g., [\"Files\", \"Reports\"]). Default: [\"Files\"]'),\n content: z.string().describe('File content as text string'),\n};\n\nexport function registerDataTools(server: McpServer): void {\n // farseer_export_variable_data - Export variable data\n registerTool(\n server,\n 'farseer_export_variable_data',\n `Export data from a Farseer variable as CSV.\n\nBuilds an export configuration from the variable's dimensions and uses\nthe evaluator export endpoint. Works on all server versions.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp file and returns the path \u2014\nuse the Read tool to inspect the file contents.\n\nUse the 'limit' parameter to restrict row count for large variables.`,\n exportVariableDataSchema,\n async (params: {\n variableName: string;\n filters?: Array<Array<string>>;\n format?: 'csv' | 'json';\n limit?: number;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName, params.limit, params.filters);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to file. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n format: 'csv',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Export variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_load_variable_data - Load variable data with specific dimensions\n registerTool(\n server,\n 'farseer_load_variable_data',\n `Load data from a Farseer variable into a structured CSV format.\n\nExports all data cells for the variable. You can optionally filter to\nspecific dimensions only.\n\nFor small results (under 500 rows), returns data inline.\nFor large results (500+ rows), automatically exports to a temp CSV file and returns the path.\n\nExample usage:\n- Load \"Revenue\" data (all dimensions)\n- Load \"Revenue\" with dimensions [\"Product\", \"Years\", \"Months\"]`,\n loadVariableDataSchema,\n async (params: { variableName: string; dimensions?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n const text = await exportVariableAsCsv(nativeClient, params.variableName);\n\n const lines = text.split('\\n').filter((l) => l.trim());\n const rowCount = Math.max(0, lines.length - 1);\n\n const CSV_THRESHOLD = 500;\n\n // Large result \u2014 export to file\n if (rowCount >= CSV_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const safeName = params.variableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const filePath = path.join(tmpDir, `farseer_${tenant}_${safeName}_data.csv`);\n fs.writeFileSync(filePath, text, 'utf-8');\n\n const previewLines = lines.slice(0, 6).join('\\n');\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n exportedToFile: filePath,\n message: `Variable has ${rowCount} rows \u2014 exported to CSV. Use Read tool to inspect.`,\n preview: previewLines,\n });\n }\n\n return successResponse({\n tenant,\n variable: params.variableName,\n dimensions: params.dimensions || 'all',\n rowCount,\n data: text,\n });\n } catch (error) {\n return errorResponse(`Load variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_import_job - Create and execute import job\n registerTool(\n server,\n 'farseer_create_import_job',\n `Create and execute a complete data import job on a Farseer instance.\n\nFor repeatable data extraction, transformation and loading, start with farseer_pipeline operation=guide topic=method. Use this tool for a direct import the user requested. If pipeline setup is missing, explain what needs preparing before choosing a different workflow.\n\nThis tool handles the full import workflow in a single call:\n1. Builds import metadata from column definitions\n2. Creates the import job\n3. Adds all data rows\n4. Optionally creates missing dimension members (importDimensions)\n5. Optionally reverts previous imports with same labels (undoPrevious)\n6. Commits the import\n\nColumn types:\n- DIMENSION_TABLE: Maps to a dimension table (e.g., Product, Years, Months)\n- VARIABLE: Maps to a variable that will receive data values\n - Can include dimensionsNames to fix specific dimension members for this column\n- DATE: Date column with format string\n- DESCRIPTION: Cell description/comment\n\nThe 'labels' parameter is important for the undoPrevious feature:\nwhen undoPrevious is true, all previously committed imports with the\nsame labels will be reverted before this import is committed.\nThis is useful for idempotent re-imports.\n\nThe 'overwriteCells' parameter controls whether existing values are\noverwritten (true) or accumulated (false, default).\n\nExample columns for importing revenue data:\n[\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Product\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Years\" },\n { \"type\": \"DIMENSION_TABLE\", \"dimensionTableName\": \"Months\" },\n { \"type\": \"VARIABLE\", \"variableName\": \"Revenue\",\n \"dimensionsNames\": [\n { \"tableName\": \"Versions\", \"memberName\": \"Actual\" }\n ]\n }\n]`,\n createImportJobSchema,\n async (params: {\n title: string;\n columns: Array<{\n type: 'DIMENSION_TABLE' | 'VARIABLE' | 'DATE' | 'DESCRIPTION';\n dimensionTableName?: string;\n variableName?: string;\n columnName?: string;\n dateFormat?: string;\n dimensionsNames?: Array<{ tableName: string; memberName: string }>;\n }>;\n rows: Array<Array<string | number | null>>;\n labels?: string[];\n undoPrevious?: boolean;\n importDimensions?: boolean;\n overwriteCells?: boolean;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const {\n title,\n columns,\n rows,\n labels,\n undoPrevious = false,\n importDimensions = false,\n overwriteCells = false,\n } = params;\n\n // Build metadata columns\n const metadataColumns = columns.map((col) => {\n switch (col.type) {\n case 'DIMENSION_TABLE':\n return {\n type: 'DIMENSION_TABLE' as const,\n dimensionTableName: col.dimensionTableName!,\n columnName: col.columnName,\n };\n case 'VARIABLE':\n return {\n type: 'VARIABLE' as const,\n variableName: col.variableName!,\n columnName: col.columnName || col.variableName!,\n dimensionsNames: col.dimensionsNames,\n };\n case 'DATE':\n return {\n type: 'DATE' as const,\n dateFormat: col.dateFormat!,\n columnName: col.columnName,\n };\n case 'DESCRIPTION':\n return {\n type: 'DESCRIPTION' as const,\n columnName: col.columnName,\n };\n default:\n return {\n type: 'NONE' as const,\n columnName: col.columnName,\n };\n }\n });\n\n // Build metadata\n const metadata = await nativeClient.buildImportJobMetadata(metadataColumns as any);\n\n if (overwriteCells) {\n (metadata as any).overwriteCells = true;\n }\n\n // Create import job\n const importActions = await nativeClient.createImportJob({\n title,\n metadata,\n labels,\n });\n\n // Add rows\n await importActions.addRows(rows as any);\n await importActions.flushRows();\n\n // Import dimensions if needed\n if (importDimensions) {\n await importActions.importDimensions();\n }\n\n // Undo previous if needed\n if (undoPrevious) {\n await importActions.undoPrevious();\n }\n\n // Commit\n const report = await importActions.commit();\n\n return successResponse({\n tenant,\n title,\n rowCount: rows.length,\n labels: labels || [],\n undoPrevious,\n importDimensions,\n overwriteCells,\n commitReport: report,\n });\n } catch (error) {\n return errorResponse(`Import job failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_file - Create or update file on instance\n registerTool(\n server,\n 'farseer_create_file',\n `Create or update a file on a Farseer instance.\n\nThis creates a file in the specified folder on the Farseer file system.\nIf a file with the same name already exists in that folder, it will be updated.\n\nThe folderPath is an array of folder names, starting from the root.\nDefault is [\"Files\"] which is the standard files folder.\n\nCommon use cases:\n- Creating CSV report files\n- Uploading configuration files\n- Saving processed data outputs`,\n createFileSchema,\n async (params: { fileName: string; folderPath?: string[]; content: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n const folderPath = params.folderPath || ['Files'];\n // Not nativeClient.getItemByPath: for a single-segment path that\n // name-searches the whole tenant and refuses on more than one\n // loose match, so a second folder called \"Files\" breaks it.\n const folder = await client.getFolderByPath(folderPath);\n if (!folder) {\n return errorResponse(`Folder \"${folderPath.join('/')}\" not found`, 'NOT_FOUND');\n }\n const buffer = Buffer.from(params.content, 'utf-8');\n\n // The SDK creates a new file through a signed Cloud Storage upload, which an agent\n // sandbox cannot reach. Its update path and the CLI's create both use the API, the\n // same multipart create `push` uses, so every login takes this one path.\n const items = await nativeClient.getFolderItems(folder.id);\n const existing = items.find((item) => item.name === params.fileName);\n if (existing) await nativeClient.createOrUpdateFarseerFile(existing, buffer);\n else await client.createFile(buffer, params.fileName, folderPath);\n\n return successResponse({\n tenant,\n fileName: params.fileName,\n folderPath,\n size: buffer.length,\n message: `File \"${params.fileName}\" created/updated in ${folderPath.join('/')}`,\n });\n } catch (error) {\n return errorResponse(`Create file failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n\n/**\n * Export variable data as CSV using evaluatorExport (works on all server versions).\n * Falls back to exportFormula if evaluatorExport fails.\n */\n/**\n * Export variable data as CSV using exportFormula.\n * Wraps the variable name in quotes as required by the API.\n * Supports dimension filters: [[\"Months\",\"M1\"],[\"Brand\",\"0000032\"]]\n * becomes sum(\"VarName\", \"Months\">\"M1\", \"Brand\">\"0000032\")\n */\nasync function exportVariableAsCsv(\n client: farseer.FarseerClient,\n variableName: string,\n limit?: number,\n filters?: Array<Array<string>>,\n): Promise<string> {\n let formula: string;\n if (filters && filters.length > 0) {\n const filterParts = filters.map(([table, member]) => `\"${table}\">\"${member}\"`).join(', ');\n formula = `sum(\"${variableName}\", ${filterParts})`;\n } else {\n formula = `\"${variableName}\"`;\n }\n\n const blob = await client.export.exportFormula({\n formula,\n format: farseer.ExportFormat.Csv,\n limit,\n });\n return await blob.text();\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,0BAA6B;AAC7B,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,cAAyB;AACzB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAGlC,MAAM,2BAA2B;AAAA,EAC7B,cAAc,aAAE,OAAO,EAAE,SAAS,gCAAgC;AAAA,EAClE,SAAS,aACJ,MAAM,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,EACnC,SAAS,EACT;AAAA,IACG;AAAA,EACJ;AAAA,EACJ,QAAQ,aAAE,KAAK,CAAC,OAAO,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,8BAA8B;AAAA,EAClF,OAAO,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,kCAAkC;AAC5E;AAEA,MAAM,yBAAyB;AAAA,EAC3B,cAAc,aAAE,OAAO,EAAE,SAAS,8BAA8B;AAAA,EAChE,YAAY,aAAE,MAAM,aAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS,2DAA2D;AACnH;AAEA,MAAM,wBAAwB;AAAA,EAC1B,OAAO,aAAE,OAAO,EAAE,SAAS,4CAA4C;AAAA,EACvE,SAAS,aACJ;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