castle-web-cli 0.4.134 → 0.4.135

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.
@@ -14,6 +14,7 @@ export interface CastleJson {
14
14
  agent?: {
15
15
  plan?: 'on' | 'off';
16
16
  };
17
+ importWhenRemixed?: boolean;
17
18
  starterScene?: string;
18
19
  [key: string]: unknown;
19
20
  }
package/dist/index.js CHANGED
@@ -88,6 +88,7 @@ function getWsPort(dir) {
88
88
  function usage() {
89
89
  console.log(`Usage:
90
90
  castle-web init <dir> [--kit NAME] (kits: physics-2d (default), physics-3d, none)
91
+ castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] (starts from a published deck instead of a kit)
91
92
  castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
92
93
  castle-web restart [--port PORT]
93
94
  castle-web screenshot [--out FILE] [--port PORT]
@@ -124,11 +125,19 @@ async function main() {
124
125
  case 'init': {
125
126
  const dir = findPositionalDir();
126
127
  if (dir === '.') {
127
- console.error('Usage: castle-web init <dir> [--kit NAME]');
128
+ console.error('Usage: castle-web init <dir> [--kit NAME | --remix DECK_ID]');
128
129
  process.exit(1);
129
130
  }
130
131
  const kit = getFlagValue('--kit');
131
- await init(dir, { kit, serve: !hasFlag('--no-serve') });
132
+ await init(dir, {
133
+ kit,
134
+ serve: !hasFlag('--no-serve'),
135
+ remixOf: getFlagValue('--remix'),
136
+ // The identity the server minted for this remix. Omitted outside the
137
+ // cloud flow, where the next save-deck creates a deck of its own.
138
+ deckId: getFlagValue('--deck-id'),
139
+ cardId: getFlagValue('--card-id'),
140
+ });
132
141
  break;
133
142
  }
134
143
  case 'serve': {
package/dist/init.d.ts CHANGED
@@ -13,4 +13,9 @@ export declare function writeStarterTheme(projectDir: string, kitDir: string): v
13
13
  export declare function init(dir: string, opts?: {
14
14
  kit?: string;
15
15
  serve?: boolean;
16
+ /** Remix this published deck instead of starting from a kit. */
17
+ remixOf?: string;
18
+ /** The identity the server already minted for a remix. */
19
+ deckId?: string;
20
+ cardId?: string;
16
21
  }): Promise<void>;
package/dist/init.js CHANGED
@@ -3,7 +3,8 @@ import * as path from 'path';
3
3
  import { COMMON_INSTRUCTIONS } from './commonInstructions.js';
4
4
  import { installDeps } from './install.js';
5
5
  import { deckMainFile, deckStarterScene } from './castleJson.js';
6
- import { IMPORTS_DIR, lockImportTree } from './imports.js';
6
+ import { addImportTo, IMPORTS_DIR, lockImportTree } from './imports.js';
7
+ import { declaresImportWhenRemixed, fetchParentSource, moveSourceInto, writeRemixIdentity, } from './remix.js';
7
8
  import { getCliEntryPath, getKitsDir, getRepoRoot, getSdkPackagePath, toPosixPath, } from './localPaths.js';
8
9
  import { serve } from './serve.js';
9
10
  import { createVersion } from './versions.js';
@@ -457,6 +458,27 @@ function scaffoldFromKitImport(kit, projectDir) {
457
458
  // This is the ordinary save path with no parent -- `parentId: null` and every
458
459
  // file as an addition -- so the store has no special case for it. It composes
459
460
  // with the no-op rule for free: `save-version` straight after init records
461
+ // The import branch is deliberately thin: `addImportTo` already adopts a bare
462
+ // deck's entry point, starter scene and theme.
463
+ async function scaffoldFromRemix(parentDeckId, projectDir, identity) {
464
+ const stageDir = await fetchParentSource(parentDeckId);
465
+ let imported = false;
466
+ try {
467
+ if (declaresImportWhenRemixed(stageDir)) {
468
+ scaffoldBare(projectDir);
469
+ await addImportTo(projectDir, { deckRef: parentDeckId });
470
+ imported = true;
471
+ }
472
+ else {
473
+ moveSourceInto(stageDir, projectDir);
474
+ }
475
+ }
476
+ finally {
477
+ fs.rmSync(stageDir, { recursive: true, force: true });
478
+ }
479
+ writeRemixIdentity(projectDir, identity);
480
+ console.log(`Created project in ${projectDir}/ (${imported ? 'importing' : 'copied from'} deck ${parentDeckId})`);
481
+ }
460
482
  // nothing, so a fresh deck has exactly one version.
461
483
  //
462
484
  // The message is the only place a deck's kit lineage is recorded at all.
@@ -483,15 +505,27 @@ export async function init(dir, opts = {}) {
483
505
  console.error(`Directory "${dir}" is not empty.`);
484
506
  process.exit(1);
485
507
  }
508
+ if (opts.remixOf && opts.kit) {
509
+ console.error('Pass either --remix or --kit, not both.');
510
+ process.exit(1);
511
+ }
486
512
  const kit = opts.kit ?? DEFAULT_KIT;
487
513
  const bare = kit === 'none' || kit === 'bare';
488
- if (bare) {
514
+ if (opts.remixOf) {
515
+ await scaffoldFromRemix(opts.remixOf, projectDir, {
516
+ deckId: opts.deckId,
517
+ cardId: opts.cardId,
518
+ });
519
+ }
520
+ else if (bare) {
489
521
  scaffoldBare(projectDir);
490
522
  }
491
523
  else {
492
524
  scaffoldFromKitImport(kit, projectDir);
493
525
  }
494
- console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
526
+ if (!opts.remixOf) {
527
+ console.log(`Created project in ${projectDir}/${bare ? '' : ` (from kit "${kit}")`}`);
528
+ }
495
529
  // Always install deps so the deck is ready to serve/edit immediately.
496
530
  // `--no-serve` only skips the serve step below (callers like the cloud
497
531
  // launcher run their own serve, but still want deps in place).
@@ -514,7 +548,7 @@ export async function init(dir, opts = {}) {
514
548
  catch {
515
549
  console.error('dependency install failed; re-run `pnpm install` (or `npm install`) in the deck.');
516
550
  }
517
- saveInitialVersion(projectDir, bare ? null : kit);
551
+ saveInitialVersion(projectDir, opts.remixOf ?? (bare ? null : kit));
518
552
  const autoServe = opts.serve !== false;
519
553
  if (autoServe && installed) {
520
554
  // Call serve() with detach so init returns once the server is up. serve()
@@ -0,0 +1,18 @@
1
+ export interface RemixIdentity {
2
+ deckId?: string;
3
+ /** Without this a later save-deck mints a second card. */
4
+ cardId?: string;
5
+ }
6
+ /**
7
+ * Unpack the parent's saved source into a temp dir -- temp because whether these
8
+ * files are wanted at all depends on the castle.json among them.
9
+ */
10
+ export declare function fetchParentSource(parentDeckId: string): Promise<string>;
11
+ export declare function declaresImportWhenRemixed(sourceDir: string): boolean;
12
+ export declare function moveSourceInto(sourceDir: string, projectDir: string): void;
13
+ /**
14
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
15
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
16
+ * the next save-deck creates a fresh deck with no lineage.
17
+ */
18
+ export declare function writeRemixIdentity(projectDir: string, identity?: RemixIdentity): void;
package/dist/remix.js ADDED
@@ -0,0 +1,86 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import * as path from 'path';
4
+ import { nanoid } from 'nanoid';
5
+ import * as api from './api.js';
6
+ import { runTar } from './save-deck.js';
7
+ // Scaffolding a deck from another published deck, for `init --remix`.
8
+ // Dropped from the copied castle.json. `autoUpdateWhenImported` is the parent's
9
+ // promise to ITS importers, which a remix hasn't made.
10
+ const PARENT_ONLY_KEYS = [
11
+ 'deckId',
12
+ 'cardId',
13
+ 'title',
14
+ 'caption',
15
+ 'publishedVersion',
16
+ 'autoUpdateWhenImported',
17
+ ];
18
+ function readJson(file) {
19
+ if (!fs.existsSync(file))
20
+ return null;
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /**
29
+ * Unpack the parent's saved source into a temp dir -- temp because whether these
30
+ * files are wanted at all depends on the castle.json among them.
31
+ */
32
+ export async function fetchParentSource(parentDeckId) {
33
+ const source = await api.webDeckSource(parentDeckId);
34
+ if (!source) {
35
+ console.error(`Deck ${parentDeckId} has no saved source to remix. Only decks saved by the web CLI can be remixed.`);
36
+ process.exit(1);
37
+ }
38
+ console.log(`Fetching ${source.archiveUrl}`);
39
+ const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
40
+ if (!res.ok) {
41
+ throw new Error(`Archive fetch failed: HTTP ${res.status}`);
42
+ }
43
+ const buf = Buffer.from(await res.arrayBuffer());
44
+ console.log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
45
+ const stageDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-remix-'));
46
+ const tmpFile = path.join(os.tmpdir(), `castle-remix-${nanoid(8)}.tar.gz`);
47
+ fs.writeFileSync(tmpFile, buf);
48
+ try {
49
+ await runTar(['-xzf', tmpFile, '-C', stageDir]);
50
+ }
51
+ finally {
52
+ try {
53
+ fs.unlinkSync(tmpFile);
54
+ }
55
+ catch {
56
+ /* nothing to clean */
57
+ }
58
+ }
59
+ return stageDir;
60
+ }
61
+ export function declaresImportWhenRemixed(sourceDir) {
62
+ return readJson(path.join(sourceDir, 'castle.json'))?.importWhenRemixed === true;
63
+ }
64
+ export function moveSourceInto(sourceDir, projectDir) {
65
+ fs.mkdirSync(projectDir, { recursive: true });
66
+ for (const entry of fs.readdirSync(sourceDir)) {
67
+ fs.renameSync(path.join(sourceDir, entry), path.join(projectDir, entry));
68
+ }
69
+ }
70
+ /**
71
+ * Everything not in PARENT_ONLY_KEYS is kept -- `editor`, `imports`, `main` and
72
+ * whatever else the deck owns. With no identity passed (a local `init --remix`),
73
+ * the next save-deck creates a fresh deck with no lineage.
74
+ */
75
+ export function writeRemixIdentity(projectDir, identity = {}) {
76
+ const file = path.join(projectDir, 'castle.json');
77
+ const next = { ...(readJson(file) ?? {}) };
78
+ for (const key of PARENT_ONLY_KEYS)
79
+ delete next[key];
80
+ if (identity.deckId)
81
+ next.deckId = identity.deckId;
82
+ if (identity.cardId)
83
+ next.cardId = identity.cardId;
84
+ fs.mkdirSync(projectDir, { recursive: true });
85
+ fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf-8');
86
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.134",
3
+ "version": "0.4.135",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castle-web": "./dist/index.js"