edhvault-mcp 0.2.24 → 0.2.25

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.
Files changed (3) hide show
  1. package/README.md +6 -3
  2. package/dist/cli.js +1403 -33
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -458,6 +458,35 @@ var init_build = __esm({
458
458
  }
459
459
  });
460
460
 
461
+ // ../src/lib/deckPlan/deckSchema.ts
462
+ function minEditorOfRaw(raw) {
463
+ if (!raw) return 0;
464
+ const m = MIN_EDITOR_PREFIX.exec(raw);
465
+ return m ? Number(m[1]) : 0;
466
+ }
467
+ function minEditorOf(record2) {
468
+ if (!record2 || typeof record2 !== "object") return 0;
469
+ const v = record2[MIN_EDITOR_FIELD];
470
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : 0;
471
+ }
472
+ function canEditDeck(record2) {
473
+ return minEditorOf(record2) <= DECK_SCHEMA;
474
+ }
475
+ function isDeckRecordKey(key2) {
476
+ return DECK_RECORD_KEY.test(key2);
477
+ }
478
+ var DECK_SCHEMA, MIN_EDITOR_FIELD, MIN_EDITOR_PREFIX, DECK_RECORD_KEY, NEWER_DECK_MESSAGE;
479
+ var init_deckSchema = __esm({
480
+ "../src/lib/deckPlan/deckSchema.ts"() {
481
+ "use strict";
482
+ DECK_SCHEMA = 3;
483
+ MIN_EDITOR_FIELD = "minEditor";
484
+ MIN_EDITOR_PREFIX = /^\{"minEditor":(\d{1,6})[,}]/;
485
+ DECK_RECORD_KEY = /^deck-[123]-/;
486
+ NEWER_DECK_MESSAGE = "This deck was saved by a newer version of EDHVault. Reload to update before editing it.";
487
+ }
488
+ });
489
+
461
490
  // ../src/lib/storage.ts
462
491
  function replacer(_key, value) {
463
492
  if (value instanceof Map) {
@@ -532,7 +561,26 @@ function noteWrite(key2) {
532
561
  }
533
562
  }
534
563
  }
564
+ function refusesOlderDeckWrite(key2, incomingMinEditor) {
565
+ if (!isDeckRecordKey(key2)) return false;
566
+ let existing;
567
+ try {
568
+ existing = localStorage.getItem(PREFIX + key2);
569
+ } catch {
570
+ return false;
571
+ }
572
+ const need = minEditorOfRaw(existing);
573
+ if (need <= DECK_SCHEMA || incomingMinEditor >= need) return false;
574
+ for (const l of newerDeckListeners) {
575
+ try {
576
+ l(key2);
577
+ } catch {
578
+ }
579
+ }
580
+ return true;
581
+ }
535
582
  function saveJSON(key2, value) {
583
+ if (refusesOlderDeckWrite(key2, minEditorOf(value))) return false;
536
584
  try {
537
585
  localStorage.setItem(PREFIX + key2, JSON.stringify(value, replacer));
538
586
  noteStorageSuccess();
@@ -543,10 +591,11 @@ function saveJSON(key2, value) {
543
591
  return false;
544
592
  }
545
593
  }
546
- var VERSION, PREFIX, quotaFailure, quotaListeners, quotaFailureObserved, blockedStorage, blockedListeners, writeListeners, writeNoticesMuted;
594
+ var VERSION, PREFIX, quotaFailure, quotaListeners, quotaFailureObserved, blockedStorage, blockedListeners, writeListeners, writeNoticesMuted, newerDeckListeners;
547
595
  var init_storage = __esm({
548
596
  "../src/lib/storage.ts"() {
549
597
  "use strict";
598
+ init_deckSchema();
550
599
  VERSION = "v1";
551
600
  PREFIX = "ce-" + VERSION + "-";
552
601
  quotaFailure = null;
@@ -556,6 +605,7 @@ var init_storage = __esm({
556
605
  blockedListeners = /* @__PURE__ */ new Set();
557
606
  writeListeners = /* @__PURE__ */ new Set();
558
607
  writeNoticesMuted = 0;
608
+ newerDeckListeners = /* @__PURE__ */ new Set();
559
609
  }
560
610
  });
561
611
 
@@ -12753,7 +12803,7 @@ var require_react_development = __commonJS({
12753
12803
  var dispatcher = resolveDispatcher();
12754
12804
  return dispatcher.useLayoutEffect(create2, deps);
12755
12805
  }
12756
- function useCallback(callback, deps) {
12806
+ function useCallback2(callback, deps) {
12757
12807
  var dispatcher = resolveDispatcher();
12758
12808
  return dispatcher.useCallback(callback, deps);
12759
12809
  }
@@ -13520,7 +13570,7 @@ var require_react_development = __commonJS({
13520
13570
  exports.memo = memo2;
13521
13571
  exports.startTransition = startTransition;
13522
13572
  exports.unstable_act = act;
13523
- exports.useCallback = useCallback;
13573
+ exports.useCallback = useCallback2;
13524
13574
  exports.useContext = useContext;
13525
13575
  exports.useDebugValue = useDebugValue2;
13526
13576
  exports.useDeferredValue = useDeferredValue;
@@ -13878,6 +13928,12 @@ function cardTrendWindows(tuple2, asOf) {
13878
13928
  }
13879
13929
  return out;
13880
13930
  }
13931
+ function compareChange(a, b, dir) {
13932
+ if (a == null && b == null) return 0;
13933
+ if (a == null) return 1;
13934
+ if (b == null) return -1;
13935
+ return dir === "desc" ? b - a : a - b;
13936
+ }
13881
13937
 
13882
13938
  // ../src/lib/cardInsights.ts
13883
13939
  init_slug();
@@ -14116,6 +14172,45 @@ var ARCHETYPE_TAGS = [
14116
14172
  // targeted discard (Thoughtseize)
14117
14173
  ];
14118
14174
 
14175
+ // ../src/lib/formats.ts
14176
+ var FORMATS = [
14177
+ // Commander and its family first: this is a Commander site.
14178
+ { key: "commander", label: "Commander", group: "commander", aliases: ["edh"] },
14179
+ { key: "oathbreaker", label: "Oathbreaker", group: "commander" },
14180
+ { key: "paupercommander", label: "Pauper Commander", group: "commander", aliases: ["pdh", "pauperedh"] },
14181
+ { key: "duel", label: "Duel Commander", group: "commander", aliases: ["duelcommander", "dc"] },
14182
+ { key: "predh", label: "PreDH", group: "commander" },
14183
+ { key: "brawl", label: "Brawl", group: "commander", aliases: ["historicbrawl"] },
14184
+ { key: "standardbrawl", label: "Standard Brawl", group: "commander" },
14185
+ // Paper constructed.
14186
+ { key: "standard", label: "Standard", group: "constructed", aliases: ["std"] },
14187
+ { key: "pioneer", label: "Pioneer", group: "constructed" },
14188
+ { key: "modern", label: "Modern", group: "constructed" },
14189
+ { key: "legacy", label: "Legacy", group: "constructed" },
14190
+ { key: "vintage", label: "Vintage", group: "constructed" },
14191
+ { key: "pauper", label: "Pauper", group: "constructed" },
14192
+ { key: "premodern", label: "Premodern", group: "constructed" },
14193
+ { key: "oldschool", label: "Old School", group: "constructed" },
14194
+ { key: "penny", label: "Penny Dreadful", group: "constructed", aliases: ["pennydreadful"] },
14195
+ // MTG Arena only.
14196
+ { key: "alchemy", label: "Alchemy", group: "arena" },
14197
+ { key: "historic", label: "Historic", group: "arena" },
14198
+ { key: "timeless", label: "Timeless", group: "arena" },
14199
+ { key: "gladiator", label: "Gladiator", group: "arena" },
14200
+ { key: "competitivebrawl", label: "Competitive Brawl", group: "arena" }
14201
+ ];
14202
+ var BY_KEY = new Map(FORMATS.map((f) => [f.key, f]));
14203
+ var BY_SPELLING = /* @__PURE__ */ new Map();
14204
+ for (const f of FORMATS) {
14205
+ BY_SPELLING.set(f.key, f.key);
14206
+ for (const a of f.aliases ?? []) BY_SPELLING.set(a, f.key);
14207
+ }
14208
+ var UNLABELED_KEYS = /* @__PURE__ */ new Set(["future", "tlr"]);
14209
+ function resolveFormat(input2) {
14210
+ const k = input2.toLowerCase().replace(/[\s_-]+/g, "");
14211
+ return BY_SPELLING.get(k) ?? (UNLABELED_KEYS.has(k) ? k : null);
14212
+ }
14213
+
14119
14214
  // ../src/lib/edhrec/game-changers.ts
14120
14215
  init_slug();
14121
14216
  var GAME_CHANGER_NAMES = [
@@ -14361,7 +14456,6 @@ var UNAVAILABLE_OPS = {
14361
14456
  "Cube search": ["cube"],
14362
14457
  "Game-availability search": ["game"],
14363
14458
  "Printing-count search": ["prints", "sets", "paperprints", "papersets"],
14364
- "Format-legality search": ["f", "format", "banned", "restricted"],
14365
14459
  "EUR / TIX price search": ["eur", "tix", "cheapest"],
14366
14460
  "Art-tag search": ["art", "atag", "arttag"],
14367
14461
  "Printing-history search": ["in", "new"],
@@ -14613,6 +14707,11 @@ var SUPPORTED_OP_PREFIXES = /* @__PURE__ */ new Set([
14613
14707
  "produce",
14614
14708
  "mv",
14615
14709
  "cmc",
14710
+ "f",
14711
+ "format",
14712
+ "legal",
14713
+ "banned",
14714
+ "restricted",
14616
14715
  "owned",
14617
14716
  "name",
14618
14717
  "is",
@@ -14892,6 +14991,7 @@ function parseScryfallQuery(input2) {
14892
14991
  sets: [],
14893
14992
  finishes: [],
14894
14993
  treatments: [],
14994
+ legality: [],
14895
14995
  routes: [],
14896
14996
  keywords: [],
14897
14997
  isDerived: [],
@@ -14997,6 +15097,11 @@ function parseScryfallQuery(input2) {
14997
15097
  for (const c of parsed.value) if (!out.sets.includes(c)) out.sets.push(c);
14998
15098
  continue;
14999
15099
  }
15100
+ if (parsed.kind === "legality") {
15101
+ const v = parsed.value;
15102
+ if (!out.legality.some((l) => l.format === v.format && l.status === v.status)) out.legality.push(v);
15103
+ continue;
15104
+ }
15000
15105
  if (parsed.kind === "finish") {
15001
15106
  if (!out.finishes.includes(parsed.value)) out.finishes.push(parsed.value);
15002
15107
  continue;
@@ -15071,7 +15176,7 @@ function parseScryfallQuery(input2) {
15071
15176
  }
15072
15177
  function hasRunnableClause(q) {
15073
15178
  if (q.tree !== null) return true;
15074
- return q.text !== "" || q.exactName !== null || q.negated.length > 0 || q.color !== null || q.identity !== null || q.types.length > 0 || q.mv.length > 0 || q.mvParity !== null || q.year.length > 0 || q.edhrecRank.length > 0 || q.oracle.length > 0 || q.otags.length > 0 || q.otagsBroad.length > 0 || q.roles.length > 0 || q.sets.length > 0 || q.finishes.length > 0 || q.treatments.length > 0 || q.keywords.length > 0 || q.isDerived.length > 0 || q.rarities.length > 0 || q.rarityCmp.length > 0 || q.pow.length > 0 || q.tou.length > 0 || q.loy.length > 0 || q.produces !== null || q.price.length > 0 || q.ownership !== null || q.ub !== "include" || q.banned !== null || q.reserved !== null || q.commander !== null;
15179
+ return q.text !== "" || q.exactName !== null || q.negated.length > 0 || q.color !== null || q.identity !== null || q.types.length > 0 || q.mv.length > 0 || q.mvParity !== null || q.year.length > 0 || q.edhrecRank.length > 0 || q.oracle.length > 0 || q.otags.length > 0 || q.otagsBroad.length > 0 || q.roles.length > 0 || q.sets.length > 0 || q.finishes.length > 0 || q.treatments.length > 0 || q.legality.length > 0 || q.keywords.length > 0 || q.isDerived.length > 0 || q.rarities.length > 0 || q.rarityCmp.length > 0 || q.pow.length > 0 || q.tou.length > 0 || q.loy.length > 0 || q.produces !== null || q.price.length > 0 || q.ownership !== null || q.ub !== "include" || q.banned !== null || q.reserved !== null || q.commander !== null;
15075
15180
  }
15076
15181
  function negatedBroadSlugs(q) {
15077
15182
  const out = [];
@@ -15284,6 +15389,20 @@ function parseToken(token) {
15284
15389
  }
15285
15390
  return { kind: "set", value: parts };
15286
15391
  }
15392
+ for (const [p, status] of [
15393
+ ["format:", "legal"],
15394
+ ["legal:", "legal"],
15395
+ ["f:", "legal"],
15396
+ ["banned:", "banned"],
15397
+ ["restricted:", "restricted"]
15398
+ ]) {
15399
+ if (!lower.startsWith(p)) continue;
15400
+ const rhs = lower.slice(p.length);
15401
+ if (!rhs) return { kind: "warn", value: `empty format filter` };
15402
+ const format = resolveFormat(rhs);
15403
+ if (!format) return { kind: "warn", value: `unknown format: "${token}"` };
15404
+ return { kind: "legality", value: { format, status } };
15405
+ }
15287
15406
  const numToken = tryParseNumeric(lower);
15288
15407
  if (numToken) return numToken;
15289
15408
  for (const p of ["produces", "produce"]) {
@@ -15739,6 +15858,218 @@ function rawSlots(c) {
15739
15858
  // ../src/lib/edhrec/salt.ts
15740
15859
  init_slug();
15741
15860
 
15861
+ // ../src/lib/edhrec/salt.generated.ts
15862
+ var SALT_BY_NAME = /* @__PURE__ */ new Map([
15863
+ ["stasis", 3.053],
15864
+ ["armageddon", 2.982],
15865
+ ["winter orb", 2.927],
15866
+ ["the tabernacle at pendrell vale", 2.83],
15867
+ ["rhystic study", 2.817],
15868
+ ["tergrid, god of fright", 2.813],
15869
+ ["grand arbiter augustin iv", 2.759],
15870
+ ["vivi ornitier", 2.71],
15871
+ ["static orb", 2.706],
15872
+ ["ravages of war", 2.633],
15873
+ ["smothering tithe", 2.624],
15874
+ ["jokulhaups", 2.592],
15875
+ ["obliterate", 2.584],
15876
+ ["vorinclex, voice of hunger", 2.555],
15877
+ ["sunder", 2.517],
15878
+ ["thassa's oracle", 2.504],
15879
+ ["jin-gitaxias, core augur", 2.503],
15880
+ ["humility", 2.48],
15881
+ ["drannith magistrate", 2.474],
15882
+ ["the one ring", 2.446],
15883
+ ["devastation", 2.44],
15884
+ ["decree of annihilation", 2.389],
15885
+ ["opposition agent", 2.388],
15886
+ ["worldfire", 2.378],
15887
+ ["cyclonic rift", 2.353],
15888
+ ["toxrill, the corrosive", 2.325],
15889
+ ["winter moon", 2.325],
15890
+ ["farewell", 2.324],
15891
+ ["hokori, dust drinker", 2.319],
15892
+ ["rising waters", 2.311],
15893
+ ["fierce guardianship", 2.289],
15894
+ ["apocalypse", 2.286],
15895
+ ["sheoldred, the apocalypse", 2.28],
15896
+ ["blood moon", 2.238],
15897
+ ["gaea's cradle", 2.234],
15898
+ ["urza, lord high artificer", 2.231],
15899
+ ["smokestack", 2.219],
15900
+ ["expropriate", 2.215],
15901
+ ["jin-gitaxias, progress tyrant", 2.209],
15902
+ ["nether void", 2.182],
15903
+ ["tectonic break", 2.171],
15904
+ ["back to basics", 2.162],
15905
+ ["force of will", 2.153],
15906
+ ["braids, cabal minion", 2.148],
15907
+ ["notion thief", 2.137],
15908
+ ["edgar markov", 2.113],
15909
+ ["global ruin", 2.112],
15910
+ ["ruination", 2.111],
15911
+ ["mana breach", 2.108],
15912
+ ["yuriko, the tiger's shadow", 2.102],
15913
+ ["the legend of yangchen", 2.092],
15914
+ ["orcish bowmasters", 2.09],
15915
+ ["sen triplets", 2.076],
15916
+ ["deadpool, trading card", 2.061],
15917
+ ["narset, parter of veils", 2.057],
15918
+ ["glacial chasm", 2.039],
15919
+ ["aura shards", 2.038],
15920
+ ["mana drain", 2.025],
15921
+ ["kinnan, bonder prodigy", 2.024],
15922
+ ["mindslaver", 2.016],
15923
+ ["wake of destruction", 2.011],
15924
+ ["grave pact", 2.009],
15925
+ ["hullbreaker horror", 2.004],
15926
+ ["tsunami", 2.004],
15927
+ ["epicenter", 2.002],
15928
+ ["catastrophe", 1.996],
15929
+ ["the ur-dragon", 1.991],
15930
+ ["acid rain", 1.984],
15931
+ ["emrakul, the promised end", 1.978],
15932
+ ["overwhelming splendor", 1.972],
15933
+ ["blightsteel colossus", 1.971],
15934
+ ["void winnower", 1.968],
15935
+ ["prismari, the inspiration", 1.966],
15936
+ ["teferi's protection", 1.959],
15937
+ ["flashfires", 1.949],
15938
+ ["force of negation", 1.948],
15939
+ ["magus of the moon", 1.934],
15940
+ ["thieves' auction", 1.924],
15941
+ ["scrambleverse", 1.923],
15942
+ ["mana vortex", 1.922],
15943
+ ["impending disaster", 1.918],
15944
+ ["elesh norn, mother of machines", 1.917],
15945
+ ["boiling seas", 1.917],
15946
+ ["dictate of erebos", 1.912],
15947
+ ["thoughts of ruin", 1.909],
15948
+ ["ulamog, the defiler", 1.905],
15949
+ ["warp world", 1.902],
15950
+ ["time stretch", 1.898],
15951
+ ["boil", 1.887],
15952
+ ["demonic consultation", 1.88],
15953
+ ["torpor orb", 1.878],
15954
+ ["jodah, the unifier", 1.861],
15955
+ ["esper sentinel", 1.858],
15956
+ ["etali, primal conqueror", 1.852],
15957
+ ["improvisation capstone", 1.836],
15958
+ ["maha, its feathers night", 1.827],
15959
+ ["ad nauseam", 1.825],
15960
+ ["possessed portal", 1.824],
15961
+ ["consecrated sphinx", 1.821],
15962
+ ["rule of law", 1.815]
15963
+ ]);
15964
+ var SALT_BY_SLUG = /* @__PURE__ */ new Map([
15965
+ ["stasis", 3.053],
15966
+ ["armageddon", 2.982],
15967
+ ["winter-orb", 2.927],
15968
+ ["the-tabernacle-at-pendrell-vale", 2.83],
15969
+ ["rhystic-study", 2.817],
15970
+ ["tergrid-god-of-fright", 2.813],
15971
+ ["grand-arbiter-augustin-iv", 2.759],
15972
+ ["vivi-ornitier", 2.71],
15973
+ ["static-orb", 2.706],
15974
+ ["ravages-of-war", 2.633],
15975
+ ["smothering-tithe", 2.624],
15976
+ ["jokulhaups", 2.592],
15977
+ ["obliterate", 2.584],
15978
+ ["vorinclex-voice-of-hunger", 2.555],
15979
+ ["sunder", 2.517],
15980
+ ["thassas-oracle", 2.504],
15981
+ ["jin-gitaxias-core-augur", 2.503],
15982
+ ["humility", 2.48],
15983
+ ["drannith-magistrate", 2.474],
15984
+ ["the-one-ring", 2.446],
15985
+ ["devastation", 2.44],
15986
+ ["decree-of-annihilation", 2.389],
15987
+ ["opposition-agent", 2.388],
15988
+ ["worldfire", 2.378],
15989
+ ["cyclonic-rift", 2.353],
15990
+ ["toxrill-the-corrosive", 2.325],
15991
+ ["winter-moon", 2.325],
15992
+ ["farewell", 2.324],
15993
+ ["hokori-dust-drinker", 2.319],
15994
+ ["rising-waters", 2.311],
15995
+ ["fierce-guardianship", 2.289],
15996
+ ["apocalypse", 2.286],
15997
+ ["sheoldred-the-apocalypse", 2.28],
15998
+ ["blood-moon", 2.238],
15999
+ ["gaeas-cradle", 2.234],
16000
+ ["urza-lord-high-artificer", 2.231],
16001
+ ["smokestack", 2.219],
16002
+ ["expropriate", 2.215],
16003
+ ["jin-gitaxias-progress-tyrant", 2.209],
16004
+ ["nether-void", 2.182],
16005
+ ["tectonic-break", 2.171],
16006
+ ["back-to-basics", 2.162],
16007
+ ["force-of-will", 2.153],
16008
+ ["braids-cabal-minion", 2.148],
16009
+ ["notion-thief", 2.137],
16010
+ ["edgar-markov", 2.113],
16011
+ ["global-ruin", 2.112],
16012
+ ["ruination", 2.111],
16013
+ ["mana-breach", 2.108],
16014
+ ["yuriko-the-tigers-shadow", 2.102],
16015
+ ["the-legend-of-yangchen", 2.092],
16016
+ ["orcish-bowmasters", 2.09],
16017
+ ["sen-triplets", 2.076],
16018
+ ["deadpool-trading-card", 2.061],
16019
+ ["narset-parter-of-veils", 2.057],
16020
+ ["glacial-chasm", 2.039],
16021
+ ["aura-shards", 2.038],
16022
+ ["mana-drain", 2.025],
16023
+ ["kinnan-bonder-prodigy", 2.024],
16024
+ ["mindslaver", 2.016],
16025
+ ["wake-of-destruction", 2.011],
16026
+ ["grave-pact", 2.009],
16027
+ ["hullbreaker-horror", 2.004],
16028
+ ["tsunami", 2.004],
16029
+ ["epicenter", 2.002],
16030
+ ["catastrophe", 1.996],
16031
+ ["the-ur-dragon", 1.991],
16032
+ ["acid-rain", 1.984],
16033
+ ["emrakul-the-promised-end", 1.978],
16034
+ ["overwhelming-splendor", 1.972],
16035
+ ["blightsteel-colossus", 1.971],
16036
+ ["void-winnower", 1.968],
16037
+ ["prismari-the-inspiration", 1.966],
16038
+ ["teferis-protection", 1.959],
16039
+ ["flashfires", 1.949],
16040
+ ["force-of-negation", 1.948],
16041
+ ["magus-of-the-moon", 1.934],
16042
+ ["thieves-auction", 1.924],
16043
+ ["scrambleverse", 1.923],
16044
+ ["mana-vortex", 1.922],
16045
+ ["impending-disaster", 1.918],
16046
+ ["elesh-norn-mother-of-machines", 1.917],
16047
+ ["boiling-seas", 1.917],
16048
+ ["dictate-of-erebos", 1.912],
16049
+ ["thoughts-of-ruin", 1.909],
16050
+ ["ulamog-the-defiler", 1.905],
16051
+ ["warp-world", 1.902],
16052
+ ["time-stretch", 1.898],
16053
+ ["boil", 1.887],
16054
+ ["demonic-consultation", 1.88],
16055
+ ["torpor-orb", 1.878],
16056
+ ["jodah-the-unifier", 1.861],
16057
+ ["esper-sentinel", 1.858],
16058
+ ["etali-primal-conqueror", 1.852],
16059
+ ["improvisation-capstone", 1.836],
16060
+ ["maha-its-feathers-night", 1.827],
16061
+ ["ad-nauseam", 1.825],
16062
+ ["possessed-portal", 1.824],
16063
+ ["consecrated-sphinx", 1.821],
16064
+ ["rule-of-law", 1.815]
16065
+ ]);
16066
+
16067
+ // ../src/lib/edhrec/salt.ts
16068
+ function saltScoreForName(name) {
16069
+ if (!name) return void 0;
16070
+ return SALT_BY_NAME.get(name.toLowerCase()) ?? SALT_BY_SLUG.get(toEdhrecSlug(name));
16071
+ }
16072
+
15742
16073
  // ../src/lib/cardCatalog/applyCatalogFilters.ts
15743
16074
  function compileClauses(parsed, broadMatch, resolvers) {
15744
16075
  return {
@@ -15749,7 +16080,8 @@ function compileClauses(parsed, broadMatch, resolvers) {
15749
16080
  setMatch: resolvers.setMatch,
15750
16081
  finishMatch: resolvers.finishMatch,
15751
16082
  treatmentMatch: resolvers.treatmentMatch,
15752
- unresolvable: parsed.otagsBroad.length > 0 && !broadMatch || parsed.oracle.length > 0 && !resolvers.oracleText || parsed.sets.length > 0 && !resolvers.setMatch || parsed.finishes.length > 0 && !resolvers.finishMatch || parsed.treatments.length > 0 && !resolvers.treatmentMatch,
16083
+ legalityMatch: resolvers.legalityMatch,
16084
+ unresolvable: parsed.otagsBroad.length > 0 && !broadMatch || parsed.oracle.length > 0 && !resolvers.oracleText || parsed.sets.length > 0 && !resolvers.setMatch || parsed.finishes.length > 0 && !resolvers.finishMatch || parsed.treatments.length > 0 && !resolvers.treatmentMatch || parsed.legality.length > 0 && !resolvers.legalityMatch,
15753
16085
  negated: parsed.negated.map((n) => compileSub(n, resolvers))
15754
16086
  };
15755
16087
  }
@@ -15824,6 +16156,9 @@ function matchClauses(card, c) {
15824
16156
  if (parsed.treatments.length > 0) {
15825
16157
  if (!c.treatmentMatch || !c.treatmentMatch(card.oracleId, parsed.treatments)) return { pass: false };
15826
16158
  }
16159
+ if (parsed.legality.length > 0) {
16160
+ if (!c.legalityMatch || !c.legalityMatch(card.oracleId, parsed.legality)) return { pass: false };
16161
+ }
15827
16162
  if (parsed.keywords.length > 0) {
15828
16163
  const kws = card.keywords?.map((k) => k.toLowerCase());
15829
16164
  if (!kws || !parsed.keywords.every((k) => kws.includes(k))) return { pass: false };
@@ -15941,6 +16276,7 @@ function buildCatalogPredicate(filters) {
15941
16276
  setMatch,
15942
16277
  finishMatch,
15943
16278
  treatmentMatch,
16279
+ legalityMatch,
15944
16280
  alwaysIncludeBasics
15945
16281
  } = filters;
15946
16282
  const parsed = filters.parsedOverride ?? parseScryfallQuery(query);
@@ -15950,7 +16286,8 @@ function buildCatalogPredicate(filters) {
15950
16286
  oracleText: oracleText ?? null,
15951
16287
  setMatch: setMatch ?? null,
15952
16288
  finishMatch: finishMatch ?? null,
15953
- treatmentMatch: treatmentMatch ?? null
16289
+ treatmentMatch: treatmentMatch ?? null,
16290
+ legalityMatch: legalityMatch ?? null
15954
16291
  };
15955
16292
  const positive = compileClauses(parsed, otagBroadMatch ?? null, resolvers);
15956
16293
  const tree = parsed.tree ? compileTree(parsed.tree, resolvers) : null;
@@ -17281,6 +17618,7 @@ init_syncApi();
17281
17618
  init_aiMarks();
17282
17619
  init_syncHistory();
17283
17620
  init_storage();
17621
+ var PUBLIC_FLAG = "isPublic";
17284
17622
  function decodeViewHistory(raw) {
17285
17623
  if (!Array.isArray(raw)) return [];
17286
17624
  let revived;
@@ -47946,6 +48284,190 @@ function colorsFit(card, allowed) {
47946
48284
  return true;
47947
48285
  }
47948
48286
 
48287
+ // ../src/lib/ranking/rankCommanders.ts
48288
+ var SYNERGY_DENOM_FLOOR = 30;
48289
+ function buildOwnedSlugs(ownedOracleIds, cards) {
48290
+ const slugs = /* @__PURE__ */ new Set();
48291
+ for (const oid of ownedOracleIds) addOwnedSlugs(slugs, oid, cards);
48292
+ return slugs;
48293
+ }
48294
+ function addOwnedSlugs(slugs, oid, cards) {
48295
+ const card = cards.byOracleId.get(oid);
48296
+ if (!card) return;
48297
+ slugs.add(toEdhrecSlug(card.name));
48298
+ if (card.name.includes(" // ")) {
48299
+ slugs.add(toEdhrecSlug(card.name, { joined: true }));
48300
+ }
48301
+ }
48302
+ var scoreCaches = /* @__PURE__ */ new WeakMap();
48303
+ function scoreCacheFor(ownedOracleIds, cards) {
48304
+ const hit = scoreCaches.get(ownedOracleIds);
48305
+ if (hit && hit.cards === cards) return hit;
48306
+ const fresh = {
48307
+ cards,
48308
+ ownedSlugs: buildOwnedSlugs(ownedOracleIds, cards),
48309
+ bySummary: /* @__PURE__ */ new WeakMap()
48310
+ };
48311
+ scoreCaches.set(ownedOracleIds, fresh);
48312
+ return fresh;
48313
+ }
48314
+ function scoredRow(cache2, summary) {
48315
+ let row = cache2.bySummary.get(summary);
48316
+ if (!row) {
48317
+ row = scoreCommander(summary, cache2.ownedSlugs, cache2.cards);
48318
+ cache2.bySummary.set(summary, row);
48319
+ }
48320
+ return row;
48321
+ }
48322
+ function scoreCommander(summary, ownedSlugs, cards) {
48323
+ let synergyOwned = 0;
48324
+ for (const slug of summary.pool) {
48325
+ if (ownedSlugs.has(slug)) synergyOwned++;
48326
+ }
48327
+ const directCard = findCardByName(cards, summary.name);
48328
+ const looksLikePartner = !directCard && summary.name.includes(" // ");
48329
+ let commanderOwned = false;
48330
+ let partiallyOwned = false;
48331
+ const ownedParts = [];
48332
+ const missingParts = [];
48333
+ let primarySlim;
48334
+ let partnerSlim;
48335
+ if (looksLikePartner) {
48336
+ const parts = summary.name.split(" // ").map((s) => s.trim());
48337
+ parts.forEach((part2, idx) => {
48338
+ const partCard = findCardByName(cards, part2);
48339
+ if (idx === 0) primarySlim = partCard;
48340
+ else if (idx === 1) partnerSlim = partCard;
48341
+ const isOwned = partCard ? ownedSlugs.has(toEdhrecSlug(partCard.name)) : ownedSlugs.has(toEdhrecSlug(part2));
48342
+ if (isOwned) ownedParts.push(part2);
48343
+ else missingParts.push(part2);
48344
+ });
48345
+ commanderOwned = missingParts.length === 0 && ownedParts.length > 0;
48346
+ partiallyOwned = ownedParts.length > 0 && missingParts.length > 0;
48347
+ } else {
48348
+ commanderOwned = directCard ? ownedSlugs.has(toEdhrecSlug(directCard.name)) : ownedSlugs.has(summary.slug);
48349
+ primarySlim = directCard;
48350
+ }
48351
+ const poolSize = summary.pool.length;
48352
+ const denom = Math.max(poolSize, SYNERGY_DENOM_FLOOR);
48353
+ const synergyRatio = denom > 0 ? synergyOwned / denom : 0;
48354
+ return {
48355
+ commander: summary,
48356
+ synergyOwned,
48357
+ poolSize,
48358
+ synergyRatio,
48359
+ commanderOwned,
48360
+ partiallyOwned,
48361
+ ownedParts,
48362
+ missingParts,
48363
+ ...primarySlim ? { primarySlim } : {},
48364
+ ...partnerSlim ? { partnerSlim } : {},
48365
+ ...looksLikePartner ? { isPartnerPair: true } : {}
48366
+ };
48367
+ }
48368
+ function compareWeek(a, b) {
48369
+ const wa = a.commander.week;
48370
+ const wb = b.commander.week;
48371
+ if (wa && wb) return wb.decks - wa.decks || wa.rank - wb.rank;
48372
+ if (wa) return -1;
48373
+ if (wb) return 1;
48374
+ return b.commander.deckCount - a.commander.deckCount || b.synergyOwned - a.synergyOwned;
48375
+ }
48376
+ function commanderMatchesNameQuery(r, q) {
48377
+ if (normalizeForSearch(r.commander.name).includes(q)) return true;
48378
+ return [r.primarySlim, r.partnerSlim].some(
48379
+ (c) => c?.searchAltNamesNorm?.some((a) => a.includes(q)) === true
48380
+ );
48381
+ }
48382
+ function rankCommanders(summaries, ownedOracleIds, cards, opts = { sortBy: "synergy" }) {
48383
+ const cache2 = scoreCacheFor(ownedOracleIds, cards);
48384
+ let ranked = summaries.map((s) => scoredRow(cache2, s));
48385
+ if (opts.colors && opts.colors.length > 0) {
48386
+ const filter = new Set(opts.colors);
48387
+ const mode = opts.colorMode ?? "includes";
48388
+ ranked = ranked.filter(
48389
+ (r) => identityMatchesPips(r.commander.colors, filter, mode)
48390
+ );
48391
+ }
48392
+ if (opts.query) {
48393
+ const q = normalizeForSearch(opts.query);
48394
+ if (q) {
48395
+ ranked = ranked.filter((r) => commanderMatchesNameQuery(r, q));
48396
+ }
48397
+ }
48398
+ if (opts.brackets && opts.brackets.length > 0) {
48399
+ const allowed = new Set(opts.brackets);
48400
+ ranked = ranked.filter(
48401
+ (r) => r.commander.bracket !== void 0 && allowed.has(r.commander.bracket)
48402
+ );
48403
+ }
48404
+ if (opts.mvMin !== void 0 || opts.mvMax !== void 0) {
48405
+ const min = opts.mvMin ?? 0;
48406
+ const max = opts.mvMax ?? Number.POSITIVE_INFINITY;
48407
+ ranked = ranked.filter((r) => {
48408
+ const lookupName = r.commander.name.split(" // ")[0].toLowerCase();
48409
+ const card = cards.byName.get(lookupName) ?? cards.byFaceName.get(lookupName);
48410
+ if (!card) return true;
48411
+ return card.cmc >= min && card.cmc <= max;
48412
+ });
48413
+ }
48414
+ if (opts.saltMax !== void 0) {
48415
+ const max = opts.saltMax;
48416
+ ranked = ranked.filter((r) => {
48417
+ const lookupName = r.commander.name.split(" // ")[0];
48418
+ const score = saltScoreForName(lookupName);
48419
+ return score === void 0 || score <= max;
48420
+ });
48421
+ }
48422
+ const changeMemo = /* @__PURE__ */ new Map();
48423
+ const changeOfCommander = (r) => {
48424
+ if (!opts.changeOf) return void 0;
48425
+ const name = r.commander.name.split(" // ")[0];
48426
+ if (changeMemo.has(name)) return changeMemo.get(name);
48427
+ const card = resolveCardName(cards, name);
48428
+ const v = card ? opts.changeOf(card.oracleId) : void 0;
48429
+ changeMemo.set(name, v);
48430
+ return v;
48431
+ };
48432
+ const dir = opts.sortDir ?? "desc";
48433
+ const flip = (n) => dir === "desc" ? n : -n;
48434
+ const byPopularity2 = (a, b) => b.commander.deckCount - a.commander.deckCount || b.synergyOwned - a.synergyOwned;
48435
+ const byKnown = (va, vb, a, b) => {
48436
+ if (va !== void 0 && vb !== void 0) return flip(vb - va) || byPopularity2(a, b);
48437
+ if (va !== void 0) return -1;
48438
+ if (vb !== void 0) return 1;
48439
+ return byPopularity2(a, b);
48440
+ };
48441
+ ranked.sort((a, b) => {
48442
+ switch (opts.sortBy) {
48443
+ case "synergy":
48444
+ return flip(
48445
+ b.synergyRatio - a.synergyRatio || b.synergyOwned - a.synergyOwned || Number(b.commanderOwned) - Number(a.commanderOwned) || b.commander.deckCount - a.commander.deckCount
48446
+ );
48447
+ case "popularity":
48448
+ return flip(byPopularity2(a, b));
48449
+ case "salt":
48450
+ return byKnown(
48451
+ saltScoreForName(a.commander.name.split(" // ")[0]),
48452
+ saltScoreForName(b.commander.name.split(" // ")[0]),
48453
+ a,
48454
+ b
48455
+ );
48456
+ case "week": {
48457
+ const wa = a.commander.week;
48458
+ const wb = b.commander.week;
48459
+ if (wa && wb) return flip(wb.decks - wa.decks || wa.rank - wb.rank);
48460
+ return compareWeek(a, b);
48461
+ }
48462
+ case "change":
48463
+ return compareChange(changeOfCommander(a), changeOfCommander(b), dir) || byPopularity2(a, b);
48464
+ case "trending":
48465
+ return byKnown(a.commander.trend ?? void 0, b.commander.trend ?? void 0, a, b);
48466
+ }
48467
+ });
48468
+ return ranked;
48469
+ }
48470
+
47949
48471
  // ../src/lib/commanders/inclusionDenominator.ts
47950
48472
  function commanderInclusionDenominator(detail) {
47951
48473
  let denom = detail.deckCount ?? 0;
@@ -48202,6 +48724,10 @@ function buildDeckSlots(detail, ownedOracleIds, cards, opts = {}) {
48202
48724
  var CURVE_BUCKETS = ["0", "1", "2", "3", "4", "5", "6", "7+"];
48203
48725
  var CURVE_BUCKET_COUNT = CURVE_BUCKETS.length;
48204
48726
  var CURVE_TOP_BUCKET = CURVE_BUCKET_COUNT - 1;
48727
+ function bucketIndex(cmc) {
48728
+ const v = Math.max(0, Math.floor(cmc));
48729
+ return v >= CURVE_TOP_BUCKET ? CURVE_TOP_BUCKET : v;
48730
+ }
48205
48731
 
48206
48732
  // ../src/lib/ranking/curveTarget.ts
48207
48733
  var UNIVERSAL_COUNTS = [1, 6, 13, 13, 10, 8, 6, 6];
@@ -48216,6 +48742,22 @@ function normalizeToFractions(weights) {
48216
48742
  }
48217
48743
  return weights.map((w) => w / total);
48218
48744
  }
48745
+ function targetCounts(curve, total) {
48746
+ const n = curve.fractions.length;
48747
+ if (total <= 0) return new Array(n).fill(0);
48748
+ const exact = curve.fractions.map((f) => f * total);
48749
+ const floors = exact.map((x) => Math.floor(x));
48750
+ let used = floors.reduce((s, x) => s + x, 0);
48751
+ let remaining = total - used;
48752
+ const order = exact.map((x, i) => ({ i, frac: x - Math.floor(x) })).sort((a, b) => b.frac - a.frac);
48753
+ const counts = floors.slice();
48754
+ for (const { i } of order) {
48755
+ if (remaining <= 0) break;
48756
+ counts[i] += 1;
48757
+ remaining -= 1;
48758
+ }
48759
+ return counts;
48760
+ }
48219
48761
 
48220
48762
  // ../src/lib/deckPlan/importDeck.ts
48221
48763
  init_utils();
@@ -48604,7 +49146,7 @@ function buildImportNotices(stats, format, hasCommander, commanderKnown = false)
48604
49146
  function messageForKind(kind) {
48605
49147
  switch (kind) {
48606
49148
  case "not-found":
48607
- return "We couldn't find that deck. It may not exist, or it may be private. Archidekt doesn't tell us which.";
49149
+ return "We couldn't find that deck. It may not exist, or it may be private: Archidekt doesn't tell us which. If it's private, make it public on Archidekt, or paste the decklist text here instead.";
48608
49150
  case "unreachable":
48609
49151
  return "Couldn't reach Archidekt just now. Try again in a moment, or paste the decklist text instead.";
48610
49152
  case "empty":
@@ -49460,15 +50002,25 @@ function isTwoCardInfiniteCombo(v) {
49460
50002
  function comboKey(v) {
49461
50003
  return (v.uses ?? []).map((u) => u.card?.name?.trim().toLowerCase() ?? "").filter(Boolean).sort().join("|");
49462
50004
  }
49463
- function countTwoCardInfiniteCombos(included) {
50005
+ function listTwoCardInfiniteCombos(included) {
49464
50006
  const seen = /* @__PURE__ */ new Set();
50007
+ const out = [];
49465
50008
  for (const v of included) {
49466
50009
  if (!isTwoCardInfiniteCombo(v)) continue;
49467
50010
  const key2 = comboKey(v);
49468
50011
  if (!key2 || seen.has(key2)) continue;
49469
50012
  seen.add(key2);
50013
+ out.push({
50014
+ key: key2,
50015
+ cards: (v.uses ?? []).map((u) => u.card?.name ?? "").filter(Boolean),
50016
+ produces: (v.produces ?? []).map((p) => p.feature?.name ?? "").filter(Boolean),
50017
+ ...v.bracketTag ? { bracketTag: v.bracketTag } : {}
50018
+ });
49470
50019
  }
49471
- return seen.size;
50020
+ return out;
50021
+ }
50022
+ function countTwoCardInfiniteCombos(included) {
50023
+ return listTwoCardInfiniteCombos(included).length;
49472
50024
  }
49473
50025
 
49474
50026
  // ../src/lib/combos/deckCards.ts
@@ -53479,6 +54031,10 @@ function budgetStatus(spent, budget) {
53479
54031
  return { over: spent > budget, delta: spent - budget };
53480
54032
  }
53481
54033
 
54034
+ // ../src/lib/deckPlan/hooks/useDeckActions.ts
54035
+ var import_react2 = __toESM(require_react(), 1);
54036
+ init_utils();
54037
+
53482
54038
  // ../src/lib/deckPlan/karstenTable.generated.ts
53483
54039
  var KARSTEN_2022 = {
53484
54040
  landsFrom: 28,
@@ -53649,6 +54205,12 @@ function distributeBasics(pips, identity2, slotCount) {
53649
54205
  }
53650
54206
  return out;
53651
54207
  }
54208
+ var COLORLESS_BASICS_FLOOR = 7;
54209
+ function minBasics(colorCount) {
54210
+ if (colorCount === 0) return COLORLESS_BASICS_FLOOR;
54211
+ if (colorCount === 1) return 0;
54212
+ return Math.min(Math.max(2 * colorCount, 4), 6);
54213
+ }
53652
54214
  var BASIC_NAME = {
53653
54215
  W: "Plains",
53654
54216
  U: "Island",
@@ -53656,6 +54218,7 @@ var BASIC_NAME = {
53656
54218
  R: "Mountain",
53657
54219
  G: "Forest"
53658
54220
  };
54221
+ var WASTES_NAME = "Wastes";
53659
54222
  var KARSTEN_LANDS_RANGE = { min: KARSTEN_2022.landsFrom, max: KARSTEN_2022.landsTo };
53660
54223
  function karstenTarget(pips, mv, lands) {
53661
54224
  if (pips <= 0) return 0;
@@ -53722,6 +54285,17 @@ function cardTarget(card, color, lands) {
53722
54285
  const colours = WUBRG_ORDER.filter((c) => (p?.[c] ?? 0) > 0).length;
53723
54286
  return karstenTarget(pips, card.cmc, lands) + (colours >= 2 ? 1 : 0);
53724
54287
  }
54288
+ function karstenTargetsByColor(cards, lands) {
54289
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
54290
+ for (const c of cards) {
54291
+ if (!c.colorPips) continue;
54292
+ for (const color of WUBRG_ORDER) {
54293
+ const t = cardTarget(c, color, lands);
54294
+ if (t > out[color]) out[color] = t;
54295
+ }
54296
+ }
54297
+ return out;
54298
+ }
53725
54299
  function fetchableColors(fetch2, lands) {
53726
54300
  const out = /* @__PURE__ */ new Set();
53727
54301
  const f = fetch2.fetches;
@@ -53737,6 +54311,511 @@ function fetchableColors(fetch2, lands) {
53737
54311
  }
53738
54312
  return out;
53739
54313
  }
54314
+ function sourcesByColor(lands) {
54315
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
54316
+ for (const c of lands) {
54317
+ const pm = c.producedMana;
54318
+ if (!pm) continue;
54319
+ for (const color of WUBRG_ORDER) if (pm.includes(color)) out[color] += 1;
54320
+ }
54321
+ return out;
54322
+ }
54323
+ function nonBasicAllowance(colorCount) {
54324
+ switch (colorCount) {
54325
+ case 0:
54326
+ return 99;
54327
+ // colorless: no colored basics to reserve; Wastes floor is separate
54328
+ case 1:
54329
+ return 12;
54330
+ case 2:
54331
+ return 20;
54332
+ case 3:
54333
+ return 26;
54334
+ case 4:
54335
+ return 30;
54336
+ default:
54337
+ return 33;
54338
+ }
54339
+ }
54340
+ function distributeBasicsBySources(targets, supply, identity2, seats) {
54341
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
54342
+ if (seats <= 0) return out;
54343
+ const allowed = WUBRG_ORDER.filter((c) => identity2.includes(c));
54344
+ if (allowed.length === 0) return out;
54345
+ const demanded = allowed.filter((c) => targets[c] > 0);
54346
+ if (demanded.length === 0) {
54347
+ return distributeBasics({ W: 0, U: 0, B: 0, R: 0, G: 0 }, identity2, seats);
54348
+ }
54349
+ const running = { ...supply };
54350
+ let placed = 0;
54351
+ for (const c of demanded) {
54352
+ if (placed >= seats) break;
54353
+ if (running[c] <= 0) {
54354
+ out[c] += 1;
54355
+ running[c] += 1;
54356
+ placed += 1;
54357
+ }
54358
+ }
54359
+ for (; placed < seats; placed++) {
54360
+ let best = demanded[0];
54361
+ let bestDeficit = targets[best] - running[best];
54362
+ for (const c of demanded) {
54363
+ const deficit = targets[c] - running[c];
54364
+ if (deficit > bestDeficit) {
54365
+ bestDeficit = deficit;
54366
+ best = c;
54367
+ }
54368
+ }
54369
+ out[best] += 1;
54370
+ running[best] += 1;
54371
+ }
54372
+ return out;
54373
+ }
54374
+
54375
+ // ../src/lib/deckPlan/applySeeds.ts
54376
+ init_slug();
54377
+
54378
+ // ../src/lib/deckPlan/hooks/useDeckActions.ts
54379
+ var RANK_SYNERGY_WEIGHT = 1;
54380
+ var CURVE_PENALTY_WEIGHT = 0.15;
54381
+ var CURVE_7PLUS_CEILING_SLACK = 2;
54382
+ function rankScore(item, mode) {
54383
+ if (mode === "popularity") return item.inclusion;
54384
+ return item.inclusionPct + RANK_SYNERGY_WEIGHT * Math.max(0, item.synergy);
54385
+ }
54386
+ function gcAllowanceForBracket(bracket) {
54387
+ if (bracket === void 0) return Infinity;
54388
+ if (bracket <= 2) return 0;
54389
+ if (bracket === 3) return 3;
54390
+ return Infinity;
54391
+ }
54392
+ function withinPriceCap(priceUsd, cap2) {
54393
+ if (cap2 == null) return true;
54394
+ return priceUsd === void 0 || priceUsd <= cap2;
54395
+ }
54396
+ function fillLands(landsSlot, ownedTaken, newAssignments, newBasicQty, nonLandsCommitted, ownedQtyForCard, effectiveDetail, opts) {
54397
+ let filled = 0;
54398
+ const need = landsSlot.target;
54399
+ const identity2 = effectiveDetail?.colors ?? [];
54400
+ const colorCount = identity2.length;
54401
+ const floor = colorCount === 0 ? Math.min(minBasics(0), need) : Math.max(0, need - Math.min(need, nonBasicAllowance(colorCount)));
54402
+ const nonBasicCap = need - floor;
54403
+ const placedNonBasics = [];
54404
+ const sortedOwned = [...landsSlot.owned].sort(
54405
+ (a, b) => b.inclusion - a.inclusion
54406
+ );
54407
+ const ownedBasicByColor = {};
54408
+ let ownedWastes;
54409
+ const heldNonBasics = [];
54410
+ for (const item of sortedOwned) {
54411
+ const isBasic = isBasicLandType(item.card.typeLine);
54412
+ if (isBasic) {
54413
+ for (const c of item.card.colors) {
54414
+ ownedBasicByColor[c] ??= item.card;
54415
+ }
54416
+ if (item.card.colors.length === 0) ownedWastes ??= item.card;
54417
+ continue;
54418
+ }
54419
+ if (ownedTaken.has(item.card.oracleId)) continue;
54420
+ if (filled >= nonBasicCap) {
54421
+ heldNonBasics.push(item.card);
54422
+ continue;
54423
+ }
54424
+ newAssignments.set(item.card.oracleId, landsSlot.slot);
54425
+ ownedTaken.add(item.card.oracleId);
54426
+ placedNonBasics.push(item.card);
54427
+ filled++;
54428
+ }
54429
+ if (opts && filled < nonBasicCap) {
54430
+ const sortedSuggestions = [...landsSlot.suggestions].filter((s) => withinPriceCap(s.card?.priceUsd, opts.priceCap)).sort((a, b) => b.inclusion - a.inclusion);
54431
+ for (const sug of sortedSuggestions) {
54432
+ if (filled >= nonBasicCap) break;
54433
+ if (opts.purchasedTaken.has(sug.slug)) continue;
54434
+ opts.purchases.set(sug.slug, landsSlot.slot);
54435
+ opts.purchasedTaken.add(sug.slug);
54436
+ if (sug.card) placedNonBasics.push(sug.card);
54437
+ filled++;
54438
+ }
54439
+ }
54440
+ const remaining = Math.max(0, need - filled);
54441
+ if (remaining > 0 && identity2.length === 0) {
54442
+ let wastes = ownedWastes;
54443
+ if (!wastes && opts?.cards) {
54444
+ wastes = findCardByName(opts.cards, WASTES_NAME);
54445
+ }
54446
+ if (wastes) {
54447
+ const planned = opts ? remaining : Math.min(remaining, ownedQtyForCard(wastes.oracleId));
54448
+ if (planned > 0) {
54449
+ if (!ownedTaken.has(wastes.oracleId)) {
54450
+ newAssignments.set(wastes.oracleId, landsSlot.slot);
54451
+ ownedTaken.add(wastes.oracleId);
54452
+ }
54453
+ if (planned > 1) newBasicQty.set(wastes.oracleId, planned);
54454
+ filled += planned;
54455
+ }
54456
+ }
54457
+ } else if (remaining > 0) {
54458
+ const targets = karstenTargetsByColor(nonLandsCommitted, need);
54459
+ const supply = sourcesByColor(placedNonBasics);
54460
+ const want = distributeBasicsBySources(targets, supply, identity2, remaining);
54461
+ for (const color of WUBRG_ORDER) {
54462
+ const targetCount = want[color];
54463
+ if (targetCount === 0) continue;
54464
+ let basicCard = ownedBasicByColor[color];
54465
+ if (!basicCard && opts?.cards) {
54466
+ basicCard = findCardByName(opts.cards, BASIC_NAME[color]);
54467
+ }
54468
+ if (!basicCard) continue;
54469
+ const planned = opts ? targetCount : Math.min(targetCount, ownedQtyForCard(basicCard.oracleId));
54470
+ if (planned <= 0) continue;
54471
+ if (!ownedTaken.has(basicCard.oracleId)) {
54472
+ newAssignments.set(basicCard.oracleId, landsSlot.slot);
54473
+ ownedTaken.add(basicCard.oracleId);
54474
+ }
54475
+ if (planned > 1) newBasicQty.set(basicCard.oracleId, planned);
54476
+ filled += planned;
54477
+ }
54478
+ }
54479
+ if (filled < need && heldNonBasics.length > 0) {
54480
+ for (const card of heldNonBasics) {
54481
+ if (filled >= need) break;
54482
+ if (ownedTaken.has(card.oracleId)) continue;
54483
+ newAssignments.set(card.oracleId, landsSlot.slot);
54484
+ ownedTaken.add(card.oracleId);
54485
+ filled++;
54486
+ }
54487
+ }
54488
+ }
54489
+ function computeBestBuildPlan(slots, ownedQtyForCard, effectiveDetail, useQualityFloor = true, rankMode = "popularity", targetCurve = void 0, targetBracket = void 0, cards = null, priceCap = null, ownedOnly = false) {
54490
+ const newAssignments = /* @__PURE__ */ new Map();
54491
+ const newPurchases = /* @__PURE__ */ new Map();
54492
+ const newBasicQty = /* @__PURE__ */ new Map();
54493
+ const ownedTaken = /* @__PURE__ */ new Set();
54494
+ const purchasedTaken = /* @__PURE__ */ new Set();
54495
+ const nonLandsCommitted = [];
54496
+ const floorStats = [];
54497
+ const bracketGcAllowance = gcAllowanceForBracket(
54498
+ targetBracket ?? effectiveDetail?.bracket
54499
+ );
54500
+ let gcUsed = 0;
54501
+ const sampleDecks = effectiveDetail?.deckCount ?? 0;
54502
+ const lowSample = sampleDecks > 0 && sampleDecks < LOW_SAMPLE_THRESHOLD;
54503
+ const effectiveRankMode = rankMode === "synergy" && lowSample ? "popularity" : rankMode;
54504
+ const hasEdhrecData = (effectiveDetail?.categories?.length ?? 0) > 0;
54505
+ const rankTiebreak = (card) => hasEdhrecData ? 0 : card?.edhrecRank ?? Number.POSITIVE_INFINITY;
54506
+ const byRank2 = (a, b) => {
54507
+ const diff = rankScore(b, effectiveRankMode) - rankScore(a, effectiveRankMode);
54508
+ if (diff !== 0) return diff;
54509
+ const incDiff = b.inclusion - a.inclusion;
54510
+ if (incDiff !== 0) return incDiff;
54511
+ return rankTiebreak(a.card) - rankTiebreak(b.card);
54512
+ };
54513
+ const assignOwned = (items, slotName, need, filled) => {
54514
+ for (const item of items) {
54515
+ if (filled >= need) break;
54516
+ if (ownedTaken.has(item.card.oracleId)) continue;
54517
+ if (gcUsed >= bracketGcAllowance && isGameChangerName(item.card.name)) {
54518
+ continue;
54519
+ }
54520
+ newAssignments.set(item.card.oracleId, slotName);
54521
+ ownedTaken.add(item.card.oracleId);
54522
+ nonLandsCommitted.push(item.card);
54523
+ if (isGameChangerName(item.card.name)) gcUsed++;
54524
+ filled++;
54525
+ }
54526
+ return filled;
54527
+ };
54528
+ const nonLandTarget = slots.reduce(
54529
+ (sum, s) => s.slot === "lands" ? sum : sum + s.target,
54530
+ 0
54531
+ );
54532
+ const targetBuckets = targetCurve ? targetCounts(targetCurve, nonLandTarget) : null;
54533
+ const ceiling7plus = targetBuckets ? targetBuckets[CURVE_TOP_BUCKET] + CURVE_7PLUS_CEILING_SLACK : Infinity;
54534
+ const curve = new Array(CURVE_BUCKET_COUNT).fill(0);
54535
+ const scoreSpread = (items) => {
54536
+ let min = Infinity;
54537
+ let max = -Infinity;
54538
+ for (const it of items) {
54539
+ const s = rankScore(it, effectiveRankMode);
54540
+ if (s < min) min = s;
54541
+ if (s > max) max = s;
54542
+ }
54543
+ if (max === -Infinity) return 1;
54544
+ const spread = max - min;
54545
+ return spread > 0 ? spread : 1;
54546
+ };
54547
+ const pickCurveAware = (pool, isTaken, isGcBlocked, scoreOf, bucketOf, inclusionOf, keyOf, scale, rankOf) => {
54548
+ let bestIdx = -1;
54549
+ let bestUnder = false;
54550
+ let bestEff = -Infinity;
54551
+ let bestInc = -Infinity;
54552
+ let bestRank = Infinity;
54553
+ let bestKey = "";
54554
+ for (let i = 0; i < pool.length; i++) {
54555
+ const t = pool[i];
54556
+ if (isTaken(t) || isGcBlocked(t)) continue;
54557
+ const b = bucketOf(t);
54558
+ const over = b !== null && targetBuckets ? Math.max(0, curve[b] + 1 - targetBuckets[b]) : 0;
54559
+ const under = !(b === CURVE_TOP_BUCKET && curve[CURVE_TOP_BUCKET] >= ceiling7plus);
54560
+ const eff = scoreOf(t) - CURVE_PENALTY_WEIGHT * scale * over;
54561
+ const inc = inclusionOf(t);
54562
+ const rank = rankOf(t);
54563
+ const key2 = keyOf(t);
54564
+ const better = bestIdx === -1 || under && !bestUnder || under === bestUnder && (eff > bestEff || eff === bestEff && (inc > bestInc || inc === bestInc && (rank < bestRank || rank === bestRank && key2 < bestKey)));
54565
+ if (better) {
54566
+ bestIdx = i;
54567
+ bestUnder = under;
54568
+ bestEff = eff;
54569
+ bestInc = inc;
54570
+ bestRank = rank;
54571
+ bestKey = key2;
54572
+ }
54573
+ }
54574
+ return bestIdx;
54575
+ };
54576
+ const assignOwnedCurveAware = (items, slotName, need, filled) => {
54577
+ const scale = scoreSpread(items);
54578
+ while (filled < need) {
54579
+ const idx = pickCurveAware(
54580
+ items,
54581
+ (it) => ownedTaken.has(it.card.oracleId),
54582
+ (it) => gcUsed >= bracketGcAllowance && isGameChangerName(it.card.name),
54583
+ (it) => rankScore(it, effectiveRankMode),
54584
+ (it) => bucketIndex(it.card.cmc),
54585
+ (it) => it.inclusion,
54586
+ (it) => it.card.oracleId,
54587
+ scale,
54588
+ (it) => rankTiebreak(it.card)
54589
+ );
54590
+ if (idx === -1) break;
54591
+ const item = items[idx];
54592
+ newAssignments.set(item.card.oracleId, slotName);
54593
+ ownedTaken.add(item.card.oracleId);
54594
+ nonLandsCommitted.push(item.card);
54595
+ curve[bucketIndex(item.card.cmc)]++;
54596
+ if (isGameChangerName(item.card.name)) gcUsed++;
54597
+ filled++;
54598
+ }
54599
+ return filled;
54600
+ };
54601
+ const buyCurveAware = (sugs, slotName, need, filled) => {
54602
+ const scale = scoreSpread(sugs);
54603
+ let placed = 0;
54604
+ while (filled < need) {
54605
+ const idx = pickCurveAware(
54606
+ sugs,
54607
+ (s) => purchasedTaken.has(s.slug),
54608
+ (s) => gcUsed >= bracketGcAllowance && isGameChangerName(s.card?.name ?? s.name ?? ""),
54609
+ (s) => rankScore(s, effectiveRankMode),
54610
+ (s) => s.card ? bucketIndex(s.card.cmc) : null,
54611
+ (s) => s.inclusion,
54612
+ (s) => s.slug,
54613
+ scale,
54614
+ (s) => rankTiebreak(s.card)
54615
+ );
54616
+ if (idx === -1) break;
54617
+ const sug = sugs[idx];
54618
+ const sugName = sug.card?.name ?? sug.name ?? "";
54619
+ newPurchases.set(sug.slug, slotName);
54620
+ purchasedTaken.add(sug.slug);
54621
+ if (sug.card) {
54622
+ nonLandsCommitted.push(sug.card);
54623
+ curve[bucketIndex(sug.card.cmc)]++;
54624
+ }
54625
+ if (isGameChangerName(sugName)) gcUsed++;
54626
+ filled++;
54627
+ placed++;
54628
+ }
54629
+ return { filled, placed };
54630
+ };
54631
+ for (const slot of slots) {
54632
+ if (slot.slot === "lands") continue;
54633
+ let filled = 0;
54634
+ const need = slot.target;
54635
+ const ownedAboveFloor = [];
54636
+ const ownedBelowFloor = [];
54637
+ for (const item of slot.owned) {
54638
+ if (!useQualityFloor || item.inclusionPct >= INCLUSION_FLOOR_PCT) {
54639
+ ownedAboveFloor.push(item);
54640
+ } else {
54641
+ ownedBelowFloor.push(item);
54642
+ }
54643
+ }
54644
+ ownedAboveFloor.sort(byRank2);
54645
+ ownedBelowFloor.sort(byRank2);
54646
+ filled = targetBuckets ? assignOwnedCurveAware(ownedAboveFloor, slot.slot, need, filled) : assignOwned(ownedAboveFloor, slot.slot, need, filled);
54647
+ let buysThisSlot = 0;
54648
+ if (!ownedOnly && filled < need) {
54649
+ const sugAboveFloor = [...slot.suggestions].filter(
54650
+ (s) => s.inclusionPct >= INCLUSION_FLOOR_PCT && withinPriceCap(s.card?.priceUsd, priceCap)
54651
+ ).sort(byRank2);
54652
+ if (targetBuckets) {
54653
+ const r = buyCurveAware(sugAboveFloor, slot.slot, need, filled);
54654
+ filled = r.filled;
54655
+ buysThisSlot = r.placed;
54656
+ } else {
54657
+ for (const sug of sugAboveFloor) {
54658
+ if (filled >= need) break;
54659
+ if (purchasedTaken.has(sug.slug)) continue;
54660
+ const sugName = sug.card?.name ?? sug.name ?? "";
54661
+ if (gcUsed >= bracketGcAllowance && isGameChangerName(sugName)) {
54662
+ continue;
54663
+ }
54664
+ newPurchases.set(sug.slug, slot.slot);
54665
+ purchasedTaken.add(sug.slug);
54666
+ if (sug.card) nonLandsCommitted.push(sug.card);
54667
+ if (isGameChangerName(sugName)) gcUsed++;
54668
+ filled++;
54669
+ buysThisSlot++;
54670
+ }
54671
+ }
54672
+ }
54673
+ if (filled < need) {
54674
+ filled = targetBuckets ? assignOwnedCurveAware(ownedBelowFloor, slot.slot, need, filled) : assignOwned(ownedBelowFloor, slot.slot, need, filled);
54675
+ }
54676
+ floorStats.push({ buys: buysThisSlot, belowFloor: ownedBelowFloor.map((o) => o.card) });
54677
+ }
54678
+ const landsSlot = slots.find((s) => s.slot === "lands");
54679
+ if (landsSlot) {
54680
+ fillLands(
54681
+ landsSlot,
54682
+ ownedTaken,
54683
+ newAssignments,
54684
+ newBasicQty,
54685
+ nonLandsCommitted,
54686
+ ownedQtyForCard,
54687
+ effectiveDetail,
54688
+ ownedOnly ? void 0 : { purchases: newPurchases, purchasedTaken, cards, priceCap }
54689
+ );
54690
+ }
54691
+ let skippedLowSignalOwned = 0;
54692
+ for (const { buys, belowFloor } of floorStats) {
54693
+ if (buys === 0) continue;
54694
+ const benched = belowFloor.filter((c) => !ownedTaken.has(c.oracleId)).length;
54695
+ skippedLowSignalOwned += Math.min(buys, benched);
54696
+ }
54697
+ const lowSignalPlacedBySlot = [];
54698
+ for (const slot of slots) {
54699
+ if (slot.slot === "lands") continue;
54700
+ const hadAboveFloorCandidate = slot.owned.some((o) => o.inclusionPct >= INCLUSION_FLOOR_PCT) || slot.suggestions.some((s) => s.inclusionPct >= INCLUSION_FLOOR_PCT);
54701
+ if (!hadAboveFloorCandidate) continue;
54702
+ let count2 = 0;
54703
+ for (const item of slot.owned) {
54704
+ if (item.inclusionPct >= INCLUSION_FLOOR_PCT) continue;
54705
+ if (newAssignments.get(item.card.oracleId) === slot.slot) count2++;
54706
+ }
54707
+ if (count2 > 0) {
54708
+ lowSignalPlacedBySlot.push({
54709
+ slot: slot.slot,
54710
+ label: slot.label,
54711
+ count: count2
54712
+ });
54713
+ }
54714
+ }
54715
+ return {
54716
+ assignments: newAssignments,
54717
+ purchases: newPurchases,
54718
+ basicQuantities: newBasicQty,
54719
+ ownedCount: newAssignments.size,
54720
+ buyCount: newPurchases.size,
54721
+ skippedLowSignalOwned,
54722
+ lowSignalPlacedBySlot
54723
+ };
54724
+ }
54725
+ var LAND_FIT_MAX_PASSES = 3;
54726
+ function retargetLands(slots, landTarget) {
54727
+ const lands = slots.find((s) => s.slot === "lands");
54728
+ if (!lands || lands.target === landTarget) return slots;
54729
+ const delta = lands.target - landTarget;
54730
+ return slots.map(
54731
+ (s) => s.slot === "lands" ? { ...s, target: landTarget } : s.slot === "creatures" ? { ...s, target: Math.max(0, s.target + delta) } : s
54732
+ );
54733
+ }
54734
+ function planNonLandCards(plan, slots, cards) {
54735
+ const out = [];
54736
+ for (const [oracleId, slot] of plan.assignments) {
54737
+ if (slot === "lands") continue;
54738
+ const c = cards.byOracleId.get(oracleId);
54739
+ if (c) out.push(c);
54740
+ }
54741
+ const bySlug = /* @__PURE__ */ new Map();
54742
+ for (const s of slots) {
54743
+ if (s.slot === "lands") continue;
54744
+ for (const sug of s.suggestions) if (sug.card) bySlug.set(sug.slug, sug.card);
54745
+ }
54746
+ for (const [slug, slot] of plan.purchases) {
54747
+ if (slot === "lands") continue;
54748
+ const c = bySlug.get(slug);
54749
+ if (c) out.push(c);
54750
+ }
54751
+ return out;
54752
+ }
54753
+ function buildWithRecommendedLands(build, slots, cards, lens) {
54754
+ let cur = slots;
54755
+ let plan = build(cur);
54756
+ if (!cards || !cur.some((s) => s.slot === "lands")) return { plan, slots: cur };
54757
+ const tried = /* @__PURE__ */ new Set();
54758
+ for (let pass = 0; pass < LAND_FIT_MAX_PASSES; pass++) {
54759
+ const landTarget = cur.find((s) => s.slot === "lands").target;
54760
+ tried.add(landTarget);
54761
+ const inputs = landCountInputs(
54762
+ planNonLandCards(plan, cur, cards).map((card) => ({ card })),
54763
+ lens
54764
+ );
54765
+ if (inputs.spellCount === 0) break;
54766
+ const rec = recommendedLandCount(inputs);
54767
+ if (rec === landTarget || tried.has(rec)) break;
54768
+ cur = retargetLands(cur, rec);
54769
+ plan = build(cur);
54770
+ }
54771
+ return { plan, slots: cur };
54772
+ }
54773
+
54774
+ // ../src/lib/commandersBySeeds.ts
54775
+ function rankCommandersBySeeds(seeds, commandersIndex) {
54776
+ if (seeds.length === 0) return [];
54777
+ const seedColors = /* @__PURE__ */ new Set();
54778
+ for (const s of seeds) {
54779
+ for (const c of s.colors) seedColors.add(c);
54780
+ }
54781
+ const out = [];
54782
+ for (const c of commandersIndex.commanders) {
54783
+ const pool = new Set(c.pool);
54784
+ const hitSlugs = [];
54785
+ const missingSlugs = [];
54786
+ for (const seed of seeds) {
54787
+ if (pool.has(seed.slug)) hitSlugs.push(seed.slug);
54788
+ else missingSlugs.push(seed.slug);
54789
+ }
54790
+ if (hitSlugs.length === 0) continue;
54791
+ let colorLegal = true;
54792
+ if (seedColors.size > 0) {
54793
+ const commanderColors = new Set(c.colors);
54794
+ for (const col of seedColors) {
54795
+ if (!commanderColors.has(col)) {
54796
+ colorLegal = false;
54797
+ break;
54798
+ }
54799
+ }
54800
+ }
54801
+ out.push({
54802
+ commander: c,
54803
+ hits: hitSlugs.length,
54804
+ hitSlugs,
54805
+ missingSlugs,
54806
+ colorLegal
54807
+ });
54808
+ }
54809
+ out.sort((a, b) => {
54810
+ if (a.hits !== b.hits) return b.hits - a.hits;
54811
+ if (a.colorLegal !== b.colorLegal) return a.colorLegal ? -1 : 1;
54812
+ return b.commander.deckCount - a.commander.deckCount;
54813
+ });
54814
+ return out;
54815
+ }
54816
+ function legalCommandersOnly(rankings) {
54817
+ return rankings.filter((r) => r.colorLegal);
54818
+ }
53740
54819
 
53741
54820
  // ../src/lib/deckPlan/deckHealth.ts
53742
54821
  function comb(n, k) {
@@ -54619,21 +55698,25 @@ function isFastManaName(name) {
54619
55698
  // ../src/components/deckBuilderV2/bracketInference.ts
54620
55699
  var BRACKET_MIN_COMMITTED = 30;
54621
55700
  var EXTRA_TURN_SIGNAL = "extra-turn";
54622
- function countSignals(cards, gameChangerCount, comboCount) {
54623
- let mld = 0;
54624
- let extraTurns = 0;
54625
- let fastMana = 0;
55701
+ function bracketSignalCards(cards) {
55702
+ const mld = [];
55703
+ const extraTurns = [];
54626
55704
  for (const c of cards) {
54627
- if (isMassLandDestructionName(c.name)) mld++;
55705
+ if (isMassLandDestructionName(c.name)) mld.push(c.name);
54628
55706
  if (c.signals?.includes(EXTRA_TURN_SIGNAL) || isExtraTurnName(c.name))
54629
- extraTurns++;
54630
- if (isFastManaName(c.name)) fastMana++;
55707
+ extraTurns.push(c.name);
54631
55708
  }
55709
+ return { mld, extraTurns };
55710
+ }
55711
+ function countSignals(cards, gameChangerCount, comboCount) {
55712
+ const named = bracketSignalCards(cards);
55713
+ let fastMana = 0;
55714
+ for (const c of cards) if (isFastManaName(c.name)) fastMana++;
54632
55715
  return {
54633
55716
  gameChangers: gameChangerCount,
54634
55717
  combos: comboCount,
54635
- mld,
54636
- extraTurns,
55718
+ mld: named.mld.length,
55719
+ extraTurns: named.extraTurns.length,
54637
55720
  fastMana
54638
55721
  };
54639
55722
  }
@@ -54809,9 +55892,11 @@ var REDUCER_FIELDS = [
54809
55892
  "fillActionAt",
54810
55893
  "editedSinceFill"
54811
55894
  ];
54812
- var REDUCER = new Set(REDUCER_FIELDS);
55895
+ var NEVER_CARRIED = ["minEditor"];
55896
+ var REDUCER = /* @__PURE__ */ new Set([...REDUCER_FIELDS, ...NEVER_CARRIED]);
54813
55897
 
54814
55898
  // ../src/lib/agentRequests/deckOps.ts
55899
+ init_deckSchema();
54815
55900
  init_utils();
54816
55901
  init_deckText();
54817
55902
  var DECK_BOARDS = ["deck", "considering", "sideboard"];
@@ -54919,7 +56004,15 @@ var isSideOp = (op) => op.op === "tags" || op.op === "print";
54919
56004
  function cardsChanged(ops) {
54920
56005
  return new Set(ops.filter((o) => !isTextOp(o)).map((o) => o.oracleId)).size;
54921
56006
  }
56007
+ function newerDeckIssues(ops, ctx) {
56008
+ return ops.map((op, index) => ({
56009
+ index,
56010
+ card: isTextOp(op) ? TEXT_LABEL[op.field] : ctx.card(op.oracleId)?.name ?? op.oracleId,
56011
+ reason: NEWER_DECK_MESSAGE
56012
+ }));
56013
+ }
54922
56014
  function checkDeckOps(stored, ops, ctx, maxCards = MAX_CARDS_PER_EDIT) {
56015
+ if (!canEditDeck(stored)) return newerDeckIssues(ops, ctx);
54923
56016
  const issues = [];
54924
56017
  if (cardsChanged(ops) > maxCards) {
54925
56018
  issues.push({ index: -1, card: "", reason: `changes ${cardsChanged(ops)} cards; at most ${maxCards} per request` });
@@ -55141,19 +56234,18 @@ function parseDeckOp(x, live = false) {
55141
56234
  case "move":
55142
56235
  return board(o.to) ? { op: "move", oracleId: o.oracleId, to: o.to } : null;
55143
56236
  case "tags": {
55144
- if (!live || !Array.isArray(o.tags) || o.tags.length > MAX_CARD_TAGS) return null;
56237
+ if (!Array.isArray(o.tags) || o.tags.length > MAX_CARD_TAGS) return null;
55145
56238
  if (!o.tags.every((t) => typeof t === "string" && t.trim().length > 0 && t.length <= MAX_TAG_NAME)) return null;
55146
56239
  return { op: "tags", oracleId: o.oracleId, tags: o.tags };
55147
56240
  }
55148
56241
  case "print": {
55149
- if (!live) return null;
55150
56242
  if (o.print === null) return { op: "print", oracleId: o.oracleId, print: null };
55151
56243
  const p = o.print;
55152
56244
  const part2 = (v) => typeof v === "string" && /^[A-Za-z0-9★_-]{1,12}$/.test(v);
55153
56245
  return p && part2(p.set) && part2(p.cn) ? { op: "print", oracleId: o.oracleId, print: { set: p.set, cn: p.cn } } : null;
55154
56246
  }
55155
56247
  case "commanders": {
55156
- if (!live || !Array.isArray(o.ids) || o.ids.length < 1 || o.ids.length > 2) return null;
56248
+ if (!Array.isArray(o.ids) || o.ids.length < 1 || o.ids.length > 2) return null;
55157
56249
  if (!o.ids.every((id) => typeof id === "string" && OID_RE.test(id)) || o.ids[0] !== o.oracleId) return null;
55158
56250
  return { op: "commanders", oracleId: o.oracleId, ids: o.ids };
55159
56251
  }
@@ -64935,7 +66027,7 @@ var comboNotes = (combos) => combos ? combos.stale ? { comboNote: "Combo data co
64935
66027
  var asDeck = (d) => d;
64936
66028
  var listDecks = {
64937
66029
  name: "list_decks",
64938
- description: "List the user's saved decks: name, commanders, card count, legality, bracket floor, folder, last edit.",
66030
+ description: "List the user's saved decks: name, commanders, card count, legality, bracket floor, public or private, folder, last edit.",
64939
66031
  input: {
64940
66032
  query: external_exports.string().optional().describe("Filter by deck or commander name."),
64941
66033
  folder: external_exports.string().optional().describe("Only decks in this folder."),
@@ -64966,6 +66058,7 @@ var listDecks = {
64966
66058
  cards: `${v.cards}/${v.target}`,
64967
66059
  status: v.status,
64968
66060
  bracketFloor: v.bracketFloor,
66061
+ ...visibilityOf(decks.get(v.id)),
64969
66062
  folder: f,
64970
66063
  updated: savedAt ? new Date(savedAt).toISOString().slice(0, 10) : void 0
64971
66064
  })),
@@ -65092,6 +66185,10 @@ function matchesOnly(l, only, stored) {
65092
66185
  const id = cats?.categories.find((c) => c.name.toLowerCase() === o)?.id;
65093
66186
  return !!id && cats?.assignments[l.card.oracleId] === id;
65094
66187
  }
66188
+ function visibilityOf(raw) {
66189
+ const flag = raw && typeof raw === "object" ? raw[PUBLIC_FLAG] : void 0;
66190
+ return typeof flag === "boolean" ? { visibility: flag ? "public" : "private" } : {};
66191
+ }
65095
66192
  function deckAnswer(v, stored, detail, only) {
65096
66193
  const main2 = v.lines.filter((l) => l.board === "main" || l.board === "buy");
65097
66194
  const byType = {};
@@ -65111,6 +66208,7 @@ function deckAnswer(v, stored, detail, only) {
65111
66208
  considering: v.lines.filter((l) => l.board === "considering").length,
65112
66209
  sideboard: v.lines.filter((l) => l.board === "sideboard").length,
65113
66210
  ...v.unknownCards ? { unknownCards: v.unknownCards } : {},
66211
+ ...visibilityOf(stored),
65114
66212
  ...stored.tags?.length ? { tags: stored.tags } : {},
65115
66213
  ...stored.description ? { description: stored.description } : {}
65116
66214
  };
@@ -66590,13 +67688,17 @@ var PENDING_ABOUT = "Nothing has changed yet. The user approves or declines it i
66590
67688
  var editDeckTool = {
66591
67689
  name: "edit_deck",
66592
67690
  write: true,
66593
- description: "Ask to change one of the user's saved decks: add cards, cut cards, set a card's copies, or move cards between the deck, considering and the sideboard. This files a REQUEST: nothing changes until the user approves it in EDHVault (Settings, AI tools), and it expires after 7 days. Owned cards go in the deck, others on its buy list, as the deck builder does. At most 30 cards per request. It's checked first against the deck as you see it (already in, not in it, outside the commander's colors, banned, one copy only) and refused with the reasons if it wouldn't apply. Give `note` to say why, in a sentence: the user sees it. Needs an access code allowed to ask to change decks.",
67691
+ description: "Ask to change one of the user's saved decks: add cards, cut cards, set a card's copies, move cards between the deck, considering and the sideboard, set a card's tags or printing, or change the commander. This files a REQUEST: nothing changes until the user approves it in EDHVault (Settings, AI tools), and it expires after 7 days. Owned cards go in the deck, others on its buy list, as the deck builder does. At most 30 cards per request. It's checked first against the deck as you see it (already in, not in it, outside the commander's colors, banned, one copy only) and refused with the reasons if it wouldn't apply. Give `note` to say why, in a sentence: the user sees it. Needs an access code allowed to ask to change decks.",
66594
67692
  input: {
66595
67693
  deck: external_exports.string().describe("The deck: its name or id (list_decks)."),
66596
67694
  add: external_exports.array(external_exports.object({ name: external_exports.string(), qty: external_exports.number().int().min(1).max(99).optional(), to: BOARD_INPUT.optional() })).max(30).optional().describe("Cards to add: name, copies (basics and any-number cards only), and where (default: deck)."),
66597
67695
  remove: external_exports.array(external_exports.string()).max(30).optional().describe("Cards to cut, wherever they are in the deck."),
66598
67696
  setQuantity: external_exports.array(external_exports.object({ name: external_exports.string(), qty: external_exports.number().int().min(1).max(99) })).max(30).optional().describe("Copies of a card already in the deck."),
66599
67697
  move: external_exports.array(external_exports.object({ name: external_exports.string(), to: BOARD_INPUT })).max(30).optional().describe("Cards to move to the deck, considering or the sideboard."),
67698
+ tags: external_exports.array(external_exports.object({ name: external_exports.string(), tags: external_exports.array(external_exports.string().min(1).max(MAX_TAG_NAME)).max(MAX_CARD_TAGS) })).max(30).optional().describe("A card's tags (the builder's categories), its main tag first; [] untags it. This replaces the card's tags: get_deck shows them."),
67699
+ printing: external_exports.array(external_exports.object({ name: external_exports.string(), printing: external_exports.string().nullable() })).max(30).optional().describe(`A card's printing: set code and collector number, like "fdc 286" (get_card lists them), or null for the default.`),
67700
+ commander: external_exports.string().optional().describe("A new commander. Cards outside its colors are named in the answer, not cut: cut them in the same request."),
67701
+ partner: external_exports.string().optional().describe("With commander: a second commander (partner, background, and the like)."),
66600
67702
  note: external_exports.string().max(MAX_NOTE_CHARS).optional().describe("Why, in a sentence. Shown to the user beside the request.")
66601
67703
  },
66602
67704
  async run(args, ctx) {
@@ -66609,18 +67711,36 @@ var editDeckTool = {
66609
67711
  if (!c) throw new ToolProblem(`No card named "${name2}".`);
66610
67712
  return c;
66611
67713
  };
67714
+ if (args.partner !== void 0 && args.commander === void 0) throw new ToolProblem("partner goes with commander: give both.");
67715
+ const newCommanders = typeof args.commander === "string" && args.commander.trim() ? [card(args.commander), ...typeof args.partner === "string" && args.partner.trim() ? [card(args.partner)] : []] : null;
67716
+ if (newCommanders) {
67717
+ for (const c of newCommanders) if (!c.canBeCommander) throw new ToolProblem(`${c.name} can't be a commander.`);
67718
+ if (newCommanders.length === 2) {
67719
+ const pair = isPairLegal(newCommanders[0], newCommanders[1]);
67720
+ if (!pair.legal) throw new ToolProblem(`${newCommanders[0].name} and ${newCommanders[1].name} can't be commanders together: ${pair.reason}`);
67721
+ }
67722
+ }
67723
+ const printingOf2 = args.printing?.length ? await printingPicker(ctx) : () => ({ set: "", cn: "" });
66612
67724
  const ops = [
67725
+ // The command zone first: what's checked after it is checked against it.
67726
+ ...newCommanders ? [{ op: "commanders", oracleId: newCommanders[0].oracleId, ids: newCommanders.map((c) => c.oracleId) }] : [],
66613
67727
  ...(args.remove ?? []).map((n) => ({ op: "remove", oracleId: card(n).oracleId })),
66614
67728
  ...(args.move ?? []).map((m) => ({ op: "move", oracleId: card(m.name).oracleId, to: m.to })),
66615
67729
  ...(args.setQuantity ?? []).map((m) => ({ op: "setQty", oracleId: card(m.name).oracleId, qty: m.qty })),
66616
- ...(args.add ?? []).map((a) => ({ op: "add", oracleId: card(a.name).oracleId, ...a.qty ? { qty: a.qty } : {}, ...a.to ? { to: a.to } : {} }))
67730
+ ...(args.add ?? []).map((a) => ({ op: "add", oracleId: card(a.name).oracleId, ...a.qty ? { qty: a.qty } : {}, ...a.to ? { to: a.to } : {} })),
67731
+ ...(args.tags ?? []).map((t) => ({ op: "tags", oracleId: card(t.name).oracleId, tags: t.tags.map((x) => x.trim()) })),
67732
+ ...(args.printing ?? []).map((p) => {
67733
+ const c = card(p.name);
67734
+ return { op: "print", oracleId: c.oracleId, print: p.printing === null ? null : printingOf2(c, p.printing) };
67735
+ })
66617
67736
  ];
66618
- if (ops.length === 0) throw new ToolProblem("Nothing to change: give add, remove, setQuantity or move.");
67737
+ if (ops.length === 0) throw new ToolProblem("Nothing to change: give add, remove, setQuantity, move, tags, printing or commander.");
66619
67738
  const owned = await ownedIdsOf(ctx, catalog, false);
66620
- const commanders = viewDeck(id, stored, catalog, null).commanderCards;
67739
+ const commanders = newCommanders ?? viewDeck(id, stored, catalog, null).commanderCards;
67740
+ const identity2 = [...new Set(commanders.flatMap((c) => c.colors ?? []))];
66621
67741
  const opCtx = {
66622
67742
  card: (oid) => catalog.index.byOracleId.get(oid),
66623
- identity: [...new Set(commanders.flatMap((c) => c.colors))],
67743
+ identity: identity2,
66624
67744
  owned: (oid) => owned.ids.has(oid)
66625
67745
  };
66626
67746
  const issues = checkDeckOps(stored, ops, opCtx);
@@ -66639,11 +67759,39 @@ var editDeckTool = {
66639
67759
  changes: ops.map(
66640
67760
  (o) => o.op === "add" ? `+ ${name(o.oracleId)}${o.qty && o.qty > 1 ? ` x${o.qty}` : ""}${o.to && o.to !== "deck" ? ` (to ${o.to})` : ""}` : o.op === "remove" ? `- ${name(o.oracleId)}` : o.op === "setQty" ? `${name(o.oracleId)}: ${o.qty} copies` : o.op === "move" ? `${name(o.oracleId)} to ${o.to}` : o.op === "tags" ? `${name(o.oracleId)}: tags ${o.tags.join(", ") || "none"}` : o.op === "print" ? `${name(o.oracleId)}: ${o.print ? `printing ${o.print.set.toUpperCase()} ${o.print.cn}` : "default printing"}` : o.op === "commanders" ? `commander: ${o.ids.map(name).join(" + ")}` : `${o.field}: ${o.value}`
66641
67761
  ),
67762
+ ...newCommanders ? offColor(stored, ops, identity2, catalog) : {},
66642
67763
  expires: new Date(r.expiresAt).toISOString().slice(0, 10),
66643
67764
  about: PENDING_ABOUT
66644
67765
  });
66645
67766
  }
66646
67767
  };
67768
+ function offColor(stored, ops, identity2, catalog) {
67769
+ const gone = new Set(ops.filter((o) => o.op === "remove" || o.op === "move" && o.to !== "deck").map((o) => o.oracleId));
67770
+ const inCommand = new Set(ops.flatMap((o) => o.op === "commanders" ? o.ids : []));
67771
+ const out = [];
67772
+ const allowed = new Set(identity2);
67773
+ for (const oid of [...stored.assignments?.keys() ?? [], ...[...stored.purchases?.keys() ?? []].map((slug) => catalog.bySlug.get(slug)?.oracleId ?? "")]) {
67774
+ if (!oid || gone.has(oid) || inCommand.has(oid)) continue;
67775
+ const c = catalog.index.byOracleId.get(oid);
67776
+ if (c && !withinColorIdentity(c.colors ?? [], allowed)) out.push(c.name);
67777
+ }
67778
+ return out.length ? { outsideColors: { cards: out.sort(), about: "In the deck but outside the new commander's colors: the deck builder flags them until they're cut. A later edit_deck can cut them." } } : {};
67779
+ }
67780
+ async function printingPicker(ctx) {
67781
+ const file4 = ctx.extras ? await ctx.extras.printings().catch(() => null) : null;
67782
+ return (card, asked) => {
67783
+ const m = asked.trim().toLowerCase().match(/^([a-z0-9]{2,8})[\s#:/-]+([^\s]+)$/);
67784
+ if (!m) throw new ToolProblem(`printing is a set code and collector number, like "fdc 286". Got "${asked}".`);
67785
+ if (!file4) throw new ToolProblem("The printings list didn't load, so a printing can't be checked. Try again in a moment.");
67786
+ const all = hydrateOraclePrintings(file4.p[card.oracleId] ?? [], file4.pr[card.oracleId]);
67787
+ const hit = all.find((p) => p.set.toLowerCase() === m[1] && p.collectorNumber.toLowerCase() === m[2]);
67788
+ if (!hit) {
67789
+ const some = all.slice(0, 8).map((p) => `${p.set} ${p.collectorNumber}`);
67790
+ throw new ToolProblem(`${card.name} has no printing "${asked}".${some.length ? ` Some it has: ${some.join(", ")}.` : ""}`);
67791
+ }
67792
+ return { set: hit.set.toLowerCase(), cn: hit.collectorNumber };
67793
+ };
67794
+ }
66647
67795
  var noteOf = (args) => typeof args.note === "string" && args.note.trim() ? args.note.trim() : void 0;
66648
67796
  var noteInput = external_exports.string().max(MAX_NOTE_CHARS).optional().describe("Why, in a sentence. Shown to the user beside the request.");
66649
67797
  var utf8Bytes2 = (t) => new TextEncoder().encode(t).length;
@@ -67221,7 +68369,229 @@ var deckHistoryTool = {
67221
68369
  });
67222
68370
  }
67223
68371
  };
67224
- var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, compareTool, overlapTool, manabaseTool, planOdds, editDeckTool, setDeckNotesTool, moveToFolderTool, createDeckTool, collectionTool("collection_add"), collectionTool("collection_remove"), wishlistEditTool, binderEditTool, setCardReadTool, getRequestsTool, collectionValueTool, deckHistoryTool];
68372
+ var LISTS = ["wishlist", "binders", "seeds"];
68373
+ var listsTool = {
68374
+ name: "get_lists",
68375
+ description: 'The user\'s wishlist (cards they want, the printing when they named one, and the named lists each is on, like "For Krenko"), binders (named groups of collection cards) and seeds (cards they want to build around), with what they own of each. Seeds also list the commanders whose EDHREC pool holds the most of them, in their colors, as the Seeds page ranks them. `binder` names one binder to list its cards. Needs an access code that can read the wishlist, binders and seeds.',
68376
+ input: {
68377
+ list: external_exports.enum(LISTS).optional().describe("One list. Default: all three (a binder's cards only with `binder`)."),
68378
+ binder: external_exports.string().optional().describe("A binder's name: lists its cards."),
68379
+ refresh: refreshInput
68380
+ },
68381
+ async run(args, ctx) {
68382
+ if (!await ctx.library.has("lists")) throw new ToolProblem(noScopeMessage("lists"));
68383
+ const catalog = await ctx.catalog();
68384
+ const refresh = args.refresh === true;
68385
+ const lib = await ctx.library.library(refresh) ?? {};
68386
+ let ownedQty = null;
68387
+ try {
68388
+ const own2 = await ownership(ctx, catalog, refresh);
68389
+ ownedQty = (oid) => own2.owned.get(oid)?.stacks.reduce((n, s) => n + s.quantity, 0) ?? 0;
68390
+ } catch (e) {
68391
+ if (!isUnread(e)) throw e;
68392
+ }
68393
+ const day2 = (t) => typeof t === "number" && t > 0 ? new Date(t).toISOString().slice(0, 10) : void 0;
68394
+ const oidOf = (name, oracleId) => oracleId && catalog.index.byOracleId.has(oracleId) ? oracleId : resolveCardName(catalog.index, name)?.oracleId;
68395
+ const owns = (oid) => ownedQty && oid ? { owned: ownedQty(oid) } : {};
68396
+ const want = args.list ?? (typeof args.binder === "string" ? "binders" : void 0);
68397
+ const out = {};
68398
+ if (!want || want === "wishlist") {
68399
+ out.wishlist = (lib.wishlist ?? []).map((w) => ({
68400
+ name: w.name,
68401
+ ...w.printing ? { printing: `${w.printing.set} ${w.printing.collectorNumber}${w.printing.foil ? " foil" : ""}` } : {},
68402
+ ...w.lists?.length ? { lists: w.lists } : {},
68403
+ ...day2(w.addedAt) ? { added: day2(w.addedAt) } : {},
68404
+ ...owns(oidOf(w.name, w.oracleId))
68405
+ }));
68406
+ }
68407
+ if (!want || want === "binders") {
68408
+ const b = lib.binders ?? { v: 1, binders: [], membership: {} };
68409
+ const sorted2 = [...b.binders].sort((x, y) => x.order - y.order);
68410
+ const cardsOf = (id) => (b.membership[id] ?? []).map((key2) => {
68411
+ const [oid, print, finish] = key2.split("::");
68412
+ const card = catalog.index.byOracleId.get(oid);
68413
+ return { name: card?.name ?? "an unknown card", ...print ? { printing: `${print.replace("/", " ")}${finish === "f" ? " foil" : ""}` } : {}, ...owns(oid) };
68414
+ });
68415
+ if (typeof args.binder === "string" && args.binder.trim()) {
68416
+ const asked = args.binder.trim().toLowerCase();
68417
+ const hit = sorted2.find((x) => x.name.trim().toLowerCase() === asked);
68418
+ if (!hit) throw new ToolProblem(`No binder named "${args.binder}".${sorted2.length ? ` Binders: ${sorted2.map((x) => x.name).join(", ")}.` : " There are no binders."}`);
68419
+ out.binder = { name: hit.name, cards: cardsOf(hit.id) };
68420
+ } else {
68421
+ out.binders = sorted2.map((x) => ({ name: x.name, cards: (b.membership[x.id] ?? []).length }));
68422
+ }
68423
+ }
68424
+ if (!want || want === "seeds") {
68425
+ const seeds = lib.seeds ?? [];
68426
+ out.seeds = seeds.map((s) => ({ name: s.name, colors: s.colors.join("") || "C", ...day2(s.addedAt) ? { added: day2(s.addedAt) } : {}, ...owns(oidOf(s.name)) }));
68427
+ if (seeds.length && ctx.extras) {
68428
+ const index = await ctx.extras.commandersIndex().catch(() => null);
68429
+ if (index) {
68430
+ const nameOf = new Map(seeds.map((s) => [s.slug, s.name]));
68431
+ out.commandersForSeeds = {
68432
+ commanders: legalCommandersOnly(rankCommandersBySeeds(seeds, index)).slice(0, 10).map((r) => ({
68433
+ commander: r.commander.name,
68434
+ colors: r.commander.colors.join("") || "C",
68435
+ seedsInPool: `${r.hits} of ${seeds.length}`,
68436
+ ...r.missingSlugs.length ? { notInPool: r.missingSlugs.map((x) => nameOf.get(x) ?? x) } : {},
68437
+ decks: r.commander.deckCount
68438
+ })),
68439
+ about: "Commanders in the seeds' colors whose EDHREC top cards include the most seeds, then the most decks: the Seeds page's ranking.",
68440
+ credit: EDHREC_CREDIT
68441
+ };
68442
+ }
68443
+ }
68444
+ }
68445
+ if (!ownedQty) out.ownedLeftOut = noScopeMessage("collection");
68446
+ return json2(out);
68447
+ }
68448
+ };
68449
+ var COLOR_MODES = { fits: "atMost", has: "includes", is: "exact" };
68450
+ var commandersToBuildTool = {
68451
+ name: "list_commanders",
68452
+ description: "Commanders ranked by how much of their EDHREC pool (each commander's ~120 most-played cards) the user already owns, as the Commanders page ranks them, or by how many decks EDHREC counts (`sortBy: popularity`). Filter by colors and bracket, or to commanders they own. The share owned is EDHVault's reading of EDHREC's lists. Needs an access code that can read the collection.",
68453
+ input: {
68454
+ colors: external_exports.string().regex(/^[WUBRGCwubrgc]{1,6}$/).optional().describe('Colors as letters, like "UB" or "C" for colorless.'),
68455
+ colorMode: external_exports.enum(["fits", "has", "is"]).optional().describe("fits (default): within those colors; has: includes them; is: exactly them."),
68456
+ bracket: external_exports.array(external_exports.number().int().min(1).max(5)).max(5).optional().describe("Only these EDHREC bracket estimates (1-5)."),
68457
+ ownedOnly: external_exports.boolean().optional().describe("Only commanders the user owns (both halves for a pair)."),
68458
+ sortBy: external_exports.enum(["synergy", "popularity"]).optional().describe("synergy (default): share of the pool owned; popularity: EDHREC's deck count."),
68459
+ limit: external_exports.number().int().min(1).max(100).optional().describe("How many (default 20)."),
68460
+ refresh: refreshInput
68461
+ },
68462
+ async run(args, ctx) {
68463
+ if (!ctx.extras) throw new ToolProblem("The commander data isn't available in this setup.");
68464
+ if (!await ctx.library.has("collection")) throw new ToolProblem(noScopeMessage("collection"));
68465
+ const catalog = await ctx.catalog();
68466
+ const owned = await ownedIdsOf(ctx, catalog, args.refresh === true);
68467
+ const index = await ctx.extras.commandersIndex();
68468
+ const colors = typeof args.colors === "string" ? [...new Set(args.colors.toUpperCase().split(""))] : void 0;
68469
+ let ranked = rankCommanders(index.commanders, owned.ids, catalog.index, {
68470
+ sortBy: args.sortBy === "popularity" ? "popularity" : "synergy",
68471
+ ...colors ? { colors, colorMode: COLOR_MODES[args.colorMode ?? "fits"] } : {},
68472
+ ...Array.isArray(args.bracket) && args.bracket.length ? { brackets: args.bracket } : {}
68473
+ });
68474
+ if (args.ownedOnly === true) ranked = ranked.filter((r) => r.commanderOwned);
68475
+ const limit = typeof args.limit === "number" ? args.limit : 20;
68476
+ return json2({
68477
+ found: ranked.length,
68478
+ commanders: ranked.slice(0, limit).map((r) => ({
68479
+ commander: r.commander.name,
68480
+ colors: r.commander.colors.join("") || "C",
68481
+ poolOwned: `${r.synergyOwned} of ${r.poolSize}`,
68482
+ share: `${Math.round(r.synergyRatio * 100)}%`,
68483
+ ...r.commanderOwned ? { commanderOwned: true } : r.partiallyOwned ? { missingHalves: r.missingParts } : {},
68484
+ decks: r.commander.deckCount,
68485
+ ...r.commander.bracket ? { bracket: r.commander.bracket } : {}
68486
+ })),
68487
+ about: "share: how much of EDHREC's top cards for the commander the user owns (EDHVault's reading; small pools count as at least 30 cards). get_rough_draft builds a deck for one.",
68488
+ dataAsOf: index.builtAt,
68489
+ credit: EDHREC_CREDIT
68490
+ });
68491
+ }
68492
+ };
68493
+ var roughDraftTool = {
68494
+ name: "get_rough_draft",
68495
+ description: "The deck builder's Rough draft for a commander: a full deck from EDHREC's cards for it, the user's owned cards first, then the most-played cards to buy (or owned cards only), shaped to the builder's slot targets, curve and land count. A suggestion only: nothing is saved. create_deck asks to make it. Uses the collection when the access code can read it; without one, everything is a card to buy.",
68496
+ input: {
68497
+ commander: external_exports.string().min(1).describe("The commander's name."),
68498
+ partner: external_exports.string().optional().describe("A second commander (partner, background, and the like)."),
68499
+ ownedOnly: external_exports.boolean().optional().describe("Only cards the user owns, no buys (needs the collection)."),
68500
+ bracket: external_exports.number().int().min(1).max(5).optional().describe("Target bracket: caps Game Changers as the builder does. Default: the commander's own estimate."),
68501
+ priceCap: external_exports.number().positive().optional().describe("Leave out cards to buy over this price (USD)."),
68502
+ refresh: refreshInput
68503
+ },
68504
+ async run(args, ctx) {
68505
+ const x = ctx.extras;
68506
+ if (!x) throw new ToolProblem("The commander data isn't available in this setup.");
68507
+ const catalog = await ctx.catalog();
68508
+ const card = (name) => {
68509
+ const c = resolveCardName(catalog.index, name);
68510
+ if (!c) throw new ToolProblem(`No card named "${name}".`);
68511
+ return c;
68512
+ };
68513
+ const commanders = [card(String(args.commander)), ...typeof args.partner === "string" && args.partner.trim() ? [card(args.partner)] : []];
68514
+ for (const c of commanders) if (!c.canBeCommander) throw new ToolProblem(`${c.name} can't be a commander.`);
68515
+ if (commanders.length === 2) {
68516
+ const pair = isPairLegal(commanders[0], commanders[1]);
68517
+ if (!pair.legal) throw new ToolProblem(`${commanders[0].name} and ${commanders[1].name} can't be commanders together: ${pair.reason}`);
68518
+ }
68519
+ const names = commanders.map((c) => c.name);
68520
+ const index = await x.commandersIndex();
68521
+ const slugs = candidateSlugs(names);
68522
+ const summary = index.commanders.find((c) => slugs.includes(c.slug));
68523
+ if (!summary) throw new ToolProblem(`EDHREC has no page for ${names.join(" + ")}, so there's nothing to draft from.`);
68524
+ const detail = await x.commanderDetail(summary.slug);
68525
+ let qty = /* @__PURE__ */ new Map();
68526
+ let connected = false;
68527
+ try {
68528
+ const own2 = await ownership(ctx, catalog, args.refresh === true);
68529
+ qty = new Map([...own2.owned].map(([oid, o]) => [oid, o.stacks.reduce((n, s) => n + s.quantity, 0)]));
68530
+ connected = true;
68531
+ } catch (e) {
68532
+ if (!isUnread(e)) throw e;
68533
+ }
68534
+ const ownedOnly = args.ownedOnly === true;
68535
+ if (ownedOnly && !connected) throw new ToolProblem(`${noScopeMessage("collection")} So an owned-only draft can't be built.`);
68536
+ for (const c of commanders) qty.delete(c.oracleId);
68537
+ const tags = catalog.otags();
68538
+ const lens = tags ? makeCardTagLens(tags) : null;
68539
+ const built = buildDeckSlots(detail, new Set(qty.keys()), catalog.index, { ownedQuantities: qty, tagLens: lens });
68540
+ const slots = commanders.length === 2 ? built.slots.map((s) => s.slot === "other" ? { ...s, target: Math.max(0, s.target - 1) } : s) : built.slots;
68541
+ const { plan } = buildWithRecommendedLands(
68542
+ (s) => computeBestBuildPlan(
68543
+ s,
68544
+ (oid) => qty.get(oid) ?? 0,
68545
+ detail,
68546
+ true,
68547
+ "synergy",
68548
+ void 0,
68549
+ typeof args.bracket === "number" ? args.bracket : void 0,
68550
+ catalog.index,
68551
+ typeof args.priceCap === "number" ? args.priceCap : null,
68552
+ ownedOnly
68553
+ ),
68554
+ slots,
68555
+ catalog.index,
68556
+ lens
68557
+ );
68558
+ const bySlot = /* @__PURE__ */ new Map();
68559
+ const put = (slot, line) => bySlot.set(slot, [...bySlot.get(slot) ?? [], line]);
68560
+ const basics = new Map(plan.basicQuantities);
68561
+ for (const [oid, slot] of plan.assignments) {
68562
+ const c = catalog.index.byOracleId.get(oid);
68563
+ if (!c) continue;
68564
+ const n = basics.get(oid);
68565
+ basics.delete(oid);
68566
+ put(slot, n && n > 1 ? `${n} ${c.name}` : c.name);
68567
+ }
68568
+ for (const [oid, n] of basics) {
68569
+ const c = catalog.index.byOracleId.get(oid);
68570
+ if (c) put("lands", `${n} ${c.name}`);
68571
+ }
68572
+ const buys = [];
68573
+ for (const [slug, slot] of plan.purchases) {
68574
+ const c = catalog.bySlug.get(slug);
68575
+ const name = c?.name ?? slug;
68576
+ buys.push(name);
68577
+ put(slot, `${name} (buy)`);
68578
+ }
68579
+ const total = [...plan.assignments.keys()].reduce((n, oid) => n + (plan.basicQuantities.get(oid) ?? 1), 0) + [...basics.values()].reduce((n, v) => n + v, 0) + plan.purchases.size;
68580
+ return json2({
68581
+ commander: names.join(" + "),
68582
+ cards: total,
68583
+ owned: total - plan.purchases.size,
68584
+ toBuy: plan.purchases.size,
68585
+ ...plan.skippedLowSignalOwned ? { ownedSetAside: plan.skippedLowSignalOwned } : {},
68586
+ slots: Object.fromEntries(bySlot),
68587
+ ...connected ? {} : { ownedLeftOut: noScopeMessage("collection") },
68588
+ about: "EDHVault's Rough draft: the builder's own engine, from EDHREC's cards for this commander. A suggestion only, nothing saved: create_deck asks to make it (with each card, and to: deck).",
68589
+ dataAsOf: index.builtAt,
68590
+ credit: EDHREC_CREDIT
68591
+ });
68592
+ }
68593
+ };
68594
+ var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, compareTool, overlapTool, manabaseTool, planOdds, editDeckTool, setDeckNotesTool, moveToFolderTool, createDeckTool, collectionTool("collection_add"), collectionTool("collection_remove"), wishlistEditTool, binderEditTool, setCardReadTool, getRequestsTool, collectionValueTool, deckHistoryTool, listsTool, commandersToBuildTool, roughDraftTool];
67225
68595
 
67226
68596
  // src/server.ts
67227
68597
  function buildServer(version2, ctx) {
@@ -67253,7 +68623,7 @@ var say = (m) => process.stderr.write(`${m}
67253
68623
  var transport = {
67254
68624
  fetchImpl: ((url2, init) => fetch(`${ORIGIN}${url2}`, {
67255
68625
  ...init,
67256
- headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.24"}` }
68626
+ headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.25"}` }
67257
68627
  }))
67258
68628
  };
67259
68629
  async function store(dir) {
@@ -67269,7 +68639,7 @@ async function secretFromEnv() {
67269
68639
  async function main() {
67270
68640
  const args = process.argv.slice(2);
67271
68641
  if (args.includes("--version")) {
67272
- say("0.2.24");
68642
+ say("0.2.25");
67273
68643
  return;
67274
68644
  }
67275
68645
  const dir = configDir();
@@ -67292,7 +68662,7 @@ async function main() {
67292
68662
  }
67293
68663
  const extras = extrasLoader({ dir, origin: ORIGIN });
67294
68664
  const fromEnv = await secretFromEnv();
67295
- await serve("0.2.24", {
68665
+ await serve("0.2.25", {
67296
68666
  // The saved login is read again when not connected and on refresh, so
67297
68667
  // `login` in another terminal works without restarting the AI tool.
67298
68668
  library: new Library({ secret: () => fromEnv ?? loadSecret(secrets), dir, transport }),