| // Registry metadata + the Sugar Proxy API, layered on top of overlay.mjs / | |
| // index.mjs without changing either. Registries are optional enhancement: | |
| // `eu4.dir('history/provinces')` (the zero-config path) keeps working | |
| // exactly as before whether or not anything is registered. All this module | |
| // adds is: | |
| // 1. a declarative shape (`defineRegistry`) for "this directory's records | |
| // have this key style, these fields may legitimately repeat, and these | |
| // fields point at that other registry's key-space"; | |
| // 2. named accessors (`eu4.provinces()`, `eu4.countries()`, ...) that are | |
| // just `eu4.dir(registry.path)` with sugar-wrapped nodes; | |
| // 3. the Sugar Proxy itself (`sugar(node, registry)`), so `p.culture` | |
| // reads like `p.get('culture')` (or `p.all('culture')` for a | |
| // multi-valued field) and `p.culture = 'x'` writes through to | |
| // `p.set('culture', 'x')`. | |
| // | |
| // registry.key is NOT consulted to pick an overlay mode — overlay.mjs's own | |
| // MODE_TABLE (keyed by path) already decides that, independently of | |
| // anything declared here. `key` is documentation of what that mode's | |
| // natural key looks like, kept for readability and for tests that want to | |
| // cross-check a registry's declared `key` against `modeFor(registry.path)`. | |
| /** | |
| * @typedef {Object} RegistryDescriptor | |
| * @property {string} path - relative directory path, e.g. "history/provinces" | |
| * @property {string} as - property name to attach on `eu4`, e.g. "provinces" | |
| * @property {'province-id'|'country-tag'|'filename'} key - documents the natural key style (see header note) | |
| * @property {string[]} [multi] - field names that may legitimately repeat at top level | |
| * @property {Object<string,string>} [refs] - field name -> target registry `as` name (or a bare defined-set name like 'countries'/'cultures'/'religions'/'tradegoods') | |
| */ | |
| /** | |
| * Normalize a registry descriptor. Doesn't validate against the filesystem | |
| * or against overlay.mjs — just fills in the optional fields so every | |
| * consumer can assume `multi`/`refs` exist without checking. | |
| * | |
| * @param {RegistryDescriptor} descriptor | |
| * @returns {RegistryDescriptor} | |
| */ | |
| export function defineRegistry(descriptor) { | |
| if (!descriptor || typeof descriptor.path !== 'string' || typeof descriptor.as !== 'string') { | |
| throw new Error('defineRegistry: "path" and "as" are required'); | |
| } | |
| return { | |
| path: descriptor.path, | |
| as: descriptor.as, | |
| key: descriptor.key ?? 'filename', | |
| multi: descriptor.multi ?? [], | |
| refs: descriptor.refs ?? {}, | |
| }; | |
| } | |
| // Wraps one already-sugared-or-not Node behind a Proxy. Kept separate from | |
| // wrapCollection so it can be reused directly by anything that already has a | |
| // bare Node in hand (e.g. tests). | |
| export function sugar(node, registry) { | |
| if (!node) return node; | |
| const multi = registry?.multi ?? []; | |
| return new Proxy(node, { | |
| get(target, prop, receiver) { | |
| if (typeof prop !== 'string') return Reflect.get(target, prop, receiver); | |
| // `in` walks the prototype chain, so this covers every real method | |
| // (get/all/has/keys/bareValues/block/blocks/set/add/remove/at/raw/file) | |
| // AND every own instance field (items/tokens/text/path/layer/session/ | |
| // readonly/...) — none of those are ever shadowed by sugar, on | |
| // purpose: a field literally named "path" or "keys" in game data must | |
| // still be reached via .get('path')/.get('keys'), never silently | |
| // replace the real API. | |
| if (prop in target) return Reflect.get(target, prop, receiver); | |
| if (multi.includes(prop)) return target.all(prop); | |
| const occurrences = target.all(prop); | |
| if (occurrences.length > 1) return occurrences; | |
| return target.get(prop); // 0 or 1 occurrence — safe, never throws | |
| }, | |
| set(target, prop, value, receiver) { | |
| if (typeof prop === 'string' && !(prop in target)) { | |
| target.set(prop, value); | |
| return true; | |
| } | |
| return Reflect.set(target, prop, value, receiver); | |
| }, | |
| }); | |
| } | |
| // Wraps a makeCollection()-shaped collection (get/all/where) so every Node | |
| // it hands back is sugared. `where()` is reimplemented (rather than | |
| // delegated to the inner collection) so a caller's predicate function sees | |
| // SUGARED nodes — `col.where(n => n.culture === 'castillian')` only works | |
| // if `n` is already wrapped by the time the predicate runs. | |
| function wrapCollection(collection, registry) { | |
| const wrapNode = (node) => sugar(node, registry); | |
| return { | |
| async get(key) { | |
| return wrapNode(await collection.get(key)); | |
| }, | |
| async all() { | |
| return (await collection.all()).map(wrapNode); | |
| }, | |
| async where(predicate) { | |
| const nodes = (await collection.all()).map(wrapNode); | |
| if (typeof predicate === 'function') return nodes.filter(predicate); | |
| return nodes.filter((node) => Object.entries(predicate).every(([k, v]) => node.get(k) === v)); | |
| }, | |
| }; | |
| } | |
| /** | |
| * Attach `eu4[registry.as]` for every registry in the list. Each accessor | |
| * is an async function (matching `eu4.dir`'s own async shape): call it as | |
| * `await eu4.provinces()` to get a sugar-wrapped collection. Purely | |
| * additive — never touches `eu4.dir`/`eu4.file`/`eu4.save`. | |
| * | |
| * @param {ReturnType<typeof import('../src/index.mjs').load>} eu4 | |
| * @param {RegistryDescriptor[]} registries | |
| */ | |
| export function attachRegistries(eu4, registries) { | |
| for (const registry of registries) { | |
| eu4[registry.as] = async () => { | |
| const collection = await eu4.dir(registry.path); | |
| return wrapCollection(collection, registry); | |
| }; | |
| } | |
| return eu4; | |
| } | |