@flare-engine/progression 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,206 +1,245 @@
1
- // src/upgrade-track.ts
2
- function createUpgradeTrack(config) {
3
- function price(currentLevel) {
4
- if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;
5
- return Math.round(config.base * config.growth ** currentLevel);
6
- }
7
- function canBuy(wallet, currentLevel) {
8
- if (currentLevel >= config.cap) return false;
9
- return wallet >= price(currentLevel);
10
- }
11
- function buy(wallet, currentLevel) {
12
- if (!canBuy(wallet, currentLevel)) {
13
- return { ok: false, wallet, level: currentLevel };
14
- }
15
- return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };
16
- }
17
- function resolveStats(base, deltas, getLevel) {
18
- const out = {};
19
- for (const key of Object.keys(base)) {
20
- const level = Math.max(0, Math.floor(getLevel(key)));
21
- out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;
22
- }
23
- return out;
24
- }
25
- return { config, price, canBuy, buy, resolveStats };
26
- }
27
-
28
- // src/drop-roll.ts
29
1
  import { weightedIndexBy } from "@flare-engine/math";
2
+ //#region src/collectible-registry.ts
3
+ function makeRegistry(all, capstoneId, unlocked) {
4
+ const isComplete = [...all].every((id) => unlocked.has(id));
5
+ const isCapstone = capstoneId !== null && unlocked.has(capstoneId);
6
+ function unlock(id) {
7
+ if (!all.has(id) && id !== capstoneId) throw new Error(`CollectibleRegistry: unknown id "${String(id)}"`);
8
+ if (unlocked.has(id)) return reg;
9
+ const next = new Set(unlocked);
10
+ next.add(id);
11
+ if (capstoneId !== null && !next.has(capstoneId)) {
12
+ if ([...all].every((k) => next.has(k))) next.add(capstoneId);
13
+ }
14
+ return makeRegistry(all, capstoneId, next);
15
+ }
16
+ function partition() {
17
+ const have = [];
18
+ const missing = [];
19
+ for (const id of all) if (unlocked.has(id)) have.push(id);
20
+ else missing.push(id);
21
+ return {
22
+ have,
23
+ missing
24
+ };
25
+ }
26
+ function list() {
27
+ return [...all];
28
+ }
29
+ const reg = {
30
+ all,
31
+ capstoneId,
32
+ unlocked,
33
+ isComplete,
34
+ isCapstone,
35
+ unlock,
36
+ partition,
37
+ list
38
+ };
39
+ return reg;
40
+ }
41
+ /**
42
+ * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an
43
+ * optional `capstoneId`.
44
+ *
45
+ * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`
46
+ * (it is tracked as a separate gate — the capstone fires only on full completion,
47
+ * not by direct unlock through `ids` membership alone).
48
+ *
49
+ * The capstone MUST be distinct from all ids in `ids` — if not, the capstone
50
+ * unlock auto-fires on full completion regardless of whether the capstone id
51
+ * was directly unlocked via the `ids` set, which would be semantically ambiguous.
52
+ */
53
+ function createCollectibleRegistry(ids, capstoneId) {
54
+ const all = /* @__PURE__ */ new Set();
55
+ for (const id of ids) {
56
+ if (all.has(id)) throw new Error(`createCollectibleRegistry: duplicate id "${String(id)}"`);
57
+ all.add(id);
58
+ }
59
+ return makeRegistry(all, capstoneId ?? null, /* @__PURE__ */ new Set());
60
+ }
61
+ //#endregion
62
+ //#region src/drop-roll.ts
63
+ /**
64
+ * Pity-aware weighted drop roller.
65
+ *
66
+ * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the
67
+ * `dryPrev` scratch buffer are allocated once inside the factory closure and
68
+ * reused across calls. The `out` parameter receives the result in-place;
69
+ * aliasing `out.pity` against the input `pity` is safe because the function
70
+ * reads all input pity fields into `dryPrev` before writing any output pity
71
+ * fields.
72
+ */
73
+ /**
74
+ * Creates a `DropTable` from `entries`.
75
+ * The `weightAt` accessor and scratch buffer are allocated once inside this
76
+ * factory (not per-roll).
77
+ */
30
78
  function createDropTable(entries) {
31
- var currentIsAllowed = () => true;
32
- const weightAt = (entry) => currentIsAllowed(entry.item) ? entry.weight : 0;
33
- const dryPrev = new Float32Array(entries.length);
34
- function rollInto(rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed, out) {
35
- let picked = "none";
36
- for (let i = 0; i < entries.length; i++) {
37
- dryPrev[i] = pity[entries[i].item] ?? 0;
38
- }
39
- for (let i = 0; i < entries.length; i++) {
40
- const e = entries[i];
41
- const threshold = thresholds[e.item];
42
- if (threshold !== void 0 && isAllowed(e.item) && dryPrev[i] + 1 >= threshold) {
43
- picked = e.item;
44
- break;
45
- }
46
- }
47
- if (picked === "none") {
48
- if (rollChance01 < chancePerRoll) {
49
- currentIsAllowed = isAllowed;
50
- let allowedTotal = 0;
51
- for (let i = 0; i < entries.length; i++) {
52
- allowedTotal += weightAt(entries[i]);
53
- }
54
- if (allowedTotal > 0) {
55
- const idx = weightedIndexBy(entries, weightAt, rollTable01);
56
- const entry = entries[idx];
57
- if (entry !== void 0) picked = entry.item;
58
- }
59
- }
60
- }
61
- out.item = picked;
62
- for (let i = 0; i < entries.length; i++) {
63
- const e = entries[i];
64
- out.pity[e.item] = picked === e.item ? 0 : dryPrev[i] + 1;
65
- }
66
- }
67
- return { entries, rollInto };
79
+ var currentIsAllowed = () => true;
80
+ const weightAt = (entry) => currentIsAllowed(entry.item) ? entry.weight : 0;
81
+ const dryPrev = new Float32Array(entries.length);
82
+ function rollInto(rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed, out) {
83
+ let picked = "none";
84
+ for (let i = 0; i < entries.length; i++) dryPrev[i] = pity[entries[i].item] ?? 0;
85
+ for (let i = 0; i < entries.length; i++) {
86
+ const e = entries[i];
87
+ const threshold = thresholds[e.item];
88
+ if (threshold !== void 0 && isAllowed(e.item) && dryPrev[i] + 1 >= threshold) {
89
+ picked = e.item;
90
+ break;
91
+ }
92
+ }
93
+ if (picked === "none") {
94
+ if (rollChance01 < chancePerRoll) {
95
+ currentIsAllowed = isAllowed;
96
+ let allowedTotal = 0;
97
+ for (let i = 0; i < entries.length; i++) allowedTotal += weightAt(entries[i]);
98
+ if (allowedTotal > 0) {
99
+ const entry = entries[weightedIndexBy(entries, weightAt, rollTable01)];
100
+ if (entry !== void 0) picked = entry.item;
101
+ }
102
+ }
103
+ }
104
+ out.item = picked;
105
+ for (let i = 0; i < entries.length; i++) {
106
+ const e = entries[i];
107
+ out.pity[e.item] = picked === e.item ? 0 : dryPrev[i] + 1;
108
+ }
109
+ }
110
+ return {
111
+ entries,
112
+ rollInto
113
+ };
68
114
  }
115
+ /**
116
+ * Allocating convenience wrapper. Creates a fresh pity object and returns both.
117
+ * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.
118
+ */
69
119
  function rollDrop(table, rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed) {
70
- const out = { item: "none", pity: { ...pity } };
71
- table.rollInto(
72
- rollTable01,
73
- rollChance01,
74
- chancePerRoll,
75
- pity,
76
- thresholds,
77
- isAllowed ?? (() => true),
78
- out
79
- );
80
- return out;
120
+ const out = {
121
+ item: "none",
122
+ pity: { ...pity }
123
+ };
124
+ table.rollInto(rollTable01, rollChance01, chancePerRoll, pity, thresholds, isAllowed ?? (() => true), out);
125
+ return out;
81
126
  }
82
-
83
- // src/unlock-dag.ts
84
- function createUnlockDag(nodes) {
85
- const map = /* @__PURE__ */ new Map();
86
- for (const node of nodes) {
87
- if (map.has(node.id)) {
88
- throw new Error(`createUnlockDag: duplicate node id "${node.id}"`);
89
- }
90
- map.set(node.id, node);
91
- }
92
- function isUnlocked(cleared, id) {
93
- const node = map.get(id);
94
- if (!node) return false;
95
- for (const req of node.requires) {
96
- if (!cleared.has(req)) return false;
97
- }
98
- return true;
99
- }
100
- function frontier(cleared) {
101
- const out = [];
102
- for (const [id] of map) {
103
- if (!cleared.has(id) && isUnlocked(cleared, id)) {
104
- out.push(id);
105
- }
106
- }
107
- return out;
108
- }
109
- function allUnlocked(cleared) {
110
- const out = [];
111
- for (const [id] of map) {
112
- if (isUnlocked(cleared, id)) {
113
- out.push(id);
114
- }
115
- }
116
- return out;
117
- }
118
- return { nodes: map, isUnlocked, frontier, allUnlocked };
119
- }
120
-
121
- // src/tier-resolve.ts
127
+ //#endregion
128
+ //#region src/tier-resolve.ts
129
+ /**
130
+ * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,
131
+ * or `null` when `tally` is below all thresholds.
132
+ *
133
+ * `entries` need not be sorted — the function scans all entries and returns the
134
+ * one with the largest `at` that satisfies `tally >= at`.
135
+ * Ties (identical `at`) are broken by iteration order (last entry wins).
136
+ */
122
137
  function resolveTier(entries, tally) {
123
- let best = null;
124
- let bestAt = Number.NEGATIVE_INFINITY;
125
- for (const e of entries) {
126
- if (tally >= e.at && e.at >= bestAt) {
127
- best = e.tier;
128
- bestAt = e.at;
129
- }
130
- }
131
- return best;
138
+ let best = null;
139
+ let bestAt = Number.NEGATIVE_INFINITY;
140
+ for (const e of entries) if (tally >= e.at && e.at >= bestAt) {
141
+ best = e.tier;
142
+ bestAt = e.at;
143
+ }
144
+ return best;
132
145
  }
146
+ /**
147
+ * Returns the index (0-based) of the highest satisfied tier entry,
148
+ * or -1 when `tally` is below all thresholds.
149
+ * Same tie-breaking rules as `resolveTier`.
150
+ */
133
151
  function resolveTierIndex(entries, tally) {
134
- let bestIdx = -1;
135
- let bestAt = Number.NEGATIVE_INFINITY;
136
- for (let i = 0; i < entries.length; i++) {
137
- const e = entries[i];
138
- if (e !== void 0 && tally >= e.at && e.at >= bestAt) {
139
- bestIdx = i;
140
- bestAt = e.at;
141
- }
142
- }
143
- return bestIdx;
152
+ let bestIdx = -1;
153
+ let bestAt = Number.NEGATIVE_INFINITY;
154
+ for (let i = 0; i < entries.length; i++) {
155
+ const e = entries[i];
156
+ if (e !== void 0 && tally >= e.at && e.at >= bestAt) {
157
+ bestIdx = i;
158
+ bestAt = e.at;
159
+ }
160
+ }
161
+ return bestIdx;
144
162
  }
145
-
146
- // src/collectible-registry.ts
147
- function makeRegistry(all, capstoneId, unlocked) {
148
- const isComplete = [...all].every((id) => unlocked.has(id));
149
- const isCapstone = capstoneId !== null && unlocked.has(capstoneId);
150
- function unlock(id) {
151
- if (!all.has(id) && id !== capstoneId) {
152
- throw new Error(`CollectibleRegistry: unknown id "${String(id)}"`);
153
- }
154
- if (unlocked.has(id)) return reg;
155
- const next = new Set(unlocked);
156
- next.add(id);
157
- if (capstoneId !== null && !next.has(capstoneId)) {
158
- const allComplete = [...all].every((k) => next.has(k));
159
- if (allComplete) next.add(capstoneId);
160
- }
161
- return makeRegistry(all, capstoneId, next);
162
- }
163
- function partition() {
164
- const have = [];
165
- const missing = [];
166
- for (const id of all) {
167
- if (unlocked.has(id)) have.push(id);
168
- else missing.push(id);
169
- }
170
- return { have, missing };
171
- }
172
- function list() {
173
- return [...all];
174
- }
175
- const reg = {
176
- all,
177
- capstoneId,
178
- unlocked,
179
- isComplete,
180
- isCapstone,
181
- unlock,
182
- partition,
183
- list
184
- };
185
- return reg;
163
+ //#endregion
164
+ //#region src/unlock-dag.ts
165
+ /**
166
+ * Creates an `UnlockDag` from `nodes`.
167
+ * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node
168
+ * whose prerequisite id doesn't exist in the graph is simply never satisfiable.
169
+ */
170
+ function createUnlockDag(nodes) {
171
+ const map = /* @__PURE__ */ new Map();
172
+ for (const node of nodes) {
173
+ if (map.has(node.id)) throw new Error(`createUnlockDag: duplicate node id "${node.id}"`);
174
+ map.set(node.id, node);
175
+ }
176
+ function isUnlocked(cleared, id) {
177
+ const node = map.get(id);
178
+ if (!node) return false;
179
+ for (const req of node.requires) if (!cleared.has(req)) return false;
180
+ return true;
181
+ }
182
+ function frontier(cleared) {
183
+ const out = [];
184
+ for (const [id] of map) if (!cleared.has(id) && isUnlocked(cleared, id)) out.push(id);
185
+ return out;
186
+ }
187
+ function allUnlocked(cleared) {
188
+ const out = [];
189
+ for (const [id] of map) if (isUnlocked(cleared, id)) out.push(id);
190
+ return out;
191
+ }
192
+ return {
193
+ nodes: map,
194
+ isUnlocked,
195
+ frontier,
196
+ allUnlocked
197
+ };
186
198
  }
187
- function createCollectibleRegistry(ids, capstoneId) {
188
- const all = /* @__PURE__ */ new Set();
189
- for (const id of ids) {
190
- if (all.has(id)) {
191
- throw new Error(`createCollectibleRegistry: duplicate id "${String(id)}"`);
192
- }
193
- all.add(id);
194
- }
195
- return makeRegistry(all, capstoneId ?? null, /* @__PURE__ */ new Set());
199
+ //#endregion
200
+ //#region src/upgrade-track.ts
201
+ /**
202
+ * Returns an `UpgradeTrack` backed by `config`.
203
+ * The returned object is a plain object (no class) — safe to freeze or copy.
204
+ */
205
+ function createUpgradeTrack(config) {
206
+ function price(currentLevel) {
207
+ if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;
208
+ return Math.round(config.base * config.growth ** currentLevel);
209
+ }
210
+ function canBuy(wallet, currentLevel) {
211
+ if (currentLevel >= config.cap) return false;
212
+ return wallet >= price(currentLevel);
213
+ }
214
+ function buy(wallet, currentLevel) {
215
+ if (!canBuy(wallet, currentLevel)) return {
216
+ ok: false,
217
+ wallet,
218
+ level: currentLevel
219
+ };
220
+ return {
221
+ ok: true,
222
+ wallet: wallet - price(currentLevel),
223
+ level: currentLevel + 1
224
+ };
225
+ }
226
+ function resolveStats(base, deltas, getLevel) {
227
+ const out = {};
228
+ for (const key of Object.keys(base)) {
229
+ const level = Math.max(0, Math.floor(getLevel(key)));
230
+ out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;
231
+ }
232
+ return out;
233
+ }
234
+ return {
235
+ config,
236
+ price,
237
+ canBuy,
238
+ buy,
239
+ resolveStats
240
+ };
196
241
  }
197
- export {
198
- createCollectibleRegistry,
199
- createDropTable,
200
- createUnlockDag,
201
- createUpgradeTrack,
202
- resolveTier,
203
- resolveTierIndex,
204
- rollDrop
205
- };
242
+ //#endregion
243
+ export { createCollectibleRegistry, createDropTable, createUnlockDag, createUpgradeTrack, resolveTier, resolveTierIndex, rollDrop };
244
+
206
245
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/upgrade-track.ts","../src/drop-roll.ts","../src/unlock-dag.ts","../src/tier-resolve.ts","../src/collectible-registry.ts"],"sourcesContent":["/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n // biome-ignore lint/style/noVar: intentional closure var for zero-alloc hot path\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n let best: T | null = null;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (const e of entries) {\n if (tally >= e.at && e.at >= bestAt) {\n best = e.tier;\n bestAt = e.at;\n }\n }\n return best;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`\n * (it is tracked as a separate gate — the capstone fires only on full completion,\n * not by direct unlock through `ids` membership alone).\n *\n * The capstone MUST be distinct from all ids in `ids` — if not, the capstone\n * unlock auto-fires on full completion regardless of whether the capstone id\n * was directly unlocked via the `ids` set, which would be semantically ambiguous.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n"],"mappings":";AAqDO,SAAS,mBAAmB,QAA0C;AAC3E,WAAS,MAAM,cAA8B;AAC3C,QAAI,gBAAgB,OAAO,IAAK,QAAO,OAAO;AAC9C,WAAO,KAAK,MAAM,OAAO,OAAO,OAAO,UAAU,YAAY;AAAA,EAC/D;AAEA,WAAS,OAAO,QAAgB,cAA+B;AAC7D,QAAI,gBAAgB,OAAO,IAAK,QAAO;AACvC,WAAO,UAAU,MAAM,YAAY;AAAA,EACrC;AAEA,WAAS,I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src/tier-resolve.ts","../src/unlock-dag.ts","../src/upgrade-track.ts"],"sourcesContent":["/**\n * Collectible-unlock registry: immutable unlock-set + partition + capstone.\n *\n * The registry is generic over a string id type.\n * All operations return new registry instances — no mutation.\n */\n\nexport interface CollectibleRegistry<K extends string> {\n /** The complete set of collectible ids (excluding the capstone). */\n readonly all: ReadonlySet<K>;\n /** The capstone id, or null when no capstone is defined. */\n readonly capstoneId: K | null;\n /** Currently unlocked ids (a subset of `all`, plus capstone when triggered). */\n readonly unlocked: ReadonlySet<K>;\n /** True when every collectible in `all` is unlocked. */\n readonly isComplete: boolean;\n /**\n * True when the capstone is in `unlocked`. Always false when `capstoneId`\n * is null.\n */\n readonly isCapstone: boolean;\n /**\n * Returns a new registry with `id` added to `unlocked`. Idempotent.\n * Automatically adds the capstone when `isComplete` transitions to true\n * and a capstone is defined.\n * Throws on unknown ids (not in `all` and not the capstoneId).\n */\n unlock(id: K): CollectibleRegistry<K>;\n /**\n * Partition the unlocked set into `{ have, missing }`.\n * `have` = ids in `all` that are in `unlocked` (capstone excluded).\n * `missing` = ids in `all` not yet unlocked.\n */\n partition(): { have: readonly K[]; missing: readonly K[] };\n /**\n * Returns all ids in `all` in insertion order.\n */\n list(): readonly K[];\n}\n\nfunction makeRegistry<K extends string>(\n all: ReadonlySet<K>,\n capstoneId: K | null,\n unlocked: ReadonlySet<K>,\n): CollectibleRegistry<K> {\n const isComplete = [...all].every((id) => unlocked.has(id));\n const isCapstone = capstoneId !== null && unlocked.has(capstoneId);\n\n function unlock(id: K): CollectibleRegistry<K> {\n if (!all.has(id) && id !== capstoneId) {\n throw new Error(`CollectibleRegistry: unknown id \"${String(id)}\"`);\n }\n if (unlocked.has(id)) return reg;\n const next = new Set<K>(unlocked);\n next.add(id);\n // Auto-unlock capstone on completion.\n if (capstoneId !== null && !next.has(capstoneId)) {\n const allComplete = [...all].every((k) => next.has(k));\n if (allComplete) next.add(capstoneId);\n }\n return makeRegistry(all, capstoneId, next);\n }\n\n function partition(): { have: readonly K[]; missing: readonly K[] } {\n const have: K[] = [];\n const missing: K[] = [];\n for (const id of all) {\n if (unlocked.has(id)) have.push(id);\n else missing.push(id);\n }\n return { have, missing };\n }\n\n function list(): readonly K[] {\n return [...all];\n }\n\n const reg: CollectibleRegistry<K> = {\n all,\n capstoneId,\n unlocked,\n isComplete,\n isCapstone,\n unlock,\n partition,\n list,\n };\n return reg;\n}\n\n/**\n * Creates a `CollectibleRegistry` from `ids` (the collectible set) and an\n * optional `capstoneId`.\n *\n * Duplicate ids in `ids` throw. `capstoneId` may equal one of the ids in `ids`\n * (it is tracked as a separate gate — the capstone fires only on full completion,\n * not by direct unlock through `ids` membership alone).\n *\n * The capstone MUST be distinct from all ids in `ids` — if not, the capstone\n * unlock auto-fires on full completion regardless of whether the capstone id\n * was directly unlocked via the `ids` set, which would be semantically ambiguous.\n */\nexport function createCollectibleRegistry<K extends string>(\n ids: readonly K[],\n capstoneId?: K,\n): CollectibleRegistry<K> {\n const all = new Set<K>();\n for (const id of ids) {\n if (all.has(id)) {\n throw new Error(`createCollectibleRegistry: duplicate id \"${String(id)}\"`);\n }\n all.add(id);\n }\n return makeRegistry<K>(all, capstoneId ?? null, new Set<K>());\n}\n","/**\n * Pity-aware weighted drop roller.\n *\n * `rollInto` is zero-alloc on the hot path: the `weightAt` accessor and the\n * `dryPrev` scratch buffer are allocated once inside the factory closure and\n * reused across calls. The `out` parameter receives the result in-place;\n * aliasing `out.pity` against the input `pity` is safe because the function\n * reads all input pity fields into `dryPrev` before writing any output pity\n * fields.\n */\n\nimport { weightedIndexBy } from '@flare-engine/math';\n\nexport interface DropEntry<K extends string> {\n readonly item: K;\n readonly weight: number;\n}\n\n/**\n * Per-item dry-roll counters feeding the pity guarantees.\n * Keys are the item ids whose pity is being tracked.\n */\nexport type DropPity<K extends string> = Record<K, number>;\n\nexport interface DropRollOut<K extends string> {\n item: K | 'none';\n pity: DropPity<K>;\n}\n\n/**\n * A `DropTable` is a factory that closes over a weight accessor to avoid\n * per-call allocations. Create once; reuse across frames.\n */\nexport interface DropTable<K extends string> {\n readonly entries: readonly DropEntry<K>[];\n /**\n * Zero-alloc weighted drop. Writes result into `out`.\n *\n * Algorithm:\n * 1. Check pity thresholds (first matching pity item fires unconditionally).\n * 2. If no pity fires and `rollChance01 >= chancePerRoll`, result = 'none'.\n * 3. Otherwise pick from the weighted table filtered by `isAllowed`.\n * An all-gated pool (every entry filtered out) fizzles to 'none'.\n *\n * `out.pity` counters reset for the dropped item, advance by 1 for all others.\n * Aliasing `out.pity` against the input `pity` is safe.\n */\n rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void;\n}\n\n/**\n * Creates a `DropTable` from `entries`.\n * The `weightAt` accessor and scratch buffer are allocated once inside this\n * factory (not per-roll).\n */\nexport function createDropTable<K extends string>(entries: readonly DropEntry<K>[]): DropTable<K> {\n // Closed-over filter state — set before each weightedIndexBy call.\n // `var` so the binding is function-scoped and hoisted; reassigned each call.\n var currentIsAllowed: (item: K) => boolean = () => true;\n\n const weightAt = (entry: DropEntry<K>): number =>\n currentIsAllowed(entry.item) ? entry.weight : 0;\n\n // Pre-allocated scratch buffer: stores dry counts read from `pity` before\n // any writes, enabling safe aliasing of out.pity === pity.\n const dryPrev = new Float32Array(entries.length);\n\n function rollInto(\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed: (item: K) => boolean,\n out: DropRollOut<K>,\n ): void {\n let picked: K | 'none' = 'none';\n\n // Read all pity inputs into scratch before writing any output (aliasing guard).\n for (let i = 0; i < entries.length; i++) {\n dryPrev[i] = pity[(entries[i] as DropEntry<K>).item] ?? 0;\n }\n\n // Pity check — first item whose dry count + 1 meets or exceeds threshold.\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n const threshold = thresholds[e.item];\n if (threshold !== undefined && isAllowed(e.item) && (dryPrev[i] as number) + 1 >= threshold) {\n picked = e.item;\n break;\n }\n }\n\n // Chance gate + weighted pick.\n if (picked === 'none') {\n if (rollChance01 < chancePerRoll) {\n currentIsAllowed = isAllowed;\n // Compute allowed total to detect an all-gated pool (fizzles to 'none').\n let allowedTotal = 0;\n for (let i = 0; i < entries.length; i++) {\n allowedTotal += weightAt(entries[i] as DropEntry<K>);\n }\n if (allowedTotal > 0) {\n const idx = weightedIndexBy(entries, weightAt, rollTable01);\n const entry = entries[idx];\n if (entry !== undefined) picked = entry.item;\n }\n }\n }\n\n // Write output — pity counters.\n out.item = picked;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i] as DropEntry<K>;\n (out.pity as Record<string, number>)[e.item] =\n picked === e.item ? 0 : (dryPrev[i] as number) + 1;\n }\n }\n\n return { entries, rollInto };\n}\n\n/**\n * Allocating convenience wrapper. Creates a fresh pity object and returns both.\n * Use `table.rollInto` on the hot path; this is for tests and cold-path setup.\n */\nexport function rollDrop<K extends string>(\n table: DropTable<K>,\n rollTable01: number,\n rollChance01: number,\n chancePerRoll: number,\n pity: DropPity<K>,\n thresholds: Partial<Record<K, number>>,\n isAllowed?: (item: K) => boolean,\n): DropRollOut<K> {\n const out: DropRollOut<K> = { item: 'none', pity: { ...pity } };\n table.rollInto(\n rollTable01,\n rollChance01,\n chancePerRoll,\n pity,\n thresholds,\n isAllowed ?? (() => true),\n out,\n );\n return out;\n}\n","/**\n * Tier resolution: \"highest threshold crossed by a running tally.\"\n *\n * The tally tiers are caller-defined (generic `T`) so the same resolver\n * works for score brackets, XP thresholds, unlock gates, etc.\n */\n\nexport interface TierEntry<T> {\n /** Minimum tally value (inclusive) required to reach this tier. */\n readonly at: number;\n /** The tier value associated with this threshold. */\n readonly tier: T;\n}\n\n/**\n * Returns the highest tier whose `at` threshold is met or exceeded by `tally`,\n * or `null` when `tally` is below all thresholds.\n *\n * `entries` need not be sorted — the function scans all entries and returns the\n * one with the largest `at` that satisfies `tally >= at`.\n * Ties (identical `at`) are broken by iteration order (last entry wins).\n */\nexport function resolveTier<T>(entries: readonly TierEntry<T>[], tally: number): T | null {\n let best: T | null = null;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (const e of entries) {\n if (tally >= e.at && e.at >= bestAt) {\n best = e.tier;\n bestAt = e.at;\n }\n }\n return best;\n}\n\n/**\n * Returns the index (0-based) of the highest satisfied tier entry,\n * or -1 when `tally` is below all thresholds.\n * Same tie-breaking rules as `resolveTier`.\n */\nexport function resolveTierIndex<T>(entries: readonly TierEntry<T>[], tally: number): number {\n let bestIdx = -1;\n let bestAt = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n if (e !== undefined && tally >= e.at && e.at >= bestAt) {\n bestIdx = i;\n bestAt = e.at;\n }\n }\n return bestIdx;\n}\n","/**\n * Prerequisite DAG for unlock/progression graphs.\n *\n * The graph is directed and acyclic by construction (caller contract — no runtime cycle\n * detection). Nodes are string ids; edges are \"requires\" lists.\n */\n\nexport interface DagNode {\n /** Unique string id for this node. */\n readonly id: string;\n /** Ids of nodes that must be in the cleared set before this node unlocks. */\n readonly requires: readonly string[];\n}\n\nexport interface UnlockDag {\n readonly nodes: ReadonlyMap<string, DagNode>;\n /**\n * Whether `id` is unlocked given the set of cleared (previously unlocked) ids.\n * A node with no requirements is always unlocked.\n * An unknown id returns false.\n */\n isUnlocked(cleared: ReadonlySet<string>, id: string): boolean;\n /**\n * The frontier: all nodes whose requirements are fully satisfied by `cleared`,\n * but which are NOT yet in `cleared`. Returned as a sorted array (stable\n * insertion order from `nodes`).\n */\n frontier(cleared: ReadonlySet<string>): readonly string[];\n /**\n * All nodes currently unlocked by `cleared` (including those already in\n * `cleared`). Returned as a sorted array (stable insertion order).\n */\n allUnlocked(cleared: ReadonlySet<string>): readonly string[];\n}\n\n/**\n * Creates an `UnlockDag` from `nodes`.\n * Duplicate ids throw. Unknown `requires` ids are silently tolerated — a node\n * whose prerequisite id doesn't exist in the graph is simply never satisfiable.\n */\nexport function createUnlockDag(nodes: readonly DagNode[]): UnlockDag {\n const map = new Map<string, DagNode>();\n for (const node of nodes) {\n if (map.has(node.id)) {\n throw new Error(`createUnlockDag: duplicate node id \"${node.id}\"`);\n }\n map.set(node.id, node);\n }\n\n function isUnlocked(cleared: ReadonlySet<string>, id: string): boolean {\n const node = map.get(id);\n if (!node) return false;\n for (const req of node.requires) {\n if (!cleared.has(req)) return false;\n }\n return true;\n }\n\n function frontier(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (!cleared.has(id) && isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n function allUnlocked(cleared: ReadonlySet<string>): readonly string[] {\n const out: string[] = [];\n for (const [id] of map) {\n if (isUnlocked(cleared, id)) {\n out.push(id);\n }\n }\n return out;\n }\n\n return { nodes: map, isUnlocked, frontier, allUnlocked };\n}\n","/**\n * Geometric upgrade track with an immutable buy operation.\n * price(level) = round(base × growth^level) — the next-level cost from `level`.\n * Consolidates the common geometric-cost upgrade pattern.\n */\n\nexport interface UpgradeTrackConfig {\n /** Base price at level 0 → 1. */\n readonly base: number;\n /** Multiplicative growth factor per level. */\n readonly growth: number;\n /** Hard level cap (inclusive). */\n readonly cap: number;\n}\n\nexport interface UpgradeBuyResult {\n readonly ok: boolean;\n readonly wallet: number;\n readonly level: number;\n}\n\nexport interface UpgradeTrack {\n readonly config: UpgradeTrackConfig;\n /**\n * Cost to advance from `currentLevel` to `currentLevel + 1`.\n * Returns Infinity when at or above cap.\n */\n price(currentLevel: number): number;\n /** Whether `wallet` is sufficient and `currentLevel` is below cap. */\n canBuy(wallet: number, currentLevel: number): boolean;\n /**\n * Pure spend: deduct `price(currentLevel)` from `wallet` and return\n * the new state. Returns `{ ok: false, wallet, level }` when blocked.\n */\n buy(wallet: number, currentLevel: number): UpgradeBuyResult;\n /**\n * Fold all per-level stat deltas into a running accumulator.\n * `getLevel` is a caller-supplied reader so the resolver is unit-testable\n * without any save/store dep. `deltas` maps a stat key to the per-level delta;\n * `base` is the starting value for each key.\n * Returns a plain Record with the accumulated values.\n */\n resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number>;\n}\n\n/**\n * Returns an `UpgradeTrack` backed by `config`.\n * The returned object is a plain object (no class) — safe to freeze or copy.\n */\nexport function createUpgradeTrack(config: UpgradeTrackConfig): UpgradeTrack {\n function price(currentLevel: number): number {\n if (currentLevel >= config.cap) return Number.POSITIVE_INFINITY;\n return Math.round(config.base * config.growth ** currentLevel);\n }\n\n function canBuy(wallet: number, currentLevel: number): boolean {\n if (currentLevel >= config.cap) return false;\n return wallet >= price(currentLevel);\n }\n\n function buy(wallet: number, currentLevel: number): UpgradeBuyResult {\n if (!canBuy(wallet, currentLevel)) {\n return { ok: false, wallet, level: currentLevel };\n }\n return { ok: true, wallet: wallet - price(currentLevel), level: currentLevel + 1 };\n }\n\n function resolveStats<K extends string>(\n base: Record<K, number>,\n deltas: Record<K, number>,\n getLevel: (key: K) => number,\n ): Record<K, number> {\n const out = {} as Record<K, number>;\n for (const key of Object.keys(base) as K[]) {\n const level = Math.max(0, Math.floor(getLevel(key)));\n out[key] = (base[key] ?? 0) + (deltas[key] ?? 0) * level;\n }\n return out;\n }\n\n return { config, price, canBuy, buy, resolveStats };\n}\n"],"mappings":";;AAwCA,SAAS,aACP,KACA,YACA,UACwB;CACxB,MAAM,aAAa,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,SAAS,IAAI,EAAE,CAAC;CAC1D,MAAM,aAAa,eAAe,QAAQ,SAAS,IAAI,UAAU;CAEjE,SAAS,OAAO,IAA+B;EAC7C,IAAI,CAAC,IAAI,IAAI,EAAE,KAAK,OAAO,YACzB,MAAM,IAAI,MAAM,oCAAoC,OAAO,EAAE,EAAE,EAAE;EAEnE,IAAI,SAAS,IAAI,EAAE,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S,OAAO,QAAgB,cAA+B;EAC7D,IAAI,gBAAgB,OAAO,KAAK,OAAO;EACvC,OAAO,UAAU,MAAM,YAAY;CACrC;CAEA,SAAS,IAAI,QAAgB,cAAwC;EACnE,IAAI,CAAC,OAAO,QAAQ,YAAY,GAC9B,OAAO;GAAE,IAAI;GAAO;GAAQ,OAAO;EAAa;EAElD,OAAO;GAAE,IAAI;GAAM,QAAQ,SAAS,MAAM,YAAY;GAAG,OAAO,eAAe;EAAE;CACnF;CAEA,SAAS,aACP,MACA,QACA,UACmB;EACnB,MAAM,MAAM,CAAC;EACb,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAU;GAC1C,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,GAAG,CAAC,CAAC;GACnD,IAAI,QAAQ,KAAK,QAAQ,MAAM,OAAO,QAAQ,KAAK;EACrD;EACA,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAO;EAAQ;EAAK;CAAa;AACpD"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@flare-engine/progression",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Meta-progression primitives: upgrade tracks, drop-roll with pity, unlock DAG, tier resolution, collectible registry",
5
5
  "keywords": ["flare-engine", "progression", "upgrade", "drop", "unlock", "tier"],
6
- "license": "MIT",
6
+ "license": "Apache-2.0",
7
7
  "author": "Grzegorz Otto",
8
8
  "homepage": "https://github.com/grzott/flare-engine#readme",
9
9
  "bugs": {
@@ -19,24 +19,32 @@
19
19
  "types": "dist/index.d.ts",
20
20
  "exports": {
21
21
  ".": {
22
- "types": "./dist/index.d.ts",
23
- "import": "./dist/index.mjs",
24
- "require": "./dist/index.js"
22
+ "import": {
23
+ "types": "./dist/index.d.mts",
24
+ "default": "./dist/index.mjs"
25
+ },
26
+ "require": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
25
30
  }
26
31
  },
27
- "files": ["dist", "README.md", "LICENSE"],
32
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
28
33
  "scripts": {
29
- "build": "tsup",
34
+ "build": "tsdown",
30
35
  "test": "bun test",
31
36
  "lint": "biome check src/",
32
37
  "typecheck": "tsc --noEmit"
33
38
  },
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
34
42
  "publishConfig": {
35
43
  "access": "restricted",
36
44
  "registry": "https://registry.npmjs.org/"
37
45
  },
38
46
  "sideEffects": false,
39
47
  "dependencies": {
40
- "@flare-engine/math": "^0.2.0"
48
+ "@flare-engine/math": "^0.3.0"
41
49
  }
42
50
  }