farseer-cli 1.11.1 → 1.12.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/README.md +60 -0
- package/dist/commands/app.js +56 -6
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/dashboards.js +16 -2
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/sheets.js +46 -34
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +7 -1
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +2 -0
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/tools/appTools.js +56 -6
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +79 -69
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +48 -59
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +39 -5
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/services/appSyncService.js +33 -1
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/apps.js +199 -9
- package/dist/services/apps.js.map +3 -3
- package/dist/services/farseerService.js +11 -0
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/modelExport.js +4 -2
- package/dist/services/modelExport.js.map +2 -2
- package/dist/utils/entityResolver.js +114 -28
- package/dist/utils/entityResolver.js.map +2 -2
- package/dist/utils/helpers.js +5 -5
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/{appResolver.js → nameResolver.js} +23 -23
- package/dist/utils/nameResolver.js.map +7 -0
- package/docs/cli-guide.md +16 -0
- package/package.json +1 -1
- package/dist/utils/appResolver.js.map +0 -7
package/dist/utils/helpers.js
CHANGED
|
@@ -78,7 +78,7 @@ var fs = __toESM(require("fs"));
|
|
|
78
78
|
var import_configService = require("../services/configService");
|
|
79
79
|
var import_logger = require("./logger");
|
|
80
80
|
var import_errorFormatter = require("./errorFormatter");
|
|
81
|
-
var
|
|
81
|
+
var import_nameResolver = require("./nameResolver");
|
|
82
82
|
function calculateHash(content) {
|
|
83
83
|
return crypto.createHash("md5").update(content).digest("hex");
|
|
84
84
|
}
|
|
@@ -432,17 +432,17 @@ async function orExit(work, message) {
|
|
|
432
432
|
}
|
|
433
433
|
async function resolveAppItemOrExit(api, selector) {
|
|
434
434
|
const apps = await orExit(api.listApps(), "Failed to list apps.");
|
|
435
|
-
const selection = (0,
|
|
435
|
+
const selection = (0, import_nameResolver.selectByNameOrId)(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);
|
|
436
436
|
if (selection.kind === "found") {
|
|
437
|
-
return selection.
|
|
437
|
+
return selection.entity;
|
|
438
438
|
}
|
|
439
439
|
if (selection.kind === "ambiguous") {
|
|
440
|
-
import_logger.logger.error((0,
|
|
440
|
+
import_logger.logger.error((0, import_nameResolver.formatAmbiguous)("apps", selector.appName ?? "", selection.matches, (a) => a.reference));
|
|
441
441
|
import_logger.logger.dim("Re-run with --id <id> in place of the name to pick one.");
|
|
442
442
|
process.exit(1);
|
|
443
443
|
}
|
|
444
444
|
if (selection.kind === "conflict") {
|
|
445
|
-
const { app, name } = selection;
|
|
445
|
+
const { entity: app, name } = selection;
|
|
446
446
|
import_logger.logger.error(
|
|
447
447
|
`App ${app.reference} is "${app.name}", not "${name}". The id and the name point at different apps, so nothing was done.`
|
|
448
448
|
);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectApp, formatAmbiguousApp } from './appResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectApp(apps, { name: selector.appName, id: selector.id });\n\n if (selection.kind === 'found') {\n return selection.app;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguousApp(selector.appName ?? '', selection.matches));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAS,iBAAiB,QAAgB,SAAgC;AAC7E,MAAI,QAAQ,WAAW,GAAG;AACtB;AAAA,EACJ;AAEA,QAAM,UAAU,gBAAgB,MAAM;AACtC,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,MAAI,aAAa;AACjB,aAAW,SAAS,SAAS;AACzB,UAAM,eAAe,MAAM,eACrB,GAAG,MAAM,YAAY,KAAK,MAAM,aAAa,MAC7C,MAAM,iBAAiB;AAE7B,UAAM,aAAa,MAAM,aAAa,IAAI,KAAK,MAAM,UAAU,EAAE,eAAe,IAAI;AAEpF,kBAAc,GAAG,SAAS,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,mBAAmB,YAAY,gBAAgB,UAAU;AAAA;AAAA,EAChI;AAEA,KAAG,eAAe,SAAS,YAAY,OAAO;AAClD;",
|
|
4
|
+
"sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectByNameOrId, formatAmbiguous } from './nameResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectByNameOrId(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);\n\n if (selection.kind === 'found') {\n return selection.entity;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { entity: app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;AACvB,4BAAkC;AAGlC,0BAAkD;AAE3C,SAAS,cAAc,SAAkC;AAC5D,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAChE;AAEO,SAAS,aAAqB;AACjC,SAAO,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc;AAClD;AAEO,SAAS,aAAa,QAAwB;AACjD,SAAO,KAAK,KAAK,WAAW,GAAG,MAAM;AACzC;AAEO,SAAS,kBAAkB,QAAwB;AACtD,SA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AI;AAEpF,kBAAc,GAAG,SAAS,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,mBAAmB,YAAY,gBAAgB,UAAU;AAAA;AAAA,EAChI;AAEA,KAAG,eAAe,SAAS,YAAY,OAAO;AAClD;",
|
|
6
6
|
"names": ["envCheckout"]
|
|
7
7
|
}
|
|
@@ -16,48 +16,48 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
var
|
|
20
|
-
__export(
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
19
|
+
var nameResolver_exports = {};
|
|
20
|
+
__export(nameResolver_exports, {
|
|
21
|
+
formatAmbiguous: () => formatAmbiguous,
|
|
22
|
+
matchByName: () => matchByName,
|
|
23
|
+
selectByNameOrId: () => selectByNameOrId
|
|
24
24
|
});
|
|
25
|
-
module.exports = __toCommonJS(
|
|
26
|
-
function
|
|
25
|
+
module.exports = __toCommonJS(nameResolver_exports);
|
|
26
|
+
function matchByName(items, name) {
|
|
27
27
|
const needle = name.trim().toLowerCase();
|
|
28
|
-
return
|
|
28
|
+
return items.filter((item) => item.name.toLowerCase() === needle);
|
|
29
29
|
}
|
|
30
|
-
function
|
|
30
|
+
function selectByNameOrId(items, selector, idOf) {
|
|
31
31
|
const id = selector.id?.trim();
|
|
32
32
|
if (id) {
|
|
33
|
-
const
|
|
34
|
-
if (!
|
|
33
|
+
const entity = items.find((item) => idOf(item) === id);
|
|
34
|
+
if (!entity) {
|
|
35
35
|
return { kind: "notFound" };
|
|
36
36
|
}
|
|
37
37
|
const name = selector.name?.trim();
|
|
38
|
-
if (name &&
|
|
39
|
-
return { kind: "conflict",
|
|
38
|
+
if (name && matchByName([entity], name).length === 0) {
|
|
39
|
+
return { kind: "conflict", entity, name };
|
|
40
40
|
}
|
|
41
|
-
return { kind: "found",
|
|
41
|
+
return { kind: "found", entity };
|
|
42
42
|
}
|
|
43
|
-
const matches =
|
|
43
|
+
const matches = matchByName(items, selector.name ?? "");
|
|
44
44
|
if (matches.length === 1) {
|
|
45
|
-
return { kind: "found",
|
|
45
|
+
return { kind: "found", entity: matches[0] };
|
|
46
46
|
}
|
|
47
47
|
if (matches.length === 0) {
|
|
48
48
|
return { kind: "notFound" };
|
|
49
49
|
}
|
|
50
50
|
return { kind: "ambiguous", matches };
|
|
51
51
|
}
|
|
52
|
-
function
|
|
53
|
-
const lines = matches.map((
|
|
54
|
-
return `Multiple
|
|
52
|
+
function formatAmbiguous(plural, name, matches, idOf) {
|
|
53
|
+
const lines = matches.map((item) => ` id ${idOf(item)} ${item.name}`);
|
|
54
|
+
return `Multiple ${plural} named "${name}" (${matches.length}). Specify one by id:
|
|
55
55
|
${lines.join("\n")}`;
|
|
56
56
|
}
|
|
57
57
|
// Annotate the CommonJS export names for ESM import in node:
|
|
58
58
|
0 && (module.exports = {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
formatAmbiguous,
|
|
60
|
+
matchByName,
|
|
61
|
+
selectByNameOrId
|
|
62
62
|
});
|
|
63
|
-
//# sourceMappingURL=
|
|
63
|
+
//# sourceMappingURL=nameResolver.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/nameResolver.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Resolving a user-typed name to one thing.\n *\n * The backend enforces name uniqueness per folder, not per tenant, so any\n * lookup that searches a whole tenant can find more than one match. Picking the\n * first is the bug this exists to prevent: it acts on an arbitrary one of them\n * and leaves the others unreachable by name.\n *\n * Pure. Each surface renders the outcome its own way \u2014 the CLI exits, the MCP\n * tools return an error response.\n */\n\nexport type Selection<T> =\n | { kind: 'found'; entity: T }\n | { kind: 'notFound' }\n | { kind: 'ambiguous'; matches: T[] }\n // Only when both a name and an id were given; see selectByNameOrId.\n | { kind: 'conflict'; entity: T; name: string };\n\n/** Every entity whose name matches, case-insensitively. */\nexport function matchByName<T extends { name: string }>(items: readonly T[], name: string): T[] {\n const needle = name.trim().toLowerCase();\n return items.filter((item) => item.name.toLowerCase() === needle);\n}\n\n/**\n * An id (unique) decides over a name (may collide). `idOf` reads whichever id\n * the caller disambiguates by, which is not always the one used to address the\n * entity afterwards \u2014 an app is selected by its Remote Job id but deleted by\n * its folder-item id.\n *\n * A name given alongside the id is a claim about which entity that is, and one\n * that does not hold is a conflict rather than something the id overrides: on\n * the CLI it is a tenant name read as an app name, and dropping it acts on the\n * id in the wrong tenant.\n */\nexport function selectByNameOrId<T extends { name: string }>(\n items: readonly T[],\n selector: { name?: string; id?: string },\n idOf: (item: T) => string,\n): Selection<T> {\n const id = selector.id?.trim();\n if (id) {\n const entity = items.find((item) => idOf(item) === id);\n if (!entity) {\n return { kind: 'notFound' };\n }\n const name = selector.name?.trim();\n if (name && matchByName([entity], name).length === 0) {\n return { kind: 'conflict', entity, name };\n }\n return { kind: 'found', entity };\n }\n\n const matches = matchByName(items, selector.name ?? '');\n if (matches.length === 1) {\n return { kind: 'found', entity: matches[0] };\n }\n if (matches.length === 0) {\n return { kind: 'notFound' };\n }\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Lists each candidate's id. Deliberately free of `--id` wording so it reads\n * correctly from the MCP tools too; the CLI appends its own hint.\n */\nexport function formatAmbiguous<T extends { name: string }>(\n plural: string,\n name: string,\n matches: readonly T[],\n idOf: (item: T) => string,\n): string {\n const lines = matches.map((item) => ` id ${idOf(item)} ${item.name}`);\n return `Multiple ${plural} named \"${name}\" (${matches.length}). Specify one by id:\\n${lines.join('\\n')}`;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,SAAS,YAAwC,OAAqB,MAAmB;AAC5F,QAAM,SAAS,KAAK,KAAK,EAAE,YAAY;AACvC,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,KAAK,YAAY,MAAM,MAAM;AACpE;AAaO,SAAS,iBACZ,OACA,UACA,MACY;AACZ,QAAM,KAAK,SAAS,IAAI,KAAK;AAC7B,MAAI,IAAI;AACJ,UAAM,SAAS,MAAM,KAAK,CAAC,SAAS,KAAK,IAAI,MAAM,EAAE;AACrD,QAAI,CAAC,QAAQ;AACT,aAAO,EAAE,MAAM,WAAW;AAAA,IAC9B;AACA,UAAM,OAAO,SAAS,MAAM,KAAK;AACjC,QAAI,QAAQ,YAAY,CAAC,MAAM,GAAG,IAAI,EAAE,WAAW,GAAG;AAClD,aAAO,EAAE,MAAM,YAAY,QAAQ,KAAK;AAAA,IAC5C;AACA,WAAO,EAAE,MAAM,SAAS,OAAO;AAAA,EACnC;AAEA,QAAM,UAAU,YAAY,OAAO,SAAS,QAAQ,EAAE;AACtD,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,SAAS,QAAQ,QAAQ,CAAC,EAAE;AAAA,EAC/C;AACA,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,WAAW;AAAA,EAC9B;AACA,SAAO,EAAE,MAAM,aAAa,QAAQ;AACxC;AAMO,SAAS,gBACZ,QACA,MACA,SACA,MACM;AACN,QAAM,QAAQ,QAAQ,IAAI,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE;AACxE,SAAO,YAAY,MAAM,WAAW,IAAI,MAAM,QAAQ,MAAM;AAAA,EAA0B,MAAM,KAAK,IAAI,CAAC;AAC1G;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/docs/cli-guide.md
CHANGED
|
@@ -123,6 +123,22 @@ deleted (they share the same status engine).
|
|
|
123
123
|
3. Create: `farseer app create "My App"`
|
|
124
124
|
4. Configure: `farseer app configure "My App" --entrypoint myScript.ts --scripts myScript.ts`
|
|
125
125
|
|
|
126
|
+
### Where and When an App Runs
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
farseer app configure "My App" --schedule "0 6 * * *"
|
|
130
|
+
farseer app configure "My App" --runner runner-1 --runner-image runner-typescript:latest
|
|
131
|
+
farseer app configure "My App" --compute batch:l
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`--compute local` runs the job in a container on the jobrunner's own machine;
|
|
135
|
+
`--compute batch` gives the run a machine of its own, and `batch:s`, `batch:m`,
|
|
136
|
+
`batch:l` or `batch:xl` pick how much machine. Pass `none` to `--schedule`,
|
|
137
|
+
`--runner` or `--runner-image` to clear it.
|
|
138
|
+
|
|
139
|
+
All four settings round-trip through `apps/<name>.json`, so `pull` records them
|
|
140
|
+
and `push` puts them back.
|
|
141
|
+
|
|
126
142
|
### Running Apps
|
|
127
143
|
|
|
128
144
|
```bash
|
package/package.json
CHANGED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/utils/appResolver.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AppListItem } from '../services/apps';\n\n/**\n * Every app whose name matches, case-insensitively. App names are not unique \u2014\n * two apps can share one in different folders \u2014 so a match is a list, and a\n * caller has to decide what more than one means.\n */\nexport function matchApps(apps: AppListItem[], name: string): AppListItem[] {\n const needle = name.trim().toLowerCase();\n return apps.filter((a) => a.name.toLowerCase() === needle);\n}\n\nexport type AppSelection =\n | { kind: 'found'; app: AppListItem }\n | { kind: 'notFound' }\n | { kind: 'ambiguous'; matches: AppListItem[] }\n | { kind: 'conflict'; app: AppListItem; name: string };\n\n/**\n * Resolve a selector \u2014 an id (unique) or a name (may collide) \u2014 to one decision.\n * Pure: the CLI exits and the MCP tools return an error response, so only the\n * rendering differs between them.\n */\nexport function selectApp(apps: AppListItem[], selector: { name?: string; id?: string }): AppSelection {\n const id = selector.id?.trim();\n if (id) {\n // The remote-job id is unique, so an id match is never ambiguous.\n const app = apps.find((a) => a.reference === id);\n if (!app) {\n return { kind: 'notFound' };\n }\n // A name given alongside the id is a claim about which app that is. One\n // that does not hold means the two were typed with different apps in\n // mind \u2014 on the CLI, a tenant name read as an app name, which the id\n // would otherwise override in silence and act on in the wrong tenant.\n const name = selector.name?.trim();\n if (name && matchApps([app], name).length === 0) {\n return { kind: 'conflict', app, name };\n }\n return { kind: 'found', app };\n }\n\n const matches = matchApps(apps, selector.name ?? '');\n if (matches.length === 1) {\n return { kind: 'found', app: matches[0] };\n }\n if (matches.length === 0) {\n return { kind: 'notFound' };\n }\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Lists each candidate's id. Deliberately free of `--id` wording so it reads\n * correctly from the MCP tools too; the CLI appends its own hint.\n */\nexport function formatAmbiguousApp(name: string, matches: AppListItem[]): string {\n const lines = matches.map((a) => ` id ${a.reference} ${a.name}`);\n return `Multiple apps named \"${name}\" (${matches.length}). Specify one by id:\\n${lines.join('\\n')}`;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,SAAS,UAAU,MAAqB,MAA6B;AACxE,QAAM,SAAS,KAAK,KAAK,EAAE,YAAY;AACvC,SAAO,KAAK,OAAO,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,MAAM;AAC7D;AAaO,SAAS,UAAU,MAAqB,UAAwD;AACnG,QAAM,KAAK,SAAS,IAAI,KAAK;AAC7B,MAAI,IAAI;AAEJ,UAAM,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,cAAc,EAAE;AAC/C,QAAI,CAAC,KAAK;AACN,aAAO,EAAE,MAAM,WAAW;AAAA,IAC9B;AAKA,UAAM,OAAO,SAAS,MAAM,KAAK;AACjC,QAAI,QAAQ,UAAU,CAAC,GAAG,GAAG,IAAI,EAAE,WAAW,GAAG;AAC7C,aAAO,EAAE,MAAM,YAAY,KAAK,KAAK;AAAA,IACzC;AACA,WAAO,EAAE,MAAM,SAAS,IAAI;AAAA,EAChC;AAEA,QAAM,UAAU,UAAU,MAAM,SAA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