@storylet-studio/play-helpers 0.9.0 → 0.10.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.cjs +18 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -6
- package/dist/index.d.ts +26 -6
- package/dist/index.js +18 -10
- package/dist/index.js.map +1 -1
- package/dist/storyletengine.min.js +4 -4
- package/dist/storyletengine.min.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var StoryletEngine=(()=>{var Se=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Gt=Object.prototype.hasOwnProperty;var qt=(s,e)=>{for(var t in e)Se(s,t,{get:e[t],enumerable:!0})},zt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _t(e))!Gt.call(s,n)&&n!==t&&Se(s,n,{get:()=>e[n],enumerable:!(r=Ft(e,n))||r.enumerable});return s};var Ut=s=>zt(Se({},"__esModule",{value:!0}),s);var Cr={};qt(Cr,{Engine:()=>ue,Flow:()=>ne,applyLiveBundle:()=>Vt,boardFrame:()=>ze,createBundleInspector:()=>Dt,createKernelStateLogger:()=>Y,createLiveLink:()=>Ht,createPropertyInspector:()=>At,createStateLogger:()=>It,createWorldContainer:()=>Nt,describeBundle:()=>fe,deserializeState:()=>me,diffState:()=>X,ensureInspectorStyle:()=>se,formatLogEntry:()=>_e,formatPropertySummary:()=>Ge,formatScopeLabel:()=>qe,loadState:()=>Fe,makePrng:()=>D,saveState:()=>je,serializeState:()=>he,shuffleInPlace:()=>H,snapshotState:()=>Rt});function T(s){switch(s[0]){case"b":return{kind:"bool",value:s[1]};case"n":return{kind:"number",value:s[1]};case"s":return{kind:"string",value:s[1]};case"sv":return{kind:"scopedvar",scope:s[1],name:s[2]};case"u":return{kind:"unary",op:s[1],operand:T(s[2])};case"bin":return{kind:"binary",op:s[1],left:T(s[2]),right:T(s[3])};case"call":{let e=s.slice(2).map(T);return{kind:"call",name:s[1],args:e}}case"fd":return{kind:"flagdelta",sign:s[1],name:s[2]}}}var v=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ie(s,e,t){let r=new Map(t.scopes.map(o=>[o.token,o.missing??"false"])),n=o=>{switch(o.kind){case"bool":return o.value;case"number":return o.value;case"string":return o.value;case"scopedvar":{let i=e.scopes[o.scope];if(i===void 0)return!1;let a=typeof i.get=="function"?i.get(o.name):i[o.name];if(a===void 0){if(r.get(o.scope)==="throw")throw new v(`@${o.scope}.${o.name} is not declared on the current ${o.scope}.`);return!1}return a}case"call":{if(o.name==="advance"&&!t.functions[o.name]){let a=o.args[0];if(o.args.length!==1||a===void 0)throw new v(`advance() takes exactly 1 argument, got ${o.args.length}`);let d=Ee(a,e);if(d===void 0)throw new v("advance() needs a quality reference (@scope.name of a quality property)");let l=M(n(a),d,"advance");return d[Math.min(l+1,d.length-1)]}let i=t.functions[o.name];if(!i)throw new v(`unknown function '${o.name}'`);return i.eval(o.args,{evaluate:n,ctx:e})}case"flagdelta":throw new v("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(o.op==="not"){let a=n(o.operand);if(typeof a!="boolean")throw new v(`'not' requires a boolean operand, got ${typeof a}`);return!a}let i=n(o.operand);if(typeof i!="number")throw new v(`unary '-' requires a numeric operand, got ${typeof i}`);return-i}case"binary":{if(o.op==="and"){let p=n(o.left);if(typeof p!="boolean")throw new v(`'and' requires boolean operands, left is ${typeof p}`);if(!p)return!1;let f=n(o.right);if(typeof f!="boolean")throw new v(`'and' requires boolean operands, right is ${typeof f}`);return f}if(o.op==="or"){let p=n(o.left);if(typeof p!="boolean")throw new v(`'or' requires boolean operands, left is ${typeof p}`);if(p)return!0;let f=n(o.right);if(typeof f!="boolean")throw new v(`'or' requires boolean operands, right is ${typeof f}`);return f}let i=n(o.left),a=n(o.right),d=Ee(o.left,e),l=Ee(o.right,e),c=d??l;if(c!==void 0){if(d&&l&&!Wt(d,l)&&(o.op===">"||o.op===">="||o.op==="<"||o.op==="<="))throw new v(`'${o.op}' compares two different qualities, whose stage orders are unrelated`);switch(o.op){case">":return M(i,c,">")>M(a,c,">");case">=":return M(i,c,">=")>=M(a,c,">=");case"<":return M(i,c,"<")<M(a,c,"<");case"<=":return M(i,c,"<=")<=M(a,c,"<=");case"+":case"-":case"*":case"/":throw new v(`'${o.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(o.op){case"==":return tt(i,a);case"!=":return!tt(i,a);case">":return A(i,a,">"),i>a;case">=":return A(i,a,">="),i>=a;case"<":return A(i,a,"<"),i<a;case"<=":return A(i,a,"<="),i<=a;case"+":if(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string")return i+a;throw new v(`'+' requires two numbers or two strings, got ${typeof i} and ${typeof a}`);case"-":return A(i,a,"-"),i-a;case"*":return A(i,a,"*"),i*a;case"/":if(A(i,a,"/"),a===0)throw new v("division by zero");return i/a}}}};return n(s)}function tt(s,e){if(Array.isArray(s)||Array.isArray(e)){if(!Array.isArray(s)||!Array.isArray(e)||s.length!==e.length)return!1;let t=[...s].sort(),r=[...e].sort();for(let n=0;n<t.length;n++)if(t[n]!==r[n])return!1;return!0}return s===e}function A(s,e,t){if(typeof s!="number"||typeof e!="number")throw new v(`'${t}' requires numeric operands, got ${typeof s} and ${typeof e}`)}function Ee(s,e){if(!(s.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(s.scope,s.name)}function M(s,e,t){if(typeof s!="string")throw new v(`'${t}' on a quality compares stages, got ${typeof s}`);let r=e.indexOf(s);if(r<0)throw new v(`"${s}" is not a stage of this quality (stages: ${e.join(", ")})`);return r}var Wt=(s,e)=>s.length===e.length&&s.every((t,r)=>t===e[r]);function rt(s){if(Number.isNaN(s)||!Number.isFinite(s))return 0;let e=Math.trunc(s)%4294967296;return e<0?e+4294967296:e}function D(s){let e=rt(s);return{next(){e=e+1831565813>>>0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296},state(){return e}}}function H(s,e){for(let t=s.length-1;t>0;t--){let r=Math.floor(e.next()*(t+1));[s[t],s[r]]=[s[r],s[t]]}}var Kt={name:"check_flags",count:s=>Math.max(1,s.args.length-1)},Jt=[Kt];function nt(s,e,t){let r=t?.countingCalls??Jt;return ae(s,t?.want??!0,e,r)}function ae(s,e,t,r){if(s.kind==="binary"&&(s.op==="and"||s.op==="or")){let n=ae(s.left,e,t,r),o=ae(s.right,e,t,r);return s.op==="and"===e?n>0&&o>0?n+o:0:Math.max(n,o)}if(s.kind==="unary"&&s.op==="not")return ae(s.operand,!e,t,r);if(s.kind==="call"){let n=r.find(o=>o.name===s.name);if(n){let o=n.count(s),i=t(s);return e?i?o:0:i?0:1}}return t(s)===e?1:0}var st=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];var de=9999,U=s=>s.ctx.host??{},_=(s,e,t,r)=>{let n=t.evaluate(e[r]);if(typeof n!="string"||n==="")throw new v(`${s}() argument ${r+1} must be a non-empty string`);return n},ot=(s,e,t)=>{if(e.length===0)throw new v(`${s}() requires at least one argument (the flags property)`);let r=t.evaluate(e[0]);if(Array.isArray(r))return r;if(r===!1)return[];throw new v(`${s}() first argument must be a flags property`)},it=["story","world","box","deck","hand"],Qt=st.map(s=>s.token).filter(s=>!it.includes(s)),ke={scopes:[...it.map(s=>({token:s,missing:"throw"})),...Qt.map(s=>({token:s,missing:"throw"}))],defaultScope:"story",functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(s,e){if(s.length!==2)throw new v("random(a, b) requires exactly 2 arguments");let t=U(e).nextRandom;if(!t)throw new v("random() called without a PRNG in context");let r=e.evaluate(s[0]),n=e.evaluate(s[1]);if(typeof r!="number"||typeof n!="number")throw new v("random(a, b) arguments must be numbers");if(!Number.isInteger(r)||!Number.isInteger(n))throw new v("random(a, b) arguments must be integers");let o=Math.min(r,n),i=Math.max(r,n);return Math.floor(t()*(i-o+1))+o}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,eval(s,e){let t=ot("check_flags",s,e);for(let r=1;r<s.length;r++){let n=s[r];if(n.kind!=="flagdelta")throw new v("check_flags() flag args must be +flagName or -flagName");if(n.sign==="+"?!t.includes(n.name):t.includes(n.name))return!1}return!0}},set_flags:{minArgs:1,returnType:"flags",flagDeltaArgs:!0,eval(s,e){let t=[...ot("set_flags",s,e)];for(let r=1;r<s.length;r++){let n=s[r];if(n.kind!=="flagdelta")throw new v("set_flags() flag args must be +flagName or -flagName");if(n.sign==="+")t.includes(n.name)||t.push(n.name);else{let o=t.indexOf(n.name);o>=0&&t.splice(o,1)}}return t.sort()}},count_played:{minArgs:1,maxArgs:1,returnType:"number",eval(s,e){let t=_("count_played",s,e,0),r=U(e).countPlayed;if(!r)throw new v("count_played() called without a play log in context");return r(t)}},turns_since_played:{minArgs:1,maxArgs:1,returnType:"number",eval(s,e){let t=_("turns_since_played",s,e,0),r=U(e).turnsSincePlayed;if(!r)throw new v("turns_since_played() called without a play log in context");return r(t)}},count_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(s,e){let t=_("count_played_in",s,e,0),r=_("count_played_in",s,e,1),n=U(e).countPlayedIn;if(!n)throw new v("count_played_in() called without a play log in context");return n(t,r)}},turns_since_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(s,e){let t=_("turns_since_played_in",s,e,0),r=_("turns_since_played_in",s,e,1),n=U(e).turnsSincePlayedIn;if(!n)throw new v("turns_since_played_in() called without a play log in context");return n(t,r)}}}};function Xt(s){return s.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function h(s){let e=s.gameId?.trim();return e||(s.title?Xt(s.title):"")||s.id}function at(s){let e=[];for(let a of s.boxes){let d=h(a);for(let l of a.tagGroups)for(let c of l.tags){let p=h(c);e.push({id:c.id,gameId:p,qualified:`${d}/${p}`})}}let t=new Map;for(let a of e){let d=t.get(a.gameId)??[];d.includes(a.qualified)||d.push(a.qualified),t.set(a.gameId,d)}let r=new Map,n=new Map,o=new Map,i=new Map;for(let a of e){let d=t.get(a.gameId)??[a.qualified],l=d.length>1;r.set(a.id,l?a.qualified:a.gameId),n.has(a.qualified)||n.set(a.qualified,a.id),!l&&!n.has(a.gameId)&&n.set(a.gameId,a.id),l&&o.set(a.gameId,d)}for(let a of s.map?.group.tags??[]){let d=h(a);r.set(a.id,d),n.has(d)||n.set(d,a.id);for(let l of s.boxes)i.set(`${h(l)}/${d}`,d)}return{print:r,accept:n,repeated:o,zoneQualified:i}}function dt(s,e,t){return`"value.${s}.${t}": "${e}" is a zone of the project map, which belongs to no box; write "value.${e}.${t}"`}function lt(s,e,t){let r=t.map(o=>`"value.${o}.${e}"`),n=r.length<=1?r[0]??"":`${r.slice(0,-1).join(", ")} or ${r[r.length-1]}`;return`"value.${s}.${e}" names a tag in ${t.length} boxes; write ${n}`}var O="place",Yt=/^@(hand|world|story)\.([a-z][a-z0-9_-]*)$/,W=s=>s.startsWith("@"),ct=s=>{let e=Yt.exec(s);return e===null?void 0:{scope:e[1],name:e[2]}},Zt="storylets/bundle@1",er="storylets/bundle@0",Pe=[er,Zt];function K(s,e){return e.usesMap===!0&&s.map!==void 0?[...e.tagGroups,s.map.group]:e.tagGroups}function Ce(s){let e=s.boxes.flatMap(t=>t.tagGroups);return s.map!==void 0?[...e,s.map.group]:e}var J="storylets/save@2",Q="storylets/save@1",le="storylets/savefile@1";function X(s,e){let t=[],r=new Set([...Object.keys(s),...Object.keys(e)]);for(let n of[...r].sort()){let o=s[n],i=e[n];JSON.stringify(o)!==JSON.stringify(i)&&t.push({path:n,from:o,to:i})}return t}var pt=s=>s===void 0?"<unset>":JSON.stringify(s),ut=s=>s.pathPrefix??s.bag.pathPrefix;function Y(s,e={}){let t=e.sink??(p=>console.log(p)),r=e.label??"",n=p=>{t(`${r}${p.path}: ${pt(p.from)} -> ${pt(p.to)}`)},o=()=>{let p={};for(let f of s.mounts()){let u=ut(f);for(let[m,g]of Object.entries(f.bag.values))p[u+m]=g}return Object.assign(p,s.extra?.()??{}),structuredClone(p)},i=o(),a=[],d=[],l=(p,f)=>f.onAudit(u=>{let m=structuredClone({path:p+u.name,from:u.prev,to:u.next});n(m),a.push(m),i[m.path]=structuredClone(u.next)}),c=()=>{let p=s.mounts();if(!(d.length===p.length&&p.every((u,m)=>d[m].bag===u.bag))){for(let u of d)u.off();d=p.map(u=>({bag:u.bag,off:l(ut(u),u.bag)}))}};return c(),{snapshot:o,capture(){let p=o(),f=X(i,p);for(let m of f)n(m);let u=[...a,...f];return a=[],i=p,c(),u},dispose(){for(let p of d)p.off();d=[],a=[]}}}var V=class s{values={};decls=new Map;subscribers=new Set;auditors=new Set;norm;pathPrefix;constructor(e=[],t){this.norm=t?.normalise??(r=>r.toLowerCase()),this.pathPrefix=t?.pathPrefix??"",this.seed(e)}seed(e){for(let t of e){let r=this.norm(t.name);this.decls.set(r,t),this.values[r]=structuredClone(t.default??ht(t))}}get(e){return this.values[this.norm(e)]}normalise(e){return this.norm(e)}set(e,t,r){let n=this.norm(e);if(!r?.host&&this.decls.get(n)?.writable===!1)throw new Error(`'${e}' is read-only`);let o={name:n,prev:this.values[n],next:t,silent:r?.silent??!1,reason:r?.reason};this.values[n]=t;for(let i of this.auditors)i(o);if(!o.silent)for(let i of this.subscribers)i(o);return o}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}onAudit(e){return this.auditors.add(e),()=>this.auditors.delete(e)}rows(){return[...this.decls.entries()].map(([e,t])=>ft(t,this.get(e),void 0,e,this.pathPrefix))}declarations(){return[...this.decls.values()]}clone(){let e=new s([],{normalise:this.norm,pathPrefix:this.pathPrefix});return e.decls=new Map(this.decls),Object.assign(e.values,structuredClone(this.values)),e}reseed(e){for(let t of Object.keys(this.values))delete this.values[t];this.decls.clear(),this.seed(e)}save(){return structuredClone(this.values)}load(e){for(let[t,r]of Object.entries(e))this.values[this.norm(t)]=r}};function ft(s,e,t,r,n=""){let o=r??s.name.toLowerCase();return{name:o,path:n+o,type:s.type,value:e,default:s.default??ht(s),...s.values!==void 0?{values:s.values}:{},...s.stages!==void 0?{stages:s.stages}:{},writable:t??s.writable??!0}}var tr=s=>s.toLowerCase(),Be=1,ce=class{scopes=new Map;parked=new Map;rev=0;get revision(){return this.rev}defineOwned(e,t,r){let n=typeof r=="string"?{pathPrefix:r}:r??{},o=new V(t,{pathPrefix:n.pathPrefix??`${e}.`,...n.normalise?{normalise:n.normalise}:{}});return this.mountOwned(e,o,n.owner!==void 0?{owner:n.owner}:void 0)}mountOwned(e,t,r){this.assertFree(e,r?.owner),this.scopes.set(e,{kind:"owned",bag:t,...r?.owner!==void 0?{owner:r.owner}:{}}),this.rev++;let n=this.parked.get(e);return n&&(t.load(n),this.parked.delete(e)),this}remove(e,t){let r=this.scopes.get(e);if(!r)throw new Error(`unknown scope '@${e}'`);return t?.keep&&r.kind==="owned"&&this.parked.set(e,r.bag.save()),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&this.parked.delete(t);return this}ownedBag(e){let t=this.scopes.get(e);if(!t||t.kind!=="owned")throw new Error(`'@${e}' is not an owned scope`);return t.bag}reseedOwned(e,t){return this.ownedBag(e).reseed(t),this}defineForeign(e,t,r=[],n=!0){let o=typeof n=="boolean"?{writable:n}:n;this.assertFree(e,o.owner);let i=o.normalise??tr,a=new Map;for(let d of r)a.set(i(d.name),d);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:o.writable??!0,norm:i,...o.owner!==void 0?{owner:o.owner}:{}}),this.rev++,this}has(e){return this.scopes.has(e)}get(e,t){let r=this.scopes.get(e);if(r)return r.kind==="owned"?r.bag.get(t):r.resolver.get(r.norm(t))}set(e,t,r,n){let o=this.scopes.get(e);if(!o)throw new Error(`unknown scope '@${e}'`);if(o.kind==="owned"){try{o.bag.set(t,r,n?.host?{host:!0}:void 0)}catch{throw new Error(`'@${e}.${t}' is read-only`)}return}let i=o.norm(t);if(!o.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!n?.host&&!this.foreignWritable(o,i))throw new Error(`'@${e}.${t}' is read-only`);o.resolver.set(i,r)}foreignWritable(e,t){return e.resolver.set?e.decls.get(t)?.writable??e.scopeWritable:!1}listProperties(){let e=[];for(let[t,r]of this.scopes){let n=r.owner!==void 0?{owner:r.owner}:{};if(r.kind==="owned")for(let o of r.bag.rows())e.push({scope:t,...n,...o});else for(let[o,i]of r.decls)e.push({scope:t,...n,...ft(i,r.resolver.get(o),this.foreignWritable(r,o),o,`${t}.`)})}return e}toEvalContext(e,t){let r=this.view(t?.aliases),n={};for(let[i,a]of r)n[i]=a.kind==="owned"?a.bag.values:a.resolver;let o=this.qualityLadders(r);return o.size===0?{scopes:n,host:e}:{scopes:n,host:e,qualities:(i,a)=>{let d=r.get(i);return d?o.get(i)?.get(rr(d)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[r,n]of Object.entries(e??{})){let o=this.scopes.get(n);if(!o)throw new Error(`alias '@${r}' names '${n}', which is not registered`);t.set(r,o)}return t}qualityLadders(e){let t=new Map;for(let[r,n]of e)for(let[o,i]of gt(n)){if(i.type!=="quality"||i.stages===void 0)continue;let a=t.get(r);a||(a=new Map,t.set(r,a)),a.set(o,i.stages)}return t}toSchema(e){let t=new Map;for(let[r,n]of this.view(e?.aliases)){let o=gt(n);if(o.length===0)continue;let i=new Map;for(let[a,d]of o)i.set(a,{type:d.type,enumValues:d.values,...d.stages!==void 0?{stages:d.stages}:{}});t.set(r,i)}return{properties:t}}save(){let e={};for(let[t,r]of this.scopes)r.kind==="owned"&&(e[t]=r.bag.save());for(let[t,r]of this.parked)e[t]=structuredClone(r);return e}load(e,t){t?.keepParked||this.parked.clear();for(let[r,n]of Object.entries(e)){let o=this.scopes.get(r);o?.kind==="owned"?o.bag.load(n):o||this.parked.set(r,structuredClone(n))}}saveFragment(){return{version:Be,scopes:this.save()}}loadFragment(e){if(e.version!==Be)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${Be})`);this.load(e.scopes)}assertFree(e,t){let r=this.scopes.get(e);if(!r)return;let n=r.owner!==void 0?` by ${r.owner}`:"",o=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${n}${o}`)}};function gt(s){return s.kind==="foreign"?[...s.decls.entries()]:s.bag.declarations().map(e=>[s.bag.normalise(e.name),e])}function rr(s){return s.kind==="foreign"?s.norm:e=>s.bag.normalise(e)}function ht(s){if(s.default!==void 0)return s.default;switch(s.type){case"boolean":return!1;case"number":return 0;case"string":return"";case"enum":return s.values?.[0]??"";case"flags":return[];case"quality":return s.stages?.[0]??"";default:return!1}}var mt=(s,e,t)=>`${s}${e}${t}`,Te=(s,e)=>s.shared??e,Et=s=>s.sharedCopies??s.copies??1,G="Storylet Engine",yt=s=>s,Ne=s=>s.replace(/%/g,"%25").replace(/\//g,"%2F"),$e=s=>s.replace(/%2F/g,"/").replace(/%25/g,"%"),Oe=(s,e)=>`storylets/${s}/${Ne(e)}`,Ae=s=>`storylets/flow/${Ne(s)}/`,De=(s,e,t)=>e==="story"?`${Ae(s)}story`:`${Ae(s)}${e}/${Ne(t)}`,te=()=>({story:{},box:{},deck:{},hand:{},value:{}});function nr(s,e){let t=te(),r=new Map,n={},o=i=>{let a=$e(i);if(!e.has(a))return;let d=r.get(a);return d||(d=te(),r.set(a,d)),d};for(let[i,a]of Object.entries(s)){let d;if(i==="story")t.story=a;else if(d=/^storylets\/(box|deck|hand|value)\/([^/]+)$/.exec(i))t[d[1]][$e(d[2])]=a;else if(d=/^storylets\/flow\/([^/]+)\/story$/.exec(i)){let l=o(d[1]);l&&(l.story=a)}else if(d=/^storylets\/flow\/([^/]+)\/(box|deck|hand|value)\/([^/]+)$/.exec(i)){let l=o(d[1]);l&&(l[d[2]][$e(d[3])]=a)}else i.startsWith("storylets/")||(n[i]=a)}return{shared:t,flows:r,rest:n}}function wt(s,e,t){Object.keys(s.story).length>0&&(t[e("story")]=s.story);for(let r of["box","deck","hand","value"])for(let[n,o]of Object.entries(s[r]))Object.keys(o).length>0&&(t[e(r,n)]=o)}var Z=(s,e)=>new V(s,{normalise:t=>t,pathPrefix:e});function bt(s){return typeof s=="boolean"?s:typeof s=="number"?s!==0:typeof s=="string"?s!=="":s.length>0}var sr={story:!0,box:!1,deck:!1,hand:!1,value:!1},kt=(s,e)=>e.shared??sr[s],vt=(s,e)=>e.filter(t=>kt(s,t)),Pt=(s,e)=>e.filter(t=>!kt(s,t)),re=["box","deck","hand","value"],pe=()=>({gameId:new Map,id:new Map,repeated:new Map,zoneQualified:new Map}),or=()=>({box:pe(),deck:pe(),hand:pe(),value:pe()}),Re=(s,e)=>{let t=h(e);s.gameId.set(e.id,t),s.id.has(t)||s.id.set(t,e.id)},ir=(s,e)=>{let t=at(e);for(let[r,n]of t.print)s.gameId.set(r,n);for(let[r,n]of t.accept)s.id.set(r,n);for(let[r,n]of t.repeated)s.repeated.set(r,n);for(let[r,n]of t.zoneQualified)s.zoneQualified.set(r,n)},He=(s,e)=>e.template!==void 0?s.templatesById.get(e.template)?.properties??s.bundle.boxes.flatMap(t=>t.handTemplates).find(t=>t.id===e.template)?.properties??[]:e.properties??[],I=(s,e,t)=>`${e}.${s.owners[e].gameId.get(t)??t}`,ar=(s,e,t)=>{let r=s.owners[e].repeated.get(t);if(r!==void 0)return{ambiguous:r};let n=s.owners[e].zoneQualified.get(t);if(n!==void 0)return{zone:n};let o=s.owners[e].id.get(t);if(o!==void 0)return{id:o,legacy:!1};if(s.owners[e].gameId.has(t))return{id:t,legacy:!0}},Ct=(s,e,t,r)=>{let n=ar(s,e,t);if(n===void 0)throw new Error(`no ${e} store "${t}"`);if("ambiguous"in n)throw new Error(lt(t,r,n.ambiguous));if("zone"in n)throw new Error(dt(t,n.zone,r));return n},Bt=(s,e,t,r)=>`"${e}.${t}.${r}" names the ${e} by its internal id; write "${I(s,e,t)}.${r}". The internal-id form is refused after the next release.`,$t=(s,e)=>{let t=s.bundle,r=(n,o)=>`${I(s,n,o)}.`;return{story:Z(e("story",t.story.properties),"story."),box:new Map(t.boxes.map(n=>[n.id,Z(e("box",n.properties),r("box",n.id))])),deck:new Map(t.boxes.flatMap(n=>n.decks.map(o=>[o.id,Z(e("deck",o.properties),r("deck",o.id))]))),hand:new Map(t.boxes.flatMap(n=>n.hands.map(o=>[o.id,Z(e("hand",He(s,o)),r("hand",o.id))]))),value:new Map(Ce(t).flatMap(n=>n.tags.map(o=>[o.id,Z(e("value",o.properties??[]),r("value",o.id))])))}},dr=s=>({story:s.story.values,box:Object.fromEntries([...s.box].map(([e,t])=>[e,t.values])),deck:Object.fromEntries([...s.deck].map(([e,t])=>[e,t.values])),hand:Object.fromEntries([...s.hand].map(([e,t])=>[e,t.values])),value:Object.fromEntries([...s.value].map(([e,t])=>[e,t.values]))}),lr=(s,e)=>{s.story.load(e?.story??{});for(let t of["box","deck","hand","value"])for(let[r,n]of Object.entries(e?.[t]??{}))s[t].get(r)?.load(n)},Me=()=>({evicted:[],droppedCooldowns:[],droppedSpent:[],droppedProperties:[],defaultedProperties:[],retypedProperties:[]}),Ve="",ee=(s,e)=>[...s].map(t=>({item:t,k:e(t)})).sort((t,r)=>t.k<r.k?-1:t.k>r.k?1:0).map(t=>t.item),Ie=s=>`${s.flow??""}${Ve}${s.path}`;function cr(s,e){switch(s.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":return typeof e=="string";case"enum":return typeof e=="string"&&(s.values===void 0||s.values.includes(e));case"quality":return typeof e=="string"&&(s.stages===void 0||s.stages.includes(e));case"flags":return Array.isArray(e)&&(s.values===void 0||e.every(t=>s.values.includes(t)));default:return!0}}function xt(s,e,t,r,n){let o=l=>({...r!==void 0?{flow:r}:{},path:t(l)}),i=new Map((s??[]).map(l=>[l.name,l])),a=e??{},d={};for(let[l,c]of Object.entries(a)){let p=i.get(l);if(p===void 0){n.droppedProperties.push(o(l));continue}if(!cr(p,c)){n.retypedProperties.push(o(l));continue}d[l]=c}for(let l of s??[])l.name in a||n.defaultedProperties.push(o(l.name));return d}function St(s,e,t,r,n){let o={story:xt(e.story,t?.story,i=>`story.${i}`,r,n),box:{},deck:{},hand:{},value:{}};for(let i of["box","deck","hand","value"]){let a=t?.[i]??{},d=[...new Set([...e[i].keys(),...Object.keys(a)])].sort();for(let l of d){let c=I(s,i,l);o[i][l]=xt(e[i].get(l),a[l],p=>`${c}.${p}`,r,n)}}return o}function Le(s,e,t,r){let n=e.version!==s.version||e.hash!==s.hash,o=ee(r.evicted,p=>[p.flow,p.hand,p.card,p.reason].join(Ve)),i=ee(r.droppedCooldowns,p=>`${p.flow}${Ve}${p.card}`),a=[...r.droppedSpent].sort(),d=ee(r.droppedProperties,Ie),l=ee(r.defaultedProperties,Ie),c=ee(r.retypedProperties,Ie);return{exact:!n&&o.length===0&&i.length===0&&a.length===0&&d.length===0&&l.length===0&&c.length===0,project:s.project,version:{saved:e.version,bundle:s.version},hash:{saved:e.hash,bundle:s.hash},flows:t,evicted:o,droppedCooldowns:i,droppedSpent:a,droppedProperties:d,defaultedProperties:l,retypedProperties:c}}var pr=s=>{let e=s.schema;if(typeof e!="string"||!Pe.includes(e))throw new Error(`unsupported bundle schema: ${String(e)} (this runtime reads ${Pe.join(" and ")})`);let t=[],r=s.map?.group,n=r!==void 0?h(r):void 0;r!==void 0&&n===O&&t.push(`the project map's tag group is called "${O}", which is reserved for a box's own hands`);let o=new Map;for(let i of s.boxes)for(let a of i.tagGroups)for(let d of a.tags){let l=h(d);o.has(l)||o.set(l,{box:h(i),group:h(a)})}for(let i of r?.tags??[]){let a=h(i),d=o.get(a);d!==void 0&&t.push(`the project map's zone "${a}" has the name of tag "${a}" in box "${d.box}", group "${d.group}", so "value.${a}.<name>" would name two things`)}for(let i of s.boxes){let a=h(i);if(i.usesMap===!0){if(r===void 0){t.push(`box "${a}" uses the project map, but the bundle has no map`);continue}i.tagGroups.find(c=>h(c)===n)!==void 0&&t.push(`box "${a}" uses the project map and declares its own tag group "${n}", the map's name`);continue}if(r===void 0)continue;let d=l=>{t.push(`box "${a}" is not on the project map, but ${l} names the map's tag group "${n}"`)};for(let l of i.decks)for(let c of l.cards)c.tags?.[r.id]!==void 0&&d(`card "${h(c)}"`);for(let l of i.handTemplates)(l.bindings?.[r.id]!==void 0||l.chooses?.includes(r.id)===!0)&&d(`hand template "${h(l)}"`);for(let l of i.hands)(l.chosen?.[r.id]!==void 0||l.rule?.bindings?.[r.id]!==void 0)&&d(`hand "${h(l)}"`)}if(t.length>0)throw new Error(`bundle refused: ${t.join("; ")}`)},ue=class s{internals;seed;onReplacedFlow;flowsById=new Map;engineTraceHandlers=new Set;hostWorld;creationOptions;sharedMounts=[];constructor(e,t={}){pr(e),this.creationOptions=t,this.seed=t.seed??0,this.onReplacedFlow=t.onReplacedFlow,t.world!==void 0&&(this.hostWorld=t.world);let r={bundle:e,...t.log?{logCap:typeof t.log=="object"?t.log.cap??1e3:1e3}:{},cardsById:new Map,cardsByGameId:new Map,boxesByGameId:new Map,boxesById:new Map,handsById:new Map,handsByGameId:new Map,owners:or(),templatesById:new Map,groupsById:new Map,requiredGroups:new Set,nodeCache:new WeakMap,ladders:{world:new Map,story:new Map,box:new Map,deck:new Map,value:new Map,hand:new Map},hasQualities:!1,hasShared:!1,flowDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},sharedDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},shared:void 0,registry:t.registry??new ce,ownsRegistry:t.registry===void 0,selfWorld:!1,registryView:()=>i(),worldResolver:void 0,worldReadOnly:new Set,emitEngine:(d,l,c)=>{this.internals.logCap!==void 0&&(this.engineLog.push({...l,flow:d,seq:this.engineSeq++,...c!==void 0?{turn:c}:{}}),this.engineLog.length>this.internals.logCap&&this.engineLog.splice(0,this.engineLog.length-this.internals.logCap));for(let p of this.engineTraceHandlers)p(d,l)},engineTracing:()=>this.engineTraceHandlers.size>0};this.internals=r;let n=-1,o={scopes:{},qualities:void 0},i=()=>{let d=r.registry;if(d.revision!==n){let l=d.toEvalContext(),c={};for(let[p,f]of Object.entries(l.scopes))p.includes("/")||(c[p]=f);o={scopes:c,qualities:l.qualities},n=d.revision}return o};ir(r.owners.value,e);for(let d of e.boxes){r.boxesById.set(d.id,d),r.boxesByGameId.set(h(d),d),Re(r.owners.box,d);for(let l of d.tagGroups)r.groupsById.set(l.id,{group:l,box:d}),l.required===!0&&r.requiredGroups.add(l.id);for(let l of d.decks){Re(r.owners.deck,l),l.shared===!0&&(r.hasShared=!0);for(let c of l.cards){let p={card:c,deck:l,box:d};r.cardsById.set(c.id,p),r.cardsByGameId.set(h(c),p),c.shared===!0&&(r.hasShared=!0)}}for(let l of d.handTemplates)r.templatesById.set(l.id,l);for(let l of d.hands)r.handsById.set(l.id,{hand:l,box:d}),r.handsByGameId.set(h(l),{hand:l,box:d}),Re(r.owners.hand,l)}e.map!==void 0&&(r.groupsById.set(e.map.group.id,{group:e.map.group}),e.map.group.required===!0&&r.requiredGroups.add(e.map.group.id)),this.initLadders();let a=d=>({story:d("story",e.story.properties),box:new Map(e.boxes.map(l=>[l.id,d("box",l.properties)])),deck:new Map(e.boxes.flatMap(l=>l.decks.map(c=>[c.id,d("deck",c.properties)]))),hand:new Map(e.boxes.flatMap(l=>l.hands.map(c=>[c.id,d("hand",He(r,c))]))),value:new Map(Ce(e).flatMap(l=>l.tags.map(c=>[c.id,d("value",c.properties??[])])))});r.flowDecls=a(Pt),r.sharedDecls=a(vt),this.initShared(this.hostWorld)}initShared(e){let t=this.internals,r=t.registry,n=t.bundle.world.properties;t.shared=$t(t,vt),t.worldReadOnly=new Set(t.bundle.world.properties.filter(a=>a.writable===!1).map(a=>a.name));let o=[],i=(a,d)=>{d(),o.push(a),this.sharedMounts.push({key:a,mount:d})};try{let a=t.shared.story;i("story",()=>{r.mountOwned("story",a,{owner:G})});for(let d of re)for(let[l,c]of t.shared[d])c.declarations().length!==0&&i(Oe(d,l),()=>{r.mountOwned(Oe(d,l),c,{owner:G})});if(e!==void 0)i("world",()=>{r.defineForeign("world",e,n,{normalise:yt,owner:G})});else if(t.ownsRegistry&&!r.has("world")){r.defineOwned("world",n,{normalise:yt,pathPrefix:"world.",owner:G});let d=r.ownedBag("world");o.push("world"),this.sharedMounts.push({key:"world",mount:()=>{r.mountOwned("world",d,{owner:G})}}),t.selfWorld=!0}}catch(a){for(let d of o)r.remove(d,{keep:!0});throw a}t.worldResolver={get:a=>r.get("world",a),set:(a,d)=>{r.set("world",a,d)}},e!==void 0?t.worldSet=e.set!==void 0?(a,d)=>{r.set("world",a,d,{host:!0})}:void 0:t.worldSet=(a,d,l)=>{r.set("world",a,d,l===!0?{host:!0}:void 0)}}reseedShared(){let{shared:e,sharedDecls:t,registry:r}=this.internals;e.story.reseed(t.story);for(let n of re)for(let[o,i]of e[n])i.reseed(t[n].get(o)??[]);this.internals.selfWorld&&r.reseedOwned("world",this.internals.bundle.world.properties)}initLadders(){let e=this.internals,t=o=>{let i=new Map;for(let a of o??[])a.type==="quality"&&a.stages!==void 0&&i.set(a.name,a.stages);return i},r=e.bundle;e.ladders.world=t(r.world.properties),e.ladders.story=t(r.story.properties);for(let o of r.boxes){e.ladders.box.set(o.id,t(o.properties));for(let i of o.decks)e.ladders.deck.set(i.id,t(i.properties));for(let i of o.tagGroups)for(let a of i.tags)e.ladders.value.set(a.id,t(a.properties));for(let i of o.hands)e.ladders.hand.set(i.id,t(He(e,i)))}for(let o of r.map?.group.tags??[])e.ladders.value.set(o.id,t(o.properties));let n=o=>[...o.values()].some(i=>i.size>0);e.hasQualities=e.ladders.world.size>0||e.ladders.story.size>0||n(e.ladders.box)||n(e.ladders.deck)||n(e.ladders.value)||n(e.ladders.hand)}openFlow(e,t={}){return this.open(e,t,!1)}open(e,t,r){this.assertExternalScopes();let n=t.restore!==void 0?this.sharedClaimsExcept(e):void 0,o=this.flowsById.get(e);if(o){let a=o.heldCardIds().length;a>0&&this.onReplacedFlow?.(e,a),o.markClosed()}r||this.internals.registry.discardParked(Ae(e));let i=new ne(this,this.internals,e,t.seed??this.seed);if(this.flowsById.set(e,i),t.restore!==void 0){let a=Me(),d=this.planFlowRestore(e,structuredClone(t.restore),n,a);i.restore(d);let l=this.internals.bundle.content;t.onRestoreReport?.(Le(l,l,[e],a))}return i}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}closeFlow(e){let t=this.flowsById.get(e);t&&(this.flowsById.delete(e),t.markClosed())}dropFlow(e,t){this.flowsById.get(e)===t&&this.flowsById.delete(e)}reset(){this.dropRun(!1),this.reseedShared(),this.internals.registry.discardParked("storylets/")}dropRun(e){this.engineLog=[];for(let[t,r]of this.flowsById)r.releaseBags(e!==!1&&e.has(t)),r.markClosed();this.flowsById.clear(),this.spent.clear()}spent=new Set;isTaken(e){return this.spent.has(e)}markTaken(e){this.spent.add(e)}engineLog=[];engineSeq=0;log(){return this.engineLog}clearLog(){this.engineLog=[]}sharedClaims(){let e=new Map;for(let t of this.flowsById.values())for(let r of t.heldCardIds())e.set(r,(e.get(r)??0)+1);return e}sharedClaimsExcept(e){let t=new Map;for(let[r,n]of this.flowsById)if(r!==e)for(let o of n.heldCardIds())t.set(o,(t.get(o)??0)+1);return t}getProperty(e){let t=this.resolveShared(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):t.bag.get(t.name);if(r===void 0)throw new Error(`no property at "${e}"`);return r}setProperty(e,t){let r=this.resolveShared(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new Error("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}r.bag.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolveShared(e){let t=e.split("."),r=()=>{throw new Error(`"${e}" is per-flow state - read it on a Flow, not the Engine`)};if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story"){let n=t[1];if(this.internals.shared.story.get(n)!==void 0)return{kind:"bag",bag:this.internals.shared.story,name:n};throw this.internals.flowDecls.story.some(o=>o.name===n)&&r(),new Error(`no property at "${e}"`)}if(t.length===3&&(t[0]==="box"||t[0]==="deck"||t[0]==="hand"||t[0]==="value")){let n=t[0],[,o,i]=t,a=Ct(this.internals,n,o,i);a.legacy&&this.diagnose(Bt(this.internals,n,o,i));let d=a.id,l=this.internals.shared[n].get(d);if(l!==void 0&&l.get(i)!==void 0)return{kind:"bag",bag:l,name:i};throw this.internals.flowDecls[n].get(d)?.some(c=>c.name===i)&&r(),l===void 0&&!this.internals.flowDecls[n].has(d)?new Error(`no ${n} store "${o}"`):new Error(`no property at "${e}"`)}throw new Error(`bad property path "${e}"`)}diagnose(e){this.internals.emitEngine("",{type:"diagnostic",where:"property address",message:e})}assertExternalScopes(){for(let e of this.internals.bundle.externalScopes??[])if(!this.internals.registry.has(e))throw new Error(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}listProperties(){let e=[];for(let r of this.internals.bundle.world.properties){let n=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:n??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,n)=>{for(let o of n.rows())e.push(o)};t("story",this.internals.shared.story);for(let r of re)for(let[n,o]of this.internals.shared[r])t(I(this.internals,r,n),o);return e}listBags(){let e=[{prefix:"story",bag:this.internals.shared.story}];for(let t of["box","deck","hand","value"])for(let[r,n]of this.internals.shared[t])e.push({prefix:I(this.internals,t,r),bag:n});return e}subscribeTrace(e){return this.engineTraceHandlers.add(e),()=>this.engineTraceHandlers.delete(e)}hotSwap(e,t={}){if(e.content.project!==this.internals.bundle.content.project)throw new Error(`save is for project "${this.internals.bundle.content.project}", bundle is "${e.content.project}"`);let r={...this.creationOptions,...t},n=this.saveGame(),o=this.internals.registry;if(this.internals.ownsRegistry){let c=new s(e,{...r,registry:void 0});return{engine:c,report:c.loadGame(n)}}let i={};for(let[c,p]of Object.entries(o.save()))(c==="story"||c.startsWith("storylets/"))&&(i[c]=p);let a=new Set([...this.sharedMounts.map(c=>c.key),...[...this.flowsById.values()].flatMap(c=>c.registeredKeys())]),d=Object.fromEntries(Object.entries(i).filter(([c])=>!a.has(c)));for(let{key:c}of this.sharedMounts)o.has(c)&&o.remove(c);for(let c of this.flowsById.values())c.releaseBags(!1);let l;try{l=new s(e,{...r,registry:o});let c=l.loadGame({...n,registry:i}),p=Object.fromEntries(Object.entries(d).filter(([f])=>!o.has(f)));return Object.keys(p).length>0&&o.load(p,{keepParked:!0}),this.dropRun(!1),{engine:l,report:c}}catch(c){l?.dropRun(!1);for(let{key:p}of l?.sharedMounts??[])o.has(p)&&o.remove(p);o.discardParked("storylets/");for(let{mount:p}of this.sharedMounts)p();for(let p of this.flowsById.values())p.mountBags();throw this.reseedShared(),o.load(i,{keepParked:!0}),c}}saveGame(){return structuredClone({schema:J,content:this.internals.bundle.content,...this.internals.ownsRegistry?{registry:this.registrySection()}:{},shared:{spent:[...this.spent].sort()},flows:Object.fromEntries([...this.flowsById].map(([e,t])=>[e,t.snapshot(!1)]))})}registrySection(){let e=this.internals.registry.save(),t={},r=n=>{Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=e[n])};for(let{key:n}of this.sharedMounts)r(n);for(let n of this.flowsById.values())for(let o of n.registeredKeys())r(o);for(let n of Object.keys(e))r(n);return t}saveFlow(e){let t=this.flowsById.get(e);if(!t)throw new Error(`unknown flow "${e}"`);return structuredClone(t.snapshot(!0))}previewLoad(e){return this.assertSameProject(e),this.planLoad(e).report}previewFlowRestore(e,t){let r=Me();this.planFlowRestore(e,t,this.sharedClaimsExcept(e),r);let n=this.internals.bundle.content;return Le(n,n,[e],r)}loadGame(e){this.assertSameProject(e),this.assertExternalScopes();let t=this.planLoad(structuredClone(e)),r=this.internals.registry;t.sections!==void 0?(this.reset(),this.internals.ownsRegistry?r.load(t.sections):r.load(t.sections,{keepParked:!0})):this.dropRun(new Set(t.flows.map(([n])=>n)));for(let n of t.spent)this.spent.add(n);for(let[n,o]of t.flows)this.open(n,{},!0).restore(o);return t.report}assertSameProject(e){if(e.content.project!==this.internals.bundle.content.project)throw new Error(`save is for project "${e.content.project}", bundle is "${this.internals.bundle.content.project}"`)}planLoad(e){let t=e.schema;if(t!==J&&t!==Q)throw new Error(`unsupported save schema: ${String(t)}`);let r=Me(),n=new Set(Object.keys(e.flows??{})),o;e.schema===Q?o={shared:e.shared?.props??te(),flows:new Map(Object.entries(e.flows??{}).map(([c,p])=>[c,p.props??te()])),rest:{}}:e.registry!==void 0&&(o=nr(e.registry,n));let i=o!==void 0?St(this.internals,this.internals.sharedDecls,o.shared,void 0,r):void 0,a=[];for(let c of e.shared?.spent??[])this.internals.cardsById.has(c)?a.push(c):r.droppedSpent.push(c);let d=[],l=o!==void 0?{...o.rest}:void 0;l!==void 0&&i!==void 0&&wt(i,(c,p)=>c==="story"?"story":Oe(c,p),l);for(let[c,p]of Object.entries(e.flows??{})){let f=o!==void 0?{...p,props:o.flows.get(c)??te()}:{...p},u=this.planFlowRestore(c,f,void 0,r);l!==void 0&&u.props!==void 0&&(wt(u.props,(m,g)=>De(c,m,g),l),delete u.props),d.push([c,u])}return{report:Le(this.internals.bundle.content,e.content,d.map(([c])=>c),r),...l!==void 0?{sections:l}:{},spent:a,flows:d}}planFlowRestore(e,t,r,n){let o=this.internals,i=t.props!==void 0?St(o,o.flowDecls,t.props,e,n):void 0,a={};for(let[p,f]of Object.entries(t.cooldowns??{}))o.cardsById.has(p)?a[p]=f:n.droppedCooldowns.push({flow:e,card:p});let d=p=>{let f=o.cardsById.get(p);return f?h(f.card):p},l={},c=new Map;for(let[p,f]of Object.entries(t.board??{})){let u=o.handsById.get(p);if(u===void 0){for(let y of f)n.evicted.push({flow:e,hand:p,card:d(y),reason:"hand-vanished"});continue}let m=h(u.hand),g=[];for(let y of f){let b=o.cardsById.get(y);if(b===void 0){n.evicted.push({flow:e,hand:m,card:y,reason:"vanished"});continue}if(r!==void 0&&Te(b.card,b.deck.shared??!1)){if((r.get(y)??0)+(c.get(y)??0)>=Et(b.card)){n.evicted.push({flow:e,hand:m,card:h(b.card),reason:"claimed-elsewhere"});continue}c.set(y,(c.get(y)??0)+1)}g.push(y)}l[p]=g}return{...i!==void 0?{props:i}:{},turns:t.turns??{},prng:t.prng,cooldowns:a,board:l,playLog:t.playLog??[]}}},ne=class{id;engine;internals;closed=!1;prng;turnCounts=new Map;cooldowns={};boardContents=new Map;playLog=[];playCount=new Map;lastPlayOf=new Map;tagPlayCount=new Map;lastPlayInTag=new Map;stores;registered=[];bagKeys=[];traceHandlers=new Set;logEntries=[];logSeq=0;storyReader;boxReaders=new Map;deckReaders=new Map;constructor(e,t,r,n){this.engine=e,this.internals=t,this.id=r,this.prng=D(n),this.stores=$t(t,Pt);let o=(a,d)=>{d.declarations().length!==0&&this.bagKeys.push([a,d])};o(De(r,"story"),this.stores.story);for(let a of re)for(let[d,l]of this.stores[a])o(De(r,a,d),l);this.mountBags();for(let a of t.bundle.boxes){this.turnCounts.set(a.id,0);for(let d of a.hands)this.boardContents.set(d.id,[])}let i=(a,d)=>({get:l=>a?.get(l)??d?.get(l)});this.storyReader=i(this.stores.story,t.shared.story);for(let a of t.bundle.boxes){this.boxReaders.set(a.id,i(this.stores.box.get(a.id),t.shared.box.get(a.id)));for(let d of a.decks)this.deckReaders.set(d.id,i(this.stores.deck.get(d.id),t.shared.deck.get(d.id)))}}get isClosed(){return this.closed}close(){this.closed||(this.engine.dropFlow(this.id,this),this.markClosed())}markClosed(){this.releaseBags(!1),this.closed=!0}releaseBags(e){for(let t of this.registered)this.internals.registry.remove(t,{keep:e});this.registered.length=0}registeredKeys(){return[...this.registered]}mountBags(){for(let[e,t]of this.bagKeys)this.internals.registry.mountOwned(e,t,{owner:G}),this.registered.push(e)}assertOpen(){if(this.closed)throw new Error(`flow "${this.id}" is closed`)}turn(e){this.assertOpen();let t=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!t)throw new Error(`unknown box "${e}"`);return this.turnCounts.get(t.id)??0}subscribeTrace(e){return this.traceHandlers.add(e),()=>this.traceHandlers.delete(e)}get tracing(){return this.traceHandlers.size>0||this.internals.logCap!==void 0||this.internals.engineTracing()}emit(e,t){this.internals.logCap!==void 0&&(this.logEntries.push({...e,seq:this.logSeq++,...t!==void 0?{turn:t}:{}}),this.logEntries.length>this.internals.logCap&&this.logEntries.splice(0,this.logEntries.length-this.internals.logCap));for(let r of this.traceHandlers)r(e);this.internals.emitEngine(this.id,e,t)}log(){return this.logEntries}clearLog(){this.logEntries=[]}node(e){let t=this.internals.nodeCache.get(e);return t||(t=T(e.ast),this.internals.nodeCache.set(e,t)),t}groupInBox(e,t){let r=K(this.internals.bundle,e);return r.find(n=>h(n)===t)??r.find(n=>n.id===t)}indexPlay(e){this.playCount.set(e.card,(this.playCount.get(e.card)??0)+1),this.lastPlayOf.set(e.card,e);let t=this.internals.cardsByGameId.get(e.card);if(t)for(let[r,n]of Object.entries(t.card.tags??{}))for(let o of n){let i=mt(t.box.id,r,o);this.tagPlayCount.set(i,(this.tagPlayCount.get(i)??0)+1),this.lastPlayInTag.set(i,e)}}rebuildPlayIndex(){this.playCount.clear(),this.lastPlayOf.clear(),this.tagPlayCount.clear(),this.lastPlayInTag.clear();for(let e of this.playLog)this.indexPlay(e)}hostsByBox=new Map;host(e){let t=this.hostsByBox.get(e.id);if(t!==void 0)return t;let r=this.makeHost(e);return this.hostsByBox.set(e.id,r),r}makeHost(e){let t=(n,o)=>{let i=this.groupInBox(e,n),a=i?.tags.find(d=>d.gameId===o);return i&&a?mt(e.id,i.id,a.id):void 0},r=n=>{let o=this.internals.cardsByGameId.get(n.card);return o?(this.turnCounts.get(o.box.id)??0)-n.turn:de};return{nextRandom:()=>this.prng.next(),countPlayed:n=>this.playCount.get(n)??0,turnsSincePlayed:n=>{let o=this.lastPlayOf.get(n);return o?r(o):de},countPlayedIn:(n,o)=>{let i=t(n,o);return i===void 0?0:this.tagPlayCount.get(i)??0},turnsSincePlayedIn:(n,o)=>{let i=t(n,o),a=i===void 0?void 0:this.lastPlayInTag.get(i);return a?r(a):de}}}evalCtx(e,t,r){let n=this.internals.registryView();return{scopes:{...n.scopes,world:this.internals.worldResolver,story:this.storyReader,box:this.boxReaders.get(e.id)??{},deck:t?this.deckReaders.get(t.id)??{}:{},hand:r.bag},host:this.host(e),...this.internals.hasQualities||n.qualities!==void 0?{qualities:(o,i)=>o==="world"?this.internals.ladders.world.get(i)??n.qualities?.(o,i):o==="story"?this.internals.ladders.story.get(i):o==="box"?this.internals.ladders.box.get(e.id)?.get(i):o==="deck"&&t?this.internals.ladders.deck.get(t.id)?.get(i):o==="hand"?this.handLadder(r,i):n.qualities?.(o,i)}:{}}}handLadder(e,t){let r=e.sources.get(t);if(r)return r.kind==="value"?this.internals.ladders.value.get(r.id)?.get(t):r.kind==="hand"?this.internals.ladders.hand.get(r.id)?.get(t):void 0}eval(e,t){return ie(this.node(e),t,ke)}passes(e,t,r){if(!e)return!0;try{return bt(this.eval(e,t))}catch(n){return this.tracing&&this.emit({type:"diagnostic",where:r??"condition",message:n instanceof Error?n.message:String(n)}),!1}}tagByGameId(e,t){return e.tags.find(r=>r.gameId===t)}askForHand(e,t){let r=new Map,n={},o;if(e.template!==void 0){let i=this.internals.templatesById.get(e.template);if(!i)throw new Error(`hand "${h(e)}": unknown template "${e.template}"`);for(let[a,d]of Object.entries(i.bindings??{}))r.set(a,d);for(let[a,d]of Object.entries(e.chosen??{})){if(W(d)){this.fillHoleFromProperty(e,a,d,r,n);continue}r.set(a,d);let l=this.internals.groupsById.get(a),c=l?.group.tags.find(p=>p.id===d);l&&c&&(n[h(l.group)]=h(c))}o=i.condition}else{for(let[i,a]of Object.entries(e.rule?.bindings??{})){if(W(a)){this.fillHoleFromProperty(e,i,a,r,n);continue}r.set(i,a);let d=this.internals.groupsById.get(i),l=d?.group.tags.find(c=>c.id===a);d&&l&&(n[h(d.group)]=h(l))}o=e.rule?.condition}return r.set(O,e.id),this.bindStateGroups(t,r,n),{box:t,hand:e,...o!==void 0?{condition:o}:{},boundTags:r,askNames:n}}askForPeek(e,t){let r=new Map,n={};for(let[o,i]of Object.entries(t)){if(o===O){let l=this.internals.handsByGameId.get(i)??this.internals.handsById.get(i);if(!l)throw new Error(`peek: unknown hand "${i}" in home criteria`);r.set(O,l.hand.id);continue}let a=this.groupInBox(e,o);if(!a)throw new Error(`peek: unknown tag group "${o}" in box "${h(e)}"`);let d=this.tagByGameId(a,i)??a.tags.find(l=>l.id===i);if(!d)throw new Error(`peek: unknown tag "${i}" in group "${h(a)}"`);r.set(a.id,d.id),n[h(a)]=h(d)}return this.bindStateGroups(e,r,n),{box:e,boundTags:r,askNames:n}}fillHoleFromProperty(e,t,r,n,o){let i=this.internals.groupsById.get(t),a=i?h(i.group):t,d=`hand ${h(e)}, tag group ${a}`,l=ct(r);if(!l){this.emit({type:"diagnostic",where:d,message:`"${r}" is not a @hand, @world or @story property reference`});return}if(!i){this.emit({type:"diagnostic",where:d,message:`"${r}" fills a tag group that is not in this box`});return}let c;if(l.scope==="hand")c=this.valuesOf("hand",e.id)[l.name];else try{c=this.getProperty(`${l.scope}.${l.name}`)}catch{c=void 0}if(c===void 0){this.emit({type:"diagnostic",where:d,message:`"${r}" names a property that is not declared`});return}let p=typeof c=="string"?c:String(c),f=i.group.tags.find(u=>h(u)===p);if(!f){this.emit({type:"diagnostic",where:d,message:`${r} is "${p}", which is not one of the tags of "${a}"`});return}n.set(t,f.id),o[a]=h(f)}bindStateGroups(e,t,r){for(let n of K(this.internals.bundle,e)){if(n.boundBy===void 0||t.has(n.id))continue;let o=/^@(world|story)\.([a-z][a-z0-9_-]*)$/.exec(n.boundBy);if(!o){this.emit({type:"diagnostic",where:`tag group ${h(n)}`,message:`boundBy "${n.boundBy}" is not a @world or @story property reference`});continue}let i;try{i=this.getProperty(`${o[1]}.${o[2]}`)}catch{this.emit({type:"diagnostic",where:`tag group ${h(n)}`,message:`boundBy "${n.boundBy}" names a property that is not declared`});continue}let a=typeof i=="string"?i:String(i),d=n.tags.find(l=>h(l)===a);if(!d){this.emit({type:"diagnostic",where:`tag group ${h(n)}`,message:`${n.boundBy} is "${a}", which is not one of its tags`});continue}t.set(n.id,d.id),r[h(n)]=h(d)}}valuesOf(e,t){return{...this.internals.shared[e].get(t)?.values??{},...this.stores[e].get(t)?.values??{}}}buildHandEnv(e){let t={},r=new Map;for(let[n,o]of e.boundTags)if(n!==O)for(let[i,a]of Object.entries(this.valuesOf("value",o)))t[i]=a,r.set(i,{kind:"value",id:o});if(e.hand)for(let[n,o]of Object.entries(this.valuesOf("hand",e.hand.id)))t[n]=o,r.set(n,{kind:"hand",id:e.hand.id});for(let[n,o]of Object.entries(e.askNames))t[n]=o,r.set(n,{kind:"criteria"});return{bag:t,sources:r,boundTags:e.boundTags}}claims(){let e=new Map;for(let t of this.boardContents.values())for(let r of t)e.set(r,(e.get(r)??0)+1);return e}heldCardIds(){return[...this.boardContents.values()].flat()}copiesOf(e){return e.copies??1}claimVerdict(e,t,r,n){let o=e.id;return(r.get(o)??0)>=this.copiesOf(e)?"claimed":t&&(n.get(o)??0)>=Et(e)?"claimed-elsewhere":null}tagsMatch(e,t){let r=e.tags?.[O];if(r!==void 0&&r.length>0){let n=t.get(O);if(n===void 0||!r.includes(n))return!1}for(let[n,o]of t){if(n===O)continue;let i=e.tags?.[n];if(i===void 0){if(this.internals.requiredGroups.has(n))return!1;continue}if(!i.includes(o))return!1}return!0}runAsk(e,t,r){let{box:n}=e,o=this.buildHandEnv(e),i=(p,f)=>{r?.push({id:h(p),verdict:f})};if(!this.passes(e.condition,this.evalCtx(n,void 0,o),`hand ${e.hand?h(e.hand):""} condition`))return{ordered:[],handEnv:o};let a=new Map;for(let p of n.decks)a.set(p.id,this.passes(p.condition,this.evalCtx(n,p,o),`deck ${p.gameId} gate`));let d=this.turnCounts.get(n.id)??0,l=[];for(let p of n.decks){let f=this.evalCtx(n,p,o),u=p.shared??!1;for(let m of p.cards){let g=Te(m,u);if(!a.get(p.id)){i(m,"deck-gate");continue}if(g&&this.engine.isTaken(m.id)){i(m,"taken");continue}if((this.cooldowns[m.id]??0)>d){i(m,"cooldown");continue}if(!this.tagsMatch(m,o.boundTags)){i(m,"tags");continue}if(m.condition&&!this.passes(m.condition,f,this.tracing?`card ${m.gameId} condition`:void 0)){i(m,"condition");continue}let y=t(m,g);if(y){i(m,y);continue}let b;if(typeof m.priority=="number")b=m.priority;else try{let x=this.eval(m.priority,f);if(typeof x!="number"){i(m,"priority");continue}b=x}catch(x){this.tracing&&this.emit({type:"diagnostic",where:`card ${m.gameId} priority`,message:x instanceof Error?x.message:String(x)}),i(m,"priority");continue}let w=0;if(n.ranking.specificity&&m.condition){let x=this.node(m.condition);w=nt(x,k=>{try{return bt(ie(k,f,ke))}catch{return!1}})}l.push({entry:{card:m,deck:p,box:n},priority:b,spec:w})}}l.sort((p,f)=>f.priority-p.priority||f.spec-p.spec);let c=0;for(;c<l.length;){let p=c+1;for(;p<l.length&&l[p].priority===l[c].priority&&l[p].spec===l[c].spec;)p++;if(p-c>1){let f=l.slice(c,p);H(f,this.prng);for(let u=0;u<f.length;u++)l[c+u]=f[u]}c=p}for(let p of l)r?.push({id:h(p.entry.card),verdict:"dealt",priority:p.priority,specificity:p.spec});return{ordered:l.map(p=>p.entry),handEnv:o}}capTrace(e,t){for(let r of e)r.verdict==="dealt"&&!t.has(r.id)&&(r.verdict="capped")}view(e){let{card:t}=e;return{id:t.id,gameId:h(t),...t.title!==void 0?{title:t.title}:{},...t.purpose!==void 0?{purpose:t.purpose}:{},...t.fields!==void 0?{fields:t.fields}:{}}}handCapacity(e){if(e.slots!==void 0)return e.slots;let t=e.template!==void 0?this.internals.templatesById.get(e.template)?.slots:e.rule?.slots;return t===void 0||t==="unbounded"?1/0:t}resolveHand(e){let t=this.internals.handsByGameId.get(e)??this.internals.handsById.get(e);if(!t)throw new Error(`unknown hand "${e}"`);return t}peek(e,t={},r){this.assertOpen();let n=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!n)throw new Error(`unknown box "${e}"`);let o=this.askForPeek(n,t),i=this.claims(),a=this.internals.hasShared?this.engine.sharedClaims():new Map,d=this.tracing?[]:void 0,{ordered:l}=this.runAsk(o,(p,f)=>this.claimVerdict(p,f,i,a),d),c=r===void 0?l:l.slice(0,Math.max(r,0));return d&&(this.capTrace(d,new Set(c.map(p=>h(p.card)))),this.emit({type:"peek",box:h(n),criteria:t,cards:d},this.turnCounts.get(n.id)??0)),{box:h(n),cards:c.map(p=>this.view(p))}}deal(e){this.assertOpen();let{hand:t}=this.resolveHand(e);return this.dealMany([e])[h(t)]??[]}dealMany(e){this.assertOpen();let t=(e??[...this.internals.handsById.keys()].sort()).map(o=>this.resolveHand(o));H(t,this.prng);for(let{hand:o,box:i}of t){let a=this.askForHand(o,i),d=this.buildHandEnv(a),l=this.passes(a.condition,this.evalCtx(i,void 0,d)),c=new Map;for(let g of i.decks)c.set(g.id,this.passes(g.condition,this.evalCtx(i,g,d)));let p=this.turnCounts.get(i.id)??0,f=[],u=(g,y)=>{let b=this.internals.cardsById.get(g);return f.push({card:b?h(b.card):g,reason:y}),!1},m=(this.boardContents.get(o.id)??[]).filter(g=>{if(!l)return u(g,"hand-condition");let y=this.internals.cardsById.get(g);return y?c.get(y.deck.id)?(this.cooldowns[g]??0)>p?u(g,"cooldown"):this.tagsMatch(y.card,d.boundTags)?this.passes(y.card.condition,this.evalCtx(i,y.deck,d),`card ${y.card.gameId} condition`)?!0:u(g,"condition"):u(g,"tags"):u(g,"deck-gate"):u(g,"vanished")});if(this.boardContents.set(o.id,m),this.tracing)for(let g of f)this.emit({type:"evict",hand:h(o),card:g.card,reason:g.reason},p)}let r=this.claims(),n=this.internals.hasShared?this.engine.sharedClaims():new Map;for(let{hand:o,box:i}of t){let a=this.boardContents.get(o.id)??[],d=this.handCapacity(o)-a.length;if(d<=0)continue;let l=this.askForHand(o,i),c=new Set(a),p=this.tracing?[]:void 0,{ordered:f}=this.runAsk(l,(g,y)=>c.has(g.id)?"claimed":this.claimVerdict(g,y,r,n),p),u=f.slice(0,d),m=u.map(g=>g.card.id);this.boardContents.set(o.id,[...a,...m]);for(let g of m)r.set(g,(r.get(g)??0)+1),n.set(g,(n.get(g)??0)+1);p&&(this.capTrace(p,new Set(u.map(g=>h(g.card)))),this.emit({type:"deal",hand:h(o),cards:p},this.turnCounts.get(i.id)??0))}return Object.fromEntries(t.map(({hand:o})=>[h(o),(this.boardContents.get(o.id)??[]).map(i=>this.view(this.internals.cardsById.get(i)))]))}board(e){this.assertOpen();let t;if(e!==void 0){let r=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!r)throw new Error(`unknown box "${e}"`);t=r.id}return Object.fromEntries([...this.boardContents.entries()].filter(([r])=>t===void 0||this.internals.handsById.get(r).box.id===t).map(([r,n])=>[h(this.internals.handsById.get(r).hand),n.map(o=>this.view(this.internals.cardsById.get(o)))]))}resolveDealt(e,t){let r=this.internals.cardsById.get(e)??this.internals.cardsByGameId.get(e);if(!r)throw new Error(`unknown card "${e}"`);let{hand:n,box:o}=this.resolveHand(t);if(!(this.boardContents.get(n.id)??[]).includes(r.card.id))throw new Error(`card "${h(r.card)}" is not dealt to hand "${h(n)}"`);return{entry:r,ask:this.askForHand(n,o)}}outcomes(e,t){this.assertOpen();let{entry:r,ask:n}=this.resolveDealt(e,t),o=this.evalCtx(r.box,r.deck,this.buildHandEnv(n));return r.card.outcomes.map(i=>({id:i.id,gameId:h(i),...i.title!==void 0?{title:i.title}:{},...i.purpose!==void 0?{purpose:i.purpose}:{},...i.fields!==void 0?{fields:i.fields}:{},available:this.passes(i.condition,o)}))}play(e,t,r,n={}){this.assertOpen();let{entry:o,ask:i}=this.resolveDealt(e,r),a=t==="";if(a&&o.card.outcomes.length>0)throw new Error(`card "${h(o.card)}" has outcomes (${o.card.outcomes.map(b=>h(b)).join(", ")}); name the one played`);let d=a?void 0:o.card.outcomes.find(b=>h(b)===t);if(!a&&!d)throw new Error(`card "${h(o.card)}" has no outcome "${t}"`);let l=this.buildHandEnv(i),c=this.evalCtx(o.box,o.deck,l);if(d&&!this.passes(d.condition,c))throw new Error(`outcome "${t}" on "${h(o.card)}" is gated shut`);let p=o.box.turn!==void 0?0:this.internals.bundle.settings.playAdvancesTurns,f=(this.turnCounts.get(o.box.id)??0)+(n.advanceTurns??p),u=[];for(let[b,w]of Object.entries(d?.changes??{}))u.push({target:b,value:this.eval(w,c)});for(let{target:b,value:w}of u){let{path:x,prev:k}=this.applyWrite(b,w,o,l);this.tracing&&this.emit({type:"write",target:b,path:x,value:w,...k!==void 0?{prev:k}:{}},f)}let m=d?h(d):"",g={card:h(o.card),outcome:m,turn:f};this.playLog.push(g),this.indexPlay(g),o.card.redraw==="never"?Te(o.card,o.deck.shared??!1)?this.engine.markTaken(o.card.id):this.cooldowns[o.card.id]=Number.MAX_SAFE_INTEGER:typeof o.card.redraw=="number"&&(this.cooldowns[o.card.id]=f+o.card.redraw);let y=i.hand.id;this.boardContents.set(y,(this.boardContents.get(y)??[]).filter(b=>b!==o.card.id)),this.turnCounts.set(o.box.id,f),this.tracing&&this.emit({type:"play",card:h(o.card),outcome:m,turn:f},f)}address(e,t){return I(this.internals,e,t)}landIn(e,t,r,n,o){let i=e==="story"?this.stores.story:t!==void 0?this.stores[e].get(t):void 0,a=e==="story"?this.internals.shared.story:t!==void 0?this.internals.shared[e].get(t):void 0,d=i!==void 0&&i.get(r)!==void 0?i:a!==void 0&&a.get(r)!==void 0?a:void 0;if(d===void 0)throw new Error(`no property at "${o}"`);let l=d.set(r,n);return{path:o,...l.prev!==void 0?{prev:l.prev}:{}}}applyWrite(e,t,r,n){let o=/^@([a-z]+)\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(e);if(!o)throw new Error(`bad change target "${e}"`);let[,i,a]=o;switch(i){case"world":{let d=this.internals.worldSet;if(!d)throw new Error(`@world.${a} cannot be written: the host bound @world read-only`);if(this.internals.worldReadOnly.has(a))throw new Error(`'@world.${a}' is read-only (writable: false)`);let l=this.internals.worldResolver.get(a);return d(a,t),{path:`world.${a}`,...l!==void 0?{prev:l}:{}}}case"story":return this.landIn("story",void 0,a,t,`story.${a}`);case"box":return this.landIn("box",r.box.id,a,t,`${this.address("box",r.box.id)}.${a}`);case"deck":return this.landIn("deck",r.deck.id,a,t,`${this.address("deck",r.deck.id)}.${a}`);case"hand":{let d=n.sources.get(a);if(!d)throw new Error(`@hand.${a} is not composed in this ask`);if(d.kind==="criteria")throw new Error(`@hand.${a} is a chosen tag / criteria name and cannot be written`);return this.landIn(d.kind,d.id,a,t,`${this.address(d.kind,d.id)}.${a}`)}default:{if(this.internals.registry.has(i)){let d=this.internals.registry.get(i,a);return this.internals.registry.set(i,a,t),{path:`${i}.${a}`,...d!==void 0?{prev:d}:{}}}throw this.internals.bundle.externalScopes?.includes(i)?new Error(`@${i}.${a} cannot be written: no engine on this registry registered @${i}`):new Error(`bad change target scope "@${i}"`)}}}advanceTurns(e,t=1){this.assertOpen();let r=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!r)throw new Error(`unknown box "${e}"`);let n=(this.turnCounts.get(r.id)??0)+t;this.turnCounts.set(r.id,n),this.tracing&&this.emit({type:"turns",box:h(r),turn:n},n)}listBoxes(){return this.assertOpen(),this.internals.bundle.boxes.map(e=>({id:e.id,gameId:h(e),...e.title!==void 0?{title:e.title}:{},turn:this.turnCounts.get(e.id)??0}))}listBags(){this.assertOpen();let e=[{prefix:"story",bag:this.stores.story}];for(let t of["box","deck","hand","value"])for(let[r,n]of this.stores[t])e.push({prefix:I(this.internals,t,r),bag:n});return e}listProperties(){this.assertOpen();let e=[];for(let r of this.internals.bundle.world.properties){let n=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:n??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,n,o)=>{for(let i of[n,o])if(i!==void 0)for(let a of i.rows())e.push(a)};t("story",this.internals.shared.story,this.stores.story);for(let r of re){let n=new Set([...this.internals.shared[r].keys(),...this.stores[r].keys()]);for(let o of n)t(I(this.internals,r,o),this.internals.shared[r].get(o),this.stores[r].get(o))}return e}getProperty(e){this.assertOpen();let t=this.resolvePath(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):t.own?.get(t.name)??t.shared?.get(t.name);if(r===void 0)throw new Error(`no property at "${e}"`);return r}setProperty(e,t){this.assertOpen();let r=this.resolvePath(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new Error("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}let n=r.own!==void 0&&r.own.get(r.name)!==void 0?r.own:r.shared!==void 0&&r.shared.get(r.name)!==void 0?r.shared:void 0;if(n===void 0)throw new Error(`no property at "${e}"`);n.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolvePath(e){let t=e.split(".");if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story")return{kind:"bag",own:this.stores.story,shared:this.internals.shared.story,name:t[1]};if(t.length===3&&(t[0]==="box"||t[0]==="deck"||t[0]==="hand"||t[0]==="value")){let r=t[0],[,n,o]=t,i=Ct(this.internals,r,n,o);i.legacy&&this.tracing&&this.emit({type:"diagnostic",where:"property address",message:Bt(this.internals,r,n,o)});let a=this.stores[r].get(i.id),d=this.internals.shared[r].get(i.id);if(a===void 0&&d===void 0)throw new Error(`no ${r} store "${n}"`);return{kind:"bag",...a!==void 0?{own:a}:{},...d!==void 0?{shared:d}:{},name:o}}throw new Error(`bad property path "${e}"`)}snapshot(e){return{...e?{props:dr(this.stores)}:{},turns:Object.fromEntries(this.turnCounts),prng:this.prng.state(),cooldowns:this.cooldowns,board:Object.fromEntries(this.boardContents),playLog:this.playLog}}restore(e){e.props!==void 0&&lr(this.stores,e.props),this.turnCounts=new Map(this.internals.bundle.boxes.map(t=>[t.id,0]));for(let[t,r]of Object.entries(e.turns??{}))this.turnCounts.has(t)&&this.turnCounts.set(t,r);this.prng=D(e.prng),this.cooldowns=e.cooldowns??{},this.playLog=e.playLog??[],this.rebuildPlayIndex(),this.boardContents=new Map(Object.entries(e.board??{}).filter(([t])=>this.internals.handsById.has(t)).map(([t,r])=>[t,r.filter(n=>this.internals.cardsById.has(n))]));for(let t of this.internals.handsById.keys())this.boardContents.has(t)||this.boardContents.set(t,[])}};var ge=s=>s.map(e=>({name:e.name,type:e.type,default:e.default,...e.values!==void 0?{values:e.values}:{},...e.durable===!0?{durable:!0}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}})),Ot=s=>s.decks.reduce((e,t)=>e+t.cards.filter(r=>(r.durable??t.durable)===!0).length,0),ur=(s,e)=>s.template!==void 0?e.handTemplates.find(t=>t.id===s.template)?.properties??[]:s.properties??[],gr=(s,e,t)=>{let r=e.template!==void 0?e.chosen:e.rule?.bindings,n=[];for(let[o,i]of Object.entries(r??{})){if(!W(i))continue;let a=K(s,t).find(d=>d.id===o);a!==void 0&&n.push({group:h(a),from:i})}return n},fr=(s,e)=>{if(s.slots!==void 0)return s.slots;let t=s.template!==void 0?e.handTemplates.find(r=>r.id===s.template)?.slots:s.rule?.slots;return t===void 0?"unbounded":t};function fe(s){let e=[],t=[],r=[{scope:"world",owner:"",properties:ge(s.world.properties)},{scope:"story",owner:"",properties:ge(s.story.properties)}],n={boxes:0,decks:0,cards:0,hands:0,templates:0,tagGroups:0};for(let i of s.boxes){let a=h(i),d=i.decks.reduce((c,p)=>c+p.cards.length,0);e.push({gameId:a,...i.title!==void 0?{title:i.title}:{},...i.usesMap===!0?{usesMap:!0}:{},ranking:{specificity:i.ranking.specificity},...i.turn!==void 0?{turn:{seconds:i.turn.seconds}}:{},...Ot(i)>0?{durableCards:Ot(i)}:{},tagGroups:i.tagGroups.map(c=>({gameId:h(c),tags:c.tags.map(p=>h(p))})),counts:{decks:i.decks.length,cards:d,hands:i.hands.length,templates:i.handTemplates.length,tagGroups:i.tagGroups.length}}),n.boxes+=1,n.decks+=i.decks.length,n.cards+=d,n.hands+=i.hands.length,n.templates+=i.handTemplates.length,n.tagGroups+=i.tagGroups.length;for(let c of i.hands){let p=c.template!==void 0?i.handTemplates.find(u=>u.id===c.template):void 0,f=gr(s,c,i);t.push({gameId:h(c),...c.title!==void 0?{title:c.title}:{},box:a,slots:fr(c,i),...p!==void 0?{template:h(p)}:{},...f.length>0?{movable:f}:{}})}let l=(c,p,f,u)=>{f.length!==0&&r.push({scope:c,owner:p,box:a,...u!==void 0?{group:u}:{},properties:ge(f)})};l("box",a,i.properties);for(let c of i.decks)l("deck",h(c),c.properties);for(let c of i.hands)l("hand",h(c),ur(c,i));for(let c of i.tagGroups)for(let p of c.tags)l("tag",h(p),p.properties??[],h(c))}let o=s.map;if(o!==void 0){let i=h(o.group);for(let a of o.group.tags){let d=a.properties??[];d.length>0&&r.push({scope:"tag",owner:h(a),group:i,properties:ge(d)})}n.tagGroups+=1}return{identity:{schema:s.schema,project:s.content.project,version:s.content.version,hash:s.content.hash,metadata:s.metadata},totals:n,boxes:e,hands:t,properties:r,...o!==void 0?{map:{group:h(o.group),tags:o.group.tags.map(i=>h(i)),boxes:s.boxes.filter(i=>i.usesMap===!0).map(i=>h(i)),zones:o.geometry?.zones.length??0,backgrounds:o.geometry?.backgrounds?.length??0,sites:Object.fromEntries(Object.entries(o.geometry?.sites??{}).map(([i,a])=>[i,a.length]))}}:{}}}function Rt(s,e){let t={};for(let{bag:r}of[...s.listBags(),...e.listBags()])for(let n of r.rows())n.value!==void 0&&(t[n.path]=n.value);return Object.assign(t,Mt(s.saveGame().flows[e.id])),t}function Mt(s){let e={};if(s===void 0)return e;for(let[t,r]of Object.entries(s.turns))e[`turn:${t}`]=r;for(let[t,r]of Object.entries(s.cooldowns))e[`cooldown:${t}`]=r;for(let[t,r]of Object.entries(s.board))e[`board:${t}`]=[...r];return e}function It(s,e,t={}){let r=e.id,n=()=>s.getFlow(r);return Y({mounts:()=>[...s.listBags(),...n()?.listBags()??[]].map(({bag:o})=>({bag:o})),extra:()=>Mt(s.saveGame().flows[r])},t)}function he(s,e){return JSON.stringify(je(s,e),null,2)}function je(s,e){return{schema:le,engine:s.saveGame(),...e!==void 0?{world:e}:{}}}function Fe(s,e){if(!e||typeof e!="object"||e.schema!==le||e.engine?.schema!==J&&e.engine?.schema!==Q)throw new Error(`not a storylets save (expected schema "${le}")`);return s.loadGame(e.engine),e.world}function me(s,e){let t;try{t=JSON.parse(e)}catch{throw new Error("not valid JSON")}return Fe(s,t)}var Lt="sl-inspector-style",hr=`
|
|
1
|
+
"use strict";var StoryletEngine=(()=>{var Pe=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var Ut=(n,e)=>{for(var t in e)Pe(n,t,{get:e[t],enumerable:!0})},Kt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zt(e))!Wt.call(n,s)&&s!==t&&Pe(n,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return n};var Jt=n=>Kt(Pe({},"__esModule",{value:!0}),n);var Mr={};Ut(Mr,{Engine:()=>he,Flow:()=>ne,StoryletError:()=>v,applyLiveBundle:()=>_t,boardFrame:()=>Ue,createBundleInspector:()=>jt,createKernelStateLogger:()=>ee,createLiveLink:()=>Ft,createPropertyInspector:()=>Ht,createStateLogger:()=>Dt,createWorldContainer:()=>Gt,describeBundle:()=>ye,deserializeState:()=>be,diffState:()=>Z,ensureInspectorStyle:()=>se,formatLogEntry:()=>qe,formatPropertySummary:()=>ze,formatScopeLabel:()=>We,loadState:()=>Ge,makePrng:()=>D,saveState:()=>_e,serializeState:()=>we,shuffleInPlace:()=>j,snapshotState:()=>It});function V(n){switch(n[0]){case"b":return{kind:"bool",value:n[1]};case"n":return{kind:"number",value:n[1]};case"s":return{kind:"string",value:n[1]};case"sv":return{kind:"scopedvar",scope:n[1],name:n[2]};case"u":return{kind:"unary",op:n[1],operand:V(n[2])};case"bin":return{kind:"binary",op:n[1],left:V(n[2]),right:V(n[3])};case"call":{let e=n.slice(2).map(V);return{kind:"call",name:n[1],args:e}}case"fd":return{kind:"flagdelta",sign:n[1],name:n[2]}}}var S=class extends Error{constructor(e){super(e),this.name="EvalError"}};function ae(n,e,t){let r=new Map(t.scopes.map(o=>[o.token,o.missing??"false"])),s=o=>{switch(o.kind){case"bool":return o.value;case"number":return o.value;case"string":return o.value;case"scopedvar":{let i=e.scopes[o.scope];if(i===void 0)return!1;let a=typeof i.get=="function"?i.get(o.name):i[o.name];if(a===void 0){if(r.get(o.scope)==="throw")throw new S(`@${o.scope}.${o.name} is not declared on the current ${o.scope}.`);return!1}return a}case"call":{if(o.name==="advance"&&!t.functions[o.name]){let a=o.args[0];if(o.args.length!==1||a===void 0)throw new S(`advance() takes exactly 1 argument, got ${o.args.length}`);let d=Be(a,e);if(d===void 0)throw new S("advance() needs a quality reference (@scope.name of a quality property)");let l=A(s(a),d,"advance");return d[Math.min(l+1,d.length-1)]}let i=t.functions[o.name];if(!i)throw new S(`unknown function '${o.name}'`);return i.eval(o.args,{evaluate:s,ctx:e})}case"flagdelta":throw new S("flagdelta node is only valid as an argument to a flag-delta function");case"unary":{if(o.op==="not"){let a=s(o.operand);if(typeof a!="boolean")throw new S(`'not' requires a boolean operand, got ${typeof a}`);return!a}let i=s(o.operand);if(typeof i!="number")throw new S(`unary '-' requires a numeric operand, got ${typeof i}`);return-i}case"binary":{if(o.op==="and"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'and' requires boolean operands, left is ${typeof p}`);if(!p)return!1;let g=s(o.right);if(typeof g!="boolean")throw new S(`'and' requires boolean operands, right is ${typeof g}`);return g}if(o.op==="or"){let p=s(o.left);if(typeof p!="boolean")throw new S(`'or' requires boolean operands, left is ${typeof p}`);if(p)return!0;let g=s(o.right);if(typeof g!="boolean")throw new S(`'or' requires boolean operands, right is ${typeof g}`);return g}let i=s(o.left),a=s(o.right),d=Be(o.left,e),l=Be(o.right,e),c=d??l;if(c!==void 0){if(d&&l&&!Qt(d,l)&&(o.op===">"||o.op===">="||o.op==="<"||o.op==="<="))throw new S(`'${o.op}' compares two different qualities, whose stage orders are unrelated`);switch(o.op){case">":return A(i,c,">")>A(a,c,">");case">=":return A(i,c,">=")>=A(a,c,">=");case"<":return A(i,c,"<")<A(a,c,"<");case"<=":return A(i,c,"<=")<=A(a,c,"<=");case"+":case"-":case"*":case"/":throw new S(`'${o.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);default:break}}switch(o.op){case"==":return nt(i,a);case"!=":return!nt(i,a);case">":return H(i,a,">"),i>a;case">=":return H(i,a,">="),i>=a;case"<":return H(i,a,"<"),i<a;case"<=":return H(i,a,"<="),i<=a;case"+":if(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string")return i+a;throw new S(`'+' requires two numbers or two strings, got ${typeof i} and ${typeof a}`);case"-":return H(i,a,"-"),i-a;case"*":return H(i,a,"*"),i*a;case"/":if(H(i,a,"/"),a===0)throw new S("division by zero");return i/a}}}};return s(n)}function nt(n,e){if(Array.isArray(n)||Array.isArray(e)){if(!Array.isArray(n)||!Array.isArray(e)||n.length!==e.length)return!1;let t=[...n].sort(),r=[...e].sort();for(let s=0;s<t.length;s++)if(t[s]!==r[s])return!1;return!0}return n===e}function H(n,e,t){if(typeof n!="number"||typeof e!="number")throw new S(`'${t}' requires numeric operands, got ${typeof n} and ${typeof e}`)}function Be(n,e){if(!(n.kind!=="scopedvar"||e.qualities===void 0))return e.qualities(n.scope,n.name)}function A(n,e,t){if(typeof n!="string")throw new S(`'${t}' on a quality compares stages, got ${typeof n}`);let r=e.indexOf(n);if(r<0)throw new S(`"${n}" is not a stage of this quality (stages: ${e.join(", ")})`);return r}var Qt=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);function st(n){if(Number.isNaN(n)||!Number.isFinite(n))return 0;let e=Math.trunc(n)%4294967296;return e<0?e+4294967296:e}function D(n){let e=st(n);return{next(){e=e+1831565813>>>0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296},state(){return e}}}function j(n,e){for(let t=n.length-1;t>0;t--){let r=Math.floor(e.next()*(t+1));[n[t],n[r]]=[n[r],n[t]]}}var Yt={name:"check_flags",count:n=>Math.max(1,n.args.length-1)},Xt=[Yt];function ot(n,e,t){let r=t?.countingCalls??Xt;return de(n,t?.want??!0,e,r)}function de(n,e,t,r){if(n.kind==="binary"&&(n.op==="and"||n.op==="or")){let s=de(n.left,e,t,r),o=de(n.right,e,t,r);return n.op==="and"===e?s>0&&o>0?s+o:0:Math.max(s,o)}if(n.kind==="unary"&&n.op==="not")return de(n.operand,!e,t,r);if(n.kind==="call"){let s=r.find(o=>o.name===n.name);if(s){let o=s.count(n),i=t(n);return e?i?o:0:i?0:1}}return t(n)===e?1:0}var it=[{token:"patter",engine:"Patterplay",means:"Patter's shared globals"},{token:"story",engine:"Storylet Engine",means:"the Storylet Engine's shared @story properties"}];var le=9999,J=n=>n.ctx.host??{},z=(n,e,t,r)=>{let s=t.evaluate(e[r]);if(typeof s!="string"||s==="")throw new S(`${n}() argument ${r+1} must be a non-empty string`);return s},at=(n,e,t)=>{if(e.length===0)throw new S(`${n}() requires at least one argument (the flags property)`);let r=t.evaluate(e[0]);if(Array.isArray(r))return r;if(r===!1)return[];throw new S(`${n}() first argument must be a flags property`)},dt=["story","world","box","deck","hand"],Zt=it.map(n=>n.token).filter(n=>!dt.includes(n)),Ce={scopes:[...dt.map(n=>({token:n,missing:"throw"})),...Zt.map(n=>({token:n,missing:"throw"}))],defaultScope:"story",functions:{random:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){if(n.length!==2)throw new S("random(a, b) requires exactly 2 arguments");let t=J(e).nextRandom;if(!t)throw new S("random() called without a PRNG in context");let r=e.evaluate(n[0]),s=e.evaluate(n[1]);if(typeof r!="number"||typeof s!="number")throw new S("random(a, b) arguments must be numbers");if(!Number.isInteger(r)||!Number.isInteger(s))throw new S("random(a, b) arguments must be integers");let o=Math.min(r,s),i=Math.max(r,s);return Math.floor(t()*(i-o+1))+o}},check_flags:{minArgs:1,returnType:"boolean",flagDeltaArgs:!0,eval(n,e){let t=at("check_flags",n,e);for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("check_flags() flag args must be +flagName or -flagName");if(s.sign==="+"?!t.includes(s.name):t.includes(s.name))return!1}return!0}},set_flags:{minArgs:1,returnType:"flags",flagDeltaArgs:!0,eval(n,e){let t=[...at("set_flags",n,e)];for(let r=1;r<n.length;r++){let s=n[r];if(s.kind!=="flagdelta")throw new S("set_flags() flag args must be +flagName or -flagName");if(s.sign==="+")t.includes(s.name)||t.push(s.name);else{let o=t.indexOf(s.name);o>=0&&t.splice(o,1)}}return t.sort()}},count_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("count_played",n,e,0),r=J(e).countPlayed;if(!r)throw new S("count_played() called without a play log in context");return r(t)}},turns_since_played:{minArgs:1,maxArgs:1,returnType:"number",eval(n,e){let t=z("turns_since_played",n,e,0),r=J(e).turnsSincePlayed;if(!r)throw new S("turns_since_played() called without a play log in context");return r(t)}},count_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("count_played_in",n,e,0),r=z("count_played_in",n,e,1),s=J(e).countPlayedIn;if(!s)throw new S("count_played_in() called without a play log in context");return s(t,r)}},turns_since_played_in:{minArgs:2,maxArgs:2,returnType:"number",eval(n,e){let t=z("turns_since_played_in",n,e,0),r=z("turns_since_played_in",n,e,1),s=J(e).turnsSincePlayedIn;if(!s)throw new S("turns_since_played_in() called without a play log in context");return s(t,r)}}}};function er(n){return n.toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function f(n){let e=n.gameId?.trim();return e||(n.title?er(n.title):"")||n.id}function lt(n){let e=[];for(let a of n.boxes){let d=f(a);for(let l of a.tagGroups)for(let c of l.tags){let p=f(c);e.push({id:c.id,gameId:p,qualified:`${d}/${p}`})}}let t=new Map;for(let a of e){let d=t.get(a.gameId)??[];d.includes(a.qualified)||d.push(a.qualified),t.set(a.gameId,d)}let r=new Map,s=new Map,o=new Map,i=new Map;for(let a of e){let d=t.get(a.gameId)??[a.qualified],l=d.length>1;r.set(a.id,l?a.qualified:a.gameId),s.has(a.qualified)||s.set(a.qualified,a.id),!l&&!s.has(a.gameId)&&s.set(a.gameId,a.id),l&&o.set(a.gameId,d)}for(let a of n.map?.group.tags??[]){let d=f(a);r.set(a.id,d),s.has(d)||s.set(d,a.id);for(let l of n.boxes)i.set(`${f(l)}/${d}`,d)}return{print:r,accept:s,repeated:o,zoneQualified:i}}function ct(n,e,t){return`"value.${n}.${t}": "${e}" is a zone of the project map, which belongs to no box; write "value.${e}.${t}"`}function pt(n,e,t){let r=t.map(o=>`"value.${o}.${e}"`),s=r.length<=1?r[0]??"":`${r.slice(0,-1).join(", ")} or ${r[r.length-1]}`;return`"value.${n}.${e}" names a tag in ${t.length} boxes; write ${s}`}var M="place",tr=/^@(hand|world|story)\.([a-z][a-z0-9_-]*)$/,ce=n=>n.startsWith("@"),ut=n=>{let e=tr.exec(n);return e===null?void 0:{scope:e[1],name:e[2]}},rr="storylets/bundle@1",nr="storylets/bundle@0",$e=[nr,rr];function Q(n,e){return e.usesMap===!0&&n.map!==void 0?[...e.tagGroups,n.map.group]:e.tagGroups}function gt(n){let e=n.boxes.flatMap(t=>t.tagGroups);return n.map!==void 0?[...e,n.map.group]:e}var Y="storylets/save@2",X="storylets/save@1",pe="storylets/savefile@1";function Z(n,e){let t=[],r=new Set([...Object.keys(n),...Object.keys(e)]);for(let s of[...r].sort()){let o=n[s],i=e[s];JSON.stringify(o)!==JSON.stringify(i)&&t.push({path:s,from:o,to:i})}return t}var ft=n=>n===void 0?"<unset>":JSON.stringify(n),ht=n=>n.pathPrefix??n.bag.pathPrefix;function ee(n,e={}){let t=e.sink??(p=>console.log(p)),r=e.label??"",s=p=>{t(`${r}${p.path}: ${ft(p.from)} -> ${ft(p.to)}`)},o=()=>{let p={};for(let g of n.mounts()){let u=ht(g);for(let[m,h]of Object.entries(g.bag.values))p[u+m]=h}return Object.assign(p,n.extra?.()??{}),structuredClone(p)},i=o(),a=[],d=[],l=(p,g)=>g.onAudit(u=>{let m=structuredClone({path:p+u.name,from:u.prev,to:u.next});s(m),a.push(m),i[m.path]=structuredClone(u.next)}),c=()=>{let p=n.mounts();if(!(d.length===p.length&&p.every((u,m)=>d[m].bag===u.bag))){for(let u of d)u.off();d=p.map(u=>({bag:u.bag,off:l(ht(u),u.bag)}))}};return c(),{snapshot:o,capture(){let p=o(),g=Z(i,p);for(let m of g)s(m);let u=[...a,...g];return a=[],i=p,c(),u},dispose(){for(let p of d)p.off();d=[],a=[]}}}var F=class n{values={};decls=new Map;subscribers=new Set;auditors=new Set;norm;pathPrefix;constructor(e=[],t){this.norm=t?.normalise??(r=>r.toLowerCase()),this.pathPrefix=t?.pathPrefix??"",this.seed(e)}seed(e){for(let t of e){let r=this.norm(t.name);this.decls.set(r,t),this.values[r]=structuredClone(t.default??wt(t))}}get(e){return this.values[this.norm(e)]}normalise(e){return this.norm(e)}set(e,t,r){let s=this.norm(e);if(!r?.host&&this.decls.get(s)?.writable===!1)throw new Error(`'${e}' is read-only`);let o={name:s,prev:this.values[s],next:t,silent:r?.silent??!1,reason:r?.reason};this.values[s]=t;for(let i of this.auditors)i(o);if(!o.silent)for(let i of this.subscribers)i(o);return o}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}onAudit(e){return this.auditors.add(e),()=>this.auditors.delete(e)}rows(){return[...this.decls.entries()].map(([e,t])=>yt(t,this.get(e),void 0,e,this.pathPrefix))}declarations(){return[...this.decls.values()]}clone(){let e=new n([],{normalise:this.norm,pathPrefix:this.pathPrefix});return e.decls=new Map(this.decls),Object.assign(e.values,structuredClone(this.values)),e}reseed(e){for(let t of Object.keys(this.values))delete this.values[t];this.decls.clear(),this.seed(e)}save(){return structuredClone(this.values)}load(e){for(let[t,r]of Object.entries(e))this.values[this.norm(t)]=r}};function yt(n,e,t,r,s=""){let o=r??n.name.toLowerCase();return{name:o,path:s+o,type:n.type,value:e,default:n.default??wt(n),...n.values!==void 0?{values:n.values}:{},...n.stages!==void 0?{stages:n.stages}:{},writable:t??n.writable??!0}}var sr=n=>n.toLowerCase(),Oe=1,ue=class{scopes=new Map;parked=new Map;rev=0;get revision(){return this.rev}defineOwned(e,t,r){let s=typeof r=="string"?{pathPrefix:r}:r??{},o=new F(t,{pathPrefix:s.pathPrefix??`${e}.`,...s.normalise?{normalise:s.normalise}:{}});return this.mountOwned(e,o,s.owner!==void 0?{owner:s.owner}:void 0)}mountOwned(e,t,r){this.assertFree(e,r?.owner),this.scopes.set(e,{kind:"owned",bag:t,...r?.owner!==void 0?{owner:r.owner}:{}}),this.rev++;let s=this.parked.get(e);return s&&(t.load(s),this.parked.delete(e)),this}remove(e,t){let r=this.scopes.get(e);if(!r)throw new Error(`unknown scope '@${e}'`);return t?.keep&&r.kind==="owned"&&this.parked.set(e,r.bag.save()),this.scopes.delete(e),this.rev++,this}discardParked(e){if(e===void 0)this.parked.clear();else for(let t of[...this.parked.keys()])t.startsWith(e)&&this.parked.delete(t);return this}ownedBag(e){let t=this.scopes.get(e);if(!t||t.kind!=="owned")throw new Error(`'@${e}' is not an owned scope`);return t.bag}reseedOwned(e,t){return this.ownedBag(e).reseed(t),this}defineForeign(e,t,r=[],s=!0){let o=typeof s=="boolean"?{writable:s}:s;this.assertFree(e,o.owner);let i=o.normalise??sr,a=new Map;for(let d of r)a.set(i(d.name),d);return this.scopes.set(e,{kind:"foreign",resolver:t,decls:a,scopeWritable:o.writable??!0,norm:i,...o.owner!==void 0?{owner:o.owner}:{}}),this.rev++,this}has(e){return this.scopes.has(e)}get(e,t){let r=this.scopes.get(e);if(r)return r.kind==="owned"?r.bag.get(t):r.resolver.get(r.norm(t))}set(e,t,r,s){let o=this.scopes.get(e);if(!o)throw new Error(`unknown scope '@${e}'`);if(o.kind==="owned"){try{o.bag.set(t,r,s?.host?{host:!0}:void 0)}catch{throw new Error(`'@${e}.${t}' is read-only`)}return}let i=o.norm(t);if(!o.resolver.set)throw new Error(`'@${e}.${t}' is read-only`);if(!s?.host&&!this.foreignWritable(o,i))throw new Error(`'@${e}.${t}' is read-only`);o.resolver.set(i,r)}foreignWritable(e,t){return e.resolver.set?e.decls.get(t)?.writable??e.scopeWritable:!1}listProperties(){let e=[];for(let[t,r]of this.scopes){let s=r.owner!==void 0?{owner:r.owner}:{};if(r.kind==="owned")for(let o of r.bag.rows())e.push({scope:t,...s,...o});else for(let[o,i]of r.decls)e.push({scope:t,...s,...yt(i,r.resolver.get(o),this.foreignWritable(r,o),o,`${t}.`)})}return e}toEvalContext(e,t){let r=this.view(t?.aliases),s={};for(let[i,a]of r)s[i]=a.kind==="owned"?a.bag.values:a.resolver;let o=this.qualityLadders(r);return o.size===0?{scopes:s,host:e}:{scopes:s,host:e,qualities:(i,a)=>{let d=r.get(i);return d?o.get(i)?.get(or(d)(a)):void 0}}}view(e){let t=new Map(this.scopes);for(let[r,s]of Object.entries(e??{})){let o=this.scopes.get(s);if(!o)throw new Error(`alias '@${r}' names '${s}', which is not registered`);t.set(r,o)}return t}qualityLadders(e){let t=new Map;for(let[r,s]of e)for(let[o,i]of mt(s)){if(i.type!=="quality"||i.stages===void 0)continue;let a=t.get(r);a||(a=new Map,t.set(r,a)),a.set(o,i.stages)}return t}toSchema(e){let t=new Map;for(let[r,s]of this.view(e?.aliases)){let o=mt(s);if(o.length===0)continue;let i=new Map;for(let[a,d]of o)i.set(a,{type:d.type,enumValues:d.values,...d.stages!==void 0?{stages:d.stages}:{}});t.set(r,i)}return{properties:t}}save(){let e={};for(let[t,r]of this.scopes)r.kind==="owned"&&(e[t]=r.bag.save());for(let[t,r]of this.parked)e[t]=structuredClone(r);return e}load(e,t){t?.keepParked||this.parked.clear();for(let[r,s]of Object.entries(e)){let o=this.scopes.get(r);o?.kind==="owned"?o.bag.load(s):o||this.parked.set(r,structuredClone(s))}}saveFragment(){return{version:Oe,scopes:this.save()}}loadFragment(e){if(e.version!==Oe)throw new Error(`unsupported owned-state fragment version ${e.version} (supported: ${Oe})`);this.load(e.scopes)}assertFree(e,t){let r=this.scopes.get(e);if(!r)return;let s=r.owner!==void 0?` by ${r.owner}`:"",o=t!==void 0?` (wanted by ${t})`:"";throw new Error(`scope '@${e}' is already registered${s}${o}`)}};function mt(n){return n.kind==="foreign"?[...n.decls.entries()]:n.bag.declarations().map(e=>[n.bag.normalise(e.name),e])}function or(n){return n.kind==="foreign"?n.norm:e=>n.bag.normalise(e)}function wt(n){if(n.default!==void 0)return n.default;switch(n.type){case"boolean":return!1;case"number":return 0;case"string":return"";case"enum":return n.values?.[0]??"";case"flags":return[];case"quality":return n.stages?.[0]??"";default:return!1}}var bt=(n,e,t)=>`${n}${e}${t}`,v=class extends Error{constructor(e){super(e),this.name="StoryletError"}},fe=(n,e)=>n.shared??e,Bt=n=>n.sharedCopies??n.copies??1,W="Storylet Engine",Ne=n=>n,Fe=n=>n.replace(/%/g,"%25").replace(/\//g,"%2F"),Re=n=>n.replace(/%2F/g,"/").replace(/%25/g,"%"),Me=(n,e)=>`storylets/${n}/${Fe(e)}`,Ve=n=>`storylets/flow/${Fe(n)}/`,He=(n,e,t)=>e==="story"?`${Ve(n)}story`:`${Ve(n)}${e}/${Fe(t)}`,re=()=>({story:{},box:{},deck:{},hand:{},value:{}});function ir(n,e){let t=re(),r=new Map,s={},o=i=>{let a=Re(i);if(!e.has(a))return;let d=r.get(a);return d||(d=re(),r.set(a,d)),d};for(let[i,a]of Object.entries(n)){let d;if(i==="story")t.story=a;else if(d=/^storylets\/(box|deck|hand|value)\/([^/]+)$/.exec(i))t[d[1]][Re(d[2])]=a;else if(d=/^storylets\/flow\/([^/]+)\/story$/.exec(i)){let l=o(d[1]);l&&(l.story=a)}else if(d=/^storylets\/flow\/([^/]+)\/(box|deck|hand|value)\/([^/]+)$/.exec(i)){let l=o(d[1]);l&&(l[d[2]][Re(d[3])]=a)}else i.startsWith("storylets/")||(s[i]=a)}return{shared:t,flows:r,rest:s}}function vt(n,e,t){Object.keys(n.story).length>0&&(t[e("story")]=n.story);for(let r of O)for(let[s,o]of Object.entries(n[r]))Object.keys(o).length>0&&(t[e(r,s)]=o)}var xt=(n,e)=>new F(n,{normalise:Ne,pathPrefix:e}),L=(n,e)=>n!==void 0&&Object.prototype.hasOwnProperty.call(n.values,e)?n.values[e]:void 0,Le=Object.freeze(Object.create(null));function St(n){return typeof n=="boolean"?n:typeof n=="number"?n!==0:typeof n=="string"?n!=="":n.length>0}var ar={story:!0,box:!1,deck:!1,hand:!1,value:!1},Ct=(n,e)=>e.shared??ar[n],dr=(n,e)=>e.filter(t=>Ct(n,t)),lr=(n,e)=>e.filter(t=>!Ct(n,t)),O=["box","deck","hand","value"],$t=n=>O.includes(n??""),ge=()=>({gameId:new Map,id:new Map,repeated:new Map,zoneQualified:new Map}),cr=()=>({box:ge(),deck:ge(),hand:ge(),value:ge()}),Ie=(n,e)=>{let t=f(e);n.gameId.set(e.id,t),n.id.has(t)||n.id.set(t,e.id)},pr=(n,e)=>{let t=lt(e);for(let[r,s]of t.print)n.gameId.set(r,s);for(let[r,s]of t.accept)n.id.set(r,s);for(let[r,s]of t.repeated)n.repeated.set(r,s);for(let[r,s]of t.zoneQualified)n.zoneQualified.set(r,s)},Et=(n,e)=>e.template!==void 0?n.templatesById.get(e.template)?.properties??[]:e.properties??[],N=(n,e,t)=>`${e}.${n.owners[e].gameId.get(t)??t}`,ur=(n,e,t)=>{let r=n.owners[e].repeated.get(t);if(r!==void 0)return{ambiguous:r};let s=n.owners[e].zoneQualified.get(t);if(s!==void 0)return{zone:s};let o=n.owners[e].id.get(t);if(o!==void 0)return{id:o,legacy:!1};if(n.owners[e].gameId.has(t))return{id:t,legacy:!0}},Ot=(n,e,t,r)=>{let s=ur(n,e,t);if(s===void 0)throw new v(`no ${e} store "${t}"`);if("ambiguous"in s)throw new v(pt(t,r,s.ambiguous));if("zone"in s)throw new v(ct(t,s.zone,r));return s},Rt=(n,e,t,r)=>`"${e}.${t}.${r}" names the ${e} by its internal id; write "${N(n,e,t)}.${r}". The internal-id form is refused after the next release.`,Mt=(n,e)=>{let t=r=>new Map([...e[r]].map(([s,o])=>[s,xt(o,`${N(n,r,s)}.`)]));return{story:xt(e.story,"story."),box:t("box"),deck:t("deck"),hand:t("hand"),value:t("value")}},gr=n=>({story:n.story.values,box:Object.fromEntries([...n.box].map(([e,t])=>[e,t.values])),deck:Object.fromEntries([...n.deck].map(([e,t])=>[e,t.values])),hand:Object.fromEntries([...n.hand].map(([e,t])=>[e,t.values])),value:Object.fromEntries([...n.value].map(([e,t])=>[e,t.values]))}),fr=(n,e)=>{n.story.load(e?.story??{});for(let t of O)for(let[r,s]of Object.entries(e?.[t]??{}))n[t].get(r)?.load(s)},Te=()=>({evicted:[],droppedCooldowns:[],droppedSpent:[],droppedProperties:[],defaultedProperties:[],retypedProperties:[]}),je="",te=(n,e)=>[...n].map(t=>({item:t,k:e(t)})).sort((t,r)=>t.k<r.k?-1:t.k>r.k?1:0).map(t=>t.item),Ae=n=>`${n.flow??""}${je}${n.path}`;function hr(n,e){switch(n.type){case"boolean":return typeof e=="boolean";case"number":return typeof e=="number";case"string":return typeof e=="string";case"enum":return typeof e=="string"&&(n.values===void 0||n.values.includes(e));case"quality":return typeof e=="string"&&(n.stages===void 0||n.stages.includes(e));case"flags":return Array.isArray(e)&&(n.values===void 0||e.every(t=>n.values.includes(t)));default:return!0}}function kt(n,e,t,r,s){let o=l=>({...r!==void 0?{flow:r}:{},path:t(l)}),i=new Map((n??[]).map(l=>[l.name,l])),a=e??{},d={};for(let[l,c]of Object.entries(a)){let p=i.get(l);if(p===void 0){s.droppedProperties.push(o(l));continue}if(!hr(p,c)){s.retypedProperties.push(o(l));continue}d[l]=c}for(let l of n??[])l.name in a||s.defaultedProperties.push(o(l.name));return d}function Pt(n,e,t,r,s){let o={story:kt(e.story,t?.story,i=>`story.${i}`,r,s),box:{},deck:{},hand:{},value:{}};for(let i of O){let a=t?.[i]??{},d=[...new Set([...e[i].keys(),...Object.keys(a)])].sort();for(let l of d){let c=N(n,i,l);o[i][l]=kt(e[i].get(l),a[l],p=>`${c}.${p}`,r,s)}}return o}function De(n,e,t,r){let s=e.version!==n.version||e.hash!==n.hash,o=te(r.evicted,p=>[p.flow,p.hand,p.card,p.reason].join(je)),i=te(r.droppedCooldowns,p=>`${p.flow}${je}${p.card}`),a=[...r.droppedSpent].sort(),d=te(r.droppedProperties,Ae),l=te(r.defaultedProperties,Ae),c=te(r.retypedProperties,Ae);return{exact:!s&&o.length===0&&i.length===0&&a.length===0&&d.length===0&&l.length===0&&c.length===0,project:n.project,version:{saved:e.version,bundle:n.version},hash:{saved:e.hash,bundle:n.hash},flows:t,evicted:o,droppedCooldowns:i,droppedSpent:a,droppedProperties:d,defaultedProperties:l,retypedProperties:c}}var mr=n=>{let e=n.schema;if(typeof e!="string"||!$e.includes(e))throw new v(`unsupported bundle schema: ${String(e)} (this runtime reads ${$e.join(" and ")})`);let t=[],r=n.map?.group,s=r!==void 0?f(r):void 0;r!==void 0&&s===M&&t.push(`the project map's tag group is called "${M}", which is reserved for a box's own hands`);let o=new Map;for(let i of n.boxes)for(let a of i.tagGroups)for(let d of a.tags){let l=f(d);o.has(l)||o.set(l,{box:f(i),group:f(a)})}for(let i of r?.tags??[]){let a=f(i),d=o.get(a);d!==void 0&&t.push(`the project map's zone "${a}" has the name of tag "${a}" in box "${d.box}", group "${d.group}", so "value.${a}.<name>" would name two things`)}for(let i of n.boxes){let a=f(i);if(i.usesMap===!0){if(r===void 0){t.push(`box "${a}" uses the project map, but the bundle has no map`);continue}i.tagGroups.find(c=>f(c)===s)!==void 0&&t.push(`box "${a}" uses the project map and declares its own tag group "${s}", the map's name`);continue}if(r===void 0)continue;let d=l=>{t.push(`box "${a}" is not on the project map, but ${l} names the map's tag group "${s}"`)};for(let l of i.decks)for(let c of l.cards)c.tags?.[r.id]!==void 0&&d(`card "${f(c)}"`);for(let l of i.handTemplates)(l.bindings?.[r.id]!==void 0||l.chooses?.includes(r.id)===!0)&&d(`hand template "${f(l)}"`);for(let l of i.hands)(l.chosen?.[r.id]!==void 0||l.rule?.bindings?.[r.id]!==void 0)&&d(`hand "${f(l)}"`)}if(t.length>0)throw new v(`bundle refused: ${t.join("; ")}`)},he=class n{internals;seed;onReplacedFlow;flowsById=new Map;engineTraceHandlers=new Set;hostWorld;creationOptions;sharedMounts=[];constructor(e,t={}){mr(e),this.creationOptions=t,this.seed=t.seed??0,this.onReplacedFlow=t.onReplacedFlow,t.world!==void 0&&(this.hostWorld=t.world);let r={bundle:e,...t.log?{logCap:typeof t.log=="object"?t.log.cap??1e3:1e3}:{},cardsById:new Map,cardsByGameId:new Map,boxesByGameId:new Map,boxesById:new Map,handsById:new Map,handsByGameId:new Map,owners:cr(),templatesById:new Map,groupsById:new Map,requiredGroups:new Set,nodeCache:new WeakMap,ladders:{world:new Map,story:new Map,box:new Map,deck:new Map,value:new Map,hand:new Map},hasQualities:!1,hasShared:!1,flowDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},sharedDecls:{story:[],box:new Map,deck:new Map,hand:new Map,value:new Map},shared:void 0,registry:t.registry??new ue,ownsRegistry:t.registry===void 0,selfWorld:!1,registryView:()=>i(),worldResolver:void 0,worldReadOnly:new Set,emitEngine:(d,l,c)=>{this.internals.logCap!==void 0&&(this.engineLog.push({...l,flow:d,seq:this.engineSeq++,...c!==void 0?{turn:c}:{}}),this.engineLog.length>this.internals.logCap&&this.engineLog.splice(0,this.engineLog.length-this.internals.logCap));for(let p of[...this.engineTraceHandlers])p(d,l)},engineTracing:()=>this.engineTraceHandlers.size>0};this.internals=r;let s=-1,o={scopes:{},qualities:void 0},i=()=>{let d=r.registry;if(d.revision!==s){let l=d.toEvalContext(),c={};for(let[p,g]of Object.entries(l.scopes))p.includes("/")||(c[p]=g);o={scopes:c,qualities:l.qualities},s=d.revision}return o};pr(r.owners.value,e);for(let d of e.boxes){r.boxesById.set(d.id,d),r.boxesByGameId.set(f(d),d),Ie(r.owners.box,d);for(let l of d.tagGroups)r.groupsById.set(l.id,{group:l,box:d}),l.required===!0&&r.requiredGroups.add(l.id);for(let l of d.decks){Ie(r.owners.deck,l),l.shared===!0&&(r.hasShared=!0);for(let c of l.cards){let p={card:c,deck:l,box:d};r.cardsById.set(c.id,p),r.cardsByGameId.set(f(c),p),c.shared===!0&&(r.hasShared=!0)}}for(let l of d.handTemplates)r.templatesById.set(l.id,l);for(let l of d.hands)r.handsById.set(l.id,{hand:l,box:d}),r.handsByGameId.set(f(l),{hand:l,box:d}),Ie(r.owners.hand,l)}e.map!==void 0&&(r.groupsById.set(e.map.group.id,{group:e.map.group}),e.map.group.required===!0&&r.requiredGroups.add(e.map.group.id)),this.initLadders();let a=d=>({story:d("story",e.story.properties),box:new Map(e.boxes.map(l=>[l.id,d("box",l.properties)])),deck:new Map(e.boxes.flatMap(l=>l.decks.map(c=>[c.id,d("deck",c.properties)]))),hand:new Map(e.boxes.flatMap(l=>l.hands.map(c=>[c.id,d("hand",Et(r,c))]))),value:new Map(gt(e).flatMap(l=>l.tags.map(c=>[c.id,d("value",c.properties??[])])))});r.flowDecls=a(lr),r.sharedDecls=a(dr),this.initShared(this.hostWorld)}initShared(e){let t=this.internals,r=t.registry,s=t.bundle.world.properties;t.shared=Mt(t,t.sharedDecls),t.worldReadOnly=new Set(t.bundle.world.properties.filter(a=>a.writable===!1).map(a=>a.name));let o=[],i=(a,d)=>{d(),o.push(a),this.sharedMounts.push({key:a,mount:d})};try{let a=t.shared.story;i("story",()=>{r.mountOwned("story",a,{owner:W})});for(let d of O)for(let[l,c]of t.shared[d])c.declarations().length!==0&&i(Me(d,l),()=>{r.mountOwned(Me(d,l),c,{owner:W})});if(e!==void 0)i("world",()=>{r.defineForeign("world",e,s,{normalise:Ne,owner:W})});else if(t.ownsRegistry&&!r.has("world")){r.defineOwned("world",s,{normalise:Ne,pathPrefix:"world.",owner:W});let d=r.ownedBag("world");o.push("world"),this.sharedMounts.push({key:"world",mount:()=>{r.mountOwned("world",d,{owner:W})}}),t.selfWorld=!0}}catch(a){for(let d of o)r.remove(d,{keep:!0});throw a}t.worldResolver={get:a=>r.get("world",a),set:(a,d)=>{r.set("world",a,d)}},e!==void 0?t.worldSet=e.set!==void 0?(a,d)=>{r.set("world",a,d,{host:!0})}:void 0:t.worldSet=(a,d,l)=>{r.set("world",a,d,l===!0?{host:!0}:void 0)}}reseedShared(){let{shared:e,sharedDecls:t,registry:r}=this.internals;e.story.reseed(t.story);for(let s of O)for(let[o,i]of e[s])i.reseed(t[s].get(o)??[]);this.internals.selfWorld&&r.reseedOwned("world",this.internals.bundle.world.properties)}initLadders(){let e=this.internals,t=o=>{let i=new Map;for(let a of o??[])a.type==="quality"&&a.stages!==void 0&&i.set(a.name,a.stages);return i},r=e.bundle;e.ladders.world=t(r.world.properties),e.ladders.story=t(r.story.properties);for(let o of r.boxes){e.ladders.box.set(o.id,t(o.properties));for(let i of o.decks)e.ladders.deck.set(i.id,t(i.properties));for(let i of o.tagGroups)for(let a of i.tags)e.ladders.value.set(a.id,t(a.properties));for(let i of o.hands)e.ladders.hand.set(i.id,t(Et(e,i)))}for(let o of r.map?.group.tags??[])e.ladders.value.set(o.id,t(o.properties));let s=o=>[...o.values()].some(i=>i.size>0);e.hasQualities=e.ladders.world.size>0||e.ladders.story.size>0||s(e.ladders.box)||s(e.ladders.deck)||s(e.ladders.value)||s(e.ladders.hand)}openFlow(e,t={}){return this.open(e,t,!1)}open(e,t,r){this.assertExternalScopes();let s=t.restore!==void 0?this.sharedClaims(e):void 0,o=this.flowsById.get(e);if(o){let a=o.heldCardIds().length;a>0&&this.onReplacedFlow?.(e,a),o.markClosed()}r||this.internals.registry.discardParked(Ve(e));let i=new ne(this,this.internals,e,t.seed??this.seed);if(this.flowsById.set(e,i),t.restore!==void 0){let a=Te(),d=this.planFlowRestore(e,structuredClone(t.restore),s,a);i.restore(d);let l=this.internals.bundle.content;t.onRestoreReport?.(De(l,l,[e],a))}return i}getFlow(e){return this.flowsById.get(e)}flows(){return[...this.flowsById.values()]}closeFlow(e){let t=this.flowsById.get(e);t&&(this.flowsById.delete(e),t.markClosed())}dropFlow(e,t){this.flowsById.get(e)===t&&this.flowsById.delete(e)}reset(){this.dropRun(!1),this.reseedShared(),this.internals.registry.discardParked("storylets/")}dropRun(e){this.engineLog=[];for(let[t,r]of this.flowsById)r.releaseBags(e!==!1&&e.has(t)),r.markClosed();this.flowsById.clear(),this.spent.clear()}spent=new Set;isTaken(e){return this.spent.has(e)}markTaken(e){this.spent.add(e)}engineLog=[];engineSeq=0;log(){return this.engineLog}clearLog(){this.engineLog=[]}sharedClaims(e){let t=new Map;for(let[r,s]of this.flowsById)if(r!==e)for(let o of s.heldCardIds())t.set(o,(t.get(o)??0)+1);return t}getProperty(e){let t=this.resolveShared(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):t.bag.get(t.name);if(r===void 0)throw new v(`no property at "${e}"`);return r}setProperty(e,t){let r=this.resolveShared(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new v("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}r.bag.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolveShared(e){let t=e.split("."),r=()=>{throw new v(`"${e}" is per-flow state - read it on a Flow, not the Engine`)};if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story"){let s=t[1];if(L(this.internals.shared.story,s)!==void 0)return{kind:"bag",bag:this.internals.shared.story,name:s};throw this.internals.flowDecls.story.some(o=>o.name===s)&&r(),new v(`no property at "${e}"`)}if(t.length===3&&$t(t[0])){let s=t[0],[,o,i]=t,a=Ot(this.internals,s,o,i);a.legacy&&this.diagnose(Rt(this.internals,s,o,i));let d=a.id,l=this.internals.shared[s].get(d);if(l!==void 0&&L(l,i)!==void 0)return{kind:"bag",bag:l,name:i};throw this.internals.flowDecls[s].get(d)?.some(c=>c.name===i)&&r(),l===void 0&&!this.internals.flowDecls[s].has(d)?new v(`no ${s} store "${o}"`):new v(`no property at "${e}"`)}throw new v(`bad property path "${e}"`)}diagnose(e){this.internals.emitEngine("",{type:"diagnostic",where:"property address",message:e})}assertExternalScopes(){for(let e of this.internals.bundle.externalScopes??[])if(!this.internals.registry.has(e))throw new v(`this content names @${e}, which no engine on this registry registered: give every engine the game's one registry`)}listProperties(){let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s)=>{for(let o of s.rows())e.push(o)};t("story",this.internals.shared.story);for(let r of O)for(let[s,o]of this.internals.shared[r])t(N(this.internals,r,s),o);return e}listBags(){let e=[{prefix:"story",bag:this.internals.shared.story}];for(let t of O)for(let[r,s]of this.internals.shared[t])e.push({prefix:N(this.internals,t,r),bag:s});return e}subscribeTrace(e){return this.engineTraceHandlers.add(e),()=>{this.engineTraceHandlers.delete(e)}}hotSwap(e,t={}){if(e.content.project!==this.internals.bundle.content.project)throw new v(`hotSwap: the bundle is for project "${e.content.project}", this engine runs "${this.internals.bundle.content.project}"`);let r={...this.creationOptions,...t},s=this.saveGame(),o=this.internals.registry;if(this.internals.ownsRegistry){let c=new n(e,{...r,registry:void 0});return{engine:c,report:c.loadGame(s)}}let i={};for(let[c,p]of Object.entries(o.save()))(c==="story"||c.startsWith("storylets/"))&&(i[c]=p);let a=new Set([...this.sharedMounts.map(c=>c.key),...[...this.flowsById.values()].flatMap(c=>c.registeredKeys())]),d=Object.fromEntries(Object.entries(i).filter(([c])=>!a.has(c)));for(let{key:c}of this.sharedMounts)o.has(c)&&o.remove(c);for(let c of this.flowsById.values())c.releaseBags(!1);let l;try{l=new n(e,{...r,registry:o});let c=l.loadGame({...s,registry:i}),p=Object.fromEntries(Object.entries(d).filter(([g])=>!o.has(g)));return Object.keys(p).length>0&&o.load(p,{keepParked:!0}),this.dropRun(!1),{engine:l,report:c}}catch(c){l?.dropRun(!1);for(let{key:p}of l?.sharedMounts??[])o.has(p)&&o.remove(p);o.discardParked("storylets/");for(let{mount:p}of this.sharedMounts)p();for(let p of this.flowsById.values())p.mountBags();throw this.reseedShared(),o.load(i,{keepParked:!0}),c}}saveGame(){return structuredClone({schema:Y,content:this.internals.bundle.content,...this.internals.ownsRegistry?{registry:this.registrySection()}:{},shared:{spent:[...this.spent].sort()},flows:Object.fromEntries([...this.flowsById].map(([e,t])=>[e,t.snapshot(!1)]))})}registrySection(){let e=this.internals.registry.save(),t={},r=s=>{Object.prototype.hasOwnProperty.call(e,s)&&!Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=e[s])};for(let{key:s}of this.sharedMounts)r(s);for(let s of Object.values(Object.fromEntries(this.flowsById)))for(let o of s.registeredKeys())r(o);for(let s of Object.keys(e))r(s);return t}saveFlow(e){let t=this.flowsById.get(e);if(!t)throw new v(`unknown flow "${e}"`);return structuredClone(t.snapshot(!0))}previewLoad(e){return this.assertSameProject(e),this.planLoad(e).report}previewFlowRestore(e,t){let r=Te();this.planFlowRestore(e,t,this.sharedClaims(e),r);let s=this.internals.bundle.content;return De(s,s,[e],r)}loadGame(e){this.assertSameProject(e),this.assertExternalScopes();let t=this.planLoad(structuredClone(e)),r=this.internals.registry;t.sections!==void 0?(this.reset(),this.internals.ownsRegistry?r.load(t.sections):r.load(t.sections,{keepParked:!0})):this.dropRun(new Set(t.flows.map(([s])=>s)));for(let s of t.spent)this.spent.add(s);for(let[s,o]of t.flows)this.open(s,{},!0).restore(o);return t.report}assertSameProject(e){if(e.content.project!==this.internals.bundle.content.project)throw new v(`save is for project "${e.content.project}", bundle is "${this.internals.bundle.content.project}"`)}planLoad(e){let t=e.schema;if(t!==Y&&t!==X)throw new v(`unsupported save schema: ${String(t)}`);let r=Te(),s=new Set(Object.keys(e.flows??{})),o;e.schema===X?o={shared:e.shared?.props??re(),flows:new Map(Object.entries(e.flows??{}).map(([c,p])=>[c,p.props??re()])),rest:{}}:e.registry!==void 0&&(o=ir(e.registry,s));let i=o!==void 0?Pt(this.internals,this.internals.sharedDecls,o.shared,void 0,r):void 0,a=[];for(let c of e.shared?.spent??[])this.internals.cardsById.has(c)?a.push(c):r.droppedSpent.push(c);let d=[],l=o!==void 0?{...o.rest}:void 0;l!==void 0&&i!==void 0&&vt(i,(c,p)=>c==="story"?"story":Me(c,p),l);for(let[c,p]of Object.entries(e.flows??{})){let g=o!==void 0?{...p,props:o.flows.get(c)??re()}:{...p},u=this.planFlowRestore(c,g,void 0,r);l!==void 0&&u.props!==void 0&&(vt(u.props,(m,h)=>He(c,m,h),l),delete u.props),d.push([c,u])}return{report:De(this.internals.bundle.content,e.content,d.map(([c])=>c),r),...l!==void 0?{sections:l}:{},spent:a,flows:d}}planFlowRestore(e,t,r,s){let o=this.internals,i=t.props!==void 0?Pt(o,o.flowDecls,t.props,e,s):void 0,a={};for(let[p,g]of Object.entries(t.cooldowns??{}))o.cardsById.has(p)?a[p]=g:s.droppedCooldowns.push({flow:e,card:p});let d=p=>{let g=o.cardsById.get(p);return g?f(g.card):p},l={},c=new Map;for(let[p,g]of Object.entries(t.board??{})){let u=o.handsById.get(p);if(u===void 0){for(let x of g)s.evicted.push({flow:e,hand:p,card:d(x),reason:"hand-vanished"});continue}let m=f(u.hand),h=[];for(let x of g){let b=o.cardsById.get(x);if(b===void 0){s.evicted.push({flow:e,hand:m,card:x,reason:"vanished"});continue}if(r!==void 0&&fe(b.card,b.deck.shared??!1)){if((r.get(x)??0)+(c.get(x)??0)>=Bt(b.card)){s.evicted.push({flow:e,hand:m,card:f(b.card),reason:"claimed-elsewhere"});continue}c.set(x,(c.get(x)??0)+1)}h.push(x)}l[p]=h}return{...i!==void 0?{props:i}:{},turns:t.turns??{},prng:t.prng,cooldowns:a,board:l,playLog:t.playLog??[]}}},ne=class{id;engine;internals;closed=!1;prng;turnCounts=new Map;cooldowns={};boardContents=new Map;playLog=[];playCount=new Map;lastPlayOf=new Map;tagPlayCount=new Map;lastPlayInTag=new Map;stores;registered=[];bagKeys=[];traceHandlers=new Set;logEntries=[];logSeq=0;storyReader;boxReaders=new Map;deckReaders=new Map;constructor(e,t,r,s){this.engine=e,this.internals=t,this.id=r,this.prng=D(s),this.stores=Mt(t,t.flowDecls);let o=(a,d)=>{d.declarations().length!==0&&this.bagKeys.push([a,d])};o(He(r,"story"),this.stores.story);for(let a of O)for(let[d,l]of this.stores[a])o(He(r,a,d),l);this.mountBags();for(let a of t.bundle.boxes){this.turnCounts.set(a.id,0);for(let d of a.hands)this.boardContents.set(d.id,[])}let i=(a,d)=>({get:l=>L(a,l)??L(d,l)});this.storyReader=i(this.stores.story,t.shared.story);for(let a of t.bundle.boxes){this.boxReaders.set(a.id,i(this.stores.box.get(a.id),t.shared.box.get(a.id)));for(let d of a.decks)this.deckReaders.set(d.id,i(this.stores.deck.get(d.id),t.shared.deck.get(d.id)))}}get isClosed(){return this.closed}close(){this.closed||(this.engine.dropFlow(this.id,this),this.markClosed())}markClosed(){this.releaseBags(!1),this.closed=!0}releaseBags(e){for(let t of this.registered)this.internals.registry.remove(t,{keep:e});this.registered.length=0}registeredKeys(){return[...this.registered]}mountBags(){for(let[e,t]of this.bagKeys)this.internals.registry.mountOwned(e,t,{owner:W}),this.registered.push(e)}assertOpen(){if(this.closed)throw new v(`flow "${this.id}" is closed`)}resolveBox(e){let t=this.internals.boxesByGameId.get(e)??this.internals.boxesById.get(e);if(!t)throw new v(`unknown box "${e}"`);return t}turn(e){return this.assertOpen(),this.turnCounts.get(this.resolveBox(e).id)??0}subscribeTrace(e){return this.traceHandlers.add(e),()=>{this.traceHandlers.delete(e)}}get tracing(){return this.traceHandlers.size>0||this.internals.logCap!==void 0||this.internals.engineTracing()}emit(e,t){this.internals.logCap!==void 0&&(this.logEntries.push({...e,seq:this.logSeq++,...t!==void 0?{turn:t}:{}}),this.logEntries.length>this.internals.logCap&&this.logEntries.splice(0,this.logEntries.length-this.internals.logCap));for(let r of[...this.traceHandlers])r(e);this.internals.emitEngine(this.id,e,t)}log(){return this.logEntries}clearLog(){this.logEntries=[]}node(e){let t=this.internals.nodeCache.get(e);return t||(t=V(e.ast),this.internals.nodeCache.set(e,t)),t}groupInBox(e,t){let r=Q(this.internals.bundle,e);return r.find(s=>f(s)===t)??r.find(s=>s.id===t)}indexPlay(e){this.playCount.set(e.card,(this.playCount.get(e.card)??0)+1),this.lastPlayOf.set(e.card,e);let t=this.internals.cardsByGameId.get(e.card);if(t)for(let[r,s]of Object.entries(t.card.tags??{}))for(let o of s){let i=bt(t.box.id,r,o);this.tagPlayCount.set(i,(this.tagPlayCount.get(i)??0)+1),this.lastPlayInTag.set(i,e)}}rebuildPlayIndex(){this.playCount.clear(),this.lastPlayOf.clear(),this.tagPlayCount.clear(),this.lastPlayInTag.clear();for(let e of this.playLog)this.indexPlay(e)}hostsByBox=new Map;host(e){let t=this.hostsByBox.get(e.id);if(t!==void 0)return t;let r=this.makeHost(e);return this.hostsByBox.set(e.id,r),r}makeHost(e){let t=new Map,r=(o,i)=>{let a=`${o}${i}`;if(t.has(a))return t.get(a);let d=this.groupInBox(e,o),l=d?.tags.find(p=>p.gameId===i),c=d&&l?bt(e.id,d.id,l.id):void 0;return t.set(a,c),c},s=o=>{let i=this.internals.cardsByGameId.get(o.card);return i?(this.turnCounts.get(i.box.id)??0)-o.turn:le};return{nextRandom:()=>this.prng.next(),countPlayed:o=>this.playCount.get(o)??0,turnsSincePlayed:o=>{let i=this.lastPlayOf.get(o);return i?s(i):le},countPlayedIn:(o,i)=>{let a=r(o,i);return a===void 0?0:this.tagPlayCount.get(a)??0},turnsSincePlayedIn:(o,i)=>{let a=r(o,i),d=a===void 0?void 0:this.lastPlayInTag.get(a);return d?s(d):le}}}evalCtx(e,t,r){let s=this.internals.registryView();return{scopes:{...s.scopes,world:this.internals.worldResolver,story:this.storyReader,box:this.boxReaders.get(e.id)??Le,deck:t?this.deckReaders.get(t.id)??Le:Le,hand:r.bag},host:this.host(e),...this.internals.hasQualities||s.qualities!==void 0?{qualities:(o,i)=>o==="world"?this.internals.ladders.world.get(i)??s.qualities?.(o,i):o==="story"?this.internals.ladders.story.get(i):o==="box"?this.internals.ladders.box.get(e.id)?.get(i):o==="deck"&&t?this.internals.ladders.deck.get(t.id)?.get(i):o==="hand"?this.handLadder(r,i):s.qualities?.(o,i)}:{}}}handLadder(e,t){let r=e.sources.get(t);if(r)return r.kind==="value"?this.internals.ladders.value.get(r.id)?.get(t):r.kind==="hand"?this.internals.ladders.hand.get(r.id)?.get(t):void 0}eval(e,t){return ae(this.node(e),t,Ce)}passes(e,t,r){if(!e)return!0;try{return St(this.eval(e,t))}catch(s){return this.tracing&&this.emit({type:"diagnostic",where:r??"condition",message:s instanceof Error?s.message:String(s)}),!1}}tagByGameId(e,t){return e.tags.find(r=>r.gameId===t)}askForHand(e,t){let r=new Map,s={},o=a=>{for(let[d,l]of Object.entries(a??{})){if(ce(l)){this.fillHoleFromProperty(e,d,l,r,s);continue}r.set(d,l);let c=this.internals.groupsById.get(d),p=c?.group.tags.find(g=>g.id===l);c&&p&&(s[f(c.group)]=f(p))}},i;if(e.template!==void 0){let a=this.internals.templatesById.get(e.template);if(!a)throw new v(`hand "${f(e)}": unknown template "${e.template}"`);for(let[d,l]of Object.entries(a.bindings??{}))r.set(d,l);o(e.chosen),i=a.condition}else o(e.rule?.bindings),i=e.rule?.condition;return r.set(M,e.id),this.bindStateGroups(t,r,s),{box:t,hand:e,...i!==void 0?{condition:i}:{},boundTags:r,askNames:s}}askForPeek(e,t){let r=new Map,s={};for(let[o,i]of Object.entries(t)){if(o===M){let l=this.internals.handsByGameId.get(i)??this.internals.handsById.get(i);if(!l)throw new v(`peek: unknown hand "${i}" in home criteria`);r.set(M,l.hand.id);continue}let a=this.groupInBox(e,o);if(!a)throw new v(`peek: unknown tag group "${o}" in box "${f(e)}"`);let d=this.tagByGameId(a,i)??a.tags.find(l=>l.id===i);if(!d)throw new v(`peek: unknown tag "${i}" in group "${f(a)}"`);r.set(a.id,d.id),s[f(a)]=f(d)}return this.bindStateGroups(e,r,s),{box:e,boundTags:r,askNames:s}}fillHoleFromProperty(e,t,r,s,o){let i=this.internals.groupsById.get(t),a=i?f(i.group):t,d=`hand ${f(e)}, tag group ${a}`,l=ut(r);if(!l){this.emit({type:"diagnostic",where:d,message:`"${r}" is not a @hand, @world or @story property reference`});return}if(!i){this.emit({type:"diagnostic",where:d,message:`"${r}" fills a tag group that is not in this box`});return}let c;if(l.scope==="hand")c=this.valuesOf("hand",e.id)[l.name];else try{c=this.getProperty(`${l.scope}.${l.name}`)}catch{c=void 0}if(c===void 0){this.emit({type:"diagnostic",where:d,message:`"${r}" names a property that is not declared`});return}let p=typeof c=="string"?c:String(c),g=i.group.tags.find(u=>f(u)===p);if(!g){this.emit({type:"diagnostic",where:d,message:`${r} is "${p}", which is not one of the tags of "${a}"`});return}s.set(t,g.id),o[a]=f(g)}bindStateGroups(e,t,r){for(let s of Q(this.internals.bundle,e)){if(s.boundBy===void 0||t.has(s.id))continue;let o=/^@(world|story)\.([a-z][a-z0-9_-]*)$/.exec(s.boundBy);if(!o){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" is not a @world or @story property reference`});continue}let i;try{i=this.getProperty(`${o[1]}.${o[2]}`)}catch{this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`boundBy "${s.boundBy}" names a property that is not declared`});continue}let a=typeof i=="string"?i:String(i),d=s.tags.find(l=>f(l)===a);if(!d){this.emit({type:"diagnostic",where:`tag group ${f(s)}`,message:`${s.boundBy} is "${a}", which is not one of its tags`});continue}t.set(s.id,d.id),r[f(s)]=f(d)}}valuesOf(e,t){return Object.assign(Object.create(null),this.internals.shared[e].get(t)?.values??{},this.stores[e].get(t)?.values??{})}buildHandEnv(e){let t=Object.create(null),r=new Map;for(let[s,o]of e.boundTags)if(s!==M)for(let[i,a]of Object.entries(this.valuesOf("value",o)))t[i]=a,r.set(i,{kind:"value",id:o});if(e.hand)for(let[s,o]of Object.entries(this.valuesOf("hand",e.hand.id)))t[s]=o,r.set(s,{kind:"hand",id:e.hand.id});for(let[s,o]of Object.entries(e.askNames))t[s]=o,r.set(s,{kind:"criteria"});return{bag:t,sources:r,boundTags:e.boundTags}}claims(){let e=new Map;for(let t of this.boardContents.values())for(let r of t)e.set(r,(e.get(r)??0)+1);return e}heldCardIds(){return[...this.boardContents.values()].flat()}copiesOf(e){return e.copies??1}claimVerdict(e,t,r,s){let o=e.id;return(r.get(o)??0)>=this.copiesOf(e)?"claimed":t&&(s.get(o)??0)>=Bt(e)?"claimed-elsewhere":null}tagsMatch(e,t){let r=e.tags?.[M];if(r!==void 0&&r.length>0){let s=t.get(M);if(s===void 0||!r.includes(s))return!1}for(let[s,o]of t){if(s===M)continue;let i=e.tags?.[s];if(i===void 0){if(this.internals.requiredGroups.has(s))return!1;continue}if(!i.includes(o))return!1}return!0}runAsk(e,t,r){let{box:s}=e,o=this.buildHandEnv(e),i=(p,g)=>{r?.push({id:f(p),verdict:g})};if(!this.passes(e.condition,this.evalCtx(s,void 0,o),`hand ${e.hand?f(e.hand):""} condition`))return{ordered:[],handEnv:o};let a=new Map;for(let p of s.decks)a.set(p.id,this.passes(p.condition,this.evalCtx(s,p,o),`deck ${p.gameId} gate`));let d=this.turnCounts.get(s.id)??0,l=[];for(let p of s.decks){let g=this.evalCtx(s,p,o),u=p.shared??!1;for(let m of p.cards){let h=fe(m,u);if(!a.get(p.id)){i(m,"deck-gate");continue}if(h&&this.engine.isTaken(m.id)){i(m,"taken");continue}if((this.cooldowns[m.id]??0)>d){i(m,"cooldown");continue}if(!this.tagsMatch(m,o.boundTags)){i(m,"tags");continue}if(m.condition&&!this.passes(m.condition,g,this.tracing?`card ${m.gameId} condition`:void 0)){i(m,"condition");continue}let x=t(m,h);if(x){i(m,x);continue}let b;if(typeof m.priority=="number")b=m.priority;else try{let y=this.eval(m.priority,g);if(typeof y!="number"||Number.isNaN(y)){i(m,"priority");continue}b=y}catch(y){this.tracing&&this.emit({type:"diagnostic",where:`card ${m.gameId} priority`,message:y instanceof Error?y.message:String(y)}),i(m,"priority");continue}let w=0;if(s.ranking.specificity&&m.condition){let y=this.node(m.condition);w=ot(y,k=>{try{return St(ae(k,g,Ce))}catch{return!1}})}l.push({entry:{card:m,deck:p,box:s},priority:b,spec:w})}}l.sort((p,g)=>g.priority-p.priority||g.spec-p.spec);let c=0;for(;c<l.length;){let p=c+1;for(;p<l.length&&l[p].priority===l[c].priority&&l[p].spec===l[c].spec;)p++;if(p-c>1){let g=l.slice(c,p);j(g,this.prng);for(let u=0;u<g.length;u++)l[c+u]=g[u]}c=p}for(let p of l)r?.push({id:f(p.entry.card),verdict:"dealt",priority:p.priority,specificity:p.spec});return{ordered:l.map(p=>p.entry),handEnv:o}}capTrace(e,t){for(let r of e)r.verdict==="dealt"&&!t.has(r.id)&&(r.verdict="capped")}view(e){let{card:t}=e;return{id:t.id,gameId:f(t),...t.title!==void 0?{title:t.title}:{},...t.purpose!==void 0?{purpose:t.purpose}:{},...t.fields!==void 0?{fields:t.fields}:{}}}handCapacity(e){if(e.slots!==void 0)return e.slots;let t=e.template!==void 0?this.internals.templatesById.get(e.template)?.slots:e.rule?.slots;return t===void 0||t==="unbounded"?1/0:t}resolveHand(e){let t=this.internals.handsByGameId.get(e)??this.internals.handsById.get(e);if(!t)throw new v(`unknown hand "${e}"`);return t}peek(e,t={},r){this.assertOpen();let s=this.resolveBox(e),o=this.askForPeek(s,t),i=this.claims(),a=this.internals.hasShared?this.engine.sharedClaims():new Map,d=this.tracing?[]:void 0,l=this.prng;this.prng=D(l.state());let c;try{({ordered:c}=this.runAsk(o,(g,u)=>this.claimVerdict(g,u,i,a),d))}finally{this.prng=l}let p=r===void 0?c:c.slice(0,Math.max(r,0));return d&&(this.capTrace(d,new Set(p.map(g=>f(g.card)))),this.emit({type:"peek",box:f(s),criteria:t,cards:d},this.turnCounts.get(s.id)??0)),{box:f(s),cards:p.map(g=>this.view(g))}}deal(e){this.assertOpen();let{hand:t}=this.resolveHand(e);return this.dealMany([e])[f(t)]??[]}dealMany(e){this.assertOpen();let t=(e??[...this.internals.handsById.keys()].sort()).map(o=>this.resolveHand(o));j(t,this.prng);for(let{hand:o,box:i}of t){let a=this.askForHand(o,i),d=this.buildHandEnv(a),l=this.passes(a.condition,this.evalCtx(i,void 0,d)),c=new Map,p=new Map;for(let b of i.decks){let w=this.evalCtx(i,b,d);p.set(b.id,w),c.set(b.id,this.passes(b.condition,w))}let g=this.tracing,u=this.turnCounts.get(i.id)??0,m=[],h=(b,w)=>{let y=this.internals.cardsById.get(b);return m.push({card:y?f(y.card):b,reason:w}),!1},x=(this.boardContents.get(o.id)??[]).filter(b=>{if(!l)return h(b,"hand-condition");let w=this.internals.cardsById.get(b);return!w||w.box.id!==i.id?h(b,"vanished"):c.get(w.deck.id)?fe(w.card,w.deck.shared??!1)&&this.engine.isTaken(b)?h(b,"taken"):(this.cooldowns[b]??0)>u?h(b,"cooldown"):this.tagsMatch(w.card,d.boundTags)?this.passes(w.card.condition,p.get(w.deck.id),g?`card ${w.card.gameId} condition`:void 0)?!0:h(b,"condition"):h(b,"tags"):h(b,"deck-gate")});if(this.boardContents.set(o.id,x),g)for(let b of m)this.emit({type:"evict",hand:f(o),card:b.card,reason:b.reason},u)}let r=this.claims(),s=this.internals.hasShared?this.engine.sharedClaims():new Map;for(let{hand:o,box:i}of t){let a=this.boardContents.get(o.id)??[],d=this.handCapacity(o)-a.length;if(d<=0)continue;let l=this.askForHand(o,i),c=new Set(a),p=this.tracing?[]:void 0,{ordered:g}=this.runAsk(l,(h,x)=>c.has(h.id)?"claimed":this.claimVerdict(h,x,r,s),p),u=g.slice(0,d),m=u.map(h=>h.card.id);this.boardContents.set(o.id,[...a,...m]);for(let h of m)r.set(h,(r.get(h)??0)+1),s.set(h,(s.get(h)??0)+1);p&&(this.capTrace(p,new Set(u.map(h=>f(h.card)))),this.emit({type:"deal",hand:f(o),cards:p},this.turnCounts.get(i.id)??0))}return Object.fromEntries(t.map(({hand:o})=>[f(o),(this.boardContents.get(o.id)??[]).map(i=>this.view(this.internals.cardsById.get(i)))]))}board(e){this.assertOpen();let t=e!==void 0?this.resolveBox(e).id:void 0;return Object.fromEntries([...this.boardContents.entries()].filter(([r])=>t===void 0||this.internals.handsById.get(r).box.id===t).map(([r,s])=>[f(this.internals.handsById.get(r).hand),s.map(o=>this.view(this.internals.cardsById.get(o)))]))}resolveDealt(e,t){let r=this.internals.cardsById.get(e)??this.internals.cardsByGameId.get(e);if(!r)throw new v(`unknown card "${e}"`);let{hand:s,box:o}=this.resolveHand(t);if(!(this.boardContents.get(s.id)??[]).includes(r.card.id))throw new v(`card "${f(r.card)}" is not dealt to hand "${f(s)}"`);return{entry:r,ask:this.askForHand(s,o)}}outcomes(e,t){this.assertOpen();let{entry:r,ask:s}=this.resolveDealt(e,t),o=this.evalCtx(r.box,r.deck,this.buildHandEnv(s));return r.card.outcomes.map(i=>({id:i.id,gameId:f(i),...i.title!==void 0?{title:i.title}:{},...i.purpose!==void 0?{purpose:i.purpose}:{},...i.fields!==void 0?{fields:i.fields}:{},available:this.passes(i.condition,o)}))}play(e,t,r,s={}){this.assertOpen();let{entry:o,ask:i}=this.resolveDealt(e,r),a=t==="";if(a&&o.card.outcomes.length>0)throw new v(`card "${f(o.card)}" has outcomes (${o.card.outcomes.map(y=>f(y)).join(", ")}); name the one played`);let d=a?void 0:o.card.outcomes.find(y=>f(y)===t);if(!a&&!d)throw new v(`card "${f(o.card)}" has no outcome "${t}"`);let l=this.buildHandEnv(i),c=this.evalCtx(o.box,o.deck,l);if(d&&!this.passes(d.condition,c))throw new v(`outcome "${t}" on "${f(o.card)}" is gated shut`);let p=o.box.turn!==void 0?0:this.internals.bundle.settings.playAdvancesTurns,g=(this.turnCounts.get(o.box.id)??0)+(s.advanceTurns??p),m=Object.entries(d?.changes??{}).map(([y,k])=>({target:y,expr:k,plan:this.planWrite(y,o,l)})).map(y=>({...y,value:this.eval(y.expr,c)})),h=[];try{for(let y of m)h.push({target:y.target,plan:y.plan,value:y.value,prev:this.landWrite(y.plan,y.value)})}catch(y){for(let k of[...h].reverse())this.undoWrite(k.plan,k.prev);throw y}if(this.tracing)for(let{target:y,plan:k,value:I,prev:ie}of h)this.emit({type:"write",target:y,path:k.path,value:I,...ie!==void 0?{prev:ie}:{}},g);let x=d?f(d):"",b={card:f(o.card),outcome:x,turn:g};this.playLog.push(b),this.indexPlay(b),o.card.redraw==="never"?fe(o.card,o.deck.shared??!1)?this.engine.markTaken(o.card.id):this.cooldowns[o.card.id]=Number.MAX_SAFE_INTEGER:typeof o.card.redraw=="number"&&(this.cooldowns[o.card.id]=g+o.card.redraw);let w=i.hand.id;this.boardContents.set(w,(this.boardContents.get(w)??[]).filter(y=>y!==o.card.id)),this.turnCounts.set(o.box.id,g),this.tracing&&this.emit({type:"play",card:f(o.card),outcome:x,turn:g},g)}address(e,t){return N(this.internals,e,t)}planBag(e,t,r,s){let o=e==="story"?this.stores.story:t!==void 0?this.stores[e].get(t):void 0,i=e==="story"?this.internals.shared.story:t!==void 0?this.internals.shared[e].get(t):void 0,a=L(o,r)!==void 0?o:L(i,r)!==void 0?i:void 0;if(a===void 0)throw new v(`no property at "${s}"`);if(a.declarations().some(d=>d.name===r&&d.writable===!1))throw new v(`'${r}' is read-only`);return{kind:"bag",bag:a,name:r,path:s}}planWrite(e,t,r){let s=/^@([a-z]+)\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(e);if(!s)throw new v(`bad change target "${e}"`);let[,o,i]=s;switch(o){case"world":{if(!this.internals.worldSet)throw new v(`@world.${i} cannot be written: the host bound @world read-only`);if(this.internals.worldReadOnly.has(i))throw new v(`'@world.${i}' is read-only (writable: false)`);return{kind:"world",name:i,path:`world.${i}`}}case"story":return this.planBag("story",void 0,i,`story.${i}`);case"box":return this.planBag("box",t.box.id,i,`${this.address("box",t.box.id)}.${i}`);case"deck":return this.planBag("deck",t.deck.id,i,`${this.address("deck",t.deck.id)}.${i}`);case"hand":{let a=r.sources.get(i);if(!a)throw new v(`@hand.${i} is not composed in this ask`);if(a.kind==="criteria")throw new v(`@hand.${i} is a chosen tag / criteria name and cannot be written`);return this.planBag(a.kind,a.id,i,`${this.address(a.kind,a.id)}.${i}`)}default:{if(this.internals.registry.has(o))return{kind:"scope",scope:o,name:i,path:`${o}.${i}`};throw this.internals.bundle.externalScopes?.includes(o)?new v(`@${o}.${i} cannot be written: no engine on this registry registered @${o}`):new v(`bad change target scope "@${o}"`)}}}landWrite(e,t){switch(e.kind){case"world":{let r=this.internals.worldResolver.get(e.name);return this.internals.worldSet(e.name,t),r}case"bag":return e.bag.set(e.name,t).prev;case"scope":{let r=this.internals.registry.get(e.scope,e.name);return this.internals.registry.set(e.scope,e.name,t),r}}}undoWrite(e,t){if(t!==void 0)switch(e.kind){case"world":this.internals.worldSet(e.name,t,!0);return;case"bag":e.bag.set(e.name,t,{silent:!0,reason:"play refused",host:!0});return;case"scope":this.internals.registry.set(e.scope,e.name,t,{host:!0});return}}advanceTurns(e,t=1){this.assertOpen();let r=this.resolveBox(e),s=(this.turnCounts.get(r.id)??0)+t;this.turnCounts.set(r.id,s),this.tracing&&this.emit({type:"turns",box:f(r),turn:s},s)}listBoxes(){return this.assertOpen(),this.internals.bundle.boxes.map(e=>({id:e.id,gameId:f(e),...e.title!==void 0?{title:e.title}:{},turn:this.turnCounts.get(e.id)??0}))}listBags(){this.assertOpen();let e=[{prefix:"story",bag:this.stores.story}];for(let t of O)for(let[r,s]of this.stores[t])e.push({prefix:N(this.internals,t,r),bag:s});return e}listProperties(){this.assertOpen();let e=[];for(let r of this.internals.bundle.world.properties){let s=this.internals.worldResolver.get(r.name);e.push({path:`world.${r.name}`,name:r.name,type:r.type,value:s??r.default,default:r.default,...r.values!==void 0?{values:r.values}:{},...r.stages!==void 0?{stages:r.stages}:{},writable:this.internals.worldSet!==void 0&&!this.internals.worldReadOnly.has(r.name)})}let t=(r,s,o)=>{for(let i of[s,o])if(i!==void 0)for(let a of i.rows())e.push(a)};t("story",this.internals.shared.story,this.stores.story);for(let r of O){let s=new Set([...this.internals.shared[r].keys(),...this.stores[r].keys()]);for(let o of s)t(N(this.internals,r,o),this.internals.shared[r].get(o),this.stores[r].get(o))}return e}getProperty(e){this.assertOpen();let t=this.resolvePath(e),r=t.kind==="world"?this.internals.worldResolver.get(t.name):t.kind==="scope"?this.internals.registry.get(t.token,t.name):L(t.own,t.name)??L(t.shared,t.name);if(r===void 0)throw new v(`no property at "${e}"`);return r}setProperty(e,t){this.assertOpen();let r=this.resolvePath(e);if(r.kind==="world"){if(!this.internals.worldSet)throw new v("@world is read-only here: the host bound no write");this.internals.worldSet(r.name,t,!0);return}if(r.kind==="scope"){this.internals.registry.set(r.token,r.name,t,{host:!0});return}let s=L(r.own,r.name)!==void 0?r.own:L(r.shared,r.name)!==void 0?r.shared:void 0;if(s===void 0)throw new v(`no property at "${e}"`);s.set(r.name,t,{silent:!0,reason:"host setProperty",host:!0})}resolvePath(e){let t=e.split(".");if(t.length===2&&t[0]==="world")return{kind:"world",name:t[1]};if(t.length===2&&t[0]!=="story"&&this.internals.registry.has(t[0]))return{kind:"scope",token:t[0],name:t[1]};if(t.length===2&&t[0]==="story")return{kind:"bag",own:this.stores.story,shared:this.internals.shared.story,name:t[1]};if(t.length===3&&$t(t[0])){let r=t[0],[,s,o]=t,i=Ot(this.internals,r,s,o);i.legacy&&this.tracing&&this.emit({type:"diagnostic",where:"property address",message:Rt(this.internals,r,s,o)});let a=this.stores[r].get(i.id),d=this.internals.shared[r].get(i.id);if(a===void 0&&d===void 0)throw new v(`no ${r} store "${s}"`);return{kind:"bag",...a!==void 0?{own:a}:{},...d!==void 0?{shared:d}:{},name:o}}throw new v(`bad property path "${e}"`)}snapshot(e){return{...e?{props:gr(this.stores)}:{},turns:Object.fromEntries(this.turnCounts),prng:this.prng.state(),cooldowns:this.cooldowns,board:Object.fromEntries(this.boardContents),playLog:this.playLog}}restore(e){e.props!==void 0&&fr(this.stores,e.props),this.turnCounts=new Map(this.internals.bundle.boxes.map(t=>[t.id,0]));for(let[t,r]of Object.entries(e.turns??{}))this.turnCounts.has(t)&&this.turnCounts.set(t,r);this.prng=D(e.prng),this.cooldowns=e.cooldowns??{},this.playLog=e.playLog??[],this.rebuildPlayIndex(),this.boardContents=new Map(Object.entries(e.board??{}).filter(([t])=>this.internals.handsById.has(t)).map(([t,r])=>[t,r.filter(s=>this.internals.cardsById.has(s))]));for(let t of this.internals.handsById.keys())this.boardContents.has(t)||this.boardContents.set(t,[])}};var me=n=>n.map(e=>({name:e.name,type:e.type,default:e.default,...e.values!==void 0?{values:e.values}:{},...e.durable===!0?{durable:!0}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}})),Lt=n=>n.decks.reduce((e,t)=>e+t.cards.filter(r=>(r.durable??t.durable)===!0).length,0),yr=(n,e)=>n.template!==void 0?e.handTemplates.find(t=>t.id===n.template)?.properties??[]:n.properties??[],wr=(n,e,t)=>{let r=e.template!==void 0?e.chosen:e.rule?.bindings,s=[];for(let[o,i]of Object.entries(r??{})){if(!ce(i))continue;let a=Q(n,t).find(d=>d.id===o);a!==void 0&&s.push({group:f(a),from:i})}return s},br=(n,e)=>{if(n.slots!==void 0)return n.slots;let t=n.template!==void 0?e.handTemplates.find(r=>r.id===n.template)?.slots:n.rule?.slots;return t===void 0?"unbounded":t};function ye(n){let e=[],t=[],r=[{scope:"world",owner:"",properties:me(n.world.properties)},{scope:"story",owner:"",properties:me(n.story.properties)}],s={boxes:0,decks:0,cards:0,hands:0,templates:0,tagGroups:0};for(let i of n.boxes){let a=f(i),d=i.decks.reduce((c,p)=>c+p.cards.length,0);e.push({gameId:a,...i.title!==void 0?{title:i.title}:{},...i.usesMap===!0?{usesMap:!0}:{},ranking:{specificity:i.ranking.specificity},...i.turn!==void 0?{turn:{seconds:i.turn.seconds}}:{},...Lt(i)>0?{durableCards:Lt(i)}:{},tagGroups:i.tagGroups.map(c=>({gameId:f(c),tags:c.tags.map(p=>f(p))})),counts:{decks:i.decks.length,cards:d,hands:i.hands.length,templates:i.handTemplates.length,tagGroups:i.tagGroups.length}}),s.boxes+=1,s.decks+=i.decks.length,s.cards+=d,s.hands+=i.hands.length,s.templates+=i.handTemplates.length,s.tagGroups+=i.tagGroups.length;for(let c of i.hands){let p=c.template!==void 0?i.handTemplates.find(u=>u.id===c.template):void 0,g=wr(n,c,i);t.push({gameId:f(c),...c.title!==void 0?{title:c.title}:{},box:a,slots:br(c,i),...p!==void 0?{template:f(p)}:{},...g.length>0?{movable:g}:{}})}let l=(c,p,g,u)=>{g.length!==0&&r.push({scope:c,owner:p,box:a,...u!==void 0?{group:u}:{},properties:me(g)})};l("box",a,i.properties);for(let c of i.decks)l("deck",f(c),c.properties);for(let c of i.hands)l("hand",f(c),yr(c,i));for(let c of i.tagGroups)for(let p of c.tags)l("tag",f(p),p.properties??[],f(c))}let o=n.map;if(o!==void 0){let i=f(o.group);for(let a of o.group.tags){let d=a.properties??[];d.length>0&&r.push({scope:"tag",owner:f(a),group:i,properties:me(d)})}s.tagGroups+=1}return{identity:{schema:n.schema,project:n.content.project,version:n.content.version,hash:n.content.hash,metadata:n.metadata},totals:s,boxes:e,hands:t,properties:r,...o!==void 0?{map:{group:f(o.group),tags:o.group.tags.map(i=>f(i)),boxes:n.boxes.filter(i=>i.usesMap===!0).map(i=>f(i)),zones:o.geometry?.zones.length??0,backgrounds:o.geometry?.backgrounds?.length??0,sites:Object.fromEntries(Object.entries(o.geometry?.sites??{}).map(([i,a])=>[i,a.length]))}}:{}}}function It(n,e){let t={};for(let{bag:r}of[...n.listBags(),...e.listBags()])for(let s of r.rows())s.value!==void 0&&(t[s.path]=s.value);return Object.assign(t,At(Tt(n,e.id))),t}function Tt(n,e){return n.getFlow(e)!==void 0?n.saveFlow(e):void 0}function At(n){let e={};if(n===void 0)return e;for(let[t,r]of Object.entries(n.turns))e[`turn:${t}`]=r;for(let[t,r]of Object.entries(n.cooldowns))e[`cooldown:${t}`]=r;for(let[t,r]of Object.entries(n.board))e[`board:${t}`]=[...r];return e}function Dt(n,e,t={}){let r=e.id,s=()=>n.getFlow(r);return ee({mounts:()=>[...n.listBags(),...s()?.listBags()??[]].map(({bag:o})=>({bag:o})),extra:()=>At(Tt(n,r))},t)}function we(n,e){return JSON.stringify(_e(n,e),null,2)}function _e(n,e){return{schema:pe,engine:n.saveGame(),...e!==void 0?{world:e}:{}}}function Ge(n,e,t={}){if(!e||typeof e!="object"||e.schema!==pe||e.engine?.schema!==Y&&e.engine?.schema!==X)throw new Error(`not a storylets save (expected schema "${pe}")`);let r=n.loadGame(e.engine);return t.onReport?.(r),e.world}function be(n,e,t={}){let r;try{r=JSON.parse(e)}catch{throw new Error("not valid JSON")}return Ge(n,r,t)}var Nt="sl-inspector-style",vr=`
|
|
2
2
|
.sl-insp { font: 12px system-ui, sans-serif; color: var(--ink, #222); background: var(--surface, #fafafa);
|
|
3
3
|
border: 1px solid var(--line, #ccc); border-radius: 8px; padding: 10px 12px; max-width: 26rem; }
|
|
4
4
|
.sl-insp h3 { margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
.sl-insp .sl-ident { font-family: ui-monospace, monospace; font-size: 11px; }
|
|
28
28
|
.sl-insp .sl-ident b { font-weight: 600; }
|
|
29
29
|
.sl-insp .sl-note { color: var(--muted, #666); }
|
|
30
|
-
`;function se(){if(document.getElementById(
|
|
31
|
-
`)
|
|
32
|
-
`))});let
|
|
30
|
+
`;function se(){if(document.getElementById(Nt))return;let n=document.createElement("style");n.id=Nt,n.textContent=vr,document.head.append(n)}var xr=(n,e)=>JSON.stringify(n)===JSON.stringify(e),Sr=["deal","play","write","evict","turns","diagnostic"],Er={deal:"Deal",play:"Play",write:"Write",evict:"Evict",turns:"Turns",diagnostic:"Diag"},kr=n=>n.type==="peek"?"deal":n.type,Vt=n=>n===void 0?"<unset>":JSON.stringify(n);function qe(n){return Pr(n,"flow"in n&&n.flow?`${n.flow} `:"")}function Pr(n,e){let t=(n.turn!==void 0?`[${n.turn}] `:"[-] ")+e;switch(n.type){case"deal":{let r=n.cards.filter(s=>s.verdict==="dealt").map(s=>s.id);return`${t}deal ${n.hand}: ${r.length>0?r.join(", "):"(none)"} (${n.cards.length} considered)`}case"peek":{let r=Object.entries(n.criteria).map(([o,i])=>`${o}=${i}`).join(", "),s=n.cards.filter(o=>o.verdict==="dealt").map(o=>o.id);return`${t}peek ${n.box}${r?` [${r}]`:""}: ${s.length>0?s.join(", "):"(none)"} (${n.cards.length} considered)`}case"evict":return`${t}evict ${n.card} from ${n.hand} (${n.reason})`;case"play":return`${t}play ${n.card}${n.outcome===""?"":` -> ${n.outcome}`}`;case"write":return`${t}write ${n.path}: ${Vt(n.prev)} -> ${Vt(n.value)}`;case"turns":return`${t}turns ${n.box} -> ${n.turn}`;default:return`${t}diagnostic ${n.where}: ${n.message}`}}var Br=n=>{let e=n.split(".");return e.length===3?`${e[0]} ${e[1]}`:e[0]};function Ht(n,e,t={}){se();let r=e,s=()=>r,o=document.createElement("div");o.className="sl-insp";let i=document.createElement("div");i.className="sl-head";let a=document.createElement("h3");a.textContent=t.title??"Runtime state",i.append(a);let d=document.createElement("button");d.type="button",d.className="sl-save",d.textContent="Save state",d.addEventListener("click",()=>{let E=new Blob([we(n)],{type:"application/json"}),B=URL.createObjectURL(E),P=document.createElement("a");P.href=B,P.download="save.storyletsave",P.click(),URL.revokeObjectURL(B)}),i.append(d);let l=document.createElement("input");l.type="file",l.accept=".storyletsave,application/json",l.hidden=!0,l.addEventListener("change",()=>{let E=l.files?.[0];if(!E)return;let B=new FileReader;B.onload=()=>{try{be(n,String(B.result)),r=n.getFlow(e.id)??n.openFlow(e.id),ve()}catch(P){console.error("storylets inspector: load failed:",P instanceof Error?P.message:P)}l.value=""},B.readAsText(E)});let c=document.createElement("button");c.type="button",c.className="sl-load",c.textContent="Load state",c.addEventListener("click",()=>l.click()),i.append(c,l),o.append(i);let p=document.createElement("input");p.type="text",p.className="sl-filter",p.placeholder="Filter properties",o.append(p);let g=[],u=[],m="";for(let E of s().listProperties()){let B=Br(E.path);if(B!==m){let $=document.createElement("div");$.className="sl-group",$.textContent=B,o.append($),u.push({el:$,rows:[]}),m=B}let P=Cr(s,E,g);u[u.length-1].rows.push({el:P,text:`${E.name} ${E.path}`.toLowerCase()}),o.append(P)}p.addEventListener("input",()=>{let E=p.value.trim().toLowerCase();for(let B of u){let P=!1;for(let $ of B.rows){let R=E===""||$.text.includes(E);$.el.style.display=R?"":"none",P=P||R}B.el.style.display=P?"":"none"}});let h=document.createElement("div");h.className="sl-section",h.textContent="Turns (per box)";let x=document.createElement("div");x.className="sl-turns";let b=document.createElement("div");b.className="sl-section",b.textContent="Board";let w=document.createElement("div");w.className="sl-board",o.append(h,x,b,w);let y=(E,B,P)=>{let $=document.createElement("label");$.className=P;let R=document.createElement("input");return R.type="checkbox",R.checked=!0,R.addEventListener("change",()=>B(R.checked)),$.append(R,E),$},k=(E,B,P,$,R)=>{let Se=document.createElement("div");Se.className=`sl-section sl-${E}`,Se.textContent=B;let U=document.createElement("div");U.className=`sl-logbar sl-${E}`;let K=document.createElement("div");K.className=`sl-log sl-${E}`;let Ee=new Map,Xe=()=>P().filter(T=>Ee.get(kr(T))!==!1).map(qe),Ze=!0,et="",ke=(T=!1)=>{let q=P(),tt=`${q.length}:${q.length>0?q[q.length-1].seq:-1}`;if(!T&&tt===et)return;et=tt;let rt=Xe();K.textContent=rt.length>0?rt.join(`
|
|
31
|
+
`):R,Ze&&(K.scrollTop=K.scrollHeight)};for(let T of Sr)Ee.set(T,!0),U.append(y(Er[T],q=>{Ee.set(T,q),ke(!0)},"sl-logkind"));U.append(y("Autoscroll",T=>{Ze=T},"sl-logscroll"));let _=document.createElement("button");_.type="button",_.className="sl-logcopy",_.textContent="Copy",_.title="Copy the visible (filtered) log to the clipboard",_.addEventListener("click",()=>{navigator.clipboard?.writeText(Xe().join(`
|
|
32
|
+
`))});let G=document.createElement("button");return G.type="button",G.className="sl-logclear",G.textContent="Clear",G.title="Drop the retained log entries (cosmetic - no game state changes)",G.addEventListener("click",()=>{$(),ke(!0)}),U.append(_,G),o.append(Se,U,K),{render:ke}},I=k("flow","Log",()=>s().log(),()=>s().clearLog(),"(empty - new Engine(bundle, { log: true }) retains the flow log)"),ie=k("run","Run log (every flow)",()=>n.log(),()=>n.clearLog(),"(empty - new Engine(bundle, { log: true }) retains the run log)"),Ke=(E=!1)=>{ie.render(E),I.render(E)},Je=(E,B)=>{let P=document.createElement("div");P.className="sl-line",P.textContent=B,E.append(P)},Qe=()=>{x.textContent="";for(let E of s().listBoxes())Je(x,`${E.title??E.gameId}: turn ${E.turn}`);w.textContent="";for(let[E,B]of Object.entries(s().board())){let P=B.map($=>$.title??$.gameId);Je(w,`${E}: ${P.length>0?P.join(", "):"(empty)"}`)}},ve=()=>{for(let E of g)E.read();Qe(),Ke()};Qe(),Ke(!0);let xe,Ye=t.pollMs??250;return Ye>0&&(xe=setInterval(ve,Ye)),(t.container??document.body).append(o),{el:o,refresh:ve,destroy(){xe!==void 0&&clearInterval(xe),o.remove()}}}function Cr(n,e,t){let r=document.createElement("div");r.className="sl-row";let s=document.createElement("span");s.className="sl-name",s.textContent=e.name,s.title=e.path;let o=()=>{try{return n().getProperty(e.path)}catch{return}},i=()=>{},a=u=>{n().setProperty(e.path,u),i()},d=document.createElement("button");d.type="button",d.className="sl-reset",d.textContent="\u21BA",d.title="Reset to default",d.addEventListener("click",()=>a(e.default));let l,c,p=u=>document.activeElement===u;switch(e.type){case"boolean":{let u=document.createElement("input");u.type="checkbox",u.addEventListener("change",()=>a(u.checked)),l=u,c=()=>{p(u)||(u.checked=o()===!0)};break}case"number":{let u=document.createElement("input");u.type="number",u.addEventListener("change",()=>a(Number(u.value))),l=u,c=()=>{p(u)||(u.value=String(o()??0))};break}case"enum":case"quality":{let u=document.createElement("select");for(let m of(e.type==="quality"?e.stages:e.values)??[]){let h=document.createElement("option");h.value=m,h.textContent=m,u.append(h)}u.addEventListener("change",()=>a(u.value)),l=u,c=()=>{p(u)||(u.value=String(o()??""))};break}case"flags":{let u=document.createElement("input");u.type="text",u.placeholder="comma, separated, flags",u.addEventListener("change",()=>a(u.value.split(",").map(m=>m.trim()).filter(m=>m.length>0))),l=u,c=()=>{p(u)||(u.value=(o()??[]).join(", "))};break}default:{let u=document.createElement("input");u.type="text",u.addEventListener("change",()=>a(u.value)),l=u,c=()=>{p(u)||(u.value=String(o()??""))}}}let g=()=>{c(),d.disabled=xr(o(),e.default)};return i=g,g(),t.push({row:e,read:g}),r.append(s,l,d),r}var $r=n=>n===void 0?"<unset>":JSON.stringify(n);function ze(n){let e=n.values!==void 0&&n.values.length>0?` [${n.values.join(", ")}]`:"",t=n.durable===!0?" (durable)":"";return`${n.name}: ${n.type} = ${$r(n.default)}${e}${t}`}function We(n){if(n.scope==="world"||n.scope==="story")return n.scope;let e=n.group!==void 0?` (${n.group})`:"";return`${n.scope} ${n.owner}${e}`}var C=(n,e,t="sl-line")=>{let r=document.createElement("div");return r.className=t,r.textContent=e,n.append(r),r},oe=(n,e,t)=>{let r=document.createElement("details");r.className="sl-fold",r.open=t;let s=document.createElement("summary");s.textContent=e,r.append(s);let o=document.createElement("div");return r.append(o),n.append(r),o};function jt(n,e={}){se();let t=ye(n),r=e.open??!0,s=document.createElement("div");s.className="sl-insp";let o=document.createElement("div");o.className="sl-head";let i=document.createElement("h3");i.textContent=e.title??"Bundle",o.append(i),s.append(o);let{identity:a,totals:d}=t,l=document.createElement("div");l.className="sl-ident",s.append(l),C(l,`${a.project} ${a.version}`,"sl-line"),C(l,`schema ${a.schema}`,"sl-line sl-note"),C(l,`hash ${a.hash===""?"(none)":a.hash} - metadata ${a.metadata}`,"sl-line sl-note");let c=oe(s,"Hands (deal)",r);c.className="sl-hands",t.hands.length===0&&C(c,"(no hands - this bundle is peek-only)","sl-line sl-note");for(let h of t.hands){let x=h.template!==void 0?`, template ${h.template}`:"",b=h.movable===void 0?"":`, moves ${h.movable.map(w=>`${w.group} from ${w.from}`).join(" and ")}`;C(c,`${h.gameId}: box ${h.box}, slots ${h.slots}${x}${b}`+(h.title!==void 0?` - ${h.title}`:""))}let p=oe(s,"Tags by box (peek criteria)",r);p.className="sl-tags";for(let h of t.boxes){C(p,`${h.title??h.gameId}`,"sl-group"),h.tagGroups.length===0&&C(p," (no tag groups)","sl-line sl-note");for(let x of h.tagGroups)C(p,` ${x.gameId}: ${x.tags.length>0?x.tags.join(", "):"(no tags)"}`)}let g=oe(s,"Properties (declared)",r);g.className="sl-props";for(let h of t.properties){C(g,We(h),"sl-group"),h.properties.length===0&&C(g," (none declared)","sl-line sl-note");for(let x of h.properties)C(g,` ${ze(x)}`)}let u=t.map;if(u!==void 0){let h=oe(s,"Project map",r);h.className="sl-maps",C(h,`${u.group}: ${u.tags.join(", ")}`),C(h,`boxes on the map: ${u.boxes.length>0?u.boxes.join(", "):"none"}`);let x=Object.entries(u.sites).map(([b,w])=>`${b} ${w}`).join(", ");C(h,`geometry carried (the engine ignores it): zones ${u.zones}, pictures ${u.backgrounds}, hands ${x===""?"0":x}`,"sl-line sl-note")}let m=oe(s,"Counts",r);m.className="sl-counts",C(m,`boxes ${d.boxes} - decks ${d.decks} - cards ${d.cards}`),C(m,`hands ${d.hands} - templates ${d.templates} - tag groups ${d.tagGroups}`);for(let h of t.boxes)C(m,`${h.gameId}: decks ${h.counts.decks}, cards ${h.counts.cards}, hands ${h.counts.hands}, templates ${h.counts.templates}, tag groups ${h.counts.tagGroups}, ranking.specificity ${h.ranking.specificity}`+(h.turn!==void 0?`, turn = ${h.turn.seconds}s`:"")+(h.durableCards!==void 0?`, durable cards ${h.durableCards}`:""));return(e.container??document.body).append(s),{el:s,description:t,destroy(){s.remove()}}}var Or="ws://127.0.0.1:4472",Rr=new Set(["deal","play","evict","turns"]);function Ue(n){let e=n.id,t={};for(let[s,o]of Object.entries(n.board()))t[s]=o.map(i=>i.gameId);let r={};for(let s of n.listBoxes())r[s.gameId]=s.turn;return{t:"board",flow:e,hands:t,turns:r}}function Ft(n){let e=n.url??Or,t=n.WebSocket??globalThis.WebSocket,r=[],s=null,o=!1,i=n.build,a=null,d=null,l=new Set;if(!t)return{state:"closed",attach(){},detach(){},setBuild(){},close(){o=!0}};let c=()=>{if(!(!s||s.readyState!==1)){for(let w of r)try{s.send(w)}catch{}r=[]}},p=w=>{o||(r.push(JSON.stringify(w)),r.length>512&&r.splice(0,r.length-512),c())},g=()=>{try{return a?a.flows():[]}catch{return[]}},u=()=>{let w=g(),y={t:"hello",v:2,build:i,flows:w.map(I=>I.id)};n.project!==void 0&&(y.project=n.project);let k=w[0];if(k)try{y.boxes=k.listBoxes().map(I=>I.gameId)}catch{}l=new Set(w.map(I=>I.id));try{s?.send(JSON.stringify(y))}catch{}},m=w=>{try{p(Ue(w))}catch{}},h=()=>{let w=g(),y=new Set(w.map(k=>k.id));for(let k of w)l.has(k.id)||(l.add(k.id),p({t:"flowOpen",flow:k.id}),m(k));for(let k of[...l])y.has(k)||(l.delete(k),p({t:"flowClose",flow:k}))},x=(w,y)=>{try{if(h(),p({t:"trace",flow:w,event:y}),Rr.has(y.type)){let k=a?.getFlow(w);k&&m(k)}}catch{}};try{s=new t(e),s.addEventListener("open",()=>{u(),c()}),s.addEventListener("message",w=>{if(!(!n.onBundle||typeof w.data!="string"))try{let y=JSON.parse(w.data);y.t==="bundle"&&typeof y.build=="string"&&typeof y.data=="string"&&n.onBundle({build:y.build,data:y.data})}catch{}}),s.addEventListener("error",()=>{}),s.addEventListener("close",()=>{s=null,o=!0,r=[]})}catch{s=null,o=!0}let b=()=>{d?.(),d=null,a=null,l=new Set};return{get state(){return o?"closed":s!==null&&s.readyState===1?"connected":"connecting"},attach(w){if(!o){b(),a=w;try{d=w.subscribeTrace(x)}catch{a=null;return}l=new Set(g().map(y=>y.id));for(let y of g())m(y)}},detach:b,setBuild(w){if(!(o||w===i)&&(i=w,s&&s.readyState===1)){u();for(let y of g())m(y)}},close(){o=!0,b(),r=[];try{s?.close()}catch{}s=null}}}function _t(n,e,t={}){let r;try{r=JSON.parse(e)}catch{return{ok:!1,error:"pushed bundle is not valid JSON"}}try{let{engine:s,report:o}=n.hotSwap(r,t);return{ok:!0,engine:s,bundle:r,report:o}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Gt(n){let e=new F(n.world.properties,{normalise:t=>t});return{resolver:{get:t=>e.get(t),set:(t,r)=>{e.set(t,r,{host:!0})}},bag:e,values:()=>e.values,load:t=>e.load(t)}}return Jt(Mr);})();
|
|
33
33
|
//# sourceMappingURL=storyletengine.min.js.map
|