castle-web-cli 0.4.218 → 0.4.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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
@@ -155,8 +155,10 @@ function usage() {
155
155
  castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
156
156
  castle-web restart [--port PORT]
157
157
  castle-web screenshot [--out FILE] [--port PORT]
158
- castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private]
158
+ castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private] [--force] (--force: save over a newer saved copy)
159
159
  castle-web get-deck [dir] [--deck-id ID] [--force] (replaces the source if the deck is already there)
160
+ castle-web get-deck <dir> --side [--deck-id ID] [--json] (fetches the saved copy into <dir>/.castle/agent/saved-source/<stamp>/, touching nothing else)
161
+ castle-web source-status <dir> [--adopt] [--notify] [--json] (whether the deck's saved copy is newer than this folder)
160
162
  castle-web list-decks [dir] [--kind mine|saved|kits] (decks this one could import; ids are what add-import takes)
161
163
  castle-web add-import <deckId|url|kit> [dir] [--as ALIAS] (adds another deck, or a kit this CLI ships, as a read-only dependency in imports/)
162
164
  castle-web fork-import-file <imports/...> [dir] (this deck's own version of one imported file)
@@ -169,7 +171,9 @@ function usage() {
169
171
  castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
170
172
  castle-web restore-version <version> [--force] [--dir DIR]
171
173
  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)
174
+ castle-web git clone <deckId|url> [dir] [--staging] (clones a deck's Castle repo; the remote is "castle")
175
+ castle-web git setup [--force|--remove] (lets plain git use your Castle login for git.castle.xyz; login does this)
176
+ castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git setup and git init set it up)
173
177
  castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
178
  castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
179
  castle-web git rehydrate [--dir DIR] (cloud sandbox only: rebuild git history missing after a cold resume)
@@ -219,7 +223,47 @@ function parseGitInitArgs() {
219
223
  }
220
224
  return { dir: dir ?? '.', staging };
221
225
  }
222
- // `castle-web git init [dir] [--dir DIR] [--staging]` and `castle-web git credential <action>`.
226
+ // `git clone`'s and `git setup`'s arguments, as strictly as `git init`'s.
227
+ // A deck id may start with `-`; pass it after `--`.
228
+ function parseGitCloneArgs() {
229
+ const positionals = [];
230
+ let staging = false;
231
+ let onlyPositionals = false;
232
+ for (const arg of args.slice(2)) {
233
+ if (onlyPositionals)
234
+ positionals.push(arg);
235
+ else if (arg === '--')
236
+ onlyPositionals = true;
237
+ else if (arg === '--staging')
238
+ staging = true;
239
+ else if (arg.startsWith('-')) {
240
+ throw new Error(`Unknown option for git clone: ${arg} (it takes <deckId|url> [dir] [--staging]; put a deck id starting with - after --).`);
241
+ }
242
+ else
243
+ positionals.push(arg);
244
+ }
245
+ if (positionals.length === 0 || positionals.length > 2) {
246
+ throw new Error('git clone takes a deck (its id, git URL or editor URL) and optionally a directory.');
247
+ }
248
+ return { target: positionals[0], dir: positionals[1], staging };
249
+ }
250
+ function parseGitSetupArgs() {
251
+ let remove = false;
252
+ let force = false;
253
+ for (const arg of args.slice(2)) {
254
+ if (arg === '--remove')
255
+ remove = true;
256
+ else if (arg === '--force')
257
+ force = true;
258
+ else
259
+ throw new Error(`Unknown argument for git setup: ${arg} (it takes [--force] or [--remove]).`);
260
+ }
261
+ if (remove && force)
262
+ throw new Error('git setup takes --force or --remove, not both.');
263
+ return { remove, force };
264
+ }
265
+ // `castle-web git init [dir] [--dir DIR] [--staging]`, `git clone`, `git setup` and
266
+ // `castle-web git credential <action>`.
223
267
  async function gitCommand() {
224
268
  const [sub, arg] = readPositionals();
225
269
  const gitRemote = await import('./gitRemote.js');
@@ -239,6 +283,37 @@ async function gitCommand() {
239
283
  await cloudGitCommand(sub);
240
284
  return;
241
285
  }
286
+ if (sub === 'setup') {
287
+ const { remove, force } = parseGitSetupArgs();
288
+ const outcomes = gitRemote.gitSetup({ remove, force }, { git: gitRemote.runGit });
289
+ for (const [environment, outcome] of Object.entries(outcomes)) {
290
+ const host = gitRemote.GIT_HOSTS[environment];
291
+ const said = {
292
+ configured: `git now uses your Castle login for ${host}.`,
293
+ unchanged: `git already uses your Castle login for ${host}.`,
294
+ 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).`,
295
+ removed: `Removed the Castle credential helper for ${host} from your git config.`,
296
+ absent: `No Castle credential helper was set for ${host}.`,
297
+ }[outcome];
298
+ console.log(said);
299
+ }
300
+ if (!remove && !gitRemote.isOnPath('castle-web')) {
301
+ 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).');
302
+ }
303
+ return;
304
+ }
305
+ if (sub === 'clone') {
306
+ const cloneArgs = parseGitCloneArgs();
307
+ gitRemote.gitClone(cloneArgs.target, cloneArgs.dir, { environment: cloneArgs.staging ? 'staging' : undefined }, {
308
+ token: config.getToken(),
309
+ envToken: process.env.CASTLE_TOKEN,
310
+ git: gitRemote.runGit,
311
+ castleWebOnPath: () => gitRemote.isOnPath('castle-web'),
312
+ log: (message) => console.log(message),
313
+ warn: (message) => console.error(message),
314
+ });
315
+ return;
316
+ }
242
317
  if (sub !== 'init') {
243
318
  if (sub)
244
319
  console.error(`Unknown command: git ${sub}`);
@@ -445,7 +520,7 @@ async function main() {
445
520
  const title = getFlagValue('--title');
446
521
  const caption = getFlagValue('--caption');
447
522
  const visibility = getFlagValue('--visibility');
448
- await saveDeck(dir, { title, caption, visibility });
523
+ await saveDeck(dir, { title, caption, visibility, force: hasFlag('--force') });
449
524
  break;
450
525
  }
451
526
  case 'get-deck': {
@@ -454,7 +529,18 @@ async function main() {
454
529
  await getDeck(findPositionalDir(), {
455
530
  deckId: getFlagValue('--deck-id'),
456
531
  force: hasFlag('--force'),
532
+ side: hasFlag('--side'),
533
+ json: hasFlag('--json'),
534
+ });
535
+ break;
536
+ }
537
+ case 'source-status': {
538
+ const { sourceStatus, describeSourceStatus } = await import('./webSourceSync.js');
539
+ const result = await sourceStatus(findPositionalDir(), {
540
+ adopt: hasFlag('--adopt'),
541
+ notify: hasFlag('--notify'),
457
542
  });
543
+ console.log(hasFlag('--json') ? JSON.stringify(result) : describeSourceStatus(result));
458
544
  break;
459
545
  }
460
546
  case 'list-decks': {
package/dist/init.js CHANGED
@@ -54,7 +54,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
54
54
  // Registry version of castle-web-sdk to inject when scaffolding from a
55
55
  // globally-installed castle-web (not from inside the workspace). Bumped
56
56
  // alongside cli/sdk version bumps.
57
- const PUBLISHED_SDK_VERSION = '0.4.39';
57
+ const PUBLISHED_SDK_VERSION = '0.4.40';
58
58
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
59
  // face can ship without a cli release, and a caret range means an existing
60
60
  // deck's next install picks it up. Nothing here has to move when it does.
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
+ }
@@ -1,4 +1,5 @@
1
1
  import * as api from './api.js';
2
+ import { type SavePrecondition } from './webSourceSync.js';
2
3
  export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
3
4
  export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
4
5
  export declare const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = "CASTLE_SAVE_COVER_SELECTION ";
@@ -7,11 +8,15 @@ export declare function runTar(args: string[], opts?: {
7
8
  capture?: boolean;
8
9
  }): Promise<string>;
9
10
  export declare function archiveSource(projectDir: string): Promise<Buffer>;
10
- export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string): Promise<string>;
11
+ export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string, log?: (line: string) => void): Promise<string>;
12
+ export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null): Promise<api.WebDeckSource>;
13
+ export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
11
14
  export type SaveVisibility = 'unlisted' | 'private';
12
15
  export interface SaveDeckOptions {
13
16
  title?: string;
14
17
  caption?: string;
15
18
  visibility?: SaveVisibility;
19
+ /** Save even when the deck's saved copy is newer than this folder. */
20
+ force?: boolean;
16
21
  }
17
22
  export declare function saveDeck(dir: string, opts?: SaveDeckOptions): Promise<void>;
package/dist/save-deck.js CHANGED
@@ -10,6 +10,7 @@ import { resolveServerConfig } from './castleJson.js';
10
10
  import { selectSaveCover } from './saveCover.js';
11
11
  import { COVER_FILE } from './localPaths.js';
12
12
  import { buildServerBundle } from './serverBundle.js';
13
+ import { decideSavePrecondition, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
13
14
  // `imports/` is derived state like node_modules: a dependency's files belong to
14
15
  // the deck that published them, and castle.json's import pins are enough to fetch
15
16
  // them again -- so they neither bloat this deck's archive nor get republished as
@@ -95,14 +96,14 @@ export async function archiveSource(projectDir) {
95
96
  // Written to tmp and read or untarred out of there, never moved out: in a sandbox
96
97
  // the deck is on a different filesystem from tmp, and a rename across that is EXDEV.
97
98
  // The caller owns the file it gets back.
98
- export async function downloadSourceArchive(source, namePrefix) {
99
- console.log(`Fetching ${source.archiveUrl}`);
99
+ export async function downloadSourceArchive(source, namePrefix, log = console.log) {
100
+ log(`Fetching ${source.archiveUrl}`);
100
101
  const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
101
102
  if (!res.ok) {
102
103
  throw new Error(`Archive fetch failed: HTTP ${res.status}`);
103
104
  }
104
105
  const buf = Buffer.from(await res.arrayBuffer());
105
- console.log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
106
+ log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
106
107
  const file = path.join(os.tmpdir(), `${namePrefix}-${nanoid(8)}.tar.gz`);
107
108
  fs.writeFileSync(file, buf);
108
109
  return file;
@@ -122,7 +123,9 @@ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, l
122
123
  if (response.status >= 300)
123
124
  throw new Error(`${label} failed: HTTP ${response.status}`);
124
125
  }
125
- async function uploadSource(projectDir, deckId) {
126
+ // `expectedS3Key` is the save precondition (api.saveWebDeckSource). Returns the saved source,
127
+ // whose key and time become this folder's sync marker.
128
+ export async function uploadSource(projectDir, deckId, expectedS3Key) {
126
129
  const archive = await traceSaveStage('source_archive', () => archiveSource(projectDir), (value) => ({ bytes: value.byteLength }));
127
130
  const sizeKB = archive.length / 1024;
128
131
  console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
@@ -131,7 +134,24 @@ async function uploadSource(projectDir, deckId) {
131
134
  const view = new Uint8Array(archive.byteLength);
132
135
  view.set(archive);
133
136
  await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload'));
134
- await traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId));
137
+ return traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId, expectedS3Key));
138
+ }
139
+ // Refused: the saved copy is newer than this folder. One machine-readable stdout line (castle-www
140
+ // turns it into its "saved copy is newer" dialog), the human message on stderr, and a dedicated
141
+ // exit code -- set, not exited with, so a piped stdout is flushed before the process ends. The
142
+ // caller returns straight after.
143
+ function refuseSave(dir, refusal) {
144
+ console.log(saveRefusedLine(refusal));
145
+ console.error(saveRefusedMessage(dir, refusal));
146
+ process.exitCode = EXIT_SAVED_DECK_NEWER;
147
+ }
148
+ // Before anything is uploaded or published: the deck goes live at updateCardAndDeckV2, so a
149
+ // refusal any later would leave it half-published. Only a deck that already has an id is
150
+ // checked; a new deck has no saved copy to overwrite.
151
+ export async function checkSavePrecondition(projectDir, deckId, force) {
152
+ const marker = readSyncMarker(projectDir, deckId);
153
+ const server = await fetchServerSourceVersion(deckId);
154
+ return decideSavePrecondition(marker, server, force);
135
155
  }
136
156
  const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
137
157
  function readPublishedServerBundleState(projectDir) {
@@ -254,6 +274,23 @@ export async function saveDeck(dir, opts = {}) {
254
274
  process.exit(1);
255
275
  }
256
276
  const castleJson = readCastleJson(projectDir);
277
+ const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
278
+ // A deck without an id is new: the source commit sends no precondition, as before.
279
+ let expectedS3Key;
280
+ let markerVia = 'save-deck';
281
+ if (existingDeckId) {
282
+ const precondition = await checkSavePrecondition(projectDir, existingDeckId, opts.force === true);
283
+ if (precondition.kind === 'refuse') {
284
+ refuseSave(dir, precondition);
285
+ return;
286
+ }
287
+ expectedS3Key = precondition.expectedS3Key;
288
+ markerVia = precondition.via;
289
+ if (precondition.adopt) {
290
+ console.error('Note: this folder has no record of which saved copy it came from; adopting it as the ' +
291
+ "deck's saved copy. Later saves are refused if someone else saves this deck in between.");
292
+ }
293
+ }
257
294
  console.log('Bundling...');
258
295
  const bundle = await traceSaveStage('bundle', () => bundleProject(projectDir), (value) => ({ bytes: Buffer.byteLength(value) }));
259
296
  const sizeKB = bundle.length / 1024;
@@ -368,11 +405,34 @@ export async function saveDeck(dir, opts = {}) {
368
405
  `"${title}" is live on the new client but its server is unchanged.`);
369
406
  }
370
407
  console.log('Uploading source archive...');
371
- await uploadSource(projectDir, result.deckId);
408
+ // The precondition only applies to the deck it was checked against.
409
+ const saved = await uploadSource(projectDir, result.deckId, result.deckId === existingDeckId ? expectedS3Key : undefined);
372
410
  console.log('Source archive saved.');
411
+ try {
412
+ writeSyncMarker(projectDir, result.deckId, saved, markerVia);
413
+ }
414
+ catch (e) {
415
+ // The save itself succeeded; a missing marker only means the next save adopts again.
416
+ console.error(`Could not record the saved version: ${e instanceof Error ? e.message : String(e)}`);
417
+ }
373
418
  }
374
419
  catch (e) {
375
420
  const code = e?.extensions?.code ?? '';
421
+ if (code === WEB_DECK_SOURCE_STALE_CODE) {
422
+ // Someone saved between the check above and this commit. The game itself is already
423
+ // live; only its saved source was refused. Reported like the check's own refusal.
424
+ const server = existingDeckId
425
+ ? await fetchServerSourceVersion(existingDeckId).catch(() => null)
426
+ : null;
427
+ const marker = existingDeckId ? readSyncMarker(projectDir, existingDeckId) : null;
428
+ console.error('The playable deck was updated, but its saved source was not: someone else saved it first.');
429
+ refuseSave(dir, {
430
+ savedAt: server?.updatedAt ?? null,
431
+ syncedAt: marker?.updatedAt ?? null,
432
+ savedS3Key: server?.s3Key ?? null,
433
+ });
434
+ return;
435
+ }
376
436
  if (code === 'LOGIN_REQUIRED') {
377
437
  console.error('Not logged in. Run `castle-web login` first.');
378
438
  }
@@ -0,0 +1,83 @@
1
+ export declare const WEB_SOURCE_SYNC_FILE: string;
2
+ /** `get-deck --side` copies of the saved source, one folder per saved version. */
3
+ export declare const SAVED_SOURCE_DIR: string;
4
+ export declare const SAVED_SOURCE_KEEP = 2;
5
+ export type SyncVia = 'get-deck' | 'save-deck' | 'adopt' | 'force';
6
+ export interface WebSourceSyncMarker {
7
+ deckId: string;
8
+ s3Key: string;
9
+ updatedAt: string;
10
+ syncedAt: string;
11
+ via: SyncVia;
12
+ }
13
+ export interface ServerSourceVersion {
14
+ s3Key: string;
15
+ updatedAt: string;
16
+ }
17
+ /** The folder's marker, or null when missing, malformed, or recorded for another deck. */
18
+ export declare function readSyncMarker(dir: string, deckId?: string): WebSourceSyncMarker | null;
19
+ export declare function writeSyncMarker(dir: string, deckId: string, source: ServerSourceVersion, via: SyncVia, now?: Date): WebSourceSyncMarker;
20
+ /** Removes a `source-status --notify` notice the serve has not consumed yet. */
21
+ export declare function clearSourceNewerNotice(dir: string): void;
22
+ export type SyncComparison = 'in-sync' | 'saved-newer' | 'lag';
23
+ /**
24
+ * The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
25
+ * server can still show the previous row: a different key alone is not proof of a newer save.
26
+ * Saved-newer only when the keys differ AND the server's save time is strictly newer than the
27
+ * marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
28
+ */
29
+ export declare function compareSync(marker: Pick<WebSourceSyncMarker, 's3Key' | 'updatedAt'>, server: ServerSourceVersion): SyncComparison;
30
+ export type SavePrecondition = {
31
+ kind: 'proceed';
32
+ /** undefined: omit the argument (no check); null: expect no saved source; string: expect this key. */
33
+ expectedS3Key: string | null | undefined;
34
+ /** No marker but a saved source exists: this folder is adopted as the deck's saved copy. */
35
+ adopt: boolean;
36
+ via: SyncVia;
37
+ } | {
38
+ kind: 'refuse';
39
+ savedAt: string;
40
+ syncedAt: string;
41
+ savedS3Key: string;
42
+ };
43
+ /** What save-deck does, given the folder's marker and the server's current saved source. */
44
+ export declare function decideSavePrecondition(marker: WebSourceSyncMarker | null, server: ServerSourceVersion | null, force: boolean): SavePrecondition;
45
+ export declare function fetchServerSourceVersion(deckId: string): Promise<ServerSourceVersion | null>;
46
+ /** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
47
+ export declare function humanTime(iso: string): string;
48
+ /** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
49
+ export declare const EXIT_SAVED_DECK_NEWER = 5;
50
+ export declare const SAVE_REFUSED_PREFIX = "CASTLE_SAVE_REFUSED ";
51
+ export declare const SAVED_DECK_NEWER_CODE = "SAVED_DECK_NEWER";
52
+ /** Ghost's code when its own check (primary, under lock) refuses the source commit. */
53
+ export declare const WEB_DECK_SOURCE_STALE_CODE = "WEB_DECK_SOURCE_STALE";
54
+ export interface SaveRefusal {
55
+ savedAt: string | null;
56
+ syncedAt: string | null;
57
+ savedS3Key: string | null;
58
+ }
59
+ /** The single machine-readable stdout line castle-www parses from a refused save. */
60
+ export declare function saveRefusedLine(refusal: SaveRefusal): string;
61
+ export declare function saveRefusedMessage(dir: string, refusal: SaveRefusal): string;
62
+ export type SourceStatus = 'in-sync' | 'saved-newer' | 'lag' | 'no-marker' | 'no-source' | 'no-deck';
63
+ export interface SourceStatusResult {
64
+ deckId: string | null;
65
+ status: SourceStatus;
66
+ marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
67
+ server: ServerSourceVersion | null;
68
+ adopted?: true;
69
+ notified?: true;
70
+ }
71
+ export interface SourceStatusOptions {
72
+ adopt?: boolean;
73
+ notify?: boolean;
74
+ /** Injected by tests; defaults to the webDeckSource query. */
75
+ fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
76
+ now?: () => Date;
77
+ }
78
+ export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
79
+ notice: string;
80
+ instruction: string;
81
+ };
82
+ export declare function sourceStatus(dir: string, opts?: SourceStatusOptions): Promise<SourceStatusResult>;
83
+ export declare function describeSourceStatus(result: SourceStatusResult): string;