edhvault-mcp 0.2.11 → 0.2.15

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 +11 -2
  2. package/dist/cli.js +1477 -108
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -791,6 +791,12 @@ async function call(t, url2, init, timeoutMs = FETCH_TIMEOUTS.sync.timeoutMs) {
791
791
  if (why === "too many devices") {
792
792
  throw new SyncHttpError("forbidden", "This sync space already has the most devices it can hold (20). Remove one first.");
793
793
  }
794
+ if (why === "outdated") {
795
+ throw new SyncHttpError("outdated", "This access code is from an older version of EDHVault. Make a new one in edhvault Settings, AI tools access.");
796
+ }
797
+ if (why === "scope") {
798
+ throw new SyncHttpError("no-scope", "This access code can't read that part of your library.");
799
+ }
794
800
  if (why === "too many codes") {
795
801
  throw new SyncHttpError("forbidden", "You already have the most access codes you can (10). Remove one first.");
796
802
  }
@@ -825,8 +831,8 @@ async function agentFetchBundle(token, t = {}) {
825
831
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
826
832
  return new Uint8Array(await res.arrayBuffer());
827
833
  }
828
- async function agentFetchView(token, etag, t = {}) {
829
- const res = await call(t, `${SYNC_AGENT_API}/view`, {
834
+ async function agentFetchView(token, scope, etag, t = {}) {
835
+ const res = await call(t, `${SYNC_AGENT_API}/view?scope=${encodeURIComponent(scope)}`, {
830
836
  method: "GET",
831
837
  headers: { ...agentHeaders(token), ...etag ? { "x-sync-if-none-match": etag } : {} }
832
838
  });
@@ -836,11 +842,11 @@ async function agentFetchView(token, etag, t = {}) {
836
842
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
837
843
  return { status: "ok", etag: tag, sealed: new Uint8Array(await res.arrayBuffer()) };
838
844
  }
839
- async function agentFetchObjects(token, names, t = {}) {
845
+ async function agentFetchObjects(token, scope, names, t = {}) {
840
846
  const res = await call(t, `${SYNC_AGENT_API}/get`, {
841
847
  method: "POST",
842
848
  headers: { ...agentHeaders(token), "content-type": "application/json" },
843
- body: JSON.stringify({ items: names })
849
+ body: JSON.stringify({ scope, items: names })
844
850
  });
845
851
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
846
852
  const parsed = unframe(new Uint8Array(await res.arrayBuffer()));
@@ -14578,12 +14584,12 @@ function cardMatchesProduces(produced, clause) {
14578
14584
  }
14579
14585
  function cardMatchesDerivedFlag(card, flag) {
14580
14586
  const t = card.typeLine.toLowerCase();
14581
- const isLand4 = t.includes("land");
14587
+ const isLand5 = t.includes("land");
14582
14588
  const layout = card.layout ?? "normal";
14583
14589
  switch (flag) {
14584
14590
  // Cast from hand as a spell — everything that isn't a land.
14585
14591
  case "spell":
14586
- return !isLand4;
14592
+ return !isLand5;
14587
14593
  // Stays on the battlefield.
14588
14594
  case "permanent":
14589
14595
  return /\b(creature|artifact|enchantment|land|planeswalker|battle)\b/.test(t) && !/\b(instant|sorcery)\b/.test(t);
@@ -16050,7 +16056,14 @@ import { join as join6 } from "node:path";
16050
16056
  init_sealedBox();
16051
16057
  init_syncKeys();
16052
16058
  var AGENT_CODE_PREFIX = "EV-AI-";
16053
- var AGENT_SCOPE = "read";
16059
+ var AGENT_SCOPES = ["decks", "notes", "collection", "lists"];
16060
+ var OUTDATED_CODE_MESSAGE = "This access code is from an older version of EDHVault. Make a new one in edhvault Settings, AI tools access.";
16061
+ var AgentCodeOutdated = class extends Error {
16062
+ constructor() {
16063
+ super(OUTDATED_CODE_MESSAGE);
16064
+ this.name = "AgentCodeOutdated";
16065
+ }
16066
+ };
16054
16067
  async function deriveAgentKeys(secret) {
16055
16068
  const [access, wrapKey] = await Promise.all([
16056
16069
  deriveLabelled(secret, "agent-access", 256),
@@ -16071,23 +16084,29 @@ async function parseAgentCode(text) {
16071
16084
  var bundleAad = (ah) => `agent-bundle:${ah}`;
16072
16085
  async function openAgentBundle(sealed, keys) {
16073
16086
  const b = JSON.parse(await openText(sealed, keys.wrapKey, { aad: bundleAad(keys.ah) }));
16074
- const viewKey = b.v === 1 && b.scope === AGENT_SCOPE ? keyFromText(b.viewKey) : null;
16075
- if (!viewKey) throw new Error("This access code's data is from a newer version.");
16076
- return viewKey;
16087
+ if (b.v === 1) throw new AgentCodeOutdated();
16088
+ if (b.v !== 2 || !b.keys || typeof b.keys !== "object") throw new Error("This access code's data is from a newer version.");
16089
+ const out = {};
16090
+ for (const s of AGENT_SCOPES) {
16091
+ const text = b.keys[s];
16092
+ const k = typeof text === "string" ? keyFromText(text) : null;
16093
+ if (k) out[s] = k;
16094
+ }
16095
+ return out;
16077
16096
  }
16078
16097
 
16079
16098
  // ../src/lib/sync/agentView.ts
16080
16099
  init_sealedBox();
16081
16100
  init_syncKeys();
16082
16101
  init_syncApi();
16083
- var viewAad = (name) => `v:${name}`;
16084
- var INDEX_AAD = "v:index";
16085
- function openViewObject(sealed, viewKey, name) {
16086
- return openText(sealed, viewKey, { aad: viewAad(name) });
16087
- }
16088
- async function openViewIndex(sealed, viewKey) {
16089
- const index = JSON.parse(await openText(sealed, viewKey, { aad: INDEX_AAD }));
16090
- if (!index || index.v !== 1 || typeof index.decks !== "object") {
16102
+ var viewAad = (scope, name) => `v2:${scope}:${name}`;
16103
+ var indexAad = (scope) => `v2:${scope}:index`;
16104
+ function openViewObject(sealed, viewKey, scope, name) {
16105
+ return openText(sealed, viewKey, { aad: viewAad(scope, name) });
16106
+ }
16107
+ async function openViewIndex(sealed, viewKey, scope) {
16108
+ const index = JSON.parse(await openText(sealed, viewKey, { aad: indexAad(scope) }));
16109
+ if (!index || index.v !== 2 || index.scope !== scope || typeof index.decks !== "object") {
16091
16110
  throw new Error("The read copy was written by a newer version of EDHVault.");
16092
16111
  }
16093
16112
  return index;
@@ -16108,9 +16127,18 @@ var LibraryError = class extends Error {
16108
16127
  }
16109
16128
  kind;
16110
16129
  };
16130
+ var KeySwapped = class extends Error {
16131
+ };
16111
16132
  var NOT_CONNECTED = "Not connected yet. Run `npx edhvault-mcp login`, or make a code in edhvault Settings, AI tools access.";
16112
16133
  var REMOVED = "This access code was removed. Connect again in edhvault Settings, AI tools access.";
16113
16134
  var NO_COPY = "Your library isn't ready yet. Open edhvault on a synced device, then try again.";
16135
+ var SCOPE_WHAT = {
16136
+ decks: "your decks",
16137
+ notes: "your deck notes, primers and descriptions",
16138
+ collection: "your collection",
16139
+ lists: "your wishlist, binders and seeds"
16140
+ };
16141
+ var noScopeMessage = (scope) => `This access code can't read ${SCOPE_WHAT[scope]}. What a code can read is chosen in edhvault Settings, AI tools access.`;
16114
16142
  function entries(index) {
16115
16143
  return [
16116
16144
  ...Object.values(index.decks),
@@ -16121,104 +16149,155 @@ function entries(index) {
16121
16149
  var Library = class {
16122
16150
  constructor(opts) {
16123
16151
  this.opts = opts;
16124
- this.cache = join6(opts.dir, "view");
16152
+ this.cache = join6(opts.dir, "view2");
16153
+ rmSync2(join6(opts.dir, "view"), { recursive: true, force: true });
16125
16154
  this.now = opts.now ?? Date.now;
16126
16155
  this.freshMs = opts.freshMs ?? FRESH_MS;
16127
16156
  }
16128
16157
  opts;
16129
16158
  token = null;
16130
- viewKey = null;
16131
- index = null;
16132
- etag = null;
16133
- checkedAt = 0;
16159
+ keys = null;
16160
+ parts = /* @__PURE__ */ new Map();
16134
16161
  cache;
16135
16162
  now;
16136
16163
  freshMs;
16164
+ forget() {
16165
+ rmSync2(this.cache, { recursive: true, force: true });
16166
+ this.parts.clear();
16167
+ this.token = null;
16168
+ this.keys = null;
16169
+ }
16137
16170
  fail(e) {
16171
+ if (e instanceof AgentCodeOutdated || e instanceof SyncHttpError && e.kind === "outdated") {
16172
+ this.forget();
16173
+ throw new LibraryError("outdated", OUTDATED_CODE_MESSAGE);
16174
+ }
16138
16175
  if (e instanceof SyncHttpError) {
16139
16176
  if (e.kind === "forbidden") {
16140
- rmSync2(this.cache, { recursive: true, force: true });
16141
- this.index = null;
16142
- this.etag = null;
16143
- this.token = null;
16144
- this.viewKey = null;
16177
+ this.forget();
16145
16178
  throw new LibraryError("removed", REMOVED);
16146
16179
  }
16180
+ if (e.kind === "no-scope") {
16181
+ this.token = null;
16182
+ this.keys = null;
16183
+ throw new LibraryError("no-scope", e.message);
16184
+ }
16147
16185
  if (e.kind === "network") throw new LibraryError("offline", "Couldn't reach edhvault.com.");
16148
16186
  }
16149
16187
  throw e;
16150
16188
  }
16151
16189
  async connect() {
16152
- if (this.token && this.viewKey) return { token: this.token, viewKey: this.viewKey };
16190
+ if (this.token && this.keys) return { token: this.token, keys: this.keys };
16153
16191
  if (!this.opts.secret) throw new LibraryError("not-connected", NOT_CONNECTED);
16154
- const keys = await deriveAgentKeys(this.opts.secret);
16155
- let viewKey;
16192
+ const agent = await deriveAgentKeys(this.opts.secret);
16193
+ let keys;
16156
16194
  try {
16157
- viewKey = await openAgentBundle(await agentFetchBundle(keys.token, this.opts.transport), keys);
16195
+ keys = await openAgentBundle(await agentFetchBundle(agent.token, this.opts.transport), agent);
16158
16196
  } catch (e) {
16159
16197
  this.fail(e);
16160
16198
  }
16161
- this.token = keys.token;
16162
- this.viewKey = viewKey;
16163
- return { token: keys.token, viewKey };
16199
+ this.token = agent.token;
16200
+ this.keys = keys;
16201
+ return { token: agent.token, keys };
16164
16202
  }
16165
- /** The read copy's index, at most FRESH_MS old unless `refresh`. */
16166
- async view(refresh = false) {
16167
- const { token, viewKey } = await this.connect();
16168
- if (this.index && !refresh && this.now() - this.checkedAt < this.freshMs) return this.index;
16203
+ /** The parts this code may read. */
16204
+ async scopes() {
16205
+ const { keys } = await this.connect();
16206
+ return AGENT_SCOPES.filter((s) => keys[s]);
16207
+ }
16208
+ /** Whether this code may read a part. */
16209
+ async has(scope) {
16210
+ return (await this.scopes()).includes(scope);
16211
+ }
16212
+ async key(scope) {
16213
+ const { token, keys } = await this.connect();
16214
+ const key = keys[scope];
16215
+ if (!key) throw new LibraryError("no-scope", noScopeMessage(scope));
16216
+ return { token, key };
16217
+ }
16218
+ /** One part's index, at most FRESH_MS old unless `refresh`. */
16219
+ async view(scope, refresh = false) {
16220
+ try {
16221
+ return await this.viewOnce(scope, refresh);
16222
+ } catch (e) {
16223
+ if (!(e instanceof KeySwapped)) throw e;
16224
+ }
16225
+ this.token = null;
16226
+ this.keys = null;
16227
+ this.parts.delete(scope);
16228
+ try {
16229
+ return await this.viewOnce(scope, true);
16230
+ } catch (e) {
16231
+ if (e instanceof KeySwapped) throw new LibraryError("no-copy", NO_COPY);
16232
+ throw e;
16233
+ }
16234
+ }
16235
+ async viewOnce(scope, refresh) {
16236
+ const { token, key } = await this.key(scope);
16237
+ const part2 = this.parts.get(scope) ?? { index: null, etag: null, checkedAt: 0 };
16238
+ this.parts.set(scope, part2);
16239
+ if (part2.index && !refresh && this.now() - part2.checkedAt < this.freshMs) return part2.index;
16169
16240
  let got;
16170
16241
  try {
16171
- got = await agentFetchView(token, this.etag, this.opts.transport);
16242
+ got = await agentFetchView(token, scope, part2.etag, this.opts.transport);
16172
16243
  } catch (e) {
16173
- if (this.index && e instanceof SyncHttpError && e.kind === "network") return this.index;
16244
+ if (part2.index && e instanceof SyncHttpError && e.kind === "network") return part2.index;
16174
16245
  this.fail(e);
16175
16246
  }
16176
16247
  if (got.status === "missing") throw new LibraryError("no-copy", NO_COPY);
16177
- this.checkedAt = this.now();
16248
+ part2.checkedAt = this.now();
16178
16249
  if (got.status === "ok") {
16179
- this.index = await openViewIndex(got.sealed, viewKey);
16180
- this.etag = got.etag;
16181
- this.prune(this.index);
16250
+ try {
16251
+ part2.index = await openViewIndex(got.sealed, key, scope);
16252
+ } catch {
16253
+ throw new KeySwapped();
16254
+ }
16255
+ part2.etag = got.etag;
16256
+ this.prune(scope, part2.index);
16182
16257
  }
16183
- return this.index;
16258
+ return part2.index;
16259
+ }
16260
+ dirOf(scope) {
16261
+ return join6(this.cache, scope);
16184
16262
  }
16185
- prune(index) {
16186
- if (!existsSync4(this.cache)) return;
16263
+ prune(scope, index) {
16264
+ const dir = this.dirOf(scope);
16265
+ if (!existsSync4(dir)) return;
16187
16266
  const live = new Set(entries(index).map((e) => e.obj));
16188
- for (const f of readdirSync(this.cache)) if (!live.has(f)) rmSync2(join6(this.cache, f), { force: true });
16267
+ for (const f of readdirSync(dir)) if (!live.has(f)) rmSync2(join6(dir, f), { force: true });
16189
16268
  }
16190
- /** Object texts by name, from the disk cache or batched reads. */
16191
- async read(list) {
16192
- const { token, viewKey } = await this.connect();
16193
- mkdirSync3(this.cache, { recursive: true });
16269
+ /** Object texts of one part by name, from the disk cache or batched reads. */
16270
+ async read(scope, list) {
16271
+ const { token, key } = await this.key(scope);
16272
+ const dir = this.dirOf(scope);
16273
+ mkdirSync3(dir, { recursive: true });
16194
16274
  const sealed = /* @__PURE__ */ new Map();
16195
16275
  const missing = [];
16196
16276
  for (const e of list) {
16197
- const file3 = join6(this.cache, e.obj);
16277
+ const file3 = join6(dir, e.obj);
16198
16278
  if (existsSync4(file3)) sealed.set(e.obj, new Uint8Array(readFileSync6(file3)));
16199
16279
  else missing.push(e.obj);
16200
16280
  }
16201
16281
  for (let i = 0; i < missing.length; i += GET_BATCH) {
16202
16282
  let got;
16203
16283
  try {
16204
- got = await agentFetchObjects(token, missing.slice(i, i + GET_BATCH), this.opts.transport);
16284
+ got = await agentFetchObjects(token, scope, missing.slice(i, i + GET_BATCH), this.opts.transport);
16205
16285
  } catch (e) {
16206
16286
  this.fail(e);
16207
16287
  }
16208
16288
  for (const [name, bytes] of got) {
16209
16289
  if (!bytes) continue;
16210
16290
  sealed.set(name, bytes);
16211
- writeFileSync3(join6(this.cache, name), bytes);
16291
+ writeFileSync3(join6(dir, name), bytes);
16212
16292
  }
16213
16293
  }
16214
16294
  const out = /* @__PURE__ */ new Map();
16215
- for (const [name, bytes] of sealed) out.set(name, await openViewObject(bytes, viewKey, name));
16295
+ for (const [name, bytes] of sealed) out.set(name, await openViewObject(bytes, key, scope, name));
16216
16296
  return out;
16217
16297
  }
16218
- /** Every deck, parsed, by deck id. */
16219
- async decks(refresh = false) {
16220
- const index = await this.view(refresh);
16221
- const texts = await this.read(Object.values(index.decks));
16298
+ async partDecks(scope, refresh) {
16299
+ const index = await this.view(scope, refresh);
16300
+ const texts = await this.read(scope, Object.values(index.decks));
16222
16301
  const out = /* @__PURE__ */ new Map();
16223
16302
  for (const [id, e] of Object.entries(index.decks)) {
16224
16303
  const text = texts.get(e.obj);
@@ -16226,24 +16305,47 @@ var Library = class {
16226
16305
  }
16227
16306
  return out;
16228
16307
  }
16308
+ /** Every deck, parsed, by deck id: the decks part, so without primers,
16309
+ * descriptions and notes (those are `notesOf`). */
16310
+ async decks(refresh = false) {
16311
+ return this.partDecks("decks", refresh);
16312
+ }
16313
+ /** One deck's primer, description and notes, from the notes part. null when
16314
+ * the code can't read notes (`has("notes")`) or the deck has none. */
16315
+ async notesOf(id, refresh = false) {
16316
+ if (!await this.has("notes")) return null;
16317
+ const index = await this.view("notes", refresh);
16318
+ const e = index.decks[id];
16319
+ if (!e) return null;
16320
+ const text = (await this.read("notes", [e])).get(e.obj);
16321
+ return text ? JSON.parse(text, reviver) : null;
16322
+ }
16229
16323
  /** Every collection stack. */
16230
16324
  async collection(refresh = false) {
16231
- const index = await this.view(refresh);
16325
+ const index = await this.view("collection", refresh);
16232
16326
  const chunks = Object.values(index.coll?.chunks ?? {});
16233
- const texts = await this.read(chunks);
16327
+ const texts = await this.read("collection", chunks);
16234
16328
  return chunks.flatMap((e) => {
16235
16329
  const text = texts.get(e.obj);
16236
16330
  if (!text) return [];
16237
16331
  return JSON.parse(text).stacks.map(([, stack]) => stack);
16238
16332
  });
16239
16333
  }
16240
- /** The library document, or null when the space has none yet. */
16241
- async library(refresh = false) {
16242
- const index = await this.view(refresh);
16334
+ async partLib(scope, refresh) {
16335
+ if (!await this.has(scope)) return null;
16336
+ const index = await this.view(scope, refresh);
16243
16337
  if (!index.lib) return null;
16244
- const text = (await this.read([index.lib])).get(index.lib.obj);
16338
+ const text = (await this.read(scope, [index.lib])).get(index.lib.obj);
16245
16339
  return text ? JSON.parse(text) : null;
16246
16340
  }
16341
+ /** The library document, from the parts this code holds: the decks part's
16342
+ * folders, card reads and odds plans, the lists part's wishlist, binders and
16343
+ * seeds. null when it holds neither, or the space has none yet. */
16344
+ async library(refresh = false) {
16345
+ const [decks, lists] = await Promise.all([this.partLib("decks", refresh), this.partLib("lists", refresh)]);
16346
+ if (!decks && !lists) return null;
16347
+ return { ...decks ?? {}, ...lists ?? {} };
16348
+ }
16247
16349
  };
16248
16350
 
16249
16351
  // src/log.ts
@@ -48690,6 +48792,187 @@ function groupByDeckCard(variants) {
48690
48792
  );
48691
48793
  }
48692
48794
 
48795
+ // ../src/lib/deckPlan/compareSources.ts
48796
+ init_slug();
48797
+
48798
+ // ../src/lib/deckPlan/compareDecks.ts
48799
+ function buildDeckCardMap(entries2) {
48800
+ const map2 = /* @__PURE__ */ new Map();
48801
+ for (const entry of entries2) {
48802
+ const card = entry?.card;
48803
+ const qty = entry?.qty ?? 0;
48804
+ if (!card || !card.oracleId || qty <= 0) continue;
48805
+ const prev = map2.get(card.oracleId);
48806
+ if (prev) prev.qty += qty;
48807
+ else map2.set(card.oracleId, { card, qty });
48808
+ }
48809
+ return map2;
48810
+ }
48811
+ var byCardName = (a, b) => a.card.name.localeCompare(b.card.name);
48812
+ function compareDecks(mine, theirs) {
48813
+ const onlyMine = [];
48814
+ const onlyTheirs = [];
48815
+ const shared = [];
48816
+ for (const [oracleId, { card, qty }] of mine) {
48817
+ const t = theirs.get(oracleId);
48818
+ if (t) {
48819
+ shared.push({ oracleId, card, mineQty: qty, theirsQty: t.qty });
48820
+ } else {
48821
+ onlyMine.push({ oracleId, card, qty });
48822
+ }
48823
+ }
48824
+ for (const [oracleId, { card, qty }] of theirs) {
48825
+ if (!mine.has(oracleId)) onlyTheirs.push({ oracleId, card, qty });
48826
+ }
48827
+ onlyMine.sort(byCardName);
48828
+ onlyTheirs.sort(byCardName);
48829
+ shared.sort(byCardName);
48830
+ return { onlyMine, onlyTheirs, shared };
48831
+ }
48832
+ function isQtyDelta(s) {
48833
+ return s.mineQty !== s.theirsQty;
48834
+ }
48835
+ function buyDifference(bucket, owned) {
48836
+ let own2 = 0;
48837
+ let buyCount = 0;
48838
+ let buyUsd = 0;
48839
+ for (const e of bucket) {
48840
+ if (owned.has(e.oracleId)) {
48841
+ own2++;
48842
+ continue;
48843
+ }
48844
+ buyCount++;
48845
+ buyUsd += (e.card.priceUsd ?? 0) * e.qty;
48846
+ }
48847
+ return { differ: bucket.length, own: own2, buyCount, buyUsd };
48848
+ }
48849
+
48850
+ // ../src/lib/deckPlan/compareSources.ts
48851
+ function deckCardMapFromStored(blob, cards, slugIndex) {
48852
+ const counts = [];
48853
+ for (const [oid] of blob.assignments) {
48854
+ const card = cards.byOracleId.get(oid);
48855
+ if (card) counts.push({ card, qty: blob.basicQuantities.get(oid) ?? 1 });
48856
+ }
48857
+ for (const [slug] of blob.purchases) {
48858
+ const card = slugIndex.get(slug);
48859
+ if (card) counts.push({ card, qty: blob.purchaseQuantities?.get(slug) ?? 1 });
48860
+ }
48861
+ return buildDeckCardMap(counts);
48862
+ }
48863
+ function buildSlugCardIndex(cards) {
48864
+ const map2 = /* @__PURE__ */ new Map();
48865
+ for (const card of cards.byOracleId.values()) {
48866
+ const slug = toEdhrecSlug(card.name);
48867
+ if (!map2.has(slug)) map2.set(slug, card);
48868
+ if (card.name.includes(" // ")) {
48869
+ const joined = toEdhrecSlug(card.name, { joined: true });
48870
+ if (!map2.has(joined)) map2.set(joined, card);
48871
+ }
48872
+ }
48873
+ return map2;
48874
+ }
48875
+
48876
+ // ../src/lib/deckPlan/crossDeckOverlap.ts
48877
+ function crossDeckOverlap(decks) {
48878
+ const acc = /* @__PURE__ */ new Map();
48879
+ decks.forEach((deck, i) => {
48880
+ for (const [oid, { card, qty }] of deck) {
48881
+ let e = acc.get(oid);
48882
+ if (!e) {
48883
+ e = { card, deckIndices: [], qtyPerDeck: [] };
48884
+ acc.set(oid, e);
48885
+ }
48886
+ e.deckIndices.push(i);
48887
+ e.qtyPerDeck.push(qty);
48888
+ }
48889
+ });
48890
+ const out = [];
48891
+ for (const [oracleId, e] of acc) {
48892
+ out.push({
48893
+ oracleId,
48894
+ card: e.card,
48895
+ inCount: e.deckIndices.length,
48896
+ deckIndices: e.deckIndices,
48897
+ qtyPerDeck: e.qtyPerDeck,
48898
+ maxQty: Math.max(...e.qtyPerDeck)
48899
+ });
48900
+ }
48901
+ out.sort(
48902
+ (a, b) => b.inCount - a.inCount || a.card.name.localeCompare(b.card.name)
48903
+ );
48904
+ return out;
48905
+ }
48906
+
48907
+ // ../src/lib/deckPlan/stickerShare.ts
48908
+ init_utils();
48909
+ var MIN_SHARED_DECKS = 2;
48910
+ function filterOverlap(entries2, opts) {
48911
+ return entries2.filter(
48912
+ (e) => e.inCount >= opts.minDecks && (opts.includeBasics || !isBasicLandType(e.card.typeLine))
48913
+ );
48914
+ }
48915
+ function stickerReadout(entry, owned) {
48916
+ let copiesIfSeparate = 0;
48917
+ for (const q of entry.qtyPerDeck) copiesIfSeparate += q;
48918
+ const copiesToShare = entry.maxQty;
48919
+ return {
48920
+ inCount: entry.inCount,
48921
+ copiesToShare,
48922
+ copiesIfSeparate,
48923
+ saved: copiesIfSeparate - copiesToShare,
48924
+ ownership: owned ? owned.has(entry.oracleId) ? "own" : "buy" : null
48925
+ };
48926
+ }
48927
+ function summarizeStickerShare(rows, owned) {
48928
+ let savedCopies = 0;
48929
+ let savedUsd = 0;
48930
+ let ownedCount = 0;
48931
+ for (const e of rows) {
48932
+ let sum = 0;
48933
+ for (const q of e.qtyPerDeck) sum += q;
48934
+ const saved = sum - e.maxQty;
48935
+ savedCopies += saved;
48936
+ savedUsd += saved * (e.card.priceUsd ?? 0);
48937
+ if (owned && owned.has(e.oracleId)) ownedCount++;
48938
+ }
48939
+ return {
48940
+ sharedCards: rows.length,
48941
+ savedCopies,
48942
+ ownedCount: owned ? ownedCount : null,
48943
+ toBuyCount: owned ? rows.length - ownedCount : null,
48944
+ savedUsd
48945
+ };
48946
+ }
48947
+
48948
+ // ../src/lib/deckPlan/overlapSort.ts
48949
+ var DEFAULT_DIR = {
48950
+ name: "asc",
48951
+ in: "desc",
48952
+ sticker: "asc",
48953
+ price: "desc"
48954
+ };
48955
+ var byName = (a, b) => a.card.name.localeCompare(b.card.name);
48956
+ function sortOverlapRows(rows, key, dir, owned) {
48957
+ const sign = dir === "asc" ? 1 : -1;
48958
+ const cmp = (a, b) => {
48959
+ switch (key) {
48960
+ case "name":
48961
+ return sign * byName(a, b);
48962
+ case "in":
48963
+ return sign * (a.inCount - b.inCount) || byName(a, b);
48964
+ case "price":
48965
+ return sign * ((a.card.priceUsd ?? 0) - (b.card.priceUsd ?? 0)) || byName(a, b);
48966
+ case "sticker": {
48967
+ const oa = owned ? owned.has(a.oracleId) ? 1 : 0 : 0;
48968
+ const ob = owned ? owned.has(b.oracleId) ? 1 : 0 : 0;
48969
+ return sign * (oa - ob) || byName(a, b);
48970
+ }
48971
+ }
48972
+ };
48973
+ return [...rows].sort(cmp);
48974
+ }
48975
+
48693
48976
  // ../src/lib/deckPlan/tutorMvGates.generated.ts
48694
48977
  var PRINTED_MV_GATES = {
48695
48978
  "4c80112a-8ff5-4ca4-8737-b8d499d78982": ["lte", 3],
@@ -51766,6 +52049,734 @@ function budgetStatus(spent, budget) {
51766
52049
  return { over: spent > budget, delta: spent - budget };
51767
52050
  }
51768
52051
 
52052
+ // ../src/lib/deckPlan/karstenTable.generated.ts
52053
+ var KARSTEN_2022 = {
52054
+ landsFrom: 28,
52055
+ landsTo: 45,
52056
+ rows: {
52057
+ 28: [
52058
+ [16, 15, 14, 12, 11, 10, 9],
52059
+ [null, 24, 21, 19, 17, 15, 14],
52060
+ [null, null, 27, 24, 21, 19, 18],
52061
+ [null, null, null, 28, 25, 23, 21]
52062
+ ],
52063
+ 29: [
52064
+ [16, 16, 14, 13, 11, 10, 10],
52065
+ [null, 24, 22, 19, 17, 16, 15],
52066
+ [null, null, 27, 25, 22, 20, 19],
52067
+ [null, null, null, 28, 26, 24, 22]
52068
+ ],
52069
+ 30: [
52070
+ [16, 16, 14, 13, 12, 11, 10],
52071
+ [null, 25, 22, 20, 18, 16, 15],
52072
+ [null, null, 28, 25, 23, 21, 19],
52073
+ [null, null, null, 29, 27, 25, 23]
52074
+ ],
52075
+ 31: [
52076
+ [17, 16, 15, 13, 12, 11, 10],
52077
+ [null, 25, 23, 20, 18, 17, 16],
52078
+ [null, null, 29, 26, 23, 21, 20],
52079
+ [null, null, null, 30, 28, 25, 23]
52080
+ ],
52081
+ 32: [
52082
+ [17, 16, 15, 14, 12, 11, 11],
52083
+ [null, 26, 23, 21, 19, 17, 16],
52084
+ [null, null, 30, 27, 24, 22, 20],
52085
+ [null, null, null, 31, 29, 26, 24]
52086
+ ],
52087
+ 33: [
52088
+ [17, 17, 15, 14, 13, 12, 11],
52089
+ [null, 26, 24, 22, 19, 18, 17],
52090
+ [null, null, 31, 27, 25, 23, 21],
52091
+ [null, null, null, 32, 29, 27, 25]
52092
+ ],
52093
+ 34: [
52094
+ [18, 17, 16, 14, 13, 12, 11],
52095
+ [null, 27, 25, 22, 20, 18, 17],
52096
+ [null, null, 31, 28, 26, 23, 22],
52097
+ [null, null, null, 33, 30, 28, 26]
52098
+ ],
52099
+ 35: [
52100
+ [18, 17, 16, 15, 13, 12, 12],
52101
+ [null, 27, 25, 23, 21, 19, 17],
52102
+ [null, null, 32, 29, 26, 24, 22],
52103
+ [null, null, null, 34, 31, 28, 26]
52104
+ ],
52105
+ 36: [
52106
+ [18, 18, 16, 15, 14, 13, 12],
52107
+ [null, 28, 26, 23, 21, 19, 18],
52108
+ [null, null, 33, 30, 27, 25, 23],
52109
+ [null, null, null, 35, 32, 29, 27]
52110
+ ],
52111
+ 37: [
52112
+ [18, 18, 17, 15, 14, 13, 12],
52113
+ [null, 28, 26, 24, 22, 20, 18],
52114
+ [null, null, 33, 30, 28, 25, 24],
52115
+ [null, null, null, 36, 33, 30, 28]
52116
+ ],
52117
+ 38: [
52118
+ [19, 18, 17, 16, 14, 13, 13],
52119
+ [null, 28, 26, 24, 22, 20, 19],
52120
+ [null, null, 34, 31, 28, 26, 24],
52121
+ [null, null, null, 36, 33, 31, 29]
52122
+ ],
52123
+ 39: [
52124
+ [19, 18, 17, 16, 15, 14, 13],
52125
+ [null, 29, 27, 25, 23, 21, 19],
52126
+ [null, null, 35, 32, 29, 27, 25],
52127
+ [null, null, null, 37, 34, 32, 29]
52128
+ ],
52129
+ 40: [
52130
+ [19, 18, 17, 16, 15, 14, 13],
52131
+ [null, 29, 27, 25, 23, 21, 20],
52132
+ [null, null, 35, 32, 30, 27, 25],
52133
+ [null, null, null, 38, 35, 32, 30]
52134
+ ],
52135
+ 41: [
52136
+ [19, 19, 18, 16, 15, 14, 14],
52137
+ [null, 30, 28, 26, 23, 22, 20],
52138
+ [null, null, 36, 33, 30, 28, 26],
52139
+ [null, null, null, 39, 36, 33, 31]
52140
+ ],
52141
+ 42: [
52142
+ [20, 19, 18, 17, 16, 15, 14],
52143
+ [null, 30, 28, 26, 24, 22, 21],
52144
+ [null, null, 37, 34, 31, 28, 26],
52145
+ [null, null, null, 40, 36, 34, 31]
52146
+ ],
52147
+ 43: [
52148
+ [20, 19, 18, 17, 16, 15, 14],
52149
+ [null, 30, 29, 26, 24, 23, 21],
52150
+ [null, null, 37, 34, 31, 29, 27],
52151
+ [null, null, null, 40, 37, 34, 32]
52152
+ ],
52153
+ 44: [
52154
+ [20, 19, 18, 17, 16, 15, 14],
52155
+ [null, 31, 29, 27, 25, 23, 22],
52156
+ [null, null, 38, 35, 32, 30, 28],
52157
+ [null, null, null, 41, 38, 35, 33]
52158
+ ],
52159
+ 45: [
52160
+ [20, 20, 19, 18, 16, 15, 15],
52161
+ [null, 31, 29, 27, 25, 24, 22],
52162
+ [null, null, 38, 35, 33, 30, 28],
52163
+ [null, null, null, 42, 39, 36, 33]
52164
+ ]
52165
+ }
52166
+ };
52167
+
52168
+ // ../src/lib/deckPlan/manabase.ts
52169
+ function sumDeckPips(cards) {
52170
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52171
+ for (const c of cards) {
52172
+ if (!c.colorPips) continue;
52173
+ out.W += c.colorPips.W;
52174
+ out.U += c.colorPips.U;
52175
+ out.B += c.colorPips.B;
52176
+ out.R += c.colorPips.R;
52177
+ out.G += c.colorPips.G;
52178
+ }
52179
+ return out;
52180
+ }
52181
+ function distributeBasics(pips, identity2, slotCount) {
52182
+ const allowed = new Set(identity2);
52183
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52184
+ if (slotCount <= 0) return out;
52185
+ const inIdentity = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52186
+ let totalInIdentity = 0;
52187
+ for (const c of WUBRG_ORDER) {
52188
+ if (!allowed.has(c)) continue;
52189
+ inIdentity[c] = pips[c];
52190
+ totalInIdentity += pips[c];
52191
+ }
52192
+ if (totalInIdentity === 0 || allowed.size === 0) {
52193
+ if (allowed.size === 0) return out;
52194
+ const per = Math.floor(slotCount / allowed.size);
52195
+ let remainder = slotCount - per * allowed.size;
52196
+ for (const c of WUBRG_ORDER) {
52197
+ if (!allowed.has(c)) continue;
52198
+ out[c] = per + (remainder > 0 ? 1 : 0);
52199
+ if (remainder > 0) remainder--;
52200
+ }
52201
+ return out;
52202
+ }
52203
+ const shares = [];
52204
+ let floorTotal = 0;
52205
+ for (const c of WUBRG_ORDER) {
52206
+ if (!allowed.has(c)) continue;
52207
+ const exact = inIdentity[c] / totalInIdentity * slotCount;
52208
+ const f = Math.floor(exact);
52209
+ shares.push({ color: c, floor: f, remainder: exact - f });
52210
+ floorTotal += f;
52211
+ out[c] = f;
52212
+ }
52213
+ let leftover = slotCount - floorTotal;
52214
+ shares.sort((a, b) => b.remainder - a.remainder);
52215
+ for (const s of shares) {
52216
+ if (leftover <= 0) break;
52217
+ out[s.color]++;
52218
+ leftover--;
52219
+ }
52220
+ return out;
52221
+ }
52222
+ var BASIC_NAME = {
52223
+ W: "Plains",
52224
+ U: "Island",
52225
+ B: "Swamp",
52226
+ R: "Mountain",
52227
+ G: "Forest"
52228
+ };
52229
+ var KARSTEN_LANDS_RANGE = { min: KARSTEN_2022.landsFrom, max: KARSTEN_2022.landsTo };
52230
+ function karstenTarget(pips, mv, lands) {
52231
+ if (pips <= 0) return 0;
52232
+ const p = Math.min(4, Math.max(1, Math.floor(pips)));
52233
+ const m = Math.max(p, Math.min(7, Math.max(1, Math.floor(mv || 1))));
52234
+ const n = Math.min(
52235
+ KARSTEN_LANDS_RANGE.max,
52236
+ Math.max(KARSTEN_LANDS_RANGE.min, Math.round(Number.isFinite(lands) ? lands : 0))
52237
+ );
52238
+ return KARSTEN_2022.rows[n][p - 1][m - 1];
52239
+ }
52240
+ var KARSTEN_LANDS = { base: 31.42, perAvgMv: 3.13, perCheap: 0.28 };
52241
+ var CHEAP_SPELL_MAX_MV = 2;
52242
+ var LAND_COUNT_RANGE = { min: 28, max: 42 };
52243
+ function recommendedLandCount(inputs) {
52244
+ const raw = KARSTEN_LANDS.base + KARSTEN_LANDS.perAvgMv * inputs.avgMv - KARSTEN_LANDS.perCheap * inputs.cheapRampDraw;
52245
+ return Math.min(LAND_COUNT_RANGE.max, Math.max(LAND_COUNT_RANGE.min, Math.round(raw)));
52246
+ }
52247
+ function isLandCard(card) {
52248
+ return card.typeLine?.toLowerCase().includes("land") ?? false;
52249
+ }
52250
+ function isCheapRampOrDraw(card, lens) {
52251
+ if ((card.cmc ?? 99) > CHEAP_SPELL_MAX_MV) return false;
52252
+ if (lens) return isRamp(card, lens) || isDraw(card, lens);
52253
+ return card.roles.includes("ramp") || card.roles.includes("draw");
52254
+ }
52255
+ function landCountInputs(cards, lens) {
52256
+ let mvSum = 0;
52257
+ let spellCount = 0;
52258
+ const cheap = /* @__PURE__ */ new Set();
52259
+ for (const dc of cards) {
52260
+ if (dc.source === "commander") continue;
52261
+ const c = dc.card;
52262
+ if (isLandCard(c)) continue;
52263
+ const copies = dc.copies ?? 1;
52264
+ mvSum += (c.cmc ?? 0) * copies;
52265
+ spellCount += copies;
52266
+ if (isCheapRampOrDraw(c, lens)) cheap.add(c.oracleId);
52267
+ }
52268
+ return {
52269
+ avgMv: spellCount > 0 ? mvSum / spellCount : 0,
52270
+ cheapRampDraw: cheap.size,
52271
+ spellCount
52272
+ };
52273
+ }
52274
+ function demandPips(card) {
52275
+ const cost = card.manaCost;
52276
+ if (!cost || !/\{(?:[WUBRG]\/[WUBRG]|2\/[WUBRG])\}/.test(cost)) return card.colorPips;
52277
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52278
+ for (const face of cost.split(" // ")) {
52279
+ const f = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52280
+ for (const tok of face.match(/\{[^}]+\}/g) ?? []) {
52281
+ const m = /^\{([WUBRG])(?:\/?P)?\}$/.exec(tok);
52282
+ if (m) f[m[1]]++;
52283
+ }
52284
+ for (const c of WUBRG_ORDER) out[c] = Math.max(out[c], f[c]);
52285
+ }
52286
+ return out;
52287
+ }
52288
+ function cardTarget(card, color, lands) {
52289
+ const p = demandPips(card);
52290
+ const pips = p?.[color] ?? 0;
52291
+ if (pips < 1) return 0;
52292
+ const colours = WUBRG_ORDER.filter((c) => (p?.[c] ?? 0) > 0).length;
52293
+ return karstenTarget(pips, card.cmc, lands) + (colours >= 2 ? 1 : 0);
52294
+ }
52295
+ function fetchableColors(fetch2, lands) {
52296
+ const out = /* @__PURE__ */ new Set();
52297
+ const f = fetch2.fetches;
52298
+ if (!f) return out;
52299
+ const typeRes = f.types?.map((t) => new RegExp(`\\b${t.toLowerCase()}\\b`));
52300
+ for (const land of lands) {
52301
+ if (land.oracleId === fetch2.oracleId) continue;
52302
+ const tl = land.typeLine?.toLowerCase() ?? "";
52303
+ if (!/\bland\b/.test(tl)) continue;
52304
+ if (f.basicOnly && !/\bbasic\b/.test(tl)) continue;
52305
+ if (typeRes && !typeRes.some((re) => re.test(tl))) continue;
52306
+ for (const c of land.producedMana ?? []) out.add(c);
52307
+ }
52308
+ return out;
52309
+ }
52310
+
52311
+ // ../src/lib/deckPlan/deckHealth.ts
52312
+ function comb(n, k) {
52313
+ if (k < 0 || k > n) return 0;
52314
+ if (k === 0 || k === n) return 1;
52315
+ const kk = Math.min(k, n - k);
52316
+ let result = 1;
52317
+ for (let i = 0; i < kk; i++) {
52318
+ result = result * (n - i) / (i + 1);
52319
+ }
52320
+ return result;
52321
+ }
52322
+ function hypergeometricPmf(N, K, n, k) {
52323
+ if (k < 0 || k > n || k > K || n - k > N - K) return 0;
52324
+ const denom = comb(N, n);
52325
+ if (denom === 0) return 0;
52326
+ return comb(K, k) * comb(N - K, n - k) / denom;
52327
+ }
52328
+ var OPENING_HAND_SIZE = 7;
52329
+ var MANA_SCREW_MAX_LANDS = 1;
52330
+ var MANA_SWEET_MAX_LANDS = 4;
52331
+ function computeManaConsistency(deckSize, landCount, handSize = OPENING_HAND_SIZE) {
52332
+ if (deckSize <= 0 || handSize <= 0) return null;
52333
+ const K = Math.max(0, Math.min(landCount, deckSize));
52334
+ const n = Math.min(handSize, deckSize);
52335
+ let screw = 0;
52336
+ let sweet = 0;
52337
+ let flood = 0;
52338
+ for (let k = 0; k <= n; k++) {
52339
+ const p = hypergeometricPmf(deckSize, K, n, k);
52340
+ if (k <= MANA_SCREW_MAX_LANDS) screw += p;
52341
+ else if (k <= MANA_SWEET_MAX_LANDS) sweet += p;
52342
+ else flood += p;
52343
+ }
52344
+ return { deckSize, landCount: K, handSize: n, screw, sweet, flood };
52345
+ }
52346
+
52347
+ // ../src/lib/deckPlan/sourceWeights.ts
52348
+ var SOURCE_WEIGHT = {
52349
+ land: 1,
52350
+ splitLand3Color: 2 / 3,
52351
+ opponentLand: 3 / 4,
52352
+ dork: 1 / 2,
52353
+ rock: 3 / 4,
52354
+ opponentRock: 1 / 2,
52355
+ ramp2: 3 / 4,
52356
+ ramp3: 1 / 2,
52357
+ treasure: 1 / 4
52358
+ };
52359
+ var SOURCE_FROM_MV = { tappedLand: 2, dork: 2, rock: 3, ramp2: 3, ramp3: 5, treasure: 2 };
52360
+ var PERMANENT2 = /\b(creature|artifact|enchantment|planeswalker|battle)\b/i;
52361
+ var isLand2 = (c) => /\bland\b/i.test(c.typeLine ?? "");
52362
+ function isPathway(c) {
52363
+ return isLand2(c) && c.layout === "modal_dfc" && / Pathway \/\/ .* Pathway$/.test(c.name);
52364
+ }
52365
+ function sourceWeight(card, color, mv, ctx) {
52366
+ const makes = card.producedMana?.includes(color) ?? false;
52367
+ const fetched = ctx.fetchColors.get(card.oracleId)?.has(color) ?? false;
52368
+ if (isLand2(card)) {
52369
+ if (!makes && !fetched) return 0;
52370
+ if (card.enterTapped === "always" && mv < SOURCE_FROM_MV.tappedLand) return 0;
52371
+ if (card.opponentColors) return SOURCE_WEIGHT.opponentLand;
52372
+ const oneOfSeveral = isPathway(card) || card.fetches?.basicOnly === true && card.fetches.types === null;
52373
+ if (oneOfSeveral && ctx.colorCount >= 3) return SOURCE_WEIGHT.splitLand3Color;
52374
+ return SOURCE_WEIGHT.land;
52375
+ }
52376
+ const manaPermanent = ctx.lens ? ctx.lens.isManaSource(card.oracleId) : PERMANENT2.test(card.typeLine ?? "");
52377
+ if (makes && manaPermanent) {
52378
+ if (/\bcreature\b/i.test(card.typeLine ?? "")) return mv >= SOURCE_FROM_MV.dork ? SOURCE_WEIGHT.dork : 0;
52379
+ if (mv < SOURCE_FROM_MV.rock) return 0;
52380
+ return card.opponentColors ? SOURCE_WEIGHT.opponentRock : SOURCE_WEIGHT.rock;
52381
+ }
52382
+ if (fetched && /\b(instant|sorcery)\b/i.test(card.typeLine ?? "") && card.roles.includes("ramp")) {
52383
+ if (card.cmc <= 2) return mv >= SOURCE_FROM_MV.ramp2 ? SOURCE_WEIGHT.ramp2 : 0;
52384
+ if (card.cmc === 3) return mv >= SOURCE_FROM_MV.ramp3 ? SOURCE_WEIGHT.ramp3 : 0;
52385
+ return 0;
52386
+ }
52387
+ if (card.tokens?.includes("treasure") && ctx.lens?.isRepeatableTreasure(card.oracleId)) {
52388
+ return mv >= SOURCE_FROM_MV.treasure ? SOURCE_WEIGHT.treasure : 0;
52389
+ }
52390
+ return 0;
52391
+ }
52392
+ function formatSources(n) {
52393
+ const r = Math.round(n * 10) / 10;
52394
+ return Number.isInteger(r) ? String(r) : r.toFixed(1);
52395
+ }
52396
+ function formatShortfall(target, have) {
52397
+ return formatSources(target - Math.round(have * 10) / 10);
52398
+ }
52399
+ function wholeShort(n) {
52400
+ return Math.ceil(n - 1e-9);
52401
+ }
52402
+
52403
+ // ../src/components/deckBuilderV2/manaSources.ts
52404
+ init_utils();
52405
+ var MANA_COLOR_ORDER = ["W", "U", "B", "R", "G"];
52406
+ var MANA_COLOR_LABEL = {
52407
+ W: "White",
52408
+ U: "Blue",
52409
+ B: "Black",
52410
+ R: "Red",
52411
+ G: "Green"
52412
+ };
52413
+ function countSources(cards, color, mv, ctx) {
52414
+ let n = 0;
52415
+ for (const { card, copies } of cards) n += copies * sourceWeight(card, color, mv, ctx);
52416
+ return Math.round(n * 100) / 100;
52417
+ }
52418
+ function deckFetchColors(cards) {
52419
+ const out = /* @__PURE__ */ new Map();
52420
+ if (!cards.some(({ card }) => card.fetches)) return out;
52421
+ const lands = cards.filter(({ card }) => isLandCard(card)).map(({ card }) => card);
52422
+ for (const { card } of cards) {
52423
+ if (card.fetches) out.set(card.oracleId, fetchableColors(card, lands));
52424
+ }
52425
+ return out;
52426
+ }
52427
+ var mvTurn = (cmc) => Math.min(7, Math.max(1, Math.floor(cmc || 1)));
52428
+ function measureDemand(cards, color, lands, haveAt) {
52429
+ let need = 0;
52430
+ let doubleNeed = 0;
52431
+ let tripleNeed = 0;
52432
+ let target = 0;
52433
+ let driverPips = 0;
52434
+ let driverMv = 0;
52435
+ let worstGap = -Infinity;
52436
+ for (const { card } of cards) {
52437
+ const pips = demandPips(card)?.[color] ?? 0;
52438
+ if (pips < 1) continue;
52439
+ need++;
52440
+ if (pips >= 2) doubleNeed++;
52441
+ if (pips >= 3) tripleNeed++;
52442
+ const t = cardTarget(card, color, lands);
52443
+ const gap = t - haveAt(mvTurn(card.cmc));
52444
+ if (gap > worstGap || gap === worstGap && (t > target || t === target && pips > driverPips)) {
52445
+ worstGap = gap;
52446
+ target = t;
52447
+ driverPips = pips;
52448
+ driverMv = card.cmc;
52449
+ }
52450
+ }
52451
+ return { target, need, doubleNeed, tripleNeed, driverPips, driverMv };
52452
+ }
52453
+ function classify(have, target) {
52454
+ if (target <= 0) return { status: "none", shortBy: 0 };
52455
+ const diff = Math.round((have - target) * 100) / 100;
52456
+ if (diff >= 3) return { status: "over", shortBy: 0 };
52457
+ if (diff >= -1) return { status: "on", shortBy: Math.max(0, -diff) };
52458
+ return { status: "short", shortBy: -diff };
52459
+ }
52460
+ function manabaseReport(cards, identity2, lens = null) {
52461
+ const idSet = new Set(identity2);
52462
+ const inIdentity = MANA_COLOR_ORDER.filter((c) => idSet.has(c));
52463
+ const rows = [];
52464
+ const fetchColors2 = deckFetchColors(cards);
52465
+ const ctx = { colorCount: inIdentity.length, fetchColors: fetchColors2, lens };
52466
+ let lands = 0;
52467
+ for (const { card, copies } of cards) if (isLandCard(card)) lands += copies;
52468
+ for (const color of MANA_COLOR_ORDER) {
52469
+ const byMv = /* @__PURE__ */ new Map();
52470
+ const haveAt = (mv) => {
52471
+ let v = byMv.get(mv);
52472
+ if (v === void 0) byMv.set(mv, v = countSources(cards, color, mv, ctx));
52473
+ return v;
52474
+ };
52475
+ const demand = measureDemand(cards, color, lands, haveAt);
52476
+ const have = demand.need > 0 ? haveAt(mvTurn(demand.driverMv)) : haveAt(7);
52477
+ const active = inIdentity.length > 0 ? idSet.has(color) : have > 0 || demand.need > 0;
52478
+ if (!active) continue;
52479
+ const { status, shortBy } = classify(have, demand.target);
52480
+ rows.push({ color, have, status, shortBy, ...demand });
52481
+ }
52482
+ const colorless = rows.length === 0 || rows.every((r) => r.have === 0 && r.need === 0);
52483
+ return { colors: rows, colorless, lands };
52484
+ }
52485
+ function manabaseSummary(cards, identity2, lens) {
52486
+ let deckSize = 0;
52487
+ let landsHave = 0;
52488
+ for (const dc of cards) {
52489
+ if (dc.source === "commander") continue;
52490
+ deckSize += dc.copies;
52491
+ if (isLandCard(dc.card)) landsHave += dc.copies;
52492
+ }
52493
+ const landInputs = landCountInputs(cards, lens);
52494
+ const report = manabaseReport(cards, identity2, lens);
52495
+ const consistency = computeManaConsistency(deckSize, landsHave);
52496
+ return {
52497
+ landsHave,
52498
+ landsRecommended: landInputs.spellCount > 0 ? recommendedLandCount(landInputs) : null,
52499
+ landInputs,
52500
+ colorsShort: report.colors.filter((r) => r.target > 0 && r.target - r.have >= COLOR_SHORT_THRESHOLD).map((r) => ({ color: r.color, shortBy: Math.round((r.target - r.have) * 100) / 100 })).sort((a, b) => b.shortBy - a.shortBy),
52501
+ screwPct: consistency ? consistency.screw * 100 : null,
52502
+ report,
52503
+ consistency
52504
+ };
52505
+ }
52506
+ var LAND_COUNT_TOLERANCE = 2;
52507
+ var COLOR_SHORT_THRESHOLD = LAND_COUNT_TOLERANCE;
52508
+ function shortLabel(color, shortBy) {
52509
+ return `${MANA_COLOR_LABEL[color]} short ${wholeShort(shortBy)}`;
52510
+ }
52511
+ function landInputsLabel(i) {
52512
+ return `avg MV ${i.avgMv.toFixed(1)}, ${i.cheapRampDraw} cheap ramp/draw`;
52513
+ }
52514
+ var COLOR_STATUS_LABEL = {
52515
+ over: "comfortably over",
52516
+ on: "on target",
52517
+ short: "short",
52518
+ none: "no demand yet"
52519
+ };
52520
+ var PIP_WORD = ["", "single", "double", "triple", "quadruple"];
52521
+ function demandSentence(row, lands) {
52522
+ const cname = MANA_COLOR_LABEL[row.color].toLowerCase();
52523
+ if (row.need === 0) {
52524
+ return `Nothing in the deck needs ${cname} yet. No target to hit.`;
52525
+ }
52526
+ const parts = [
52527
+ `${row.need} card${row.need === 1 ? "" : "s"} need${row.need === 1 ? "s" : ""} ${cname}`
52528
+ ];
52529
+ if (row.doubleNeed > 0) parts.push(`${row.doubleNeed} double`);
52530
+ if (row.tripleNeed > 0) parts.push(`${row.tripleNeed} triple`);
52531
+ const demand = parts.join(" \xB7 ");
52532
+ const p = Math.min(4, Math.max(1, row.driverPips));
52533
+ const driver = p === 1 ? `a single ${cname} pip` : `a ${PIP_WORD[p]}-${cname} card`;
52534
+ const basis = lands >= KARSTEN_LANDS_RANGE.min ? `with your ${lands} lands` : `for a ${KARSTEN_LANDS_RANGE.min}-land deck`;
52535
+ return `${demand} \u2192 Karsten wants ~${row.target} ${basis}, enough to cast ${driver} on turn ${row.driverMv}.`;
52536
+ }
52537
+ function balancedBasics(deckCards, identity2) {
52538
+ const current = /* @__PURE__ */ new Map();
52539
+ let total = 0;
52540
+ for (const dc of deckCards) {
52541
+ if (dc.source === "commander") continue;
52542
+ if (!isBasicLandType(dc.card.typeLine)) continue;
52543
+ const pm = dc.card.producedMana;
52544
+ if (!pm || pm.length !== 1) continue;
52545
+ const color = pm[0];
52546
+ if (!WUBRG_ORDER.includes(color)) continue;
52547
+ const prev = current.get(color);
52548
+ current.set(color, { oracleId: dc.card.oracleId, copies: (prev?.copies ?? 0) + dc.copies });
52549
+ total += dc.copies;
52550
+ }
52551
+ const spells = deckCards.filter((dc) => dc.source !== "commander" && !isBasicLandType(dc.card.typeLine)).map((dc) => dc.card);
52552
+ const target = total > 0 ? distributeBasics(sumDeckPips(spells), identity2, total) : { W: 0, U: 0, B: 0, R: 0, G: 0 };
52553
+ return { current, total, target, basicName: BASIC_NAME };
52554
+ }
52555
+
52556
+ // ../src/components/deckBuilderV2/fixingLands.ts
52557
+ init_slug();
52558
+ init_utils();
52559
+ var WUBRG2 = /* @__PURE__ */ new Set(["W", "U", "B", "R", "G"]);
52560
+ var PREMIUM_CYCLES = /* @__PURE__ */ new Set([
52561
+ "dual",
52562
+ "shockland",
52563
+ "painland",
52564
+ "checkland",
52565
+ "fastland",
52566
+ "battleland",
52567
+ "canopyland",
52568
+ "snarl",
52569
+ "pathway"
52570
+ ]);
52571
+ var TAPLAND_CYCLES = /* @__PURE__ */ new Set([
52572
+ "triome",
52573
+ "scryland",
52574
+ "gainland",
52575
+ "bounceland",
52576
+ "bikeland",
52577
+ "slowland",
52578
+ "storageland",
52579
+ "filterland"
52580
+ ]);
52581
+ var BASIC_DEPENDENT_TAP = /* @__PURE__ */ new Set([
52582
+ "controls_basic_type",
52583
+ "reveals_basic",
52584
+ "two_or_more_basics"
52585
+ ]);
52586
+ function coloredProduced(card) {
52587
+ return (card.producedMana ?? []).filter((c) => WUBRG2.has(c));
52588
+ }
52589
+ function isLandType(typeLine) {
52590
+ return (typeLine ?? "").toLowerCase().includes("land");
52591
+ }
52592
+ function indexCyclesByOracleId(cycles) {
52593
+ const m = /* @__PURE__ */ new Map();
52594
+ for (const c of cycles) {
52595
+ for (const member of c.members) {
52596
+ const s = m.get(member.oracleId);
52597
+ if (s) s.add(c.slug);
52598
+ else m.set(member.oracleId, /* @__PURE__ */ new Set([c.slug]));
52599
+ }
52600
+ }
52601
+ return m;
52602
+ }
52603
+ function cycleLabels(cycles) {
52604
+ const m = /* @__PURE__ */ new Map();
52605
+ for (const c of cycles) m.set(c.slug, c.displayName);
52606
+ return m;
52607
+ }
52608
+ function classifyTier(card, cycleSlugs, labels) {
52609
+ let premium = null;
52610
+ let tapland = null;
52611
+ if (cycleSlugs) {
52612
+ for (const slug of cycleSlugs) {
52613
+ if (PREMIUM_CYCLES.has(slug) && !premium) premium = slug;
52614
+ else if (TAPLAND_CYCLES.has(slug) && !tapland) tapland = slug;
52615
+ }
52616
+ }
52617
+ if (premium) return { tier: 0, cycleLabel: labels.get(premium) ?? null, cycleSlug: premium };
52618
+ if (coloredProduced(card).length === 5) return { tier: 1, cycleLabel: null, cycleSlug: null };
52619
+ if (tapland) return { tier: 2, cycleLabel: labels.get(tapland) ?? null, cycleSlug: tapland };
52620
+ return { tier: 3, cycleLabel: null, cycleSlug: null };
52621
+ }
52622
+ function fixingLandCandidates(input2) {
52623
+ const {
52624
+ shortColor,
52625
+ cards,
52626
+ identity: identity2,
52627
+ ownedOracleIds,
52628
+ inDeckOracleIds,
52629
+ cycles,
52630
+ priceOf,
52631
+ limit = 5
52632
+ } = input2;
52633
+ const allowed = new Set(identity2);
52634
+ if (allowed.size < 2) return [];
52635
+ const cyclesByOid = indexCyclesByOracleId(cycles);
52636
+ const labels = cycleLabels(cycles);
52637
+ const out = [];
52638
+ for (const card of cards.byOracleId.values()) {
52639
+ if (!isLandType(card.typeLine)) continue;
52640
+ if (isBasicLandType(card.typeLine)) continue;
52641
+ if (inDeckOracleIds.has(card.oracleId)) continue;
52642
+ const produced = coloredProduced(card);
52643
+ if (!produced.includes(shortColor) || produced.length < 2) continue;
52644
+ if (!withinColorIdentity(card.colors, allowed)) continue;
52645
+ const { tier, cycleLabel, cycleSlug } = classifyTier(
52646
+ card,
52647
+ cyclesByOid.get(card.oracleId),
52648
+ labels
52649
+ );
52650
+ out.push({
52651
+ card,
52652
+ owned: ownedOracleIds?.has(card.oracleId) ?? false,
52653
+ slug: toEdhrecSlug(card.name),
52654
+ committed: false,
52655
+ untapped: card.enterTapped === void 0,
52656
+ cycleLabel,
52657
+ cycleSlug,
52658
+ price: priceOf(card),
52659
+ tier
52660
+ });
52661
+ }
52662
+ out.sort(compareFixingCandidates);
52663
+ return out.slice(0, limit);
52664
+ }
52665
+ function compareFixingCandidates(a, b) {
52666
+ if (a.owned !== b.owned) return a.owned ? -1 : 1;
52667
+ if (a.tier !== b.tier) return a.tier - b.tier;
52668
+ if (a.untapped !== b.untapped) return a.untapped ? -1 : 1;
52669
+ const pa = a.price ?? Infinity;
52670
+ const pb = b.price ?? Infinity;
52671
+ if (pa !== pb) return pa - pb;
52672
+ const ra = a.card.edhrecRank ?? Infinity;
52673
+ const rb = b.card.edhrecRank ?? Infinity;
52674
+ if (ra !== rb) return ra - rb;
52675
+ return a.card.name.localeCompare(b.card.name);
52676
+ }
52677
+ function surplusByColor(report) {
52678
+ const m = /* @__PURE__ */ new Map();
52679
+ for (const row of report.colors) m.set(row.color, row.have - row.target);
52680
+ return m;
52681
+ }
52682
+ function deckNeedsBasics(deckCards, cycles) {
52683
+ const basicFetchOids = /* @__PURE__ */ new Set();
52684
+ for (const c of cycles) {
52685
+ if (c.slug === "basicfetch") for (const m of c.members) basicFetchOids.add(m.oracleId);
52686
+ }
52687
+ for (const { card } of deckCards) {
52688
+ if (card.tapCondition && BASIC_DEPENDENT_TAP.has(card.tapCondition)) return true;
52689
+ if (basicFetchOids.has(card.oracleId)) return true;
52690
+ }
52691
+ return false;
52692
+ }
52693
+ function pickBasicToCut(input2) {
52694
+ const { report, deckCards, cycles, shortColor } = input2;
52695
+ const backfillColors = input2.backfillColors ?? /* @__PURE__ */ new Set();
52696
+ const surplus = surplusByColor(report);
52697
+ const floor = Math.max(1, deckNeedsBasics(deckCards, cycles) ? 2 : 0);
52698
+ const colors = [...surplus.entries()].filter(
52699
+ ([color, s]) => color !== shortColor && (s >= 1 || backfillColors.has(color))
52700
+ ).sort((a, b) => b[1] - a[1]).map(([color]) => color);
52701
+ for (const color of colors) {
52702
+ for (const { card, copies } of deckCards) {
52703
+ if (!isBasicLandType(card.typeLine)) continue;
52704
+ if (!coloredProduced(card).includes(color)) continue;
52705
+ if (copies - 1 < floor) continue;
52706
+ return { card, color, copies };
52707
+ }
52708
+ }
52709
+ return null;
52710
+ }
52711
+ function sharedBackfillColors(candidates, shortColor) {
52712
+ if (candidates.length === 0) return /* @__PURE__ */ new Set();
52713
+ let shared = coloredProduced(candidates[0].card);
52714
+ for (let i = 1; i < candidates.length; i++) {
52715
+ const produced = new Set(coloredProduced(candidates[i].card));
52716
+ shared = shared.filter((x) => produced.has(x));
52717
+ }
52718
+ const out = /* @__PURE__ */ new Set();
52719
+ for (const x of shared) {
52720
+ if (x !== shortColor) out.add(x);
52721
+ }
52722
+ return out;
52723
+ }
52724
+ function uncountedFetchCount(deckCards, cycles) {
52725
+ const fetchOids = /* @__PURE__ */ new Set();
52726
+ for (const c of cycles) {
52727
+ if (c.slug === "fetchland") for (const m of c.members) fetchOids.add(m.oracleId);
52728
+ }
52729
+ let n = 0;
52730
+ for (const { card, copies } of deckCards) {
52731
+ if (fetchOids.has(card.oracleId) && (card.producedMana?.length ?? 0) === 0 && !card.fetches) {
52732
+ n += copies;
52733
+ }
52734
+ }
52735
+ return n;
52736
+ }
52737
+ function buildManabaseFixes(input2) {
52738
+ const {
52739
+ report,
52740
+ deckCards,
52741
+ cards,
52742
+ identity: identity2,
52743
+ ownedOracleIds,
52744
+ cycles,
52745
+ priceOf,
52746
+ perColor = 3
52747
+ } = input2;
52748
+ if (new Set(identity2).size < 2) return [];
52749
+ const inDeckOracleIds = /* @__PURE__ */ new Set();
52750
+ for (const { card } of deckCards) inDeckOracleIds.add(card.oracleId);
52751
+ const fixes = [];
52752
+ for (const row of report.colors) {
52753
+ if (row.status !== "short" || row.shortBy <= 0) continue;
52754
+ const candidates = fixingLandCandidates({
52755
+ shortColor: row.color,
52756
+ cards,
52757
+ identity: identity2,
52758
+ ownedOracleIds,
52759
+ inDeckOracleIds,
52760
+ cycles,
52761
+ priceOf,
52762
+ limit: perColor
52763
+ });
52764
+ if (candidates.length === 0) continue;
52765
+ const cut = pickBasicToCut({
52766
+ report,
52767
+ deckCards,
52768
+ cycles,
52769
+ shortColor: row.color,
52770
+ // A basic of a colour the offered duals also make is safe to cut — the dual
52771
+ // backfills it. This is what lets a both-colours-short deck swap instead of
52772
+ // being told to add a land.
52773
+ backfillColors: sharedBackfillColors(candidates, row.color)
52774
+ });
52775
+ fixes.push({ color: row.color, shortBy: row.shortBy, candidates, cut });
52776
+ }
52777
+ return fixes;
52778
+ }
52779
+
51769
52780
  // ../src/lib/edhrec/cardStats.ts
51770
52781
  var TRENDING_MIN = 3;
51771
52782
  function isTrending(trend) {
@@ -52079,7 +53090,7 @@ function primaryType(card) {
52079
53090
  const front = card.typeLine.split(" // ")[0] ?? card.typeLine;
52080
53091
  return TYPE_ORDER.find((t) => front.includes(t)) ?? "Other";
52081
53092
  }
52082
- function isLand2(card) {
53093
+ function isLand3(card) {
52083
53094
  return (card.typeLine.split(" // ")[0] ?? card.typeLine).includes("Land");
52084
53095
  }
52085
53096
 
@@ -52094,7 +53105,7 @@ function mulberry32(seed) {
52094
53105
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
52095
53106
  };
52096
53107
  }
52097
- function isLand3(card) {
53108
+ function isLand4(card) {
52098
53109
  return card.typeLine.toLowerCase().includes("land");
52099
53110
  }
52100
53111
  function frontFaceLower(typeLine) {
@@ -52327,13 +53338,23 @@ function readUntapsAndReduces(text) {
52327
53338
  t.match(/\beach spell you cast that's ((?:[a-z]+ or )?[a-z]+ )costs \{(\d+)\} less/)
52328
53339
  );
52329
53340
  const tax = red ? null : t.match(/(?:^|\n)((?:[a-z]+ (?:spells )?(?:and|or) )?(?:[a-z]+ )?)?spells cost \{(\d+)\} more to cast\.(?:\n|$)/);
52330
- if (red || tax) {
52331
- const m = red ?? tax;
53341
+ const counted = !!red && t.startsWith(" to cast for each ", red.index + red[0].length);
53342
+ const colored = !red && !tax ? t.match(/(?:^|\n)spells of the chosen type you cast cost ((?:\{[wubrg]\})+) less to cast\. this effect reduces only the amount of colored mana you pay\./) : null;
53343
+ if (colored) {
53344
+ const pips = {};
53345
+ for (const x of colored[1].match(/\{([wubrg])\}/g)) {
53346
+ const k = x[1].toUpperCase();
53347
+ pips[k] = (pips[k] ?? 0) + 1;
53348
+ }
53349
+ out.reduces = { amount: 0, finds: /\bchoose a creature type\b/.test(t) ? "@subtype" : "@type", pips };
53350
+ }
53351
+ if (red && !counted || tax) {
53352
+ const m = red && !counted ? red : tax;
52332
53353
  const sign = red ? 1 : -1;
52333
53354
  const words = (m[1] ?? "").trim();
52334
53355
  const COLOR = { white: "w", blue: "u", black: "b", red: "r", green: "g" };
52335
53356
  const NOT_A_TYPE = /* @__PURE__ */ new Set(["the", "other", "each", "your", "all", "that", "of", "and", "or", "spells"]);
52336
- const one = (w) => w === "noncreature" ? "-t:creature" : COLOR[w] ? `c:${COLOR[w]}` : w && !NOT_A_TYPE.has(w) ? `t:${w}` : "";
53357
+ const one = (w) => w === "noncreature" ? "-t:creature" : w === "historic" ? "is:historic" : w === "colorless" ? "c:c" : w === "multicolored" ? "c:m" : COLOR[w] ? `c:${COLOR[w]}` : w && !NOT_A_TYPE.has(w) ? `t:${w}` : "";
52337
53358
  const parts = words.split(/ (?:and|or) /).map((part2) => part2.split(/\s+/).map(one).filter(Boolean).join(" ")).filter(Boolean);
52338
53359
  const finds = parts.length > 1 ? parts.join(" or ") : parts[0] ?? "";
52339
53360
  const chosen = / of the chosen type /.test(m[0]) ? /\bchoose a creature type\b/.test(t) || /\bcreature\b/.test(words) ? "@subtype" : "@type" : "";
@@ -52814,9 +53835,13 @@ function readDiesDraws(text) {
52814
53835
  var SAC_DRAW = /^whenever you sacrifice (?:a|an|one or more|another) (permanent|creature|artifact|treasure)s?, (?:put [^.]*? and )?(?:you )?draw (a|one|two) cards?\.$/;
52815
53836
  var GRANTS_CREATURE_MANA = /\bcreatures you control (?:have|gain) (?:[a-z]+ and )?"\{t\}: add (one mana of any color|\{[wubrgc]\})\.( spend this mana only to cast (?:a )?creature spells?\.)?"/;
52816
53837
  function readGrantsTapMana(text) {
53838
+ const all = text.match(/(?:^|\n)all ([a-z]+)s have "\{t\}: add (one mana of any color|\{[wubrgc]\})\."/);
53839
+ if (all) return { grantsTapMana: [all[2] === "one mana of any color" ? "WUBRG" : all[2][1].toUpperCase()], grantType: all[1] };
52817
53840
  const m = text.match(GRANTS_CREATURE_MANA);
52818
53841
  if (!m || /\buntil end of turn\b/.test(text.slice(m.index + m[0].length, m.index + m[0].length + 20))) return {};
52819
- return { grantsTapMana: [m[1] === "one mana of any color" ? "WUBRG" : m[1][1].toUpperCase()], ...m[2] ? { manaVaries: true } : {} };
53842
+ const kind = text.slice(0, m.index).match(/(?:^|[\n ])([a-z]+) $/)?.[1];
53843
+ const grantType = kind && !/^(?:other|nontoken|untapped|tapped|and|the|your|of|legendary|artifact|enchantment)$/.test(kind) ? kind : void 0;
53844
+ return { grantsTapMana: [m[1] === "one mana of any color" ? "WUBRG" : m[1][1].toUpperCase()], ...m[2] ? { manaVaries: true } : {}, ...grantType ? { grantType } : {} };
52820
53845
  }
52821
53846
  var LANDFALL_DRAW = /^(?:landfall — )?whenever a land you control enters, (?:you gain \d+ life and )?(?:you )?draw a card\.$/;
52822
53847
  function readTokenEngines(text) {
@@ -52846,6 +53871,46 @@ function readStartsInPlay(text) {
52846
53871
  const luck = !!m[2] && /if [^.\n]* has a luck counter on it, instead add one mana of any color/.test(text);
52847
53872
  return { onDrawOnly: !!m[1], exiles, ...luck ? { makes: ["WUBRG"] } : {} };
52848
53873
  }
53874
+ function readLandSearch(text) {
53875
+ const N = { a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5 };
53876
+ const BASIC = { plains: "W", island: "U", swamp: "B", mountain: "R", forest: "G" };
53877
+ const TYPE = "(?:basic |snow |nonbasic )*(?:land|forest|plains|island|swamp|mountain|gate|desert|town|cave|sphere)s?(?: cards?)?";
53878
+ const WHAT = `(${TYPE}(?:(?:,? and\\/or |,? or |, )${TYPE})*)(?: cards?)?(?: with different names)?`;
53879
+ const re = new RegExp(`search your library for (up to )?(a|an|one|two|three|four|five) ${WHAT}(?:,| and)(?: reveal (?:it|them|those cards),)? (?:and )?put (?:it|them|that card|those cards|one) onto the battlefield( tapped)?(?: and the (?:other|rest) into your hand)?`);
53880
+ for (const raw of text.replace(/\([^)]*\)/g, "").split("\n")) {
53881
+ let l = raw.trim().replace(/^i(?:, [ivx]+)* — /, "").replace(/^• /, "");
53882
+ if (/^[ivx]+(?:, [ivx]+)* — /.test(l)) continue;
53883
+ l = l.replace(/^[a-z][a-z' ]* — /, "");
53884
+ if (/^(?:when|whenever|at the beginning|as long as|as the game begins)\b/.test(l)) {
53885
+ const t = l.match(/^(?:when(?:ever)? (?:this [a-z]+|~|[^,]+?) enters(?: or attacks)?|when you cast this spell), (?:you may )?/);
53886
+ if (!t || /\bequipped|enchanted|another|a creature\b/.test(t[0])) continue;
53887
+ l = l.slice(t[0].length);
53888
+ }
53889
+ let cost;
53890
+ const act = l.match(/^((?:\{[^}]+\}(?:, )?)+)(?:, \{t\})?(?:, sacrifice (?:this [a-z]+|~))?: (.*)$/);
53891
+ if (act) {
53892
+ const c = parseCost(act[1].replace(/\{t\}/g, "").replace(/, /g, ""));
53893
+ cost = { generic: c.generic, pips: c.pips };
53894
+ l = act[2];
53895
+ } else if (/^[^:]*\b(?:tap|sacrifice|exile|discard|pay) [^:]*: /.test(l)) continue;
53896
+ for (const [k, s] of l.split(/(?<=\.)\s+/).entries()) {
53897
+ if (/^(?:if|then if)\b|\binstead\b/.test(s) || /\bif\b[^,]*,\s*search/.test(s)) continue;
53898
+ if (/\b(?:target|an?) opponent|each opponent|target player\b/.test(s.split("search your library")[0])) continue;
53899
+ const m = s.match(re);
53900
+ if (!m) continue;
53901
+ const words = m[3];
53902
+ const typed = words.match(/forest|plains|island|swamp|mountain/g) ?? [];
53903
+ const anyLand = /\bland\b|gate|desert|town|cave|sphere/.test(words);
53904
+ const colors = anyLand ? void 0 : "WUBRG".split("").filter((c) => typed.some((w) => BASIC[w] === c)).join("") || void 0;
53905
+ const n = N[m[2]] ?? 1;
53906
+ const split = /\bput one onto the battlefield/.test(s) && /into your hand/.test(s);
53907
+ const prev = l.split(/(?<=\.)\s+/)[k - 1] ?? "";
53908
+ const sac = prev.match(/^sacrifice (a|an|one|two|three) lands?\.$/);
53909
+ return { ramp: { n: split ? 1 : n, tapped: !!m[4] || split && /onto the battlefield tapped/.test(s), ...colors ? { colors } : {} }, ...cost && (cost.generic || Object.keys(cost.pips).length) ? { cost } : {}, ...sac ? { sacLands: N[sac[1]] ?? 1 } : {}, ...split ? { toHand: n - 1 } : {} };
53910
+ }
53911
+ }
53912
+ return null;
53913
+ }
52849
53914
  function readSacOutlet(text) {
52850
53915
  const m = text.match(/(?:^|\n)(\{t\}, )?(?:pay \d+ life, )?sacrifice (?:a|another) (?:nontoken )?(?:creature|artifact or creature)(?: or artifact)?:/);
52851
53916
  return m ? { sacOutlet: m[1] ? "tap" : "free" } : {};
@@ -53234,6 +54299,22 @@ function withNonPlain(p0, text) {
53234
54299
  }
53235
54300
  }
53236
54301
  const restricted = mana.filter((m) => /^spend this mana only to /.test(m[3]));
54302
+ if (restricted.length && mana.length === 1 && p.makes.length === 1) {
54303
+ const syms = mana[0][2].match(/^add ((?:\{[wubrgc]\}){2,})\.$/);
54304
+ if (syms && /^\{t\}$/.test(mana[0][1].trim())) {
54305
+ const makes2 = syms[1].match(/\{[wubrgc]\}/g).map((x) => x[1].toUpperCase());
54306
+ const { manaVaries: _v, ...rest } = p;
54307
+ void _v;
54308
+ p = { ...rest, makes: makes2, produces: makes2.length };
54309
+ }
54310
+ } else if (!p.land && restricted.length && mana.every((m) => /^\{t\}$/.test(m[1].trim()))) {
54311
+ const plain2 = mana.filter(plainLine);
54312
+ const own2 = plain2.length === 1 ? plain2[0][2].match(/^add ((?:\{[wubrgc]\})+)\.$/) : null;
54313
+ if (own2 && plain2.length + restricted.length === mana.length) {
54314
+ const makes2 = own2[1].match(/\{[wubrgc]\}/g).map((x) => x[1].toUpperCase());
54315
+ if (makes2.length < p.makes.length) return { ...p, makes: makes2, produces: makes2.length, manaVaries: true };
54316
+ }
54317
+ }
53237
54318
  const code = restricted.map((m) => restrictionCode(m[3].replace(/^spend this mana only to (?:cast )?/, "").replace(/\..*$/, "").replace(/^(?:activate|pay|turn|foretell|unlock).*/, "zz"))).find((c) => c !== null) ?? null;
53238
54319
  if (!restricted.length || code === null) return p;
53239
54320
  const tag = (us) => us.map((u) => {
@@ -53286,7 +54367,8 @@ function readExtraMana2(text) {
53286
54367
  }
53287
54368
  const mult = !out.boost ? text.match(/(?:^|\n)if you tap an? (permanent|basic land|land) for mana, it produces (twice|three times) as much of that mana instead\./) : null;
53288
54369
  if (mult) out.boost = { per: mult[1] === "permanent" ? "permanent" : "land", adds: null, mult: mult[2] === "twice" ? 1 : 2 };
53289
- else if (!out.boost && /(?:^|\n)(?:whenever a land's ability causes you to add one or more mana of the chosen color, add an additional one mana of that color|whenever a basic land is tapped for mana of the chosen color, its controller adds an additional one mana of that color)\./.test(text)) out.boost = { per: "land", adds: null };
54370
+ else if (!out.boost && /(?:^|\n)whenever a land's ability causes you to add one or more mana of the chosen color, add an additional one mana of that color\./.test(text)) out.boost = { per: "land", adds: null, chosenColor: true };
54371
+ else if (!out.boost && /(?:^|\n)whenever a basic land is tapped for mana of the chosen color, its controller adds an additional one mana of that color\./.test(text)) out.boost = { per: "land", adds: null, chosenColor: true, basicOnly: true };
53290
54372
  else if (!out.boost && /(?:^|\n)whenever you tap a land for mana while you're the monarch, add an additional one mana of any color\./.test(text)) out.boost = { per: "land", adds: ["WUBRG"] };
53291
54373
  const landfall = text.match(/(?:^|\n)(?:landfall — )?whenever a land (?:you control )?enters(?: the battlefield)?(?: under your control)?, add ([^.\n]*)/);
53292
54374
  if (landfall) {
@@ -53596,6 +54678,13 @@ function readProfile(card, oracleText) {
53596
54678
  p0 = { ...p0, rampLands: { n: m[1] === "three" ? 3 : m[1] === "two" ? 2 : 1, tapped: !!m[3], ...colors !== "WUBRG" ? { colors } : {} } };
53597
54679
  break;
53598
54680
  }
54681
+ if (!p0.land && !p0.rampLands) {
54682
+ const r = readLandSearch(text);
54683
+ if (r) {
54684
+ p0 = { ...p0, rampLands: r.ramp, ...r.cost ? { rampCost: r.cost } : {}, ...r.toHand && !p0.landsToHand ? { landsToHand: r.toHand } : {} };
54685
+ if (r.sacLands && !p0.sacrifice) p0 = { ...p0, sacrifice: { count: r.sacLands, kinds: ["land"] } };
54686
+ }
54687
+ }
53599
54688
  if (!p0.land && !p0.landsToHand)
53600
54689
  for (const l of self2.split("\n")) {
53601
54690
  const s = l.trim().replace(/^• /, "");
@@ -53622,6 +54711,7 @@ function readProfile(card, oracleText) {
53622
54711
  void _v;
53623
54712
  p0 = { ...rest, makes: [], grantsTapMana: [urza[1].toUpperCase()], grantTo: "artifact" };
53624
54713
  }
54714
+ if (p0.grantType && p0.grantsTapMana && new RegExp(`\\b${p0.grantType}s?\\b`).test(type) && p0.makes.length === 1 && p0.makes[0] === p0.grantsTapMana[0]) p0 = { ...p0, makes: [] };
53625
54715
  if (!p0.land && (p0.draws ?? 0) > 0 && /(?:^|\n)• each player may discard their hand and draw five cards\./.test(text)) p0 = { ...p0, wheel: true };
53626
54716
  const discDraw = !p0.land ? text.match(/(?:^|\n)you may (?:discard a card|sacrifice an? [a-z]+ or discard a card|discard a card or sacrifice an? [a-z]+)\. if you do, draw (two|three) cards\./) : null;
53627
54717
  if (discDraw && !p0.draws) p0 = { ...p0, draws: discDraw[1] === "three" ? 3 : 2, discards: 1, discardFirst: true };
@@ -53655,6 +54745,10 @@ function readProfile(card, oracleText) {
53655
54745
  const sb = text.match(/(?:^|\n)(\{t\}, )?sacrifice (?:this [a-z]+|~): add ((?:\{[wubrgc]\})+|one mana of any color)\.(?:\n|$)/);
53656
54746
  if (sb) p0 = { ...p0, sacBurst: { units: unitsOf(sb[2]), tap: !!sb[1] } };
53657
54747
  }
54748
+ if (!p0.makes.length && !p0.ritualMakes.length && !p0.sacBurst) {
54749
+ const own3 = text.match(/(?:^|\n)sacrifice an? ([a-z]+): add ((?:\{[wubrgc]\})+)\.(?:\n|$)/);
54750
+ if (own3 && own3[1] !== "land" && new RegExp(`\\b${own3[1]}\\b`).test(type)) p0 = { ...p0, sacBurst: { units: unitsOf(own3[2]), tap: false } };
54751
+ }
53658
54752
  const pt = text.match(/(?:^|\n)((?:\{[0-9wubrgc]\})+, \{t\}|\{t\}|(?:\{[0-9wubrgc]\})+): (?:roll a d(\d+) and create a number of treasure tokens equal to the result|create (a|an|one|two|three) treasure tokens?)\.( [^.\n]* gains control of this [a-z]+\.)?(?:\n|$)/);
53659
54753
  if (pt) {
53660
54754
  const c = parseCost(pt[1].replace(/(?:, )?\{t\}/, ""));
@@ -54446,12 +55540,12 @@ function planEngineProfiles({
54446
55540
  // A commander that cuts costs: -1 - zone.
54447
55541
  ...(commanderReads ?? []).map((p, z2) => ({ r: -1 - z2, red: p.reduces }))
54448
55542
  ].filter(
54449
- (x) => !!x.red && x.red.amount !== 0
55543
+ (x) => !!x.red && (x.red.amount !== 0 || !!x.red.pips)
54450
55544
  );
54451
55545
  const triggers = castTriggerSources(manaProfiles, commanderReads, finder);
54452
55546
  const byToughness = manaProfiles.some((p) => p.paidDraw?.sacCreature);
54453
55547
  const byPower = [...manaProfiles, ...commanderReads ?? []].some((p) => p.enterDraw?.minPower);
54454
- const byType = [...manaProfiles, ...commanderReads ?? []].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type);
55548
+ const byType = [...manaProfiles, ...commanderReads ?? []].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type || !!p.grantType);
54455
55549
  const byLegend = [...manaProfiles, ...commanderReads ?? []].some((p) => p.manaIf?.kind === "legendary");
54456
55550
  const byShare = deck.some((c) => !!tutorBoardShare(c.oracleId)) || (commanderReads ?? []).some((p) => !!p.tutorShares);
54457
55551
  const byImprint = [...manaProfiles, ...commanderReads ?? []].some((p) => p.manaIf?.kind === "imprint" || p.manaIf?.kind === "permanentColors");
@@ -54465,7 +55559,7 @@ function planEngineProfiles({
54465
55559
  const ov = tutorOv[oid];
54466
55560
  const cutBy = p.land ? [] : reducers.filter(
54467
55561
  ({ r, red }) => r !== i && (!red.finds.trim() || finder(chosenFinds(red.finds, deck))(deck[i]))
54468
- ).map(({ r, red }) => ({ by: r, amount: red.amount }));
55562
+ ).map(({ r, red }) => ({ by: r, amount: red.amount, ...red.pips ? { pips: red.pips } : {} }));
54469
55563
  return {
54470
55564
  ...p,
54471
55565
  ...tutorFields(read, ov, deck[i]),
@@ -54590,16 +55684,16 @@ function zoneEngineProfiles({
54590
55684
  const reducers = [
54591
55685
  ...manaProfiles.map((p, r) => ({ r, red: p.reduces })),
54592
55686
  ...commanderReads.map((p, z2) => ({ r: -1 - z2, red: p.reduces }))
54593
- ].filter((x) => !!x.red && x.red.amount !== 0);
55687
+ ].filter((x) => !!x.red && (x.red.amount !== 0 || !!x.red.pips));
54594
55688
  const triggers = castTriggerSources(manaProfiles, commanderReads, finder);
54595
55689
  const byToughness = manaProfiles.some((p) => p.paidDraw?.sacCreature);
54596
55690
  const byPower = [...manaProfiles, ...commanderReads].some((p) => p.enterDraw?.minPower);
54597
- const byType = [...manaProfiles, ...commanderReads].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type);
55691
+ const byType = [...manaProfiles, ...commanderReads].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type || !!p.grantType);
54598
55692
  const byLegend = [...manaProfiles, ...commanderReads].some((p) => p.manaIf?.kind === "legendary");
54599
55693
  const byShare = [...deck ?? [], ...zone].some((c) => !!tutorBoardShare(c.oracleId));
54600
55694
  const byRestricted = restrictedMana([...manaProfiles, ...commanderReads]);
54601
55695
  return commanderReads.map((p, z2) => {
54602
- const cutBy = reducers.filter(({ r, red }) => r !== -1 - z2 && (!red.finds.trim() || (!/@/.test(red.finds) || !!deck) && finder(chosenFinds(red.finds, deck ?? []))(zone[z2]))).map(({ r, red }) => ({ by: r, amount: red.amount }));
55696
+ const cutBy = reducers.filter(({ r, red }) => r !== -1 - z2 && (!red.finds.trim() || (!/@/.test(red.finds) || !!deck) && finder(chosenFinds(red.finds, deck ?? []))(zone[z2]))).map(({ r, red }) => ({ by: r, amount: red.amount, ...red.pips ? { pips: red.pips } : {} }));
54603
55697
  const triggeredBy = triggersOn(zone[z2], -1 - z2, triggers);
54604
55698
  const read = tutorReads?.get(zone[z2].oracleId);
54605
55699
  const ov = tutorOv?.[zone[z2].oracleId];
@@ -55230,6 +56324,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55230
56324
  return unit.replace(/^[WUBRGC]+/, colors);
55231
56325
  };
55232
56326
  const chosenColor = /* @__PURE__ */ new Map();
56327
+ const boostColor = /* @__PURE__ */ new Map();
55233
56328
  const deckColors = new Set([...profiles.flatMap((q) => Object.keys(q.pips)), ...opts.commanders.flatMap((c) => Object.keys(c.pips))].join("").replace(/[^WUBRG]/g, ""));
55234
56329
  const chooseColor = (can) => {
55235
56330
  const opts_ = [...can.replace(/[^WUBRG]/g, "")].filter((c) => deckColors.has(c));
@@ -55293,6 +56388,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55293
56388
  const charged = /* @__PURE__ */ new Set();
55294
56389
  const suspended = [];
55295
56390
  const cracked = /* @__PURE__ */ new Set();
56391
+ const rampLater = [];
55296
56392
  const rampUnits = [];
55297
56393
  const fixLands = () => {
55298
56394
  const all = fixesAll();
@@ -55349,6 +56445,16 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55349
56445
  }
55350
56446
  };
55351
56447
  const isOut = (by) => by < 0 ? !!zoneCast[-1 - by] : !!cast[by];
56448
+ const lessPips = (pips, by) => {
56449
+ if (!by?.some((x) => x.pips && isOut(x.by))) return pips;
56450
+ const out = { ...pips };
56451
+ for (const x of by) {
56452
+ if (!x.pips || !isOut(x.by)) continue;
56453
+ for (const [k, v] of Object.entries(x.pips)) if (out[k]) out[k] = Math.max(0, out[k] - v);
56454
+ }
56455
+ for (const k of Object.keys(out)) if (!out[k]) delete out[k];
56456
+ return out;
56457
+ };
55352
56458
  const cutOf = (by) => {
55353
56459
  if (!by) return 0;
55354
56460
  let n2 = 0;
@@ -55359,7 +56465,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55359
56465
  const costNow = (i, extra = 0) => {
55360
56466
  const q = profiles[i];
55361
56467
  const c = costParts(q, extra + xFor(i) + (q.scaling ? (kicked.get(i) ?? 0) * q.scaling.generic : 0));
55362
- return { generic: Math.max(0, c.generic - cut(i)), pips: c.pips };
56468
+ return { generic: Math.max(0, c.generic - cut(i)), pips: lessPips(c.pips, q.cutBy) };
55363
56469
  };
55364
56470
  const xFor = (i) => profiles[i].xCounters && rowNeeds(i) ? profiles[i].xSymbols ?? 1 : 0;
55365
56471
  const xPaid = /* @__PURE__ */ new Map();
@@ -55460,7 +56566,6 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55460
56566
  }
55461
56567
  };
55462
56568
  const resolveEffects = (i, refund, q) => {
55463
- for (let e = q.extraLandsNow ?? 0; e > 0 && playExtraLand(); e--) ;
55464
56569
  if (q.freeCast && !q.freeCast.each) for (let n2 = 0; n2 < q.freeCast.count && castFree(q.freeCast, i); n2++) ;
55465
56570
  if (q.treasures) lg?.("treasure", { made: q.treasures, why: "when it resolves or enters" });
55466
56571
  makeTreasure(q.treasures ?? 0);
@@ -55494,7 +56599,10 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55494
56599
  toPool(...g.map((x) => x.unit));
55495
56600
  }
55496
56601
  }
55497
- if (q.rampLands) {
56602
+ if (q.rampLands && q.rampCost && !pay(q.rampCost.generic, q.rampCost.pips, false)) {
56603
+ rampLater.push(i);
56604
+ lg?.("rampLater", { card: i, cost: { ...q.rampCost }, note: "its land search costs mana it doesn't have now: on a later main phase" });
56605
+ } else if (q.rampLands) {
55498
56606
  rampLandsOut += q.rampLands.n;
55499
56607
  const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
55500
56608
  rampUnits.push(...u);
@@ -55512,6 +56620,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55512
56620
  else discard(q.discards, !!q.discardsLand, false, !!q.discardRandom);
55513
56621
  }
55514
56622
  if (!noDraw) drawWith(q);
56623
+ for (let e = q.extraLandsNow ?? 0; e > 0 && playExtraLand(); e--) ;
55515
56624
  if (q.selects) dig(q.selects.look, q.selects.keep, !!q.selects.top);
55516
56625
  if (q.discards && !q.discardFirst && searching !== i) discard(q.discards, !!q.discardsLand, false, !!q.discardRandom);
55517
56626
  if (refund && q.untaps && !q.ritualMakes.length) {
@@ -56471,7 +57580,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56471
57580
  const q = c.profile;
56472
57581
  const off = cutOf(q?.cutBy);
56473
57582
  const tax = 2 * (zoneCasts[z2] ?? 0);
56474
- const options = [{ generic: Math.max(0, c.generic + tax - off), pips: c.pips, alt: null }];
57583
+ const options = [{ generic: Math.max(0, c.generic + tax - off), pips: lessPips(c.pips, q?.cutBy), alt: null }];
56475
57584
  for (const a of q?.alts ?? []) {
56476
57585
  if (!holds(a)) continue;
56477
57586
  const k = parseCost(a.cost);
@@ -56523,7 +57632,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56523
57632
  };
56524
57633
  const zoneMakesMana = (z2) => {
56525
57634
  const q = opts.commanders[z2].profile;
56526
- return !!q && (q.makes.length > 0 || !!q.boost || !!q.landfall?.length || (q.reduces?.amount ?? 0) > 0 || tableTreasure(q) || !!q.combatTreasures || !!q.tapTreasure);
57635
+ return !!q && (q.makes.length > 0 || !!q.boost || !!q.landfall?.length || (q.reduces?.amount ?? 0) > 0 || !!q.reduces?.pips || tableTreasure(q) || !!q.combatTreasures || !!q.tapTreasure);
56527
57636
  };
56528
57637
  const zoneSearches = (z2) => opts.useTutors && reqs.some((r, k) => !!r.zoneTutors?.[z2] && wanted(k));
56529
57638
  const zoneDraws = (z2) => {
@@ -57445,26 +58554,29 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57445
58554
  }
57446
58555
  };
57447
58556
  const granted = () => {
57448
- let adds;
58557
+ const creatureGrants = [];
57449
58558
  let artAdds;
57450
58559
  const take = (q) => {
57451
58560
  if (!q?.grantsTapMana?.length) return;
57452
58561
  if (q.grantTo === "artifact") artAdds ??= q.grantsTapMana[0];
57453
- else adds ??= q.grantsTapMana[0];
58562
+ else creatureGrants.push({ unit: q.grantsTapMana[0], ...q.grantType ? { type: q.grantType } : {} });
57454
58563
  };
57455
58564
  for (let j = 0; j < deckSize; j++) if (cast[j]) take(profiles[j]);
57456
58565
  for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2]) take(opts.commanders[z2].profile);
57457
- if (!adds && !artAdds) return [];
58566
+ if (!creatureGrants.length && !artAdds) return [];
58567
+ const grantFor = (types) => creatureGrants.find((g) => !g.type || !!types?.includes(g.type))?.unit;
57458
58568
  const out = [];
57459
58569
  for (let j = 0; j < deckSize; j++) {
57460
58570
  const q = profiles[j];
57461
58571
  if (!cast[j] || q.land || srcOut.get(j)?.length) continue;
57462
58572
  if (condOut.includes(j) && condUnit(j)) continue;
57463
- if (adds && q.creature && !(entered[j] === turn && !hasteOf(q, true))) out.push({ who: j, unit: adds });
58573
+ const adds = q.creature ? grantFor(q.types) : void 0;
58574
+ if (adds && !(entered[j] === turn && !hasteOf(q, true))) out.push({ who: j, unit: adds });
57464
58575
  else if (artAdds && q.artifact) out.push({ who: j, unit: artAdds });
57465
58576
  }
57466
58577
  for (let z2 = 0; z2 < zoneCast.length; z2++) {
57467
58578
  const c = opts.commanders[z2];
58579
+ const adds = grantFor(c.profile?.types);
57468
58580
  if (!adds || !zoneCast[z2] || c.creature === false || c.profile?.makes.length || zoneEntered[z2] === turn && !zoneHaste(z2)) continue;
57469
58581
  out.push({ who: -1 - z2, unit: adds });
57470
58582
  }
@@ -57478,11 +58590,17 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57478
58590
  };
57479
58591
  const boostUnits = () => {
57480
58592
  const by = [];
57481
- for (let j = 0; j < deckSize; j++) if (cast[j] && profiles[j].boost) by.push(profiles[j].boost);
57482
- for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2] && opts.commanders[z2].profile?.boost) by.push(opts.commanders[z2].profile.boost);
58593
+ const who = [];
58594
+ for (let j = 0; j < deckSize; j++) if (cast[j] && profiles[j].boost) by.push(profiles[j].boost), who.push(j);
58595
+ for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2] && opts.commanders[z2].profile?.boost) by.push(opts.commanders[z2].profile.boost), who.push(-1 - z2);
57483
58596
  if (!by.length) return [];
57484
58597
  const out = [];
57485
- for (const b of by) {
58598
+ for (const [n2, b] of by.entries()) {
58599
+ let chosen = "";
58600
+ if (b.chosenColor) {
58601
+ chosen = boostColor.get(who[n2]) ?? chooseColor("WUBRG");
58602
+ boostColor.set(who[n2], chosen);
58603
+ }
57486
58604
  const sources = b.per === "land" ? [...landOut] : b.per === "permanent" ? [...landOut, ...srcOut] : [...srcOut];
57487
58605
  for (const [j, units] of sources) {
57488
58606
  if (!units.length) continue;
@@ -57490,6 +58608,10 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57490
58608
  if (b.per === "creature" ? !q.creature : b.per === "artifact" ? !q.artifact : false) continue;
57491
58609
  if (b.landType && !(q.basicTypes ?? []).includes(b.landType)) continue;
57492
58610
  if (b.basicOnly && !q.basicLand) continue;
58611
+ if (chosen) {
58612
+ for (const u of units) if (u.includes(chosen) || u.includes("*")) out.push(chosen);
58613
+ continue;
58614
+ }
57493
58615
  if (b.per !== "land" && b.per !== "permanent" && q.enchantLand) continue;
57494
58616
  if (b.mult) for (let k = 0; k < b.mult; k++) out.push(...units);
57495
58617
  else out.push(...b.adds ?? [units[0]]);
@@ -57965,6 +59087,20 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57965
59087
  }
57966
59088
  condPaid.clear();
57967
59089
  condCheck();
59090
+ for (const j of [...rampLater]) {
59091
+ const q = profiles[j];
59092
+ if (!cast[j] || !q.rampLands || !q.rampCost || !pay(q.rampCost.generic, q.rampCost.pips, false)) continue;
59093
+ rampLater.splice(rampLater.indexOf(j), 1);
59094
+ rampLandsOut += q.rampLands.n;
59095
+ const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
59096
+ rampUnits.push(...u);
59097
+ lg?.("rampLands", { card: j, lands: q.rampLands.n, units: [...u], tapped: q.rampLands.tapped && !landsUntapped(), note: "an activated land search, paid now" });
59098
+ if (q.rampLands.tapped && !landsUntapped()) pending.push(...u);
59099
+ else {
59100
+ online.push(...u);
59101
+ toPool(...u);
59102
+ }
59103
+ }
57968
59104
  for (const j of [...manaLocked]) {
57969
59105
  if (!cast[j]) {
57970
59106
  manaLocked.delete(j);
@@ -58048,7 +59184,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58048
59184
  (i) => !profiles[i].land && !profiles[i].target && // (A sunburst source waits for the colors it could have: not
58049
59185
  // Pentad Prism off Sol Ring's {C}{C} when your lands make two.)
58050
59186
  !sunburstWaits(i) && manaIfSoon(i) && (profiles[i].makes.length > 0 || // A boost or landfall (Leyline of Abundance, Lotus Cobra) is mana while it's out.
58051
- !!profiles[i].boost || !!profiles[i].landfall?.length || (profiles[i].reduces?.amount ?? 0) > 0 || tableTreasure(profiles[i]) || (profiles[i].treasures ?? 0) > sizeOf(costNow(i)) || // Mana for every creature of yours (Cryptolith Rite), with one
59187
+ !!profiles[i].boost || !!profiles[i].landfall?.length || (profiles[i].reduces?.amount ?? 0) > 0 || !!profiles[i].reduces?.pips || tableTreasure(profiles[i]) || (profiles[i].treasures ?? 0) > sizeOf(costNow(i)) || // Mana for every creature of yours (Cryptolith Rite), with one
58052
59188
  // out or in hand; and with one out, a cheap creature is a dork
58053
59189
  // (2 mana or less: a 6-drop isn't ramp for one mana a turn).
58054
59190
  !!profiles[i].grantsTapMana?.length && (hasCreatureOut() || hand.some((h) => h !== i && !!profiles[h].creature && !profiles[h].land)) || !!profiles[i].creature && sizeOf(costNow(i)) <= 2 && grantOut() || // (With Urza out, a cheap artifact taps for {U}.)
@@ -58707,7 +59843,7 @@ function canonicalDeck(cards) {
58707
59843
  }
58708
59844
  function planContext(a) {
58709
59845
  const { deck, commanders, cards, oracle, otagIndex, overrides, tutorOv } = a;
58710
- const landFlags = deck.map((c) => isLand3(c));
59846
+ const landFlags = deck.map((c) => isLand4(c));
58711
59847
  const autoProfiles = oracle ? withLifeDraws(deck, withFetchColors(deck.map((c) => manaProfile(c, oracle(c.oracleId))))) : null;
58712
59848
  const tutorReads = new Map(oracle ? deck.map((c) => [c.oracleId, readTutor(c.manaCost, oracle(c.oracleId))]) : []);
58713
59849
  const zoneTutorReads = new Map(
@@ -60355,7 +61491,7 @@ function planZoneCard(c) {
60355
61491
  return { name: c.name.split(" // ")[0], cost: c.cmc, manaCost: c.manaCost, oracleId: c.oracleId, card: c };
60356
61492
  }
60357
61493
  var PLAN_GROUPS = [
60358
- { id: "land", label: "Lands", match: (c) => isLand3(c) },
61494
+ { id: "land", label: "Lands", match: (c) => isLand4(c) },
60359
61495
  { id: "creature", label: "Creatures", match: (c) => isCreatureType(c) },
60360
61496
  { id: "dork", label: "Mana creatures", match: (c) => isCreatureType(c) && c.roles.includes("ramp") },
60361
61497
  { id: "ramp", label: "Ramp", match: (c) => c.roles.includes("ramp") },
@@ -60728,11 +61864,12 @@ async function tryCatalog(ctx) {
60728
61864
  return null;
60729
61865
  }
60730
61866
  }
61867
+ var isUnread = (e) => e instanceof LibraryError && (e.kind === "not-connected" || e.kind === "no-scope");
60731
61868
  async function tryLibrary(ctx) {
60732
61869
  try {
60733
61870
  return await ctx.library.library();
60734
61871
  } catch (e) {
60735
- if (e instanceof LibraryError && e.kind === "not-connected") return null;
61872
+ if (isUnread(e)) return null;
60736
61873
  throw e;
60737
61874
  }
60738
61875
  }
@@ -60812,7 +61949,7 @@ async function collectionMatch(ctx, catalog, refresh) {
60812
61949
  try {
60813
61950
  stacks = await ctx.library.collection(refresh);
60814
61951
  } catch (e) {
60815
- if (e instanceof LibraryError && e.kind === "not-connected") return emptyMatchResult();
61952
+ if (isUnread(e)) return emptyMatchResult();
60816
61953
  throw e;
60817
61954
  }
60818
61955
  const out = emptyMatchResult();
@@ -60865,7 +62002,7 @@ var pastedNote = (src) => src.pasted ? {
60865
62002
  function curveOf(lines) {
60866
62003
  const curve = {};
60867
62004
  for (const l of lines) {
60868
- if (isLand2(l.card)) continue;
62005
+ if (isLand3(l.card)) continue;
60869
62006
  const key = l.card.cmc >= 7 ? "7+" : String(l.card.cmc);
60870
62007
  curve[key] = (curve[key] ?? 0) + l.qty;
60871
62008
  }
@@ -60880,7 +62017,7 @@ function matchesOnly(l, only, stored) {
60880
62017
  const o = only.toLowerCase();
60881
62018
  if (o === "buy" || o === "considering" || o === "sideboard") return l.board === o;
60882
62019
  if (l.board !== "main" && l.board !== "buy") return false;
60883
- if (o === "lands") return isLand2(l.card);
62020
+ if (o === "lands") return isLand3(l.card);
60884
62021
  if (l.card.typeLine.toLowerCase().includes(o)) return true;
60885
62022
  const cats = stored.v2Categories;
60886
62023
  const id = cats?.categories.find((c) => c.name.toLowerCase() === o)?.id;
@@ -60937,9 +62074,22 @@ var getDeck = {
60937
62074
  const src = await deckFrom(args, ctx, catalog);
60938
62075
  const { id, raw } = src;
60939
62076
  const combos = catalog ? await tryCombos(ctx) : null;
60940
- const stored = asDeck(raw);
62077
+ const detail = detailOf(args);
62078
+ let canNotes = !src.pasted && await ctx.library.has("notes");
62079
+ let notes = null;
62080
+ if (canNotes) {
62081
+ try {
62082
+ notes = await ctx.library.notesOf(id, args.refresh === true);
62083
+ } catch (e) {
62084
+ if (!(e instanceof LibraryError && e.kind === "no-scope")) throw e;
62085
+ canNotes = false;
62086
+ }
62087
+ }
62088
+ const stored = asDeck(notes ? { ...raw, ...notes } : raw);
62089
+ const noNotes = !src.pasted && !canNotes;
60941
62090
  return json2({
60942
- ...deckAnswer(viewDeck(id, stored, catalog, combos?.index), stored, detailOf(args), typeof args.only === "string" ? args.only : void 0),
62091
+ ...deckAnswer(viewDeck(id, stored, catalog, combos?.index), stored, detail, typeof args.only === "string" ? args.only : void 0),
62092
+ ...noNotes ? { notesLeftOut: noScopeMessage("notes") } : {},
60943
62093
  ...pastedNote(src),
60944
62094
  ...catalog ? comboNotes(combos) : {},
60945
62095
  ...catalog ? staleNote(catalog) : { note: "Card data isn't available, so card names and legality are missing." }
@@ -61326,7 +62476,7 @@ var cardTool = {
61326
62476
  yours = (await ownership(ctx, catalog, args.refresh === true)).row(c.oracleId, detail === "summary" ? "standard" : detail);
61327
62477
  } catch (e) {
61328
62478
  if (!(e instanceof LibraryError)) throw e;
61329
- if (e.kind !== "not-connected") missing.push(`what you own (${e.message})`);
62479
+ if (!isUnread(e)) missing.push(`what you own (${e.message})`);
61330
62480
  }
61331
62481
  const stale = [...catalog.stale ? ["the card catalog"] : [], ...x?.stale() ?? []];
61332
62482
  return json2({
@@ -61488,7 +62638,7 @@ var commanderTool = {
61488
62638
  owned = new Map([...own2.owned].map(([oid, r]) => [oid, r.stacks.reduce((n, s) => n + s.quantity, 0)]));
61489
62639
  } catch (e) {
61490
62640
  if (!(e instanceof LibraryError)) throw e;
61491
- if (e.kind !== "not-connected") missing.push(`what you own (${e.message})`);
62641
+ if (!isUnread(e)) missing.push(`what you own (${e.message})`);
61492
62642
  }
61493
62643
  }
61494
62644
  const ownedOf = (name) => {
@@ -61838,7 +62988,7 @@ var ownedIdsOf = async (ctx, catalog, refresh) => {
61838
62988
  const own2 = await ownership(ctx, catalog, refresh);
61839
62989
  return { ids: new Set(own2.owned.keys()), connected: true };
61840
62990
  } catch (e) {
61841
- if (e instanceof LibraryError && e.kind === "not-connected") return { ids: /* @__PURE__ */ new Set(), connected: false };
62991
+ if (isUnread(e)) return { ids: /* @__PURE__ */ new Set(), connected: false };
61842
62992
  throw e;
61843
62993
  }
61844
62994
  };
@@ -62069,7 +63219,226 @@ var comboSearch = {
62069
63219
  });
62070
63220
  }
62071
63221
  };
62072
- var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, planOdds];
63222
+ var slugIndexes = /* @__PURE__ */ new WeakMap();
63223
+ var slugIndexOf = (catalog) => {
63224
+ let s = slugIndexes.get(catalog.index);
63225
+ if (!s) slugIndexes.set(catalog.index, s = buildSlugCardIndex(catalog.index));
63226
+ return s;
63227
+ };
63228
+ var deckMapOf = (stored, catalog) => deckCardMapFromStored(
63229
+ {
63230
+ ...stored,
63231
+ assignments: stored.assignments ?? /* @__PURE__ */ new Map(),
63232
+ purchases: stored.purchases ?? /* @__PURE__ */ new Map(),
63233
+ basicQuantities: stored.basicQuantities ?? /* @__PURE__ */ new Map()
63234
+ },
63235
+ catalog.index,
63236
+ slugIndexOf(catalog)
63237
+ );
63238
+ var ownedOrNull = async (ctx, catalog, refresh) => {
63239
+ const o = await ownedIdsOf(ctx, catalog, refresh);
63240
+ return o.connected ? o.ids : null;
63241
+ };
63242
+ var compareTool = {
63243
+ name: "deck_compare",
63244
+ description: "Two decks side by side, as the deck builder's Compare shows them: the cards only in the first, only in the second, and in both (with each side's copies), over the 99 (commanders apart). And what the second deck's extra cards would cost to buy, minus the ones the user owns. Either deck can be saved, a pasted list, or a public Moxfield / Archidekt link.",
63245
+ input: {
63246
+ ...deckOrList,
63247
+ with: external_exports.string().optional().describe("The other deck: a saved deck's name or id."),
63248
+ withList: external_exports.string().optional().describe("Or the other deck as a pasted list or a public Moxfield / Archidekt link."),
63249
+ withCommander: external_exports.string().optional().describe("With withList: its commander, when the list doesn't mark one."),
63250
+ detail: detailInput,
63251
+ refresh: refreshInput
63252
+ },
63253
+ async run(args, ctx) {
63254
+ const catalog = await ctx.catalog();
63255
+ const mine = await deckFrom(args, ctx, catalog);
63256
+ if (!(typeof args.with === "string" && args.with.trim()) && !(typeof args.withList === "string" && args.withList.trim())) {
63257
+ throw new ToolProblem("Compare with which deck? Give with (a saved deck) or withList (a pasted list or link).");
63258
+ }
63259
+ const theirs = await deckFrom({ deck: args.with, list: args.withList, commander: args.withCommander, refresh: args.refresh }, ctx, catalog);
63260
+ const a = asDeck(mine.raw);
63261
+ const b = asDeck(theirs.raw);
63262
+ const diff = compareDecks(deckMapOf(a, catalog), deckMapOf(b, catalog));
63263
+ const owned = await ownedOrNull(ctx, catalog, args.refresh === true);
63264
+ const buy = buyDifference(diff.onlyTheirs, owned ?? /* @__PURE__ */ new Set());
63265
+ const detail = detailOf(args);
63266
+ const cap2 = { summary: 40, standard: 120, full: Infinity }[detail];
63267
+ const only = (xs) => xs.slice(0, cap2).map((x) => x.qty > 1 ? `${x.qty} ${x.card.name}` : x.card.name);
63268
+ const changed = diff.shared.filter(isQtyDelta);
63269
+ const nameOf = (s) => viewDeck(s.id, asDeck(s.raw), null).name;
63270
+ const cmdr = (s) => viewDeck(s.id, asDeck(s.raw), catalog, null).commanders;
63271
+ return json2({
63272
+ first: { deck: nameOf(mine), commanders: cmdr(mine), ...pastedNote(mine) },
63273
+ second: { deck: nameOf(theirs), commanders: cmdr(theirs), ...pastedNote(theirs) },
63274
+ counts: { onlyFirst: diff.onlyMine.length, onlySecond: diff.onlyTheirs.length, inBoth: diff.shared.length, inBothDifferentCopies: changed.length },
63275
+ onlyFirst: only(diff.onlyMine),
63276
+ onlySecond: only(diff.onlyTheirs),
63277
+ ...changed.length ? { differentCopies: changed.slice(0, cap2).map((s) => `${s.card.name}: ${s.mineQty} \u2192 ${s.theirsQty}`) } : {},
63278
+ ...detail !== "summary" ? { inBoth: diff.shared.slice(0, cap2).map((s) => s.card.name) } : {},
63279
+ ...diff.onlyMine.length > cap2 || diff.onlyTheirs.length > cap2 ? { more: "Ask with detail: full for every card." } : {},
63280
+ toAddTheSecondsCards: {
63281
+ cards: buy.differ,
63282
+ ...owned ? { youOwn: buy.own } : {},
63283
+ toBuy: owned ? buy.buyCount : buy.differ,
63284
+ usd: Math.round(buy.buyUsd * 100) / 100,
63285
+ ...owned ? {} : { note: "Without the collection (no access code, or one that can't read it), it counts every card as a buy." }
63286
+ },
63287
+ credit: SCRYFALL_CREDIT
63288
+ });
63289
+ }
63290
+ };
63291
+ var OVERLAP_SORTS = ["in", "name", "sticker", "price"];
63292
+ var overlapTool = {
63293
+ name: "deck_overlap",
63294
+ description: "Cards shared across the user's decks, as /overlap shows them: each card, how many of the chosen decks run it, which, and the copies each needs. With the sticker-share readout: decks you don't play at the same time can share one physical copy, so it says how many copies sharing saves and their value, and with the collection which shared cards the user owns. Basics are left out unless asked. Needs an access code.",
63295
+ input: {
63296
+ decks: external_exports.array(external_exports.string()).max(60).optional().describe("Which decks, by name or id (at least 2). Default: every deck."),
63297
+ minDecks: external_exports.number().int().min(2).max(60).optional().describe("Only cards in at least this many of them (default 2)."),
63298
+ includeBasics: external_exports.boolean().optional().describe("Also list basic lands (never counted in the savings)."),
63299
+ inDeck: external_exports.string().optional().describe("Only the shared cards in this one deck."),
63300
+ sort: external_exports.enum(OVERLAP_SORTS).optional().describe("in (default: most-shared first), name, sticker (owned first), or price."),
63301
+ detail: detailInput,
63302
+ refresh: refreshInput
63303
+ },
63304
+ async run(args, ctx) {
63305
+ const catalog = await ctx.catalog();
63306
+ const all = await ctx.library.decks(args.refresh === true);
63307
+ const chosen = Array.isArray(args.decks) && args.decks.length ? args.decks.map((d) => findDeck(d, all)) : [...all];
63308
+ const unique = [...new Map(chosen).entries()];
63309
+ if (unique.length < 2) throw new ToolProblem("Overlap needs at least 2 decks.");
63310
+ const names = unique.map(([id, raw]) => viewDeck(id, asDeck(raw), null).name);
63311
+ const tally = crossDeckOverlap(unique.map(([, raw]) => deckMapOf(asDeck(raw), catalog)));
63312
+ const owned = await ownedOrNull(ctx, catalog, args.refresh === true);
63313
+ const minDecks = typeof args.minDecks === "number" ? args.minDecks : MIN_SHARED_DECKS;
63314
+ let rows = filterOverlap(tally, { minDecks, includeBasics: args.includeBasics === true });
63315
+ if (typeof args.inDeck === "string" && args.inDeck.trim()) {
63316
+ const [id] = findDeck(args.inDeck, new Map(unique));
63317
+ const at = unique.findIndex(([x]) => x === id);
63318
+ rows = rows.filter((e) => e.deckIndices.includes(at));
63319
+ }
63320
+ const key = OVERLAP_SORTS.includes(args.sort) ? args.sort : "in";
63321
+ if (args.sort) rows = sortOverlapRows(rows, key, DEFAULT_DIR[key], owned);
63322
+ const summary = summarizeStickerShare(filterOverlap(tally, { minDecks, includeBasics: false }), owned);
63323
+ const cap2 = { summary: 40, standard: 150, full: 1e3 }[detailOf(args)];
63324
+ return json2({
63325
+ decks: names.length,
63326
+ ...names.length <= 12 ? { deckNames: names } : {},
63327
+ shared: {
63328
+ cards: summary.sharedCards,
63329
+ copiesSaved: summary.savedCopies,
63330
+ usdSaved: Math.round(summary.savedUsd * 100) / 100,
63331
+ ...summary.ownedCount !== null ? { youOwn: summary.ownedCount, toBuy: summary.toBuyCount } : {}
63332
+ },
63333
+ rows: rows.slice(0, cap2).map((e) => {
63334
+ const s = stickerReadout(e, owned);
63335
+ return {
63336
+ name: e.card.name,
63337
+ inDecks: e.inCount,
63338
+ decks: e.deckIndices.map((i) => names[i]),
63339
+ ...s.copiesIfSeparate !== e.inCount ? { copiesPerDeck: e.qtyPerDeck } : {},
63340
+ ...s.saved > 0 ? { sharingSaves: s.saved } : {},
63341
+ ...s.ownership ? { youHaveIt: s.ownership === "own" } : {},
63342
+ ...e.card.priceUsd != null ? { priceUsd: e.card.priceUsd } : {}
63343
+ };
63344
+ }),
63345
+ ...rows.length > cap2 ? { more: rows.length - cap2 } : {},
63346
+ about: "Sharing: decks you don't play at the same time can share one physical copy, moved between them. copiesSaved is the copies a one-per-deck approach needs minus the copies sharing needs; usdSaved prices them today (unpriced cards count 0).",
63347
+ credit: SCRYFALL_CREDIT
63348
+ });
63349
+ }
63350
+ };
63351
+ var manabaseTool = {
63352
+ name: "deck_manabase",
63353
+ description: "A deck's mana base, as the deck builder's Manabase shows it: lands run vs Karsten's recommended count (and what it's based on), the opening-hand odds (screw, keepable, flood), and per color the sources the deck runs vs Frank Karsten's target for what its spells demand, with the card that sets each target. For a short color, the fixing lands that would help (owned first, then by cycle, untapped, price) and the basic to cut to keep the land count. And what balancing the basics to the colored pips would change. A shortfall is a finding, not an error. Either a saved deck, a pasted list, or a public Moxfield / Archidekt link.",
63354
+ input: {
63355
+ ...deckOrList,
63356
+ refresh: refreshInput
63357
+ },
63358
+ async run(args, ctx) {
63359
+ const catalog = await ctx.catalog();
63360
+ const src = await deckFrom(args, ctx, catalog);
63361
+ const v = viewDeck(src.id, asDeck(src.raw), catalog, null);
63362
+ const missing = [];
63363
+ const tags = catalog.otags();
63364
+ if (!tags) missing.push("Scryfall tags (rocks and dorks fall back to any mana-making permanent)");
63365
+ const lens = tags ? makeCardTagLens(tags) : null;
63366
+ const deckCards = [
63367
+ ...v.commanderCards.map((card) => ({ card, copies: 1, source: "commander" })),
63368
+ ...v.lines.filter((l) => l.board === "main" || l.board === "buy").map((l) => ({ card: l.card, copies: l.qty }))
63369
+ ];
63370
+ const identity2 = MANA_COLOR_ORDER.filter((c) => v.commanderCards.some((x) => x.colors.includes(c)));
63371
+ const s = manabaseSummary(deckCards, identity2, lens);
63372
+ const cycles = await part(missing, "land cycles (no fixing-land suggestions)", ctx.extras?.landCycles);
63373
+ const owned = await ownedIdsOf(ctx, catalog, args.refresh === true);
63374
+ const fixes = new Map(
63375
+ (cycles ? buildManabaseFixes({
63376
+ report: s.report,
63377
+ deckCards,
63378
+ cards: catalog.index,
63379
+ identity: identity2,
63380
+ ownedOracleIds: owned.connected ? owned.ids : null,
63381
+ cycles,
63382
+ priceOf: (c) => c.priceUsd ?? void 0
63383
+ }) : []).map((f) => [f.color, f])
63384
+ );
63385
+ const fetches = cycles ? uncountedFetchCount(deckCards, cycles) : 0;
63386
+ const bal = balancedBasics(deckCards, identity2);
63387
+ const balance = MANA_COLOR_ORDER.flatMap((c) => {
63388
+ const have = bal.current.get(c)?.copies ?? 0;
63389
+ const want = bal.target[c] ?? 0;
63390
+ return have === want ? [] : [`${bal.basicName[c]}: ${have} \u2192 ${want}`];
63391
+ });
63392
+ const pct3 = (x) => Math.round(x * 100);
63393
+ return json2({
63394
+ deck: v.name,
63395
+ ...pastedNote(src),
63396
+ commander: v.commanders,
63397
+ lands: {
63398
+ have: s.landsHave,
63399
+ ...s.landsRecommended !== null ? { recommended: s.landsRecommended, basedOn: landInputsLabel(s.landInputs), ...Math.abs(s.landsHave - s.landsRecommended) >= LAND_COUNT_TOLERANCE ? { off: true } : {} } : {}
63400
+ },
63401
+ ...s.consistency ? {
63402
+ openingHand: {
63403
+ screwPct: pct3(s.consistency.screw),
63404
+ keepablePct: pct3(s.consistency.sweet),
63405
+ floodPct: pct3(s.consistency.flood),
63406
+ about: `Chance the opening 7 has 0-1 / 2-4 / 5+ lands (${s.consistency.landCount} of ${s.consistency.deckSize}). Exact math, no mulligan: the London mulligan only improves these.`
63407
+ }
63408
+ } : {},
63409
+ ...s.report.colorless ? { colorless: "Nothing in the deck needs or makes colored mana." } : {},
63410
+ colors: s.report.colors.map((r) => {
63411
+ const f = fixes.get(r.color);
63412
+ return {
63413
+ color: MANA_COLOR_LABEL[r.color],
63414
+ sources: r.have,
63415
+ ...r.target > 0 ? { target: r.target } : {},
63416
+ status: r.status === "short" ? `short ${formatShortfall(r.target, r.have)}` : COLOR_STATUS_LABEL[r.status],
63417
+ why: demandSentence(r, s.report.lands),
63418
+ ...f ? {
63419
+ fix: {
63420
+ move: f.cut ? `Swap a ${f.cut.card.name} for one of these (keeps the land count).` : "Add one of these (no basic to spare, so this raises the land count).",
63421
+ lands: f.candidates.map((c) => ({
63422
+ name: c.card.name,
63423
+ ...c.owned ? { youOwn: true } : {},
63424
+ ...c.cycleLabel ? { cycle: c.cycleLabel } : {},
63425
+ untapped: c.untapped,
63426
+ ...c.price != null ? { priceUsd: c.price } : {}
63427
+ })),
63428
+ ...fetches > 0 ? { note: `The deck runs ${fetches} fetch land${fetches === 1 ? "" : "s"} not counted above, so the real access is higher: treat this shortfall as a ceiling.` } : {}
63429
+ }
63430
+ } : {}
63431
+ };
63432
+ }),
63433
+ ...s.colorsShort.length ? { short: s.colorsShort.map((c) => shortLabel(c.color, c.shortBy)) } : {},
63434
+ ...bal.total > 0 ? { balanceBasics: balance.length ? balance : "The basics already match the color demand." } : {},
63435
+ about: "Sources: lands count 1; rocks and dorks count part of a source by the turn the spell needs them, as Karsten counts them. Targets are Frank Karsten's for the deck's land count. Short means 2 or more under target.",
63436
+ ...missing.length ? { missing } : {},
63437
+ credit: SCRYFALL_CREDIT
63438
+ });
63439
+ }
63440
+ };
63441
+ var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, compareTool, overlapTool, manabaseTool, planOdds];
62073
63442
 
62074
63443
  // src/server.ts
62075
63444
  async function serve(version2, ctx) {
@@ -62099,7 +63468,7 @@ var say = (m) => process.stderr.write(`${m}
62099
63468
  var transport = {
62100
63469
  fetchImpl: ((url2, init) => fetch(`${ORIGIN}${url2}`, {
62101
63470
  ...init,
62102
- headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.11"}` }
63471
+ headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.15"}` }
62103
63472
  }))
62104
63473
  };
62105
63474
  async function store(dir) {
@@ -62115,7 +63484,7 @@ async function secretFromEnv() {
62115
63484
  async function main() {
62116
63485
  const args = process.argv.slice(2);
62117
63486
  if (args.includes("--version")) {
62118
- say("0.2.11");
63487
+ say("0.2.15");
62119
63488
  return;
62120
63489
  }
62121
63490
  const dir = configDir();
@@ -62137,7 +63506,7 @@ async function main() {
62137
63506
  return;
62138
63507
  }
62139
63508
  const extras = extrasLoader({ dir, origin: ORIGIN });
62140
- await serve("0.2.11", {
63509
+ await serve("0.2.15", {
62141
63510
  library: new Library({ secret: await secretFromEnv() ?? loadSecret(secrets), dir, transport }),
62142
63511
  catalog: catalogLoader({ dir, origin: ORIGIN, prices: extras.prices }),
62143
63512
  combos: comboLoader({ dir, origin: ORIGIN }),