decklight 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,21 +12,31 @@
12
12
  // A marketplace is a git repo (or a local directory) with
13
13
  // `.decklight/marketplace.json` at its root, mirroring Claude Code's layout
14
14
  // (MARKETPLACE.md MARKETPLACES). Registration lives under `~/.decklight/`:
15
- // one registry file (`marketplaces.json`) plus a `marketplaces/` directory of
16
- // cached manifests — the boring layout the engine wizard will share.
15
+ // one registry file (`marketplaces.json`) plus a `marketplaces/` directory
16
+ // holding, per marketplace, its cached manifest (`<name>.json`) and the
17
+ // CHECKOUT that manifest came with (`<name>/`) — the boring layout the engine
18
+ // wizard shares.
19
+ //
20
+ // A remote marketplace is read by CLONING it (MARKETPLACES#CLONE), never by
21
+ // fetching one file at a time off a raw-content host. That is what lets a
22
+ // private marketplace work at all — a clone uses the caller's own git
23
+ // credentials, an anonymous fetch has none — and it is also what makes an
24
+ // entry's files provably come from the same commit as the manifest that
25
+ // offered them.
17
26
  //
18
27
  // The invariant this module exists to keep (SPEC MARKETPLACE_REGISTRY): the
19
28
  // network is touched ONLY by an explicit `add` or `update` of a remote
20
29
  // source. Registering is a filesystem write; `list` reads only the cache;
21
- // nothing on the deck-load or presenting path imports this module at all. A
22
- // deck on conference wifi, on a plane, or air-gapped behaves identically to
23
- // one at a desk, marketplace or no marketplace.
30
+ // installing an entry reads the checkout; nothing on the deck-load or
31
+ // presenting path imports this module at all. A deck on conference wifi, on a
32
+ // plane, or air-gapped behaves identically to one at a desk, marketplace or
33
+ // no marketplace.
24
34
 
25
35
  import {
26
- existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync,
36
+ existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync,
27
37
  } from 'node:fs';
28
38
  import { execFileSync } from 'node:child_process';
29
- import { homedir, tmpdir } from 'node:os';
39
+ import { homedir } from 'node:os';
30
40
  import { join, resolve } from 'node:path';
31
41
  import { argReader, isMain } from '../tools/args.mjs';
32
42
  import { oneline } from './git.mjs';
@@ -73,6 +83,25 @@ export const configHome = (env = process.env) =>
73
83
  const registryPath = (home) => join(home, 'marketplaces.json');
74
84
  const cachePath = (home, name) => join(home, 'marketplaces', `${name}.json`);
75
85
 
86
+ /**
87
+ * The CHECKOUT a remote marketplace keeps beside its cached manifest
88
+ * (MARKETPLACES#CLONE): `~/.decklight/marketplaces/<name>/`, the working tree
89
+ * of the shallow clone `add`/`update` made, with its `.git` removed.
90
+ *
91
+ * It exists because an entry's `source` is repo-relative, and the two ways to
92
+ * turn that into bytes are not equivalent. A second unauthenticated fetch of
93
+ * `raw.githubusercontent.com` cannot see a private repo at all, and reads a
94
+ * ref that may have moved since the manifest was read; a file in the checkout
95
+ * came from the same clone as the manifest, over the caller's own git
96
+ * credentials. So the clone is what an install reads, and the network is not
97
+ * on the install path at all.
98
+ *
99
+ * A LOCAL marketplace has none — its directory already is the checkout, and
100
+ * copying somebody's working tree into the config home would give them a stale
101
+ * second copy of files they are editing.
102
+ */
103
+ export const checkoutPath = (home, name) => join(home, 'marketplaces', name);
104
+
76
105
  export function loadRegistry(home = configHome()) {
77
106
  const p = registryPath(home);
78
107
  if (!existsSync(p)) return { version: 1, marketplaces: {} };
@@ -461,11 +490,20 @@ export function validateManifest(raw) {
461
490
 
462
491
  // ── sources: owner/repo, git URL, local path ───────────────────────────────
463
492
 
464
- /** What kind of source a spec names. A path that exists always wins. */
493
+ /**
494
+ * What kind of source a spec names. A path that exists always wins.
495
+ *
496
+ * `github` is a shorthand for a CLONE, not for a raw-content host: it carries
497
+ * the owner and repo so a message can name the SSH form, and `cloneUrl` below
498
+ * is what it is actually read through.
499
+ */
465
500
  export function classifySource(spec, { exists = existsSync } = {}) {
466
501
  const gh = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(spec);
467
502
  if (gh) return { kind: 'github', owner: gh[1], repo: gh[2], spec };
468
- if (/^(git@|ssh:\/\/|git:\/\/|https?:\/\/)/.test(spec)) return { kind: 'git', url: spec, spec };
503
+ // `file://` is a git transport like any other (a bare mirror on a share, a
504
+ // fixture in a test) — and unlike a bare path, writing it means "clone this",
505
+ // not "read this directory in place".
506
+ if (/^(git@|ssh:\/\/|git:\/\/|file:\/\/|https?:\/\/)/.test(spec)) return { kind: 'git', url: spec, spec };
469
507
  if (/^[\w.-]+\/[\w.-]+$/.test(spec) && !spec.startsWith('.') && !exists(spec)) {
470
508
  const [owner, repo] = spec.split('/');
471
509
  return { kind: 'github', owner, repo, spec };
@@ -473,55 +511,164 @@ export function classifySource(spec, { exists = existsSync } = {}) {
473
511
  return { kind: 'local', root: resolve(spec), spec };
474
512
  }
475
513
 
476
- const fetchWhy = (e, timeoutMs) =>
477
- e.name === 'TimeoutError' || e.code === 'ABORT_ERR'
478
- ? `no response after ${timeoutMs / 1000}s`
479
- : String(e.cause?.code ?? e.cause?.message ?? e.message);
514
+ /** The URL git is handed for a remote source. */
515
+ export const cloneUrl = (src) =>
516
+ (src.kind === 'github' ? `https://github.com/${src.owner}/${src.repo}.git` : src.url);
480
517
 
481
518
  /**
482
- * The manifest text at a source's root. The only network in the subsystem —
483
- * and it fails FAST and says why: the fetch carries a timeout, git is told
484
- * never to prompt, and offline is an answer, not a hang (a plane is a
485
- * first-class place to run decklight).
519
+ * What to say when git could not clone a marketplace.
520
+ *
521
+ * The HTTPS form of a private repo fails here rather than 404ing somewhere
522
+ * unauthenticated, which is already the improvement — but "Repository not
523
+ * found" from a repo the user can see in their browser needs the missing half
524
+ * spelled out: decklight clones with the CALLER's git credentials, so the
525
+ * usual answer is that git has none for that host.
526
+ *
527
+ * Which it does not GUESS at. The setup instructions are printed when the
528
+ * machine actually needs them and withheld when it does not (`hasGitCredential`
529
+ * below), because advice that is wrong half the time is what teaches people to
530
+ * skim past the last line of an error. When git does have a credential, saying
531
+ * so is the more useful sentence: it means the name or the access is the
532
+ * problem, not the setup.
486
533
  */
487
- export async function fetchManifestText(src, { fetchImpl = fetch, exec = execFileSync, timeoutMs = 8000 } = {}) {
488
- if (src.kind === 'local') {
489
- if (!existsSync(src.root)) throw new MarketplaceError(`no such directory: ${src.spec}`);
490
- const p = join(src.root, MANIFEST_PATH);
491
- if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
492
- return readFileSync(p, 'utf8');
534
+ function cloneFailure(src, e, exec) {
535
+ const why = `git clone ${cloneUrl(src)} failed — ${oneline(e)}`;
536
+ // Offline is not an auth problem, and must not be answered as one: a plane
537
+ // is a first-class place to run decklight, and the cache is still there.
538
+ if (/could not resolve host|unable to access|connection (refused|timed out)|network is unreachable|SIGTERM/i.test(oneline(e))) {
539
+ return `${why}\n offline? the cached copy, if any, still serves \`marketplace list\``
540
+ + ' — and an already-cloned marketplace still installs.';
493
541
  }
494
- if (src.kind === 'github') {
495
- const url = `https://raw.githubusercontent.com/${src.owner}/${src.repo}/HEAD/${MANIFEST_PATH}`;
496
- let r;
497
- try {
498
- r = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
499
- } catch (e) {
500
- throw new MarketplaceError(`could not fetch ${src.spec} — ${fetchWhy(e, timeoutMs)}`
501
- + ' (offline? the cached copy, if any, still serves `marketplace list`)');
502
- }
503
- if (r.status === 404) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} (HTTP 404)`);
504
- if (!r.ok) throw new MarketplaceError(`could not fetch ${src.spec} — HTTP ${r.status}`);
505
- return await r.text();
542
+ // Named for GitHub only, because that is the only host whose SSH URL can be
543
+ // derived rather than guessed at.
544
+ const ssh = src.kind === 'github'
545
+ ? `\n Or add it by its SSH URL, which uses your keys instead of a helper:`
546
+ + `\n decklight marketplace add git@github.com:${src.owner}/${src.repo}.git`
547
+ : '';
548
+ const url = cloneUrl(src);
549
+ if (!/^https?:\/\//i.test(url)) {
550
+ // An SSH or git:// URL never consults a credential helper — the key is the
551
+ // credential, so pointing at helper setup here would be a wrong turn.
552
+ return `${why}\n decklight clones with your own git credentials; for an SSH URL that means`
553
+ + ' your key — `ssh -T git@github.com` says whether GitHub accepts it.';
554
+ }
555
+ const host = new URL(url).host;
556
+ if (hasGitCredential(url, exec)) {
557
+ return `${why}\n git does have a credential for ${host}, so this is not a setup problem:`
558
+ + '\n check the spelling, and that the account that credential belongs to can see'
559
+ + ` the repo.${ssh}`;
506
560
  }
507
- // an arbitrary git URL: shallow-clone somewhere disposable, read one file
508
- const tmp = mkdtempSync(join(tmpdir(), 'decklight-marketplace-'));
561
+ return `${why}\n git has no credential for ${host}, so this clone was anonymous — and a`
562
+ + '\n private repo answers an anonymous clone exactly as a missing one does.'
563
+ + '\n Configure a credential helper, then try again:'
564
+ + '\n gh auth setup-git (or the macOS Keychain, or git-credential-store)'
565
+ + ssh;
566
+ }
567
+
568
+ /**
569
+ * Does git already have a usable credential for this URL's host?
570
+ *
571
+ * `git credential fill` is the only honest way to ask. Reading
572
+ * `credential.helper` out of the config answers a different question and gets
573
+ * it wrong exactly where it matters: macOS ships a global `osxkeychain`
574
+ * helper, so "a helper is configured" is true on a machine that has never
575
+ * stored a GitHub credential in its life — the precise state that fails.
576
+ *
577
+ * Prompts are disabled on every axis (terminal, askpass), so this cannot hang
578
+ * or pop a dialog, and it is bounded by its own timeout. The credential it
579
+ * fills is DISCARDED unread: only the exit status is used, nothing is logged,
580
+ * nothing is returned. This runs only after a clone has already failed.
581
+ */
582
+ export function hasGitCredential(url, exec = execFileSync) {
583
+ const { GIT_ASKPASS, SSH_ASKPASS, ...env } = process.env;
509
584
  try {
510
- exec('git', ['clone', '--quiet', '--depth', '1', src.url, tmp], {
511
- stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs * 4,
585
+ const u = new URL(url);
586
+ exec('git', ['credential', 'fill'], {
587
+ input: `protocol=${u.protocol.replace(':', '')}\nhost=${u.host}\n\n`,
588
+ stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf8', timeout: 5000,
589
+ env: { ...env, GIT_TERMINAL_PROMPT: '0' },
590
+ });
591
+ return true;
592
+ } catch {
593
+ return false;
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Clone a remote marketplace into a fresh directory under `stagingIn` and read
599
+ * its manifest. Returns the working tree for the caller to ADOPT (see
600
+ * `adoptCheckout`) or discard — it is never left behind on a failure.
601
+ *
602
+ * `.git` is dropped once the commit is recorded: what decklight keeps is a
603
+ * checkout, not a repository. Nothing ever pulls into it — `update` re-clones
604
+ * — which is what keeps decklight out of the credential-helper trap a
605
+ * background `git pull` walks into, and keeps `~/.decklight/` from filling up
606
+ * with nested repositories.
607
+ */
608
+ function cloneMarketplace(src, { exec, timeoutMs, stagingIn }) {
609
+ mkdirSync(stagingIn, { recursive: true });
610
+ const dir = mkdtempSync(join(stagingIn, '.staging-'));
611
+ const opts = { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs * 4, encoding: 'utf8' };
612
+ try {
613
+ exec('git', ['clone', '--quiet', '--depth', '1', cloneUrl(src), dir], {
614
+ ...opts,
615
+ // never a password prompt: an unreachable private repo is an answer, not a hang
512
616
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
513
617
  });
514
- const p = join(tmp, MANIFEST_PATH);
618
+ } catch (e) {
619
+ rmSync(dir, { recursive: true, force: true });
620
+ throw new MarketplaceError(cloneFailure(src, e, exec));
621
+ }
622
+ try {
623
+ const p = join(dir, MANIFEST_PATH);
515
624
  if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
516
- return readFileSync(p, 'utf8');
625
+ const raw = readFileSync(p, 'utf8');
626
+ let commit = null;
627
+ try { commit = String(exec('git', ['rev-parse', 'HEAD'], { ...opts, cwd: dir })).trim(); } catch { /* not fatal */ }
628
+ rmSync(join(dir, '.git'), { recursive: true, force: true });
629
+ return { raw, checkout: dir, commit };
517
630
  } catch (e) {
518
- if (e instanceof MarketplaceError) throw e;
519
- throw new MarketplaceError(`git clone ${src.spec} failed — ${oneline(e)}`);
520
- } finally {
521
- rmSync(tmp, { recursive: true, force: true });
631
+ rmSync(dir, { recursive: true, force: true });
632
+ throw e;
522
633
  }
523
634
  }
524
635
 
636
+ /**
637
+ * A source's manifest, and the files it came with — the only network in the
638
+ * subsystem, reached only by an explicit `add` or `update`.
639
+ *
640
+ * Returns `{ raw, checkout, commit }`. `checkout` is a directory the caller
641
+ * must adopt or remove, and is null for a local source (whose own directory
642
+ * serves that role). It fails FAST and says why: git is told never to prompt,
643
+ * the clone carries a timeout, and offline is an answer, not a hang (a plane
644
+ * is a first-class place to run decklight).
645
+ */
646
+ export async function fetchManifest(src, { exec = execFileSync, timeoutMs = 8000, stagingIn } = {}) {
647
+ if (src.kind === 'local') {
648
+ if (!existsSync(src.root)) throw new MarketplaceError(`no such directory: ${src.spec}`);
649
+ const p = join(src.root, MANIFEST_PATH);
650
+ if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
651
+ return { raw: readFileSync(p, 'utf8'), checkout: null, commit: null };
652
+ }
653
+ // staged beside the destination by default, so adopting it is a rename
654
+ return cloneMarketplace(src, { exec, timeoutMs, stagingIn: stagingIn ?? join(configHome(), 'marketplaces') });
655
+ }
656
+
657
+ /**
658
+ * Put a freshly cloned working tree in place as `name`'s checkout, replacing
659
+ * whatever was there. A rename, not a copy, and the staging directory is a
660
+ * sibling of the destination — so the swap is one filesystem operation on one
661
+ * filesystem, and a half-written checkout is not a state that exists.
662
+ */
663
+ export function adoptCheckout(home, name, checkout) {
664
+ const dest = checkoutPath(home, name);
665
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
666
+ rmSync(dest, { recursive: true, force: true });
667
+ if (checkout === null) return null; // a local marketplace keeps none
668
+ renameSync(checkout, dest);
669
+ return dest;
670
+ }
671
+
525
672
  // ── the cache, and names ───────────────────────────────────────────────────
526
673
 
527
674
  /** The cached manifest for `name`: null when never fetched, else a validation. */
@@ -568,21 +715,26 @@ export function resolveEntry(ref, catalogs) {
568
715
  const USAGE = `usage: decklight marketplace <add|list|update|remove> …
569
716
 
570
717
  decklight marketplace add <owner/repo | git url | path> [--name <name>]
571
- read ${MANIFEST_PATH} at the source's root and register the catalog
572
- under ~/.decklight/ — a local path never touches the network
718
+ clone the source, read ${MANIFEST_PATH} at its root, and register
719
+ the catalog under ~/.decklight/ — a local path never touches the network
573
720
  EXAMPLE: decklight marketplace add decklight/decklight-plugins-official
574
721
  EXAMPLE: decklight marketplace add ../my-marketplace
575
722
 
723
+ the clone uses YOUR git credentials, so a private marketplace works the
724
+ way git clone does in your terminal — and its entries install from that
725
+ clone, at the commit the manifest came from
726
+
576
727
  decklight marketplace list
577
728
  every registered marketplace and its cached entries (as name@marketplace),
578
729
  read from the cache alone — list works on a plane
579
730
 
580
731
  decklight marketplace update <name>
581
- re-fetch a marketplace's manifest and refresh the cached copy; for a
582
- registered-not-fetched marketplace this is the FIRST fetch it ever gets
732
+ re-clone a marketplace, refreshing the cached manifest and the checkout
733
+ its entries install from; for a registered-not-fetched marketplace this is
734
+ the FIRST fetch it ever gets
583
735
 
584
736
  decklight marketplace remove <name>
585
- unregister a marketplace and drop its cached manifest
737
+ unregister a marketplace and drop its cached manifest and checkout
586
738
 
587
739
  registering is not fetching: the network is touched only by an explicit add
588
740
  or update, never when a deck loads or presents (SPEC MARKETPLACE_REGISTRY).
@@ -605,29 +757,38 @@ async function addMain(args, home) {
605
757
  if (!spec) { console.error(`decklight marketplace add: needs an owner/repo, a git url, or a path\n\n${USAGE}`); return 1; }
606
758
 
607
759
  const src = classifySource(spec);
608
- let raw;
609
- try { raw = await fetchManifestText(src); } catch (e) {
760
+ let got;
761
+ try { got = await fetchManifest(src, { stagingIn: join(home, 'marketplaces') }); } catch (e) {
610
762
  console.error(`decklight marketplace add: ${e.message}`);
611
763
  return 1;
612
764
  }
613
- const v = validateManifest(raw);
614
- if (!v.ok) { printManifestErrors('add', spec, v.errors); return 1; }
615
-
616
- const name = opt('--name') ?? v.manifest.name;
617
- if (!NAME_RE.test(name)) { console.error(`decklight marketplace add: "${name}" is not a usable marketplace name`); return 1; }
618
-
619
- const reg = loadRegistry(home);
620
- const existing = reg.marketplaces[name];
621
- if (existing && existing.source !== spec) {
622
- console.error(`decklight marketplace add: "${name}" is already registered from ${existing.source}`);
623
- console.error(` remove it first, or register this one under another name with --name`);
624
- return 1;
765
+ // Everything below either adopts the clone or drops it — a staging directory
766
+ // must not survive a refusal, so every early return passes through here.
767
+ try {
768
+ const v = validateManifest(got.raw);
769
+ if (!v.ok) { printManifestErrors('add', spec, v.errors); return 1; }
770
+
771
+ const name = opt('--name') ?? v.manifest.name;
772
+ if (!NAME_RE.test(name)) { console.error(`decklight marketplace add: "${name}" is not a usable marketplace name`); return 1; }
773
+
774
+ const reg = loadRegistry(home);
775
+ const existing = reg.marketplaces[name];
776
+ if (existing && existing.source !== spec) {
777
+ console.error(`decklight marketplace add: "${name}" is already registered from ${existing.source}`);
778
+ console.error(` remove it first, or register this one under another name with --name`);
779
+ return 1;
780
+ }
781
+ reg.marketplaces[name] = { ...(existing ?? {}), source: spec, commit: got.commit ?? undefined };
782
+ writeCache(home, name, got.raw);
783
+ const at = adoptCheckout(home, name, got.checkout);
784
+ got.checkout = null;
785
+ saveRegistry(reg, home);
786
+ console.log(`${existing ? 'refreshed' : 'registered'} ${name} from ${spec} — ${entriesSummary(name, v.manifest.entries)}`);
787
+ if (at) console.log(` cloned to ${at}${got.commit ? ` (${got.commit.slice(0, 7)})` : ''} — installing an entry reads it, not the network`);
788
+ return 0;
789
+ } finally {
790
+ if (got.checkout) rmSync(got.checkout, { recursive: true, force: true });
625
791
  }
626
- reg.marketplaces[name] = { ...(existing ?? {}), source: spec };
627
- writeCache(home, name, raw);
628
- saveRegistry(reg, home);
629
- console.log(`${existing ? 'refreshed' : 'registered'} ${name} from ${spec} — ${entriesSummary(name, v.manifest.entries)}`);
630
- return 0;
631
792
  }
632
793
 
633
794
  function writeCache(home, name, raw) {
@@ -644,7 +805,11 @@ function listMain(home) {
644
805
  }
645
806
  for (const name of names) {
646
807
  const m = reg.marketplaces[name];
647
- const head = `${name}${m.firstParty ? ' (first-party)' : ''} ${m.source}`;
808
+ // The commit is what the manifest AND every entry's files came from — one
809
+ // clone, so there is a single answer to "which version of this catalog is
810
+ // installed", and it is worth printing.
811
+ const head = `${name}${m.firstParty ? ' (first-party)' : ''} ${m.source}`
812
+ + `${m.commit ? ` @${m.commit.slice(0, 7)}` : ''}`;
648
813
  const cached = loadCatalog(name, home);
649
814
  if (cached === null) {
650
815
  console.log(`${head} — registered, not fetched (decklight marketplace update ${name})`);
@@ -682,17 +847,32 @@ async function updateMain(args, home) {
682
847
  if (!m) { console.error(`decklight marketplace update: no marketplace "${name}" (decklight marketplace list)`); return 1; }
683
848
 
684
849
  const first = loadCatalog(name, home) === null;
685
- let raw;
686
- try { raw = await fetchManifestText(classifySource(m.source)); } catch (e) {
850
+ let got;
851
+ try { got = await fetchManifest(classifySource(m.source), { stagingIn: join(home, 'marketplaces') }); } catch (e) {
687
852
  console.error(`decklight marketplace update: ${name}: ${e.message}`);
853
+ // The clone lands in staging and is adopted only once it validates, so a
854
+ // failed update leaves BOTH halves of what is on disk untouched — the
855
+ // cached manifest and the checkout its entries install from.
688
856
  if (!first) console.error(` the cached copy is untouched — list still works`);
689
857
  return 1;
690
858
  }
691
- const v = validateManifest(raw);
692
- if (!v.ok) { printManifestErrors('update', m.source, v.errors); return 1; }
693
- writeCache(home, name, raw);
694
- console.log(`${first ? 'fetched' : 'updated'} ${name} — ${entriesSummary(name, v.manifest.entries)}`);
695
- return 0;
859
+ try {
860
+ const v = validateManifest(got.raw);
861
+ if (!v.ok) { printManifestErrors('update', m.source, v.errors); return 1; }
862
+ writeCache(home, name, got.raw);
863
+ const at = adoptCheckout(home, name, got.checkout);
864
+ got.checkout = null;
865
+ const reg2 = loadRegistry(home);
866
+ if (reg2.marketplaces[name]) {
867
+ reg2.marketplaces[name] = { ...reg2.marketplaces[name], commit: got.commit ?? undefined };
868
+ saveRegistry(reg2, home);
869
+ }
870
+ console.log(`${first ? 'fetched' : 'updated'} ${name} — ${entriesSummary(name, v.manifest.entries)}`);
871
+ if (at) console.log(` cloned to ${at}${got.commit ? ` (${got.commit.slice(0, 7)})` : ''}`);
872
+ return 0;
873
+ } finally {
874
+ if (got.checkout) rmSync(got.checkout, { recursive: true, force: true });
875
+ }
696
876
  }
697
877
 
698
878
  function removeMain(args, home) {
@@ -704,6 +884,7 @@ function removeMain(args, home) {
704
884
  delete reg.marketplaces[name];
705
885
  saveRegistry(reg, home);
706
886
  rmSync(cachePath(home, name), { force: true });
887
+ rmSync(checkoutPath(home, name), { recursive: true, force: true });
707
888
  console.log(`removed ${name} — re-add any time with: decklight marketplace add ${m.source}`);
708
889
  return 0;
709
890
  }
package/cli/plugin.mjs CHANGED
@@ -555,7 +555,15 @@ async function addMain(args, home) {
555
555
  }
556
556
 
557
557
  const { resolveSource } = await import('./theme.mjs');
558
- const src = resolveSource(hit.entry.source, reg.marketplaces[hit.marketplace]?.source);
558
+ let src;
559
+ try {
560
+ src = resolveSource(hit.entry.source,
561
+ { name: hit.marketplace, source: reg.marketplaces[hit.marketplace]?.source }, home);
562
+ } catch (e) {
563
+ if (!(e instanceof MarketplaceError)) throw e;
564
+ console.error(`decklight plugin add: ${e.message}`);
565
+ return 1;
566
+ }
559
567
  let manifest;
560
568
  let files;
561
569
  try {
package/cli/present.mjs CHANGED
@@ -246,6 +246,14 @@ const USAGE = `usage: decklight present <deck.html|deck.decklight> [--port 8790]
246
246
  // `client` is the sigstore client — injectable for the same reason as
247
247
  // `bundleMain`'s: `undefined` means "go load the real one", an explicit stub
248
248
  // lets a test drive the verification states without the network.
249
+ /**
250
+ * A refusal that says which command refused. Every other command names itself
251
+ * — `decklight bundle: deck not found: …` — and present's three refusals did
252
+ * not, so a bare `deck not found:` in a terminal running several tools was the
253
+ * one message that could not be traced back to what printed it.
254
+ */
255
+ const fail = (msg) => { console.error(`decklight present: ${msg}`); return 1; };
256
+
249
257
  export async function presentMain(args, { client } = {}) {
250
258
  const positional = args.filter((a) => !a.startsWith('-'));
251
259
  if (args.includes('--help') || args.includes('-h') || !positional.length) {
@@ -267,17 +275,14 @@ export async function presentMain(args, { client } = {}) {
267
275
  const token = remote ? randomBytes(16).toString('base64url') : null;
268
276
 
269
277
  const deckPath = resolve(process.cwd(), positional[0]);
270
- if (!existsSync(deckPath)) {
271
- console.error(`deck not found: ${deckPath}`);
272
- return 1;
273
- }
278
+ if (!existsSync(deckPath)) return fail(`deck not found: ${deckPath}`);
274
279
  // A .decklight is the same deck with its signature and manifest stapled on
275
280
  // (DECK_FILE), so it is unwrapped here and everything below treats it exactly
276
281
  // like the HTML it wraps — same audit, same CSP, same strict rule. Nothing is
277
282
  // written to unwrap it: the payload is a slice of the bytes already read.
278
283
  let container = null;
279
284
  if (isContainer(deckPath)) {
280
- try { container = readContainer(deckPath); } catch (e) { console.error(e.message); return 1; }
285
+ try { container = readContainer(deckPath); } catch (e) { return fail(e.message); }
281
286
  }
282
287
  const payload = container ? container.payload : readFileSync(deckPath);
283
288
 
@@ -335,8 +340,7 @@ export async function presentMain(args, { client } = {}) {
335
340
  const rootArg = opt('--root');
336
341
  const root = rootArg ? resolve(process.cwd(), rootArg) : dirname(deckPath);
337
342
  if (!deckPath.startsWith(root + sep)) {
338
- console.error('deck must live under --root');
339
- return 1;
343
+ return fail('deck must live under --root');
340
344
  }
341
345
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
342
346
 
package/cli/theme.mjs CHANGED
@@ -22,6 +22,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
22
22
  import path, { resolve } from 'node:path';
23
23
  import { argReader, isMain } from '../tools/args.mjs';
24
24
  import { validateTheme, themeNameFrom, validThemeName, REQUIRED } from '../tools/theme-check.mjs';
25
+ import { checkoutPath, classifySource, configHome, MarketplaceError } from './marketplace.mjs';
25
26
 
26
27
  const USAGE = `usage: decklight theme <check|add> …
27
28
 
@@ -82,29 +83,46 @@ export function installTheme(html, name, css) {
82
83
  *
83
84
  * A manifest says `./themes/nord-deep.css`, which is relative to the
84
85
  * MARKETPLACE — and by the time the catalog is a cached JSON file, the repo it
85
- * came from is not the cwd of whoever is installing. The registry records each
86
- * marketplace's source, so that is what a relative entry resolves against:
87
- * a local path joins, `owner/repo` becomes a raw URL on the default branch.
86
+ * came from is not the cwd of whoever is installing. So a relative entry
87
+ * resolves against what `marketplace add`/`update` left on disk for that
88
+ * marketplace: the CHECKOUT it cloned (MARKETPLACES#CLONE), or, for a local
89
+ * marketplace, the directory it was registered from.
88
90
  *
89
- * This lives in theme.mjs rather than in the author server on purpose. Fetching
91
+ * It used to build a `raw.githubusercontent.com` URL instead, and that was the
92
+ * private-marketplace bug in one line: the manifest could be read with the
93
+ * caller's git credentials while every entry's bytes were fetched with none,
94
+ * so a private catalog listed correctly and then 404'd on every install. It
95
+ * also read a moving ref — the manifest at one HEAD, each artifact at another
96
+ * — so an install could match no single commit of the marketplace. Resolving
97
+ * into the checkout closes both: same commit, same credentials, no network.
98
+ *
99
+ * An ABSOLUTE `https://` source is still fetched as written: an entry may
100
+ * legitimately point at a gist or a release asset outside its own repo.
101
+ *
102
+ * This lives in theme.mjs rather than in the author server on purpose. Reading
90
103
  * an ARTIFACT on an explicit install is fine anywhere; fetching a CATALOG is
91
104
  * what `registered, not fetched` forbids on a deck-serving path, and keeping the
92
105
  * two in different files is what keeps the sweep in test/marketplace.test.mjs
93
106
  * able to tell them apart.
107
+ *
108
+ * @param {string} source the entry's `source`, as the manifest wrote it
109
+ * @param {{name?: string, source?: string}} marketplace registry name + registered source
94
110
  */
95
- export function resolveSource(source, marketplaceSource) {
111
+ export function resolveSource(source, marketplace, home = configHome()) {
96
112
  if (/^https?:\/\//i.test(source)) return source; // absolute already
97
113
  const rel = source.replace(/^\.\//, '');
98
- if (!marketplaceSource) return source; // nothing to resolve against
99
- if (/^https?:\/\//i.test(marketplaceSource)) {
100
- return `${marketplaceSource.replace(/\.git$/, '').replace(/\/$/, '')}/raw/HEAD/${rel}`;
101
- }
102
- if (/^[\w.-]+\/[\w.-]+$/.test(marketplaceSource)) {
103
- // owner/repo — GitHub's raw host, HEAD so a marketplace is not pinned to a
104
- // branch name we guessed at.
105
- return `https://raw.githubusercontent.com/${marketplaceSource}/HEAD/${rel}`;
114
+ const { name, source: from } = marketplace ?? {};
115
+ if (name) {
116
+ const checkout = checkoutPath(home, name);
117
+ if (existsSync(checkout)) return path.join(checkout, rel);
106
118
  }
107
- return path.resolve(marketplaceSource, rel); // a local marketplace
119
+ if (!from) return source; // nothing to resolve against
120
+ if (classifySource(from).kind === 'local') return path.resolve(from, rel);
121
+ // Registered from a remote source with nothing cloned: the entry is real and
122
+ // its bytes are simply not here yet. Naming the one command that fixes it
123
+ // beats a fetch that would only work for a public repo (SPEC MARKETPLACE_REGISTRY).
124
+ throw new MarketplaceError(`${name ?? from} has no local checkout, so "${source}" cannot be read`
125
+ + `\n its files arrive with the marketplace itself: decklight marketplace update ${name ?? ''}`.trimEnd());
108
126
  }
109
127
 
110
128
  /** Read a theme from disk or over https. */
package/cli/units.mjs CHANGED
@@ -68,12 +68,14 @@ export const UNIT_TYPES = {
68
68
  required: [],
69
69
  },
70
70
  // `pinned` marks the kinds that are Node code the loader runs unsandboxed
71
- // at author privilege (EXTENSIONS#LOADER): their `source` resolves against
72
- // a moving ref (`resolveSource` deliberately fetches HEAD), so an entry
73
- // installs only against the `sha256` its catalog admitted — refused before
74
- // any fetch without one, refused before any write on a mismatch (SPEC
75
- // UNIT_PINNING). Data kinds stay unpinned: a theme re-passes its whole
76
- // contract at `theme add`, and nothing in a template or skill executes.
71
+ // at author privilege (EXTENSIONS#LOADER): their `source` resolves into a
72
+ // checkout cloned at whatever the marketplace's default branch pointed to
73
+ // when it was last added or updated — later than the admission that screened
74
+ // the code — so an entry installs only against the `sha256` its catalog
75
+ // admitted: refused before any read without one, refused before any write on
76
+ // a mismatch (SPEC UNIT_PINNING). Data kinds stay unpinned: a theme
77
+ // re-passes its whole contract at `theme add`, and nothing in a template or
78
+ // skill executes.
77
79
  importer: {
78
80
  dir: 'importers',
79
81
  files: ['importer.mjs'],
@@ -343,8 +345,18 @@ export async function installUnit(type, ref, home = configHome(), { fetchImpl =
343
345
  : ''));
344
346
  }
345
347
 
348
+ // An entry's `source` is relative to its marketplace, which by now is a
349
+ // CHECKOUT on disk (MARKETPLACES#CLONE) — so for everything but an absolute
350
+ // URL, installing a unit reads files rather than reaching the network.
346
351
  const { resolveSource } = await import('./theme.mjs');
347
- const base = resolveSource(hit.entry.source, reg.marketplaces[hit.marketplace]?.source);
352
+ let base;
353
+ try {
354
+ base = resolveSource(hit.entry.source,
355
+ { name: hit.marketplace, source: reg.marketplaces[hit.marketplace]?.source }, home);
356
+ } catch (e) {
357
+ if (e instanceof MarketplaceError) throw new UnitError(e.message);
358
+ throw e;
359
+ }
348
360
 
349
361
  // Fetch first, write second.
350
362
  const fetched = [];