@spica/cli 0.18.31 → 0.18.33

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 (2) hide show
  1. package/index.js +1564 -18
  2. package/package.json +43 -1
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // apps/cli/index.ts
2
- import caporalCore4 from "@caporal/core";
2
+ import caporalCore6 from "@caporal/core";
3
3
 
4
4
  // apps/cli/src/console.ts
5
5
  import { blue, bold, red, yellow } from "colorette";
@@ -20,11 +20,6 @@ function spin(options) {
20
20
  },
21
21
  (error) => {
22
22
  spinner.fail();
23
- if (typeof error == "object" && "message" in error) {
24
- console.error(error.message);
25
- console.debug(error);
26
- process.exit();
27
- }
28
23
  return Promise.reject(error);
29
24
  }
30
25
  );
@@ -95,7 +90,7 @@ $\xA0spica context switch <name> to switch context.`
95
90
  return searchResult.config;
96
91
  }
97
92
  config2.get = get;
98
- async function path9() {
93
+ async function path19() {
99
94
  let config3 = await explorer.search(process.cwd());
100
95
  if (!config3) {
101
96
  config3 = await explorer.search(os.homedir());
@@ -105,9 +100,9 @@ $\xA0spica context switch <name> to switch context.`
105
100
  }
106
101
  return void 0;
107
102
  }
108
- config2.path = path9;
103
+ config2.path = path19;
109
104
  async function set(config3) {
110
- let configPath = await path9();
105
+ let configPath = await path19();
111
106
  if (!configPath) {
112
107
  configPath = _path.join(os.homedir(), ".spicarc");
113
108
  }
@@ -2976,9 +2971,10 @@ var ApikeySynchronizer = class {
2976
2971
  objectName: this.getDisplayableModuleName() + " " + apikey.name,
2977
2972
  e
2978
2973
  });
2979
- const policies = [...apikey.policies];
2980
- delete apikey.policies;
2981
- const apikeyInsertPromise = this.targetService.post("passport/apikey", apikey).catch((e) => insertRejectionHandler(e));
2974
+ const policies = [...apikey.policies ?? []];
2975
+ const apikeyData = { ...apikey };
2976
+ delete apikeyData.policies;
2977
+ const apikeyInsertPromise = this.targetService.post("passport/apikey", apikeyData).catch((e) => insertRejectionHandler(e));
2982
2978
  return apikeyInsertPromise.then(() => {
2983
2979
  const policyAttachPromises = policies.map(
2984
2980
  (policy) => this.targetService.put(`passport/apikey/${apikey._id}/policy/${policy}`).catch((e) => insertRejectionHandler(e))
@@ -2995,11 +2991,12 @@ var ApikeySynchronizer = class {
2995
2991
  e
2996
2992
  });
2997
2993
  };
2998
- const policies = [...apikey.policies];
2999
- delete apikey.policies;
2994
+ const policies = [...apikey.policies ?? []];
2995
+ const apikeyData = { ...apikey };
2996
+ delete apikeyData.policies;
3000
2997
  const apikeyDeletePromise = this.targetService.delete(`passport/apikey/${apikey._id}`).catch((e) => rejectionHandler(e));
3001
2998
  const apikeyInsertPromise = apikeyDeletePromise.then(
3002
- () => this.targetService.post(`passport/apikey`, apikey).catch((e) => rejectionHandler(e))
2999
+ () => this.targetService.post(`passport/apikey`, apikeyData).catch((e) => rejectionHandler(e))
3003
3000
  );
3004
3001
  return apikeyInsertPromise.then(() => {
3005
3002
  const policyAttachPromises = policies.map(
@@ -3239,8 +3236,8 @@ function isNotFoundException(e) {
3239
3236
  const code = 404;
3240
3237
  return e.status == code || e.statusCode == code || e.data && e.data.statusCode == code;
3241
3238
  }
3242
- async function getFilteredResources(path9, service, ids, paginate) {
3243
- const res = await service.get(path9);
3239
+ async function getFilteredResources(path19, service, ids, paginate) {
3240
+ const res = await service.get(path19);
3244
3241
  const resources = paginate ? res.data : res;
3245
3242
  return ids ? resources.filter((resource) => ids.includes(resource._id)) : resources;
3246
3243
  }
@@ -3431,6 +3428,1551 @@ function upgrade_default(program2) {
3431
3428
  }).action(upgrade);
3432
3429
  }
3433
3430
 
3431
+ // apps/cli/src/commands/sync/plan.ts
3432
+ import path15 from "path";
3433
+
3434
+ // apps/cli/src/commands/sync/planner.ts
3435
+ import { bold as bold4, cyan, green as green4, red as red4, yellow as yellow2 } from "colorette";
3436
+ import isEqual2 from "lodash/isEqual.js";
3437
+ import { createTwoFilesPatch } from "diff";
3438
+ import ora2 from "ora";
3439
+ async function buildPlan(modules, http2, rootDir, detailed = false, detectRenames = true) {
3440
+ const modulePlans = [];
3441
+ for (const mod of modules) {
3442
+ const [locals, remotes] = await Promise.all([
3443
+ spin({
3444
+ text: `Reading local ${mod.displayName} files`,
3445
+ op: () => mod.readLocal(rootDir)
3446
+ }),
3447
+ spin({
3448
+ text: `Fetching remote ${mod.displayName}`,
3449
+ op: () => mod.readRemote(http2)
3450
+ })
3451
+ ]);
3452
+ const localBySlug = new Map(locals.map((l) => [l.slug, l]));
3453
+ const remoteBySlug = new Map(remotes.map((r) => [r.slug, r]));
3454
+ const creates = [];
3455
+ const updates = [];
3456
+ const deletes = [];
3457
+ for (const local of locals) {
3458
+ const remote = remoteBySlug.get(local.slug);
3459
+ if (!remote) {
3460
+ creates.push({
3461
+ kind: "create" /* Create */,
3462
+ slug: local.slug,
3463
+ summary: mod.summaryLine(local),
3464
+ changedFields: [],
3465
+ diffs: {},
3466
+ local,
3467
+ remote: void 0
3468
+ });
3469
+ } else {
3470
+ const changedFields = mod.diffFields(local.data, remote.data);
3471
+ if (changedFields.length > 0) {
3472
+ updates.push({
3473
+ kind: "update" /* Update */,
3474
+ slug: local.slug,
3475
+ summary: mod.summaryLine(local),
3476
+ changedFields,
3477
+ diffs: detailed ? mod.renderDetail(local, remote) : {},
3478
+ local,
3479
+ remote
3480
+ });
3481
+ }
3482
+ }
3483
+ }
3484
+ for (const remote of remotes) {
3485
+ if (!localBySlug.has(remote.slug)) {
3486
+ deletes.push({
3487
+ kind: "delete" /* Delete */,
3488
+ slug: remote.slug,
3489
+ summary: mod.summaryLine(remote),
3490
+ changedFields: [],
3491
+ diffs: {},
3492
+ local: void 0,
3493
+ remote
3494
+ });
3495
+ }
3496
+ }
3497
+ if (detectRenames && mod.extractLocalId) {
3498
+ const deleteByRemoteId = new Map(deletes.map((e) => [e.remote.id, e]));
3499
+ const remainingCreates = [];
3500
+ const promotedRemoteIds = /* @__PURE__ */ new Set();
3501
+ for (const create2 of creates) {
3502
+ const localId = mod.extractLocalId(create2.local.data);
3503
+ const matchedDelete = localId ? deleteByRemoteId.get(localId) : void 0;
3504
+ if (matchedDelete) {
3505
+ promotedRemoteIds.add(matchedDelete.remote.id);
3506
+ const changedFields = mod.diffFields(create2.local.data, matchedDelete.remote.data);
3507
+ updates.push({
3508
+ kind: "update" /* Update */,
3509
+ slug: create2.slug,
3510
+ summary: mod.summaryLine(create2.local),
3511
+ changedFields,
3512
+ diffs: detailed ? mod.renderDetail(create2.local, matchedDelete.remote) : {},
3513
+ local: create2.local,
3514
+ remote: matchedDelete.remote
3515
+ });
3516
+ } else {
3517
+ remainingCreates.push(create2);
3518
+ }
3519
+ }
3520
+ creates.splice(0, creates.length, ...remainingCreates);
3521
+ deletes.splice(
3522
+ 0,
3523
+ deletes.length,
3524
+ ...deletes.filter((e) => !promotedRemoteIds.has(e.remote.id))
3525
+ );
3526
+ }
3527
+ modulePlans.push({ module: mod, creates, updates, deletes });
3528
+ }
3529
+ return { modules: modulePlans };
3530
+ }
3531
+ function renderPlan(plan2, opts = {}) {
3532
+ if (opts.json) {
3533
+ const output = plan2.modules.map((mp) => ({
3534
+ module: mp.module.name,
3535
+ creates: mp.creates.map((e) => ({ slug: e.slug, summary: e.summary })),
3536
+ updates: mp.updates.map((e) => ({
3537
+ slug: e.slug,
3538
+ summary: e.summary,
3539
+ changedFields: e.changedFields
3540
+ })),
3541
+ deletes: mp.deletes.map((e) => ({ slug: e.slug, summary: e.summary }))
3542
+ }));
3543
+ console.log(JSON.stringify(output, null, 2));
3544
+ return;
3545
+ }
3546
+ if (opts.fetchMode) {
3547
+ const toWrite = plan2.modules.reduce((n, m) => n + m.deletes.length, 0);
3548
+ const toUpdate = plan2.modules.reduce((n, m) => n + m.updates.length, 0);
3549
+ const toDelete = opts.clean ? plan2.modules.reduce((n, m) => n + m.creates.length, 0) : 0;
3550
+ const totalChanges2 = toWrite + toUpdate + toDelete;
3551
+ if (totalChanges2 === 0) {
3552
+ console.log(bold4(green4("\n\u2713 No changes detected. Local files already match remote.")));
3553
+ return;
3554
+ }
3555
+ for (const mp of plan2.modules) {
3556
+ const { module: mod, creates, updates, deletes } = mp;
3557
+ if (!creates.length && !updates.length && !deletes.length) continue;
3558
+ const staleCount = opts.clean ? creates.length : 0;
3559
+ console.log(
3560
+ `
3561
+ ${bold4(cyan(`\u2500\u2500 ${mod.displayName.toUpperCase()} \u2500\u2500`))} ${summaryBadges(deletes.length, updates.length, staleCount)}`
3562
+ );
3563
+ for (const e of deletes) {
3564
+ console.log(` ${green4("+")} ${bold4(e.slug)} ${dim(e.summary)}`);
3565
+ }
3566
+ for (const e of updates) {
3567
+ console.log(
3568
+ ` ${yellow2("~")} ${bold4(e.slug)} ${dim(e.summary)} ${yellow2(`[${e.changedFields.join(", ")}]`)}`
3569
+ );
3570
+ if (opts.detailed) {
3571
+ for (const [section, diff] of Object.entries(e.diffs)) {
3572
+ if (!diff) continue;
3573
+ console.log(` ${bold4(section)}:`);
3574
+ renderUnifiedDiff(diff);
3575
+ }
3576
+ }
3577
+ }
3578
+ if (opts.clean) {
3579
+ for (const e of creates) {
3580
+ console.log(` ${red4("-")} ${bold4(e.slug)} ${dim(e.summary)}`);
3581
+ }
3582
+ }
3583
+ }
3584
+ console.log(
3585
+ `
3586
+ ${bold4("Plan:")} ${green4(`+${toWrite} to write`)} ${yellow2(`~${toUpdate} to update`)} ${red4(`-${toDelete} to delete`)}`
3587
+ );
3588
+ if (!opts.detailed && toUpdate > 0) {
3589
+ console.log(` ${dim("Run with --detailed to see full diffs.")}`);
3590
+ }
3591
+ return;
3592
+ }
3593
+ const totalCreates = plan2.modules.reduce((n, m) => n + m.creates.length, 0);
3594
+ const totalUpdates = plan2.modules.reduce((n, m) => n + m.updates.length, 0);
3595
+ const totalDeletes = plan2.modules.reduce((n, m) => n + m.deletes.length, 0);
3596
+ const totalChanges = totalCreates + totalUpdates + totalDeletes;
3597
+ if (totalChanges === 0) {
3598
+ console.log(bold4(green4("\n\u2713 No changes detected. Local state matches remote.")));
3599
+ return;
3600
+ }
3601
+ for (const mp of plan2.modules) {
3602
+ const { module: mod, creates, updates, deletes } = mp;
3603
+ if (!creates.length && !updates.length && !deletes.length) continue;
3604
+ console.log(
3605
+ `
3606
+ ${bold4(cyan(`\u2500\u2500 ${mod.displayName.toUpperCase()} \u2500\u2500`))} ${summaryBadges(creates.length, updates.length, deletes.length)}`
3607
+ );
3608
+ for (const e of creates) {
3609
+ console.log(` ${green4("+")} ${bold4(e.slug)} ${dim(e.summary)}`);
3610
+ }
3611
+ for (const e of updates) {
3612
+ console.log(
3613
+ ` ${yellow2("~")} ${bold4(e.slug)} ${dim(e.summary)} ${yellow2(`[${e.changedFields.join(", ")}]`)}`
3614
+ );
3615
+ if (opts.detailed) {
3616
+ for (const [section, diff] of Object.entries(e.diffs)) {
3617
+ if (!diff) continue;
3618
+ console.log(` ${bold4(section)}:`);
3619
+ renderUnifiedDiff(diff);
3620
+ }
3621
+ }
3622
+ }
3623
+ for (const e of deletes) {
3624
+ console.log(` ${red4("-")} ${bold4(e.slug)} ${dim(e.summary)}`);
3625
+ }
3626
+ }
3627
+ console.log(
3628
+ `
3629
+ ${bold4("Plan:")} ${green4(`+${totalCreates} to create`)} ${yellow2(`~${totalUpdates} to update`)} ${red4(`-${totalDeletes} to delete`)}`
3630
+ );
3631
+ if (!opts.detailed && totalUpdates > 0) {
3632
+ console.log(` ${dim("Run with --detailed to see full diffs.")}`);
3633
+ }
3634
+ }
3635
+ function summaryBadges(c, u, d) {
3636
+ const parts = [];
3637
+ if (c) parts.push(green4(`+${c}`));
3638
+ if (u) parts.push(yellow2(`~${u}`));
3639
+ if (d) parts.push(red4(`-${d}`));
3640
+ return parts.join(" ");
3641
+ }
3642
+ function dim(s) {
3643
+ return `\x1B[2m${s}\x1B[0m`;
3644
+ }
3645
+ function renderUnifiedDiff(diff) {
3646
+ for (const line of diff.split("\n")) {
3647
+ if (line.startsWith("+")) {
3648
+ process.stdout.write(green4(" " + line) + "\n");
3649
+ } else if (line.startsWith("-")) {
3650
+ process.stdout.write(red4(" " + line) + "\n");
3651
+ } else {
3652
+ process.stdout.write(dim(" " + line) + "\n");
3653
+ }
3654
+ }
3655
+ }
3656
+ async function applyPlan(plan2, http2, opts = {}) {
3657
+ const concurrency = opts.concurrency ?? 10;
3658
+ const errors = [];
3659
+ const handleErr = (label, e) => {
3660
+ const msg = formatError(e);
3661
+ const full = `${label}: ${msg}`;
3662
+ if (opts.abortOnError) throw new Error(full);
3663
+ console.warn(bold4(yellow2(` \u26A0 ${full}`)));
3664
+ errors.push(full);
3665
+ };
3666
+ for (const mp of plan2.modules) {
3667
+ const { module: mod, creates, updates, deletes } = mp;
3668
+ if (deletes.length) {
3669
+ await runConcurrently(
3670
+ deletes.map((e) => ({ slug: e.slug, run: () => mod.delete(http2, e.remote.id) })),
3671
+ concurrency,
3672
+ `Deleting ${mod.displayName}`,
3673
+ handleErr
3674
+ );
3675
+ }
3676
+ if (updates.length) {
3677
+ await runConcurrently(
3678
+ updates.map((e) => ({ slug: e.slug, run: () => mod.update(http2, e.local, e.remote.id) })),
3679
+ concurrency,
3680
+ `Updating ${mod.displayName}`,
3681
+ handleErr
3682
+ );
3683
+ }
3684
+ if (creates.length) {
3685
+ await runConcurrently(
3686
+ creates.map((e) => ({ slug: e.slug, run: () => mod.create(http2, e.local) })),
3687
+ concurrency,
3688
+ `Creating ${mod.displayName}`,
3689
+ handleErr
3690
+ );
3691
+ }
3692
+ }
3693
+ return { errors };
3694
+ }
3695
+ async function fetchToDisk(plan2, http2, rootDir, opts = {}) {
3696
+ const concurrency = opts.concurrency ?? 10;
3697
+ const errors = [];
3698
+ let written = 0;
3699
+ let deleted = 0;
3700
+ const handleErr = (label, e) => {
3701
+ const msg = formatError(e);
3702
+ const full = `${label}: ${msg}`;
3703
+ if (opts.abortOnError) throw new Error(full);
3704
+ console.warn(bold4(yellow2(` \u26A0 ${full}`)));
3705
+ errors.push(full);
3706
+ };
3707
+ for (const mp of plan2.modules) {
3708
+ const { module: mod, updates, deletes, creates } = mp;
3709
+ const toWrite = [...deletes, ...updates];
3710
+ if (toWrite.length) {
3711
+ await runConcurrently(
3712
+ toWrite.map((e) => ({
3713
+ slug: e.slug,
3714
+ run: async () => {
3715
+ await mod.writeLocal(rootDir, e.remote);
3716
+ written++;
3717
+ }
3718
+ })),
3719
+ concurrency,
3720
+ `Writing ${mod.displayName}`,
3721
+ handleErr
3722
+ );
3723
+ }
3724
+ if (opts.clean && creates.length) {
3725
+ await runConcurrently(
3726
+ creates.map((e) => ({
3727
+ slug: e.slug,
3728
+ run: async () => {
3729
+ await mod.deleteLocal(rootDir, e.slug);
3730
+ deleted++;
3731
+ }
3732
+ })),
3733
+ concurrency,
3734
+ `Deleting ${mod.displayName}`,
3735
+ handleErr
3736
+ );
3737
+ }
3738
+ }
3739
+ return { written, deleted, errors };
3740
+ }
3741
+ function diffObjectFields(local, remote, ignoredFields) {
3742
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)]);
3743
+ const changed = [];
3744
+ for (const key of allKeys) {
3745
+ if (ignoredFields.includes(key)) continue;
3746
+ if (!isEqual2(local[key], remote[key])) {
3747
+ changed.push(key);
3748
+ }
3749
+ }
3750
+ return changed;
3751
+ }
3752
+ function buildUnifiedDiff(oldContent, newContent, filename) {
3753
+ return createTwoFilesPatch(`remote/${filename}`, `local/${filename}`, oldContent, newContent);
3754
+ }
3755
+ async function runConcurrently(tasks, concurrency, label, onError) {
3756
+ if (!tasks.length) return;
3757
+ const total = tasks.length;
3758
+ let done = 0;
3759
+ const spinner = ora2({ text: `${label} (0/${total})`, color: "yellow" }).start();
3760
+ try {
3761
+ const limit = Math.max(1, Math.min(total, concurrency));
3762
+ let batch = [];
3763
+ for (let i = 0; i < tasks.length; i++) {
3764
+ batch.push(tasks[i]);
3765
+ if (batch.length === limit || i === tasks.length - 1) {
3766
+ await Promise.all(
3767
+ batch.map(
3768
+ (task) => task.run().catch((e) => onError(`${label}: ${task.slug}`, e)).finally(() => {
3769
+ done++;
3770
+ spinner.text = `${label}: ${task.slug} (${done}/${total})`;
3771
+ })
3772
+ )
3773
+ );
3774
+ batch = [];
3775
+ }
3776
+ }
3777
+ spinner.succeed();
3778
+ } catch (e) {
3779
+ spinner.fail();
3780
+ throw e;
3781
+ }
3782
+ }
3783
+ function formatError(e) {
3784
+ if (e && typeof e === "object") {
3785
+ const err = e;
3786
+ return err.message ?? err.data?.message ?? JSON.stringify(e);
3787
+ }
3788
+ return String(e);
3789
+ }
3790
+
3791
+ // apps/cli/src/commands/sync/modules/bucket.ts
3792
+ import path10 from "path";
3793
+ import yaml2 from "yaml";
3794
+
3795
+ // apps/cli/src/commands/sync/fs-utils.ts
3796
+ import fs9 from "fs";
3797
+ import path9 from "path";
3798
+ import yaml from "yaml";
3799
+ function ensureDir(dir) {
3800
+ fs9.mkdirSync(dir, { recursive: true });
3801
+ }
3802
+ function listFolders(dir) {
3803
+ if (!fs9.existsSync(dir)) return [];
3804
+ return fs9.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
3805
+ }
3806
+ function readYaml(filePath) {
3807
+ if (!fs9.existsSync(filePath)) return null;
3808
+ return yaml.parse(fs9.readFileSync(filePath, "utf-8"));
3809
+ }
3810
+ function writeYaml(filePath, data) {
3811
+ ensureDir(path9.dirname(filePath));
3812
+ fs9.writeFileSync(filePath, yaml.stringify(data), "utf-8");
3813
+ }
3814
+ function readText(filePath) {
3815
+ if (!fs9.existsSync(filePath)) return null;
3816
+ return fs9.readFileSync(filePath, "utf-8");
3817
+ }
3818
+ function writeText(filePath, content) {
3819
+ ensureDir(path9.dirname(filePath));
3820
+ fs9.writeFileSync(filePath, content, "utf-8");
3821
+ }
3822
+ function removeDir(dir) {
3823
+ if (fs9.existsSync(dir)) {
3824
+ fs9.rmSync(dir, { recursive: true, force: true });
3825
+ }
3826
+ }
3827
+ function omit(obj, fields) {
3828
+ const clone = structuredClone(obj);
3829
+ for (const f of fields) delete clone[f];
3830
+ return clone;
3831
+ }
3832
+ function sanitizeSlug(slug) {
3833
+ return path9.basename(path9.normalize(slug));
3834
+ }
3835
+ function unwrapList(res) {
3836
+ if (Array.isArray(res)) return res;
3837
+ return res.data ?? [];
3838
+ }
3839
+
3840
+ // apps/cli/src/commands/sync/modules/bucket.ts
3841
+ var IGNORED_FIELDS = ["_id"];
3842
+ var bucketModule = {
3843
+ name: "bucket",
3844
+ displayName: "Bucket",
3845
+ identityField: "title",
3846
+ ignoredFields: IGNORED_FIELDS,
3847
+ async readLocal(rootDir) {
3848
+ const dir = path10.join(rootDir, "bucket");
3849
+ const slugs = listFolders(dir);
3850
+ const results = [];
3851
+ for (const slug of slugs) {
3852
+ const data = readYaml(path10.join(dir, slug, "schema.yaml"));
3853
+ if (data) results.push({ slug, data });
3854
+ }
3855
+ return results;
3856
+ },
3857
+ async readRemote(http2) {
3858
+ const res = await http2.get("bucket");
3859
+ const buckets = unwrapList(res);
3860
+ return buckets.map((b) => ({
3861
+ slug: sanitizeSlug(b.title),
3862
+ id: b._id,
3863
+ data: b
3864
+ }));
3865
+ },
3866
+ async create(http2, local) {
3867
+ await http2.post("bucket", local.data);
3868
+ },
3869
+ async update(http2, local, remoteId) {
3870
+ await http2.put(`bucket/${remoteId}`, local.data);
3871
+ },
3872
+ async delete(http2, remoteId) {
3873
+ await http2.delete(`bucket/${remoteId}`);
3874
+ },
3875
+ async writeLocal(rootDir, remote) {
3876
+ const dir = path10.join(rootDir, "bucket", remote.slug);
3877
+ writeYaml(path10.join(dir, "schema.yaml"), remote.data);
3878
+ },
3879
+ async deleteLocal(rootDir, slug) {
3880
+ removeDir(path10.join(rootDir, "bucket", slug));
3881
+ },
3882
+ diffFields(local, remote) {
3883
+ return diffObjectFields(
3884
+ local,
3885
+ remote,
3886
+ IGNORED_FIELDS
3887
+ );
3888
+ },
3889
+ renderDetail(local, remote) {
3890
+ const localYaml = yaml2.stringify(omit(local.data, IGNORED_FIELDS));
3891
+ const remoteYaml = yaml2.stringify(omit(remote.data, IGNORED_FIELDS));
3892
+ return {
3893
+ schema: buildUnifiedDiff(remoteYaml, localYaml, "schema.yaml")
3894
+ };
3895
+ },
3896
+ summaryLine(resource) {
3897
+ const propCount = Object.keys(resource.data.properties ?? {}).length;
3898
+ return `${propCount} properties`;
3899
+ },
3900
+ extractLocalId(data) {
3901
+ return data._id;
3902
+ }
3903
+ };
3904
+
3905
+ // apps/cli/src/commands/sync/modules/env-var.ts
3906
+ import path11 from "path";
3907
+ import yaml3 from "yaml";
3908
+ var IGNORED_FIELDS2 = ["_id"];
3909
+ var envVarModule = {
3910
+ name: "env-var",
3911
+ displayName: "Environment Variable",
3912
+ identityField: "key",
3913
+ ignoredFields: IGNORED_FIELDS2,
3914
+ async readLocal(rootDir) {
3915
+ const dir = path11.join(rootDir, "env-var");
3916
+ const slugs = listFolders(dir);
3917
+ const results = [];
3918
+ for (const slug of slugs) {
3919
+ const data = readYaml(path11.join(dir, slug, "schema.yaml"));
3920
+ if (data) results.push({ slug, data });
3921
+ }
3922
+ return results;
3923
+ },
3924
+ async readRemote(http2) {
3925
+ const res = await http2.get("env-var");
3926
+ const items = unwrapList(res);
3927
+ return items.map((e) => ({
3928
+ slug: sanitizeSlug(e.key),
3929
+ id: e._id,
3930
+ data: e
3931
+ }));
3932
+ },
3933
+ async create(http2, local) {
3934
+ await http2.post("env-var", local.data);
3935
+ },
3936
+ async update(http2, local, remoteId) {
3937
+ await http2.put(`env-var/${remoteId}`, local.data);
3938
+ },
3939
+ async delete(http2, remoteId) {
3940
+ await http2.delete(`env-var/${remoteId}`);
3941
+ },
3942
+ async writeLocal(rootDir, remote) {
3943
+ const dir = path11.join(rootDir, "env-var", remote.slug);
3944
+ writeYaml(path11.join(dir, "schema.yaml"), remote.data);
3945
+ },
3946
+ async deleteLocal(rootDir, slug) {
3947
+ removeDir(path11.join(rootDir, "env-var", slug));
3948
+ },
3949
+ diffFields(local, remote) {
3950
+ return diffObjectFields(
3951
+ local,
3952
+ remote,
3953
+ IGNORED_FIELDS2
3954
+ );
3955
+ },
3956
+ renderDetail(local, remote) {
3957
+ const localYaml = yaml3.stringify(omit(local.data, IGNORED_FIELDS2));
3958
+ const remoteYaml = yaml3.stringify(omit(remote.data, IGNORED_FIELDS2));
3959
+ return {
3960
+ schema: buildUnifiedDiff(remoteYaml, localYaml, "schema.yaml")
3961
+ };
3962
+ },
3963
+ summaryLine(resource) {
3964
+ return `key: ${resource.data.key}`;
3965
+ },
3966
+ extractLocalId(data) {
3967
+ return data._id;
3968
+ }
3969
+ };
3970
+
3971
+ // apps/cli/src/commands/sync/modules/function.ts
3972
+ import path12 from "path";
3973
+ import yaml4 from "yaml";
3974
+ import isEqual3 from "lodash/isEqual.js";
3975
+ import { bold as bold5, cyan as cyan2, green as green5, yellow as yellow3 } from "colorette";
3976
+ var SCHEMA_IGNORED = ["_id", "env_vars", "secrets"];
3977
+ function indexFilename(language) {
3978
+ return language === "typescript" ? "index.ts" : "index.mjs";
3979
+ }
3980
+ function extractId(v) {
3981
+ if (v && typeof v === "object" && "_id" in v) {
3982
+ return String(v._id);
3983
+ }
3984
+ return String(v);
3985
+ }
3986
+ function normalizeSchema(schema) {
3987
+ const normalized = { ...schema };
3988
+ if (Array.isArray(schema.env_vars)) {
3989
+ normalized.env_vars = schema.env_vars.map(extractId);
3990
+ }
3991
+ if (Array.isArray(schema.secrets)) {
3992
+ normalized.secrets = schema.secrets.map(extractId);
3993
+ }
3994
+ return normalized;
3995
+ }
3996
+ function isNotFoundError(error) {
3997
+ if (!error || typeof error !== "object") return false;
3998
+ const c = error;
3999
+ return c.status === 404 || c.statusCode === 404 || c.response?.status === 404 || c.response?.statusCode === 404;
4000
+ }
4001
+ var functionModule = {
4002
+ name: "function",
4003
+ displayName: "Function",
4004
+ identityField: "name",
4005
+ ignoredFields: SCHEMA_IGNORED,
4006
+ readSchema(rootDir, slug) {
4007
+ return readYaml(path12.join(rootDir, "function", slug, "schema.yaml"));
4008
+ },
4009
+ readIndex(rootDir, slug, language) {
4010
+ return readText(path12.join(rootDir, "function", slug, indexFilename(language))) ?? "";
4011
+ },
4012
+ readDependencies(rootDir, slug) {
4013
+ const pkgText = readText(path12.join(rootDir, "function", slug, "package.json"));
4014
+ if (!pkgText) return {};
4015
+ try {
4016
+ return JSON.parse(pkgText).dependencies ?? {};
4017
+ } catch {
4018
+ return {};
4019
+ }
4020
+ },
4021
+ async readLocal(rootDir) {
4022
+ const dir = path12.join(rootDir, "function");
4023
+ const slugs = listFolders(dir);
4024
+ const results = [];
4025
+ for (const slug of slugs) {
4026
+ const schema = this.readSchema(rootDir, slug);
4027
+ if (!schema) continue;
4028
+ const index = this.readIndex(rootDir, slug, schema.language);
4029
+ const dependencies = this.readDependencies(rootDir, slug);
4030
+ results.push({ slug, data: { schema, index, dependencies } });
4031
+ }
4032
+ return results;
4033
+ },
4034
+ async readRemote(http2) {
4035
+ const fns = await http2.get("function");
4036
+ return Promise.all(
4037
+ fns.map(async (fn) => {
4038
+ const id = fn._id;
4039
+ const [indexRes, depsRes] = await Promise.all([
4040
+ http2.get(`function/${id}/index`).catch(() => ({ index: "" })),
4041
+ http2.get(`function/${id}/dependencies`).catch(() => [])
4042
+ ]);
4043
+ const dependencies = {};
4044
+ for (const dep of depsRes) {
4045
+ dependencies[dep.name] = dep.version;
4046
+ }
4047
+ return {
4048
+ slug: sanitizeSlug(fn.name),
4049
+ id,
4050
+ data: {
4051
+ schema: normalizeSchema(fn),
4052
+ index: indexRes.index ?? "",
4053
+ dependencies
4054
+ }
4055
+ };
4056
+ })
4057
+ );
4058
+ },
4059
+ async create(http2, local) {
4060
+ const id = await this.createSchema(http2, local.data.schema);
4061
+ if (!id) return;
4062
+ await this.uploadIndex(http2, id, local.data.index);
4063
+ await this.uploadDependencies(http2, id, local.data.dependencies);
4064
+ },
4065
+ async createSchema(http2, schema) {
4066
+ const created = await http2.post(
4067
+ "function",
4068
+ omit(schema, ["env_vars", "secrets"])
4069
+ );
4070
+ const id = created._id ?? schema._id;
4071
+ if (!id) return void 0;
4072
+ const envVarIds = schema.env_vars ?? [];
4073
+ await Promise.all(envVarIds.map((evId) => http2.put(`function/${id}/env-var/${evId}`, {})));
4074
+ const secretIds = schema.secrets ?? [];
4075
+ await Promise.all(secretIds.map((sId) => http2.put(`function/${id}/secret/${sId}`, {})));
4076
+ return id;
4077
+ },
4078
+ async update(http2, local, remoteId) {
4079
+ await this.updateSchema(http2, remoteId, local.data.schema);
4080
+ await this.uploadIndex(http2, remoteId, local.data.index);
4081
+ await this.uploadDependencies(http2, remoteId, local.data.dependencies);
4082
+ },
4083
+ async updateSchema(http2, remoteId, schema) {
4084
+ await http2.put(`function/${remoteId}`, omit(schema, ["env_vars", "secrets"]));
4085
+ const localEnvVarIds = new Set(schema.env_vars ?? []);
4086
+ const currentFn = await http2.get(`function/${remoteId}`).then(normalizeSchema).catch(() => ({}));
4087
+ const remoteEnvVarIds = new Set(currentFn.env_vars ?? []);
4088
+ await Promise.all([
4089
+ ...[...localEnvVarIds].filter((id) => !remoteEnvVarIds.has(id)).map((id) => http2.put(`function/${remoteId}/env-var/${id}`, {})),
4090
+ ...[...remoteEnvVarIds].filter((id) => !localEnvVarIds.has(id)).map((id) => http2.delete(`function/${remoteId}/env-var/${id}`))
4091
+ ]);
4092
+ const localSecretIds = new Set(schema.secrets ?? []);
4093
+ const remoteSecretIds = new Set(currentFn.secrets ?? []);
4094
+ await Promise.all([
4095
+ ...[...localSecretIds].filter((id) => !remoteSecretIds.has(id)).map((id) => http2.put(`function/${remoteId}/secret/${id}`, {})),
4096
+ ...[...remoteSecretIds].filter((id) => !localSecretIds.has(id)).map((id) => http2.delete(`function/${remoteId}/secret/${id}`))
4097
+ ]);
4098
+ },
4099
+ async uploadIndex(http2, remoteId, index) {
4100
+ await http2.post(`function/${remoteId}/index`, { index });
4101
+ },
4102
+ async uploadDependencies(http2, remoteId, localDeps) {
4103
+ const currentDeps = await http2.get(`function/${remoteId}/dependencies`).catch(() => []);
4104
+ const currentByName = new Map(currentDeps.map((d) => [d.name, d.version]));
4105
+ const toDelete = currentDeps.filter((d) => !(d.name in localDeps));
4106
+ await Promise.all(
4107
+ toDelete.map(
4108
+ (d) => http2.delete(`function/${remoteId}/dependencies/${d.name}`).catch((error) => {
4109
+ if (isNotFoundError(error)) return;
4110
+ throw error;
4111
+ })
4112
+ )
4113
+ );
4114
+ const toAdd = Object.entries(localDeps).filter(([n, v]) => {
4115
+ const cur = currentByName.get(n);
4116
+ return !cur || cur !== v;
4117
+ }).map(([n, v]) => `${n}@${v}`);
4118
+ if (toAdd.length) {
4119
+ await http2.post(`function/${remoteId}/dependencies`, { name: toAdd });
4120
+ }
4121
+ },
4122
+ async delete(http2, remoteId) {
4123
+ await http2.delete(`function/${remoteId}`);
4124
+ },
4125
+ async writeLocal(rootDir, remote) {
4126
+ const fnDir = path12.join(rootDir, "function", remote.slug);
4127
+ ensureDir(fnDir);
4128
+ writeYaml(path12.join(fnDir, "schema.yaml"), remote.data.schema);
4129
+ const indexFile = indexFilename(remote.data.schema.language);
4130
+ writeText(path12.join(fnDir, indexFile), remote.data.index);
4131
+ const pkg = {
4132
+ name: remote.slug,
4133
+ version: "0.0.1",
4134
+ dependencies: remote.data.dependencies
4135
+ };
4136
+ writeText(path12.join(fnDir, "package.json"), JSON.stringify(pkg, null, 2));
4137
+ },
4138
+ async deleteLocal(rootDir, slug) {
4139
+ removeDir(path12.join(rootDir, "function", slug));
4140
+ },
4141
+ diffFields(local, remote) {
4142
+ const changed = [];
4143
+ const schemaChanged = diffObjectFields(
4144
+ local.schema,
4145
+ remote.schema,
4146
+ SCHEMA_IGNORED
4147
+ );
4148
+ if (schemaChanged.length) changed.push("schema");
4149
+ if (local.index !== remote.index) changed.push("index");
4150
+ if (!isEqual3(local.dependencies, remote.dependencies)) changed.push("dependencies");
4151
+ const localEnvVars = local.schema.env_vars ?? [];
4152
+ const remoteEnvVars = remote.schema.env_vars ?? [];
4153
+ if (!isEqual3(new Set(localEnvVars), new Set(remoteEnvVars))) changed.push("env_vars");
4154
+ const localSecrets = local.schema.secrets ?? [];
4155
+ const remoteSecrets = remote.schema.secrets ?? [];
4156
+ if (!isEqual3(new Set(localSecrets), new Set(remoteSecrets))) changed.push("secrets");
4157
+ return changed;
4158
+ },
4159
+ renderDetail(local, remote) {
4160
+ const result = {};
4161
+ const localSchemaYaml = yaml4.stringify(omit(local.data.schema, SCHEMA_IGNORED));
4162
+ const remoteSchemaYaml = yaml4.stringify(omit(remote.data.schema, SCHEMA_IGNORED));
4163
+ if (localSchemaYaml !== remoteSchemaYaml) {
4164
+ result["schema"] = buildUnifiedDiff(remoteSchemaYaml, localSchemaYaml, "schema.yaml");
4165
+ }
4166
+ if (local.data.index !== remote.data.index) {
4167
+ result["index"] = buildUnifiedDiff(
4168
+ remote.data.index,
4169
+ local.data.index,
4170
+ indexFilename(local.data.schema.language)
4171
+ );
4172
+ }
4173
+ const sortKeys = (obj) => Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
4174
+ const localDepsYaml = yaml4.stringify(sortKeys(local.data.dependencies));
4175
+ const remoteDepsYaml = yaml4.stringify(sortKeys(remote.data.dependencies));
4176
+ if (localDepsYaml !== remoteDepsYaml) {
4177
+ result["dependencies"] = buildUnifiedDiff(remoteDepsYaml, localDepsYaml, "package.json");
4178
+ }
4179
+ return result;
4180
+ },
4181
+ summaryLine(resource) {
4182
+ const triggerCount = Object.keys(resource.data.schema.triggers ?? {}).length;
4183
+ return `${triggerCount} trigger${triggerCount !== 1 ? "s" : ""}`;
4184
+ },
4185
+ extractLocalId(data) {
4186
+ return data.schema._id;
4187
+ },
4188
+ watchedFiles: ["schema.yaml", "index.ts", "index.mjs", "index.js", "package.json"],
4189
+ async devHandleEvent(ctx) {
4190
+ const self = this;
4191
+ const {
4192
+ type,
4193
+ slug,
4194
+ file,
4195
+ http: http2,
4196
+ rootDir,
4197
+ warn,
4198
+ spin: spin2,
4199
+ refreshState,
4200
+ getRemoteId,
4201
+ setRemoteId,
4202
+ clearRemoteId,
4203
+ schedulePendingDelete,
4204
+ consumePendingDeleteByRemoteId
4205
+ } = ctx;
4206
+ const isIndexFile = (f) => f === "index.ts" || f === "index.mjs" || f === "index.js";
4207
+ const isPackageFile = (f) => f === "package.json";
4208
+ function fnLabel(symbol, forSlug, sub) {
4209
+ const parts = [symbol, bold5(self.displayName), bold5(forSlug)];
4210
+ if (sub) parts.push(yellow3(`[${sub}]`));
4211
+ return parts.join(" ");
4212
+ }
4213
+ async function waitForRemoteId() {
4214
+ for (let attempt = 0; attempt < 10; attempt++) {
4215
+ const id = getRemoteId(slug);
4216
+ if (id) return id;
4217
+ await ctx.sleep(200);
4218
+ }
4219
+ return getRemoteId(slug);
4220
+ }
4221
+ async function onSchemaAdd() {
4222
+ const schema = self.readSchema(rootDir, slug);
4223
+ if (!schema) return;
4224
+ const newLocalId = schema._id;
4225
+ if (newLocalId) {
4226
+ const pending = consumePendingDeleteByRemoteId(newLocalId);
4227
+ if (pending) {
4228
+ clearRemoteId(pending.slug);
4229
+ setRemoteId(slug, pending.remoteId);
4230
+ const renameLabel = `${yellow3("~")} ${bold5(self.displayName)} ${bold5(pending.slug)} ${cyan2("\u2192")} ${bold5(slug)}`;
4231
+ await spin2(renameLabel, "updated (rename)", () => self.updateSchema(http2, pending.remoteId, schema));
4232
+ return;
4233
+ }
4234
+ }
4235
+ const remoteId = getRemoteId(slug);
4236
+ if (remoteId) {
4237
+ await spin2(fnLabel(yellow3("~"), slug, "schema"), "updated", () => self.updateSchema(http2, remoteId, schema));
4238
+ } else {
4239
+ await spin2(fnLabel(green5("+"), slug), "created", async () => {
4240
+ const newRemoteId = await self.createSchema(http2, schema);
4241
+ if (!newRemoteId) return;
4242
+ await refreshState();
4243
+ });
4244
+ }
4245
+ }
4246
+ const isSchema = file === "schema.yaml";
4247
+ if (type === "add" && isSchema) {
4248
+ await onSchemaAdd();
4249
+ } else if (type === "change" && isSchema) {
4250
+ const id = getRemoteId(slug);
4251
+ if (id) {
4252
+ const schema = self.readSchema(rootDir, slug);
4253
+ if (schema) {
4254
+ await spin2(
4255
+ fnLabel(yellow3("~"), slug, "schema"),
4256
+ "updated",
4257
+ () => self.updateSchema(http2, id, schema)
4258
+ );
4259
+ }
4260
+ }
4261
+ } else if (type !== "unlink" && isIndexFile(file)) {
4262
+ const id = getRemoteId(slug) ?? (type === "add" ? await waitForRemoteId() : void 0);
4263
+ if (id) {
4264
+ const schema = self.readSchema(rootDir, slug);
4265
+ const index = self.readIndex(rootDir, slug, schema?.language);
4266
+ await spin2(fnLabel(yellow3("~"), slug, "index"), "updated", () => self.uploadIndex(http2, id, index));
4267
+ }
4268
+ } else if (type !== "unlink" && isPackageFile(file)) {
4269
+ const id = getRemoteId(slug) ?? (type === "add" ? await waitForRemoteId() : void 0);
4270
+ if (id) {
4271
+ const deps = self.readDependencies(rootDir, slug);
4272
+ await spin2(fnLabel(yellow3("~"), slug, "deps"), "updated", () => self.uploadDependencies(http2, id, deps));
4273
+ }
4274
+ } else if (type === "unlink" && isSchema) {
4275
+ const id = getRemoteId(slug);
4276
+ if (id) schedulePendingDelete(slug, id);
4277
+ } else if (type === "unlink" && (isIndexFile(file) || isPackageFile(file))) {
4278
+ }
4279
+ }
4280
+ };
4281
+
4282
+ // apps/cli/src/commands/sync/modules/policy.ts
4283
+ import path13 from "path";
4284
+ import yaml5 from "yaml";
4285
+ var IGNORED_FIELDS3 = ["_id", "system"];
4286
+ var policyModule = {
4287
+ name: "policy",
4288
+ displayName: "Policy",
4289
+ identityField: "name",
4290
+ ignoredFields: IGNORED_FIELDS3,
4291
+ async readLocal(rootDir) {
4292
+ const dir = path13.join(rootDir, "policy");
4293
+ const slugs = listFolders(dir);
4294
+ const results = [];
4295
+ for (const slug of slugs) {
4296
+ const data = readYaml(path13.join(dir, slug, "schema.yaml"));
4297
+ if (data) results.push({ slug, data });
4298
+ }
4299
+ return results;
4300
+ },
4301
+ async readRemote(http2) {
4302
+ const res = await http2.get("passport/policy");
4303
+ const items = Array.isArray(res) ? res : res.data ?? [];
4304
+ return items.filter((p) => !p.system).map((p) => ({
4305
+ slug: sanitizeSlug(p.name),
4306
+ id: p._id,
4307
+ data: p
4308
+ }));
4309
+ },
4310
+ async create(http2, local) {
4311
+ const body = omit(local.data, ["system"]);
4312
+ await http2.post("passport/policy", body);
4313
+ },
4314
+ async update(http2, local, remoteId) {
4315
+ const body = omit(local.data, ["system"]);
4316
+ await http2.put(`passport/policy/${remoteId}`, body);
4317
+ },
4318
+ async delete(http2, remoteId) {
4319
+ await http2.delete(`passport/policy/${remoteId}`);
4320
+ },
4321
+ async writeLocal(rootDir, remote) {
4322
+ const dir = path13.join(rootDir, "policy", remote.slug);
4323
+ writeYaml(path13.join(dir, "schema.yaml"), remote.data);
4324
+ },
4325
+ async deleteLocal(rootDir, slug) {
4326
+ removeDir(path13.join(rootDir, "policy", slug));
4327
+ },
4328
+ diffFields(local, remote) {
4329
+ return diffObjectFields(
4330
+ local,
4331
+ remote,
4332
+ IGNORED_FIELDS3
4333
+ );
4334
+ },
4335
+ renderDetail(local, remote) {
4336
+ const localYaml = yaml5.stringify(omit(local.data, IGNORED_FIELDS3));
4337
+ const remoteYaml = yaml5.stringify(omit(remote.data, IGNORED_FIELDS3));
4338
+ return {
4339
+ schema: buildUnifiedDiff(remoteYaml, localYaml, "schema.yaml")
4340
+ };
4341
+ },
4342
+ summaryLine(resource) {
4343
+ const stmts = resource.data.statement?.length ?? 0;
4344
+ return `${stmts} statement${stmts !== 1 ? "s" : ""}`;
4345
+ },
4346
+ extractLocalId(data) {
4347
+ return data._id;
4348
+ }
4349
+ };
4350
+
4351
+ // apps/cli/src/commands/sync/modules/secret.ts
4352
+ import path14 from "path";
4353
+ import yaml6 from "yaml";
4354
+ var IGNORED_FIELDS4 = ["_id", "value"];
4355
+ var secretModule = {
4356
+ name: "secret",
4357
+ displayName: "Secret",
4358
+ identityField: "key",
4359
+ ignoredFields: IGNORED_FIELDS4,
4360
+ async readLocal(rootDir) {
4361
+ const dir = path14.join(rootDir, "secret");
4362
+ const slugs = listFolders(dir);
4363
+ const results = [];
4364
+ for (const slug of slugs) {
4365
+ const data = readYaml(path14.join(dir, slug, "schema.yaml"));
4366
+ if (data) results.push({ slug, data });
4367
+ }
4368
+ return results;
4369
+ },
4370
+ async readRemote(http2) {
4371
+ const res = await http2.get("secret");
4372
+ const items = unwrapList(res);
4373
+ return items.map((s) => ({
4374
+ slug: sanitizeSlug(s.key),
4375
+ id: s._id,
4376
+ data: s
4377
+ }));
4378
+ },
4379
+ async create(http2, local) {
4380
+ await http2.post("secret", local.data);
4381
+ },
4382
+ async update(http2, local, remoteId) {
4383
+ await http2.put(`secret/${remoteId}`, local.data);
4384
+ },
4385
+ async delete(http2, remoteId) {
4386
+ await http2.delete(`secret/${remoteId}`);
4387
+ },
4388
+ async writeLocal(rootDir, remote) {
4389
+ const dir = path14.join(rootDir, "secret", remote.slug);
4390
+ writeYaml(path14.join(dir, "schema.yaml"), remote.data);
4391
+ },
4392
+ async deleteLocal(rootDir, slug) {
4393
+ removeDir(path14.join(rootDir, "secret", slug));
4394
+ },
4395
+ diffFields(local, remote) {
4396
+ return diffObjectFields(
4397
+ local,
4398
+ remote,
4399
+ IGNORED_FIELDS4
4400
+ );
4401
+ },
4402
+ renderDetail(local, remote) {
4403
+ const localYaml = yaml6.stringify(omit(local.data, IGNORED_FIELDS4));
4404
+ const remoteYaml = yaml6.stringify(omit(remote.data, IGNORED_FIELDS4));
4405
+ return {
4406
+ schema: buildUnifiedDiff(remoteYaml, localYaml, "schema.yaml")
4407
+ };
4408
+ },
4409
+ summaryLine(resource) {
4410
+ return `key: ${resource.data.key}`;
4411
+ },
4412
+ extractLocalId(data) {
4413
+ return data._id;
4414
+ }
4415
+ };
4416
+
4417
+ // apps/cli/src/commands/sync/modules/index.ts
4418
+ var ALL_MODULES = [
4419
+ policyModule,
4420
+ bucketModule,
4421
+ envVarModule,
4422
+ secretModule,
4423
+ functionModule
4424
+ ];
4425
+ var MODULE_NAMES = ALL_MODULES.map((m) => m.name);
4426
+ function resolveModules(names) {
4427
+ if (!names || names.length === 0) return ALL_MODULES;
4428
+ return [...new Set(names)].map((name) => {
4429
+ const mod = ALL_MODULES.find((m) => m.name === name);
4430
+ if (!mod) throw new Error(`Unknown module: "${name}". Available: ${MODULE_NAMES.join(", ")}`);
4431
+ return mod;
4432
+ });
4433
+ }
4434
+
4435
+ // apps/cli/src/commands/sync/plan.ts
4436
+ async function plan({ args, options }) {
4437
+ try {
4438
+ const rootDir = path15.resolve(args.dir ?? process.cwd());
4439
+ const detailed = !!options.detailed;
4440
+ const json = !!options.json;
4441
+ const moduleFilter = options.module ? (Array.isArray(options.module) ? options.module : [options.module]).map(String) : void 0;
4442
+ const modules = resolveModules(moduleFilter);
4443
+ const http2 = await httpService.createFromCurrentCtx();
4444
+ const p = await buildPlan(modules, http2, rootDir, detailed);
4445
+ renderPlan(p, { detailed, json });
4446
+ process.exitCode = 0;
4447
+ } catch (err) {
4448
+ const msg = err instanceof Error ? err.message : String(err);
4449
+ console.error(msg);
4450
+ process.exitCode = 1;
4451
+ }
4452
+ }
4453
+ function plan_default(program2) {
4454
+ return program2.command(
4455
+ "plan",
4456
+ "Compare local project files with remote Spica resources and show planned changes."
4457
+ ).argument("[dir]", "Project directory (default: current working directory)").option(
4458
+ "--detailed",
4459
+ "Show full unified diffs for changed resources instead of just field names.",
4460
+ { default: false }
4461
+ ).option("--json", "Output the plan as JSON (machine-readable).", { default: false }).option(
4462
+ "--module <name>",
4463
+ `Filter to specific module(s). Available: ${MODULE_NAMES.join(", ")}.`,
4464
+ {
4465
+ validator: MODULE_NAMES
4466
+ }
4467
+ ).action(plan);
4468
+ }
4469
+
4470
+ // apps/cli/src/commands/sync/apply.ts
4471
+ import path16 from "path";
4472
+ import caporalCore4 from "@caporal/core";
4473
+ import { bold as bold6, green as green6, red as red6, yellow as yellow4 } from "colorette";
4474
+
4475
+ // apps/cli/src/commands/sync/prompt.ts
4476
+ import readline from "readline";
4477
+ async function confirm(question) {
4478
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
4479
+ return new Promise((resolve) => {
4480
+ rl.question(`${question} [y/N] `, (answer) => {
4481
+ rl.close();
4482
+ resolve(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
4483
+ });
4484
+ });
4485
+ }
4486
+
4487
+ // apps/cli/src/commands/sync/apply.ts
4488
+ var { CaporalValidator: CaporalValidator4 } = caporalCore4;
4489
+ async function apply2({ args, options }) {
4490
+ const rootDir = path16.resolve(args.dir ?? process.cwd());
4491
+ const autoApprove = !!options.autoApprove;
4492
+ const concurrency = options.concurrency ?? 10;
4493
+ const abortOnError = !!options.abortOnError;
4494
+ const detailed = !!options.detailed;
4495
+ const moduleFilter = options.module ? (Array.isArray(options.module) ? options.module : [options.module]).map(String) : void 0;
4496
+ const modules = resolveModules(moduleFilter);
4497
+ const http2 = await httpService.createFromCurrentCtx();
4498
+ console.log(bold6("\nBuilding plan\u2026"));
4499
+ const p = await buildPlan(modules, http2, rootDir, detailed);
4500
+ const totalChanges = p.modules.reduce(
4501
+ (n, m) => n + m.creates.length + m.updates.length + m.deletes.length,
4502
+ 0
4503
+ );
4504
+ renderPlan(p, { detailed });
4505
+ if (totalChanges === 0) {
4506
+ process.exitCode = 0;
4507
+ return;
4508
+ }
4509
+ if (!autoApprove) {
4510
+ const ok = await confirm("\nApply these changes?");
4511
+ if (!ok) {
4512
+ console.log(bold6(yellow4("Aborted. No changes were applied.")));
4513
+ process.exitCode = 1;
4514
+ return;
4515
+ }
4516
+ }
4517
+ console.log(bold6("\nApplying changes\u2026"));
4518
+ try {
4519
+ const { errors } = await applyPlan(p, http2, { concurrency, abortOnError });
4520
+ if (errors.length) {
4521
+ console.log(bold6(yellow4(`
4522
+ \u26A0 Completed with ${errors.length} error(s):`)));
4523
+ for (const e of errors) console.log(` ${red6("\u2717")} ${e}`);
4524
+ process.exitCode = 1;
4525
+ } else {
4526
+ const c = p.modules.reduce((n, m) => n + m.creates.length, 0);
4527
+ const u = p.modules.reduce((n, m) => n + m.updates.length, 0);
4528
+ const d = p.modules.reduce((n, m) => n + m.deletes.length, 0);
4529
+ console.log(
4530
+ bold6(green6(`
4531
+ \u2713 Apply completed.`)) + ` ${green6(`+${c} created`)} ${yellow4(`~${u} updated`)} ${red6(`-${d} deleted`)}`
4532
+ );
4533
+ process.exitCode = 0;
4534
+ }
4535
+ } catch (err) {
4536
+ const msg = err instanceof Error ? err.message : String(err);
4537
+ console.log(`
4538
+ ${bold6(red6(`\u2717 ${msg}`))}`);
4539
+ process.exitCode = 1;
4540
+ }
4541
+ }
4542
+ function apply_default2(program2) {
4543
+ return program2.command(
4544
+ "apply",
4545
+ "Detect changes between local project files and remote Spica resources and apply them."
4546
+ ).argument("[dir]", "Project directory (default: current working directory)").option("--auto-approve, -y", "Skip confirmation prompt and apply immediately.", {
4547
+ default: false
4548
+ }).option("--concurrency <n>", "Maximum parallel API requests.", {
4549
+ default: 5,
4550
+ validator: CaporalValidator4.NUMBER
4551
+ }).option("--abort-on-error", "Stop immediately if any operation fails.", { default: false }).option("--detailed", "Show full unified diffs in the plan before applying.", { default: false }).option(
4552
+ "--module <name>",
4553
+ `Filter to specific module(s). Available: ${MODULE_NAMES.join(", ")}.`,
4554
+ {
4555
+ validator: MODULE_NAMES
4556
+ }
4557
+ ).action(apply2);
4558
+ }
4559
+
4560
+ // apps/cli/src/commands/sync/fetch.ts
4561
+ import path17 from "path";
4562
+ import caporalCore5 from "@caporal/core";
4563
+ import { bold as bold7, green as green7, red as red7, yellow as yellow5 } from "colorette";
4564
+ var { CaporalValidator: CaporalValidator5 } = caporalCore5;
4565
+ async function fetch_({ args, options }) {
4566
+ const rootDir = path17.resolve(args.dir ?? process.cwd());
4567
+ const autoApprove = !!options.autoApprove;
4568
+ const concurrency = options.concurrency ?? 10;
4569
+ const abortOnError = !!options.abortOnError;
4570
+ const detailed = !!options.detailed;
4571
+ const clean = !!options.clean;
4572
+ const moduleFilter = options.module ? (Array.isArray(options.module) ? options.module : [options.module]).map(String) : void 0;
4573
+ const modules = resolveModules(moduleFilter);
4574
+ const http2 = await httpService.createFromCurrentCtx();
4575
+ console.log(bold7("\nBuilding plan\u2026"));
4576
+ const p = await buildPlan(modules, http2, rootDir, detailed, false);
4577
+ const toWrite = p.modules.reduce((n, m) => n + m.deletes.length + m.updates.length, 0);
4578
+ const toDelete = p.modules.reduce((n, m) => n + m.creates.length, 0);
4579
+ const effectiveChanges = toWrite + (clean ? toDelete : 0);
4580
+ renderPlan(p, { detailed, fetchMode: true, clean });
4581
+ if (effectiveChanges === 0) {
4582
+ process.exitCode = 0;
4583
+ return;
4584
+ }
4585
+ if (!autoApprove) {
4586
+ const ok = await confirm("\nApply these changes?");
4587
+ if (!ok) {
4588
+ console.log(bold7(yellow5("Aborted. No changes were applied.")));
4589
+ process.exitCode = 1;
4590
+ return;
4591
+ }
4592
+ }
4593
+ console.log(bold7("\nWriting files\u2026"));
4594
+ try {
4595
+ const { written, deleted, errors } = await fetchToDisk(p, http2, rootDir, {
4596
+ concurrency,
4597
+ abortOnError,
4598
+ clean
4599
+ });
4600
+ if (errors.length) {
4601
+ console.log(bold7(yellow5(`
4602
+ \u26A0 Completed with ${errors.length} error(s):`)));
4603
+ for (const e of errors) console.log(` ${red7("\u2717")} ${e}`);
4604
+ process.exitCode = 1;
4605
+ } else {
4606
+ console.log(
4607
+ bold7(green7(`
4608
+ \u2713 Fetch complete.`)) + ` ${green7(`+${written} written`)}` + (deleted ? ` ${red7(`-${deleted} deleted`)}` : "")
4609
+ );
4610
+ process.exitCode = 0;
4611
+ }
4612
+ } catch (err) {
4613
+ const msg = err instanceof Error ? err.message : String(err);
4614
+ console.log(`
4615
+ ${bold7(red7(`\u2717 ${msg}`))}`);
4616
+ process.exitCode = 1;
4617
+ }
4618
+ }
4619
+ function fetch_default(program2) {
4620
+ return program2.command("fetch", "Export remote Spica resources into local project files.").argument("[dir]", "Project directory (default: current working directory)").option("--auto-approve, -y", "Skip confirmation prompt and write immediately.", {
4621
+ default: false
4622
+ }).option("--concurrency <n>", "Maximum parallel file writes.", {
4623
+ default: 10,
4624
+ validator: CaporalValidator5.NUMBER
4625
+ }).option("--abort-on-error", "Stop immediately if any operation fails.", { default: false }).option("--detailed", "Show full unified diffs in the plan before writing.", { default: false }).option("--clean", "Remove local resource folders that no longer exist remotely.", {
4626
+ default: false
4627
+ }).option(
4628
+ "--module <name>",
4629
+ `Filter to specific module(s). Available: ${MODULE_NAMES.join(", ")}.`,
4630
+ {
4631
+ validator: MODULE_NAMES
4632
+ }
4633
+ ).action(fetch_);
4634
+ }
4635
+
4636
+ // apps/cli/src/commands/sync/dev.ts
4637
+ import path18 from "path";
4638
+ import chokidar from "chokidar";
4639
+ import { bold as bold8, cyan as cyan3, green as green8, red as red8, yellow as yellow6 } from "colorette";
4640
+ import ora3 from "ora";
4641
+ function createEmptyState() {
4642
+ return { remoteIds: /* @__PURE__ */ new Map() };
4643
+ }
4644
+ async function refreshStateForModule(mod, http2, state, rootDir) {
4645
+ try {
4646
+ const [locals, remotes] = await Promise.all([mod.readLocal(rootDir), mod.readRemote(http2)]);
4647
+ const map = /* @__PURE__ */ new Map();
4648
+ const remoteBySlug = new Map(remotes.map((r) => [r.slug, r]));
4649
+ for (const local of locals) {
4650
+ const bySlug = remoteBySlug.get(local.slug);
4651
+ if (bySlug) {
4652
+ map.set(local.slug, bySlug.id);
4653
+ continue;
4654
+ }
4655
+ const localIdentity = local.data[mod.identityField];
4656
+ const matched = remotes.find(
4657
+ (r) => r.data[mod.identityField] === localIdentity
4658
+ );
4659
+ if (matched) map.set(local.slug, matched.id);
4660
+ }
4661
+ state.remoteIds.set(mod.name, map);
4662
+ } catch {
4663
+ }
4664
+ }
4665
+ function buildWatchIgnored(modules, rootDir) {
4666
+ const watchedByModule = new Map(
4667
+ modules.map((m) => [m.name, new Set(m.watchedFiles ?? ["schema.yaml"])])
4668
+ );
4669
+ return (filePath, stats) => {
4670
+ const rel = path18.relative(rootDir, filePath);
4671
+ const parts = rel.split(path18.sep);
4672
+ if (stats?.isDirectory()) {
4673
+ return parts.length >= 3;
4674
+ }
4675
+ if (!stats) return false;
4676
+ if (parts.length !== 3) return true;
4677
+ const [moduleName, , file] = parts;
4678
+ const watched = watchedByModule.get(moduleName);
4679
+ if (!watched) return true;
4680
+ return !watched.has(file);
4681
+ };
4682
+ }
4683
+ function readLocalSchema(mod, rootDir, slug) {
4684
+ const schemaPath = path18.join(rootDir, mod.name, slug, "schema.yaml");
4685
+ const data = readYaml(schemaPath);
4686
+ if (!data) return null;
4687
+ return { slug, data };
4688
+ }
4689
+ function createDevDispatcher(opts) {
4690
+ const { modules, http: http2, rootDir, state, renameWindowMs = 500 } = opts;
4691
+ const log = opts.logger ?? ((m) => console.log(m));
4692
+ const warn = opts.warnLogger ?? ((m) => console.warn(m));
4693
+ const moduleMap = new Map(modules.map((m) => [m.name, m]));
4694
+ const pendingDeletes = /* @__PURE__ */ new Map();
4695
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4696
+ function parseFilePath(absolutePath) {
4697
+ const rel = path18.relative(rootDir, absolutePath);
4698
+ const parts = rel.split(path18.sep);
4699
+ if (parts.length < 3) return null;
4700
+ const [moduleName, slug, ...rest] = parts;
4701
+ return { moduleName, slug, file: rest.join(path18.sep) };
4702
+ }
4703
+ function getRemoteId(moduleName, slug) {
4704
+ return state.remoteIds.get(moduleName)?.get(slug);
4705
+ }
4706
+ function setRemoteId(moduleName, slug, id) {
4707
+ if (!state.remoteIds.has(moduleName)) state.remoteIds.set(moduleName, /* @__PURE__ */ new Map());
4708
+ state.remoteIds.get(moduleName).set(slug, id);
4709
+ }
4710
+ function clearRemoteId(moduleName, slug) {
4711
+ state.remoteIds.get(moduleName)?.delete(slug);
4712
+ }
4713
+ async function spinOp(label, successText, op) {
4714
+ const spinner = ora3({ text: `${label} Applying\u2026`, color: "yellow" }).start();
4715
+ try {
4716
+ await op();
4717
+ spinner.succeed(`${label} ${successText}`);
4718
+ } catch (err) {
4719
+ spinner.fail(`${label} failed: ${formatError2(err)}`);
4720
+ }
4721
+ }
4722
+ async function handleSchemaAdd(mod, slug) {
4723
+ const local = readLocalSchema(mod, rootDir, slug);
4724
+ if (!local) return;
4725
+ const newLocalId = mod.extractLocalId?.(local.data);
4726
+ let promotedKey;
4727
+ if (newLocalId) {
4728
+ for (const [key, pending] of pendingDeletes) {
4729
+ if (pending.moduleName === mod.name && pending.remoteId === newLocalId) {
4730
+ promotedKey = key;
4731
+ break;
4732
+ }
4733
+ }
4734
+ }
4735
+ if (promotedKey) {
4736
+ const pending = pendingDeletes.get(promotedKey);
4737
+ clearTimeout(pending.timer);
4738
+ pendingDeletes.delete(promotedKey);
4739
+ clearRemoteId(mod.name, pending.slug);
4740
+ setRemoteId(mod.name, slug, pending.remoteId);
4741
+ const renameLabel = `${yellow6("~")} ${bold8(mod.displayName)} ${bold8(pending.slug)} ${cyan3("\u2192")} ${bold8(slug)}`;
4742
+ await spinOp(renameLabel, "updated (rename)", () => mod.update(http2, local, pending.remoteId));
4743
+ return;
4744
+ }
4745
+ const remoteId = getRemoteId(mod.name, slug);
4746
+ if (remoteId) {
4747
+ await spinOp(
4748
+ `${yellow6("~")} ${bold8(mod.displayName)} ${bold8(slug)}`,
4749
+ "updated",
4750
+ () => mod.update(http2, local, remoteId)
4751
+ );
4752
+ } else {
4753
+ await spinOp(
4754
+ `${green8("+")} ${bold8(mod.displayName)} ${bold8(slug)}`,
4755
+ "created",
4756
+ async () => {
4757
+ await mod.create(http2, local);
4758
+ await refreshStateForModule(mod, http2, state, rootDir);
4759
+ }
4760
+ );
4761
+ }
4762
+ }
4763
+ async function handleSchemaChange(mod, slug) {
4764
+ const local = readLocalSchema(mod, rootDir, slug);
4765
+ if (!local) return;
4766
+ const remoteId = getRemoteId(mod.name, slug);
4767
+ if (!remoteId) return handleSchemaAdd(mod, slug);
4768
+ await spinOp(
4769
+ `${yellow6("~")} ${bold8(mod.displayName)} ${bold8(slug)}`,
4770
+ "updated",
4771
+ () => mod.update(http2, local, remoteId)
4772
+ );
4773
+ }
4774
+ async function handleSchemaUnlink(mod, slug) {
4775
+ const remoteId = getRemoteId(mod.name, slug);
4776
+ if (!remoteId) return;
4777
+ const pendingKey = `${mod.name}:${slug}`;
4778
+ if (pendingDeletes.has(pendingKey)) return;
4779
+ const timer = setTimeout(async () => {
4780
+ pendingDeletes.delete(pendingKey);
4781
+ clearRemoteId(mod.name, slug);
4782
+ await spinOp(
4783
+ `${red8("-")} ${bold8(mod.displayName)} ${bold8(slug)}`,
4784
+ "deleted",
4785
+ () => mod.delete(http2, remoteId)
4786
+ );
4787
+ }, renameWindowMs);
4788
+ pendingDeletes.set(pendingKey, { timer, moduleName: mod.name, slug, remoteId });
4789
+ }
4790
+ function makeContext(mod, type, slug, file) {
4791
+ return {
4792
+ type,
4793
+ slug,
4794
+ file,
4795
+ http: http2,
4796
+ rootDir,
4797
+ getRemoteId: (s) => getRemoteId(mod.name, s),
4798
+ setRemoteId: (s, id) => setRemoteId(mod.name, s, id),
4799
+ clearRemoteId: (s) => clearRemoteId(mod.name, s),
4800
+ schedulePendingDelete(s, remoteId) {
4801
+ const pendingKey = `${mod.name}:${s}`;
4802
+ if (pendingDeletes.has(pendingKey)) return;
4803
+ const timer = setTimeout(async () => {
4804
+ pendingDeletes.delete(pendingKey);
4805
+ clearRemoteId(mod.name, s);
4806
+ await spinOp(
4807
+ `${red8("-")} ${bold8(mod.displayName)} ${bold8(s)}`,
4808
+ "deleted",
4809
+ () => mod.delete(http2, remoteId)
4810
+ );
4811
+ }, renameWindowMs);
4812
+ pendingDeletes.set(pendingKey, { timer, moduleName: mod.name, slug: s, remoteId });
4813
+ },
4814
+ consumePendingDeleteByRemoteId(remoteId) {
4815
+ for (const [key, pending] of pendingDeletes) {
4816
+ if (pending.moduleName === mod.name && pending.remoteId === remoteId) {
4817
+ clearTimeout(pending.timer);
4818
+ pendingDeletes.delete(key);
4819
+ return { slug: pending.slug, remoteId: pending.remoteId };
4820
+ }
4821
+ }
4822
+ return void 0;
4823
+ },
4824
+ sleep,
4825
+ refreshState: () => refreshStateForModule(mod, http2, state, rootDir),
4826
+ log,
4827
+ warn,
4828
+ spin: (label, successText, op) => spinOp(label, successText, op)
4829
+ };
4830
+ }
4831
+ async function handleEvent(type, absolutePath) {
4832
+ const parsed = parseFilePath(absolutePath);
4833
+ if (!parsed) return;
4834
+ const { moduleName, slug, file } = parsed;
4835
+ const mod = moduleMap.get(moduleName);
4836
+ if (!mod) return;
4837
+ if (mod.devHandleEvent) {
4838
+ await mod.devHandleEvent(makeContext(mod, type, slug, file));
4839
+ } else {
4840
+ if (file !== "schema.yaml") return;
4841
+ if (type === "add") {
4842
+ await handleSchemaAdd(mod, slug);
4843
+ } else if (type === "change") {
4844
+ await handleSchemaChange(mod, slug);
4845
+ } else if (type === "unlink") {
4846
+ await handleSchemaUnlink(mod, slug);
4847
+ }
4848
+ }
4849
+ }
4850
+ function dispose() {
4851
+ for (const pending of pendingDeletes.values()) {
4852
+ clearTimeout(pending.timer);
4853
+ }
4854
+ pendingDeletes.clear();
4855
+ }
4856
+ return { handleEvent, dispose };
4857
+ }
4858
+ function formatError2(e) {
4859
+ if (e instanceof Error) return e.message;
4860
+ if (e && typeof e === "object" && "message" in e) return String(e.message);
4861
+ return String(e);
4862
+ }
4863
+ async function dev({ args, options }) {
4864
+ const rootDir = path18.resolve(args.dir ?? process.cwd());
4865
+ const moduleFilter = options.module ? (Array.isArray(options.module) ? options.module : [options.module]).map(String) : void 0;
4866
+ const modules = resolveModules(moduleFilter);
4867
+ let ctx;
4868
+ try {
4869
+ ctx = await context.getCurrent();
4870
+ } catch (err) {
4871
+ console.log(`
4872
+ ${bold8(red8(`\u2717 ${formatError2(err)}`))}`);
4873
+ process.exitCode = 1;
4874
+ return;
4875
+ }
4876
+ if (ctx.url.startsWith("https://")) {
4877
+ console.log(
4878
+ bold8(yellow6("\n\u26A0 Warning: The current context is using HTTPS.\n")) + ` ${bold8("sync dev")} is designed for development. Using it against a remote instance may have unintended side-effects.
4879
+ Tip: Start a local instance with ${bold8("spica project start")} and switch to it with ${bold8("spica context switch <name>")} before running ${bold8("sync dev")}.`
4880
+ );
4881
+ }
4882
+ const http2 = httpService.create({
4883
+ baseUrl: ctx.url,
4884
+ authorization: ctx.authorization
4885
+ });
4886
+ console.log(bold8("\nBuilding plan\u2026"));
4887
+ let plan2;
4888
+ try {
4889
+ plan2 = await buildPlan(modules, http2, rootDir, false);
4890
+ } catch (err) {
4891
+ console.log(`
4892
+ ${bold8(red8(`\u2717 Failed to build plan: ${formatError2(err)}`))}`);
4893
+ process.exitCode = 1;
4894
+ return;
4895
+ }
4896
+ const totalChanges = plan2.modules.reduce(
4897
+ (n, m) => n + m.creates.length + m.updates.length + m.deletes.length,
4898
+ 0
4899
+ );
4900
+ renderPlan(plan2, { detailed: false });
4901
+ if (totalChanges > 0) {
4902
+ const ok = await confirm("\nApply these changes?");
4903
+ if (!ok) {
4904
+ console.log(bold8(yellow6("Aborted. No changes were applied.")));
4905
+ process.exitCode = 1;
4906
+ return;
4907
+ }
4908
+ console.log(bold8("\nApplying changes\u2026"));
4909
+ try {
4910
+ const { errors } = await applyPlan(plan2, http2, { concurrency: 5, abortOnError: true });
4911
+ if (errors.length) {
4912
+ console.log(bold8(red8(`
4913
+ \u2717 Apply failed with ${errors.length} error(s).`)));
4914
+ process.exitCode = 1;
4915
+ return;
4916
+ }
4917
+ } catch (err) {
4918
+ console.log(`
4919
+ ${bold8(red8(`\u2717 ${formatError2(err)}`))}`);
4920
+ process.exitCode = 1;
4921
+ return;
4922
+ }
4923
+ const c = plan2.modules.reduce((n, m) => n + m.creates.length, 0);
4924
+ const u = plan2.modules.reduce((n, m) => n + m.updates.length, 0);
4925
+ const d = plan2.modules.reduce((n, m) => n + m.deletes.length, 0);
4926
+ console.log(
4927
+ bold8(green8(`
4928
+ \u2713 Initial sync completed.`)) + ` ${green8(`+${c} created`)} ${yellow6(`~${u} updated`)} ${red8(`-${d} deleted`)}`
4929
+ );
4930
+ } else {
4931
+ console.log(bold8(green8("\n\u2713 Already in sync. Starting watcher\u2026")));
4932
+ }
4933
+ const state = createEmptyState();
4934
+ await Promise.all(modules.map((mod) => refreshStateForModule(mod, http2, state, rootDir)));
4935
+ const watchDirs = modules.map((mod) => path18.join(rootDir, mod.name));
4936
+ const dispatcher = createDevDispatcher({ modules, http: http2, rootDir, state });
4937
+ console.log(
4938
+ bold8(`
4939
+ ${cyan3("\u{1F441}")} Watching for changes in ${bold8(rootDir)}\u2026`) + ` ${bold8(yellow6("(Ctrl-C to stop)"))}`
4940
+ );
4941
+ const watcher = chokidar.watch(watchDirs, {
4942
+ ignoreInitial: true,
4943
+ persistent: true,
4944
+ ignored: buildWatchIgnored(modules, rootDir),
4945
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }
4946
+ });
4947
+ watcher.on("add", (p) => dispatcher.handleEvent("add", p));
4948
+ watcher.on("change", (p) => dispatcher.handleEvent("change", p));
4949
+ watcher.on("unlink", (p) => dispatcher.handleEvent("unlink", p));
4950
+ watcher.on(
4951
+ "error",
4952
+ (err) => console.warn(bold8(yellow6(`
4953
+ \u26A0 Watcher error: ${formatError2(err)}`)))
4954
+ );
4955
+ const shutdown = () => {
4956
+ console.log(bold8("\nStopping watcher\u2026"));
4957
+ dispatcher.dispose();
4958
+ watcher.close().then(() => process.exit(0));
4959
+ };
4960
+ process.on("SIGINT", shutdown);
4961
+ process.on("SIGTERM", shutdown);
4962
+ }
4963
+ function dev_default(program2) {
4964
+ return program2.command(
4965
+ "dev",
4966
+ "Watch local project files and automatically sync changes to the connected Spica instance."
4967
+ ).argument("[dir]", "Project directory (default: current working directory)").option(
4968
+ "--module <name>",
4969
+ `Filter to specific module(s). Available: ${MODULE_NAMES.join(", ")}.`,
4970
+ {
4971
+ validator: MODULE_NAMES
4972
+ }
4973
+ ).action(dev);
4974
+ }
4975
+
3434
4976
  // apps/cli/src/version.ts
3435
4977
  import { readFileSync } from "node:fs";
3436
4978
  function readPackageVersion(baseUrl) {
@@ -3443,7 +4985,7 @@ function readPackageVersion(baseUrl) {
3443
4985
  }
3444
4986
 
3445
4987
  // apps/cli/index.ts
3446
- var { program } = caporalCore4;
4988
+ var { program } = caporalCore6;
3447
4989
  function run(argv) {
3448
4990
  program.version(readPackageVersion(import.meta.url)).name("spica").bin("spica").description("Command line interface for spica.");
3449
4991
  apply_default(program);
@@ -3459,6 +5001,10 @@ function run(argv) {
3459
5001
  start_default(program);
3460
5002
  sync_default(program);
3461
5003
  upgrade_default(program);
5004
+ plan_default(program);
5005
+ apply_default2(program);
5006
+ fetch_default(program);
5007
+ dev_default(program);
3462
5008
  return program.run(argv);
3463
5009
  }
3464
5010
  export {