(function (root, factory) { const api = factory(); if (typeof module === 'object' && module.exports) module.exports = api; else root.GlemoResale = api; })(typeof window === 'undefined' ? globalThis : window, function () { 'use strict'; const KEY = 'glemo-assisted-resale-v1'; const ROLES = ['holder', 'buyer', 'compliance', 'rails', 'auditor', 'admin']; const STATES = ['draft', 'review', 'approved', 'listed', 'negotiating', 'agreement', 'settlement', 'reconciled', 'rejected', 'cancelled', 'expired']; const RESERVED = ['review', 'approved', 'listed', 'negotiating', 'agreement', 'settlement']; const CLOSED = ['reconciled', 'rejected', 'cancelled', 'expired']; const clone = x => JSON.parse(JSON.stringify(x)); const fail = code => { const e = new Error(code); e.code = code; throw e; }; const instant = x => typeof x === 'string' && Number.isFinite(Date.parse(x)); const text = (x, max = 200) => typeof x === 'string' && x.trim().length > 0 && x.length <= max; const integer = x => Number.isSafeInteger(x) && x >= 0; const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); function decimal(value, precision) { if (!Number.isInteger(precision) || precision < 0 || precision > 18) fail('invalid'); const s = String(value); if (!/^(0|[1-9]\d{0,24})(?:\.\d+)?$/.test(s)) fail('invalidNumber'); const [whole, fraction = ''] = s.split('.'); if (fraction.length > precision) fail('precision'); return (BigInt(whole) * 10n ** BigInt(precision) + BigInt(fraction.padEnd(precision, '0') || '0')).toString(); } function displayUnits(value, precision) { const padded = BigInt(value).toString().padStart(precision + 1, '0'); return precision ? (padded.slice(0, -precision) + '.' + padded.slice(-precision)).replace(/\.?0+$/, '') : padded; } function cents(value) { const n = BigInt(decimal(value, 2)); if (n > BigInt(Number.MAX_SAFE_INTEGER)) fail('invalidNumber'); return Number(n); } function rounded(n, d) { const result = (n + d / 2n) / d; if (result > BigInt(Number.MAX_SAFE_INTEGER)) fail('invalidNumber'); return Number(result); } const fee = (amount, bps) => rounded(BigInt(amount) * BigInt(bps), 10000n); function economics(quantity, decimals, priceCents, agent, thirdPartyCents = null) { if (!integer(priceCents) || priceCents === 0 || !/^\d+$/.test(quantity) || BigInt(quantity) <= 0n || typeof agent !== 'boolean' || !(thirdPartyCents === null || integer(thirdPartyCents))) fail('invalid'); const principal = rounded(BigInt(quantity) * BigInt(priceCents), 10n ** BigInt(decimals)); if (principal <= 0) fail('invalidNumber'); const glemo = fee(principal, 100), commission = agent ? fee(principal, 100) : 0; const net = principal - glemo - commission - (thirdPartyCents || 0); if (net < 0) fail('invalidNumber'); return {currency: 'USD', principal, glemo, agent: commission, thirdPartyCents, netBeforeUnknownCostsAndTax: net, taxCents: null, glemoBps: 100, agentBps: agent ? 100 : 0, feePayer: 'seller', collection: 'separate_invoice', roundedTo: 'cent_half_up'}; } function seed(now = new Date().toISOString()) { const pos = (id, asset, quantity, cost, policy = {}) => ({id, ownerId: 'ORG-001', asset, assetId: id, issuer: 'DEMO-ISSUER-AE', country: 'AE', city: 'Dubai', category: id === 'RS-AE-02' ? 'Real estate' : 'Private credit', decimals: 6, quantity: decimal(quantity, 6), costCents: cost, originalDeal: 'DEMO-PURCHASE-' + id, source: 'synthetic', sourceRevision: 1, network: 'DEMO-EVM', tokenRef: 'DEMO-TOKEN-' + id, sourceAccount: 'DEMO-EXTERNAL-ACCOUNT-ORG-001', policy: {transferable: true, issuerConsentRequired: true, lockedUntil: null, countries: ['AE'], qualifiedOnly: true, redemptionAvailable: false, ...policy}, createdAt: now}); return {schema: 1, revision: 0, simulation: true, positions: [pos('RS-AE-01', 'assetReceivables', '1000', 10000000), pos('RS-AE-02', 'assetProperty', '500', 5000000, {lockedUntil: new Date(Date.parse(now) + 30 * 86400000).toISOString()}), pos('RS-AE-03', 'assetFund', '200', 2000000, {transferable: false, redemptionAvailable: true})], requests: [], events: []}; } function valid(s) { try { if (!s || s.schema !== 1 || s.simulation !== true || !integer(s.revision) || !Array.isArray(s.positions) || !Array.isArray(s.requests) || !Array.isArray(s.events) || s.events.length !== s.revision) return false; if (new Set(s.positions.map(p => p.id)).size !== s.positions.length || new Set(s.requests.map(r => r.id)).size !== s.requests.length) return false; if (!s.positions.every(p => text(p.id) && text(p.ownerId) && text(p.asset) && text(p.assetId) && text(p.issuer) && /^[A-Z]{2}$/.test(p.country) && Number.isInteger(p.decimals) && p.decimals >= 0 && p.decimals <= 18 && /^\d+$/.test(p.quantity) && integer(p.costCents) && integer(p.sourceRevision) && p.sourceRevision > 0 && text(p.originalDeal) && text(p.source) && text(p.network) && text(p.tokenRef) && text(p.sourceAccount) && instant(p.createdAt) && p.policy && typeof p.policy.transferable === 'boolean' && typeof p.policy.issuerConsentRequired === 'boolean' && typeof p.policy.qualifiedOnly === 'boolean' && typeof p.policy.redemptionAvailable === 'boolean' && Array.isArray(p.policy.countries) && p.policy.countries.every(c => /^[A-Z]{2}$/.test(c)) && (p.policy.lockedUntil === null || instant(p.policy.lockedUntil)))) return false; if (!s.events.every((e, i) => e.sequence === i + 1 && instant(e.at) && text(e.action) && text(e.requestId) && text(e.commandId) && text(e.fingerprint, 10000) && e.actor && ROLES.includes(e.actor.role) && text(e.actor.id))) return false; if (new Set(s.events.map(e => e.commandId)).size !== s.events.length) return false; const proofRefs = new Set(); for (const r of s.requests) { const p = s.positions.find(p => p.id === r.positionId); if (!p || r.ownerId !== p.ownerId || !STATES.includes(r.status) || !/^\d+$/.test(r.quantity) || BigInt(r.quantity) <= 0n || !integer(r.priceCents) || r.priceCents === 0 || !integer(r.version) || r.version < 1 || typeof r.agent !== 'boolean' || !(r.thirdPartyCents === null || integer(r.thirdPartyCents)) || !instant(r.createdAt) || !instant(r.expiresAt) || !Array.isArray(r.history) || r.history.length !== r.version) return false; if (!r.history.every((e, i) => e.version === i + 1 && text(e.action) && instant(e.at) && e.actor && ROLES.includes(e.actor.role))) return false; const events = s.events.filter(e => e.requestId === r.id); if (events.length !== r.history.length || events.some((e, i) => e.action !== r.history[i].action || e.at !== r.history[i].at || !same(e.actor,r.history[i].actor))) return false; if (r.status === 'reconciled' && (!r.receipt || !r.cash || !r.delivery || !r.signatures.holder || !r.signatures.buyer)) return false; if (r.status === 'settlement' && (!r.signatures.holder || !r.signatures.buyer || !r.settlement)) return false; if (['agreement', 'settlement', 'reconciled'].includes(r.status) && (!r.proposal?.accepted.holder || !r.proposal?.accepted.buyer || !r.buyerId)) return false; if (r.instructions) { if (!integer(r.instructions.version) || r.instructions.version < 1 || ![r.instructions.destination,r.instructions.beneficiary,r.instructions.controlRef,r.instructions.gatewayRef,r.instructions.reference].every(v=>text(v)) || r.instructions.quantity !== r.quantity || r.instructions.buyerId !== r.buyerId || r.instructions.sourceAccount !== p.sourceAccount || r.instructions.network !== p.network || r.instructions.tokenRef !== p.tokenRef) return false; const expected = economics(r.quantity,p.decimals,r.proposal.priceCents,r.agent,r.thirdPartyCents); if (!same(r.instructions.economics,expected)) return false; } for (const side of ['holder','buyer']) if (r.signatures[side] && (!r.instructions || r.signatures[side].proposalVersion !== r.proposal.version || r.signatures[side].instructionsVersion !== r.instructions.version || r.signatures[side].instructions !== JSON.stringify(r.instructions))) return false; if (r.settlement && (!r.instructions || !same(r.settlement.instructions,r.instructions) || !same(r.settlement.economics,r.instructions.economics) || ['destination','beneficiary','controlRef','gatewayRef','buyerId','sourceAccount','network','tokenRef','quantity','version'].some(k=>r.settlement[k]!==r.instructions[k]))) return false; if (r.cash && (!r.settlement || r.cash.amountCents !== r.settlement.economics.principal || r.cash.currency !== 'USD' || r.cash.beneficiary !== r.settlement.beneficiary)) return false; if (r.delivery && (!r.settlement || ['quantity','network','tokenRef','destination','sourceAccount'].some(k=>r.delivery[k]!==r.settlement[k]))) return false; for (const item of [r.cash,r.delivery,r.receipt]) if (item) {if (!text(item.reference) || item.reference !== item.reference.trim() || proofRefs.has(item.reference)) return false; proofRefs.add(item.reference);} } if (s.events.filter(e=>e.action==='importPosition').some(e=>!s.positions.some(p=>p.id===e.requestId)) || s.events.some(e=>e.action!=='importPosition'&&!s.requests.some(r=>r.id===e.requestId))) return false; for (const p of s.positions) if (reserved(s, p.id) > BigInt(p.quantity)) return false; return true; } catch (_) { return false; } } function reserved(s, positionId, except = '') { return s.requests.filter(r => r.positionId === positionId && r.id !== except && RESERVED.includes(r.status)).reduce((n, r) => n + BigInt(r.quantity), 0n); } const available = (s, p, except = '') => (BigInt(p.quantity) - reserved(s, p.id, except)).toString(); function policyReasons(p, now) { const reasons = []; if (!p.policy.transferable) reasons.push('notTransferable'); if (p.policy.lockedUntil && Date.parse(p.policy.lockedUntil) > Date.parse(now)) reasons.push('locked'); return reasons; } function freshness(r, p, now) { return !!r.verification && r.verification.sourceRevision === p.sourceRevision && Date.parse(r.verification.validUntil) > Date.parse(now) && Date.parse(r.verification.at) <= Date.parse(now) && !policyReasons(p, now).length; } function eligible(p, r, buyer, now) { return !!buyer && text(buyer.id) && buyer.id !== r.ownerId && buyer.verified === true && buyer.suspended === false && buyer.gatewayApproved === true && instant(buyer.validUntil) && Date.parse(buyer.validUntil) > Date.parse(now) && p.policy.countries.includes(buyer.country) && (!p.policy.qualifiedOnly || buyer.qualified === true); } function dispatch(state, action, input, actor, context = {}) { if (!valid(state)) fail('corrupt'); if (!actor || !ROLES.includes(actor.role) || !text(actor.id)) fail('forbidden'); const now = context.now || new Date().toISOString(); if (!instant(now)) fail('invalid'); const x = clone(input || {}); if (!text(x.commandId)) fail('invalid'); const fingerprint = JSON.stringify({action, input: x, actor}); const replay = state.events.find(e => e.commandId === x.commandId); if (replay) { if (replay.fingerprint !== fingerprint) fail('conflict'); return clone(state); } if (x.expectedRevision !== state.revision) fail('conflict'); const s = clone(state); let r = s.requests.find(v => v.id === x.id), p = r ? s.positions.find(p => p.id === r.positionId) : s.positions.find(p => p.id === x.positionId); const role = (...roles) => { if (!roles.includes(actor.role)) fail('forbidden'); }; const owner = () => { role('holder'); if (!p || actor.partyId !== p.ownerId) fail('forbidden'); }; const party = () => { role('holder', 'buyer'); if (actor.role === 'holder') owner(); else if (!text(actor.partyId) || !text(r.buyerId) || actor.partyId !== r.buyerId) fail('forbidden'); }; const stage = (...states) => { if (!r || !states.includes(r.status)) fail('transition'); }; const live = () => { if (Date.parse(r.expiresAt) <= Date.parse(now)) fail('expiredError'); if (r.issue) fail('issueOpen'); }; const fresh = () => { if (!freshness(r, p, now)) fail('staleProof'); }; const proof = (value = x.reference) => { if (!text(value)) fail('proofRequired'); return value.trim(); }; const uniqueProof = value => { proof(value); const normalized = value.trim(); if (s.requests.some(v => [v.cash?.reference, v.delivery?.reference, v.receipt?.reference].includes(normalized))) fail('proofReused'); return normalized; }; const buyer = () => { const b = context.buyer; if (!eligible(p, r, b, now) || (r.buyerId && r.buyerId !== b.id) || (actor.role === 'buyer' && actor.partyId !== b.id)) fail('buyerIneligible'); return b; }; if (action === 'importPosition') { role('holder'); const imported = context.position; if (!imported || imported.ownerId !== actor.partyId || imported.id !== x.positionId || !['mobile_purchase_demo', 'mobile_fixture', 'platform_purchase_demo'].includes(imported.source)) fail('forbidden'); if (s.positions.some(v => v.id === imported.id)) fail('conflict'); s.positions.push(clone(imported)); s.revision++; s.events.push({sequence: s.revision, action, requestId: imported.id, commandId: x.commandId, fingerprint, actor: clone(actor), at: now}); if (!valid(s)) fail('invalid'); return s; } if (action !== 'create' && (!r || x.expectedVersion !== r.version)) fail(r ? 'conflict' : 'missing'); const before = r?.status || null; switch (action) { case 'create': { owner(); if (policyReasons(p, now).length) fail(policyReasons(p, now)[0]); const quantity = decimal(x.quantity, p.decimals), priceCents = cents(x.price); if (BigInt(quantity) <= 0n || BigInt(quantity) > BigInt(available(s, p)) || priceCents <= 0) fail('quantityError'); if (!Number.isInteger(x.days) || x.days < 1 || x.days > 30 || typeof x.agent !== 'boolean' || x.acknowledged !== true) fail('consentRequired'); const thirdPartyCents = x.thirdParty === '' || x.thirdParty == null ? null : cents(x.thirdParty); economics(quantity, p.decimals, priceCents, x.agent, thirdPartyCents); r = {id: 'RESALE-' + String(s.revision + 1).padStart(5, '0'), positionId: p.id, ownerId: p.ownerId, originalDeal: p.originalDeal, issuer: p.issuer, quantity, priceCents, agent: x.agent, thirdPartyCents, expiresAt: new Date(Date.parse(now) + x.days * 86400000).toISOString(), status: 'draft', version: 0, createdAt: now, updatedAt: now, verification: null, buyerId: null, proposal: null, signatures: {holder: null, buyer: null}, instructions: null, settlement: null, cash: null, delivery: null, receipt: null, issue: null, history: []}; s.requests.unshift(r); break; } case 'submit': { owner(); stage('draft'); live(); if (policyReasons(p, now).length) fail(policyReasons(p, now)[0]); if (BigInt(r.quantity) > BigInt(available(s, p, r.id))) fail('quantityError'); r.status = 'review'; break; } case 'verify': { role('compliance'); stage('review', 'approved', 'listed', 'negotiating', 'agreement'); live(); if (policyReasons(p, now).length) fail(policyReasons(p, now)[0]); if (!['ownership', 'transfer', 'issuer', 'jurisdiction', 'unencumbered', 'gateway', 'documents'].every(k => x[k] === true)) fail('checklistRequired'); if (x.sourceRevision !== p.sourceRevision || BigInt(r.quantity) > BigInt(available(s, p, r.id))) fail('staleProof'); r.verification = {reference: proof(), actor: clone(actor), at: now, sourceRevision: p.sourceRevision, validUntil: new Date(Date.parse(now) + 24 * 3600000).toISOString(), checks: ['ownership', 'transfer', 'issuer', 'jurisdiction', 'unencumbered', 'gateway', 'documents']}; if (r.status === 'review') r.status = 'approved'; break; } case 'reject': { role('compliance'); stage('review', 'approved', 'listed', 'negotiating'); if (!text(x.reason, 1000)) fail('reasonRequired'); r.reason = x.reason.trim(); r.status = 'rejected'; break; } case 'publish': owner(); stage('approved'); live(); fresh(); r.status = 'listed'; break; case 'propose': { role('holder', 'buyer'); stage('listed', 'negotiating'); live(); fresh(); if (actor.role === 'holder') { owner(); if (!r.buyerId) fail('transition'); buyer(); } else { const b = buyer(); if (r.buyerId && r.buyerId !== b.id) fail('buyerBusy'); r.buyerId = b.id; } const priceCents = cents(x.price); if (priceCents <= 0) fail('invalidNumber'); economics(r.quantity, p.decimals, priceCents, r.agent, r.thirdPartyCents); r.proposal = {version: (r.proposal?.version || 0) + 1, priceCents, by: actor.role, accepted: {holder: actor.role === 'holder', buyer: actor.role === 'buyer'}, at: now, validUntil: new Date(Math.min(Date.parse(r.expiresAt), Date.parse(now) + 86400000)).toISOString()}; r.signatures = {holder: null, buyer: null}; r.status = 'negotiating'; break; } case 'accept': { party(); stage('negotiating'); live(); fresh(); buyer(); if (!r.proposal || x.proposalVersion !== r.proposal.version || Date.parse(r.proposal.validUntil) <= Date.parse(now)) fail('quoteExpired'); if (x.acknowledged !== true) fail('consentRequired'); if (r.proposal.accepted[actor.role]) fail('transition'); r.proposal.accepted[actor.role] = true; if (r.proposal.accepted.holder && r.proposal.accepted.buyer) r.status = 'agreement'; break; } case 'sign': { party(); stage('agreement'); live(); fresh(); buyer(); if (r.signatures[actor.role] || x.proposalVersion !== r.proposal.version) fail('conflict'); if (x.acknowledged !== true) fail('consentRequired'); if (!r.instructions) fail('instructionsRequired'); r.signatures[actor.role] = {reference: proof(), actor: clone(actor), at: now, proposalVersion: r.proposal.version, instructionsVersion:r.instructions.version, instructions:JSON.stringify(r.instructions)}; break; } case 'instructions': { role('rails'); stage('agreement'); live(); fresh(); buyer(); if (![x.destination, x.beneficiary, x.controlRef, x.gatewayRef].every(v => text(v))) fail('proofRequired'); r.instructions = {version:(r.instructions?.version||0)+1, reference: proof(), actor: clone(actor), at: now, destination: x.destination.trim(), beneficiary: x.beneficiary.trim(), controlRef: x.controlRef.trim(), gatewayRef: x.gatewayRef.trim(), buyerId: r.buyerId, sourceAccount: p.sourceAccount, network: p.network, tokenRef: p.tokenRef, quantity: r.quantity, economics: economics(r.quantity, p.decimals, r.proposal.priceCents, r.agent, r.thirdPartyCents)}; r.signatures={holder:null,buyer:null};break; } case 'begin': { role('rails'); stage('agreement'); live(); fresh(); buyer(); if (!r.instructions || !r.signatures.holder || !r.signatures.buyer) fail('signaturesRequired'); if (['destination','beneficiary','controlRef','gatewayRef'].some(k=>x[k]!==undefined&&x[k]!==r.instructions[k])) fail('instructionsChanged'); r.settlement={...clone(r.instructions),reference:proof(),instructions:clone(r.instructions),actor:clone(actor),at:now}; r.status = 'settlement'; break; } case 'cash': { role('rails'); stage('settlement'); if (r.issue) fail('issueOpen'); if (r.cash) fail('transition'); if (cents(x.amount) !== r.settlement.economics.principal || x.beneficiary !== r.settlement.beneficiary || x.currency !== 'USD') fail('cashMismatch'); r.cash = {reference: uniqueProof(x.reference), actor: clone(actor), at: now, amountCents: cents(x.amount), beneficiary: x.beneficiary, currency: 'USD'}; break; } case 'delivery': { role('rails'); stage('settlement'); if (r.issue) fail('issueOpen'); if (r.delivery) fail('transition'); if (decimal(x.quantity, p.decimals) !== r.quantity || x.network !== r.settlement.network || x.tokenRef !== r.settlement.tokenRef || x.destination !== r.settlement.destination || x.sourceAccount !== r.settlement.sourceAccount) fail('deliveryMismatch'); r.delivery = {reference: uniqueProof(x.reference), actor: clone(actor), at: now, quantity: r.quantity, network: x.network, tokenRef: x.tokenRef, destination: x.destination, sourceAccount: x.sourceAccount}; break; } case 'reconcile': { role('auditor'); stage('settlement'); if (r.issue) fail('issueOpen'); if (!r.cash || !r.delivery || !r.signatures.holder || !r.signatures.buyer) fail('bothLegsRequired'); if ([r.cash.actor.id, r.delivery.actor.id, r.settlement.actor.id].includes(actor.id)) fail('independence'); const reference = uniqueProof(x.reference), q = BigInt(r.quantity), total = BigInt(p.quantity); if (q > total) fail('quantityError'); const allocatedCost = q === total ? p.costCents : rounded(BigInt(p.costCents) * q, total); const e = r.settlement.economics; r.receipt = {reference, actor: clone(actor), at: now, allocatedCostCents: allocatedCost, sellerNetCents: e.netBeforeUnknownCostsAndTax, realizedBeforeUnknownCostsAndTax: e.netBeforeUnknownCostsAndTax - allocatedCost, remainingQuantity: (total - q).toString(), costBasisMethod: 'proportional_remaining_cost', allCostsKnown: false}; p.quantity = (total - q).toString(); p.costCents -= allocatedCost; p.sourceRevision++; s.positions.push({...clone(p), id: 'POSITION-' + r.id, ownerId: r.buyerId, quantity: r.quantity, costCents: e.principal, sourceRevision: 1, originalDeal: r.id, source: 'simulated_resale', sourceAccount: r.settlement.destination, createdAt: now}); r.status = 'reconciled'; break; } case 'cancel': { owner(); stage('draft', 'review', 'approved', 'listed', 'negotiating'); if (!text(x.reason, 1000)) fail('reasonRequired'); r.reason = x.reason.trim(); r.status = 'cancelled'; break; } case 'expire': { role('compliance', 'admin'); stage('draft', 'review', 'approved', 'listed', 'negotiating'); if (Date.parse(r.expiresAt) > Date.parse(now)) fail('notExpired'); r.status = 'expired'; break; } case 'closeAgreement': { role('compliance');stage('agreement');if(r.issue)fail('issueOpen'); if(x.noMovement!==true||![x.holderReleaseRef,x.buyerReleaseRef,x.providerClosureRef].every(v=>text(v)))fail('closureRequired'); if(!text(x.reason,1000))fail('reasonRequired'); r.closure={reference:proof(),holderReleaseRef:x.holderReleaseRef.trim(),buyerReleaseRef:x.buyerReleaseRef.trim(),providerClosureRef:x.providerClosureRef.trim(),noExternalMovement:true,actor:clone(actor),at:now}; r.reason=x.reason.trim();r.status='cancelled';break; } case 'issue': { if (['holder', 'buyer'].includes(actor.role)) party(); else role('compliance', 'rails', 'auditor', 'admin'); if (CLOSED.includes(r.status) || r.issue) fail('transition'); if (!text(x.reason, 1000)) fail('reasonRequired'); r.issue = {reason: x.reason.trim(), actor: clone(actor), at: now}; break; } case 'resolve': { role('compliance', 'auditor'); if (!r.issue) fail('transition'); if (r.issue.actor.id === actor.id) fail('independence'); if (!text(x.reason, 1000)) fail('reasonRequired'); r.lastResolution = {reason: x.reason.trim(), reference: proof(), actor: clone(actor), at: now}; r.issue = null; break; } default: fail('transition'); } r.version++; r.updatedAt = now; r.history.push({version: r.version, action, actor: clone(actor), at: now, before, after: r.status, reference: x.reference || null, reason: x.reason || null, proposal: action === 'propose' ? clone(r.proposal) : null}); s.revision++; s.events.push({sequence: s.revision, action, requestId: r.id, commandId: x.commandId, fingerprint, actor: clone(actor), at: now}); if (!valid(s)) fail('invalid'); return s; } const queues = new WeakMap(); function createStore(storage, options = {}) { let state, health = 'ok', raw; function reload() { try { raw = storage.getItem(KEY); state = raw === null ? seed(options.now?.()) : JSON.parse(raw); if (!valid(state)) fail('corrupt'); health = 'ok'; } catch (e) { health = e.code === 'corrupt' || e instanceof SyntaxError ? 'corrupt' : 'storage'; state = null; } return health; } reload(); function command(action, input, actor, context) { const run = () => { if (health !== 'ok') fail(health); let current; try { current = storage.getItem(KEY); } catch (_) { fail('storage'); } if (current !== raw) { reload(); fail('conflict'); } const next = dispatch(state, action, input, actor, context); const serialized = JSON.stringify(next); try { storage.setItem(KEY, serialized); } catch (_) { fail('storage'); } state = next; raw = serialized; return clone(next); }; if (typeof window !== 'undefined') { if (!window.navigator?.locks?.request) return Promise.reject(Object.assign(new Error('concurrency'), {code: 'concurrency'})); return window.navigator.locks.request(KEY, {mode: 'exclusive'}, run); } const last = queues.get(storage) || Promise.resolve(); const next = last.catch(() => {}).then(run); queues.set(storage, next); return next; } return {get: () => { if (health !== 'ok') fail(health); return clone(state); }, health: () => health, reload, command}; } return Object.freeze({KEY, ROLES, STATES, RESERVED, CLOSED, decimal, displayUnits, cents, economics, seed, valid, reserved, available, policyReasons, freshness, eligible, dispatch, createStore}); });