decklight 0.4.0 → 0.6.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.
package/cli/init.mjs CHANGED
@@ -38,6 +38,7 @@
38
38
 
39
39
  import fs from 'node:fs';
40
40
  import path from 'node:path';
41
+ const { basename, relative } = path;
41
42
  import { pathToFileURL } from 'node:url';
42
43
  import { spawn, execFileSync } from 'node:child_process';
43
44
  import { createInterface } from 'node:readline/promises';
@@ -49,7 +50,10 @@ import { THEMES_DIR, themeCss, runtimeCss, runtimeJs } from './pkg.mjs';
49
50
  import { TARGETS, detectedTargets, installGlobalSkill, display } from './skills.mjs';
50
51
  import { onPath } from './agents.mjs';
51
52
  import { escapeHtml } from './edit.mjs';
52
- import { inGitRepo, createRepo, isIdentityError, oneline } from './git.mjs';
53
+ import {
54
+ classifyRemoteError, createRepo, foreignWarning, git as gitRun, inGitRepo, isIdentityError,
55
+ looksLikeGitUrl, noPromptEnv, oneline, remoteNames, splitDeckPaths,
56
+ } from './git.mjs';
53
57
  import { makeFail, runMain } from './util.mjs';
54
58
  import { isMain } from '../tools/args.mjs';
55
59
 
@@ -170,6 +174,123 @@ export function planGit({ args = [], tty = false, inRepo = false } = {}) {
170
174
  return { action: tty ? 'ask' : 'hint' };
171
175
  }
172
176
 
177
+ /** Everything committed here that is not the deck — what a push would carry. */
178
+ export function notTheDeck(root, deckPath, run = gitRun) {
179
+ try {
180
+ const tracked = run(['ls-files'], root).split('\n').filter(Boolean);
181
+ return splitDeckPaths(tracked, relative(root, deckPath)).foreign;
182
+ } catch { return []; }
183
+ }
184
+
185
+ /**
186
+ * Carry out whatever planRemote decided. Every failure is a NOTE, never an
187
+ * exit: the deck is the product, and a remote that could not be created is a
188
+ * line of advice rather than a reason to have failed the scaffold.
189
+ */
190
+ export async function offerRemote(plan, { root, note, askYes, question, exec = execFileSync }) {
191
+ const git = (args) => exec('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
192
+ const push = () => {
193
+ try {
194
+ exec('git', ['push', '-u', 'origin', 'HEAD'], {
195
+ cwd: root, stdio: 'ignore', timeout: 60_000, env: noPromptEnv(),
196
+ });
197
+ return null;
198
+ } catch (e) { return classifyRemoteError(e); }
199
+ };
200
+
201
+ if (plan.action === 'skip') return;
202
+ if (plan.action === 'hint') {
203
+ return note(' git: no remote — this history is only on this machine'
204
+ + ' (git remote add origin <url>, or --remote <url> next time)');
205
+ }
206
+
207
+ if (plan.action === 'set') {
208
+ if (!looksLikeGitUrl(plan.url)) {
209
+ return note(` git: "${plan.url}" does not look like a git remote URL — no remote added`);
210
+ }
211
+ try { git(['remote', 'add', 'origin', plan.url]); }
212
+ catch (e) { return note(` git: could not add the remote — ${oneline(e)}`); }
213
+ const why = push();
214
+ return note(why
215
+ ? ` git: origin added; the push failed (${why}) — retry with: git push -u origin HEAD`
216
+ : ' git: origin added and pushed — decklight publish turns this into a page');
217
+ }
218
+
219
+ if (plan.action === 'ask-gh') {
220
+ // PRIVATE, and the prompt says so. A public repository created off a
221
+ // default-yes prompt is a disclosure, not a convenience — and `gh repo edit
222
+ // --visibility public` is one command away for anyone who wants the
223
+ // opposite, which a second question here would not be worth.
224
+ const yes = await askYes(' create a PRIVATE GitHub repository and push this deck to it?'
225
+ + ` [${plan.defaultYes ? 'Y/n' : 'y/N'}] `, plan.defaultYes);
226
+ if (!yes) return note(' git: no remote — add one later with: gh repo create --source=. --push');
227
+ try {
228
+ exec('gh', ['repo', 'create', basename(root), '--private', '--source=.', '--remote', 'origin', '--push'],
229
+ { cwd: root, stdio: 'ignore', timeout: 120_000, env: noPromptEnv() });
230
+ return note(` git: created a private GitHub repository from ${basename(root)} and pushed`);
231
+ } catch (e) { return note(` git: gh could not create the repository — ${oneline(e)}`); }
232
+ }
233
+
234
+ // ask-url
235
+ const url = (await question(' paste a git remote URL so this deck is not only on this laptop'
236
+ + ' (blank to skip): ')).trim();
237
+ if (!url) return note(' git: no remote — add one later with: git remote add origin <url>');
238
+ if (!looksLikeGitUrl(url)) {
239
+ return note(' git: that does not look like a git remote URL — skipped'
240
+ + ' (git remote add origin <url> later)');
241
+ }
242
+ try { git(['remote', 'add', 'origin', url]); }
243
+ catch (e) { return note(` git: could not add the remote — ${oneline(e)}`); }
244
+ const why = push();
245
+ // The remote STAYS ADDED on a failed push — that is the durable half, and it
246
+ // is what makes the retry one command instead of two.
247
+ return note(why
248
+ ? ` git: origin added; the push failed (${why}) — retry with: git push -u origin HEAD`
249
+ : ' git: origin added and pushed — decklight publish turns this into a page');
250
+ }
251
+
252
+ /**
253
+ * Is `gh` here AND signed in? Both halves matter: `gh` installed but logged out
254
+ * is exactly the state that turns a helpful offer into a confusing failure.
255
+ */
256
+ export function ghReady(exec = execFileSync) {
257
+ if (!onPath('gh')) return false;
258
+ try {
259
+ exec('gh', ['auth', 'status'], {
260
+ stdio: 'ignore', timeout: 5000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
261
+ });
262
+ return true;
263
+ } catch { return false; }
264
+ }
265
+
266
+ /**
267
+ * Whether to offer a remote, and by which door. Pure, like planGit above.
268
+ *
269
+ * The two roads are `gh` (create the repository and push in one command) and a
270
+ * URL you paste, and which one is offered depends on whether `gh` is BOTH
271
+ * installed and logged in — `gh` present but signed out is exactly the state
272
+ * that turns a helpful offer into a confusing failure.
273
+ *
274
+ * `foreign` is how many files in the new repository are not the deck, and it
275
+ * only changes the DEFAULT: for a directory decklight just scaffolded the
276
+ * answer is almost certainly yes, and for one that already held somebody's
277
+ * work — where `git add -A` has just committed all of it — the answer should
278
+ * not be yes because they pressed return. Same question, different default,
279
+ * and the count is why.
280
+ */
281
+ export function planRemote({
282
+ args = [], tty = false, haveRepo = false, hasRemote = false, ghReady = false, foreign = 0,
283
+ } = {}) {
284
+ if (args.includes('--no-remote')) return { action: 'skip' };
285
+ const i = args.indexOf('--remote');
286
+ const url = i >= 0 ? args[i + 1] : null;
287
+ if (url && !url.startsWith('-')) return { action: 'set', url };
288
+ // Nothing to attach a remote to, or one is already attached.
289
+ if (!haveRepo || hasRemote) return { action: 'skip' };
290
+ if (!tty) return { action: 'hint' };
291
+ return { action: ghReady ? 'ask-gh' : 'ask-url', defaultYes: foreign === 0 };
292
+ }
293
+
173
294
  // ── the skill scope: project by default, global as a proposition ────────────
174
295
  // The same shape as planGit: a pure decision table over flags and the TTY
175
296
  // gate. --no-skill skips skill AND question, --global-skill preselects the
@@ -395,6 +516,8 @@ unless --no-skill is given. The deck file is only touched with --force.
395
516
  else if (a === '--open') openAfter = true;
396
517
  else if (a === '--no-skill' || a === '--global-skill') ; // consumed by planSkill below
397
518
  else if (a === '--git' || a === '--no-git') ; // consumed by planGit below
519
+ else if (a === '--remote') i++; // consumed by planRemote below
520
+ else if (a === '--no-remote') ; // likewise
398
521
  else if (!a.startsWith('-')) title = title ?? a;
399
522
  else fail(`unknown argument: ${a}`);
400
523
  }
@@ -426,7 +549,16 @@ unless --no-skill is given. The deck file is only touched with --force.
426
549
  rl.question(q).then(res, () => res(''));
427
550
  });
428
551
  };
429
- const askYes = async (q) => !/^n/i.test((await question(q)).trim());
552
+ // `defaultYes` is what a bare Enter means. It is a parameter rather than a
553
+ // constant because the remote question flips it: for a directory decklight
554
+ // scaffolded the answer is almost certainly yes, and for one that already
555
+ // held somebody's work — where `git add -A` has just committed all of it —
556
+ // it should not be yes because they pressed return.
557
+ const askYes = async (q, defaultYes = true) => {
558
+ const a = (await question(q)).trim();
559
+ if (!a) return defaultYes;
560
+ return defaultYes ? !/^n/i.test(a) : /^y/i.test(a);
561
+ };
430
562
 
431
563
  if (from && themesSel !== 'all') {
432
564
  // A template carries its own themes — it is a whole deck, not a body to
@@ -541,6 +673,34 @@ unless --no-skill is given. The deck file is only touched with --force.
541
673
  }
542
674
  else if (action === 'hint') note(' git: no repository here — pass --git to create one and auto-commit the deck');
543
675
 
676
+ // ── the remote offer — the deck exists nowhere else until this happens ───
677
+ // ONLY for a repository decklight just created. A repo that was already here
678
+ // is somebody else's — it may be a monorepo, a checkout, a subdirectory of
679
+ // something larger — and offering to publish it because a deck was scaffolded
680
+ // inside it would be presumptuous. decklight's repositories are decklight's
681
+ // to ask about; everyone else's are not.
682
+ if (action === 'create') {
683
+ const foreignFiles = notTheDeck(root, deckPath);
684
+ const remote = planRemote({
685
+ args: argv,
686
+ tty,
687
+ haveRepo: inGitRepo(root),
688
+ hasRemote: remoteNames(root).length > 0,
689
+ ghReady: (argv.includes('--remote') || !tty) ? false : ghReady(),
690
+ foreign: foreignFiles.length,
691
+ });
692
+ // What would actually be pushed, said BEFORE the question rather than
693
+ // discovered after it: `initRepo` runs `git add -A`, so a decklight init in
694
+ // a directory that already held work has just committed all of it.
695
+ if (['ask-gh', 'ask-url'].includes(remote.action) && foreignFiles.length) {
696
+ for (const line of foreignWarning(
697
+ { total: foreignFiles.length + 1, own: [], foreign: foreignFiles },
698
+ { verb: 'push', scope: 'everything in this directory' },
699
+ ) ?? []) note(` ${line}`);
700
+ }
701
+ await offerRemote(remote, { root, note, askYes, question });
702
+ }
703
+
544
704
  process.stdout.write(epilogue({ deckPath, tty: !!process.stdout.isTTY, noColor: !!process.env.NO_COLOR }));
545
705
 
546
706
  // last of the writes, so every "created/wrote" line is on screen before the
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // decklight marketplace add <owner/repo | git url | path> [--name x]
8
8
  // decklight marketplace list
9
- // decklight marketplace update <name>
9
+ // decklight marketplace update <name> [--branch <ref>]
10
10
  // decklight marketplace remove <name>
11
11
  //
12
12
  // A marketplace is a git repo (or a local directory) with
@@ -42,6 +42,9 @@ import { argReader, isMain } from '../tools/args.mjs';
42
42
  import { oneline } from './git.mjs';
43
43
 
44
44
  export const MANIFEST_PATH = '.decklight/marketplace.json';
45
+ /** A group heading, not a description. */
46
+ const MAX_TITLE = 60;
47
+
45
48
  export const NAME_RE = /^[A-Za-z0-9_-]+$/;
46
49
 
47
50
  /**
@@ -452,6 +455,22 @@ export function validateManifest(raw) {
452
455
  else if (typeof data.name !== 'string' || !NAME_RE.test(data.name)) {
453
456
  err('name', `${JSON.stringify(data.name)} — letters, digits, - and _ only (it names every entry: entry@${typeof data.name === 'string' ? data.name : 'name'})`);
454
457
  }
458
+ // `title` is the catalog's human name — what a theme picker draws as a group
459
+ // heading, since `name` is kebab by construction and `decklight-confluent` is
460
+ // an identifier rather than a word anyone says. Optional, and OLD DECKLIGHTS
461
+ // IGNORE IT: unknown top-level keys already validate, so a catalog can add
462
+ // one without waiting for anybody to upgrade.
463
+ //
464
+ // Loose on purpose — it is a display string, not an identifier — but not
465
+ // unbounded: 60 characters is generous for a heading, and an empty one is a
466
+ // refusal rather than a silently-empty attribute in somebody's deck.
467
+ if (data.title !== undefined) {
468
+ if (typeof data.title !== 'string' || !data.title.trim()) {
469
+ err('title', 'must be the catalog\'s human name, e.g. "Confluent" — or left out entirely');
470
+ } else if (data.title.trim().length > MAX_TITLE) {
471
+ err('title', `${data.title.trim().length} characters — a group heading, not a description (max ${MAX_TITLE})`);
472
+ }
473
+ }
455
474
  if (data.entries === undefined) err('entries', 'missing — an array of { name, type, source, description? }');
456
475
  else if (!Array.isArray(data.entries)) err('entries', 'must be an array');
457
476
  else {
@@ -515,6 +534,41 @@ export function classifySource(spec, { exists = existsSync } = {}) {
515
534
  export const cloneUrl = (src) =>
516
535
  (src.kind === 'github' ? `https://github.com/${src.owner}/${src.repo}.git` : src.url);
517
536
 
537
+ /**
538
+ * Is `ref` a branch or tag name safe to hand `git clone --branch`?
539
+ *
540
+ * An ALLOWLIST, and deliberately narrower than git's own rules. This value goes
541
+ * onto a command line as the argument to `--branch`, so the first thing it must
542
+ * not be is another option: a ref beginning with `-` would be read as one, and
543
+ * `--upload-pack` is a ref name as far as this function's caller knows.
544
+ * Everything else is `check-ref-format` in the cases that matter — `..` and
545
+ * `~^:?*[` are refspec syntax, a trailing `.lock` is how git names its own
546
+ * lockfiles, and a leading or trailing `/` is not a ref at all.
547
+ *
548
+ * A full commit SHA is refused ON PURPOSE and by a rule of its own, because it
549
+ * LOOKS like it should work: `git clone --branch <sha>` fails, since --branch
550
+ * takes a ref and a bare object name is not one. Fetching a commit means a
551
+ * second round trip and a checkout — a different shape from the single shallow
552
+ * clone everything here is built on. Saying so beats relaying a git error
553
+ * nobody asked for.
554
+ */
555
+ export const REF_RE = /^(?!-)(?!\.)(?!\/)[A-Za-z0-9][A-Za-z0-9._/-]*$/;
556
+ export function refProblem(ref) {
557
+ const r = String(ref ?? '');
558
+ if (!r) return 'is empty';
559
+ // hex-only and long enough to be an object name — `beef` and `add` are hex
560
+ // too, and they are also perfectly good branch names, so the length is what
561
+ // separates them
562
+ if (/^[0-9a-f]{7,40}$/i.test(r)) {
563
+ return 'looks like a commit — --branch takes a branch or a tag, not an object name';
564
+ }
565
+ if (!REF_RE.test(r)) return 'is not a branch or tag name';
566
+ if (r.includes('..') || r.endsWith('/') || r.endsWith('.lock') || /[~^:?*[\]\\ ]/.test(r)) {
567
+ return 'is not a branch or tag name';
568
+ }
569
+ return null;
570
+ }
571
+
518
572
  /**
519
573
  * What to say when git could not clone a marketplace.
520
574
  *
@@ -531,8 +585,16 @@ export const cloneUrl = (src) =>
531
585
  * so is the more useful sentence: it means the name or the access is the
532
586
  * problem, not the setup.
533
587
  */
534
- function cloneFailure(src, e, exec) {
535
- const why = `git clone ${cloneUrl(src)} failed — ${oneline(e)}`;
588
+ function cloneFailure(src, e, exec, ref = null) {
589
+ const why = `git clone ${cloneUrl(src)}${ref ? ` --branch ${ref}` : ''} failed — ${oneline(e)}`;
590
+ // The commonest failure once a ref is in play, and the one whose git wording
591
+ // ("Remote branch X not found in upstream origin") does not mention tags at
592
+ // all — so somebody who asked for a tag is told their tag does not exist as a
593
+ // branch, which is not what they got wrong.
594
+ if (ref && /remote branch .* not found|could not find remote branch/i.test(oneline(e))) {
595
+ return `${why}\n no branch or tag "${ref}" in ${src.spec}`
596
+ + '\n (a tag works here too — check the name, or drop --branch for the default)';
597
+ }
536
598
  // Offline is not an auth problem, and must not be answered as one: a plane
537
599
  // is a first-class place to run decklight, and the cache is still there.
538
600
  if (/could not resolve host|unable to access|connection (refused|timed out)|network is unreachable|SIGTERM/i.test(oneline(e))) {
@@ -605,19 +667,25 @@ export function hasGitCredential(url, exec = execFileSync) {
605
667
  * background `git pull` walks into, and keeps `~/.decklight/` from filling up
606
668
  * with nested repositories.
607
669
  */
608
- function cloneMarketplace(src, { exec, timeoutMs, stagingIn }) {
670
+ function cloneMarketplace(src, { exec, timeoutMs, stagingIn, ref = null }) {
609
671
  mkdirSync(stagingIn, { recursive: true });
610
672
  const dir = mkdtempSync(join(stagingIn, '.staging-'));
611
673
  const opts = { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs * 4, encoding: 'utf8' };
612
674
  try {
613
- exec('git', ['clone', '--quiet', '--depth', '1', cloneUrl(src), dir], {
675
+ // No --branch means the REMOTE's default branch, whatever it is called —
676
+ // nothing here has ever assumed `main` or `master`, so a repo whose default
677
+ // is `trunk` already worked. --branch takes a tag as happily as a branch; a
678
+ // tag simply lands detached, which costs nothing because `.git` is deleted
679
+ // below either way.
680
+ exec('git', ['clone', '--quiet', '--depth', '1',
681
+ ...(ref ? ['--branch', ref] : []), cloneUrl(src), dir], {
614
682
  ...opts,
615
683
  // never a password prompt: an unreachable private repo is an answer, not a hang
616
684
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
617
685
  });
618
686
  } catch (e) {
619
687
  rmSync(dir, { recursive: true, force: true });
620
- throw new MarketplaceError(cloneFailure(src, e, exec));
688
+ throw new MarketplaceError(cloneFailure(src, e, exec, ref));
621
689
  }
622
690
  try {
623
691
  const p = join(dir, MANIFEST_PATH);
@@ -643,15 +711,18 @@ function cloneMarketplace(src, { exec, timeoutMs, stagingIn }) {
643
711
  * the clone carries a timeout, and offline is an answer, not a hang (a plane
644
712
  * is a first-class place to run decklight).
645
713
  */
646
- export async function fetchManifest(src, { exec = execFileSync, timeoutMs = 8000, stagingIn } = {}) {
714
+ export async function fetchManifest(src, { exec = execFileSync, timeoutMs = 8000, stagingIn, ref = null } = {}) {
647
715
  if (src.kind === 'local') {
716
+ // A directory has no refs to choose between: it IS the checkout, read in
717
+ // place. Silently ignoring a --branch here would look like it worked.
718
+ if (ref) throw new MarketplaceError(`${src.spec} is a local directory — --branch needs a repository to clone`);
648
719
  if (!existsSync(src.root)) throw new MarketplaceError(`no such directory: ${src.spec}`);
649
720
  const p = join(src.root, MANIFEST_PATH);
650
721
  if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
651
722
  return { raw: readFileSync(p, 'utf8'), checkout: null, commit: null };
652
723
  }
653
724
  // staged beside the destination by default, so adopting it is a rename
654
- return cloneMarketplace(src, { exec, timeoutMs, stagingIn: stagingIn ?? join(configHome(), 'marketplaces') });
725
+ return cloneMarketplace(src, { exec, timeoutMs, ref, stagingIn: stagingIn ?? join(configHome(), 'marketplaces') });
655
726
  }
656
727
 
657
728
  /**
@@ -715,10 +786,17 @@ export function resolveEntry(ref, catalogs) {
715
786
  const USAGE = `usage: decklight marketplace <add|list|update|remove> …
716
787
 
717
788
  decklight marketplace add <owner/repo | git url | path> [--name <name>]
789
+ [--branch <ref>]
718
790
  clone the source, read ${MANIFEST_PATH} at its root, and register
719
791
  the catalog under ~/.decklight/ — a local path never touches the network
720
792
  EXAMPLE: decklight marketplace add decklight/decklight-plugins-official
721
793
  EXAMPLE: decklight marketplace add ../my-marketplace
794
+ EXAMPLE: decklight marketplace add acme/themes --branch v2.1.0
795
+
796
+ --branch takes a BRANCH OR A TAG. Without it you get the remote's default
797
+ branch, whatever it is called — decklight has never assumed main or master.
798
+ The ref is remembered, so update re-clones the same one: a catalog pinned
799
+ to a tag stays pinned until you say otherwise.
722
800
 
723
801
  the clone uses YOUR git credentials, so a private marketplace works the
724
802
  way git clone does in your terminal — and its entries install from that
@@ -728,8 +806,9 @@ const USAGE = `usage: decklight marketplace <add|list|update|remove> …
728
806
  every registered marketplace and its cached entries (as name@marketplace),
729
807
  read from the cache alone — list works on a plane
730
808
 
731
- decklight marketplace update <name>
809
+ decklight marketplace update <name> [--branch <ref>]
732
810
  re-clone a marketplace, refreshing the cached manifest and the checkout
811
+ (at the ref it was added with, unless --branch moves the pin)
733
812
  its entries install from; for a registered-not-fetched marketplace this is
734
813
  the FIRST fetch it ever gets
735
814
 
@@ -753,12 +832,19 @@ const entriesSummary = (name, entries) => {
753
832
 
754
833
  async function addMain(args, home) {
755
834
  const { opt } = argReader(args);
756
- const [spec] = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--name');
835
+ const [spec] = args.filter((a, i) => !a.startsWith('-')
836
+ && args[i - 1] !== '--name' && args[i - 1] !== '--branch');
757
837
  if (!spec) { console.error(`decklight marketplace add: needs an owner/repo, a git url, or a path\n\n${USAGE}`); return 1; }
758
838
 
839
+ // A branch or a TAG — a tag is what you reach for to pin a catalog to a
840
+ // known-good version, which is the whole reason this is not branches only.
841
+ const ref = opt('--branch') ?? null;
842
+ const bad = ref === null ? null : refProblem(ref);
843
+ if (bad) { console.error(`decklight marketplace add: --branch ${JSON.stringify(ref)} ${bad}`); return 1; }
844
+
759
845
  const src = classifySource(spec);
760
846
  let got;
761
- try { got = await fetchManifest(src, { stagingIn: join(home, 'marketplaces') }); } catch (e) {
847
+ try { got = await fetchManifest(src, { ref, stagingIn: join(home, 'marketplaces') }); } catch (e) {
762
848
  console.error(`decklight marketplace add: ${e.message}`);
763
849
  return 1;
764
850
  }
@@ -778,7 +864,12 @@ async function addMain(args, home) {
778
864
  console.error(` remove it first, or register this one under another name with --name`);
779
865
  return 1;
780
866
  }
781
- reg.marketplaces[name] = { ...(existing ?? {}), source: spec, commit: got.commit ?? undefined };
867
+ // The ref is REMEMBERED, so `update` re-clones the same one. Without that a
868
+ // catalog pinned to v1.2.0 would silently jump to the default branch the
869
+ // first time anybody refreshed it — which is the opposite of pinning.
870
+ reg.marketplaces[name] = {
871
+ ...(existing ?? {}), source: spec, ref: ref ?? undefined, commit: got.commit ?? undefined,
872
+ };
782
873
  writeCache(home, name, got.raw);
783
874
  const at = adoptCheckout(home, name, got.checkout);
784
875
  got.checkout = null;
@@ -808,8 +899,12 @@ function listMain(home) {
808
899
  // The commit is what the manifest AND every entry's files came from — one
809
900
  // clone, so there is a single answer to "which version of this catalog is
810
901
  // installed", and it is worth printing.
902
+ // The ref is shown BEFORE the commit, because they answer different
903
+ // questions: the ref is what you asked for and what `update` will fetch
904
+ // again, the commit is where that ref happened to point when it was cloned.
905
+ // A pinned catalog whose pin is invisible is one nobody remembers pinning.
811
906
  const head = `${name}${m.firstParty ? ' (first-party)' : ''} ${m.source}`
812
- + `${m.commit ? ` @${m.commit.slice(0, 7)}` : ''}`;
907
+ + `${m.ref ? ` #${m.ref}` : ''}${m.commit ? ` @${m.commit.slice(0, 7)}` : ''}`;
813
908
  const cached = loadCatalog(name, home);
814
909
  if (cached === null) {
815
910
  console.log(`${head} — registered, not fetched (decklight marketplace update ${name})`);
@@ -840,15 +935,24 @@ function listMain(home) {
840
935
  }
841
936
 
842
937
  async function updateMain(args, home) {
843
- const [name] = args.filter((a) => !a.startsWith('-'));
938
+ const [name] = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--branch');
844
939
  if (!name) { console.error(`decklight marketplace update: which one?\n\n${USAGE}`); return 1; }
845
940
  const reg = loadRegistry(home);
846
941
  const m = reg.marketplaces[name];
847
942
  if (!m) { console.error(`decklight marketplace update: no marketplace "${name}" (decklight marketplace list)`); return 1; }
848
943
 
849
944
  const first = loadCatalog(name, home) === null;
945
+ // --branch here RE-PINS: it is how you move a marketplace from one tag to the
946
+ // next without removing and re-adding it (which would lose the name it was
947
+ // registered under). With no flag, whatever was pinned before still holds.
948
+ const { opt } = argReader(args);
949
+ const asked = opt('--branch') ?? null;
950
+ const bad = asked === null ? null : refProblem(asked);
951
+ if (bad) { console.error(`decklight marketplace update: --branch ${JSON.stringify(asked)} ${bad}`); return 1; }
952
+ const ref = asked ?? m.ref ?? null;
953
+
850
954
  let got;
851
- try { got = await fetchManifest(classifySource(m.source), { stagingIn: join(home, 'marketplaces') }); } catch (e) {
955
+ try { got = await fetchManifest(classifySource(m.source), { ref, stagingIn: join(home, 'marketplaces') }); } catch (e) {
852
956
  console.error(`decklight marketplace update: ${name}: ${e.message}`);
853
957
  // The clone lands in staging and is adopted only once it validates, so a
854
958
  // failed update leaves BOTH halves of what is on disk untouched — the
@@ -864,10 +968,12 @@ async function updateMain(args, home) {
864
968
  got.checkout = null;
865
969
  const reg2 = loadRegistry(home);
866
970
  if (reg2.marketplaces[name]) {
867
- reg2.marketplaces[name] = { ...reg2.marketplaces[name], commit: got.commit ?? undefined };
971
+ reg2.marketplaces[name] = {
972
+ ...reg2.marketplaces[name], ref: ref ?? undefined, commit: got.commit ?? undefined,
973
+ };
868
974
  saveRegistry(reg2, home);
869
975
  }
870
- console.log(`${first ? 'fetched' : 'updated'} ${name} — ${entriesSummary(name, v.manifest.entries)}`);
976
+ console.log(`${first ? 'fetched' : 'updated'} ${name}${ref ? ` at ${ref}` : ''} — ${entriesSummary(name, v.manifest.entries)}`);
871
977
  if (at) console.log(` cloned to ${at}${got.commit ? ` (${got.commit.slice(0, 7)})` : ''}`);
872
978
  return 0;
873
979
  } finally {
@@ -13,7 +13,7 @@
13
13
  // EADDRINUSE, and proactively, by author BEFORE it spawns the edit child —
14
14
  // that child's stdin is closed (piped, not a TTY), so it could never ask.
15
15
 
16
- import { createConnection } from 'node:net';
16
+ import { createConnection, createServer } from 'node:net';
17
17
 
18
18
  /** Is something listening on `port`? Port 0 ("OS picks one") never conflicts. */
19
19
  export function isPortOpen(port, host = '127.0.0.1', timeout = 400) {
@@ -49,11 +49,46 @@ export async function shutdownEditServer(port, host = '127.0.0.1') {
49
49
  return !(await isPortOpen(port, host));
50
50
  }
51
51
 
52
- /** The next port at or after `port` that nothing is listening on. */
53
- export async function nextFreePort(port, host = '127.0.0.1') {
54
- let p = port;
55
- while (await isPortOpen(p, host)) p++;
56
- return p;
52
+ /**
53
+ * Can we actually LISTEN on this port?
54
+ *
55
+ * `isPortOpen` asks a different question — it connects, so it answers "is
56
+ * somebody there". For "may I have this port" that is the wrong question, and
57
+ * on Windows it is wrong in a way that fails: Hyper-V and WinNAT reserve blocks
58
+ * of ephemeral ports (`netsh int ipv4 show excludedportrange`), and a reserved
59
+ * port has NOTHING LISTENING on it. Connect is refused, `isPortOpen` says
60
+ * "free", and the bind that follows gets `EACCES` — a permission error, not
61
+ * `EADDRINUSE`, which is why it read as a crash rather than a busy port (#334).
62
+ *
63
+ * Binding is the only probe that answers the question being asked. It costs one
64
+ * listen/close per candidate, which is cheaper than the connect it replaces.
65
+ */
66
+ export function canBind(port, host = '127.0.0.1') {
67
+ return new Promise((done) => {
68
+ const server = createServer();
69
+ // Every reason a bind can fail is a reason to try the next port: taken
70
+ // (EADDRINUSE), reserved or privileged (EACCES), or an address this host
71
+ // does not have (EADDRNOTAVAIL). None of them become usable by waiting.
72
+ server.once('error', () => done(false));
73
+ server.once('listening', () => server.close(() => done(true)));
74
+ try { server.listen(port, host); } catch { done(false); }
75
+ });
76
+ }
77
+
78
+ /**
79
+ * The next port at or after `port` this process can actually bind.
80
+ *
81
+ * Bounded, because the failure it now catches can repeat: a Hyper-V reservation
82
+ * is a BLOCK of ports, often 16 or more, and an unbounded walk through one is
83
+ * indistinguishable from a hang. Giving up returns the original port so the
84
+ * caller fails with the real bind error rather than on a number this function
85
+ * invented.
86
+ */
87
+ export async function nextFreePort(port, host = '127.0.0.1', tries = 64) {
88
+ for (let p = port; p < port + tries && p <= 65535; p++) {
89
+ if (await canBind(p, host)) return p;
90
+ }
91
+ return port;
57
92
  }
58
93
 
59
94
  /**