castle-web-cli 0.4.217 → 0.4.219

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.
@@ -0,0 +1,14 @@
1
+ export interface GitHeadChangedMessage {
2
+ type: 'git_head_changed';
3
+ }
4
+ /**
5
+ * Where the deck's HEAD points, as `<ref> <sha>` (or a bare sha when detached),
6
+ * or null when the deck has no git repo. Unborn branches read as the ref alone.
7
+ */
8
+ export declare function readGitHead(projectDir: string): string | null;
9
+ /** Broadcasts `git_head_changed` whenever the deck's HEAD moves. Returns a stop function. */
10
+ export declare function installGitHeadWatcher(opts: {
11
+ projectDir: string;
12
+ broadcast: (msg: GitHeadChangedMessage) => void;
13
+ pollMs?: number;
14
+ }): () => void;
@@ -0,0 +1,106 @@
1
+ // Serve-side "the deck's git history moved" broadcast, for the Versions panel.
2
+ //
3
+ // The files-changed watcher ignores `.git` on purpose, so a commit, a background
4
+ // `castle-web git sync` or a merge that moves `main` without touching a file the
5
+ // panel reports never reached it: the panel showed the old list until a reload.
6
+ // Those all run in other processes (the agent's commit, ghost's sync notify), so
7
+ // the serve cannot be told; it reads where HEAD points instead. That is two small
8
+ // file reads, so a poll is cheaper and sturdier than watching a `.git` that a
9
+ // cold resume recreates underneath us.
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ const POLL_MS = 2_000;
13
+ // A ref name as git writes it: slash-separated components, none empty, none `.`/`..`.
14
+ const REF_RE = /^ref: (refs(?:\/[A-Za-z0-9_+@-][A-Za-z0-9._+@-]*)+)$/;
15
+ const SHA_RE = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
16
+ // HEAD and a loose ref are one line; packed-refs grows with tags, so it gets more room.
17
+ const MAX_REF_BYTES = 4 * 1024;
18
+ const MAX_PACKED_REFS_BYTES = 1024 * 1024;
19
+ // The deck is written by the agent and whoever pushes to it, so a ref file can be a
20
+ // symlink, a pipe or something huge. Only a small regular file under a chain of real
21
+ // directories is read; anything else reads as absent. The file itself is lstat'd
22
+ // first, because Windows has neither O_NOFOLLOW nor O_NONBLOCK (Node turns them into
23
+ // 0); where they exist they also close the gap between that check and the open, and
24
+ // the fstat check refuses anything that changed in between before any read.
25
+ function readText(gitDir, rel, maxBytes) {
26
+ const parts = rel.split('/');
27
+ try {
28
+ let dir = gitDir;
29
+ for (const part of [null, ...parts.slice(0, -1)]) {
30
+ if (part !== null)
31
+ dir = path.join(dir, part);
32
+ if (!fs.lstatSync(dir).isDirectory())
33
+ return null;
34
+ }
35
+ const file = fs.lstatSync(path.join(gitDir, ...parts));
36
+ if (!file.isFile() || file.size > maxBytes)
37
+ return null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ let fd = null;
43
+ try {
44
+ fd = fs.openSync(path.join(gitDir, ...parts), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
45
+ const stat = fs.fstatSync(fd);
46
+ if (!stat.isFile() || stat.size > maxBytes)
47
+ return null;
48
+ const buffer = Buffer.alloc(stat.size);
49
+ const read = fs.readSync(fd, buffer, 0, stat.size, 0);
50
+ return buffer.subarray(0, read).toString('utf8');
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ finally {
56
+ if (fd !== null)
57
+ fs.closeSync(fd);
58
+ }
59
+ }
60
+ function packedRef(gitDir, ref) {
61
+ const packed = readText(gitDir, 'packed-refs', MAX_PACKED_REFS_BYTES);
62
+ if (!packed)
63
+ return null;
64
+ for (const line of packed.split('\n')) {
65
+ const [sha, name] = line.trim().split(' ');
66
+ if (name === ref && sha && SHA_RE.test(sha))
67
+ return sha;
68
+ }
69
+ return null;
70
+ }
71
+ /**
72
+ * Where the deck's HEAD points, as `<ref> <sha>` (or a bare sha when detached),
73
+ * or null when the deck has no git repo. Unborn branches read as the ref alone.
74
+ */
75
+ export function readGitHead(projectDir) {
76
+ const gitDir = path.join(projectDir, '.git');
77
+ const head = readText(gitDir, 'HEAD', MAX_REF_BYTES)?.trim();
78
+ if (!head)
79
+ return null;
80
+ if (SHA_RE.test(head))
81
+ return head;
82
+ const ref = REF_RE.exec(head)?.[1];
83
+ if (!ref)
84
+ return null;
85
+ const loose = readText(gitDir, ref, MAX_REF_BYTES)?.trim();
86
+ const sha = loose && SHA_RE.test(loose) ? loose : packedRef(gitDir, ref);
87
+ return sha ? `${ref} ${sha}` : ref;
88
+ }
89
+ /** Broadcasts `git_head_changed` whenever the deck's HEAD moves. Returns a stop function. */
90
+ export function installGitHeadWatcher(opts) {
91
+ let last = readGitHead(opts.projectDir);
92
+ const timer = setInterval(() => {
93
+ const now = readGitHead(opts.projectDir);
94
+ if (now === last)
95
+ return;
96
+ last = now;
97
+ try {
98
+ opts.broadcast({ type: 'git_head_changed' });
99
+ }
100
+ catch {
101
+ // A broadcast is never worth crashing the serve for.
102
+ }
103
+ }, opts.pollMs ?? POLL_MS);
104
+ timer.unref?.();
105
+ return () => clearInterval(timer);
106
+ }
@@ -51,3 +51,41 @@ export interface GitInitResult {
51
51
  export declare function gitInit(dirArg: string, opts: {
52
52
  environment: GitEnvironment;
53
53
  }, deps: GitInitDeps): Promise<GitInitResult>;
54
+ export type GitSetupOutcome = 'configured' | 'unchanged' | 'kept' | 'removed' | 'absent';
55
+ export interface GitSetupDeps {
56
+ git(args: string[], cwd: string): GitResult;
57
+ }
58
+ /**
59
+ * Points git at this CLI for the Castle git hosts in the user's global config, or removes
60
+ * that. A helper someone set for a Castle host themselves is left alone ('kept') unless
61
+ * `force`, since it can't be put back; `remove` takes out only what this wrote.
62
+ */
63
+ export declare function gitSetup(opts: {
64
+ remove?: boolean;
65
+ force?: boolean;
66
+ }, deps: GitSetupDeps): Record<GitEnvironment, GitSetupOutcome>;
67
+ /**
68
+ * The deck a `git clone` argument names: a deck id, its git URL, or its editor URL
69
+ * (castle.xyz/create/<deckId>). A git URL also says which environment it is on.
70
+ */
71
+ export declare function parseDeckTarget(target: string): {
72
+ deckId: string;
73
+ environment?: GitEnvironment;
74
+ };
75
+ export interface GitCloneDeps {
76
+ token: string | null;
77
+ envToken: string | undefined;
78
+ git(args: string[], cwd: string): GitResult;
79
+ castleWebOnPath(): boolean;
80
+ log(message: string): void;
81
+ warn(message: string): void;
82
+ }
83
+ export interface GitCloneResult {
84
+ deckId: string;
85
+ dir: string;
86
+ remoteUrl: string;
87
+ }
88
+ /** Clones a deck's Castle repo, with the remote named `castle` and the credential helper in the clone's config. */
89
+ export declare function gitClone(target: string, dirArg: string | undefined, opts: {
90
+ environment?: GitEnvironment;
91
+ }, deps: GitCloneDeps, cwd?: string): GitCloneResult;
package/dist/gitRemote.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from 'child_process';
2
2
  import * as fs from 'fs';
3
+ import * as os from 'os';
3
4
  import * as path from 'path';
4
5
  import { readCastleJsonOrThrow } from './castleJson.js';
5
6
  // Castle-hosted git remotes (castle-sandboxes docs/git-remotes-phase1.md): each deck
@@ -377,3 +378,170 @@ export async function gitInit(dirArg, opts, deps) {
377
378
  deps.log(pushHint(deps, dir));
378
379
  return { deckId, remoteUrl, registered, initialized, wroteGitignore, remote };
379
380
  }
381
+ // --- git setup ------------------------------------------------------------
382
+ // What the helper list for a Castle git host should be: an empty entry that resets
383
+ // whatever came before (osxkeychain, manager), then this CLI. The same pair `git init`
384
+ // writes per repo, here in the user's global config, the way `gh auth setup-git` does
385
+ // for github.com. Keyed to the Castle hosts only, so no other remote is affected.
386
+ const HELPER_VALUES = ['', CREDENTIAL_HELPER];
387
+ function globalHelperValues(deps, key, cwd) {
388
+ const current = git(deps, ['config', '--global', '--get-all', key], cwd);
389
+ // 1: the key isn't set.
390
+ if (current.status === 1)
391
+ return [];
392
+ if (current.status !== 0)
393
+ gitOrThrow(deps, ['config', '--global', '--get-all', key], cwd);
394
+ return current.stdout.replace(/\n$/, '').split('\n');
395
+ }
396
+ // Values this CLI writes: the reset entry and itself. Anything else under the key is
397
+ // someone's own helper (Git Credential Manager, `store`, a script). An empty entry alone
398
+ // proves nothing -- people write `helper =` before their own helper too -- so only the
399
+ // helper value itself marks the key as ours.
400
+ const isOurs = (value) => HELPER_VALUES.includes(value);
401
+ const HELPER_VALUE_RE = `^${CREDENTIAL_HELPER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`;
402
+ /**
403
+ * Points git at this CLI for the Castle git hosts in the user's global config, or removes
404
+ * that. A helper someone set for a Castle host themselves is left alone ('kept') unless
405
+ * `force`, since it can't be put back; `remove` takes out only what this wrote.
406
+ */
407
+ export function gitSetup(opts, deps) {
408
+ // The home dir, so a broken repo in the current directory can't get in the way.
409
+ const cwd = os.homedir();
410
+ const outcomes = {};
411
+ for (const environment of Object.keys(GIT_HOSTS)) {
412
+ const key = credentialConfigKey(environment);
413
+ const values = globalHelperValues(deps, key, cwd);
414
+ if (opts.remove) {
415
+ if (!values.includes(CREDENTIAL_HELPER)) {
416
+ outcomes[environment] = 'absent';
417
+ continue;
418
+ }
419
+ // Exactly what this wrote goes whole; beside someone else's entries, only the helper
420
+ // itself goes, and their reset entry (if that is what it is) stays.
421
+ const exactlyOurs = values.length === HELPER_VALUES.length && values.every((v, i) => v === HELPER_VALUES[i]);
422
+ gitOrThrow(deps, exactlyOurs
423
+ ? ['config', '--global', '--unset-all', key]
424
+ : ['config', '--global', '--unset-all', key, HELPER_VALUE_RE], cwd);
425
+ outcomes[environment] = 'removed';
426
+ continue;
427
+ }
428
+ if (values.length === HELPER_VALUES.length && values.every((v, i) => v === HELPER_VALUES[i])) {
429
+ outcomes[environment] = 'unchanged';
430
+ continue;
431
+ }
432
+ if (values.some((v) => !isOurs(v)) && !opts.force) {
433
+ outcomes[environment] = 'kept';
434
+ continue;
435
+ }
436
+ if (values.length > 0)
437
+ gitOrThrow(deps, ['config', '--global', '--unset-all', key], cwd);
438
+ for (const value of HELPER_VALUES)
439
+ gitOrThrow(deps, ['config', '--global', '--add', key, value], cwd);
440
+ outcomes[environment] = 'configured';
441
+ }
442
+ return outcomes;
443
+ }
444
+ // --- git clone ------------------------------------------------------------
445
+ const DECK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
446
+ const WEB_HOSTS = new Set(['castle.xyz', 'www.castle.xyz']);
447
+ /**
448
+ * The deck a `git clone` argument names: a deck id, its git URL, or its editor URL
449
+ * (castle.xyz/create/<deckId>). A git URL also says which environment it is on.
450
+ */
451
+ export function parseDeckTarget(target) {
452
+ if (DECK_ID_RE.test(target))
453
+ return { deckId: target };
454
+ let url = null;
455
+ try {
456
+ url = new URL(/^[a-z]+:\/\//i.test(target) ? target : `https://${target}`);
457
+ }
458
+ catch {
459
+ url = null;
460
+ }
461
+ if (url && url.protocol === 'https:') {
462
+ const segments = url.pathname.split('/').filter(Boolean);
463
+ const gitEnvironment = Object.keys(GIT_HOSTS).find((env) => GIT_HOSTS[env] === url.host);
464
+ if (gitEnvironment && segments.length === 1) {
465
+ const deckId = segments[0].replace(/\.git$/, '');
466
+ if (DECK_ID_RE.test(deckId))
467
+ return { deckId, environment: gitEnvironment };
468
+ }
469
+ if (WEB_HOSTS.has(url.host) && segments.length === 2 && segments[0] === 'create' && DECK_ID_RE.test(segments[1])) {
470
+ return { deckId: segments[1] };
471
+ }
472
+ }
473
+ throw new Error(`${target} is not a deck. Pass a deck id, its git URL (https://git.castle.xyz/<deckId>.git) or its editor URL (https://castle.xyz/create/<deckId>).`);
474
+ }
475
+ function helperArgs(environment) {
476
+ const key = credentialConfigKey(environment);
477
+ return HELPER_VALUES.flatMap((value) => ['-c', `${key}=${value}`]);
478
+ }
479
+ // Turns git's answer for a Castle remote into what the user should do about it. The git
480
+ // proxy answers 404 for a deck with no repo (or no deck), 403 for someone else's deck and
481
+ // 401 for a login it doesn't accept.
482
+ function explainRemoteFailure(result, deckId, environment) {
483
+ const why = (result.stderr || result.stdout || result.error?.message || '').trim();
484
+ // Only git's own words for an HTTP 404 -- not, say, a shell's "castle-web: not found".
485
+ if (/repository '[^']*' not found|error: 404/.test(why))
486
+ return noHistoryError(deckId, environment);
487
+ if (/error: 403/.test(why)) {
488
+ return new Error(`You don't have access to deck ${deckId}: only its owner can clone it.`);
489
+ }
490
+ if (/error: 401|Authentication failed|could not read (Username|Password)/i.test(why)) {
491
+ return new Error('Castle did not accept your login. Run `castle-web login`, then retry.');
492
+ }
493
+ return new Error(`Could not reach the Castle git remote for ${deckId}${why ? `: ${why}` : ''}`);
494
+ }
495
+ function noHistoryError(deckId, environment) {
496
+ const editor = environment === 'staging'
497
+ ? `https://castle.xyz/create/${deckId}?sandbox=staging`
498
+ : `https://castle.xyz/create/${deckId}`;
499
+ return new Error(`Deck ${deckId} has no git history${environment === 'staging' ? ' on staging' : ''} yet (or doesn't exist). Open it in the cloud editor once (${editor}), which starts its history, then clone again.`);
500
+ }
501
+ /** Clones a deck's Castle repo, with the remote named `castle` and the credential helper in the clone's config. */
502
+ export function gitClone(target, dirArg, opts, deps, cwd = process.cwd()) {
503
+ if (isSandboxToken(deps.envToken)) {
504
+ throw new Error('Cloning a Castle git remote is not available from a cloud sandbox.');
505
+ }
506
+ if (!deps.token)
507
+ throw new Error('Not logged in. Run `castle-web login`.');
508
+ const parsed = parseDeckTarget(target);
509
+ if (parsed.environment && opts.environment && parsed.environment !== opts.environment) {
510
+ throw new Error(`${target} is a ${parsed.environment} remote, but --staging says ${opts.environment}.`);
511
+ }
512
+ const environment = parsed.environment ?? opts.environment ?? 'production';
513
+ const { deckId } = parsed;
514
+ const remoteUrl = expectedRemoteUrl(environment, deckId);
515
+ const dir = path.resolve(cwd, dirArg ?? deckId);
516
+ if (fs.existsSync(dir) && (!fs.statSync(dir).isDirectory() || fs.readdirSync(dir).length > 0)) {
517
+ throw new Error(`${dir} already exists and is not an empty directory.`);
518
+ }
519
+ // git runs the helper as `castle-web git credential`; without it on PATH every request
520
+ // fails to authenticate, which should say so rather than look like a missing deck.
521
+ if (!deps.castleWebOnPath()) {
522
+ throw new Error('`castle-web` is not on PATH. git runs `castle-web git credential` to get your Castle token, so install the CLI globally first (npm install -g castle-web-cli).');
523
+ }
524
+ // Ask first, so a deck with no history gets a sentence rather than an empty clone.
525
+ const heads = git(deps, [...helperArgs(environment), 'ls-remote', '--heads', remoteUrl], cwd);
526
+ if (heads.status !== 0)
527
+ throw explainRemoteFailure(heads, deckId, environment);
528
+ if (!heads.stdout.trim())
529
+ throw noHistoryError(deckId, environment);
530
+ // `clone -c` writes these into the new repo before it fetches, so they both authenticate
531
+ // this clone and stay for later pushes and pulls.
532
+ const cloned = git(deps, ['clone', '--origin', GIT_REMOTE_NAME, ...helperArgs(environment), remoteUrl, dir], cwd);
533
+ if (cloned.status !== 0)
534
+ throw explainRemoteFailure(cloned, deckId, environment);
535
+ deps.log(`Cloned deck ${deckId} into ${dir}.`);
536
+ try {
537
+ const castleJson = readCastleJsonOrThrow(dir);
538
+ if (castleJson?.deckId && castleJson.deckId !== deckId) {
539
+ deps.warn(`Warning: castle.json in this repo names deck ${String(castleJson.deckId)}, not ${deckId}.`);
540
+ }
541
+ }
542
+ catch {
543
+ // A repo without a readable castle.json still cloned; nothing more to say about it.
544
+ }
545
+ deps.log(pushHint(deps, dir));
546
+ return { deckId, dir, remoteUrl };
547
+ }
package/dist/index.js CHANGED
@@ -169,7 +169,9 @@ function usage() {
169
169
  castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
170
170
  castle-web restore-version <version> [--force] [--dir DIR]
171
171
  castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
172
- castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
172
+ castle-web git clone <deckId|url> [dir] [--staging] (clones a deck's Castle repo; the remote is "castle")
173
+ castle-web git setup [--force|--remove] (lets plain git use your Castle login for git.castle.xyz; login does this)
174
+ castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git setup and git init set it up)
173
175
  castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
176
  castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
177
  castle-web git rehydrate [--dir DIR] (cloud sandbox only: rebuild git history missing after a cold resume)
@@ -219,7 +221,47 @@ function parseGitInitArgs() {
219
221
  }
220
222
  return { dir: dir ?? '.', staging };
221
223
  }
222
- // `castle-web git init [dir] [--dir DIR] [--staging]` and `castle-web git credential <action>`.
224
+ // `git clone`'s and `git setup`'s arguments, as strictly as `git init`'s.
225
+ // A deck id may start with `-`; pass it after `--`.
226
+ function parseGitCloneArgs() {
227
+ const positionals = [];
228
+ let staging = false;
229
+ let onlyPositionals = false;
230
+ for (const arg of args.slice(2)) {
231
+ if (onlyPositionals)
232
+ positionals.push(arg);
233
+ else if (arg === '--')
234
+ onlyPositionals = true;
235
+ else if (arg === '--staging')
236
+ staging = true;
237
+ else if (arg.startsWith('-')) {
238
+ throw new Error(`Unknown option for git clone: ${arg} (it takes <deckId|url> [dir] [--staging]; put a deck id starting with - after --).`);
239
+ }
240
+ else
241
+ positionals.push(arg);
242
+ }
243
+ if (positionals.length === 0 || positionals.length > 2) {
244
+ throw new Error('git clone takes a deck (its id, git URL or editor URL) and optionally a directory.');
245
+ }
246
+ return { target: positionals[0], dir: positionals[1], staging };
247
+ }
248
+ function parseGitSetupArgs() {
249
+ let remove = false;
250
+ let force = false;
251
+ for (const arg of args.slice(2)) {
252
+ if (arg === '--remove')
253
+ remove = true;
254
+ else if (arg === '--force')
255
+ force = true;
256
+ else
257
+ throw new Error(`Unknown argument for git setup: ${arg} (it takes [--force] or [--remove]).`);
258
+ }
259
+ if (remove && force)
260
+ throw new Error('git setup takes --force or --remove, not both.');
261
+ return { remove, force };
262
+ }
263
+ // `castle-web git init [dir] [--dir DIR] [--staging]`, `git clone`, `git setup` and
264
+ // `castle-web git credential <action>`.
223
265
  async function gitCommand() {
224
266
  const [sub, arg] = readPositionals();
225
267
  const gitRemote = await import('./gitRemote.js');
@@ -239,6 +281,37 @@ async function gitCommand() {
239
281
  await cloudGitCommand(sub);
240
282
  return;
241
283
  }
284
+ if (sub === 'setup') {
285
+ const { remove, force } = parseGitSetupArgs();
286
+ const outcomes = gitRemote.gitSetup({ remove, force }, { git: gitRemote.runGit });
287
+ for (const [environment, outcome] of Object.entries(outcomes)) {
288
+ const host = gitRemote.GIT_HOSTS[environment];
289
+ const said = {
290
+ configured: `git now uses your Castle login for ${host}.`,
291
+ unchanged: `git already uses your Castle login for ${host}.`,
292
+ kept: `Your git config already has its own credential helper for ${host}; left it alone. \`castle-web git setup --force\` replaces it (\`castle-web git clone\` works either way).`,
293
+ removed: `Removed the Castle credential helper for ${host} from your git config.`,
294
+ absent: `No Castle credential helper was set for ${host}.`,
295
+ }[outcome];
296
+ console.log(said);
297
+ }
298
+ if (!remove && !gitRemote.isOnPath('castle-web')) {
299
+ console.error('Warning: `castle-web` is not on PATH. git runs `castle-web git credential` to get your Castle token, so it will fail to authenticate until it is (npm install -g castle-web-cli).');
300
+ }
301
+ return;
302
+ }
303
+ if (sub === 'clone') {
304
+ const cloneArgs = parseGitCloneArgs();
305
+ gitRemote.gitClone(cloneArgs.target, cloneArgs.dir, { environment: cloneArgs.staging ? 'staging' : undefined }, {
306
+ token: config.getToken(),
307
+ envToken: process.env.CASTLE_TOKEN,
308
+ git: gitRemote.runGit,
309
+ castleWebOnPath: () => gitRemote.isOnPath('castle-web'),
310
+ log: (message) => console.log(message),
311
+ warn: (message) => console.error(message),
312
+ });
313
+ return;
314
+ }
242
315
  if (sub !== 'init') {
243
316
  if (sub)
244
317
  console.error(`Unknown command: git ${sub}`);
package/dist/login.js CHANGED
@@ -13,9 +13,39 @@ export async function login() {
13
13
  if (user) {
14
14
  config.setAuth(user.token, user.userId);
15
15
  console.log(`Logged in as @${user.username}`);
16
+ await setUpGitAfterLogin();
16
17
  return;
17
18
  }
18
19
  }
19
20
  console.error('Login timed out.');
20
21
  process.exit(1);
21
22
  }
23
+ // Like `gh auth login`: once logged in, plain git can use that login for Castle's git
24
+ // hosts (`castle-web git setup`). Best effort -- it never fails the login -- and silent
25
+ // when git isn't installed, since then there is nothing to set up.
26
+ async function setUpGitAfterLogin() {
27
+ const gitRemote = await import('./gitRemote.js');
28
+ if (gitRemote.isSandboxToken(process.env.CASTLE_TOKEN))
29
+ return;
30
+ try {
31
+ const outcomes = gitRemote.gitSetup({}, { git: gitRemote.runGit });
32
+ const hosts = (outcome) => Object.keys(outcomes)
33
+ .filter((environment) => outcomes[environment] === outcome)
34
+ .map((environment) => gitRemote.GIT_HOSTS[environment])
35
+ .join(' and ');
36
+ const configured = hosts('configured');
37
+ const kept = hosts('kept');
38
+ if (configured) {
39
+ console.log(`git now uses your Castle login for ${configured}, so you can clone a deck with \`castle-web git clone <deckId>\`. (Undo: castle-web git setup --remove)`);
40
+ }
41
+ if (kept) {
42
+ console.log(`Your git config has its own credential helper for ${kept}, so login left it alone. \`castle-web git clone <deckId>\` still works; \`castle-web git setup --force\` replaces it.`);
43
+ }
44
+ }
45
+ catch (e) {
46
+ const message = e instanceof Error ? e.message : String(e);
47
+ if (/git is not installed/.test(message))
48
+ return;
49
+ console.error(`Could not set up git for Castle remotes (${message}). Run \`castle-web git setup\` to retry.`);
50
+ }
51
+ }
package/dist/serve.js CHANGED
@@ -17,6 +17,7 @@ import { externalSourcemapsPlugin } from './externalSourcemaps.js';
17
17
  import { fontFaceImportsPlugin } from './fontFaceImports.js';
18
18
  import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
19
19
  import { installFilesChangedWatcher } from './filesChanged.js';
20
+ import { installGitHeadWatcher } from './gitHeadWatcher.js';
20
21
  import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
21
22
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
22
23
  import { ensureAgentsSymlink } from './init.js';
@@ -1318,6 +1319,9 @@ export async function serve(dir, options = {}) {
1318
1319
  log: (line) => appendCapped(logFile, line),
1319
1320
  claimTunes: (relPath, event) => tuneLedger.claim(relPath, event),
1320
1321
  });
1322
+ // `.git` is outside that watcher, so a commit or a background sync that moves the
1323
+ // deck's history reaches the Versions panel through this instead.
1324
+ installGitHeadWatcher({ projectDir, broadcast });
1321
1325
  // Bring content up first so `--open` cannot race an iframe against a port
1322
1326
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
1323
1327
  await vite.listen();