farseer-cli 1.3.0 → 1.4.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.
Files changed (57) hide show
  1. package/README.md +102 -30
  2. package/dist/commands/checkout.js +3 -8
  3. package/dist/commands/checkout.js.map +2 -2
  4. package/dist/commands/pull.js +159 -46
  5. package/dist/commands/pull.js.map +2 -2
  6. package/dist/commands/push.js +185 -75
  7. package/dist/commands/push.js.map +2 -2
  8. package/dist/commands/run.js +31 -30
  9. package/dist/commands/run.js.map +2 -2
  10. package/dist/commands/status.js +26 -33
  11. package/dist/commands/status.js.map +2 -2
  12. package/dist/index.js +5 -3
  13. package/dist/index.js.map +2 -2
  14. package/dist/mcp/tools/appTools.js +6 -20
  15. package/dist/mcp/tools/appTools.js.map +2 -2
  16. package/dist/mcp/tools/authTools.js +2 -1
  17. package/dist/mcp/tools/authTools.js.map +2 -2
  18. package/dist/mcp/tools/cellTools.js +2 -10
  19. package/dist/mcp/tools/cellTools.js.map +2 -2
  20. package/dist/mcp/tools/dashboardTools.js +12 -23
  21. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  22. package/dist/mcp/tools/dataTools.js +5 -16
  23. package/dist/mcp/tools/dataTools.js.map +2 -2
  24. package/dist/mcp/tools/folderTools.js +3 -11
  25. package/dist/mcp/tools/folderTools.js.map +2 -2
  26. package/dist/mcp/tools/modelTools.js +14 -40
  27. package/dist/mcp/tools/modelTools.js.map +2 -2
  28. package/dist/mcp/tools/runTools.js +3 -8
  29. package/dist/mcp/tools/runTools.js.map +2 -2
  30. package/dist/mcp/tools/sheetTools.js +11 -22
  31. package/dist/mcp/tools/sheetTools.js.map +2 -2
  32. package/dist/mcp/tools/syncTools.js +132 -47
  33. package/dist/mcp/tools/syncTools.js.map +2 -2
  34. package/dist/mcp/utils/helpers.js +2 -2
  35. package/dist/mcp/utils/helpers.js.map +2 -2
  36. package/dist/services/appSyncService.js +3 -2
  37. package/dist/services/appSyncService.js.map +2 -2
  38. package/dist/services/farseerApi.js +13 -36
  39. package/dist/services/farseerApi.js.map +2 -2
  40. package/dist/services/farseerFactory.js +1 -1
  41. package/dist/services/farseerFactory.js.map +2 -2
  42. package/dist/services/farseerService.js +22 -14
  43. package/dist/services/farseerService.js.map +2 -2
  44. package/dist/services/syncService.js +322 -182
  45. package/dist/services/syncService.js.map +3 -3
  46. package/dist/utils/cliOptions.js +36 -0
  47. package/dist/utils/cliOptions.js.map +7 -0
  48. package/dist/utils/errorFormatter.js +152 -0
  49. package/dist/utils/errorFormatter.js.map +7 -0
  50. package/dist/utils/fileLogger.js +13 -0
  51. package/dist/utils/fileLogger.js.map +2 -2
  52. package/dist/utils/fileValidation.js +180 -0
  53. package/dist/utils/fileValidation.js.map +7 -0
  54. package/dist/utils/helpers.js +85 -14
  55. package/dist/utils/helpers.js.map +2 -2
  56. package/docs/cli-guide.md +49 -4
  57. package/package.json +1 -1
package/README.md CHANGED
@@ -263,15 +263,21 @@ All sync commands use the checked-out tenant by default. You can specify a diffe
263
263
  Download scripts and apps from Farseer instance.
264
264
 
265
265
  ```bash
266
- # Pull for checked-out tenant
266
+ # Pull for checked-out tenant (asks before merging into a dirty tree)
267
267
  farseer pull
268
268
 
269
+ # Skip the dirty-tree confirmation prompt
270
+ farseer pull -y
271
+
269
272
  # Pull for specific tenant
270
273
  farseer pull other-tenant
271
274
 
272
275
  # Download all files (not just .ts/.js)
273
276
  farseer pull --all
274
277
 
278
+ # Hard-reset local to match remote (overwrite edits, delete local-only)
279
+ farseer pull --force
280
+
275
281
  # Pull scripts + specific extra extensions
276
282
  farseer pull --include-ext .json --include-ext .txt
277
283
 
@@ -279,42 +285,96 @@ farseer pull --include-ext .json --include-ext .txt
279
285
  farseer pull --include-folder Config --include-folder "App Logs"
280
286
  ```
281
287
 
282
- **What it does:**
283
- 1. Fetches all files from `Files/` folder on instance
284
- 2. Downloads app configurations
285
- 3. Saves to `apps/<tenant>/files/` and `apps/<tenant>/apps/`
286
- 4. Creates `package.json` if missing
287
- 5. Updates sync tracking file
288
+ **Default behaviour:**
289
+ 1. Fetches files from `Files/` folder on instance.
290
+ 2. Downloads app configurations.
291
+ 3. If local has uncommitted changes, **asks before merging** so it doesn't silently mix remote into your work in progress (use `-y` to skip the prompt).
292
+ 4. Per-file conflict prompts when local and remote both moved — see [Conflict resolution](#conflict-resolution) below.
293
+ 5. Saves to `farseer-apps/<tenant>/files/` and `farseer-apps/<tenant>/apps/`, creates `package.json` if missing, updates sync tracking file.
294
+
295
+ **`--force` (destructive):**
296
+ - Hard reset local to remote within the current sync scope: overwrites local edits, restores files you deleted locally, AND removes local-only files.
297
+ - Scope-aware: a default `pull --force` only mirrors scripts. Previously-pulled out-of-scope files (e.g. a `.csv` you grabbed once with `--include-ext .csv`) survive a default `pull --force` because they're invisible to this run. To wipe everything, pass `--all` or pass the same `--include-ext` / `--include-folder` flags you used to pull them.
298
+ - **Always asks for confirmation** — `-y` does NOT bypass this.
299
+
300
+ ##### Conflict resolution
301
+
302
+ When `farseer pull` finds a file edited on BOTH sides, it prompts you per file. The choice list depends on the conflict type — both-modified gets the full menu, delete-vs-edit gets only the two choices that actually make sense.
303
+
304
+ **Both modified (or both newly added at the same path):**
305
+
306
+ | Choice | What happens |
307
+ |---|---|
308
+ | **Keep local version** | Your local file wins; sync state records that you've taken a stance, next push uploads your version. |
309
+ | **Use remote version (overwrite local)** | Remote wins; your local edit is discarded. |
310
+ | **Keep both (save remote as `.remote` file)** | Local stays untouched, remote version saved alongside as `<name>.remote.<ext>`. You decide later. |
311
+ | **Merge with markers (git-style)** | File is rewritten with `<<<<<<< LOCAL` / `=======` / `>>>>>>> REMOTE` blocks around both versions. Only offered for text files — binaries skip this option to avoid corruption. Open in your editor, pick what you want, remove the marker lines, then `farseer push`. The push pre-flight refuses any file that still contains LOCAL or REMOTE markers, so accidentally-unfinished resolves never reach the backend. |
312
+
313
+ **Locally modified, remote deleted** *(only two choices — there is no "remote version" to keep)*:
314
+
315
+ | Choice | What happens |
316
+ |---|---|
317
+ | **Keep local** | Your modified file stays; next push will recreate it on remote. |
318
+ | **Accept deletion** | Local file is removed to match remote. |
319
+
320
+ **Locally deleted, remote modified** *(mirror image — only two choices)*:
321
+
322
+ | Choice | What happens |
323
+ |---|---|
324
+ | **Keep deleted** | Stay deleted; next push will delete it on remote too. |
325
+ | **Restore remote version** | The remote version is downloaded back into your tree. |
326
+
327
+ After a `merge_markers` resolve, `farseer push` works without `--force` — the drift check sees only "local diverged from baseline" since the pull just ran. `--force` is only needed if someone else pushed AGAIN in the meantime.
288
328
 
289
329
  #### `farseer push [tenant]`
290
330
 
291
331
  Upload local changes to Farseer instance.
292
332
 
293
333
  ```bash
294
- # Push changes
334
+ # Push changes (asks for confirmation by default)
295
335
  farseer push
296
336
 
297
- # Force push (ignore remote changes)
337
+ # Skip the confirmation prompt for non-destructive pushes
338
+ farseer push -y
339
+
340
+ # Mirror local → remote: overwrite drift AND delete remote-only files
298
341
  farseer push --force
299
342
 
300
- # Include extra file types in status preview
343
+ # Include extra file types in the push set
301
344
  farseer push --include-ext .json
302
345
  ```
303
346
 
304
- **What it does:**
305
- 1. Checks for unpulled remote changes (fails if found, unless `--force`)
306
- 2. Shows diff and asks for confirmation
307
- 3. Uploads/updates/deletes files on instance
308
- 4. Uploads/updates app configurations
347
+ **Default behaviour:**
348
+ 1. **Pre-flight** — refuses any local file the backend would refuse anyway:
349
+ - Extension not on the [backend whitelist](#sync-includes-extra-file-types).
350
+ - Filename longer than 256 chars or empty after trimming.
351
+ - File body empty (0 bytes — common cause of opaque `BadRequest`).
352
+ - Unresolved git-style merge markers (`<<<<<<< LOCAL` / `=======` / `>>>>>>> REMOTE`) left over from a `merge_markers` pull — see [Conflict resolution](#conflict-resolution).
353
+
354
+ Reported up-front in a single grouped section; nothing leaves your machine until those are fixed.
355
+ 2. **Drift check** — if the remote has changes you haven't pulled (added or deleted files within your sync scope), push refuses and lists the exact files that are blocking, plus the matching `farseer pull` command (with the same `--include-ext` / `--include-folder` flags so it actually fetches them).
356
+ 3. **Plan preview** — shows added/modified/deleted files (and any conflicts) using the same buckets `farseer status` shows. Asks for confirmation (`-y` skips).
357
+ 4. Uploads/updates/deletes files on instance, then app configurations.
358
+
359
+ **Conflict-only push exits non-zero** — if every candidate file hits a service-side conflict (someone else edited the same file content), push prints `Push did nothing — N conflict(s) blocked the upload` and exits 1. CI scripts can branch on this.
360
+
361
+ **Out-of-scope files are invisible** — a `.json` or `.csv` next to your scripts won't be pushed under default `farseer push`. The push CLI does NOT have an `--all` flag (only `pull` and `status` do); broaden the push set with `--include-ext` / `--include-folder` instead. Hidden paths (any segment starting with `.`, like `.vscode/`) are skipped even by `pull --all` — they require explicit `--include-folder .vscode` to be picked up, on either side.
362
+
363
+ **`--force` (destructive — true mirror):**
364
+ - Skips the drift check AND deletes remote files that have no local counterpart (within the scope you declared via `--include-ext` / `--include-folder`).
365
+ - **Always asks for confirmation** — `-y` does NOT bypass this.
309
366
 
310
367
  #### `farseer status [tenant]`
311
368
 
312
369
  Compare local files with remote instance.
313
370
 
314
371
  ```bash
315
- # Check script files
372
+ # Fast (default): list-only, trusts the last sync for remote-side state
316
373
  farseer status
317
374
 
375
+ # Deep: also hashes remote contents to detect remote-side edits
376
+ farseer status --deep
377
+
318
378
  # Check all files
319
379
  farseer status --all
320
380
 
@@ -322,23 +382,30 @@ farseer status --all
322
382
  farseer status --include-ext .json --include-folder Config
323
383
  ```
324
384
 
325
- Output:
385
+ Output uses explicit add/modify/delete buckets per side, so a deletion never shows up as `M`:
386
+
326
387
  ```
327
- Comparing local with remote...
388
+ Comparing local (apps/<tenant>/files/) with remote (Files/)...
328
389
 
329
- Modified locally:
390
+ Local changes:
391
+ + Scripts/new-script.ts
330
392
  M Scripts/import-sales.ts
393
+ - Scripts/old-helper.ts
331
394
 
332
- Modified on remote:
333
- M Scripts/sync-actuals.ts
395
+ Remote changes:
396
+ + Data/from-other-dev.xlsx
397
+ M Scripts/sync-actuals.ts (by Matej)
398
+ - Scripts/legacy.ts
334
399
 
335
- Only local (new):
336
- + Scripts/new-script.ts
337
-
338
- Only on remote:
339
- - Data/old-file.xlsx
400
+ Run with --deep to also check for remote-side content edits.
340
401
  ```
341
402
 
403
+ Remote-modified entries pick up a `(by <name>)` suffix when the recorded sync metadata knows who last uploaded the file; everything else is bare `+` / `M` / `-`. The legend is consistent across `status` and the `push` plan preview.
404
+
405
+ In default fast mode the engine trusts the recorded baseline for remote — it can detect remote adds and deletes from the listing alone, but **not** remote-side content edits. Pass `--deep` when you want every remote file hashed.
406
+
407
+ `farseer status` and the preview that `farseer push` shows before its confirmation prompt come from the same status engine, so they always agree on which files are added / modified / deleted. If status says nothing is changed, push will say "Nothing to push"; if status lists three modified files, push lists the same three.
408
+
342
409
  #### `farseer diff [tenant] [file]`
343
410
 
344
411
  Show file differences.
@@ -562,9 +629,9 @@ Once configured, AI assistants have access to:
562
629
  - `farseer_checkout_clear` - Clear default tenant
563
630
 
564
631
  **Sync Operations:**
565
- - `farseer_pull` - Pull scripts and apps from remote
566
- - `farseer_push` - Push local changes to remote
567
- - `farseer_status` - Compare local vs remote state
632
+ - `farseer_pull` - Pull scripts and apps from remote. `force=true` overwrites local edits with remote on conflicts (does NOT wipe local-only files — that destructive step lives behind the CLI's interactive confirm; use `farseer pull --force` from a shell when you actually want a hard reset). Per-file conflict resolutions (keep_local / keep_remote / keep_both / merge_markers) are CLI-only because they require an interactive prompt; the MCP path either lets the conflict bubble up in the response (`conflicts[]` field) or `force=true` to overwrite.
633
+ - `farseer_push` - Push local changes to remote. `force=true` skips the drift check; `mirror=true` (separate parameter) also deletes remote files that have no local counterpart. The two are independent — combine when you want both. Returns `files.rejected[]` for any files the backend pre-flight refused (extension whitelist, name length, empty body, unresolved git-style conflict markers from a prior `merge_markers` pull). If every candidate was rejected and nothing was uploaded/updated/deleted, the call returns `VALIDATION_ERROR` instead of a silent no-op success.
634
+ - `farseer_status` - Compare local vs remote state. Default (fast) mode trusts the recorded baseline for remote-side state; pass `deep=true` to also hash every remote file and detect content edits made since last pull. The fast-mode response is **byte-for-byte the same** view that `farseer push` shows in its confirmation preview — the two commands are guaranteed not to disagree.
568
635
  - `farseer_diff` - Show file differences
569
636
  - `farseer_list_files` - List remote files
570
637
 
@@ -733,7 +800,12 @@ apps/
733
800
 
734
801
  ### Sync Includes (Extra File Types)
735
802
 
736
- By default, `pull`/`push`/`status` only sync script files (`.ts`, `.js`, `.mjs`, `.cjs`). Use `--all` to sync everything, or configure includes for a middle ground.
803
+ By default, `pull`/`push`/`status` only sync script files (`.ts`, `.js`). To broaden the set:
804
+ - `pull --all` / `status --all` syncs everything (push CLI does not have `--all`; use `--include-ext` / `--include-folder` to broaden a push).
805
+ - `--include-ext <ext>` / `--include-folder <folder>` adds inline scope to a single command (works on all four sync verbs: pull, push, status, checkout).
806
+ - Persistent includes via `farseer config include` (below) apply to every run without re-typing the flags.
807
+
808
+ **Hidden files** (anything with a path segment starting with `.` — `.env`, `.git/`, `.vscode/`, …) require **explicit opt-in** via `--include-ext` or `--include-folder` even under `--all`. This protects against a stray credential file in the working tree leaking on a force push. The CLI never picks them up just because they happen to have a whitelisted extension.
737
809
 
738
810
  **Persistent config (set once, always applies):**
739
811
 
@@ -38,10 +38,11 @@ var import_farseerFactory = require("../services/farseerFactory");
38
38
  var import_syncService = require("../services/syncService");
39
39
  var import_appSyncService = require("../services/appSyncService");
40
40
  var import_helpers = require("../utils/helpers");
41
+ var import_cliOptions = require("../utils/cliOptions");
41
42
  var fs = __toESM(require("fs"));
42
43
  var path = __toESM(require("path"));
43
44
  function registerCheckoutCommand(program) {
44
- program.command("checkout [org] [tenant]").description("Set default tenant for commands (runs auth check and pull)").option("--no-pull", "Skip automatic pull").option("--clear", "Clear current checkout").option("--include-ext <ext>", "Include extra file extension for pull (repeatable)", collectValues, []).option("--include-folder <folder>", "Include all files in folder for pull (repeatable)", collectValues, []).action(async (first, second, options) => {
45
+ program.command("checkout [org] [tenant]").description("Set default tenant for commands (runs auth check and pull)").option("--no-pull", "Skip automatic pull").option("--clear", "Clear current checkout").option("--include-ext <ext>", "Include extra file extension for pull (repeatable)", import_cliOptions.collectValues, []).option("--include-folder <folder>", "Include all files in folder for pull (repeatable)", import_cliOptions.collectValues, []).action(async (first, second, options) => {
45
46
  if (options.clear) {
46
47
  (0, import_configService.clearCurrentTenant)();
47
48
  import_logger.logger.success("Checkout cleared. You now need to specify tenant for each command.");
@@ -91,7 +92,7 @@ function registerCheckoutCommand(program) {
91
92
  if (!fs.existsSync(packageJsonPath)) {
92
93
  createDefaultPackageJson(tenant, packageJsonPath);
93
94
  }
94
- const includeExtensions = normalizeExtensions(options.includeExt);
95
+ const includeExtensions = (0, import_cliOptions.normalizeExtensions)(options.includeExt);
95
96
  const includeFolders = options.includeFolder;
96
97
  const result = await syncService.pull({
97
98
  all: false,
@@ -123,12 +124,6 @@ function registerCheckoutCommand(program) {
123
124
  import_logger.logger.dim(" farseer push");
124
125
  });
125
126
  }
126
- function collectValues(value, previous) {
127
- return previous.concat([value]);
128
- }
129
- function normalizeExtensions(exts) {
130
- return exts.map((ext) => ext.startsWith(".") ? ext.toLowerCase() : `.${ext.toLowerCase()}`);
131
- }
132
127
  function createDefaultPackageJson(tenant, packageJsonPath) {
133
128
  const packageJson = {
134
129
  name: `farseer-${tenant}`,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/checkout.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport {\n getCurrentCheckout,\n setCurrentCheckout,\n clearCurrentTenant,\n saveTenantOrgMapping,\n} from '../services/configService';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantDir, ensureDirectoryExists } from '../utils/helpers';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport function registerCheckoutCommand(program: Command): void {\n program\n .command('checkout [org] [tenant]')\n .description('Set default tenant for commands (runs auth check and pull)')\n .option('--no-pull', 'Skip automatic pull')\n .option('--clear', 'Clear current checkout')\n .option('--include-ext <ext>', 'Include extra file extension for pull (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder for pull (repeatable)', collectValues, [])\n .action(async (first, second, options) => {\n // Handle --clear flag\n if (options.clear) {\n clearCurrentTenant();\n logger.success('Checkout cleared. You now need to specify tenant for each command.');\n return;\n }\n\n // If no arguments specified, show current checkout status\n if (!first) {\n const current = getCurrentCheckout();\n if (current) {\n if (current.organisation === current.tenant) {\n logger.info(`Currently checked out: ${chalk.bold(current.tenant)}`);\n } else {\n logger.info(\n `Currently checked out: ${chalk.bold(current.tenant)} (org: ${chalk.bold(current.organisation)})`,\n );\n }\n logger.dim('Run \"farseer checkout <tenant>\" to switch tenants.');\n logger.dim('Run \"farseer checkout --clear\" to clear checkout.');\n } else {\n logger.info('No tenant currently checked out.');\n logger.dim('Run \"farseer checkout <tenant>\" to set a default tenant.');\n logger.dim('Run \"farseer checkout <org> <tenant>\" if organisation and tenant differ.');\n }\n return;\n }\n\n // Determine organisation and tenant\n // If two arguments: first=organisation, second=tenant\n // If one argument: organisation=tenant=first\n const organisation = second ? first : first;\n const tenant = second || first;\n\n logger.info(`Checking out tenant: ${chalk.bold(tenant)} (org: ${chalk.bold(organisation)})...`);\n console.log();\n\n // Step 1: Verify authentication\n logger.info('Verifying authentication...');\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const authLabel = clientResult.authType === 'apiKey' ? 'API key' : 'browser login';\n logger.success(`Authenticated (using ${authLabel})`);\n\n // Step 2: Set as current checkout and save org-tenant mapping\n setCurrentCheckout(organisation, tenant);\n saveTenantOrgMapping(tenant, organisation);\n\n // Step 3: Auto-pull (unless --no-pull)\n if (options.pull) {\n console.log();\n logger.info('Pulling latest files and apps...');\n\n const syncService = new SyncService(tenant, clientResult.client);\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n try {\n // Ensure package.json exists\n const packageJsonPath = path.join(tenantDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n createDefaultPackageJson(tenant, packageJsonPath);\n }\n\n // Pull files (scripts + includes by default)\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const result = await syncService.pull({\n all: false,\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // Pull apps\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appResult = await appSyncService.pull();\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n logger.success('Pull complete!');\n } catch (error) {\n logger.warning('Pull failed, but checkout is complete.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n }\n }\n\n // Final message\n console.log();\n logger.success(`Tenant ${chalk.bold(tenant)} is now checked out.`);\n logger.dim('You can now run commands without specifying the tenant:');\n logger.dim(' farseer status');\n logger.dim(' farseer model --variables');\n logger.dim(' farseer apps');\n logger.dim(' farseer push');\n });\n}\n\nfunction collectValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nfunction normalizeExtensions(exts: string[]): string[] {\n return exts.map((ext) => (ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`));\n}\n\nfunction createDefaultPackageJson(tenant: string, packageJsonPath: string): void {\n const packageJson = {\n name: `farseer-${tenant}`,\n version: '1.0.0',\n description: `Farseer scripts for ${tenant}`,\n type: 'module',\n scripts: {\n build: 'tsc',\n },\n dependencies: {\n 'farseer-client':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar',\n arquero: '^7.0.1',\n xlsx: '^0.18.5',\n xmldom: '^0.6.0',\n },\n devDependencies: {\n '@types/node': '^22.5.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,oBAAuB;AACvB,2BAKO;AACP,4BAA8D;AAC9D,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAAoD;AACpD,SAAoB;AACpB,WAAsB;AAEf,SAAS,wBAAwB,SAAwB;AAC5D,UACK,QAAQ,yBAAyB,EACjC,YAAY,4DAA4D,EACxE,OAAO,aAAa,qBAAqB,EACzC,OAAO,WAAW,wBAAwB,EAC1C,OAAO,uBAAuB,sDAAsD,eAAe,CAAC,CAAC,EACrG,OAAO,6BAA6B,qDAAqD,eAAe,CAAC,CAAC,EAC1G,OAAO,OAAO,OAAO,QAAQ,YAAY;AAEtC,QAAI,QAAQ,OAAO;AACf,mDAAmB;AACnB,2BAAO,QAAQ,oEAAoE;AACnF;AAAA,IACJ;AAGA,QAAI,CAAC,OAAO;AACR,YAAM,cAAU,yCAAmB;AACnC,UAAI,SAAS;AACT,YAAI,QAAQ,iBAAiB,QAAQ,QAAQ;AACzC,+BAAO,KAAK,0BAA0B,aAAAA,QAAM,KAAK,QAAQ,MAAM,CAAC,EAAE;AAAA,QACtE,OAAO;AACH,+BAAO;AAAA,YACH,0BAA0B,aAAAA,QAAM,KAAK,QAAQ,MAAM,CAAC,UAAU,aAAAA,QAAM,KAAK,QAAQ,YAAY,CAAC;AAAA,UAClG;AAAA,QACJ;AACA,6BAAO,IAAI,oDAAoD;AAC/D,6BAAO,IAAI,mDAAmD;AAAA,MAClE,OAAO;AACH,6BAAO,KAAK,kCAAkC;AAC9C,6BAAO,IAAI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AAY;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 { logger } from '../utils/logger';\nimport {\n getCurrentCheckout,\n setCurrentCheckout,\n clearCurrentTenant,\n saveTenantOrgMapping,\n} from '../services/configService';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantDir, ensureDirectoryExists } from '../utils/helpers';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport function registerCheckoutCommand(program: Command): void {\n program\n .command('checkout [org] [tenant]')\n .description('Set default tenant for commands (runs auth check and pull)')\n .option('--no-pull', 'Skip automatic pull')\n .option('--clear', 'Clear current checkout')\n .option('--include-ext <ext>', 'Include extra file extension for pull (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder for pull (repeatable)', collectValues, [])\n .action(async (first, second, options) => {\n // Handle --clear flag\n if (options.clear) {\n clearCurrentTenant();\n logger.success('Checkout cleared. You now need to specify tenant for each command.');\n return;\n }\n\n // If no arguments specified, show current checkout status\n if (!first) {\n const current = getCurrentCheckout();\n if (current) {\n if (current.organisation === current.tenant) {\n logger.info(`Currently checked out: ${chalk.bold(current.tenant)}`);\n } else {\n logger.info(\n `Currently checked out: ${chalk.bold(current.tenant)} (org: ${chalk.bold(current.organisation)})`,\n );\n }\n logger.dim('Run \"farseer checkout <tenant>\" to switch tenants.');\n logger.dim('Run \"farseer checkout --clear\" to clear checkout.');\n } else {\n logger.info('No tenant currently checked out.');\n logger.dim('Run \"farseer checkout <tenant>\" to set a default tenant.');\n logger.dim('Run \"farseer checkout <org> <tenant>\" if organisation and tenant differ.');\n }\n return;\n }\n\n // Determine organisation and tenant\n // If two arguments: first=organisation, second=tenant\n // If one argument: organisation=tenant=first\n const organisation = second ? first : first;\n const tenant = second || first;\n\n logger.info(`Checking out tenant: ${chalk.bold(tenant)} (org: ${chalk.bold(organisation)})...`);\n console.log();\n\n // Step 1: Verify authentication\n logger.info('Verifying authentication...');\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const authLabel = clientResult.authType === 'apiKey' ? 'API key' : 'browser login';\n logger.success(`Authenticated (using ${authLabel})`);\n\n // Step 2: Set as current checkout and save org-tenant mapping\n setCurrentCheckout(organisation, tenant);\n saveTenantOrgMapping(tenant, organisation);\n\n // Step 3: Auto-pull (unless --no-pull)\n if (options.pull) {\n console.log();\n logger.info('Pulling latest files and apps...');\n\n const syncService = new SyncService(tenant, clientResult.client);\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n try {\n // Ensure package.json exists\n const packageJsonPath = path.join(tenantDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n createDefaultPackageJson(tenant, packageJsonPath);\n }\n\n // Pull files (scripts + includes by default)\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const result = await syncService.pull({\n all: false,\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // Pull apps\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appResult = await appSyncService.pull();\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n logger.success('Pull complete!');\n } catch (error) {\n logger.warning('Pull failed, but checkout is complete.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n }\n }\n\n // Final message\n console.log();\n logger.success(`Tenant ${chalk.bold(tenant)} is now checked out.`);\n logger.dim('You can now run commands without specifying the tenant:');\n logger.dim(' farseer status');\n logger.dim(' farseer model --variables');\n logger.dim(' farseer apps');\n logger.dim(' farseer push');\n });\n}\n\nfunction createDefaultPackageJson(tenant: string, packageJsonPath: string): void {\n const packageJson = {\n name: `farseer-${tenant}`,\n version: '1.0.0',\n description: `Farseer scripts for ${tenant}`,\n type: 'module',\n scripts: {\n build: 'tsc',\n },\n dependencies: {\n 'farseer-client':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar',\n arquero: '^7.0.1',\n xlsx: '^0.18.5',\n xmldom: '^0.6.0',\n },\n devDependencies: {\n '@types/node': '^22.5.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,oBAAuB;AACvB,2BAKO;AACP,4BAA8D;AAC9D,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAAoD;AACpD,wBAAmD;AACnD,SAAoB;AACpB,WAAsB;AAEf,SAAS,wBAAwB,SAAwB;AAC5D,UACK,QAAQ,yBAAyB,EACjC,YAAY,4DAA4D,EACxE,OAAO,aAAa,qBAAqB,EACzC,OAAO,WAAW,wBAAwB,EAC1C,OAAO,uBAAuB,sDAAsD,iCAAe,CAAC,CAAC,EACrG,OAAO,6BAA6B,qDAAqD,iCAAe,CAAC,CAAC,EAC1G,OAAO,OAAO,OAAO,QAAQ,YAAY;AAEtC,QAAI,QAAQ,OAAO;AACf,mDAAmB;AACnB,2BAAO,QAAQ,oEAAoE;AACnF;AAAA,IACJ;AAGA,QAAI,CAAC,OAAO;AACR,YAAM,cAAU,yC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A,IACX;AAAA,IACA,cAAc;AAAA,MACV,kBACI;AAAA,MACJ,SAAS;AAAA,MACT,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,IACA,iBAAiB;AAAA,MACb,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"]
7
7
  }
@@ -39,10 +39,18 @@ var import_farseerFactory = require("../services/farseerFactory");
39
39
  var import_syncService = require("../services/syncService");
40
40
  var import_appSyncService = require("../services/appSyncService");
41
41
  var import_helpers = require("../utils/helpers");
42
+ var import_errorFormatter = require("../utils/errorFormatter");
43
+ var import_fileValidation = require("../utils/fileValidation");
44
+ var import_cliOptions = require("../utils/cliOptions");
45
+ var fs = __toESM(require("fs"));
46
+ var path = __toESM(require("path"));
42
47
  function registerPullCommand(program) {
43
48
  program.command("pull [org] [tenant]").description(
44
49
  "Pull files from Farseer instance to local\n\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)"
45
- ).option("--all", "Pull all files (default: only scripts .ts, .js)").option("--force", "Force pull, overwriting local changes on conflicts").option("--include-ext <ext>", "Include extra file extension (repeatable)", collectValues, []).option("--include-folder <folder>", "Include all files in folder (repeatable)", collectValues, []).action(async (arg1, arg2, options) => {
50
+ ).option("--all", "Pull all files (default: only scripts .ts, .js)").option(
51
+ "--force",
52
+ "Hard reset local to remote within the current sync scope: overwrite local edits, delete local-only files. Files outside scope (e.g. previously-pulled .csv on a default --force run without --include-ext .csv) are NOT touched. Always asks for confirmation."
53
+ ).option("-y, --yes", "Skip confirmation when local has uncommitted changes (ignored under --force)").option("--include-ext <ext>", "Include extra file extension (repeatable)", import_cliOptions.collectValues, []).option("--include-folder <folder>", "Include all files in folder (repeatable)", import_cliOptions.collectValues, []).action(async (arg1, arg2, options) => {
46
54
  const { organisation, tenant } = (0, import_helpers.resolveTenantWithOrgMapping)(arg1, arg2);
47
55
  const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
48
56
  if (!clientResult) {
@@ -53,18 +61,81 @@ function registerPullCommand(program) {
53
61
  const tenantDir = (0, import_helpers.getTenantDir)(tenant);
54
62
  (0, import_helpers.ensureDirectoryExists)(tenantDir);
55
63
  await createDefaultPackageJson(tenantDir, tenant);
64
+ const includeExtensions = (0, import_cliOptions.normalizeExtensions)(options.includeExt);
65
+ const includeFolders = options.includeFolder;
66
+ const filterOptions = {
67
+ includeExtensions: includeExtensions.length > 0 ? includeExtensions : void 0,
68
+ includeFolders: includeFolders.length > 0 ? includeFolders : void 0
69
+ };
70
+ const syncOptions = {
71
+ all: options.all,
72
+ force: options.force,
73
+ ...filterOptions
74
+ };
75
+ const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
76
+ const folderInitialised = fs.existsSync(filesDir);
77
+ let preStatus = null;
78
+ let preStatusError = null;
79
+ if (folderInitialised) {
80
+ try {
81
+ preStatus = await syncService.getStatus({ ...filterOptions, all: options.all, deep: false });
82
+ } catch (error) {
83
+ preStatusError = error;
84
+ import_logger.logger.dim(`Could not compute pre-pull status: ${preStatusError.message}`);
85
+ }
86
+ }
87
+ const localChanges = preStatus ? preStatus.addedLocally.length + preStatus.modifiedLocally.length + preStatus.deletedLocally.length + preStatus.conflicts.length : 0;
88
+ if (options.force) {
89
+ console.log();
90
+ console.log(import_chalk.default.red.bold("--force will hard-reset local to match remote."));
91
+ if (preStatus) {
92
+ summarisePreStatus(preStatus);
93
+ } else if (preStatusError) {
94
+ console.log(
95
+ import_chalk.default.red(
96
+ "Cannot show what will be lost \u2014 pre-pull status failed (see line above). Refusing to --force without visibility."
97
+ )
98
+ );
99
+ import_logger.logger.dim("Re-run after the underlying issue clears, or use a non-force pull to merge.");
100
+ process.exit(1);
101
+ } else {
102
+ import_logger.logger.dim("No local files yet \u2014 nothing to discard.");
103
+ }
104
+ const confirm = await import_inquirer.default.prompt([
105
+ {
106
+ type: "confirm",
107
+ name: "proceed",
108
+ message: `Discard local changes and reset ${tenant} to remote?`,
109
+ default: false
110
+ }
111
+ ]);
112
+ if (!confirm.proceed) {
113
+ import_logger.logger.info("Pull cancelled.");
114
+ return;
115
+ }
116
+ } else if (localChanges > 0 && !options.yes) {
117
+ console.log();
118
+ import_logger.logger.warning(`Local has ${localChanges} unsynced change(s).`);
119
+ summarisePreStatus(preStatus);
120
+ import_logger.logger.dim("Pull will keep your edits and merge remote-side changes around them.");
121
+ import_logger.logger.dim("To wipe local and reset to remote: re-run with --force.");
122
+ const confirm = await import_inquirer.default.prompt([
123
+ {
124
+ type: "confirm",
125
+ name: "proceed",
126
+ message: `Continue pulling into a dirty working tree?`,
127
+ default: true
128
+ }
129
+ ]);
130
+ if (!confirm.proceed) {
131
+ import_logger.logger.info("Pull cancelled.");
132
+ return;
133
+ }
134
+ }
56
135
  console.log();
57
136
  console.log(import_chalk.default.bold("\u2550\u2550\u2550 Files \u2550\u2550\u2550"));
58
137
  import_logger.logger.info(`Pulling files from ${tenant}...`);
59
138
  try {
60
- const includeExtensions = normalizeExtensions(options.includeExt);
61
- const includeFolders = options.includeFolder;
62
- const syncOptions = {
63
- all: options.all,
64
- force: options.force,
65
- includeExtensions: includeExtensions.length > 0 ? includeExtensions : void 0,
66
- includeFolders: includeFolders.length > 0 ? includeFolders : void 0
67
- };
68
139
  let result = await syncService.pull(syncOptions);
69
140
  if (result.conflicts.length > 0 && !options.force) {
70
141
  console.log();
@@ -94,6 +165,12 @@ function registerPullCommand(program) {
94
165
  { name: "Use remote version (overwrite local)", value: "keep_remote" },
95
166
  { name: "Keep both (save remote as .remote file)", value: "keep_both" }
96
167
  ];
168
+ if ((0, import_fileValidation.isLikelyTextFile)(conflict.filePath)) {
169
+ choices.push({
170
+ name: "Merge with markers (git-style \u2014 edit file, then push to finish)",
171
+ value: "merge_markers"
172
+ });
173
+ }
97
174
  }
98
175
  const answer = await import_inquirer.default.prompt([
99
176
  {
@@ -109,25 +186,36 @@ function registerPullCommand(program) {
109
186
  }
110
187
  if (result.downloaded.length > 0) {
111
188
  console.log(import_chalk.default.green("Downloaded:"));
112
- for (const file of result.downloaded) {
113
- console.log(import_chalk.default.green(` + ${file}`));
114
- }
189
+ for (const file of result.downloaded) console.log(import_chalk.default.green(` + ${file}`));
115
190
  }
116
191
  if (result.deleted.length > 0) {
117
192
  console.log(import_chalk.default.red("Deleted (removed from remote):"));
118
- for (const file of result.deleted) {
119
- console.log(import_chalk.default.red(` - ${file}`));
120
- }
193
+ for (const file of result.deleted) console.log(import_chalk.default.red(` - ${file}`));
121
194
  }
122
195
  if (result.conflictFilesWritten.length > 0) {
123
196
  console.log(import_chalk.default.yellow("Conflict files created:"));
124
- for (const file of result.conflictFilesWritten) {
125
- console.log(import_chalk.default.yellow(` ~ ${file}`));
197
+ for (const file of result.conflictFilesWritten) console.log(import_chalk.default.yellow(` ~ ${file}`));
198
+ if (result.conflictFilesWritten.some((f) => f.includes("(merge markers)"))) {
199
+ console.log();
200
+ import_logger.logger.dim('Files marked with "(merge markers)" contain git-style <<<<<<</=======/>>>>>>>');
201
+ import_logger.logger.dim("blocks. Open them, pick which version to keep, remove the marker lines,");
202
+ import_logger.logger.dim(`then run \`farseer push ${tenant}\` to upload the resolved version.`);
126
203
  }
127
204
  }
128
205
  import_logger.logger.dim(
129
206
  `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`
130
207
  );
208
+ let extraLocalDeletes = [];
209
+ if (options.force) {
210
+ extraLocalDeletes = await wipeLocalOnly(syncService, filesDir, {
211
+ ...filterOptions,
212
+ all: options.all
213
+ });
214
+ if (extraLocalDeletes.length > 0) {
215
+ console.log(import_chalk.default.red("Local-only files removed (mirror remote):"));
216
+ for (const file of extraLocalDeletes) console.log(import_chalk.default.red(` - ${file}`));
217
+ }
218
+ }
131
219
  if (result.downloaded.length > 0) {
132
220
  const syncState = syncService.loadSyncState();
133
221
  const auditEntries = result.downloaded.map((filePath) => ({
@@ -139,35 +227,23 @@ function registerPullCommand(program) {
139
227
  }));
140
228
  (0, import_helpers.appendToAuditLog)(tenant, auditEntries);
141
229
  }
142
- let hasChanges = result.downloaded.length > 0 || result.deleted.length > 0;
143
- let appResult = {
144
- created: [],
145
- updated: [],
146
- deleted: [],
147
- unchanged: []
148
- };
230
+ let hasChanges = result.downloaded.length > 0 || result.deleted.length > 0 || extraLocalDeletes.length > 0;
149
231
  console.log();
150
232
  console.log(import_chalk.default.bold("\u2550\u2550\u2550 Apps \u2550\u2550\u2550"));
151
233
  import_logger.logger.info(`Pulling apps from ${tenant}...`);
152
234
  const appSyncService = new import_appSyncService.AppSyncService(tenant, clientResult.client);
153
- appResult = await appSyncService.pull();
235
+ const appResult = await appSyncService.pull();
154
236
  if (appResult.created.length > 0) {
155
237
  console.log(import_chalk.default.green("New apps:"));
156
- for (const app of appResult.created) {
157
- console.log(import_chalk.default.green(` + ${app}`));
158
- }
238
+ for (const app of appResult.created) console.log(import_chalk.default.green(` + ${app}`));
159
239
  }
160
240
  if (appResult.updated.length > 0) {
161
241
  console.log(import_chalk.default.yellow("Updated apps:"));
162
- for (const app of appResult.updated) {
163
- console.log(import_chalk.default.yellow(` ~ ${app}`));
164
- }
242
+ for (const app of appResult.updated) console.log(import_chalk.default.yellow(` ~ ${app}`));
165
243
  }
166
244
  if (appResult.deleted.length > 0) {
167
245
  console.log(import_chalk.default.red("Deleted apps (removed from remote):"));
168
- for (const app of appResult.deleted) {
169
- console.log(import_chalk.default.red(` - ${app}`));
170
- }
246
+ for (const app of appResult.deleted) console.log(import_chalk.default.red(` - ${app}`));
171
247
  }
172
248
  import_logger.logger.dim(
173
249
  `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`
@@ -181,7 +257,7 @@ function registerPullCommand(program) {
181
257
  console.log(import_chalk.default.bold("\u2550\u2550\u2550 Summary \u2550\u2550\u2550"));
182
258
  import_logger.logger.success("Pull complete!");
183
259
  import_logger.logger.dim(
184
- `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`
260
+ `Files: +${result.downloaded.length} -${result.deleted.length} ${extraLocalDeletes.length > 0 ? `(${extraLocalDeletes.length} local-only removed) ` : ""}(${result.unchanged.length} unchanged)`
185
261
  );
186
262
  import_logger.logger.dim(
187
263
  `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`
@@ -189,9 +265,7 @@ function registerPullCommand(program) {
189
265
  } catch (error) {
190
266
  import_fileLogger.fileLogger.error("pull", error);
191
267
  import_logger.logger.error("Pull failed.");
192
- if (error instanceof Error) {
193
- import_logger.logger.error(error.message);
194
- }
268
+ import_logger.logger.error(await (0, import_errorFormatter.formatClientError)(error));
195
269
  const logPath = import_fileLogger.fileLogger.getLogPath();
196
270
  if (logPath) {
197
271
  import_logger.logger.dim(`Debug log: ${logPath}`);
@@ -200,9 +274,54 @@ function registerPullCommand(program) {
200
274
  }
201
275
  });
202
276
  }
277
+ function summarisePreStatus(status) {
278
+ const MAX_PATHS_PER_SECTION = 20;
279
+ const renderSection = (label, paths, color) => {
280
+ if (paths.length === 0) return;
281
+ console.log(color(` ${label} (${paths.length}):`));
282
+ const visible = paths.slice(0, MAX_PATHS_PER_SECTION);
283
+ for (const p of visible) console.log(color(` ${p}`));
284
+ if (paths.length > MAX_PATHS_PER_SECTION) {
285
+ console.log(import_chalk.default.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));
286
+ }
287
+ };
288
+ renderSection("+ new local file(s)", status.addedLocally, import_chalk.default.green);
289
+ renderSection("M locally modified file(s)", status.modifiedLocally, import_chalk.default.yellow);
290
+ renderSection("- locally deleted file(s)", status.deletedLocally, import_chalk.default.red);
291
+ if (status.conflicts.length > 0) {
292
+ const conflictPaths = status.conflicts.map((c) => c.filePath);
293
+ renderSection("! conflict(s)", conflictPaths, import_chalk.default.red.bold);
294
+ }
295
+ console.log();
296
+ }
297
+ async function wipeLocalOnly(syncService, filesDir, filterOptions) {
298
+ const status = await syncService.getStatus({ ...filterOptions, deep: false });
299
+ const removed = [];
300
+ const failed = [];
301
+ const syncState = syncService.loadSyncState();
302
+ for (const file of status.addedLocally) {
303
+ const fullPath = (0, import_helpers.safeResolveWithinBase)(filesDir, file);
304
+ if (fs.existsSync(fullPath)) {
305
+ try {
306
+ fs.unlinkSync(fullPath);
307
+ removed.push(file);
308
+ delete syncState.files[file];
309
+ syncService.saveSyncState(syncState);
310
+ } catch (err) {
311
+ failed.push({ file, reason: err instanceof Error ? err.message : String(err) });
312
+ }
313
+ } else {
314
+ delete syncState.files[file];
315
+ syncService.saveSyncState(syncState);
316
+ }
317
+ }
318
+ if (failed.length > 0) {
319
+ import_logger.logger.warning(`${failed.length} local-only file(s) could not be removed:`);
320
+ for (const f of failed) import_logger.logger.dim(` ${f.file} \u2014 ${f.reason}`);
321
+ }
322
+ return removed;
323
+ }
203
324
  async function createDefaultPackageJson(tenantDir, tenant) {
204
- const fs = await import("fs");
205
- const path = await import("path");
206
325
  const packageJsonPath = path.join(tenantDir, "package.json");
207
326
  if (fs.existsSync(packageJsonPath)) {
208
327
  return;
@@ -283,12 +402,6 @@ async function createDefaultPackageJson(tenantDir, tenant) {
283
402
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf-8");
284
403
  import_logger.logger.dim(`Created package.json for ${tenant}`);
285
404
  }
286
- function collectValues(value, previous) {
287
- return previous.concat([value]);
288
- }
289
- function normalizeExtensions(exts) {
290
- return exts.map((ext) => ext.startsWith(".") ? ext.toLowerCase() : `.${ext.toLowerCase()}`);
291
- }
292
405
  // Annotate the CommonJS export names for ESM import in node:
293
406
  0 && (module.exports = {
294
407
  registerPullCommand