@net-mesh/browser 0.43.0 → 0.44.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.
@@ -1,2 +1,2 @@
1
- var _e=class{constructor(e=()=>{}){this.detach=e}detach;buffered=[];waiting=null;ended=!1;push(e){if(this.ended)return;let t=this.waiting;if(t){this.waiting=null,t({value:e,done:!1});return}this.buffered.push(e)}end(){if(this.ended)return;this.ended=!0;let e=this.waiting;e&&(this.waiting=null,e({value:void 0,done:!0}))}next(){let e=this.buffered.shift();if(e!==void 0)return Promise.resolve({value:e,done:!1});if(this.ended)return Promise.resolve({value:void 0,done:!0});let{promise:t,resolve:r}=Promise.withResolvers();return this.waiting=r,t}return(){return this.detach(),this.end(),Promise.resolve({value:void 0,done:!0})}[Symbol.asyncIterator](){return this}};function vt(n,e,t,r=[t]){return!n||!e||t.length===0||r.length===0||r[0]!==t||r.some(s=>s.length===0)?null:{bootstrapOk:!0,stunProbeFailed:!0,probed:t,probedAll:[...r]}}var z=class extends Error{constructor(e){super(e),this.name="LeafError"}},yt=class extends z{constructor(t){super(`wire: ${t}`);this.detail=t;this.name="WireError"}detail;kind="wire"},Ie=class extends z{constructor(t){super(`session: ${t}`);this.detail=t;this.name="SessionError"}detail;kind="session"},gt=class extends z{constructor(t){super(`control plane: ${t}`);this.detail=t;this.name="ControlPlaneError"}detail;kind="control-plane"},ge=class extends z{constructor(t){super(`identity: ${t}`);this.detail=t;this.name="IdentityError"}detail;kind="identity"},mt=class extends z{constructor(t,r){super(`ice configuration: the iceServers entry ${t} names this connection's peer RTC endpoint ${r}; a peer cannot be its own STUN server. Omit iceServers to use the STUN endpoint the anchor announces (the stun_addr field of GET /rtc/anchor), or name a STUN server that is not this peer`);this.entry=t;this.peerRtcAddr=r;this.name="IceServerConflictError"}entry;peerRtcAddr;kind="ice-server-conflict"},bt=class extends z{constructor(t,r=null){super(r===null?`not the leader: this tab holds generation ${t}`:`not the leader: this tab holds generation ${t}, the leader holds ${r}`);this.presented=t;this.current=r;this.name="NotLeaderError"}presented;current;kind="not-leader"},de=class extends z{constructor(t){super(`rtc: ${ui(t)}`);this.failure=t;this.name="RtcError",this.kind=ci[t.type]}failure;kind},St=class extends z{constructor(t){super(`rpc: ${pi(t)}`);this.failure=t;this.name="RpcError",this.kind=di[t.type]}failure;kind},$e=class extends z{constructor(t,r){super(t);this.cause=r;this.name="UnknownLeafError"}cause;kind="unknown"},te=class extends z{},ye=class extends te{constructor(t,r){super(r??`org:admission_denied:${ai[t]}`);this.coarse=t;this.name="OrgAdmissionDeniedError"}coarse;kind="org-admission-denied"},Ce=class extends ye{kind="org-revoked";constructor(e="org:admission_denied:denied"){super("denied",e),this.name="OrgRevokedError"}},je=class extends te{kind="org-timeout";constructor(e="org:rpc:timeout"){super(e),this.name="OrgTimeoutError"}},D=class extends te{kind="org-cancelled";constructor(e="org:rpc:cancelled"){super(e),this.name="OrgCancelledError"}},ne=class extends te{constructor(t,r="org:rpc:leader_lost"){super(r);this.generation=t;this.name="OrgLeaderLostError"}generation;kind="org-leader-lost"},He=class extends te{kind="org-session-lost";constructor(e="org:rpc:session_lost"){super(e),this.name="OrgSessionLostError"}},Ke=class extends te{constructor(t,r="org:rpc:indeterminate"){super(r);this.deadlineMs=t;this.name="OrgIndeterminateError"}deadlineMs;kind="org-indeterminate"},Xe=class extends te{constructor(t,r="org:rpc:refused"){super(r);this.status=t;this.name="OrgRefusedError"}status;kind="org-refused"},Pe=class extends te{kind="org-internal";constructor(e="org:rpc:internal"){super(e),this.name="OrgInternalError"}},Fe=class extends te{kind="org-malformed";constructor(e="org:rpc:malformed"){super(e),this.name="OrgMalformedError"}},Ot="org: the response sink is closed: the call was retired",si="org: the upload sink is closed: the call was retired",ii="org: the response sink is closed: the call's byte budget refused the item and retired the call",oi="org: the upload sink is closed: the call's byte budget refused the item and retired the call",or="org:",ai={denied:"denied","not-supported":"not_supported",unavailable:"unavailable"};function wt(n){let e=(n??"").trim();return e==="unavailable"?"unavailable":e==="not_supported"||e==="not-supported"?"not-supported":e==="\0"||e==="0"?"denied":e===""||e==="1"?"not-supported":e===""||e==="2"?"unavailable":"denied"}function li(n){switch(n){case"timeout":return new je;case"revoked":return new Ce;case"session-lost":return new He;case"leader-lost":return new ne("");case"cancelled":case"node-closed":case"replaced":return new D;case"resource-exhausted":return new ye("unavailable")}}function sn(n){let e=n.message;switch(n.kind){case"admission-denied":return new ye(wt(n.coarse),e);case"revoked":return e===void 0?new Ce:new Ce(e);case"timeout":return e===void 0?new je:new je(e);case"cancelled":return e===void 0?new D:new D(e);case"leader-lost":return new ne(n.generation??"",e);case"session-lost":return e===void 0?new He:new He(e);case"indeterminate":return new Ke(n.deadlineMs??0,e);case"refused":return new Xe(n.status??0,e);case"malformed":return e===void 0?new Fe:new Fe(e);case"internal":return e===void 0?new Pe:new Pe(e);default:return new Pe(`org:rpc:internal: unrecognized terminal kind ${JSON.stringify(n.kind)}`+(e===void 0?"":`: ${e}`))}}function xt(n){switch(n){case"timeout":case"cancelled":case"revoked":case"session-lost":case"leader-lost":case"node-closed":case"replaced":case"resource-exhausted":return n;default:return"replaced"}}function ar(n){if(/^org: .+ is closed: the call was retired$/.test(n))return new D(n);if(/^org: .+ is closed: the call's byte budget refused the item and retired the call$/.test(n))return new ye("unavailable",n);if(n.startsWith(or)){let t=n.slice(or.length),r=t.indexOf(":");if(r<=0)return null;let s=t.slice(0,r),i=t.slice(r+1),o=i.indexOf(":"),a=o===-1?i:i.slice(0,o);if(a.length===0)return null;if(s==="admission_denied")return new ye(wt(a),n);if(s!=="rpc")return null;switch(a){case"revoked":return new Ce(n);case"timeout":return new je(n);case"cancelled":return new D(n);case"leader_lost":case"leader-lost":return new ne("",n);case"session_lost":case"session-lost":return new He(n);case"indeterminate":return new Ke(0,n);case"refused":case"server_error":case"capability_denied":return new Xe(0,n);case"malformed":case"codec_encode":case"codec_decode":return new Fe(n);case"internal":case"no_route":case"transport":return new Pe(n);default:return null}}let e=/^rpc: refused \(9\): ([\s\S]*)$/.exec(n);return e?new ye(wt(e[1]),n):null}var ci={iceTimeout:"ice-timeout",udpBlocked:"udp-blocked",channelClosed:"channel-closed",unsupported:"rtc-unsupported"},di={refused:"rpc-refused",timeout:"rpc-timeout",sessionLost:"session-lost",leaderLost:"leader-lost",indeterminate:"rpc-indeterminate",malformed:"rpc-malformed"},lr="ICE did not connect inside the deadline (this does not establish that UDP is blocked)";function ui(n){switch(n.type){case"iceTimeout":return lr;case"udpBlocked":return`no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to ${n.evidence.probedAll.join(", ")} went unanswered`;case"channelClosed":return`the DataChannel closed: ${n.detail}`;case"unsupported":return`this browser refused the attempt: ${n.detail}`}}function pi(n){switch(n.type){case"refused":return`refused (${n.status}): ${n.message}`;case"timeout":return"the call's deadline elapsed";case"sessionLost":return"the session carrying the call went away";case"leaderLost":return`the leader holding generation ${n.generation} was replaced`;case"indeterminate":return`the local deadline of ${n.deadlineMs}ms elapsed before the tab running the node answered; the remote operation may still have executed (it was not retried)`;case"malformed":return`the reply did not decode: ${n.detail}`}}function S(n){if(n instanceof z)return n;let e=fi(n);return cr(e)??new $e(e,n)}function fi(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n!==null&&typeof n=="object"&&"message"in n){let e=n.message;if(typeof e=="string")return e}return String(n)}function cr(n){let e=ar(n);if(e!==null)return e;let t=ce(n,"rtc: ");if(t!==null){let d=dr(t);return d===null?null:new de(d)}let r=ce(n,"rpc: ");if(r!==null){let d=ur(r);return d===null?null:new St(d)}let s=ce(n,"wire: ");if(s!==null)return new yt(s);let i=ce(n,"session: ");if(i!==null)return new Ie(i);let o=ce(n,"control plane: ");if(o!==null)return new gt(o);let a=ce(n,"identity: ");if(a!==null)return new ge(a);let c=ce(n,"ice configuration: ");if(c!==null){let d=/^the iceServers entry (.+?) names this connection's peer RTC endpoint (.+?); a peer cannot be its own STUN server\./.exec(c);if(d)return new mt(d[1]??"",d[2]??"")}let l=/^not the leader: this tab holds generation (\d+)(?:, the leader holds (\d+))?$/.exec(n);if(l){let d=Number(l[1]),u=l[2]===void 0?null:Number(l[2]);return new bt(d,u)}return null}function dr(n){if(n===lr)return{type:"iceTimeout"};let e=/^no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to (.+) went unanswered$/.exec(n);if(e){let s=(e[1]??"").split(", "),i=s[0]??"",o=vt(!0,!0,i,s);return o===null?null:{type:"udpBlocked",evidence:o}}let t=ce(n,"the DataChannel closed: ");if(t!==null)return{type:"channelClosed",detail:t};let r=ce(n,"this browser refused the attempt: ");return r!==null?{type:"unsupported",detail:r}:null}function ur(n){let e=/^refused \((\d+)\): ([\s\S]*)$/.exec(n);if(e)return{type:"refused",status:Number(e[1]),message:e[2]??""};if(n==="the call's deadline elapsed")return{type:"timeout"};if(n==="the session carrying the call went away")return{type:"sessionLost"};let t=/^the leader holding generation (\d+) was replaced$/.exec(n);if(t)return{type:"leaderLost",generation:Number(t[1])};let r=/^the local deadline of (\d+)ms elapsed before the tab running the node answered; the remote operation may still have executed \(it was not retried\)$/.exec(n);if(r)return{type:"indeterminate",deadlineMs:Number(r[1])};let s=ce(n,"the reply did not decode: ");return s!==null?{type:"malformed",detail:s}:null}function hi(n){return n instanceof de&&n.failure.type==="udpBlocked"}function ce(n,e){return n.startsWith(e)?n.slice(e.length):null}var fr=["node_id","peer_node","channel_hash","origin_hash","stream_id","dialog","not_after","call_id","seq","generation","incarnation","version","from","to"];function ve(n){let e;try{e=Et(n)}catch{return{type:"unknown",tag:null,raw:n}}if(e===null||typeof e!="object")return{type:"unknown",tag:null,raw:e};let t=e,r=typeof t.type=="string"?t.type:null;switch(r){case"connected":return{type:"connected",nodeIdHex:$(t,"node_id_hex"),peerNode:$(t,"peer_node"),rtcAddr:ln(t,"rtc_addr"),rtcAddrs:yi(t)};case"disconnected":return{type:"disconnected",reason:$(t,"reason")};case"channel_message":return{type:"channel_message",channelHash:$(t,"channel_hash"),originHash:$(t,"origin_hash"),payload:an(t,"payload")};case"stream_data":return{type:"stream_data",peerNode:$(t,"peer_node"),incarnation:$(t,"incarnation"),streamId:$(t,"stream_id"),seq:on(t,"seq"),payload:an(t,"payload")};case"announcement":return{type:"announcement",nodeId:$(t,"node_id"),capabilities:gi(t,"capabilities"),rtcAddr:ln(t,"rtc_addr"),verified:t.verified===!0};case"signal":return{type:"signal",from:$(t,"from"),to:$(t,"to"),dialog:$(t,"dialog"),kind:$(t,"kind"),payload:an(t,"payload"),notAfter:$(t,"not_after")};case"rpc_response":return{type:"rpc_response",callId:$(t,"call_id"),status:on(t,"status")};case"dropped":return{type:"dropped",reason:$(t,"reason"),subprotocol:on(t,"subprotocol")};case"rtc_failure":return{type:"rtc_failure",error:S($(t,"error"))};default:return{type:"unknown",tag:r,raw:t}}}var Le=class{typed=new Map;any=new Set;queues=new Set;on(e,t){let r=this.typed.get(e)??new Set;this.typed.set(e,r);let s=t;return r.add(s),()=>{r.delete(s)}}onAny(e){return this.any.add(e),()=>{this.any.delete(e)}}events(){let e=new _e(()=>this.queues.delete(e));return this.queues.add(e),e}deliver(e,t){this.dispatch(t?t(e):ve(e))}dispatch(e){for(let t of this.typed.get(e.type)??[])pr(t,e);for(let t of this.any)pr(t,e);for(let t of this.queues)t.push(e)}close(){this.typed.clear(),this.any.clear();for(let e of[...this.queues])e.end();this.queues.clear()}};function pr(n,e){try{n(e)}catch(t){console.error("[@net-mesh/browser] event listener threw",t)}}function Et(n){let e=fr.join("|"),t=n.replace(new RegExp(`("(?:${e})"\\s*:\\s*)(\\d+)`,"g"),'$1"$2"');return JSON.parse(t)}function $(n,e){let t=n[e];return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):""}function yi(n){let e=n.rtc_addrs;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.length>0);let t=ln(n,"rtc_addr");return t===null?[]:[t]}function ln(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:null}function on(n,e){let t=n[e];if(typeof t=="number")return t;if(typeof t=="string"){let r=Number(t);return Number.isFinite(r)?r:0}return 0}function gi(n,e){let t=n[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function an(n,e){let t=n[e];return t instanceof Uint8Array?t:typeof t!="string"?new Uint8Array(0):hr(t)}function hr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function cn(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Te=class{live=new Set;add(e){this.live.add(e)}delete(e){this.live.delete(e)}retireAll(e){let t=[...this.live];this.live.clear();let r=[];for(let s of t)try{s.retire(e)}catch(i){r.push(i)}return r}},Oe=class{constructor(e,t,r){this.inner=e;this.onCancel=t;this.onDone=r}inner;onCancel;onDone;terminal=null;failure=null;handleDropped=!1;waiters=[];next(){if(this.failure!==null)return Promise.reject(this.failure);if(this.terminal!==null)return Promise.resolve(this.terminal);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={resolve:t,reject:r};return this.waiters.push(s),this.inner.next().then(i=>{Je(this.waiters,s);let o=mi(i);o.done&&this.complete(o),t(o)},i=>{Je(this.waiters,s);let o=S(i);this.fail(o),r(o)}),e}cancel(){this.retire(new D)}retire(e){this.terminal!==null||this.failure!==null||(this.dropHandle(),this.complete({done:!0,error:e}))}[Symbol.asyncIterator](){let e=!1;return{next:async()=>{if(e)return{done:!0,value:void 0};let t=await this.next();if(t.error!==void 0)throw t.error;return t.value===void 0?(e=!0,{done:!0,value:void 0}):(t.done&&(e=!0),{done:!1,value:t.value})},return:async()=>(e=!0,this.cancel(),{done:!0,value:void 0})}}complete(e){if(this.terminal!==null)return;this.terminal=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.resolve(e)}fail(e){if(this.terminal!==null||this.failure!==null)return;this.failure=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.onCancel()}catch{}}}},De=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;failure=null;handleDropped=!1;waiters=[];async send(e){if(this.failure!==null)throw this.failure;try{await this.inner.send(e)}catch(t){throw S(t)}}finish(){if(this.failure!==null)return Promise.reject(this.failure);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={reject:r};return this.waiters.push(s),this.inner.finish().then(i=>{Je(this.waiters,s),this.onDone?.(),t(i)},i=>{Je(this.waiters,s),this.onDone?.(),r(S(i))}),e}cancel(){this.retire(new D)}retire(e){if(this.failure!==null)return;if(this.failure=e,!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}},Me=class{constructor(e,t){this.inner=e;this.onDone=t;this.stream=new Oe(e.stream(),()=>this.dropHandle(),()=>this.onDone?.()),this.sink={send:async r=>{if(this.failure!==null)throw this.failure;try{await this.inner.send(r)}catch(s){throw S(s)}},finishSending:async()=>{if(this.failure!==null)throw this.failure;try{await this.inner.finish_sending()}catch(r){throw S(r)}},cancel:()=>{this.retire(new D)}}}inner;onDone;handleDropped=!1;failure=null;sink;stream;retire(e){this.failure??=e,this.dropHandle(),this.stream.retire(e),this.onDone?.()}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}}},Ge=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.verdict??=xt(t),this.verdict),()=>(this.verdict??="replaced",this.verdict))}inner;retired;verdict=null;async send(e){if(this.verdict!==null)throw new D(Ot);try{await this.inner.send(e)}catch(t){throw S(t)}}async close(){if(this.verdict!==null)throw new D(Ot);try{await this.inner.close()}catch(e){throw S(e)}}},ze=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.settle(xt(t)),this.verdict),()=>(this.settle("replaced"),this.verdict))}inner;retired;verdict=null;waiters=[];next(){if(this.verdict!==null)return Promise.resolve({done:!0});let{promise:e,resolve:t}=Promise.withResolvers();return this.waiters.push(t),this.inner.next().then(r=>{Je(this.waiters,t),t(bi(r))},()=>{Je(this.waiters,t),t({done:!0})}),e}[Symbol.asyncIterator](){return{next:async()=>{let e=await this.next();return e.done||e.value===void 0?{done:!0,value:void 0}:{done:!1,value:e.value}},return:async()=>({done:!0,value:void 0})}}settle(e){if(this.verdict!==null)return;this.verdict=e;let t=[...this.waiters];this.waiters.length=0;for(let r of t)r({done:!0})}},ee=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;closed=!1;get service(){return this.inner.service()}close(){this.closed||(this.closed=!0,this.onDone?.(),this.inner.close())}retire(e){this.close()}};function se(n){return{credentials:{membership:n.credentials.membership,dispatcher:n.credentials.dispatcher,...n.credentials.capabilityGrant===void 0?{}:{capabilityGrant:n.credentials.capabilityGrant},actingOrg:n.credentials.actingOrg,providerOwnerOrg:n.credentials.providerOwnerOrg,provider:n.credentials.provider,...n.credentials.proofTtlSecs===void 0?{}:{proofTtlSecs:n.credentials.proofTtlSecs}},...n.deadlineMs===void 0?{}:{deadlineMs:n.deadlineMs},...n.streamWindowInitial===void 0?{}:{streamWindowInitial:n.streamWindowInitial},...n.requestWindowInitial===void 0?{}:{requestWindowInitial:n.requestWindowInitial}}}function ie(n){return{ownerOrg:n.ownerOrg}}function Ye(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new $e("the caller attribution is not an OrgCaller object");let t=e;return{entity:String(t.entity??""),actingOrg:String(t.actingOrg??""),providerOrg:String(t.providerOrg??""),provider:String(t.provider??""),capability:String(t.capability??""),isSameOrg:t.isSameOrg===!0}}function Qe(n){return async(e,t)=>await n(Ye(e),t)}function Ze(n){return async(e,t,r)=>{await n(Ye(e),t,new Ge(r))}}function et(n){return async(e,t)=>await n(Ye(e),new ze(t))}function tt(n){return async(e,t,r)=>{await n(Ye(e),new ze(t),new Ge(r))}}function Je(n,e){let t=n.indexOf(e);t>=0&&n.splice(t,1)}function mi(n){return n.done?n.error!==void 0?{done:!0,error:sn(n.error)}:n.value===void 0?{done:!0}:{done:!0,value:n.value}:{done:!1,value:n.value}}function bi(n){return n.done?{done:!0}:{done:!1,value:n.value}}var kt=class extends Ie{constructor(e){super(e),this.name="StreamIdentityError"}},Si=1024,yr=1<<20,Ne=class{constructor(e,t,r="required"){this.inner=e;this.onClosed=t;if(this.wireId=gr(()=>e.stream_id_hex()),this.peerId=gr(()=>e.peer_node_hex()),r==="required"&&this.peerId===null)throw new kt("the stream did not report a readable peer, so its frames cannot be attributed");e.on_message(s=>this.receive(s))}inner;onClosed;queues=new Set;listeners=new Set;pending=[];pendingBytes=0;dropped=0;closed=!1;retiredBy=null;wireId;peerId;get droppedBeforeConsumer(){return this.dropped}get peerNode(){return this.inner.peer_node_hex()}get reliability(){return this.inner.is_reliable()?"reliable":"fireAndForget"}get streamId(){return this.inner.stream_id_hex()}async send(e){if(this.closed)throw new Ie(this.retiredBy??"the stream is closed");try{await this.inner.send(e)}catch(t){throw S(t)}}onMessage(e){this.listeners.add(e);let t=this.drainPending();for(let r of t)e(r);return()=>{this.listeners.delete(e)}}[Symbol.asyncIterator](){let e=new _e(()=>this.queues.delete(e));this.queues.add(e);let t=this.drainPending();for(let r of t)e.push(r);return this.closed&&e.end(),e}retire(e){this.closed||(this.retiredBy=e,this.close())}close(){if(!this.closed){this.closed=!0;for(let e of[...this.queues])e.end();this.queues.clear(),this.listeners.clear(),this.onClosed?.(),this.inner.close()}}drainPending(){return this.pendingBytes=0,this.pending.splice(0,this.pending.length)}receive(e){let t=this.decode(e);if(!(t===null||this.closed)){if(this.queues.size===0&&this.listeners.size===0){if(t.byteLength>yr){this.dropped+=1;return}for(this.pending.push(t),this.pendingBytes+=t.byteLength;this.pending.length>Si||this.pendingBytes>yr;){let r=this.pending.shift();this.pendingBytes-=r.byteLength,this.dropped+=1}return}for(let r of this.listeners)try{r(t)}catch(s){console.error("[@net-mesh/browser] stream listener threw",s)}for(let r of this.queues)r.push(t)}}decode(e){if(e instanceof Uint8Array)return e;if(typeof e!="string")return console.error("[@net-mesh/browser] stream callback received",typeof e,"not the leaf event JSON"),null;let t=ve(e);return t.type!=="stream_data"||!/^\d+$/.test(t.streamId)||this.wireId!==null&&BigInt(t.streamId)!==this.wireId||this.peerId!==null&&(!/^\d+$/.test(t.peerNode)||BigInt(t.peerNode)!==this.peerId)?null:t.payload}};function gr(n){let e;try{e=n()}catch{return null}return e===void 0||!/^[0-9a-fA-F]{1,16}$/.test(e)?null:BigInt(`0x${e}`)}var dn="no verified announcement for",Sr="no live attempt with",wr="no verified offer from",vr="is not the live attempt",Or=50,xr=5e3,mr=1e4;function br(n){switch(n.type){case"direct":case"iceTimeout":case"udpBlocked":return!0;case"superseded":return n.liveDialog!==null;default:return!1}}var We=class n{constructor(e=()=>null,t=()=>Date.now()){this.self=e;this.now=t}self;now;#e=new Map;#t=new Map;#r=new Map;noteOffer(e){let t=this.now();for(let[r,s]of this.#r)s<=t-mr&&this.#r.delete(r);this.#r.set(e.toLowerCase(),t)}connect(e,t,r,s){let i=e.toLowerCase(),o=this.#e.get(i);if(o!==void 0)return o;let a=this.#t.get(i),c=(async()=>{if(a!==void 0){let d=await a.catch(()=>null);if(d!==null&&br(d))return d}let l=await t();if(l!=null)return{type:"direct",peer:e,dialog:l};if(s===void 0||!this.#n(i))return r();if(this.#s(i,this.now()-mr)){let d=await s();if(d!==null&&br(d))return d}return this.#g(i,r,s)})();return n.#o(this.#e,i,c)}accept(e,t){let r=e.toLowerCase(),s=this.#t.get(r);if(s!==void 0)return s;let i=this.#e.get(r);return i!==void 0&&this.self()!==null?i:n.#o(this.#t,r,t())}#n(e){let t=this.self()?.toLowerCase();return t!==void 0&&t.length===e.length&&t>e}#s(e,t){let r=this.#r.get(e);return r===void 0||r<=t?!1:(this.#r.delete(e),!0)}async#g(e,t,r){let s=this.now(),i=t(),o=!1,a=()=>{o=!0};return i.then(a,a),(async()=>{for(;!o;){if(await un(),o||!this.#s(e,s))continue;let l=await r();if(l!==null)return l}return null})().then(l=>l??i)}static#o(e,t,r){e.set(t,r);let s=()=>{e.get(t)===r&&e.delete(t)};return r.then(s,s),r}},wi="1";function At(n,e){if(e.type!=="signal"||e.kind!==wi||e.from===void 0||!/^\d{1,20}$/.test(e.from))return;let t=BigInt(e.from);t>0xffffffffffffffffn||n.noteOffer(t.toString(16).padStart(16,"0"))}async function nt(n,e,t){let r;try{r=await e.offer(n)}catch(i){let o=S(i);if(o.message.includes(dn))return{type:"noAnnouncement",peer:n,detail:o.message};throw o}let s=await Pt(n,r,i=>i.state==="open",e,t);return s.type!=="direct"?s:_t(n,r,e)}async function rt(n,e,t){let r=null,s=Date.now()+xr;for(;;)try{r=await e.acceptOffer(n);break}catch(i){let o=S(i);if(o.message.includes(dn))return{type:"noAnnouncement",peer:n,detail:o.message};if(!o.message.includes(wr)||Date.now()>=s)throw o;await un()}return Pt(n,r,i=>i.direct,e,t)}async function Rt(n,e,t){let r;try{r=await e.acceptOffer(n)}catch{return null}return Pt(n,r,s=>s.direct,e,t)}async function _t(n,e,t){let r;try{r=await t.handshake(n,e)}catch(s){let i=Er(s,n,e);return i!==null?i:{type:"handshakeFailed",peer:n,dialog:e,detail:S(s).message}}return r!==e?{type:"superseded",peer:n,dialog:e,liveDialog:r}:{type:"direct",peer:n,dialog:e}}async function Pt(n,e,t,r,s){for(;;){let i;try{i=s(await r.candidate(n,e))}catch(o){let a=Er(o,n,e);if(a!==null)return a;throw S(o)}if(i.dialog!==e)return{type:"superseded",peer:n,dialog:e,liveDialog:i.dialog};if(t(i))return{type:"direct",peer:n,dialog:e};if(i.state==="iceTimeout")return{type:"iceTimeout",peer:n,dialog:e};if(i.state==="udpBlocked")return{type:"udpBlocked",peer:n,dialog:e};if(i.state==="failed")return{type:"handshakeFailed",peer:n,dialog:e,detail:i.candidateError??"the attempt reached its terminal transition without installing a session"};await un()}}function Er(n,e,t){let{message:r}=S(n);return r.includes(vr)?{type:"superseded",peer:e,dialog:t,liveDialog:vi(r)}:r.includes(Sr)?{type:"superseded",peer:e,dialog:t,liveDialog:null}:null}function vi(n){return/\(dialog ([0-9a-f]{16}) is\)/.exec(n)?.[1]??null}async function un(){let n=Promise.withResolvers();setTimeout(n.resolve,Or),await n.promise}function fn(n){let e=n.trim().split(/\s+/);return e.some((t,r)=>t==="typ"&&e[r+1]==="srflx")}function hn(n){return"candidate"in n?fn(n.candidate):"error"in n?n.error<yn:!1}function Ar(n){if(n.some(hn))return"answered";let e=n.some(o=>"candidate"in o);if(n.some(o=>"ice"in o&&o.ice==="failed")&&!e)return"notRun";let r=n.some(o=>"gathering"in o),s=n.some(o=>"error"in o&&o.error>=yn),i=n.some(o=>"candidate"in o&&Rr(o.candidate));return r&&!s&&i?"notRun":"unanswered"}function Rr(n){let e=n.trim().split(/\s+/),t=!1;for(let l=0;l+1<e.length;l+=1)e[l]==="typ"&&e[l+1]==="host"&&(t=!0);let r=e[4];if(!t||r===void 0)return!1;let s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(r);if(s!==null){let l=s.slice(1).map(Number);if(l.some(j=>j>255))return!1;let[d,u]=l,p=d===10||d===172&&u>=16&&u<=31||d===192&&u===168,f=d===127,y=d===169&&u===254,b=l.every(j=>j===0),k=l.every(j=>j===255),A=d===100&&(u&192)===64;return!(p||f||y||b||k||A)}if(!r.includes(":")||!/^[0-9a-f:.]+$/i.test(r))return!1;let i=r.toLowerCase();if(i==="::"||i==="::1")return!1;let o=Number.parseInt(i.startsWith(":")?"0":i.split(":")[0]??"0",16);if(Number.isNaN(o))return!1;let a=(o&65024)===64512,c=(o&65472)===65152;return!(a||c)}function Oi(n){return Ar(n)==="answered"}function _r(n){let{bootstrapOk:e,stunProbe:t,probed:r}=n;return r===null?{type:"iceTimeout"}:It({bootstrapOk:e,probes:[{probed:r,stunProbe:t}]})}function It(n){let{bootstrapOk:e,probes:t}=n;if(t.length===0||t.some(i=>i.stunProbe.type!=="unanswered"))return{type:"iceTimeout"};let r=t.map(i=>i.probed),s=vt(e,!0,r[0]??"",r);return s===null?{type:"iceTimeout"}:{type:"udpBlocked",evidence:s}}function xi(n){return new de(_r(n))}var Ei=2500,yn=700,pn=3478;async function Pr(n,e={}){let t=Ir(n);if(t===null)return{type:"notRun",reason:`not an address: ${n}`};let r=e.peerConnectionFactory??Ai();if(r===null)return{type:"unsupported",detail:"RTCPeerConnection is not available in this context"};let s=e.timeoutMs??Ei,{promise:i,resolve:o}=Promise.withResolvers(),a;try{a=r({iceServers:[{urls:t}],iceCandidatePoolSize:0})}catch(b){return{type:"unsupported",detail:String(b)}}let c=!1,l=b=>{c||(c=!0,o(b))},d=null,u=setTimeout(()=>l({type:"unanswered",detail:d??"no answer inside the probe deadline"}),s),p=!1,f=()=>{if(d===null&&p){l({type:"notRun",reason:'gathering completed beside a public host with no reflexive candidate and no "no response" report: inconclusive'});return}l({type:"unanswered",detail:d??"gathering completed with no reflexive candidate"})},y=!1;a.oniceconnectionstatechange=()=>{a.iceConnectionState==="failed"&&!y&&l({type:"notRun",reason:"the engine failed the probe connection before gathering any candidate"})},a.onicecandidate=b=>{let k=b.candidate;if(k===null){f();return}y=!0,Rr(k.candidate)&&(p=!0);let A=Cr(k);A!==null&&l({type:"reflexive",address:A})},a.onicecandidateerror=b=>{let k=b.errorCode,A=`${k}: ${b.errorText} (${b.url})`;if(hn({error:k})){l({type:"stunError",code:k,detail:A});return}d=A},a.onicegatheringstatechange=()=>{a.iceGatheringState==="complete"&&f()};try{a.createDataChannel("net-udp-probe"),await a.setLocalDescription(await a.createOffer())}catch(b){l({type:"unsupported",detail:String(b)})}try{return await i}finally{clearTimeout(u),a.onicecandidate=null,a.onicecandidateerror=null,a.oniceconnectionstatechange=null,a.onicegatheringstatechange=null,a.close()}}async function gn(n,e={}){return Promise.all(n.map(async t=>({probed:t,stunProbe:await Pr(t,e)})))}var ki=3e3;async function mn(n,e={}){let t=e.fetchImpl??globalThis.fetch;if(typeof t!="function")return!1;try{return await t(n,{method:"GET",mode:"no-cors",cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(e.timeoutMs??ki)}),!0}catch{return!1}}function Ir(n){let e=n.trim();if(e.length===0)return null;if(e.startsWith("stun:")||e.startsWith("stuns:"))return e;let t=/^\[([0-9a-fA-F:.]+)\](?::(\d+))?$/.exec(e);if(t)return`stun:[${t[1]??""}]:${t[2]??pn}`;if((e.match(/:/g)?.length??0)>1)return`stun:[${e}]:${pn}`;let r=/^([A-Za-z0-9._-]+)(?::(\d+))?$/.exec(e);return r===null?null:`stun:${r[1]??""}:${r[2]??pn}`}function Cr(n){return n.type==="srflx"?n.address??kr(n.candidate):n.type!==null?null:fn(n.candidate)?kr(n.candidate):null}function kr(n){let e=n.split(" "),t=e[4]??"",r=e[5]??"";return r.length>0?`${t}:${r}`:t}function Ai(){return typeof RTCPeerConnection>"u"?null:n=>new RTCPeerConnection(n)}var bn=new Map;async function st(n={}){if(n.wasm)return n.wasm;let e=n.wasmModule??new URL("./net_leaf.js",import.meta.url).href,t=`${e}|${String(n.wasmUrl??"")}`,r=bn.get(t);if(r)return r;let s=Ri(e,n.wasmUrl);bn.set(t,s);try{return await s}catch(i){throw bn.delete(t),i}}async function Ri(n,e){let t=await import(n),r=_i(t,n);return r.default&&await r.default(e===void 0?void 0:{module_or_path:e}),r}function _i(n,e){if(n===null||typeof n!="object"||!("LeafNode"in n))throw new Error(`${e} is not a net-mesh-leaf module: no LeafNode export`);let t=n.LeafNode;if(typeof t!="function"||!("connect"in t))throw new Error(`${e} exports a LeafNode without a static connect()`);if(typeof t.connect!="function")throw new Error(`${e} exports a LeafNode whose connect is not callable`);return n}function xe(n,e){if(typeof n=="string")return n;let t=typeof n=="object"&&n!==null?Object.prototype.toString.call(n):String(n);throw new TypeError(`${t} is not a ${e} id: a ${e} id crosses this boundary as 16 hex digits as a STRING \u2014 the spelling this boundary hands out; a ${typeof n} is refused rather than coerced, because a number cannot carry a u64 id`)}function Hr(n){if(!/^\d+$/.test(n))throw new TypeError(`a decimal node id is digits only, got ${JSON.stringify(n)}`);let e=BigInt(n);if(e>0xffffffffffffffffn)throw new TypeError(`${n} does not fit in a u64 node id`);return e.toString(16).padStart(16,"0")}var jt=class{constructor(e,t,r,s){this.inner=e;this.bootstrapUrl=t;this.failureTyping=r;this.nodeId=e.node_id_hex(),this.anchorRtcAddr=s,e.on_event(i=>this.ingest(i))}inner;bootstrapUrl;failureTyping;hub=new Le;nodeId;closed=!1;streams=new Set;attempts=new We(()=>this.nodeId);orgHandles=new Te;anchorRtcAddr;anchorRtcAddrs=[];bootstrapObserved=!1;releaseIdentity=null;releaseIdentityOnClose(e){this.releaseIdentity=e}nodeIdHex(){return this.nodeId}anchorIdHex(){return this.inner.anchor_id_hex()}originHashHex(){return this.inner.origin_hash_hex()}async enroll(){try{await this.inner.enroll()}catch(e){throw S(e)}}isEnrolled(){return this.inner.is_enrolled()}async call(e,t,r){try{return await this.inner.call(e,t,r)}catch(s){throw S(s)}}async subscribe(e){try{await this.inner.subscribe(e)}catch(t){throw S(t)}}async publish(e,t){try{await this.inner.publish(e,t)}catch(r){throw S(r)}}openStream(e){let t;try{t=this.inner.open_stream(e)}catch(s){throw S(s)}let r=new Ne(t,()=>this.streams.delete(r));return this.streams.add(r),r}async callOrg(e,t,r){try{return await this.inner.call_org(e,t,se(r))}catch(s){throw S(s)}}async callOrgStreaming(e,t,r){try{let s=await this.inner.call_org_streaming(e,t,se(r)),i=new Oe(s,()=>s.cancel(),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(s){throw S(s)}}async callOrgClientStream(e,t){try{let r=await this.inner.call_org_client_stream(e,se(t)),s=new De(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}async callOrgDuplex(e,t){try{let r=await this.inner.call_org_duplex(e,se(t)),s=new Me(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}serveOrg(e,t,r,s){try{let i=new ee(this.inner.serve_org(e,t,Qe(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new ee(this.inner.serve_org_streaming(e,t,Ze(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new ee(this.inner.serve_org_client_stream(e,t,et(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new ee(this.inner.serve_org_duplex(e,t,tt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}async signal(e,t,r,s){try{await this.inner.signal(xe(e,"peer"),xe(t,"dialog"),r,s)}catch(i){throw S(i)}}async connectPeer(e){let t;try{t=xe(e,"peer")}catch(r){throw S(r)}return this.attempts.connect(e,()=>{try{return this.inner.peer_direct_dialog(t)}catch(r){throw S(r)}},()=>nt(e,this.peerPrimitives(),me),()=>Rt(e,this.peerPrimitives(),me))}peerPrimitives(){return{offer:e=>this.inner.peer_offer(e),acceptOffer:e=>this.inner.peer_accept_offer(e),candidate:(e,t)=>this.inner.peer_candidate_in(e,t),handshake:(e,t)=>this.inner.peer_handshake_in(e,t)}}async handshakePeer(e,t){return _t(e,t,this.peerPrimitives())}async acceptPeer(e){return this.attempts.accept(e,()=>rt(e,this.peerPrimitives(),me))}async peerAttempt(e){try{return me(await this.inner.peer_candidate(e))}catch(t){throw S(t)}}counters(){return Lt(this.inner.counters_json())}rtcStats(){return Lr(this.inner.rtc_stats_json())}enableNetworkRetry(){try{this.inner.arm_network_retry()}catch(e){throw S(e)}}retryReport(){return Tr(this.inner.retry_report())}async announce(e){try{await this.inner.announce([...e])}catch(t){throw S(t)}}async query(e){let t;try{t=await this.inner.query(e)}catch(r){throw S(r)}return Tt(t)}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}events(){return this.hub.events()}async refineIceFailure(e){return wn(e,{bootstrapUrl:this.bootstrapUrl,bootstrapObserved:this.bootstrapObserved,anchorRtcAddr:this.anchorRtcAddr,anchorRtcAddrs:this.anchorRtcAddrs,failureTyping:this.failureTyping})}close(){if(this.closed)return;this.closed=!0;let e=this.releaseIdentity;this.releaseIdentity=null,queueMicrotask(()=>e?.());let t=[];for(let s of this.orgHandles.retireAll(new D("org:rpc:cancelled: the node is closed")))t.push(S(s));let r=[...this.streams];this.streams.clear();for(let s of r)try{s.close()}catch(i){t.push(S(i))}try{this.hub.close()}catch(s){t.push(S(s))}try{this.inner.close()}catch(s){t.push(S(s))}if(t.length>0)throw new AggregateError(t,`close: ${t.length} of this node's teardown steps failed`)}ingest(e){let t=ve(e);t.type==="connected"&&(this.bootstrapObserved=!0,t.rtcAddr!==null&&(this.anchorRtcAddr=t.rtcAddr),t.rtcAddrs.length>0&&(this.anchorRtcAddrs=t.rtcAddrs)),At(this.attempts,t),this.hub.dispatch(t)}};async function Pi(n){let e=Ht(n),t=n.failureTyping??{},r=await st(n),s=e.entitySecretHex!==void 0&&n.lockIdentity!==!1?await Ii(e.entitySecretHex):null;try{let i=await r.LeafNode.connect(e),o=new jt(i,n.bootstrapUrl??null,t,n.anchorRtcAddr??null);return o.releaseIdentityOnClose(s),o}catch(i){throw s?.(),await wn(S(i),{bootstrapUrl:n.bootstrapUrl??null,bootstrapObserved:!1,anchorRtcAddr:n.anchorRtcAddr??null,failureTyping:t})}}async function Sn(n){let e=globalThis.crypto?.subtle;if(e===void 0)return null;let t=n.toLowerCase(),r=new Uint8Array(await e.digest("SHA-256",new TextEncoder().encode(`net-mesh:identity:${t}`)));return`net-mesh:identity:${Array.from(r.subarray(0,16),s=>s.toString(16).padStart(2,"0")).join("")}`}async function Ii(n){let e=globalThis.navigator?.locks;if(e===void 0)return null;let t=await Sn(n);if(t===null)return null;let r=await new Promise((s,i)=>{let o,a=new Promise(c=>{o=c});e.request(t,{ifAvailable:!0},async c=>{if(c===null){s("busy");return}s(o),await a}).catch(i)});if(r==="busy")throw new ge("this identity is already connected in another tab or window of this browser; two nodes with one identity evict each other at the anchor (use openSession() to share one node across tabs, or pass lockIdentity: false)");return r}function Ht(n){return{credentialB64:Hi(n),origin:n.origin??Li(),...n.bootstrapUrl===void 0?{}:{bootstrapUrl:n.bootstrapUrl},...n.iceServers?{iceServers:n.iceServers}:{},...Ci(n)}}function Lt(n){let e=JSON.parse(n);if(e===null||typeof e!="object")return{};let t={},r=(s,i)=>{for(let[o,a]of Object.entries(s))a!==null&&typeof a=="object"&&!Array.isArray(a)?r(a,`${i}${o}.`):t[`${i}${o}`]=typeof a=="string"?a:String(a)};return r(e,""),t}function me(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`peer_candidate did not answer an object: ${n}`);let t=e,r=t.state;if(r!=="gathering"&&r!=="open"&&r!=="iceTimeout"&&r!=="udpBlocked"&&r!=="failed")throw new TypeError(`peer_candidate answered an unknown state: ${String(r)}`);let s=t.candidateError;return{dialog:String(t.dialog??""),state:r,sent:Number(t.sent??0),applied:Number(t.applied??0),answered:t.answered===!0,direct:t.direct===!0,remainingMs:String(t.remainingMs??"0"),candidateError:typeof s=="string"?s:null}}function Lr(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`rtc_stats_json did not answer an object: ${n}`);let t={},r={};for(let[s,i]of Object.entries(e)){if(s==="not_applicable"){if(i===null||typeof i!="object")continue;for(let[o,a]of Object.entries(i))r[o]=String(a);continue}t[s]=typeof i=="string"?i:String(i)}return{counters:t,notApplicable:r}}function Tr(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`retry_report did not answer an object: ${n}`);let t=e;return{armed:t.armed===!0,online:String(t.online??"0"),iceFailed:String(t.iceFailed??"0"),triggers:String(t.triggers??"0"),started:String(t.started??"0"),coalesced:String(t.coalesced??"0"),notEligible:String(t.notEligible??"0"),openEpisodes:Number(t.openEpisodes??0),owned:Number(t.owned??0),last:typeof t.last=="string"?t.last:null}}async function wn(n,e){if(!(n instanceof de)||n.failure.type!=="iceTimeout"||e.failureTyping.probeOnIceTimeout===!1)return n;let t=e.anchorRtcAddrs!==void 0&&e.anchorRtcAddrs.length>0?e.anchorRtcAddrs:e.anchorRtcAddr!==null?[e.anchorRtcAddr]:[];if(t.length===0)return n;let r=await gn(t,e.failureTyping.stun);if(r.some(i=>i.stunProbe.type!=="unanswered"))return n;let s=e.bootstrapObserved||e.bootstrapUrl!==null&&await mn(e.bootstrapUrl,e.failureTyping.bootstrap);return new de(It({bootstrapOk:s,probes:r}))}function Tt(n){let e=Et(n);if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s={...r},i=s.capabilities,o=ji(s.node_id);t.push({nodeId:o,peerIdHex:Hr(o),entityId:Ct(s.entity_id),capabilities:Array.isArray(i)?i.filter(a=>typeof a=="string"):[],rtcAddr:Ct(s.rtc_addr),noisePubkey:Ct(s.noise_pubkey),version:Ct(s.version)})}return t}var jr=/^[0-9a-fA-F]{64}$/;function Ci(n){let{entitySecretHex:e,noiseSecretHex:t}=n;if(e===void 0){if(t!==void 0)throw new ge("noiseSecretHex was supplied without entitySecretHex: the leaf would generate the entity half, so the identity would not be the one you meant to inject");return{}}if(!jr.test(e))throw new ge(`entitySecretHex must be 32 bytes of hex (64 hex digits), got ${e.length} characters`);if(t===void 0)return{entitySecretHex:e};if(!jr.test(t))throw new ge(`noiseSecretHex must be 32 bytes of hex (64 hex digits), got ${t.length} characters`);return{entitySecretHex:e,noiseSecretHex:t}}function ji(n){return typeof n=="string"?n:typeof n=="number"?String(n):""}function Ct(n){return typeof n=="string"?n.length>0?n:null:typeof n=="number"?String(n):null}function Hi(n){if(n.credentialB64!==void 0)return n.credentialB64;let e=n.credential;if(typeof e=="string")return e;if(e instanceof Uint8Array)return cn(e);throw new Error("connect() needs a credential: pass credentialB64 or credential")}function Li(){let n=globalThis.location?.origin;if(typeof n=="string"&&n.length>0)return n;throw new Error("connect() needs an origin: there is no location.origin in this context")}function vn(n){let e=ve(n);return e.type!=="unknown"?e:Ti(e)??e}function On(n){switch(n.type){case"leader_changed":case"subscription_restored":case"leader_lost":case"generation_fenced":case"not_leader":case"promotion_failed":return!0;default:return!1}}function Ti(n){let e=n.raw;if(e===null||typeof e!="object")return null;let t={...e};switch(n.tag){case"leader_changed":return{type:"leader_changed",generation:qe(t.generation)};case"subscription_restored":return{type:"subscription_restored",channel:typeof t.channel=="string"?t.channel:""};case"leader_lost":{let r=Number(t.failed);return{type:"leader_lost",generation:qe(t.generation),failed:Number.isFinite(r)?r:0}}case"generation_fenced":return{type:"generation_fenced",presented:qe(t.presented),current:qe(t.current)};case"not_leader":return{type:"not_leader",presented:qe(t.presented),current:qe(t.current)};case"promotion_failed":return{type:"promotion_failed",generation:qe(t.generation),detail:typeof t.detail=="string"?t.detail:""};default:return null}}function qe(n){return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):"0"}function xn(n){let e=n.MeshSession;if(!(e!==null&&(typeof e=="object"||typeof e=="function")&&"open"in e&&typeof e.open=="function"))throw new Error("this net-mesh-leaf bundle has no MeshSession: leader election and the follower proxy need a wasm build from Stage 5 slice 3 or later");return n}var Dr="stale stream handle: the leader changed; reopen the stream",Dt=class{constructor(e){this.inner=e;this.streamGeneration=e.generation(),e.on_event(t=>this.hub.deliver(t,vn)),this.hub.onAny(t=>At(this.attempts,t)),this.hub.onAny(t=>{if(t.type==="leader_lost"||t.type==="not_leader"){this.orgHandles.retireAll(new ne(this.streamGeneration)),this.endStreams(Dr);return}let r=this.inner.generation();if(r===this.streamGeneration)return;let s=this.streamGeneration;this.streamGeneration=r,this.orgHandles.retireAll(new ne(s)),this.endStreams(Dr)})}inner;hub=new Le;streams=new Set;attempts=new We(()=>this.inner.node_id_hex()??null);streamGeneration;orgHandles=new Te;closed=!1;role(){return this.inner.role()==="leader"?"leader":"follower"}generation(){return this.inner.generation()}nodeIdHex(){return this.inner.node_id_hex()??null}fingerprint(){return this.inner.fingerprint()}scope(){return this.inner.scope()}interruptionMs(){return this.inner.interruption_ms()??null}async call(e,t,r){return await this.guard(()=>this.inner.call(e,t,r))}async subscribe(e){await this.guard(()=>this.inner.subscribe(e))}async unsubscribe(e){await this.guard(()=>this.inner.unsubscribe(e))}async publish(e,t){await this.guard(()=>this.inner.publish(e,t))}async announce(e){await this.guard(()=>this.inner.announce([...e]))}async query(e){return Tt(await this.guard(()=>this.inner.query(e)))}async counters(){return Lt(await this.guard(()=>this.inner.counters_json()))}async enroll(){await this.guard(()=>this.inner.enroll())}async isEnrolled(){return await this.guard(()=>this.inner.is_enrolled())}async signal(e,t,r,s){await this.guard(()=>this.inner.signal(xe(e,"peer"),xe(t,"dialog"),r,s))}async connectPeer(e){return this.attempts.connect(e,async()=>{try{return await this.inner.peer_direct_dialog(e)??void 0}catch{return}},()=>nt(e,this.peerPrimitives(),me),()=>Rt(e,this.peerPrimitives(),me))}async acceptPeer(e){return this.attempts.accept(e,()=>rt(e,this.peerPrimitives(),me))}peerPrimitives(){return{offer:e=>this.guard(()=>this.inner.peer_offer(e)),acceptOffer:e=>this.guard(()=>this.inner.peer_accept_offer(e)),candidate:(e,t)=>this.guard(()=>this.inner.peer_candidate(e,t)),handshake:(e,t)=>this.guard(()=>this.inner.peer_handshake(e,t))}}async openStream(e){let t=this.inner.generation(),r=new Ne(await this.guard(()=>this.inner.open_stream(e)));return this.closed||this.inner.generation()!==t?(r.close(),r):(this.streams.add(r),r)}async callOrg(e,t,r){return await this.guard(()=>this.inner.call_org(e,t,se(r)))}async callOrgStreaming(e,t,r){let s=this.inner.generation(),i;try{let o=await this.inner.call_org_streaming(e,t,se(r));i=new Oe(o,()=>o.cancel(),()=>this.orgHandles.delete(i))}catch(o){throw S(o)}return this.closed||this.inner.generation()!==s?(i.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(s)),i):(this.orgHandles.add(i),i)}async callOrgClientStream(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_client_stream(e,se(t));s=new De(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(r)),s):(this.orgHandles.add(s),s)}async callOrgDuplex(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_duplex(e,se(t));s=new Me(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(r)),s):(this.orgHandles.add(s),s)}serveOrg(e,t,r,s){try{let i=new ee(this.inner.serve_org(e,t,Qe(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new ee(this.inner.serve_org_streaming(e,t,Ze(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new ee(this.inner.serve_org_client_stream(e,t,et(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new ee(this.inner.serve_org_duplex(e,t,tt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}onLifecycle(e){return this.hub.onAny(t=>{On(t)&&e(t)})}events(){return this.hub.events()}close(){this.closed||(this.closed=!0,this.orgHandles.retireAll(new D("org:rpc:cancelled: the session is closed")),this.endStreams(),this.hub.close(),this.inner.close())}endStreams(e){let t=[...this.streams];this.streams.clear();for(let r of t)e===void 0?r.close():r.retire(e)}async guard(e){try{return await e()}catch(t){throw S(t)}}};async function Di(n){let e=xn(await st(n)),t={...Ht(n),...n.capabilities?{capabilities:[...n.capabilities]}:{},...n.subscriptions?{subscriptions:[...n.subscriptions]}:{},...n.dbName===void 0?{}:{dbName:n.dbName},...n.lockScope===void 0?{}:{lockScope:n.lockScope}};if(t.lockScope===void 0&&t.entitySecretHex!==void 0&&n.lockIdentity!==!1){let r=await Sn(t.entitySecretHex);r!==null&&(t.lockScope=r)}try{return new Dt(await e.MeshSession.open(t))}catch(r){throw S(r)}}var En=["invalid-data","version-mismatch","forbidden","not-ready","capacity","timeout","aborted","indeterminate","owner-lost","closed","action-rejected","result-expired"],h=class extends Error{code;constructor(e,t,r){super(t,r),this.name="StoreError",this.code=e}};function it(n){return(n instanceof Error?n.message:String(n)).includes("stale stream handle")}var Mt=Object.freeze({$hidden:!0});function Nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.keys(n).length===1&&n.$hidden===!0}function Mi(n){return e=>Nt(e)?Mt:n(e)}var Mr=Object.freeze({"card-game":Object.freeze({"players.*.hand":"owner",deck:"nobody","deck.length":"everyone"})}),Ni=/^(\*|[^.*]+)$/;function Ee(n){let e;if(n==="open")e={};else if(typeof n=="string"){let s=Mr[n];if(s===void 0)throw new h("invalid-data",`unknown visibility preset '${n}'`);e={...s}}else if(typeof n=="object"&&n!==null){let{preset:s,...i}=n;if(e={},s!==void 0){let o=Mr[s];if(o===void 0)throw new h("invalid-data",`unknown visibility preset '${String(s)}'`);Object.assign(e,o)}Object.assign(e,i)}else throw new h("invalid-data","visibility is a preset name or an object of path \u2192 rule");let t=[],r=!1;for(let[s,i]of Object.entries(e)){let o=s.split(".");if(s.length===0||!o.every(l=>Ni.test(l)))throw new h("invalid-data",`visibility path '${s}' is not dot-separated keys and '*'`);let a=o.length>1&&o[o.length-1]==="length";if(!(i==="everyone"||i==="nobody"||i==="owner"||Array.isArray(i)&&i.length>0&&i.every(l=>typeof l=="string"&&l.length>0)))throw new h("invalid-data",`visibility rule for '${s}' must be 'everyone', 'nobody', 'owner' or a non-empty list of audiences`);if(i==="owner"){if(!o.includes("*"))throw new h("invalid-data",`'owner' needs a '*' in the path to name the owner: '${s}'`);r=!0}t.push(Object.freeze({path:s,segments:Object.freeze(o),rule:i,counts:a}))}return t.sort((s,i)=>s.segments.length-i.segments.length),Object.freeze({rules:Object.freeze(t),perPlayer:r})}function Nr(n,e,t){return n==="everyone"?!0:n==="nobody"||t===null?!1:n==="owner"?e[0]===t.peer:n.some(r=>t.audience.includes(r))}function Wi(n,e){let t=[],r=(s,i,o,a)=>{if(i===e.length){t.push({keys:[...o],captures:[...a],value:s});return}if(typeof s!="object"||s===null)return;let c=e[i];if(c==="*"){let l=Array.isArray(s)?s.map((d,u)=>[u,d]):Object.entries(s);for(let[d,u]of l)r(u,i+1,[...o,d],[...a,String(d)]);return}Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,c)||r(s[c],i+1,[...o,c],a)};return r(n,0,[],[]),t}var kn=Symbol("drop");function qi(n,e,t){let r=n;for(let s of e){let i=r.children.get(s);i===void 0&&(i={children:new Map},r.children.set(s,i)),r=i}r.value=t}function An(n,e){if("value"in e)return e.value;if(e.children.size===0||typeof n!="object"||n===null)return n;if(Array.isArray(n)){let r=[];return n.forEach((s,i)=>{let o=e.children.get(i),a=o===void 0?s:An(s,o);a!==kn&&r.push(a)}),r}let t={};for(let[r,s]of Object.entries(n)){let i=e.children.get(r),o=i===void 0?s:An(s,i);o!==kn&&(t[r]=o)}return t}var Wr="\0";function ke(n,e,t){if(n.rules.length===0)return e;let r={children:new Map},s=new Set,i=!1;for(let o of n.rules){if(o.counts)continue;let a=n.rules.find(l=>l.counts&&l.segments.length===o.segments.length+1&&l.segments.slice(0,-1).every((d,u)=>d===o.segments[u])),c=o.segments[o.segments.length-1]==="*";for(let l of Wi(e,o.segments)){let d="",u=!1;for(let f=0;f<l.keys.length-1&&!u;f+=1)d=f===0?String(l.keys[0]):`${d}${Wr}${String(l.keys[f])}`,u=s.has(d);if(u||Nr(o.rule,l.captures,t))continue;let p=c?kn:Mt;a!==void 0&&Array.isArray(l.value)&&Nr(a.rule,l.captures,t)&&(p=l.value.map(()=>Mt)),qi(r,l.keys,p),s.add(l.keys.map(String).join(Wr)),i=!0}}return i?An(e,r):e}function qr(n,e,t){return n.visibility===void 0?e:ke(Ee(n.visibility),e,t)}function Ui(n,e,t,r){let s=qr(n,e,t);for(let i of r){let o=s;for(let c of i.split(".")){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,c)){o=void 0;break}o=o[c]}if(o!==void 0&&!Nt(o)&&!(Array.isArray(o)&&o.every(c=>Nt(c))))throw new Error(`'${i}' is visible to ${t===null?"nobody in particular":t.peer}`)}}function Bi(n){if(n.id.length===0)throw new h("invalid-data","a store definition needs a non-empty id");if(!Number.isSafeInteger(n.version)||n.version<1)throw new h("invalid-data",`store '${n.id}' needs a positive integer version, got ${String(n.version)}`);let e;try{e=n.empty()}catch(t){throw new h("invalid-data",`store '${n.id}' could not build its empty state: ${String(t)}`,{cause:t})}try{n.state(e)}catch(t){throw new h("invalid-data",`store '${n.id}': empty() is not a valid state, so a replica could not clear a projection with it: ${String(t)}`,{cause:t})}if(n.visibility!==void 0)try{Ee(n.visibility)}catch(t){throw new h("invalid-data",`store '${n.id}': ${t instanceof Error?t.message:String(t)}`,{cause:t})}if(n.interest!==void 0){for(let[t,r]of Object.entries(n.interest))if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': interest maps a top-level collection name to a key function, got '${t}'`)}if(n.entities!==void 0)for(let[t,r]of Object.entries(n.entities)){if(t.length===0||t.includes(".")||typeof r!="function")throw new h("invalid-data",`store '${n.id}': entities maps a top-level collection name to a per-entity parser, got '${t}'`);let s=e[t];if(s!==void 0&&!Wt(s))throw new h("invalid-data",`store '${n.id}': entities names '${t}', but empty().${t} is not a record of entities`)}return Object.freeze({...n})}function Wt(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var $i=16;var T=class extends Error{constructor(t,r){super(t);this.reason=t;this.at=r}reason;at};function Ae(n){let e=new Rn(n);try{return{ok:!0,value:e.document()}}catch(t){if(t instanceof T)return{ok:!1,reason:t.reason,at:t.at};throw t}}var Rn=class{constructor(e){this.src=e}src;i=0;document(){if(this.skipWhitespace(),this.i>=this.src.length)throw new T("empty",this.i);let e=this.value(0);if(this.skipWhitespace(),this.i!==this.src.length)throw new T("trailing-content",this.i);return e}value(e){let t=this.src.charCodeAt(this.i);switch(t){case 123:return this.object(e+1);case 91:return this.array(e+1);case 34:return this.string();default:break}if(t===45||t>=48&&t<=57)return this.number();if(this.src.startsWith("true",this.i))return this.i+=4,!0;if(this.src.startsWith("false",this.i))return this.i+=5,!1;if(this.src.startsWith("null",this.i))return this.i+=4,null;throw new T(Number.isNaN(t)?"unexpected-end":"literal",this.i)}object(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=Object.create(null);if(this.skipWhitespace(),this.peek()===125)return this.i+=1,t;for(;;){if(this.skipWhitespace(),this.peek()!==34)throw new T("unexpected-token",this.i);let r=this.i,s=this.string();if(Object.prototype.hasOwnProperty.call(t,s))throw new T("duplicate-key",r);if(this.skipWhitespace(),this.peek()!==58)throw new T("unexpected-token",this.i);this.i+=1,this.skipWhitespace(),t[s]=this.value(e),this.skipWhitespace();let i=this.peek();if(i===44){this.i+=1;continue}if(i===125)return this.i+=1,t;throw new T(i===-1?"unexpected-end":"unexpected-token",this.i)}}array(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=[];if(this.skipWhitespace(),this.peek()===93)return this.i+=1,t;for(;;){this.skipWhitespace(),t.push(this.value(e)),this.skipWhitespace();let r=this.peek();if(r===44){this.i+=1;continue}if(r===93)return this.i+=1,t;throw new T(r===-1?"unexpected-end":"unexpected-token",this.i)}}string(){this.i+=1;let e="";for(;;){if(this.i>=this.src.length)throw new T("unexpected-end",this.i);let t=this.src.charCodeAt(this.i);if(t===34)return this.i+=1,e;if(t===92){e+=this.escape();continue}if(t<32)throw new T("string-control-char",this.i);e+=this.src[this.i],this.i+=1}}escape(){this.i+=1;let e=this.src[this.i];switch(this.i+=1,e){case'"':return'"';case"\\":return"\\";case"/":return"/";case"b":return"\b";case"f":return"\f";case"n":return`
2
- `;case"r":return"\r";case"t":return" ";case"u":{let t=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t))throw new T("string-escape",this.i);return this.i+=4,String.fromCharCode(Number.parseInt(t,16))}default:throw new T("string-escape",this.i-1)}}number(){let e=this.i;if(this.peek()===45&&(this.i+=1),this.peek()===48){if(this.i+=1,this.isDigit(this.peek()))throw new T("number-grammar",e)}else if(this.isDigit(this.peek()))for(;this.isDigit(this.peek());)this.i+=1;else throw new T("number-grammar",e);if(this.peek()===46){if(this.i+=1,!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let t=this.src[this.i];if(t==="e"||t==="E"){this.i+=1;let s=this.peek();if((s===43||s===45)&&(this.i+=1),!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let r=Number(this.src.slice(e,this.i));if(!Number.isFinite(r))throw new T("number-not-finite",e);return r}isDigit(e){return e>=48&&e<=57}peek(){return this.i>=this.src.length?-1:this.src.charCodeAt(this.i)}skipWhitespace(){for(;;){let e=this.peek();if(e===32||e===9||e===10||e===13){this.i+=1;continue}return}}};var In=1,Y=32,ue=16,Ut=16,Br=32,$r=128,Fr=256,Jr=64,be=1024*1024,oe=255,Bt=256,$t=8,Ve=64,Vr=256,Kr=18446744073709551615n,Fi=20,Xr=["join","resume","resync","act","in","aud","alive","leave","int"],Gr=["man","snap","delta","res","ok","no"],Ji={join:{required:["v","k","q","def","ver","store","key","aud"],optional:["int"]},resume:{required:["v","k","q","h","aud"],optional:["int"]},int:{required:["v","k","q","h","int"],optional:[]},resync:{required:["v","k","q","h","g","have"],optional:[]},aud:{required:["v","k","q","h","aud"],optional:[]},alive:{required:["v","k","q","h"],optional:[]},leave:{required:["v","k","q","h"],optional:[]},act:{required:["v","k","q","h","s","name","in"],optional:[]},in:{required:["v","k","h","name","s","in"],optional:[]},man:{required:["v","k","h","inc","g","r","n","bytes"],optional:["q"]},snap:{required:["v","k","h","g","r","i","n","d"],optional:[]},delta:{required:["v","k","h","g","base","r","ops"],optional:[]},res:{required:["v","k","q","h","s","out"],optional:[]},ok:{required:["v","k","q","h"],optional:[]},no:{required:["v","k","code"],optional:["q","h","s","detail"]}},Vi={join:["v","k","q","def","ver","store","key","aud","int"],resume:["v","k","q","h","aud","int"],int:["v","k","q","h","int"],resync:["v","k","q","h","g","have"],aud:["v","k","q","h","aud"],alive:["v","k","q","h"],leave:["v","k","q","h"],act:["v","k","q","h","s","name","in"],in:["v","k","h","name","s","in"],man:["v","k","q","h","inc","g","r","n","bytes"],snap:["v","k","h","g","r","i","n","d"],delta:["v","k","h","g","base","r","ops"],res:["v","k","q","h","s","out"],ok:["v","k","q","h"],no:["v","k","q","h","code","s","detail"]},_n=new Set(Xr),Ur=new Set(Gr),Ki=new Set(En),Xi=/^[A-Za-z0-9+/]+={0,2}$/;function F(n,e,t="invalid-data"){return{ok:!1,code:t,stage:n,reason:e}}var qt=class{constructor(e){this.refusal=e}refusal};function L(n,e,t="invalid-data"){return new qt(F(n,e,t))}function O(n){return n instanceof qt}function N(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.codePointAt(t);r>65535&&(t+=1),e+=r<=127?1:r<=2047?2:r<=65535?3:4}return e}function Re(n,e){if(N(n)>e.maxBytes)return F("bytes","frame-too-large","capacity");let r=Ae(n);if(!r.ok)return F("json",r.reason);let s=r.value;if(typeof s!="object"||s===null||Array.isArray(s))return F("json","not-an-object");let i=s;if(i.v!==In)return F("envelope","unknown-version");let o=i.k;if(typeof o!="string"||!(_n.has(o)||Ur.has(o)))return F("envelope","unknown-kind");let a=o;if(!(e.as==="owner"?_n:Ur).has(a))return F("direction",`wrong-direction:${a}`);let l=Ji[a],d=new Set([...l.required,...l.optional]);for(let u of Object.keys(i))if(!d.has(u))return F("payload","unknown-field");for(let u of l.required)if(!Object.prototype.hasOwnProperty.call(i,u))return F("payload","missing-field");return Gi(a,i)}function Gi(n,e){let t=(l,d)=>{let u=e[l];return typeof u!="string"||u.length!==d||!zr(u)?L("payload",`non-canonical-hex:${l}`):u},r=l=>{let d=e[l];return typeof d!="string"||!Cn(d)?L("payload",`non-canonical-decimal:${l}`):d},s=(l,d,u)=>{let p=e[l];return typeof p!="number"||!Number.isInteger(p)||p<d||p>u?L("payload",`bad-integer:${l}`):p},i=l=>{let d=e[l];return typeof d!="string"||d.length===0?L("payload",`bad-string:${l}`):d},o=l=>{let d=e[l];return typeof d!="object"||d===null||Array.isArray(d)?L("payload",`bad-object:${l}`):d},a=()=>{let l=e.aud;if(!Array.isArray(l))return L("payload","bad-audience");if(l.length>Br)return L("payload","audience-too-many","capacity");let d=[];for(let u of l){if(typeof u!="string"||u.length===0)return L("payload","bad-audience-label");if(N(u)>$r)return L("payload","audience-label-too-long","capacity");d.push(u)}return d},c=l=>{if(!Object.prototype.hasOwnProperty.call(e,"int"))return l?L("payload","missing-field"):void 0;let d=e.int;if(!Array.isArray(d))return L("payload","bad-interest");if(d.length>Fr)return L("payload","interest-too-many","capacity");let u=[];for(let p of d){if(typeof p!="string"||p.length===0)return L("payload","bad-interest-key");if(N(p)>Jr)return L("payload","interest-key-too-long","capacity");u.push(p)}return u};switch(n){case"int":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=c(!0);return O(u)?u.refusal:{ok:!0,message:{k:n,q:l,h:d,int:u}}}case"join":{let l=t("q",ue);if(O(l))return l.refusal;let d=i("def");if(O(d))return d.refusal;let u=s("ver",0,Number.MAX_SAFE_INTEGER);if(O(u))return u.refusal;let p=i("store");if(O(p))return p.refusal;let f=i("key");if(O(f))return f.refusal;let y=a();if(O(y))return y.refusal;let b=c(!1);return O(b)?b.refusal:{ok:!0,message:b===void 0?{k:n,q:l,def:d,ver:u,store:p,key:f,aud:y}:{k:n,q:l,def:d,ver:u,store:p,key:f,aud:y,int:b}}}case"resume":case"aud":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=a();if(O(u))return u.refusal;if(n==="resume"){let p=c(!1);return O(p)?p.refusal:{ok:!0,message:p===void 0?{k:n,q:l,h:d,aud:u}:{k:n,q:l,h:d,aud:u,int:p}}}return{ok:!0,message:{k:n,q:l,h:d,aud:u}}}case"resync":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("have");return O(p)?p.refusal:{ok:!0,message:{k:n,q:l,h:d,g:u,have:p}}}case"alive":case"leave":case"ok":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);return O(d)?d.refusal:{ok:!0,message:{k:n,q:l,h:d}}}case"act":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=i("name");if(O(p))return p.refusal;let f=o("in");return O(f)?f.refusal:{ok:!0,message:{k:n,q:l,h:d,s:u,name:p,in:f}}}case"in":{let l=t("h",Y);if(O(l))return l.refusal;let d=i("name");if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("in");return O(p)?p.refusal:{ok:!0,message:{k:n,h:l,name:d,s:u,in:p}}}case"res":{let l=t("q",ue);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("out");return O(p)?p.refusal:{ok:!0,message:{k:n,q:l,h:d,s:u,out:p}}}case"man":{let l=t("h",Y);if(O(l))return l.refusal;let d=t("inc",Ut);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let f=s("n",1,oe);if(O(f))return f.refusal;let y=r("bytes");if(O(y))return y.refusal;if(BigInt(y)>BigInt(be))return F("payload","snapshot-too-large","capacity");if(Object.prototype.hasOwnProperty.call(e,"q")){let b=t("q",ue);return O(b)?b.refusal:{ok:!0,message:{k:n,q:b,h:l,inc:d,g:u,r:p,n:f,bytes:y}}}return{ok:!0,message:{k:n,h:l,inc:d,g:u,r:p,n:f,bytes:y}}}case"snap":{let l=t("h",Y);if(O(l))return l.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("r");if(O(u))return u.refusal;let p=s("n",1,oe);if(O(p))return p.refusal;let f=s("i",0,p-1);if(O(f))return f.refusal;let y=e.d;return typeof y!="string"||!Ft(y)?F("payload","non-canonical-base64:d"):{ok:!0,message:{k:n,h:l,g:d,r:u,i:f,n:p,d:y}}}case"delta":{let l=t("h",Y);if(O(l))return l.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("base");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let f=zi(e.ops);return O(f)?f.refusal:{ok:!0,message:{k:n,h:l,g:d,base:u,r:p,ops:f}}}case"no":{let l=e.code;if(typeof l!="string"||!Ki.has(l))return F("payload","unknown-code");let d=Object.prototype.hasOwnProperty.call(e,"q"),u=Object.prototype.hasOwnProperty.call(e,"h"),p=Object.prototype.hasOwnProperty.call(e,"s");if(!d&&!u)return F("payload","no-names-nothing");if(!d){if(l!=="closed"&&l!=="owner-lost")return F("payload","unsolicited-no-must-be-closed-or-owner-lost");if(p)return F("payload","unsolicited-no-carries-no-sequence")}let f={k:"no",code:l};if(d){let y=t("q",ue);if(O(y))return y.refusal;f.q=y}if(u){let y=t("h",Y);if(O(y))return y.refusal;f.h=y}if(p){let y=r("s");if(O(y))return y.refusal;f.s=y}if(Object.prototype.hasOwnProperty.call(e,"detail")){let y=e.detail;if(typeof y!="string")return F("payload","bad-string:detail");if(N(y)>Vr)return F("payload","detail-too-long","capacity");f.detail=y}return{ok:!0,message:f}}}}function zi(n){if(!Array.isArray(n))return L("payload","bad-ops");if(n.length>Bt)return L("payload","ops-too-many","capacity");let e=[];for(let t of n){if(typeof t!="object"||t===null||Array.isArray(t))return L("payload","bad-op");let r=t,s=r.o;if(s!=="r"&&s!=="x")return L("payload","bad-op-kind");let i=s==="r"?["o","p","val"]:["o","p"];for(let c of Object.keys(r))if(!i.includes(c))return L("payload","unknown-field");if(s==="r"&&!Object.prototype.hasOwnProperty.call(r,"val"))return L("payload","missing-field");let o=r.p;if(!Array.isArray(o))return L("payload","bad-path");if(o.length>$t)return L("payload","path-too-deep","capacity");let a=[];for(let c of o){if(typeof c!="string"||c.length===0)return L("payload","bad-segment");if(N(c)>Ve)return L("payload","segment-too-long","capacity");a.push(c)}e.push(s==="r"?{o:s,p:a,val:r.val}:{o:s,p:a})}return e}function zr(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e),r=t>=48&&t<=57,s=t>=97&&t<=102;if(!r&&!s)return!1}return n.length>0}function Cn(n){if(n.length===0||n.length>Fi)return!1;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t<48||t>57)return!1}return n.length>1&&n.charCodeAt(0)===48?!1:BigInt(n)<=Kr}function Ft(n){if(n.length===0)return!0;if(n.length%4!==0||!Xi.test(n))return!1;let e=n.endsWith("==")?2:n.endsWith("=")?1:0;if(e===0)return!0;let t=n.charCodeAt(n.length-e-1),r=Yi(t);return r<0?!1:(r&(e===2?15:3))===0}function Yi(n){return n>=65&&n<=90?n-65:n>=97&&n<=122?n-97+26:n>=48&&n<=57?n-48+52:n===43?62:n===47?63:-1}function ae(n){if(!Cn(n))throw new RangeError(`not a canonical decimal: ${JSON.stringify(n)}`);return BigInt(n)}function Jt(n,e){return Pn(n,e,new Set)}function Pn(n,e,t){if(n===null)return null;switch(typeof n){case"boolean":case"string":return null;case"number":return Number.isFinite(n)?null:`non-finite-number:${e}`;case"object":{let r=n;if(t.has(r))return`circular:${e}`;if("toJSON"in r)return`to-json-transform:${e}`;if(r instanceof Map||r instanceof Set||r instanceof WeakMap||r instanceof WeakSet)return`map-or-set:${e}`;if(Object.getOwnPropertySymbols(r).length>0)return`symbol-key:${e}`;t.add(r);try{if(Array.isArray(n)){for(let s=0;s<n.length;s+=1){let i=Pn(n[s],`${e}[${s}]`,t);if(i!==null)return i}return null}for(let[s,i]of Object.entries(n)){let o=Pn(i,`${e}.${s}`,t);if(o!==null)return o}return null}finally{t.delete(r)}}default:return`not-json:${e}`}}function Qi(n){switch(n.k){case"act":case"in":return[["in",n.in]];case"res":return[["out",n.out]];case"delta":return n.ops.flatMap((e,t)=>e.o==="r"?[[`ops[${t}].val`,e.val]]:[]);default:return[]}}function P(n){for(let[o,a]of Qi(n)){let c=Jt(a,o);if(c!==null)throw new RangeError(`refusing to encode an invalid ${n.k}: ${c}`)}let e={v:In,k:n.k},t=n;for(let o of Vi[n.k]){if(o==="v"||o==="k"||!Object.prototype.hasOwnProperty.call(t,o))continue;let a=t[o];a!==void 0&&(e[o]=a)}let r=JSON.stringify(e),s=_n.has(n.k)?"owner":"replica",i=Re(r,{maxBytes:Number.MAX_SAFE_INTEGER,as:s});if(!i.ok)throw new RangeError(`refusing to encode an invalid ${n.k}: ${i.reason}`);return r}var Qr=192,jn=1024,Hn=197;function Zr(n){return Math.floor((n-Qr)/4)*3}function Ln(n){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new h("capacity",`the transport reported no usable event size (${String(n)})`);if(Hn>n)throw new h("capacity",`the frozen envelopes need ${Hn} B and the transport allows ${n} B`);let e=Zr(n);if(e<jn)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk, below the ${jn} B floor`);if(e*oe<be)throw new h("capacity",`a ${n} B event leaves ${e} B per chunk: ${oe} of them cover ${e*oe} B, below the ${be} B snapshot bound`);return e}function Tn(n,e){if(e<1)throw new h("capacity",`a chunk budget of ${e} B cannot carry anything`);try{let i=Jt(n,"state");if(i!==null)throw new h("invalid-data",`the projected state is not JSON: ${i}`)}catch(i){throw i instanceof h?i:new h("invalid-data",`the projected state is not JSON: ${String(i)}`,{cause:i})}let t;try{t=JSON.stringify(n)}catch(i){throw new h("invalid-data","the projected state is not JSON",{cause:i})}if(t===void 0)throw new h("invalid-data","the projected state is not JSON");let r=new TextEncoder().encode(t);if(r.length>be)throw new h("capacity",`the projection is ${r.length} B and the bound is ${be} B`);let s=[];for(let i=0;i<r.length;i+=e)s.push(es(r.subarray(i,i+e)));if(s.length>oe)throw new h("capacity",`the projection needs ${s.length} chunks and the bound is ${oe}`);return{bytes:r.length,n:s.length,pieces:s}}var Yr=32768;function es(n){let e="";for(let t=0;t<n.length;t+=Yr)e+=String.fromCharCode(...n.subarray(t,t+Yr));return btoa(e)}function Dn(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Zi(n){let e=JSON.stringify(n);if(e===void 0)throw new h("invalid-data","not JSON");return N(e)}var Kt=1e4,ts=8*1024*1024;function X(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,fatal:e}}var Vt=class{constructor(e,t){this.manifest=e;this.openedAt=t;this.pieces=new Array(e.n),this.encoded=new Array(e.n)}manifest;openedAt;pieces;encoded;admitted=0;held=0;closed=!1;get bytesHeld(){return this.held}get bytesReserved(){return this.closed?0:Math.max(Number(this.manifest.bytes),this.held)}get have(){return this.admitted}get reclaimed(){return this.closed}reclaim(){this.closed=!0,this.pieces.fill(void 0),this.encoded.fill(void 0),this.admitted=0,this.held=0}expired(e){return e-this.openedAt>=Kt}accept(e,t,r){if(this.closed)return X("chunk-wrong-assembly",!1);if(this.expired(r))return this.reclaim(),X("deadline",!0,"timeout");let s=this.manifest;if(e.h!==s.h||e.g!==s.g||e.r!==s.r||e.n!==s.n)return X("chunk-wrong-assembly",!1);if(!Number.isInteger(e.i)||e.i<0||e.i>=s.n)return X("chunk-index",!1);if(!Ft(e.d))return X("chunk-non-canonical",!1);let i=this.encoded[e.i];if(i!==void 0)return i===e.d?{ok:!0,done:!1,have:this.admitted}:(this.reclaim(),X("chunk-conflict",!0));let o=Dn(e.d),a=Number(s.bytes);if(this.held+o.length>a)return this.reclaim(),X("byte-total-mismatch",!0);if(this.encoded[e.i]=e.d,this.pieces[e.i]=o,this.admitted+=1,this.held+=o.length,this.admitted<s.n)return{ok:!0,done:!1,have:this.admitted};if(this.held!==a)return this.reclaim(),X("byte-total-mismatch",!0);let c=new Uint8Array(this.held),l=0;for(let p of this.pieces){if(p===void 0)return this.reclaim(),X("byte-total-mismatch",!0);c.set(p,l),l+=p.length}let d=new TextDecoder("utf-8",{fatal:!0}),u;try{let p=Ae(d.decode(c));if(!p.ok)return this.reclaim(),X("assembled-not-json",!0);u=p.value}catch{return this.reclaim(),X("assembled-not-json",!0)}try{t(u)}catch{return this.reclaim(),X("assembled-invalid",!0)}return this.reclaim(),{ok:!0,done:!0,document:u}}},ot=class n{constructor(e=ts){this.maxTotalBytes=e}maxTotalBytes;live=new Map;static key(e,t){return`${e}/${t}`}get bytesHeld(){let e=0;for(let t of this.live.values())e+=t.bytesHeld;return e}get bytesReserved(){let e=0;for(let t of this.live.values())e+=t.bytesReserved;return e}get size(){return this.live.size}get(e,t){return this.live.get(n.key(e,t))}open(e,t){if(!Number.isInteger(e.n)||e.n<1||e.n>oe)return X("manifest-chunk-count",!0);let r=Number(e.bytes);if(!Number.isSafeInteger(r)||r<0||r>be)return X("manifest-bytes",!0,"capacity");let s=n.key(e.h,e.g),i=this.live.get(s),o=i?.bytesReserved??0;if(this.bytesReserved-o+r>this.maxTotalBytes)return X("assembly-too-large",!0,"capacity");i?.reclaim(),this.live.delete(s);let a=new Vt(e,t);return this.live.set(s,a),a}reclaim(e,t){let r=n.key(e,t);this.live.get(r)?.reclaim(),this.live.delete(r)}reclaimHandle(e){for(let[t,r]of[...this.live])t.startsWith(`${e}/`)&&(r.reclaim(),this.live.delete(t))}sweep(e){let t=0;for(let[r,s]of[...this.live])s.expired(e)&&(s.reclaim(),this.live.delete(r),t+=1);return t}clear(){for(let e of this.live.values())e.reclaim();this.live.clear()}};function pe(n,e){if(Object.is(n,e))return e;if(Array.isArray(e)){let t=e;if(!Array.isArray(n))return rs(t,void 0);let r=rs(t,n);return n.length===t.length&&eo(n,r)?n:r}if(ns(e)){if(!ns(n))return ss(e,void 0);let t=ss(e,n),r=Object.keys(e);return r.length===Object.keys(n).length&&r.every(s=>is(n,s)&&Object.is(n[s],t[s]))?n:t}return e}function Xt(n,e){let t=Object.keys(e);if(t.length===0)return n;let r=!1,s={...n};for(let i of t){let o=os(n,i),a=pe(o,e[i]);Object.is(o,a)||(Object.defineProperty(s,i,{value:a,enumerable:!0,writable:!0,configurable:!0}),r=!0)}return r?Object.freeze(s):n}function ns(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function eo(n,e){for(let t=0;t<e.length;t+=1)if(!Object.is(n[t],e[t]))return!1;return!0}function rs(n,e){let t=new Array(n.length);for(let r=0;r<n.length;r+=1)t[r]=pe(e?.[r],n[r]);return Object.freeze(t)}function is(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function os(n,e){if(n!==void 0)return is(n,e)?n[e]:void 0}function ss(n,e){let t={};for(let r of Object.keys(n))Object.defineProperty(t,r,{value:pe(os(e,r),n[r]),enumerable:!0,writable:!1,configurable:!1});return Object.freeze(t)}var as=["__proto__","constructor","prototype"],to=new Set(as);function fe(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,resync:e}}function Mn(n,e,t){if(e.length>Bt)return fe("ops-too-many",!1,"capacity");for(let a of e){if(a.p.length>$t)return fe("path-too-deep",!1,"capacity");for(let c of a.p){if(N(c)>Ve)return fe("segment-too-long",!1,"capacity");if(to.has(c))return fe("segment-forbidden",!1)}if(a.o==="x"&&a.p.length===0)return fe("root-remove",!1)}let r=n,s=new WeakSet;for(let a of e){if(a.p.length===0){a.o==="r"&&(r=a.val);continue}if(!ds(r))return fe("parent-not-object",!0);let c=us(r,s);r=c;let l=no(c,a.p.slice(0,-1),s);if(l===ls)return fe("missing-parent",!0);if(l===cs)return fe("parent-not-object",!0);let d=l,u=a.p[a.p.length-1];if(a.o==="x"){if(!Object.prototype.hasOwnProperty.call(d,u))return fe("missing-key",!0);delete d[u];continue}d[u]=a.val}let i;try{i=t(r)}catch{return fe("invalid-state",!0)}let o=pe(n,i);return{ok:!0,next:o,changed:!Object.is(o,n)}}var ls=Symbol("missing-parent"),cs=Symbol("parent-not-object");function no(n,e,t){let r=n;for(let s of e){let i=r;if(!Object.prototype.hasOwnProperty.call(i,s))return ls;let o=i[s];if(!ds(o))return cs;let a=us(o,t);i[s]=a,r=a}return r}function ds(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function us(n,e){if(e.has(n))return n;let t=Object.assign(Object.create(null),n);return e.add(t),t}var Se=class{#e;#t=new Set;#r=new Set;#n;#s;#g=0;#o=null;#a=0;#u=!1;constructor(e){this.#e=e.definition,this.#n=pe(void 0,this.#d(e.initialState)),this.#s=Object.freeze({phase:e.phase??"ready",stale:!1,error:null})}getState(){return this.#n}get revision(){return this.#g}get inTransaction(){return this.#o!==null&&this.#o.active}subscribe(e,t,r){let s=t===void 0?this.#y(e):this.#O(e,t,r);this.#t.add(s);let i=!0;return()=>{i&&(i=!1,this.#t.delete(s))}}getStatus(){return this.#s}subscribeStatus(e){this.#r.add(e);let t=!0;return()=>{t&&(t=!1,this.#r.delete(e))}}setStatus(e){let t=this.#s,r={phase:e.phase??t.phase,stale:e.stale??t.stale,error:e.error===void 0?t.error:e.error};if(!(r.phase===t.phase&&r.stale===t.stale&&Object.is(r.error,t.error))){this.#s=Object.freeze(r);for(let s of[...this.#r])this.#r.has(s)&&Gt(()=>s(this.#s,t))}}transact(e,t){if(this.#l(),this.#o!==null)throw new h("action-rejected","a store transaction is already open on this store; handlers are synchronous and must not nest");let r={staged:this.#n,active:!0};this.#o=r;try{let s=e(this.#c(r,t));if(ro(s))throw new h("action-rejected","a store handler returned a thenable; handlers are synchronous so that a throw can discard the whole transaction");return this.#b(r.staged),s}finally{r.active=!1,this.#o=null}}applyOwnerUpdate(e){this.#l();let t=this.#o;if(t!==null&&t.active){t.staged=this.#f(t.staged,e);return}let r=this.#f(this.#n,e);this.#b(r)}applySnapshot(e){this.#l();let t=this.#o;if(t!==null&&t.active){t.staged=this.#d(e);return}this.#b(this.#d(e))}applyEntities(e,t){this.#l();let r=this.#e.entities?.[e];if(r===void 0||!Object.prototype.hasOwnProperty.call(this.#e.entities,e))throw new h("invalid-data",`store '${this.#e.id}' declares no per-entity parser for '${e}'; declare it in \`entities\` or write through setState`);let s=this.#o,i=s!==null&&s.active?s.staged:this.#n,o=i[e];if(o!==void 0&&!Wt(o))throw new h("invalid-data",`store '${this.#e.id}': '${e}' is not an entity map in the current state`);let a=[];for(let p of Object.keys(t)){if(p.length===0)throw new h("invalid-data",`store '${this.#e.id}': an entity id in '${e}' is empty`);let f=t[p];if(f===void 0){a.push([p,void 0]);continue}try{a.push([p,this.runReadOnly(()=>r(f))])}catch(y){throw y instanceof h?y:new h("invalid-data",`entity '${e}.${p}' failed the '${this.#e.id}' entity validator: ${String(y)}`,{cause:y})}}if(s!==null&&s.active){let p={...o??{}};for(let[f,y]of a)y===void 0?delete p[f]:Nn(p,f,y);s.staged=Xt(i,{[e]:p});return}let c=!1,l=[];for(let[p,f]of a){let y=o!==void 0&&Object.prototype.hasOwnProperty.call(o,p),b=y?o[p]:void 0;if(f===void 0){y&&(c=!0),l.push([p,void 0]);continue}let k=pe(b,f);Object.is(b,k)||(c=!0),l.push([p,k])}if(!c)return;let d={...o??{}};for(let[p,f]of l)f===void 0?delete d[p]:Nn(d,p,f);let u={...i};Nn(u,e,Object.freeze(d)),this.#p(Object.freeze(u))}applyDelta(e){this.#l();let t=Mn(this.#n,e,r=>this.#d(r));return t.ok&&t.changed&&this.#h(t.next),t}runReadOnly(e){this.#a+=1;try{return e()}finally{this.#a-=1}}close(){this.#u||(this.#u=!0,this.setStatus({phase:"closed",stale:!0}),this.#t.clear(),this.#r.clear())}#c(e,t){return{peer:t,getState:()=>(this.#w(e),e.staged),setState:r=>{if(this.#w(e),this.#a>0)throw new h("action-rejected","a read-only store callback may not write state; validators, authorize, project and update functions run with setters fenced");e.staged=this.#f(e.staged,r)}}}#f(e,t){let r=typeof t=="function"?this.runReadOnly(()=>t(e)):t;return Xt(e,r)}#b(e){this.#h(this.#d(e))}#h(e){let t=pe(this.#n,e);Object.is(t,this.#n)||this.#p(t)}#p(e){let t=this.#n;this.#n=e,this.#g+=1;for(let r of[...this.#t])this.#t.has(r)&&r.notify(e,t)}#d(e){try{return this.runReadOnly(()=>this.#e.state(e))}catch(t){throw t instanceof h?t:new h("invalid-data",`state failed the '${this.#e.id}' validator: ${String(t)}`,{cause:t})}}#y(e){return{notify:(t,r)=>{Gt(()=>e(t,r))}}}#O(e,t,r){let s=r?.equality??Object.is,i=this.runReadOnly(()=>e(this.#n));return r?.fireImmediately===!0&&Gt(()=>t(i,i)),{notify:o=>{let a=this.runReadOnly(()=>e(o)),c=i;s(a,c)||(i=a,Gt(()=>t(a,c)))}}}#w(e){if(!e.active)throw new h("action-rejected","this store transaction has already ended; its context cannot read or write from a later turn")}#l(){if(this.#u)throw new h("closed","this store handle is closed")}};function ro(n){return n===null||typeof n!="object"&&typeof n!="function"?!1:typeof n.then=="function"}function Gt(n){try{n()}catch(e){console.error("[@net-mesh/browser] store listener threw",e)}}function Nn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}var ps=32,fs=64*1024,hs=6e4,ys=2048,gs=(1n<<64n)-1n,so="";function qn(n,e){return`${n}${so}${Wn(e)}`}function Wn(n){if(n===null||typeof n=="boolean")return String(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new h("invalid-data","a canonical request cannot contain a non-finite number");return String(n)}if(typeof n=="string")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(s=>Wn(s)).join(",")}]`;let e=n;return`{${Object.keys(e).sort().map(s=>`${JSON.stringify(s)}:${Wn(e[s])}`).join(",")}}`}function ms(n){return new TextEncoder().encode(n).byteLength}function Qt(n){return ms(n)>ys}function Un(n){if(Qt(n))throw new h("invalid-data","this canonical form needs the digest path");return{form:"inline",value:n}}async function Bn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t=new Uint8Array(e),r="";for(let s of t)r+=s.toString(16).padStart(2,"0");return{form:"digest",value:r}}function io(n,e){return n.form===e.form&&n.value===e.value}var zt=class{constructor(e=ps,t=fs,r=hs){this.maxEntries=e;this.maxBytes=t;this.maxAgeMs=r}maxEntries;maxBytes;maxAgeMs;#e=0n;#t=new Map;#r=0;get floor(){return this.#e.toString()}get size(){return this.#t.size}get bytesHeld(){return this.#r}disposition(e,t,r){if(this.expire(r),e>=gs)return{kind:"exhausted"};let s=this.#t.get(e.toString());return s!==void 0?io(s.binding,t)?{kind:"replay",outcome:s.outcome}:{kind:"conflict"}:e<=this.#e?{kind:"expired"}:{kind:"execute"}}retain(e,t,r,s){let i=oo(t,r);this.#t.set(e.toString(),{s:e,binding:t,outcome:r,bytes:i,at:s}),this.#r+=i,this.evict(s)}expire(e){for(let t of this.ordered()){if(e-t.at<this.maxAgeMs)break;this.drop(t)}}evict(e){for(this.expire(e);this.#t.size>this.maxEntries||this.#r>this.maxBytes;){let t=this.ordered()[0];if(t===void 0)return;this.drop(t)}}drop(e){this.#t.delete(e.s.toString()),this.#r-=e.bytes,e.s>this.#e&&(this.#e=e.s)}ordered(){return[...this.#t.values()].sort((e,t)=>e.s<t.s?-1:e.s>t.s?1:0)}};function oo(n,e){let t=e.kind==="result"?JSON.stringify(e.out):e.code;return N(n.value)+N(t)}var Yt=class{#e=new Map;#t=0;get dropped(){return this.#t}admit(e,t){let r=this.#e.get(e);return r!==void 0&&t<=r?(this.#t+=1,!1):(this.#e.set(e,t),!0)}latest(e){let t=this.#e.get(e);return t===void 0?null:t.toString()}},at=class{#e=new Map;#t=new Map;ledger(e){let t=this.#e.get(e);return t===void 0&&(t=new zt,this.#e.set(e,t)),t}inputs(e){let t=this.#t.get(e);return t===void 0&&(t=new Yt,this.#t.set(e,t)),t}forget(e){this.#e.delete(e),this.#t.delete(e)}get size(){return this.#e.size}};var ws=32,vs=256,ao=16,$n=6e4,Os=256;function we(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var lo="0".repeat(16),co="0".repeat(32),lt=class{constructor(e){this.deps=e;if(this.chunkBytes=Ln(e.maxEventBytes),this.incarnation=e.newIncarnation(),this.incarnation.length!==Ut)throw new h("invalid-data","newIncarnation must return 16 lowercase hex");let t=(typeof e.project=="function"?1:0)+(typeof e.projectFor=="function"?1:0),r=e.definition.visibility;if(t>1||t===0&&r===void 0)throw new h("invalid-data","a host needs one of `project` and `projectFor`, or a definition that declares `visibility`");this.visibility=r===void 0?null:Ee(r),this.perPlayer=typeof e.projectFor=="function"||this.visibility?.perPlayer===!0,this.core=new Se({definition:e.definition,initialState:e.definition.empty()})}deps;handles=new Map;counters={};chunkBytes;incarnation;core;pending=0;ledgers=new at;deferred=new Map;revisionBeforeCommit=0;perPlayer;visibility;warned=new Set;warnOnce(e){if(!(this.deps.warn===void 0||this.warned.has(e))){this.warned.add(e);try{this.deps.warn(e)}catch{}}}viewKey(e,t){return this.perPlayer?JSON.stringify([e,t]):JSON.stringify(t)}get sparseViews(){return this.sparseViewCount}sparseViewCount=0;snapshotCounters(){return{...this.counters}}get handleCount(){return this.handles.size}handle(e){return this.handles.get(e)}commit(e){let t=this.core.inTransaction,r=this.core.getState();if(t||(this.revisionBeforeCommit=this.core.revision),this.core.applySnapshot(e),t)return this.accept([]);let s=this.core.getState();return Object.is(r,s)?this.accept([]):this.accept(this.propagate(r,s))}commitEntities(e,t){let r=this.core.inTransaction,s=this.core.getState();if(r||(this.revisionBeforeCommit=this.core.revision),this.core.applyEntities(e,t),r)return this.accept([]);let i=this.core.getState();return Object.is(s,i)?this.accept([]):this.accept(this.propagate(s,i))}propagate(e,t){let r=[],s=String(this.core.revision),i=new Map,o=new Map,a;for(let c of[...this.handles.values()]){if(this.deferred.has(c.h))continue;if(!this.permitsRead(c.peer,c.audience,c.key)){this.forget(c.h,"refused"),r.push(this.no(c.peer,c.h,"closed",null));continue}let l=this.viewKey(c.peer,c.audience),d;if(this.interestFns.length>0&&c.interest!==null){let f=i.get(l);if(f===void 0){if(a===void 0&&(a=this.entityDelta(e,t)),f=a===null?void 0:this.sparseInterestDiff(c.peer,c.audience,a),f===void 0){let y=this.project(c.peer,c.audience,e),b=this.project(c.peer,c.audience,t);f=y===null||b===null?null:this.interestDiff(y,b)}else this.sparseViewCount+=1;i.set(l,f)}d=f===null?null:this.interestOps(f,c.interest)}else if(d=o.get(l),d===void 0){let f=this.project(c.peer,c.audience,e),y=this.project(c.peer,c.audience,t);d=f===null||y===null?null:bs(f,y),o.set(l,d)}if(d===null){this.forget(c.h),r.push(this.no(c.peer,c.h,"closed",null));continue}if(d.length===0)continue;let u=Ss({k:"delta",h:c.h,g:String(c.generation),base:String(c.revision),r:s,ops:d},this.deps.maxEventBytes);if(u!==null){r.push({peer:c.peer,h:c.h,frame:u}),this.handles.set(c.h,{...c,revision:this.core.revision});continue}let p=this.install(c,null);if(p===null){this.forget(c.h),r.push(this.no(c.peer,c.h,"closed",null));continue}r.push(...p)}return r}getState(){return this.core.getState()}subscribe(e){return this.core.subscribe((t,r)=>{e(t,r)})}get currentRevision(){return this.core.revision}localRead(e,t){return this.permitsRead(e,t)}localView(e,t,r=null){let s=this.project(e,t);return s===null?null:this.filterInterest(s,r)}localAct(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,e))return{outcome:{kind:"refusal",code:"invalid-data"},dispatched:this.refuse("local-act-unknown-name")};if(!this.permitsAction(r,e,t))return{outcome:{kind:"refusal",code:"forbidden"},dispatched:this.refuse("local-act-forbidden")};let s=this.deps.definition.actions[e],i=this.core.getState();this.revisionBeforeCommit=this.core.revision;let o;try{let l=this.deps.actions[e];o={kind:"result",out:this.core.transact(u=>{let p=s.output(l(s.input(t),u)),f=P({k:"res",q:lo,h:co,s:"1",out:p});if(N(f)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return p},r)}}catch(l){o={kind:"refusal",code:l instanceof h&&l.code==="capacity"?"capacity":"action-rejected"}}let a=this.core.getState(),c=Object.is(i,a)?[]:this.propagate(i,a);return{outcome:o,dispatched:o.kind==="refusal"?this.refuse(`local-act-${o.code}`,c):this.accept(c)}}localInput(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,e))return this.refuse("local-in-unknown-name");if(!this.permitsInput(r,e,t))return this.refuse("local-in-forbidden");let s=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(o=>{let a=this.deps.definition.inputs[e],c=this.deps.inputs[e];c(a(t),o)},r)}catch{return this.refuse("local-in-rejected")}let i=this.core.getState();return this.accept(Object.is(s,i)?[]:this.propagate(s,i))}receive(e,t,r=this.deps.now()){let s=Re(e,{maxBytes:this.deps.maxEventBytes,as:"owner"});if(!s.ok)return this.refuse(s.reason,[]);let i=s.message;if(i.k==="join")return this.join(i,t,r);let o=this.bind(i.h,t,r);if(typeof o=="string")return this.refuse(o,[this.no(t,i.h,"closed",fo(i))]);switch(i.k){case"alive":return this.handles.set(o.h,{...o,lastSeen:r}),this.accept([{peer:t,h:o.h,frame:P({k:"ok",q:i.q,h:o.h})}]);case"leave":return this.forget(o.h,"left"),this.accept([{peer:t,h:o.h,frame:P({k:"ok",q:i.q,h:o.h})}]);case"int":return this.interestChange(i,o,t,r);case"act":return this.action(i,o,t,r);case"in":return this.input(i,o,t,r);case"resync":{if(!this.permitsRead(t,o.audience,o.key))return this.refuse("resync-forbidden",[this.no(t,o.h,"forbidden",i.q)]);let a={...o,lastSeen:r};this.handles.set(o.h,a);let c=this.install(a,i.q);return c===null?(this.forget(o.h),this.refuse("resync-projection-capacity",[this.no(t,o.h,"capacity",i.q)])):this.accept(c)}case"aud":case"resume":{if(!this.permitsRead(t,i.aud,o.key))return this.refuse(`${i.k}-forbidden`,[this.no(t,o.h,"forbidden",i.q)]);let a={...o,audience:[...i.aud],interest:i.k==="resume"&&i.int!==void 0?[...i.int]:o.interest,lastSeen:r};if(this.handles.set(a.h,a),!this.deps.canProject())return this.deferred.set(a.h,{q:i.q,peer:t}),this.accept([]);let c=this.install(a,i.q);return c===null?(this.forget(a.h),this.refuse(`${i.k}-projection-capacity`,[this.no(t,a.h,"capacity",i.q)])):this.accept(c)}default:return this.refuse("unreachable-kind")}}action(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,i))return this.refuse("act-unknown-name",[this.no(r,t.h,"invalid-data",e.q)]);let o;try{o=qn(i,e.in)}catch{return this.refuse("act-uncanonical",[this.no(r,t.h,"invalid-data",e.q)])}if(!Qt(o))return this.decide(e,t,r,s,Un(o));if(this.pending>=ws)return this.refuse("act-pending-bound",[this.no(r,t.h,"capacity",e.q)]);this.pending+=1;let a=Bn(o).then(c=>{let l=this.deps.now(),d=this.bind(e.h,r,l);return typeof d=="string"?this.refuse(d,[this.no(r,e.h,"closed",e.q)]):this.decide(e,d,r,l,c)}).catch(()=>this.refuse("act-digest-failed",[this.no(r,e.h,"indeterminate",e.q)])).finally(()=>{this.pending-=1});return{out:[],refused:null,deferred:a}}decide(e,t,r,s,i){let o=this.ledgers.ledger(t.h),a=ae(e.s),c=o.disposition(a,i,s);switch(c.kind){case"exhausted":return this.refuse("act-sequence-exhausted",[this.no(r,t.h,"capacity",e.q)]);case"conflict":return this.refuse("act-binding-mismatch",[this.no(r,t.h,"invalid-data",e.q)]);case"expired":return this.refuse("act-result-expired",[this.no(r,t.h,"result-expired",e.q)]);case"replay":return this.permitsAction(r,e.name,e.in)?(this.renew(t,s),this.accept([this.reply(t,r,e.q,a,c.outcome)])):this.refuse("act-forbidden-replay",[this.no(r,t.h,"forbidden",e.q)]);case"execute":break}if(!this.permitsAction(r,e.name,e.in))return o.retain(a,i,{kind:"refusal",code:"forbidden"},s),this.renew(t,s),this.refuse("act-forbidden",[this.no(r,t.h,"forbidden",e.q)]);let l=this.deps.definition.actions[e.name],d=this.core.getState();this.revisionBeforeCommit=this.core.revision;let u;try{let y=this.deps.actions[e.name];u={kind:"result",out:this.core.transact(k=>{let A=l.input(e.in),j=l.output(y(A,k)),M=P({k:"res",q:e.q,h:t.h,s:e.s,out:j});if(N(M)>this.deps.maxEventBytes)throw new h("capacity","the result does not fit the message budget");return j},r)}}catch(y){u={kind:"refusal",code:y instanceof h&&y.code==="capacity"?"capacity":"action-rejected"}}o.retain(a,i,u,s),this.renew(t,s);let p=this.core.getState(),f=Object.is(d,p)?[]:this.propagate(d,p);return this.accept([this.reply(t,r,e.q,a,u),...f])}input(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,i))return this.refuse("in-unknown-name");if(!this.ledgers.inputs(t.h).admit(i,ae(e.s)))return this.refuse("in-stale-sequence");if(!this.permitsInput(r,i,e.in))return this.refuse("in-forbidden");let o=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(c=>{let l=this.deps.definition.inputs[i],d=this.deps.inputs[i];d(l(e.in),c)},r)}catch{return this.refuse("in-rejected")}this.renew(t,s);let a=this.core.getState();return this.accept(Object.is(o,a)?[]:this.propagate(o,a))}reply(e,t,r,s,i){let o=i.kind==="result"?P({k:"res",q:r,h:e.h,s:s.toString(),out:i.out}):P({k:"no",q:r,h:e.h,code:i.code,s:s.toString()});return{peer:t,h:e.h,frame:o}}permitsAction(e,t,r){let s={type:"action",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}permitsInput(e,t,r){let s={type:"input",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}renew(e,t){let r=this.handles.get(e.h);r!==void 0&&this.handles.set(e.h,{...r,lastSeen:t})}forget(e,t="dropped"){let r=this.handles.get(e);this.handles.delete(e),this.ledgers.forget(e),this.deferred.delete(e),r!==void 0&&(this.presenceChanged(r.peer,t),this.membershipChanged())}present=new Set;localPlayers=new Set;pendingEvents=[];areas=new Map;areasAt=-1;ending=!1;get wantsEvents(){return this.deps.onEvent!==void 0||this.deps.areaOf!==void 0}isPresent(e){if(this.localPlayers.has(e))return!0;for(let t of this.handles.values())if(t.peer===e)return!0;return!1}presenceChanged(e,t,r=[]){if(!this.wantsEvents||this.ending)return;let s=this.isPresent(e),i=this.present.has(e);s!==i&&(s?(this.present.add(e),this.pendingEvents.push(Object.freeze({type:"join",peer:e,audience:Object.freeze([...r])}))):(this.present.delete(e),this.areas.delete(e),this.pendingEvents.push(Object.freeze({type:"leave",peer:e,reason:t??"dropped"}))))}localPresence(e,t,r=[],s="left"){t?this.localPlayers.add(e):this.localPlayers.delete(e),this.presenceChanged(e,t?null:s,r)}detectAreas(){let e=this.deps.areaOf;if(e===void 0||this.ending||this.areasAt===this.core.revision&&[...this.present].every(r=>this.areas.has(r)))return;this.areasAt=this.core.revision;let t=this.core.getState();for(let r of this.present){let s;try{let a=this.core.runReadOnly(()=>e(t,r));s=typeof a=="string"?a:null}catch{s=null}let i=this.areas.has(r),o=i?this.areas.get(r)??null:null;this.areas.set(r,s),(i?o!==s:s!==null)&&this.pendingEvents.push(Object.freeze({type:"area",peer:r,from:o,to:s}))}}drainEvents(){let e=[];if(!this.wantsEvents)return this.accept(e);for(let t=0;;t+=1){this.pendingEvents.length===0&&this.detectAreas();let r=this.pendingEvents.shift();if(r===void 0)break;if(t>=Os){this.pendingEvents.length=0,this.counters["event-rounds-bound"]=(this.counters["event-rounds-bound"]??0)+1;break}let s=this.deps.onEvent;if(s===void 0)continue;let i=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(a=>s(r,a),r.peer)}catch{this.counters["event-rejected"]=(this.counters["event-rejected"]??0)+1;continue}let o=this.core.getState();Object.is(i,o)||e.push(...this.propagate(i,o))}return this.accept(e)}membership=new Set;membershipChanged(){for(let e of[...this.membership])try{e()}catch{}}onMembership(e){return this.membership.add(e),()=>{this.membership.delete(e)}}peers(){return[...new Set([...this.handles.values()].map(e=>e.peer))]}reauthorize(){let e=[];for(let t of[...this.handles.values()])this.permitsRead(t.peer,t.audience,t.key)||(this.forget(t.h,"refused"),e.push(this.no(t.peer,t.h,"closed",null)));return this.accept(e)}resumeDeferred(e=this.deps.now()){if(!this.deps.canProject())return this.accept([]);let t=[];for(let[r,s]of[...this.deferred]){this.deferred.delete(r);let i=this.bind(r,s.peer,e);if(typeof i=="string"){this.counters[`deferred-${i}`]=(this.counters[`deferred-${i}`]??0)+1;continue}let o=this.install(i,s.q);if(o===null){this.forget(r),t.push(this.no(s.peer,r,"capacity",s.q));continue}t.push(...o)}return this.accept(t)}get deferredCount(){return this.deferred.size}get ledgerCount(){return this.ledgers.size}accept(e,t=null){return{out:e,refused:null,deferred:t}}sweep(e){let t=[];for(let[r,s]of[...this.handles])e-s.lastSeen>=$n&&(this.forget(r,"expired"),t.push({h:r,peer:s.peer}));return t}farewell(){this.ending=!0,this.pendingEvents.length=0;let e=[];for(let[t,r]of[...this.handles])this.forget(t),e.push(this.no(r.peer,t,"owner-lost",null));return e}get incarnationHex(){return this.incarnation}join(e,t,r){if(e.store!==this.deps.store)return this.refuse("join-other-store",[]);if(e.def!==this.deps.definition.id)return this.refuse("join-wrong-definition",[this.no(t,null,"version-mismatch",e.q)]);if(e.ver!==this.deps.definition.version)return this.refuse("join-wrong-version",[this.no(t,null,"version-mismatch",e.q)]);if(this.handles.size>=vs)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);let s=0;for(let c of this.handles.values())c.peer===t&&(s+=1);if(s>=ao)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);if(!this.permitsRead(t,e.aud,e.key))return this.refuse("join-forbidden",[this.no(t,null,"forbidden",e.q)]);let i=this.newHandle();if(i===null||i.length!==Y||this.handles.has(i))return this.refuse("join-handle-unusable",[this.no(t,null,"owner-lost",e.q)]);let o={h:i,inc:this.incarnation,peer:t,audience:[...e.aud],key:e.key,interest:e.int===void 0?null:[...e.int],generation:0,revision:this.core.revision,lastSeen:r};this.handles.set(i,o);let a=this.install(o,e.q);return a===null?(this.forget(i),this.refuse("join-projection-capacity",[this.no(t,null,"capacity",e.q)])):(this.presenceChanged(t,null,e.aud),this.membershipChanged(),this.accept(a))}install(e,t){let r=this.project(e.peer,e.audience),s=r===null?null:this.filterInterest(r,e.interest);if(s===null)return null;let i;try{i=Tn(s,this.chunkBytes)}catch{return null}let o=e.generation+1;this.handles.set(e.h,{...e,generation:o,revision:this.core.revision});let a=String(o),c=String(this.core.revision),l=[{peer:e.peer,h:e.h,frame:P(t===null?{k:"man",h:e.h,inc:e.inc,g:a,r:c,n:i.n,bytes:String(i.bytes)}:{k:"man",q:t,h:e.h,inc:e.inc,g:a,r:c,n:i.n,bytes:String(i.bytes)})}];for(let d=0;d<i.n;d+=1)l.push({peer:e.peer,h:e.h,frame:P({k:"snap",h:e.h,g:a,r:c,i:d,n:i.n,d:i.pieces[d]})});return l}permitsRead(e,t,r){let s=r===void 0?{type:"read",peer:e,audience:[...t]}:{type:"read",peer:e,audience:[...t],key:r};try{return this.deps.authorize(s)===!0}catch{return!1}}newHandle(){try{return this.deps.newHandle()}catch{return null}}get interestFns(){return this.#e??=Object.entries(this.deps.definition.interest??{}).map(([e,t])=>[e,t]),this.#e}#e;interestKey(e,t,r){try{let s=this.core.runReadOnly(()=>e(t,r));return typeof s=="string"?s:null}catch{return null}}filterInterest(e,t){if(t===null||this.interestFns.length===0)return e;let r=new Set(t),s={...e};for(let[i,o]of this.interestFns){let a=s[i];if(!we(a))continue;let c={};for(let[l,d]of Object.entries(a)){let u=this.interestKey(o,d,l);(u===null||r.has(u))&&(c[l]=d)}s[i]=c}return s}entityDelta(e,t){if(this.deps.project!==void 0||this.deps.projectFor!==void 0)return null;let r=this.deps.definition.entities;if(r===void 0)return null;let s=new Set(this.interestFns.map(([c])=>c)),i=e,o=t,a=[];for(let c of new Set([...Object.keys(i),...Object.keys(o)])){let l=Object.prototype.hasOwnProperty.call(i,c)?i[c]:void 0,d=Object.prototype.hasOwnProperty.call(o,c)?o[c]:void 0;if(Object.is(l,d))continue;if(!s.has(c)||!Object.prototype.hasOwnProperty.call(r,c)||!we(l)||!we(d))return null;let u=[];for(let p of new Set([...Object.keys(l),...Object.keys(d)])){let f=Object.prototype.hasOwnProperty.call(l,p)?l[p]:void 0,y=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0;Object.is(f,y)||u.push(p)}a.push({collection:c,ids:u,before:l,after:d})}return{collections:a}}sparseInterestDiff(e,t,r){let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=(f,y,b)=>{Object.defineProperty(f,y,{value:b,enumerable:!0,writable:!0,configurable:!0})},o={},a={};for(let{collection:f,ids:y,before:b,after:k}of r.collections){let A={},j={};for(let M of y)Object.prototype.hasOwnProperty.call(b,M)&&i(A,M,b[M]),Object.prototype.hasOwnProperty.call(k,M)&&i(j,M,k[M]);i(o,f,A),i(a,f,j)}let c=this.visibility===null?o:ke(this.visibility,o,s),l=this.visibility===null?a:ke(this.visibility,a,s),d=new Map(this.interestFns),u=this.deps.definition.entities,p=[];for(let{collection:f,ids:y}of r.collections){let b=c[f],k=l[f];if(!we(b)||!we(k))return;let A=u[f],j=d.get(f),M=(E,_)=>{if(E===void 0||!_)return{ok:!0,value:E};try{return{ok:!0,value:this.core.runReadOnly(()=>A(E))}}catch{return{ok:!1,value:void 0}}};for(let E of y){let _=M(Object.prototype.hasOwnProperty.call(b,E)?b[E]:void 0,c!==o),I=M(Object.prototype.hasOwnProperty.call(k,E)?k[E]:void 0,l!==a);if(!_.ok||!I.ok)return;Object.is(_.value,I.value)||_.value!==void 0&&I.value!==void 0&&JSON.stringify(_.value)===JSON.stringify(I.value)||p.push({collection:f,id:E,before:_.value,after:I.value,beforeKey:_.value===void 0?null:this.interestKey(j,_.value,E),afterKey:I.value===void 0?null:this.interestKey(j,I.value,E)})}}return{rest:[],entities:p,whole:[]}}interestDiff(e,t){let r=new Set(this.interestFns.map(([c])=>c)),s=c=>{let l={};for(let[d,u]of Object.entries(c))r.has(d)||(l[d]=u);return l},i=bs(s(e),s(t)),o=[],a=[];for(let[c,l]of this.interestFns){let d=e[c],u=t[c];if(!we(d)||!we(u)){JSON.stringify(d)!==JSON.stringify(u)&&a.push({collection:c,after:u});continue}for(let p of new Set([...Object.keys(d),...Object.keys(u)])){let f=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0,y=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0;Object.is(f,y)||f!==void 0&&y!==void 0&&JSON.stringify(f)===JSON.stringify(y)||o.push({collection:c,id:p,before:f,after:y,beforeKey:f===void 0?null:this.interestKey(l,f,p),afterKey:y===void 0?null:this.interestKey(l,y,p)})}}return{rest:i,entities:o,whole:a}}interestOps(e,t){let r=new Set(t),s=o=>o===null||r.has(o),i=[...e.rest];for(let o of e.entities){let a=o.before!==void 0&&s(o.beforeKey);o.after!==void 0&&s(o.afterKey)?i.push({o:"r",p:[o.collection,o.id],val:o.after}):a&&i.push({o:"x",p:[o.collection,o.id]})}for(let o of e.whole){let a=this.filterInterest({[o.collection]:o.after},t);i.push({o:"r",p:[o.collection],val:a[o.collection]})}return i}interestChange(e,t,r,s){let i={...t,interest:[...e.int],lastSeen:s};this.handles.set(i.h,i);let o={peer:r,h:t.h,frame:P({k:"ok",q:e.q,h:t.h})};if(this.interestFns.length===0||this.deferred.has(t.h))return this.accept([o]);let a=this.project(r,t.audience);if(a===null)return this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)]);let c=this.filterInterest(a,t.interest),l=this.filterInterest(a,i.interest),d=[];for(let[y]of this.interestFns){let b=c[y],k=l[y];if(!(!we(b)||!we(k))){for(let A of Object.keys(k))Object.prototype.hasOwnProperty.call(b,A)||d.push({o:"r",p:[y,A],val:k[A]});for(let A of Object.keys(b))Object.prototype.hasOwnProperty.call(k,A)||d.push({o:"x",p:[y,A]})}}if(d.length===0)return this.accept([o]);let u=String(this.core.revision),p=t.revision===this.core.revision?Ss({k:"delta",h:t.h,g:String(t.generation),base:u,r:u,ops:d},this.deps.maxEventBytes):null;if(p!==null)return this.accept([{peer:r,h:t.h,frame:p},o]);let f=this.install(i,null);return f===null?(this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)])):this.accept([...f,o])}project(e,t,r=this.core.getState()){try{let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=this.deps.projectFor!==void 0?this.deps.projectFor(r,s):this.deps.project!==void 0?this.deps.project(r,t):r;this.visibility===null&&i===r&&this.warnOnce(`store '${this.deps.definition.id}': every player receives the full state. Declare \`visibility: 'open'\` on the definition if that is intended, or rules for what is secret.`);let o=this.visibility===null?i:ke(this.visibility,i,s);if(o===r)return r;try{return this.deps.definition.state(o)}catch(a){throw this.warnOnce(`store '${this.deps.definition.id}': a projection failed the state validator, so the player got empty() \u2014 ${a instanceof Error?a.message:String(a)}`+(this.visibility===null?"":" (a hidden field is the HIDDEN marker: wrap its parser with hiddenOr)")),a}}catch{try{return this.deps.definition.empty()}catch{return null}}}bind(e,t,r){let s=this.handles.get(e);return s===void 0?"handle-unknown":r-s.lastSeen>=$n?(this.forget(e,"expired"),"handle-expired"):s.peer!==t?"handle-foreign-peer":s}no(e,t,r,s){return{peer:e,h:t,frame:P(s===null?{k:"no",h:t,code:r}:t===null?{k:"no",q:s,code:r}:{k:"no",q:s,h:t,code:r})}}refuse(e,t=[]){return this.counters[e]=(this.counters[e]??0)+1,{out:t,refused:e,deferred:null}}};function bs(n,e){let t=[];for(let r of Object.keys(e)){let s=e[r];if(Object.prototype.hasOwnProperty.call(n,r)&&Object.is(n[r],s))continue;let i=Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0,o=i===void 0?null:po(r,i,s);if(o!==null){t.push(...o);continue}i!==void 0&&JSON.stringify(i)===JSON.stringify(s)||t.push({o:"r",p:[r],val:s})}for(let r of Object.keys(n))Object.prototype.hasOwnProperty.call(e,r)||t.push({o:"x",p:[r]});return t}var uo=128;function po(n,e,t){let r=a=>typeof a=="object"&&a!==null&&!Array.isArray(a);if(!r(e)||!r(t))return null;let s=[],i=Math.min(uo,Math.max(1,Math.floor(Object.keys(t).length/2))),o=a=>N(a)<=Ve&&!["__proto__","constructor","prototype"].includes(a);for(let a of Object.keys(t)){let c=t[a];if(!(Object.prototype.hasOwnProperty.call(e,a)&&(Object.is(e[a],c)||JSON.stringify(e[a])===JSON.stringify(c)))&&(!o(a)||(s.push({o:"r",p:[n,a],val:c}),s.length>i)))return null}for(let a of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,a)&&(!o(a)||(s.push({o:"x",p:[n,a]}),s.length>i)))return null;return s}function Ss(n,e){let t;try{t=P(n)}catch{return null}return N(t)<=e?t:null}function fo(n){return"q"in n&&typeof n.q=="string"?n.q:null}var ks=5e3,Jn=500;function ct(n){let e=/^\d+$/.test(n),t=/^(0x)?[0-9a-f]{1,16}$/i.test(n),r;try{if(e)r=BigInt(n).toString(16).padStart(16,"0");else if(t)r=BigInt(n.startsWith("0x")?n:`0x${n}`).toString(16).padStart(16,"0");else return null}catch{return null}return r.length===16?r:null}function Ue(n){return/^[0-9a-f]{16}$/i.test(n)?n.toLowerCase():ct(n)}var Fn=new WeakMap,Zt=new WeakMap;function ho(n){try{let e=JSON.parse(n);return e!==null&&typeof e=="object"&&e.k!=="join"&&typeof e.h=="string"?e.h:null}catch{return null}}var As=new WeakMap;function dt(n){return As.get(n)}function xs(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var Es=new TextEncoder,yo=new TextDecoder;function Vn(n){let e=n.streamId??`store/${n.definition.id}`,t=n.store??n.definition.id,r=Fn.get(n.transport)??new Set;if(r.has(t))throw new h("invalid-data",`a store named ${t} is already hosted on this transport: name each store of one definition, or a join for that name is ambiguous`);r.add(t),Fn.set(n.transport,r);let s=new lt({definition:n.definition,store:t,authorize:n.authorize,project:n.project,projectFor:n.projectFor,onEvent:n.onEvent,areaOf:n.areaOf,warn:n.dev===!0?w=>console.warn(`[@net-mesh/browser] ${w}`):typeof n.dev=="function"?n.dev:void 0,actions:n.actions,inputs:n.inputs,maxEventBytes:n.maxEventBytes,now:n.now??(()=>Date.now()),newHandle:n.newHandle??(()=>xs(16)),newIncarnation:n.newIncarnation??(()=>xs(8)),canProject:n.canProject??(()=>!0)});if(n.definition.visibility!==void 0){let w=ke(Ee(n.definition.visibility),n.initialState,null);try{n.definition.state(w)}catch(R){throw new h("invalid-data",`store '${n.definition.id}': the state validator rejects a view with secrets hidden \u2014 wrap each field a rule hides with hiddenOr(\u2026): ${R instanceof Error?R.message:String(R)}`,{cause:R})}}s.commit(n.initialState);let i=new Map,o=null,a=new Map,c={},l=!1,d=null;async function u(w){let R=i.get(w);if(R!==void 0)return R;let C=a.get(w);if(C!==void 0)return C;let K=Promise.resolve(n.transport.openStream({reliability:"reliable",peer:w,label:e})).then(V=>{if(a.delete(w),l){try{V.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return i.set(w,V),V}).catch(V=>{throw a.delete(w),V});return a.set(w,K),K}async function p(w){for(let R of w){if(l)return;let C=Es.encode(R.frame),U=await u(R.peer);try{await U.send(C)}catch(K){if(l)return;if(!it(K))throw K;if(i.get(R.peer)===U){i.delete(R.peer),a.delete(R.peer),c["reopened-stream"]=(c["reopened-stream"]??0)+1;try{U.close()}catch{}}await(await u(R.peer)).send(C)}}}function f(w){w.catch(()=>{c["send-failed"]=(c["send-failed"]??0)+1})}function y(w){f(p(w.out)),w.deferred!==null&&f(w.deferred.then(R=>y(R))),k()}let b=!1;function k(){if(!(b||l)){b=!0;try{let w=s.drainEvents();w.out.length>0&&f(p(w.out))}finally{b=!1}}}let A=Zt.get(n.transport)??new Set;A.add(s),Zt.set(n.transport,A);let j=n.transport.onEvent(w=>{if(w.type!=="stream_data")return;let R=w.peerNode;if(typeof R!="string"||R.length===0){c["no-authenticated-peer"]=(c["no-authenticated-peer"]??0)+1;return}let C=w.payload;if(C===void 0){c["no-payload"]=(c["no-payload"]??0)+1;return}let U=w.streamId;if(o!==null&&U!==void 0&&U!==o){c["foreign-stream"]=(c["foreign-stream"]??0)+1;return}let K;try{K=yo.decode(C)}catch{c["undecodable-frame"]=(c["undecodable-frame"]??0)+1;return}let V=ct(R);if(V===null){c["unusable-peer"]=(c["unusable-peer"]??0)+1;return}let B=Zt.get(n.transport);if(B!==void 0&&B.size>1){let m=ho(K);if(m!==null&&s.handle(m)===void 0){let x=!1;for(let v of B)v!==s&&v.handle(m)!==void 0&&(x=!0);if(x||B.values().next().value!==s){c["sibling-handle"]=(c["sibling-handle"]??0)+1;return}}}let g=s.receive(K,V);U!==void 0&&o===null&&g.refused===null&&(o=U),y(g)}),M=n.schedule??((w,R)=>{let C=setInterval(w,R);return()=>{clearInterval(C)}}),E=M(()=>{if(l)return;let w=(n.now??(()=>Date.now()))(),R=s.sweep(w);R.length>0&&f(p(R.filter(C=>i.has(C.peer)).map(C=>({peer:C.peer,h:C.h,frame:P({k:"no",h:C.h,code:"closed"})})))),y(s.resumeDeferred(w))},ks);async function _(){l=!0,E(),j();let w=s.farewell();await Promise.all(w.map(async R=>{let C=i.get(R.peer);if(C===void 0){c["farewell-unreachable"]=(c["farewell-unreachable"]??0)+1;return}try{await I(Promise.resolve(C.send(Es.encode(R.frame))))}catch{c["farewell-failed"]=(c["farewell-failed"]??0)+1}}));for(let R of i.values())try{R.close()}catch{c["stream-close-failed"]=(c["stream-close-failed"]??0)+1}i.clear(),a.clear(),Fn.get(n.transport)?.delete(t),Zt.get(n.transport)?.delete(s)}function I(w){return new Promise((R,C)=>{let U=()=>{B(),C(new h("timeout","the farewell did not flush before the deadline"))},K=M(U,Jn),V=setTimeout(U,Jn),B=()=>{K(),clearTimeout(V)};w.then(()=>{B(),R()},g=>{B(),C(g instanceof Error?g:new Error(String(g)))})})}let W=n.transport.nodeIdHex()??s.incarnationHex,Q=new Set,le={authority:W,definition:n.definition,getState:()=>s.getState(),subscribe:w=>s.subscribe(w),setState:w=>{y(s.commit(w))},setEntities:(w,R)=>{y(s.commitEntities(w,R))},setEntity:(w,R,C)=>{let U={};Object.defineProperty(U,R,{value:C,enumerable:!0,writable:!0,configurable:!0}),y(s.commitEntities(w,U))},counts:()=>({handles:s.handleCount,ledgers:s.ledgerCount,deferred:s.deferredCount,sparseViews:s.sparseViews}),counters:()=>({...s.snapshotCounters(),...c}),close:()=>{if(d===null){d=_();for(let w of[...Q])w();Q.clear()}return d}};return As.set(le,{owner:s,peer:Ue(W)??W,maxEventBytes:n.maxEventBytes,dispatched:y,isClosed:()=>l,onClose:w=>{Q.add(w)}}),le}var Rs=3,ut=class{constructor(e){this.deps=e;this.#d=[...e.audience],this.#l=e.interest===void 0?null:[...e.interest]}deps;#e="joining";#t=null;#r=null;#n=null;#s=null;#g=null;#o=0n;#a=null;#u=!1;#c=null;#f=null;#b=0;#h=0;#p=null;#d;#y=0;#O=new ot;#w={};#l;get interest(){return this.#l===null?null:[...this.#l]}set interest(e){this.#l=e===null?null:[...e]}get desired(){return[...this.#d]}get waiters(){return this.#y}get state(){return this.#e}get handle(){return this.#t}get installed(){return this.#n===null?null:this.#n.toString()}get revision(){return this.#s===null?null:this.#s.toString()}get retired(){return this.#o.toString()}get skipped(){return this.#a===null?null:this.#a.toString()}get dropped(){return{...this.#w}}join(){if(this.#e==="closed")throw new h("closed","a closed replica cannot join again");this.#h+=1,this.#y=1,this.#k();let e=this.deps.newQ();return this.#c=e,this.#f=this.deps.now(),this.#b=0,this.#e="joining",this.deps.core.setStatus({phase:"connecting",stale:this.#v()}),{kind:"join",q:e,frame:P({k:"join",q:e,def:this.deps.definition.id,store:this.deps.store,ver:this.deps.definition.version,key:this.deps.key,aud:[...this.#d],...this.#l===null?{}:{int:[...this.#l]}})}}setAudience(e){if(this.#e==="closed")throw new h("closed","a closed replica cannot change audience");this.#h+=1;let t=[...e];if(this.#e==="installing"&&mo(t,this.#d))return this.#y+=1,[];this.#d=t;let r=this.#t;if(this.#m(),this.#n=null,this.#s=null,this.#a=null,this.#u=!1,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:"syncing",stale:!1,error:null}),r===null)return this.#y=1,[this.join()];let s=this.deps.newQ();return this.#c=s,this.#f=this.deps.now(),this.#y=1,this.#e="installing",[{kind:"aud",q:s,frame:P({k:"aud",q:s,h:r,aud:t})}]}reconnect(){if(this.#e==="closed")throw new h("closed","a closed replica cannot reconnect");this.#h+=1;let e=this.#t;if(this.#m(),e===null)return[this.join()];let t=this.deps.newQ();return this.#c=t,this.#e="installing",this.deps.core.setStatus({phase:"reconnecting",stale:this.#v()}),[{kind:"resume",q:t,frame:P({k:"resume",q:t,h:e,aud:[...this.#d],...this.#l===null?{}:{int:[...this.#l]}})}]}cancelWaiter(){this.#y>0&&(this.#y-=1),!(this.#y>0)&&this.#e==="installing"&&this.cancel()}receive(e){if(this.#e==="closed")return this.#i("closed");let t=Re(e,{maxBytes:this.deps.maxEventBytes,as:"replica"});if(!t.ok)return this.#i(t.reason);let r=t.message;if("h"in r&&r.h!==void 0&&this.#t!==null&&r.h!==this.#t)return this.#i("foreign-handle");switch(r.k){case"man":return this.#A(r);case"snap":return this.#R(r);case"delta":return this.#P(r);case"no":return this.#I(r.code,r.q);case"ok":case"res":return this.#i("unimplemented-kind")}}tick(){let e=this.deps.now();if(this.#e==="installing"&&this.#p!==null)return this.#p.expired(e)?this.#E("assembly-deadline"):[];if(this.#f===null||e-this.#f<Kt)return[];if(this.#e!=="joining"&&this.#e!=="installing")return[];if(this.#b>=Rs)return this.#f=null,this.#e="fenced",this.#c=null,this.#m(),this.#S("failed",new h("timeout",`no store named ${this.deps.store} answered the join`)),[];let t=this.#b,r=this.join();return this.#b=t+1,[r]}cancel(){this.#e!=="closed"&&(this.#h+=1,this.#m(),this.#c=null,this.#e="fenced",this.#a=null,this.#u=!1,this.#S("failed"))}#A(e){let t=ae(e.g),r=e.q!==void 0&&e.q===this.#c;if(e.q!==void 0&&!r)return this.#i("stale-correlation");if(t<=this.#o)return this.#i("stale-generation");if(r){if(this.#e!=="joining"&&this.#e!=="installing"&&this.#e!=="fenced")return this.#i("unexpected-manifest")}else{if(this.#e==="fenced")return this.#i("fenced");if(this.#e!=="ready")return this.#a=this.#a===null?t:go(this.#a,t),this.#i("mid-transition")}if(this.#t===null)this.#t=e.h,this.#r=e.inc;else if(this.#r!==null&&e.inc!==this.#r)return this.#i("foreign-incarnation");this.#m(),this.#o=t;let s={h:e.h,g:e.g,r:e.r,n:e.n,bytes:e.bytes},i=this.#O.open(s,this.deps.now());return"accept"in i?(this.#g=t,this.#p=i,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),{out:[],dropped:null}):{out:this.#E(i.reason),dropped:i.reason}}#R(e){let t=this.#p;if(t===null)return this.#i("no-open-assembly");let r=this.#h,s=t.accept({h:e.h,g:e.g,r:e.r,n:e.n,i:e.i,d:e.d},i=>this.deps.definition.state(i),this.deps.now());return this.#h!==r?this.#i("superseded-installation"):s.ok?s.done?this.#_(s.document,e.g,e.r,r):{out:[],dropped:null}:s.fatal?{out:this.#E(s.reason),dropped:s.reason}:this.#i(s.reason)}#_(e,t,r,s){return this.deps.core.applySnapshot(e),this.#g=null,this.#p=null,this.#O.reclaim(this.#t,t),this.#h!==s?(this.#n=null,this.#s=null,this.#S("failed"),this.#i("superseded-installation")):(this.#n=ae(t),this.#s=ae(r),this.#c=null,this.#e="ready",this.deps.core.setStatus({phase:"ready",stale:!1,error:null}),{out:this.#C(),dropped:null})}#P(e){if(this.#e!=="ready")return this.#u=!0,this.#i("not-ready");let t=ae(e.g),r=this.#n;if(r===null||t!==r)return r!==null&&t>r?{out:this.#x("generation-ahead"),dropped:"generation-ahead"}:this.#i("stale-generation");if(this.#s===null||ae(e.base)!==this.#s)return{out:this.#x("gap"),dropped:"gap"};let s=this.deps.core.applyDelta(e.ops);return s.ok?(this.#s=ae(e.r),{out:[],dropped:null}):{out:this.#x(s.reason),dropped:s.reason}}#I(e,t){if(e==="owner-lost")return this.#m(),this.#e="closed",this.#t=null,this.#S("closed"),{out:[],dropped:"owner-lost"};if(e==="closed"){let r=this.#e==="fenced";return this.#k(),r?(this.#S("failed"),{out:[],dropped:"closed-while-fenced"}):(this.#S("connecting"),{out:[this.join()],dropped:"closed"})}return t===void 0||t!==this.#c?this.#i("stale-correlation"):(this.#m(),this.#c=null,this.#e="fenced",this.#S("failed",new h(e,`the request was refused: ${e}`)),{out:[],dropped:`refused-${e}`})}#E(e){return this.#m(),this.#g=null,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),this.#x(e)}#x(e){let t=this.#t;if(t===null)return[];let r=this.deps.newQ();return this.#c=r,this.#f=this.deps.now(),this.#e="installing",this.#a=null,this.#u=!1,this.deps.core.setStatus({phase:this.#v()?"reconnecting":"syncing",stale:this.#v()}),[{kind:"resync",q:r,frame:P({k:"resync",q:r,h:t,g:this.#n===null?"0":this.#n.toString(),have:this.#s===null?"0":this.#s.toString()})}]}#C(){let e=this.#a,t=this.#u;return!t&&(e===null||this.#n===null||e<=this.#n)?(this.#a=null,this.#u=!1,[]):this.#x(t?"behind":"skipped-refresh")}#k(){this.#m(),this.#t=null,this.#r=null,this.#n=null,this.#s=null,this.#o=0n,this.#a=null,this.#u=!1,this.#c=null}#m(){this.#p!==null&&(this.#p.reclaim(),this.#p=null),this.#t!==null&&this.#O.reclaimHandle(this.#t),this.#g=null}#v(){return this.#n!==null}#S(e,t=null){this.#n=null,this.#s=null,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:e,stale:!1,error:t})}#i(e){return this.#w[e]=(this.#w[e]??0)+1,{out:[],dropped:e}}};function go(n,e){return n>e?n:e}function mo(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Ps=2e4,Kn=1e4,Is=6e4,Cs=1e3,Xn=64,_s=new TextEncoder,bo=new TextDecoder;function pt(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function Gn(n){let e=n.transport.nodeIdHex(),t=Ue(n.host);if(e!==null&&t!==null&&Ue(e)===t)throw new h("invalid-data","a replica cannot join the node it runs on: hold the hostStore handle instead");let r=n.streamId??`store/${n.definition.id}`,s=n.now??(()=>Date.now()),i=n.schedule??((g,m)=>{let x=setInterval(g,m);return()=>{clearInterval(x)}}),o=new Se({definition:n.definition,initialState:n.definition.empty()}),a=new ut({definition:n.definition,core:o,maxEventBytes:n.maxEventBytes,now:s,newQ:()=>(n.newQ??(()=>pt(8)))(),audience:n.audience,store:n.store??n.definition.id,key:n.key,...n.interest===void 0?{}:{interest:n.interest}}),c=new Map,l=new Map,d=0n,u=!1,p=null,f=null,y=0,b=[],k=null;async function A(){if(p!==null)return p;if(f!==null)return f;if(t===null)return Promise.reject(new h("invalid-data",`the host id is not a node id: ${n.host}`));let g=y;return f=Promise.resolve(n.transport.connectPeer?.(t)).catch(()=>{}).then(()=>n.transport.openStream({reliability:"reliable",peer:t,label:r})).then(m=>{if(g!==y){try{m.close()}catch{}throw new h("aborted","the stream open was superseded by reconnect()")}if(f=null,u){try{m.close()}catch{}throw new h("closed","the store closed while its stream was opening")}return p=m,m}).catch(m=>{throw g===y&&(f=null),m}),f}async function j(g){for(let m of g){if(u)return;let x=_s.encode(m),v=await A();try{await v.send(x)}catch(H){if(u)return;if(!it(H))throw H;if(p===v){p=null,f=null;try{v.close()}catch{}}await(await A()).send(x)}}}function M(g){let m=g instanceof h?g:new h("indeterminate",`the transport could not carry a store frame: ${String(g)}`);for(let x of b.splice(0,b.length))x.reject(m);W(m);for(let[x,v]of[...c])c.delete(x),v.reject(m)}function E(g){j(g).catch(M)}let _=g=>g.map(m=>m.frame);function I(g){if(a.state==="ready"){W(null);for(let x of b.splice(0,b.length))x.resolve();return}if(a.state!=="fenced"&&a.state!=="closed")return;let m=g??new h(a.state==="closed"?"owner-lost":"aborted",`the store handle is ${a.state}`);W(m);for(let x of b.splice(0,b.length))x.reject(m)}function W(g){let m=k;if(m!==null){k=null,m.q!==null&&c.delete(m.q);for(let x of[...m.calls])m.calls.delete(x),g===null?x.resolve():x.reject(g)}}function Q(g){return W(new h("aborted","a newer transition superseded this one before it installed")),k={q:g,calls:new Set},g===null?null:c.size>=Xn?new h("capacity","too many requests are already outstanding"):(c.set(g,{resolve:()=>W(null),reject:m=>W(m),at:s(),transition:!0}),null)}function le(){return new Promise((g,m)=>{let x={resolve:g,reject:m,deadlineAt:s()+Is},v=k??{q:null,calls:new Set};k=v,v.calls.add(x)})}let w=n.transport.onEvent(g=>{if(u||g.type!=="stream_data"||typeof g.peerNode!="string"||t===null||ct(g.peerNode)!==t)return;let m=g.payload;if(m===void 0)return;let x=bo.decode(m),v=Re(x,{maxBytes:n.maxEventBytes,as:"replica"});if(v.ok&&"q"in v.message&&typeof v.message.q=="string"){let Z=c.get(v.message.q);if(Z!==void 0&&(v.message.k==="res"||v.message.k==="ok")){c.delete(v.message.q),Z.resolve(v.message.k==="res"?v.message.out:void 0);return}Z!==void 0&&v.message.k==="no"&&(c.delete(v.message.q),Z.reject(new h(v.message.code,`the store refused: ${v.message.code}`)))}let H=null;v.ok&&v.message.k==="no"&&(H=new h(v.message.code,`the store refused: ${v.message.code}`));let G=a.receive(x);E(_(G.out)),I(H)}),R=i(()=>{if(u)return;let g=a.handle;g!==null&&E([P({k:"alive",q:pt(8),h:g})])},Ps),C=i(()=>{if(u)return;let g=s(),m=k;if(m!==null){for(let x of[...m.calls])g<x.deadlineAt||(m.calls.delete(x),a.cancelWaiter(),x.reject(new h("indeterminate","the transition did not install before its deadline")));m.q!==null&&m.calls.size===0&&W(null)}for(let[x,v]of[...c])v.transition||g-v.at<Kn||(c.delete(x),v.reject(new h("indeterminate","the store did not answer before the deadline")))},Kn),U=i(()=>{u||(E(_(a.tick())),I(o.getStatus().error??null))},Cs),K;try{K=a.join()}catch(g){throw new h("invalid-data","the join request cannot be encoded",{cause:g})}Q(null),E(_([K]));function V(g){return c.size>=Xn?Promise.reject(new h("capacity","too many requests are already outstanding")):new Promise((m,x)=>{c.set(g,{resolve:v=>{m(v)},reject:x,at:s(),transition:!1})})}let B={getState:()=>o.getState(),subscribe:g=>o.subscribe(g),getStatus:()=>o.getStatus(),subscribeStatus:g=>o.subscribeStatus(g),ready:()=>new Promise((g,m)=>{if(u){m(new h("closed","this store handle is closed"));return}if(a.state==="ready"){g();return}if(a.state==="closed"){m(new h("owner-lost","the store owner closed this handle"));return}b.push({resolve:g,reject:m})}),act:async(g,m)=>{if(u)throw new h("closed","this store handle is closed");if(a.state==="closed")throw new h("owner-lost","the store owner closed this handle");let x=a.handle;if(x===null)throw new h("not-ready","no handle yet: the join has not been answered");d+=1n;let v=(n.newQ??(()=>pt(8)))(),H;try{H=P({k:"act",q:v,h:x,s:d.toString(),name:g,in:m})}catch(Z){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:Z})}let G=V(v);return G.catch(()=>{}),await j([H]),await G},input:(g,m)=>{if(u)return{type:"dropped",reason:"not-ready"};let x=a.handle;if(x===null||a.state!=="ready")return{type:"dropped",reason:"not-ready"};let v=(l.get(g)??0n)+1n;l.set(g,v);let H;try{H=P({k:"in",h:x,s:v.toString(),name:g,in:m})}catch(G){throw new h("invalid-data",`the input for '${g}' cannot be encoded`,{cause:G})}return E([H]),{type:v===1n?"queued":"replaced"}},setAudience:async g=>{if(u)throw new h("closed","this store handle is closed");let m;try{m=a.setAudience(g)}catch(H){throw new h("invalid-data","the audience cannot be encoded",{cause:H})}let x=m[0];if(x!==void 0){let H=Q(x.q);if(H!==null)throw H}let v=le();v.catch(()=>{}),x!==void 0&&await j(_(m)),await v},setInterest:async g=>{if(u)throw new h("closed","this store handle is closed");let m=[...g],x="0".repeat(32),v;try{v=P({k:"int",q:"0".repeat(16),h:x,int:m})}catch(rn){throw new h("invalid-data","the interest set cannot be encoded",{cause:rn})}if(N(v)>n.maxEventBytes)throw new h("capacity","the interest set does not fit one message");a.interest=m;let H=a.handle;if(H===null||a.state!=="ready")return await B.ready(),a.interest===null||a.interest.join("\0")!==m.join("\0")?void 0:B.setInterest(m);let G=(n.newQ??(()=>pt(8)))(),Z=V(G);Z.catch(()=>{}),await j([P({k:"int",q:G,h:H,int:m})]),await Z},reconnect:async()=>{if(u)throw new h("closed","this store handle is closed");let g=p;if(p=null,y+=1,f=null,g!==null)try{g.close()}catch{}let m;try{m=a.reconnect()}catch(x){throw new h("invalid-data","the reconnect request cannot be encoded",{cause:x})}m[0]!==void 0&&Q(null),await j(_(m))},close:async()=>{if(u)return;u=!0,R(),C(),U();let g=a.handle;if(g!==null)try{await(await A()).send(_s.encode(P({k:"leave",q:pt(8),h:g})))}catch{}w(),W(new h("aborted","the store handle closed before this request was answered"));for(let m of c.values())m.reject(new h("aborted","the store handle closed before this request was answered"));c.clear();for(let m of b.splice(0,b.length))m.reject(new h("closed","the store handle closed before a view was installed"));p?.close(),p=null,o.close()}};return B}var Hs="0".repeat(16),zn="0".repeat(32);function js(n,e,t){let r;try{r=t==="act"?P({k:"act",q:Hs,h:zn,s:"1",name:n,in:e}):P({k:"in",h:zn,s:"1",name:n,in:e})}catch(i){throw new h("invalid-data",`the input for '${n}' cannot be encoded`,{cause:i})}let s=Ae(r);if(!s.ok||typeof s.value!="object"||s.value===null||Array.isArray(s.value))throw new h("invalid-data",`the input for '${n}' cannot be encoded`);return s.value.in}function So(n){let e=Ae(JSON.stringify(n));return e.ok?e.value:n}function Yn(n,e){let t=dt(n);if(t===void 0)throw new h("invalid-data","hostPlayer needs a handle returned by hostStore");let{owner:r,peer:s}=t,i=n.definition,o=new Se({definition:i,initialState:i.empty(),phase:"syncing"}),a=[...e.audience],c=e.interest===void 0?null:[...e.interest],l=!1,d=!1,u=new Map;function p(E,_){d=!0,_?.code==="forbidden"&&queueMicrotask(()=>k("refused")),o.applySnapshot(i.empty()),o.setStatus({phase:E,stale:!1,error:_})}function f(){if(l||d)return;if(t.isClosed()){p("closed",null);return}if(!r.localRead(s,a)){p("failed",new h("forbidden","the store refused: forbidden"));return}let E=r.localView(s,a,c);if(E===null){p("failed",new h("capacity","the store refused: capacity"));return}o.applySnapshot(E),o.setStatus({phase:"ready",stale:!1,error:null})}let y=r.subscribe(()=>{f()});t.onClose(()=>{y(),!l&&!d&&p("closed",null)}),f();let b=!1;o.getStatus().phase==="ready"&&(b=!0,r.localPresence(s,!0,a),t.dispatched({out:[],refused:null,deferred:null}));function k(E){!b||t.isClosed()||(b=!1,r.localPresence(s,!1,a,E),t.dispatched({out:[],refused:null,deferred:null}))}function A(){return l?new h("closed","this store handle is closed"):t.isClosed()?new h("owner-lost","the store owner closed this handle"):d?o.getStatus().error??new h("owner-lost","the store owner closed this handle"):null}function j(){let E=[...u];if(u.clear(),A()===null)for(let[_,I]of E)t.dispatched(r.localInput(_,I,s))}function M(E,_,I){return _===void 0?o.subscribe(E):o.subscribe(E,_,I)}return{getState:()=>o.getState(),subscribe:M,getStatus:()=>o.getStatus(),subscribeStatus:E=>o.subscribeStatus(E),ready:()=>{let E=o.getStatus();return E.phase==="ready"?Promise.resolve():Promise.reject(E.error??new h(l?"closed":"owner-lost","this store handle is not ready"))},act:async(E,_)=>{let I=A();if(I!==null)throw I;let W=js(E,_,"act");await Promise.resolve();let Q=A();if(Q!==null)throw Q;let{outcome:le,dispatched:w}=r.localAct(E,W,s);if(t.dispatched(w),le.kind==="refusal")throw new h(le.code,`the store refused: ${le.code}`);return So(le.out)},input:(E,_)=>{if(A()!==null||o.getStatus().phase!=="ready")return{type:"dropped",reason:"not-ready"};let I=js(E,_,"in"),W=u.size===0,Q=u.has(E);return u.set(E,I),W&&queueMicrotask(j),{type:Q?"replaced":"queued"}},setAudience:async E=>{let _=A();if(_!==null)throw _;try{P({k:"aud",q:Hs,h:zn,aud:[...E]})}catch(W){throw new h("invalid-data","the audience cannot be encoded",{cause:W})}await Promise.resolve();let I=A();if(I!==null)throw I;if(!r.localRead(s,E))throw new h("forbidden","the store refused: forbidden");a=[...E],f()},setInterest:async E=>{let _=A();if(_!==null)throw _;let I=[...E];await Promise.resolve(),c=I,f()},reconnect:()=>Promise.resolve(),close:()=>(l||(l=!0,k("left"),u.clear(),y(),o.close()),Promise.resolve())}}var he=class extends Error{constructor(t,r){super(r);this.code=t;this.name="InventoryError"}code},Qn=64,Zn=Object.freeze({});function wo(){return Zn}function Ls(n){if(typeof n!="string"||n.length===0||n.length>Qn||n==="__proto__")throw new he("invalid",`an item id is 1-${Qn} characters, got ${JSON.stringify(n)}`)}function Ts(n){if(!Number.isSafeInteger(n)||n<1)throw new he("invalid",`a count is a whole number of at least 1, got ${String(n)}`)}function vo(n,e){let t=e?.maxCount;return t===void 0?Number.MAX_SAFE_INTEGER:typeof t=="number"?t:Object.prototype.hasOwnProperty.call(t,n)?t[n]:Number.MAX_SAFE_INTEGER}function en(n,e){return n===void 0||!Object.prototype.hasOwnProperty.call(n,e)?0:n[e]??0}function Oo(n,e,t=1){return en(n,e)>=t}function Ds(n,e,t,r){Ls(e),Ts(t);let s=en(n,e),i=s+t;if(!Number.isSafeInteger(i)||i>vo(e,r))throw new he("full",`no room for ${String(t)} more ${e}`);if(s===0&&r?.maxKinds!==void 0&&Object.keys(n).length>=r.maxKinds)throw new he("full",`no room for another kind of item (${String(r.maxKinds)} at most)`);return Object.freeze({...n,[e]:i})}function xo(n,e,t){Ls(e),Ts(t);let r=en(n,e);if(r<t)throw new he("insufficient",`has ${String(r)} ${e}, needs ${String(t)}`);let s={...n};return r===t?delete s[e]:s[e]=r-t,Object.freeze(s)}function Eo(n,e){if(typeof n!="object"||n===null||Array.isArray(n))throw new he("invalid","an inventory is an object of item id \u2192 count");let t=Zn;for(let[r,s]of Object.entries(n)){if(typeof s!="number")throw new he("invalid",`the count of ${r} is not a number`);t=Ds(t,r,s,e)}return t}function ko(n,e){return Object.prototype.hasOwnProperty.call(n,e)?n[e]:Zn}function Ao(n,e){return Object.prototype.hasOwnProperty.call(n,e)?{[e]:n[e]}:{}}function Ms(n){if(!(n>0)||!Number.isFinite(n))throw new RangeError(`a cell size is a positive number, got ${String(n)}`)}function Ro(n,e,t){return Ms(t),`${String(Math.floor(n/t))}:${String(Math.floor(e/t))}`}function _o(n){let e=/^(-?\d+):(-?\d+)$/.exec(n);return e===null?null:[Number(e[1]),Number(e[2])]}function Ns(n,e,t){Ms(t.size);let r=t.radius??1,s=Math.floor(n/t.size),i=Math.floor(e/t.size),o=[`${String(s)}:${String(i)}`];for(let a=-r;a<=r;a+=1)for(let c=-r;c<=r;c+=1)(a!==0||c!==0)&&o.push(`${String(s+a)}:${String(i+c)}`);return o}function Po(n,e,t,r){let s=Ns(e,t,r),o=(r.radius??1)+(r.margin??1),a=Math.floor(e/r.size),c=Math.floor(t/r.size),l=new Set(s);for(let d of n){if(l.has(d))continue;let u=_o(d);u!==null&&Math.abs(u[0]-a)<=o&&Math.abs(u[1]-c)<=o&&(s.push(d),l.add(d))}return s}function Io(n,e){if(n.length!==e.length)return!1;let t=new Set(n);return e.every(r=>t.has(r))}var J=class extends Error{constructor(t,r){super(r);this.code=t;this.name="LobbyError"}code},Ws=64,qs=256,er=512,Us=256,tn="ABCDEFGHJKMNPQRSTUVWXYZ23456789",tr=6,$s=2e3,Fs=8104,Co=/^[a-z0-9][a-z0-9._-]{0,63}$/,Js=1,ft=new TextEncoder,jo=new TextDecoder;function nr(n){if(!Co.test(n))throw new J("invalid",`a game name is 1-64 of a-z 0-9 . _ - (starting with a letter or digit), got ${JSON.stringify(n)}`)}function rr(n){let e=n.toUpperCase().replace(/[\s-]/g,"");if(e.length!==tr||[...e].some(t=>!tn.includes(t)))throw new J("invalid",`not a lobby code: ${JSON.stringify(n)}`);return e}function Ho(){let n=256-256%tn.length,e="";for(;e.length<tr;){let t=new Uint8Array(16);crypto.getRandomValues(t);for(let r of t)r<n&&e.length<tr&&(e+=tn[r%tn.length])}return e}function Lo(n,e){return`net-lobby:${n}:seek:${e}`}function Vs(n){return`net-lobby:${n}`}function sr(n){return`net-lobby:${n}:rec:`}async function Ks(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",ft.encode(`net-lobby${n}${e}`))),r="";for(let s of t.subarray(0,16))r+=s.toString(16).padStart(2,"0");return`net-lobby:${n}:code:${r}`}function To(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Do(n){if(!/^[A-Za-z0-9_-]*$/.test(n))return null;try{let e=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(e,t=>t.charCodeAt(0))}catch{return null}}function Xs(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new J("invalid","lobby info is a flat object of strings, numbers and booleans");let e={};for(let[t,r]of Object.entries(n)){if(typeof r=="number"?!Number.isFinite(r):typeof r!="string"&&typeof r!="boolean")throw new J("invalid",`lobby info.${t} must be a string, a finite number or a boolean`);e[t]=r}if(ft.encode(JSON.stringify(e)).length>qs)throw new J("invalid",`lobby info is over ${qs} bytes of JSON`);return Object.freeze(e)}function Gs(n){if(typeof n!="string"||n.trim().length===0||[...n].length>Ws)throw new J("invalid",`a lobby name is 1-${Ws} characters`);return n}function zs(n){if(typeof n!="number"||!Number.isInteger(n)||n<1||n>Us)throw new J("invalid",`capacity is a whole number from 1 to ${Us}`);return n}function Bs(n,e){let t=JSON.stringify({v:Js,c:e.code,n:e.name,p:e.players,m:e.capacity,s:e.store,i:e.info}),r=sr(n)+To(ft.encode(t));if(ft.encode(r).length>er)throw new J("invalid",`the lobby record is over ${er} bytes: shorten the name or info`);return r}function Mo(n,e){if(ft.encode(e).length>er)return null;let t=Do(e.slice(sr(n).length));if(t===null)return null;let r;try{r=JSON.parse(jo.decode(t))}catch{return null}if(typeof r!="object"||r===null)return null;let s=r;try{if(s.v!==Js||typeof s.c!="string"||typeof s.s!="string"||s.s.length>200)return null;let i=zs(s.m),o=s.p;return typeof o!="number"||!Number.isInteger(o)||o<0||o>i?null:{code:rr(s.c),name:Gs(s.n),players:o,capacity:i,store:s.s,info:Xs(s.i??{})}}catch{return null}}function nn(n){let e=Ue(n);if(e!==null)return e;throw new J("invalid",`not a peer id: ${JSON.stringify(n)}`)}async function uc(n){let{node:e,game:t}=n;nr(t);let r=Gs(n.name),s=zs(n.capacity),i=Xs(n.info??{}),o=n.visibility??"public",a=Ho(),c=`${n.definition.id}@${n.definition.version}`,l=await Ks(t,a);Bs(t,{code:a,name:r,players:s,capacity:s,store:c,info:i});let d=e.nodeIdHex();if(d===null)throw new J("invalid","the node has no id yet: connect it before opening a lobby");let u=nn(d),p=new Set,f=n.authorize??(()=>!0),y=()=>[],b=q=>{let re=q.peer;return p.has(re)||q.type==="read"&&re!==u&&!y().includes(re)&&1+y().filter(ri=>ri!==u).length>=s?!1:f(q)},{audience:k,tags:A,announceEveryMs:j,maxEventBytes:M}=n,{node:E,game:_,name:I,capacity:W,visibility:Q,info:le,audience:w,tags:R,announceEveryMs:C,maxEventBytes:U,authorize:K,...V}=n,B=Vn({...V,transport:e,maxEventBytes:M??Fs,authorize:b}),g=dt(B);y=()=>g.owner.peers();let m=Yn(B,{audience:k??[]});function x(){return[u,...g.owner.peers().filter(q=>q!==u)]}let v=new Set,H=!1,G=null,Z=!1;function rn(){let q=[...A??[],l];return o==="public"&&q.push(Vs(t),Bs(t,{code:a,name:r,players:x().length,capacity:s,store:c,info:i})),q}function ht(){if(!H){if(G!==null){Z=!0;return}G=e.announce(rn()).catch(()=>{}).finally(()=>{G=null,Z&&(Z=!1,ht())})}}let ir=x().join(),ti=g.owner.onMembership(()=>{queueMicrotask(()=>{if(H)return;let q=x();if(q.join()!==ir){ir=q.join(),ht();for(let re of[...v])try{re(q)}catch{}}})});ht();let ni=setInterval(ht,j??$s);return{code:a,game:t,visibility:o,host:B,self:m,players:x,subscribePlayers:q=>(v.add(q),()=>{v.delete(q)}),link:q=>{let re=new URL(q??globalThis.location?.href??"about:blank");return re.searchParams.set("lobby",a),re.toString()},kick:q=>{let re=nn(q);if(re===u)throw new J("invalid","the host cannot kick itself; close the lobby instead");p.add(re),g.dispatched(g.owner.reauthorize())},close:async()=>{H||(H=!0,clearInterval(ni),ti(),v.clear(),await m.close(),await B.close(),await e.announce([...A??[]]).catch(()=>{}))}}}async function pc(n){nr(n.game);let e=sr(n.game),t=[],r=new Set;for(let s of await n.node.query(Vs(n.game))){if(r.has(s.peerIdHex))continue;let i=s.capabilities.find(a=>a.startsWith(e));if(i===void 0)continue;let o=Mo(n.game,i);o!==null&&(r.add(s.peerIdHex),t.push({...o,host:s.peerIdHex}))}return t}async function fc(n){nr(n.game);let e;if(n.lobby!==void 0)e=nn(n.lobby.host);else if(n.code!==void 0){let f=await Ks(n.game,rr(n.code)),y=Date.now()+(n.timeoutMs??2e4),b=[];for(;b=[...new Set((await n.node.query(f)).map(k=>k.peerIdHex))],!(b.length>0||Date.now()>=y);)await new Promise(k=>setTimeout(k,250));if(b.length===0)throw new J("not-found",`no lobby answered to code ${n.code}`);if(b.length>1)throw new J("ambiguous",`${b.length} nodes claim code ${n.code}; join from the list instead`);e=b[0]}else throw new J("invalid","joinLobby needs a code or a lobby");let t=n.node.nodeIdHex();if(t!==null&&nn(t)===e)throw new h("invalid-data","this node hosts that lobby: use lobby.self to play in it");let r=n.node,s=[...n.tags??[]],i=[...s,Lo(n.game,e)],o=null,a=new Set,c=()=>{if(o!==null)return;let f=r.announce(i).catch(()=>{});a.add(f),f.finally(()=>a.delete(f))};c();let l=setInterval(c,$s),d=()=>(o!==null||(clearInterval(l),o=Promise.all(a).then(()=>r.announce(s)).catch(()=>{})),o);if(r.connectPeer!==void 0){let f=Date.now()+(n.timeoutMs??2e4);for(;;)try{await r.connectPeer(e);break}catch(y){if(Date.now()>=f)throw d(),new J("not-found",`could not reach the lobby's host ${e}: ${String(y?.message??y)}`);await new Promise(b=>setTimeout(b,500))}}let u;try{u=Gn({definition:n.definition,transport:r,host:e,audience:n.audience??[],key:n.key??"player",maxEventBytes:n.maxEventBytes??Fs,...n.interest===void 0?{}:{interest:n.interest}})}catch(f){throw d(),f}let p=u.close.bind(u);return u.close=async()=>{let f=d();await p(),await f},u}function hc(n){try{let e=new URL(n??globalThis.location?.href??"").searchParams.get("lobby");return e===null?null:rr(e)}catch{return null}}var Zs="net-mesh:identity";function Ys(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var Qs=/^[0-9a-f]{64}$/;function No(n){if(n===null)return null;try{let e=JSON.parse(n);if(typeof e.entitySecretHex=="string"&&typeof e.noiseSecretHex=="string"&&Qs.test(e.entitySecretHex)&&Qs.test(e.noiseSecretHex))return{entitySecretHex:e.entitySecretHex,noiseSecretHex:e.noiseSecretHex}}catch{}return null}function Wo(n=Zs,e){let t=e;try{t??=globalThis.localStorage}catch{t=void 0}let r=null;try{r=No(t?.getItem(n)??null)}catch{t=void 0}if(r!==null)return r;let s={entitySecretHex:Ys(32),noiseSecretHex:Ys(32)};try{t?.setItem(n,JSON.stringify(s))}catch{}return s}var Be=class extends Error{constructor(t,r,s=null){super(r);this.kind=t;this.status=s}kind;status;name="CredentialRequestError"},ei={unknown_game:"unknown-game",rate_limited:"rate-limited",malformed_request:"malformed-request"};async function qo(n){let e=n.fetch??globalThis.fetch;if(typeof e!="function")throw new Be("unreachable","requestCredential needs fetch");let t=`${n.anchorUrl.replace(/\/+$/,"")}/credential`,r;try{r=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({game:n.game}),...n.signal===void 0?{}:{signal:n.signal}})}catch(o){throw n.signal?.aborted?o:new Be("unreachable",`could not reach ${t}: ${String(o)}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){let o=s?.refusal,a=s?.message,c=typeof o=="string"&&o in ei?ei[o]:r.status===404?"unreachable":"unexpected",l=c==="unreachable"?`${t} issues no credentials (is the anchor started with --game?)`:typeof a=="string"?a:`the anchor answered ${r.status}`;throw new Be(c,l,r.status)}let i=s;if(typeof i?.credentialB64!="string"||typeof i.bootstrapUrl!="string"||typeof i.game!="string")throw new Be("unexpected","the anchor answered without a credential",r.status);return{credentialB64:i.credentialB64,bootstrapUrl:i.bootstrapUrl,game:i.game}}export{Ps as ALIVE_INTERVAL_MS,Kt as ASSEMBLY_DEADLINE_MS,Vt as Assembly,ot as AssemblyTable,_e as AsyncQueue,ys as BINDING_INLINE_MAX_BYTES,jt as BrowserNode,Xr as CALLER_KINDS,gt as ControlPlaneError,Be as CredentialRequestError,Zs as DEFAULT_IDENTITY_KEY,Le as EventHub,Jn as FAREWELL_DEADLINE_MS,as as FORBIDDEN_SEGMENTS,Y as HANDLE_HEX_LENGTH,$n as HANDLE_LEASE_MS,Mt as HIDDEN,ks as HOST_SWEEP_MS,zt as HandleLedger,Ut as INCARNATION_HEX_LENGTH,mt as IceServerConflictError,ge as IdentityError,Yt as InputSequences,he as InventoryError,Hn as LARGEST_FROZEN_ENVELOPE,hs as LEDGER_MAX_AGE_MS,fs as LEDGER_MAX_BYTES,ps as LEDGER_MAX_ENTRIES,$s as LOBBY_ANNOUNCE_MS,tn as LOBBY_CODE_ALPHABET,tr as LOBBY_CODE_LENGTH,z as LeafError,Ne as LeafStream,at as LedgerTable,J as LobbyError,ts as MAX_ASSEMBLY_BYTES_TOTAL,Br as MAX_AUDIENCE_LABELS,$r as MAX_AUDIENCE_LABEL_BYTES,Kr as MAX_DECIMAL,Vr as MAX_DETAIL_BYTES,Os as MAX_EVENT_ROUNDS,vs as MAX_HANDLES,Fr as MAX_INTEREST_KEYS,Jr as MAX_INTEREST_KEY_BYTES,Qn as MAX_ITEM_ID_CHARS,Rs as MAX_JOIN_REASKS,$i as MAX_JSON_DEPTH,Us as MAX_LOBBY_CAPACITY,qs as MAX_LOBBY_INFO_BYTES,Ws as MAX_LOBBY_NAME_CHARS,er as MAX_LOBBY_RECORD_TAG_BYTES,Xn as MAX_OUTSTANDING,Bt as MAX_PATCH_OPS,$t as MAX_PATH_SEGMENTS,Ve as MAX_PATH_SEGMENT_BYTES,ws as MAX_PENDING_ACTIONS,gs as MAX_SEQUENCE,be as MAX_SNAPSHOT_BYTES,oe as MAX_SNAPSHOT_CHUNKS,jn as MIN_CHUNK_BYTES,Dt as MeshSession,dn as NO_ANNOUNCEMENT_PREFIX,Sr as NO_LIVE_ATTEMPT_PREFIX,wr as NO_OFFER_PREFIX,bt as NotLeaderError,ii as ORG_SINK_BUDGET_REFUSAL,Ot as ORG_SINK_CLOSED_REFUSAL,oi as ORG_UPLOAD_SINK_BUDGET_REFUSAL,si as ORG_UPLOAD_SINK_CLOSED_REFUSAL,Gr as OWNER_KINDS,ye as OrgAdmissionDeniedError,D as OrgCancelledError,Me as OrgDuplex,Te as OrgHandleRegistry,Ke as OrgIndeterminateError,Pe as OrgInternalError,ne as OrgLeaderLostError,Fe as OrgMalformedError,Xe as OrgRefusedError,ze as OrgRequests,Ce as OrgRevokedError,ee as OrgServe,He as OrgSessionLostError,Ge as OrgSink,Oe as OrgStream,te as OrgStreamError,je as OrgTimeoutError,De as OrgUpload,xr as PEER_OFFER_WAIT_MS,Or as PEER_TICK_MS,We as PeerAttempts,vr as REPLACED_ATTEMPT_MARKER,Kn as REQUEST_DEADLINE_MS,ue as REQUEST_HEX_LENGTH,St as RpcError,de as RtcError,Qr as SNAP_ENVELOPE_RESERVE,En as STORE_ERROR_CODES,yn as STUN_NO_RESPONSE_CODE,Ie as SessionError,Se as StoreCore,h as StoreError,lt as StoreOwner,ut as StoreReplica,kt as StreamIdentityError,Cs as TICK_INTERVAL_MS,Is as TRANSITION_DEADLINE_MS,fr as U64_EVENT_KEYS,$e as UnknownLeafError,In as WIRE_VERSION,yt as WireError,rt as acceptPeer,Ds as addItems,Mn as applyPatch,ke as applyVisibility,xn as asSessionModule,Ln as assertChunkingFits,Ui as assertHidden,es as base64,Ht as buildConnectRequest,fn as candidateLineIsReflexive,ms as canonicalBytes,qn as canonicalRequest,Ro as cellKey,Ns as cellsAround,Zr as chunkBytesFor,Tn as chunkSnapshot,xi as classifyRtcError,_r as classifyRtcFailure,It as classifyRtcFailureAll,et as clientStreamOrgTrampoline,wt as coarseAdmissionReason,Ee as compileVisibility,Pi as connect,nt as connectPeer,en as countItems,uc as createLobby,ae as decimalValue,Re as decodeMessage,Bi as defineStore,Ir as diagnosticStunUrl,Bn as digestBinding,Pt as driveAttempt,tt as duplexOrgTrampoline,wo as emptyInventory,P as encodeMessage,hr as fromBase64,S as fromWasmError,_t as handshakePeer,Oo as hasItems,Mi as hiddenOr,dt as hostInternals,Yn as hostPlayer,Vn as hostStore,xe as idArg,Jt as inadmissibleValue,Un as inlineBinding,ko as inventoryOf,Ft as isCanonicalBase64,Cn as isCanonicalDecimal,zr as isCanonicalHex,Wt as isEntityMap,Nt as isHidden,On as isLifecycleEvent,it as isStaleStream,hi as isUdpBlocked,fc as joinLobby,Gn as joinStore,Zi as jsonByteLength,pc as listLobbies,st as loadLeafWasm,hc as lobbyCodeFromUrl,Xt as mergeShallow,Qt as needsDigest,Ue as nodeHexOf,rr as normalizeLobbyCode,Ao as onlyOwn,Di as openSession,li as orgRetireError,xt as orgRetireReason,sn as orgTerminalError,me as parseAttemptStatus,Lt as parseCounters,Tt as parseDescriptors,ve as parseEvent,Eo as parseInventory,Et as parseJsonPreservingU64,cr as parseLeafError,Ye as parseOrgCaller,ar as parseOrgError,Tr as parseRetryReport,ur as parseRpcFailure,dr as parseRtcFailure,Lr as parseRtcStats,vn as parseSessionEvent,Ae as parseStoreJson,ct as peerHexOf,Hr as peerIdHex,mn as probeBootstrapReachable,hn as probeEventAnswers,Pr as probeStunBinding,gn as probeStunBindings,qr as projectVisible,pe as reconcile,wn as refineIceFailure,Cr as reflexiveAddress,Wo as rememberedIdentity,xo as removeItems,qo as requestCredential,Io as sameCells,Po as stickyCells,Ze as streamingOrgTrampoline,Oi as stunProbeAnswered,Ar as stunProbeVerdict,cn as toBase64,se as toWasmOrgCallOptions,ie as toWasmOrgServeOptions,vt as udpBlockedEvidence,Qe as unaryOrgTrampoline,N as utf8Length};
1
+ var Pe=class{constructor(e=()=>{}){this.detach=e}detach;buffered=[];waiting=null;ended=!1;push(e){if(this.ended)return;let t=this.waiting;if(t){this.waiting=null,t({value:e,done:!1});return}this.buffered.push(e)}end(){if(this.ended)return;this.ended=!0;let e=this.waiting;e&&(this.waiting=null,e({value:void 0,done:!0}))}next(){let e=this.buffered.shift();if(e!==void 0)return Promise.resolve({value:e,done:!1});if(this.ended)return Promise.resolve({value:void 0,done:!0});let{promise:t,resolve:r}=Promise.withResolvers();return this.waiting=r,t}return(){return this.detach(),this.end(),Promise.resolve({value:void 0,done:!0})}[Symbol.asyncIterator](){return this}};function xt(n,e,t,r=[t]){return!n||!e||t.length===0||r.length===0||r[0]!==t||r.some(s=>s.length===0)?null:{bootstrapOk:!0,stunProbeFailed:!0,probed:t,probedAll:[...r]}}var z=class extends Error{constructor(e){super(e),this.name="LeafError"}},mt=class extends z{constructor(t){super(`wire: ${t}`);this.detail=t;this.name="WireError"}detail;kind="wire"},Ce=class extends z{constructor(t){super(`session: ${t}`);this.detail=t;this.name="SessionError"}detail;kind="session"},bt=class extends z{constructor(t){super(`control plane: ${t}`);this.detail=t;this.name="ControlPlaneError"}detail;kind="control-plane"},me=class extends z{constructor(t){super(`identity: ${t}`);this.detail=t;this.name="IdentityError"}detail;kind="identity"},St=class extends z{constructor(t,r){super(`ice configuration: the iceServers entry ${t} names this connection's peer RTC endpoint ${r}; a peer cannot be its own STUN server. Omit iceServers to use the STUN endpoint the anchor announces (the stun_addr field of GET /rtc/anchor), or name a STUN server that is not this peer`);this.entry=t;this.peerRtcAddr=r;this.name="IceServerConflictError"}entry;peerRtcAddr;kind="ice-server-conflict"},wt=class extends z{constructor(t,r=null){super(r===null?`not the leader: this tab holds generation ${t}`:`not the leader: this tab holds generation ${t}, the leader holds ${r}`);this.presented=t;this.current=r;this.name="NotLeaderError"}presented;current;kind="not-leader"},ue=class extends z{constructor(t){super(`rtc: ${yi(t)}`);this.failure=t;this.name="RtcError",this.kind=fi[t.type]}failure;kind},vt=class extends z{constructor(t){super(`rpc: ${gi(t)}`);this.failure=t;this.name="RpcError",this.kind=hi[t.type]}failure;kind},Fe=class extends z{constructor(t,r){super(t);this.cause=r;this.name="UnknownLeafError"}cause;kind="unknown"},te=class extends z{},ge=class extends te{constructor(t,r){super(r??`org:admission_denied:${ui[t]}`);this.coarse=t;this.name="OrgAdmissionDeniedError"}coarse;kind="org-admission-denied"},je=class extends ge{kind="org-revoked";constructor(e="org:admission_denied:denied"){super("denied",e),this.name="OrgRevokedError"}},He=class extends te{kind="org-timeout";constructor(e="org:rpc:timeout"){super(e),this.name="OrgTimeoutError"}},D=class extends te{kind="org-cancelled";constructor(e="org:rpc:cancelled"){super(e),this.name="OrgCancelledError"}},ne=class extends te{constructor(t,r="org:rpc:leader_lost"){super(r);this.generation=t;this.name="OrgLeaderLostError"}generation;kind="org-leader-lost"},Le=class extends te{kind="org-session-lost";constructor(e="org:rpc:session_lost"){super(e),this.name="OrgSessionLostError"}},Ge=class extends te{constructor(t,r="org:rpc:indeterminate"){super(r);this.deadlineMs=t;this.name="OrgIndeterminateError"}deadlineMs;kind="org-indeterminate"},ze=class extends te{constructor(t,r="org:rpc:refused"){super(r);this.status=t;this.name="OrgRefusedError"}status;kind="org-refused"},Ie=class extends te{kind="org-internal";constructor(e="org:rpc:internal"){super(e),this.name="OrgInternalError"}},Je=class extends te{kind="org-malformed";constructor(e="org:rpc:malformed"){super(e),this.name="OrgMalformedError"}},Et="org: the response sink is closed: the call was retired",li="org: the upload sink is closed: the call was retired",ci="org: the response sink is closed: the call's byte budget refused the item and retired the call",di="org: the upload sink is closed: the call's byte budget refused the item and retired the call",lr="org:",ui={denied:"denied","not-supported":"not_supported",unavailable:"unavailable"};function Ot(n){let e=(n??"").trim();return e==="unavailable"?"unavailable":e==="not_supported"||e==="not-supported"?"not-supported":e==="\0"||e==="0"?"denied":e===""||e==="1"?"not-supported":e===""||e==="2"?"unavailable":"denied"}function pi(n){switch(n){case"timeout":return new He;case"revoked":return new je;case"session-lost":return new Le;case"leader-lost":return new ne("");case"cancelled":case"node-closed":case"replaced":return new D;case"resource-exhausted":return new ge("unavailable")}}function an(n){let e=n.message;switch(n.kind){case"admission-denied":return new ge(Ot(n.coarse),e);case"revoked":return e===void 0?new je:new je(e);case"timeout":return e===void 0?new He:new He(e);case"cancelled":return e===void 0?new D:new D(e);case"leader-lost":return new ne(n.generation??"",e);case"session-lost":return e===void 0?new Le:new Le(e);case"indeterminate":return new Ge(n.deadlineMs??0,e);case"refused":return new ze(n.status??0,e);case"malformed":return e===void 0?new Je:new Je(e);case"internal":return e===void 0?new Ie:new Ie(e);default:return new Ie(`org:rpc:internal: unrecognized terminal kind ${JSON.stringify(n.kind)}`+(e===void 0?"":`: ${e}`))}}function kt(n){switch(n){case"timeout":case"cancelled":case"revoked":case"session-lost":case"leader-lost":case"node-closed":case"replaced":case"resource-exhausted":return n;default:return"replaced"}}function cr(n){if(/^org: .+ is closed: the call was retired$/.test(n))return new D(n);if(/^org: .+ is closed: the call's byte budget refused the item and retired the call$/.test(n))return new ge("unavailable",n);if(n.startsWith(lr)){let t=n.slice(lr.length),r=t.indexOf(":");if(r<=0)return null;let s=t.slice(0,r),i=t.slice(r+1),o=i.indexOf(":"),a=o===-1?i:i.slice(0,o);if(a.length===0)return null;if(s==="admission_denied")return new ge(Ot(a),n);if(s!=="rpc")return null;switch(a){case"revoked":return new je(n);case"timeout":return new He(n);case"cancelled":return new D(n);case"leader_lost":case"leader-lost":return new ne("",n);case"session_lost":case"session-lost":return new Le(n);case"indeterminate":return new Ge(0,n);case"refused":case"server_error":case"capability_denied":return new ze(0,n);case"malformed":case"codec_encode":case"codec_decode":return new Je(n);case"internal":case"no_route":case"transport":return new Ie(n);default:return null}}let e=/^rpc: refused \(9\): ([\s\S]*)$/.exec(n);return e?new ge(Ot(e[1]),n):null}var fi={iceTimeout:"ice-timeout",udpBlocked:"udp-blocked",channelClosed:"channel-closed",unsupported:"rtc-unsupported"},hi={refused:"rpc-refused",timeout:"rpc-timeout",sessionLost:"session-lost",leaderLost:"leader-lost",indeterminate:"rpc-indeterminate",malformed:"rpc-malformed"},dr="ICE did not connect inside the deadline (this does not establish that UDP is blocked)";function yi(n){switch(n.type){case"iceTimeout":return dr;case"udpBlocked":return`no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to ${n.evidence.probedAll.join(", ")} went unanswered`;case"channelClosed":return`the DataChannel closed: ${n.detail}`;case"unsupported":return`this browser refused the attempt: ${n.detail}`}}function gi(n){switch(n.type){case"refused":return`refused (${n.status}): ${n.message}`;case"timeout":return"the call's deadline elapsed";case"sessionLost":return"the session carrying the call went away";case"leaderLost":return`the leader holding generation ${n.generation} was replaced`;case"indeterminate":return`the local deadline of ${n.deadlineMs}ms elapsed before the tab running the node answered; the remote operation may still have executed (it was not retried)`;case"malformed":return`the reply did not decode: ${n.detail}`}}function S(n){if(n instanceof z)return n;let e=mi(n);return ur(e)??new Fe(e,n)}function mi(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n!==null&&typeof n=="object"&&"message"in n){let e=n.message;if(typeof e=="string")return e}return String(n)}function ur(n){let e=cr(n);if(e!==null)return e;let t=de(n,"rtc: ");if(t!==null){let d=pr(t);return d===null?null:new ue(d)}let r=de(n,"rpc: ");if(r!==null){let d=fr(r);return d===null?null:new vt(d)}let s=de(n,"wire: ");if(s!==null)return new mt(s);let i=de(n,"session: ");if(i!==null)return new Ce(i);let o=de(n,"control plane: ");if(o!==null)return new bt(o);let a=de(n,"identity: ");if(a!==null)return new me(a);let c=de(n,"ice configuration: ");if(c!==null){let d=/^the iceServers entry (.+?) names this connection's peer RTC endpoint (.+?); a peer cannot be its own STUN server\./.exec(c);if(d)return new St(d[1]??"",d[2]??"")}let l=/^not the leader: this tab holds generation (\d+)(?:, the leader holds (\d+))?$/.exec(n);if(l){let d=Number(l[1]),u=l[2]===void 0?null:Number(l[2]);return new wt(d,u)}return null}function pr(n){if(n===dr)return{type:"iceTimeout"};let e=/^no UDP response from the anchor's advertised endpoints: its HTTPS bootstrap succeeded but STUN bindings to (.+) went unanswered$/.exec(n);if(e){let s=(e[1]??"").split(", "),i=s[0]??"",o=xt(!0,!0,i,s);return o===null?null:{type:"udpBlocked",evidence:o}}let t=de(n,"the DataChannel closed: ");if(t!==null)return{type:"channelClosed",detail:t};let r=de(n,"this browser refused the attempt: ");return r!==null?{type:"unsupported",detail:r}:null}function fr(n){let e=/^refused \((\d+)\): ([\s\S]*)$/.exec(n);if(e)return{type:"refused",status:Number(e[1]),message:e[2]??""};if(n==="the call's deadline elapsed")return{type:"timeout"};if(n==="the session carrying the call went away")return{type:"sessionLost"};let t=/^the leader holding generation (\d+) was replaced$/.exec(n);if(t)return{type:"leaderLost",generation:Number(t[1])};let r=/^the local deadline of (\d+)ms elapsed before the tab running the node answered; the remote operation may still have executed \(it was not retried\)$/.exec(n);if(r)return{type:"indeterminate",deadlineMs:Number(r[1])};let s=de(n,"the reply did not decode: ");return s!==null?{type:"malformed",detail:s}:null}function bi(n){return n instanceof ue&&n.failure.type==="udpBlocked"}function de(n,e){return n.startsWith(e)?n.slice(e.length):null}var yr=["node_id","peer_node","channel_hash","origin_hash","stream_id","dialog","not_after","call_id","seq","generation","incarnation","version","from","to"];function Oe(n){let e;try{e=At(n)}catch{return{type:"unknown",tag:null,raw:n}}if(e===null||typeof e!="object")return{type:"unknown",tag:null,raw:e};let t=e,r=typeof t.type=="string"?t.type:null;switch(r){case"connected":return{type:"connected",nodeIdHex:$(t,"node_id_hex"),peerNode:$(t,"peer_node"),rtcAddr:dn(t,"rtc_addr"),rtcAddrs:Si(t)};case"disconnected":return{type:"disconnected",reason:$(t,"reason")};case"channel_message":return{type:"channel_message",channelHash:$(t,"channel_hash"),originHash:$(t,"origin_hash"),payload:cn(t,"payload")};case"stream_data":return{type:"stream_data",peerNode:$(t,"peer_node"),incarnation:$(t,"incarnation"),streamId:$(t,"stream_id"),seq:ln(t,"seq"),payload:cn(t,"payload")};case"announcement":return{type:"announcement",nodeId:$(t,"node_id"),capabilities:wi(t,"capabilities"),rtcAddr:dn(t,"rtc_addr"),verified:t.verified===!0};case"signal":return{type:"signal",from:$(t,"from"),to:$(t,"to"),dialog:$(t,"dialog"),kind:$(t,"kind"),payload:cn(t,"payload"),notAfter:$(t,"not_after")};case"rpc_response":return{type:"rpc_response",callId:$(t,"call_id"),status:ln(t,"status")};case"dropped":return{type:"dropped",reason:$(t,"reason"),subprotocol:ln(t,"subprotocol")};case"rtc_failure":return{type:"rtc_failure",error:S($(t,"error"))};default:return{type:"unknown",tag:r,raw:t}}}var Te=class{typed=new Map;any=new Set;queues=new Set;on(e,t){let r=this.typed.get(e)??new Set;this.typed.set(e,r);let s=t;return r.add(s),()=>{r.delete(s)}}onAny(e){return this.any.add(e),()=>{this.any.delete(e)}}events(){let e=new Pe(()=>this.queues.delete(e));return this.queues.add(e),e}deliver(e,t){this.dispatch(t?t(e):Oe(e))}dispatch(e){for(let t of this.typed.get(e.type)??[])hr(t,e);for(let t of this.any)hr(t,e);for(let t of this.queues)t.push(e)}close(){this.typed.clear(),this.any.clear();for(let e of[...this.queues])e.end();this.queues.clear()}};function hr(n,e){try{n(e)}catch(t){console.error("[@net-mesh/browser] event listener threw",t)}}function At(n){let e=yr.join("|"),t=n.replace(new RegExp(`("(?:${e})"\\s*:\\s*)(\\d+)`,"g"),'$1"$2"');return JSON.parse(t)}function $(n,e){let t=n[e];return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):""}function Si(n){let e=n.rtc_addrs;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.length>0);let t=dn(n,"rtc_addr");return t===null?[]:[t]}function dn(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:null}function ln(n,e){let t=n[e];if(typeof t=="number")return t;if(typeof t=="string"){let r=Number(t);return Number.isFinite(r)?r:0}return 0}function wi(n,e){let t=n[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function cn(n,e){let t=n[e];return t instanceof Uint8Array?t:typeof t!="string"?new Uint8Array(0):gr(t)}function gr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function un(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var De=class{live=new Set;add(e){this.live.add(e)}delete(e){this.live.delete(e)}retireAll(e){let t=[...this.live];this.live.clear();let r=[];for(let s of t)try{s.retire(e)}catch(i){r.push(i)}return r}},xe=class{constructor(e,t,r){this.inner=e;this.onCancel=t;this.onDone=r}inner;onCancel;onDone;terminal=null;failure=null;handleDropped=!1;waiters=[];next(){if(this.failure!==null)return Promise.reject(this.failure);if(this.terminal!==null)return Promise.resolve(this.terminal);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={resolve:t,reject:r};return this.waiters.push(s),this.inner.next().then(i=>{Ve(this.waiters,s);let o=vi(i);o.done&&this.complete(o),t(o)},i=>{Ve(this.waiters,s);let o=S(i);this.fail(o),r(o)}),e}cancel(){this.retire(new D)}retire(e){this.terminal!==null||this.failure!==null||(this.dropHandle(),this.complete({done:!0,error:e}))}[Symbol.asyncIterator](){let e=!1;return{next:async()=>{if(e)return{done:!0,value:void 0};let t=await this.next();if(t.error!==void 0)throw t.error;return t.value===void 0?(e=!0,{done:!0,value:void 0}):(t.done&&(e=!0),{done:!1,value:t.value})},return:async()=>(e=!0,this.cancel(),{done:!0,value:void 0})}}complete(e){if(this.terminal!==null)return;this.terminal=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.resolve(e)}fail(e){if(this.terminal!==null||this.failure!==null)return;this.failure=e,this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.onCancel()}catch{}}}},Me=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;failure=null;handleDropped=!1;waiters=[];async send(e){if(this.failure!==null)throw this.failure;try{await this.inner.send(e)}catch(t){throw S(t)}}finish(){if(this.failure!==null)return Promise.reject(this.failure);let{promise:e,resolve:t,reject:r}=Promise.withResolvers(),s={reject:r};return this.waiters.push(s),this.inner.finish().then(i=>{Ve(this.waiters,s),this.onDone?.(),t(i)},i=>{Ve(this.waiters,s),this.onDone?.(),r(S(i))}),e}cancel(){this.retire(new D)}retire(e){if(this.failure!==null)return;if(this.failure=e,!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}this.onDone?.();let t=[...this.waiters];this.waiters.length=0;for(let r of t)r.reject(e)}},Ne=class{constructor(e,t){this.inner=e;this.onDone=t;this.stream=new xe(e.stream(),()=>this.dropHandle(),()=>this.onDone?.()),this.sink={send:async r=>{if(this.failure!==null)throw this.failure;try{await this.inner.send(r)}catch(s){throw S(s)}},finishSending:async()=>{if(this.failure!==null)throw this.failure;try{await this.inner.finish_sending()}catch(r){throw S(r)}},cancel:()=>{this.retire(new D)}}}inner;onDone;handleDropped=!1;failure=null;sink;stream;retire(e){this.failure??=e,this.dropHandle(),this.stream.retire(e),this.onDone?.()}dropHandle(){if(!this.handleDropped){this.handleDropped=!0;try{this.inner.cancel()}catch{}}}},Ye=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.verdict??=kt(t),this.verdict),()=>(this.verdict??="replaced",this.verdict))}inner;retired;verdict=null;async send(e){if(this.verdict!==null)throw new D(Et);try{await this.inner.send(e)}catch(t){throw S(t)}}async close(){if(this.verdict!==null)throw new D(Et);try{await this.inner.close()}catch(e){throw S(e)}}},Qe=class{constructor(e){this.inner=e;this.retired=e.retired().then(t=>(this.settle(kt(t)),this.verdict),()=>(this.settle("replaced"),this.verdict))}inner;retired;verdict=null;waiters=[];next(){if(this.verdict!==null)return Promise.resolve({done:!0});let{promise:e,resolve:t}=Promise.withResolvers();return this.waiters.push(t),this.inner.next().then(r=>{Ve(this.waiters,t),t(Oi(r))},()=>{Ve(this.waiters,t),t({done:!0})}),e}[Symbol.asyncIterator](){return{next:async()=>{let e=await this.next();return e.done||e.value===void 0?{done:!0,value:void 0}:{done:!1,value:e.value}},return:async()=>({done:!0,value:void 0})}}settle(e){if(this.verdict!==null)return;this.verdict=e;let t=[...this.waiters];this.waiters.length=0;for(let r of t)r({done:!0})}},ee=class{constructor(e,t){this.inner=e;this.onDone=t}inner;onDone;closed=!1;get service(){return this.inner.service()}close(){this.closed||(this.closed=!0,this.onDone?.(),this.inner.close())}retire(e){this.close()}};function se(n){return{credentials:{membership:n.credentials.membership,dispatcher:n.credentials.dispatcher,...n.credentials.capabilityGrant===void 0?{}:{capabilityGrant:n.credentials.capabilityGrant},actingOrg:n.credentials.actingOrg,providerOwnerOrg:n.credentials.providerOwnerOrg,provider:n.credentials.provider,...n.credentials.proofTtlSecs===void 0?{}:{proofTtlSecs:n.credentials.proofTtlSecs}},...n.deadlineMs===void 0?{}:{deadlineMs:n.deadlineMs},...n.streamWindowInitial===void 0?{}:{streamWindowInitial:n.streamWindowInitial},...n.requestWindowInitial===void 0?{}:{requestWindowInitial:n.requestWindowInitial}}}function ie(n){return{ownerOrg:n.ownerOrg}}function Ze(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new Fe("the caller attribution is not an OrgCaller object");let t=e;return{entity:String(t.entity??""),actingOrg:String(t.actingOrg??""),providerOrg:String(t.providerOrg??""),provider:String(t.provider??""),capability:String(t.capability??""),isSameOrg:t.isSameOrg===!0}}function et(n){return async(e,t)=>await n(Ze(e),t)}function tt(n){return async(e,t,r)=>{await n(Ze(e),t,new Ye(r))}}function nt(n){return async(e,t)=>await n(Ze(e),new Qe(t))}function rt(n){return async(e,t,r)=>{await n(Ze(e),new Qe(t),new Ye(r))}}function Ve(n,e){let t=n.indexOf(e);t>=0&&n.splice(t,1)}function vi(n){return n.done?n.error!==void 0?{done:!0,error:an(n.error)}:n.value===void 0?{done:!0}:{done:!0,value:n.value}:{done:!1,value:n.value}}function Oi(n){return n.done?{done:!0}:{done:!1,value:n.value}}var Rt=class extends Ce{constructor(e){super(e),this.name="StreamIdentityError"}},xi=1024,mr=1<<20,We=class{constructor(e,t,r="required"){this.inner=e;this.onClosed=t;if(this.wireId=br(()=>e.stream_id_hex()),this.peerId=br(()=>e.peer_node_hex()),r==="required"&&this.peerId===null)throw new Rt("the stream did not report a readable peer, so its frames cannot be attributed");e.on_message(s=>this.receive(s))}inner;onClosed;queues=new Set;listeners=new Set;pending=[];pendingBytes=0;dropped=0;closed=!1;retiredBy=null;wireId;peerId;get droppedBeforeConsumer(){return this.dropped}get peerNode(){return this.inner.peer_node_hex()}get reliability(){return this.inner.is_reliable()?"reliable":"fireAndForget"}get streamId(){return this.inner.stream_id_hex()}async send(e){if(this.closed)throw new Ce(this.retiredBy??"the stream is closed");try{await this.inner.send(e)}catch(t){throw S(t)}}onMessage(e){this.listeners.add(e);let t=this.drainPending();for(let r of t)e(r);return()=>{this.listeners.delete(e)}}[Symbol.asyncIterator](){let e=new Pe(()=>this.queues.delete(e));this.queues.add(e);let t=this.drainPending();for(let r of t)e.push(r);return this.closed&&e.end(),e}retire(e){this.closed||(this.retiredBy=e,this.close())}close(){if(!this.closed){this.closed=!0;for(let e of[...this.queues])e.end();this.queues.clear(),this.listeners.clear(),this.onClosed?.(),this.inner.close()}}drainPending(){return this.pendingBytes=0,this.pending.splice(0,this.pending.length)}receive(e){let t=this.decode(e);if(!(t===null||this.closed)){if(this.queues.size===0&&this.listeners.size===0){if(t.byteLength>mr){this.dropped+=1;return}for(this.pending.push(t),this.pendingBytes+=t.byteLength;this.pending.length>xi||this.pendingBytes>mr;){let r=this.pending.shift();this.pendingBytes-=r.byteLength,this.dropped+=1}return}for(let r of this.listeners)try{r(t)}catch(s){console.error("[@net-mesh/browser] stream listener threw",s)}for(let r of this.queues)r.push(t)}}decode(e){if(e instanceof Uint8Array)return e;if(typeof e!="string")return console.error("[@net-mesh/browser] stream callback received",typeof e,"not the leaf event JSON"),null;let t=Oe(e);return t.type!=="stream_data"||!/^\d+$/.test(t.streamId)||this.wireId!==null&&BigInt(t.streamId)!==this.wireId||this.peerId!==null&&(!/^\d+$/.test(t.peerNode)||BigInt(t.peerNode)!==this.peerId)?null:t.payload}};function br(n){let e;try{e=n()}catch{return null}return e===void 0||!/^[0-9a-fA-F]{1,16}$/.test(e)?null:BigInt(`0x${e}`)}var pn="no verified announcement for",vr="no live attempt with",Or="no verified offer from",xr="is not the live attempt",Er=50,kr=5e3,Sr=1e4;function wr(n){switch(n.type){case"direct":case"iceTimeout":case"udpBlocked":return!0;case"superseded":return n.liveDialog!==null;default:return!1}}var qe=class n{constructor(e=()=>null,t=()=>Date.now()){this.self=e;this.now=t}self;now;#e=new Map;#t=new Map;#r=new Map;noteOffer(e){let t=this.now();for(let[r,s]of this.#r)s<=t-Sr&&this.#r.delete(r);this.#r.set(e.toLowerCase(),t)}connect(e,t,r,s){let i=e.toLowerCase(),o=this.#e.get(i);if(o!==void 0)return o;let a=this.#t.get(i),c=(async()=>{if(a!==void 0){let d=await a.catch(()=>null);if(d!==null&&wr(d))return d}let l=await t();if(l!=null)return{type:"direct",peer:e,dialog:l};if(s===void 0||!this.#n(i))return r();if(this.#s(i,this.now()-Sr)){let d=await s();if(d!==null&&wr(d))return d}return this.#g(i,r,s)})();return n.#o(this.#e,i,c)}accept(e,t){let r=e.toLowerCase(),s=this.#t.get(r);if(s!==void 0)return s;let i=this.#e.get(r);return i!==void 0&&this.self()!==null?i:n.#o(this.#t,r,t())}#n(e){let t=this.self()?.toLowerCase();return t!==void 0&&t.length===e.length&&t>e}#s(e,t){let r=this.#r.get(e);return r===void 0||r<=t?!1:(this.#r.delete(e),!0)}async#g(e,t,r){let s=this.now(),i=t(),o=!1,a=()=>{o=!0};return i.then(a,a),(async()=>{for(;!o;){if(await fn(),o||!this.#s(e,s))continue;let l=await r();if(l!==null)return l}return null})().then(l=>l??i)}static#o(e,t,r){e.set(t,r);let s=()=>{e.get(t)===r&&e.delete(t)};return r.then(s,s),r}},Ei="1";function _t(n,e){if(e.type!=="signal"||e.kind!==Ei||e.from===void 0||!/^\d{1,20}$/.test(e.from))return;let t=BigInt(e.from);t>0xffffffffffffffffn||n.noteOffer(t.toString(16).padStart(16,"0"))}async function st(n,e,t){let r;try{r=await e.offer(n)}catch(i){let o=S(i);if(o.message.includes(pn))return{type:"noAnnouncement",peer:n,detail:o.message};throw o}let s=await Ct(n,r,i=>i.state==="open",e,t);return s.type!=="direct"?s:It(n,r,e)}async function it(n,e,t){let r=null,s=Date.now()+kr;for(;;)try{r=await e.acceptOffer(n);break}catch(i){let o=S(i);if(o.message.includes(pn))return{type:"noAnnouncement",peer:n,detail:o.message};if(!o.message.includes(Or)||Date.now()>=s)throw o;await fn()}return Ct(n,r,i=>i.direct,e,t)}async function Pt(n,e,t){let r;try{r=await e.acceptOffer(n)}catch{return null}return Ct(n,r,s=>s.direct,e,t)}async function It(n,e,t){let r;try{r=await t.handshake(n,e)}catch(s){let i=Ar(s,n,e);return i!==null?i:{type:"handshakeFailed",peer:n,dialog:e,detail:S(s).message}}return r!==e?{type:"superseded",peer:n,dialog:e,liveDialog:r}:{type:"direct",peer:n,dialog:e}}async function Ct(n,e,t,r,s){for(;;){let i;try{i=s(await r.candidate(n,e))}catch(o){let a=Ar(o,n,e);if(a!==null)return a;throw S(o)}if(i.dialog!==e)return{type:"superseded",peer:n,dialog:e,liveDialog:i.dialog};if(t(i))return{type:"direct",peer:n,dialog:e};if(i.state==="iceTimeout")return{type:"iceTimeout",peer:n,dialog:e};if(i.state==="udpBlocked")return{type:"udpBlocked",peer:n,dialog:e};if(i.state==="failed")return{type:"handshakeFailed",peer:n,dialog:e,detail:i.candidateError??"the attempt reached its terminal transition without installing a session"};await fn()}}function Ar(n,e,t){let{message:r}=S(n);return r.includes(xr)?{type:"superseded",peer:e,dialog:t,liveDialog:ki(r)}:r.includes(vr)?{type:"superseded",peer:e,dialog:t,liveDialog:null}:null}function ki(n){return/\(dialog ([0-9a-f]{16}) is\)/.exec(n)?.[1]??null}async function fn(){let n=Promise.withResolvers();setTimeout(n.resolve,Er),await n.promise}function yn(n){let e=n.trim().split(/\s+/);return e.some((t,r)=>t==="typ"&&e[r+1]==="srflx")}function gn(n){return"candidate"in n?yn(n.candidate):"error"in n?n.error<mn:!1}function _r(n){if(n.some(gn))return"answered";let e=n.some(o=>"candidate"in o);if(n.some(o=>"ice"in o&&o.ice==="failed")&&!e)return"notRun";let r=n.some(o=>"gathering"in o),s=n.some(o=>"error"in o&&o.error>=mn),i=n.some(o=>"candidate"in o&&Pr(o.candidate));return r&&!s&&i?"notRun":"unanswered"}function Pr(n){let e=n.trim().split(/\s+/),t=!1;for(let l=0;l+1<e.length;l+=1)e[l]==="typ"&&e[l+1]==="host"&&(t=!0);let r=e[4];if(!t||r===void 0)return!1;let s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(r);if(s!==null){let l=s.slice(1).map(Number);if(l.some(I=>I>255))return!1;let[d,u]=l,p=d===10||d===172&&u>=16&&u<=31||d===192&&u===168,h=d===127,y=d===169&&u===254,m=l.every(I=>I===0),A=l.every(I=>I===255),k=d===100&&(u&192)===64;return!(p||h||y||m||A||k)}if(!r.includes(":")||!/^[0-9a-f:.]+$/i.test(r))return!1;let i=r.toLowerCase();if(i==="::"||i==="::1")return!1;let o=Number.parseInt(i.startsWith(":")?"0":i.split(":")[0]??"0",16);if(Number.isNaN(o))return!1;let a=(o&65024)===64512,c=(o&65472)===65152;return!(a||c)}function Ai(n){return _r(n)==="answered"}function Ir(n){let{bootstrapOk:e,stunProbe:t,probed:r}=n;return r===null?{type:"iceTimeout"}:jt({bootstrapOk:e,probes:[{probed:r,stunProbe:t}]})}function jt(n){let{bootstrapOk:e,probes:t}=n;if(t.length===0||t.some(i=>i.stunProbe.type!=="unanswered"))return{type:"iceTimeout"};let r=t.map(i=>i.probed),s=xt(e,!0,r[0]??"",r);return s===null?{type:"iceTimeout"}:{type:"udpBlocked",evidence:s}}function Ri(n){return new ue(Ir(n))}var _i=2500,mn=700,hn=3478;async function Cr(n,e={}){let t=jr(n);if(t===null)return{type:"notRun",reason:`not an address: ${n}`};let r=e.peerConnectionFactory??Ii();if(r===null)return{type:"unsupported",detail:"RTCPeerConnection is not available in this context"};let s=e.timeoutMs??_i,{promise:i,resolve:o}=Promise.withResolvers(),a;try{a=r({iceServers:[{urls:t}],iceCandidatePoolSize:0})}catch(m){return{type:"unsupported",detail:String(m)}}let c=!1,l=m=>{c||(c=!0,o(m))},d=null,u=setTimeout(()=>l({type:"unanswered",detail:d??"no answer inside the probe deadline"}),s),p=!1,h=()=>{if(d===null&&p){l({type:"notRun",reason:'gathering completed beside a public host with no reflexive candidate and no "no response" report: inconclusive'});return}l({type:"unanswered",detail:d??"gathering completed with no reflexive candidate"})},y=!1;a.oniceconnectionstatechange=()=>{a.iceConnectionState==="failed"&&!y&&l({type:"notRun",reason:"the engine failed the probe connection before gathering any candidate"})},a.onicecandidate=m=>{let A=m.candidate;if(A===null){h();return}y=!0,Pr(A.candidate)&&(p=!0);let k=Hr(A);k!==null&&l({type:"reflexive",address:k})},a.onicecandidateerror=m=>{let A=m.errorCode,k=`${A}: ${m.errorText} (${m.url})`;if(gn({error:A})){l({type:"stunError",code:A,detail:k});return}d=k},a.onicegatheringstatechange=()=>{a.iceGatheringState==="complete"&&h()};try{a.createDataChannel("net-udp-probe"),await a.setLocalDescription(await a.createOffer())}catch(m){l({type:"unsupported",detail:String(m)})}try{return await i}finally{clearTimeout(u),a.onicecandidate=null,a.onicecandidateerror=null,a.oniceconnectionstatechange=null,a.onicegatheringstatechange=null,a.close()}}async function bn(n,e={}){return Promise.all(n.map(async t=>({probed:t,stunProbe:await Cr(t,e)})))}var Pi=3e3;async function Sn(n,e={}){let t=e.fetchImpl??globalThis.fetch;if(typeof t!="function")return!1;try{return await t(n,{method:"GET",mode:"no-cors",cache:"no-store",redirect:"follow",signal:AbortSignal.timeout(e.timeoutMs??Pi)}),!0}catch{return!1}}function jr(n){let e=n.trim();if(e.length===0)return null;if(e.startsWith("stun:")||e.startsWith("stuns:"))return e;let t=/^\[([0-9a-fA-F:.]+)\](?::(\d+))?$/.exec(e);if(t)return`stun:[${t[1]??""}]:${t[2]??hn}`;if((e.match(/:/g)?.length??0)>1)return`stun:[${e}]:${hn}`;let r=/^([A-Za-z0-9._-]+)(?::(\d+))?$/.exec(e);return r===null?null:`stun:${r[1]??""}:${r[2]??hn}`}function Hr(n){return n.type==="srflx"?n.address??Rr(n.candidate):n.type!==null?null:yn(n.candidate)?Rr(n.candidate):null}function Rr(n){let e=n.split(" "),t=e[4]??"",r=e[5]??"";return r.length>0?`${t}:${r}`:t}function Ii(){return typeof RTCPeerConnection>"u"?null:n=>new RTCPeerConnection(n)}var wn=new Map;async function ot(n={}){if(n.wasm)return n.wasm;let e=n.wasmModule??new URL("./net_leaf.js",import.meta.url).href,t=`${e}|${String(n.wasmUrl??"")}`,r=wn.get(t);if(r)return r;let s=Ci(e,n.wasmUrl);wn.set(t,s);try{return await s}catch(i){throw wn.delete(t),i}}async function Ci(n,e){let t=await import(n),r=ji(t,n);return r.default&&await r.default(e===void 0?void 0:{module_or_path:e}),r}function ji(n,e){if(n===null||typeof n!="object"||!("LeafNode"in n))throw new Error(`${e} is not a net-mesh-leaf module: no LeafNode export`);let t=n.LeafNode;if(typeof t!="function"||!("connect"in t))throw new Error(`${e} exports a LeafNode without a static connect()`);if(typeof t.connect!="function")throw new Error(`${e} exports a LeafNode whose connect is not callable`);return n}function Ee(n,e){if(typeof n=="string")return n;let t=typeof n=="object"&&n!==null?Object.prototype.toString.call(n):String(n);throw new TypeError(`${t} is not a ${e} id: a ${e} id crosses this boundary as 16 hex digits as a STRING \u2014 the spelling this boundary hands out; a ${typeof n} is refused rather than coerced, because a number cannot carry a u64 id`)}function Tr(n){if(!/^\d+$/.test(n))throw new TypeError(`a decimal node id is digits only, got ${JSON.stringify(n)}`);let e=BigInt(n);if(e>0xffffffffffffffffn)throw new TypeError(`${n} does not fit in a u64 node id`);return e.toString(16).padStart(16,"0")}var Lt=class{constructor(e,t,r,s){this.inner=e;this.bootstrapUrl=t;this.failureTyping=r;this.nodeId=e.node_id_hex(),this.anchorRtcAddr=s,e.on_event(i=>this.ingest(i))}inner;bootstrapUrl;failureTyping;hub=new Te;nodeId;closed=!1;streams=new Set;attempts=new qe(()=>this.nodeId);orgHandles=new De;anchorRtcAddr;anchorRtcAddrs=[];bootstrapObserved=!1;releaseIdentity=null;releaseIdentityOnClose(e){this.releaseIdentity=e}nodeIdHex(){return this.nodeId}anchorIdHex(){return this.inner.anchor_id_hex()}originHashHex(){return this.inner.origin_hash_hex()}async enroll(){try{await this.inner.enroll()}catch(e){throw S(e)}}isEnrolled(){return this.inner.is_enrolled()}async call(e,t,r){try{return await this.inner.call(e,t,r)}catch(s){throw S(s)}}async subscribe(e){try{await this.inner.subscribe(e)}catch(t){throw S(t)}}async publish(e,t){try{await this.inner.publish(e,t)}catch(r){throw S(r)}}openStream(e){let t;try{t=this.inner.open_stream(e)}catch(s){throw S(s)}let r=new We(t,()=>this.streams.delete(r));return this.streams.add(r),r}async callOrg(e,t,r){try{return await this.inner.call_org(e,t,se(r))}catch(s){throw S(s)}}async callOrgStreaming(e,t,r){try{let s=await this.inner.call_org_streaming(e,t,se(r)),i=new xe(s,()=>s.cancel(),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(s){throw S(s)}}async callOrgClientStream(e,t){try{let r=await this.inner.call_org_client_stream(e,se(t)),s=new Me(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}async callOrgDuplex(e,t){try{let r=await this.inner.call_org_duplex(e,se(t)),s=new Ne(r,()=>this.orgHandles.delete(s));return this.orgHandles.add(s),s}catch(r){throw S(r)}}serveOrg(e,t,r,s){try{let i=new ee(this.inner.serve_org(e,t,et(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new ee(this.inner.serve_org_streaming(e,t,tt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new ee(this.inner.serve_org_client_stream(e,t,nt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new ee(this.inner.serve_org_duplex(e,t,rt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}async signal(e,t,r,s){try{await this.inner.signal(Ee(e,"peer"),Ee(t,"dialog"),r,s)}catch(i){throw S(i)}}async connectPeer(e){let t;try{t=Ee(e,"peer")}catch(r){throw S(r)}return this.attempts.connect(e,()=>{try{return this.inner.peer_direct_dialog(t)}catch(r){throw S(r)}},()=>st(e,this.peerPrimitives(),be),()=>Pt(e,this.peerPrimitives(),be))}peerPrimitives(){return{offer:e=>this.inner.peer_offer(e),acceptOffer:e=>this.inner.peer_accept_offer(e),candidate:(e,t)=>this.inner.peer_candidate_in(e,t),handshake:(e,t)=>this.inner.peer_handshake_in(e,t)}}async handshakePeer(e,t){return It(e,t,this.peerPrimitives())}async acceptPeer(e){return this.attempts.accept(e,()=>it(e,this.peerPrimitives(),be))}async peerAttempt(e){try{return be(await this.inner.peer_candidate(e))}catch(t){throw S(t)}}counters(){return Dt(this.inner.counters_json())}rtcStats(){return Dr(this.inner.rtc_stats_json())}enableNetworkRetry(){try{this.inner.arm_network_retry()}catch(e){throw S(e)}}retryReport(){return Mr(this.inner.retry_report())}async announce(e){try{await this.inner.announce([...e])}catch(t){throw S(t)}}async query(e){let t;try{t=await this.inner.query(e)}catch(r){throw S(r)}return Mt(t)}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}events(){return this.hub.events()}async refineIceFailure(e){return On(e,{bootstrapUrl:this.bootstrapUrl,bootstrapObserved:this.bootstrapObserved,anchorRtcAddr:this.anchorRtcAddr,anchorRtcAddrs:this.anchorRtcAddrs,failureTyping:this.failureTyping})}close(){if(this.closed)return;this.closed=!0;let e=this.releaseIdentity;this.releaseIdentity=null,queueMicrotask(()=>e?.());let t=[];for(let s of this.orgHandles.retireAll(new D("org:rpc:cancelled: the node is closed")))t.push(S(s));let r=[...this.streams];this.streams.clear();for(let s of r)try{s.close()}catch(i){t.push(S(i))}try{this.hub.close()}catch(s){t.push(S(s))}try{this.inner.close()}catch(s){t.push(S(s))}if(t.length>0)throw new AggregateError(t,`close: ${t.length} of this node's teardown steps failed`)}ingest(e){let t=Oe(e);t.type==="connected"&&(this.bootstrapObserved=!0,t.rtcAddr!==null&&(this.anchorRtcAddr=t.rtcAddr),t.rtcAddrs.length>0&&(this.anchorRtcAddrs=t.rtcAddrs)),_t(this.attempts,t),this.hub.dispatch(t)}};async function Hi(n){let e=Tt(n),t=n.failureTyping??{},r=await ot(n),s=e.entitySecretHex!==void 0&&n.lockIdentity!==!1?await Li(e.entitySecretHex):null;try{let i=await r.LeafNode.connect(e),o=new Lt(i,n.bootstrapUrl??null,t,n.anchorRtcAddr??null);return o.releaseIdentityOnClose(s),o}catch(i){throw s?.(),await On(S(i),{bootstrapUrl:n.bootstrapUrl??null,bootstrapObserved:!1,anchorRtcAddr:n.anchorRtcAddr??null,failureTyping:t})}}async function vn(n){let e=globalThis.crypto?.subtle;if(e===void 0)return null;let t=n.toLowerCase(),r=new Uint8Array(await e.digest("SHA-256",new TextEncoder().encode(`net-mesh:identity:${t}`)));return`net-mesh:identity:${Array.from(r.subarray(0,16),s=>s.toString(16).padStart(2,"0")).join("")}`}async function Li(n){let e=globalThis.navigator?.locks;if(e===void 0)return null;let t=await vn(n);if(t===null)return null;let r=await new Promise((s,i)=>{let o,a=new Promise(c=>{o=c});e.request(t,{ifAvailable:!0},async c=>{if(c===null){s("busy");return}s(o),await a}).catch(i)});if(r==="busy")throw new me("this identity is already connected in another tab or window of this browser; two nodes with one identity evict each other at the anchor (use openSession() to share one node across tabs, or pass lockIdentity: false)");return r}function Tt(n){return{credentialB64:Mi(n),origin:n.origin??Ni(),...n.bootstrapUrl===void 0?{}:{bootstrapUrl:n.bootstrapUrl},...n.iceServers?{iceServers:n.iceServers}:{},...Ti(n)}}function Dt(n){let e=JSON.parse(n);if(e===null||typeof e!="object")return{};let t={},r=(s,i)=>{for(let[o,a]of Object.entries(s))a!==null&&typeof a=="object"&&!Array.isArray(a)?r(a,`${i}${o}.`):t[`${i}${o}`]=typeof a=="string"?a:String(a)};return r(e,""),t}function be(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`peer_candidate did not answer an object: ${n}`);let t=e,r=t.state;if(r!=="gathering"&&r!=="open"&&r!=="iceTimeout"&&r!=="udpBlocked"&&r!=="failed")throw new TypeError(`peer_candidate answered an unknown state: ${String(r)}`);let s=t.candidateError;return{dialog:String(t.dialog??""),state:r,sent:Number(t.sent??0),applied:Number(t.applied??0),answered:t.answered===!0,direct:t.direct===!0,remainingMs:String(t.remainingMs??"0"),candidateError:typeof s=="string"?s:null}}function Dr(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`rtc_stats_json did not answer an object: ${n}`);let t={},r={};for(let[s,i]of Object.entries(e)){if(s==="not_applicable"){if(i===null||typeof i!="object")continue;for(let[o,a]of Object.entries(i))r[o]=String(a);continue}t[s]=typeof i=="string"?i:String(i)}return{counters:t,notApplicable:r}}function Mr(n){let e=JSON.parse(n);if(e===null||typeof e!="object")throw new TypeError(`retry_report did not answer an object: ${n}`);let t=e;return{armed:t.armed===!0,online:String(t.online??"0"),iceFailed:String(t.iceFailed??"0"),channelClosed:String(t.channelClosed??"0"),triggers:String(t.triggers??"0"),started:String(t.started??"0"),coalesced:String(t.coalesced??"0"),notEligible:String(t.notEligible??"0"),openEpisodes:Number(t.openEpisodes??0),owned:Number(t.owned??0),last:typeof t.last=="string"?t.last:null}}async function On(n,e){if(!(n instanceof ue)||n.failure.type!=="iceTimeout"||e.failureTyping.probeOnIceTimeout===!1)return n;let t=e.anchorRtcAddrs!==void 0&&e.anchorRtcAddrs.length>0?e.anchorRtcAddrs:e.anchorRtcAddr!==null?[e.anchorRtcAddr]:[];if(t.length===0)return n;let r=await bn(t,e.failureTyping.stun);if(r.some(i=>i.stunProbe.type!=="unanswered"))return n;let s=e.bootstrapObserved||e.bootstrapUrl!==null&&await Sn(e.bootstrapUrl,e.failureTyping.bootstrap);return new ue(jt({bootstrapOk:s,probes:r}))}function Mt(n){let e=At(n);if(!Array.isArray(e))return[];let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let s={...r},i=s.capabilities,o=Di(s.node_id);t.push({nodeId:o,peerIdHex:Tr(o),entityId:Ht(s.entity_id),capabilities:Array.isArray(i)?i.filter(a=>typeof a=="string"):[],rtcAddr:Ht(s.rtc_addr),noisePubkey:Ht(s.noise_pubkey),version:Ht(s.version)})}return t}var Lr=/^[0-9a-fA-F]{64}$/;function Ti(n){let{entitySecretHex:e,noiseSecretHex:t}=n;if(e===void 0){if(t!==void 0)throw new me("noiseSecretHex was supplied without entitySecretHex: the leaf would generate the entity half, so the identity would not be the one you meant to inject");return{}}if(!Lr.test(e))throw new me(`entitySecretHex must be 32 bytes of hex (64 hex digits), got ${e.length} characters`);if(t===void 0)return{entitySecretHex:e};if(!Lr.test(t))throw new me(`noiseSecretHex must be 32 bytes of hex (64 hex digits), got ${t.length} characters`);return{entitySecretHex:e,noiseSecretHex:t}}function Di(n){return typeof n=="string"?n:typeof n=="number"?String(n):""}function Ht(n){return typeof n=="string"?n.length>0?n:null:typeof n=="number"?String(n):null}function Mi(n){if(n.credentialB64!==void 0)return n.credentialB64;let e=n.credential;if(typeof e=="string")return e;if(e instanceof Uint8Array)return un(e);throw new Error("connect() needs a credential: pass credentialB64 or credential")}function Ni(){let n=globalThis.location?.origin;if(typeof n=="string"&&n.length>0)return n;throw new Error("connect() needs an origin: there is no location.origin in this context")}function xn(n){let e=Oe(n);return e.type!=="unknown"?e:Wi(e)??e}function En(n){switch(n.type){case"leader_changed":case"subscription_restored":case"leader_lost":case"generation_fenced":case"not_leader":case"promotion_failed":return!0;default:return!1}}function Wi(n){let e=n.raw;if(e===null||typeof e!="object")return null;let t={...e};switch(n.tag){case"leader_changed":return{type:"leader_changed",generation:Ue(t.generation)};case"subscription_restored":return{type:"subscription_restored",channel:typeof t.channel=="string"?t.channel:""};case"leader_lost":{let r=Number(t.failed);return{type:"leader_lost",generation:Ue(t.generation),failed:Number.isFinite(r)?r:0}}case"generation_fenced":return{type:"generation_fenced",presented:Ue(t.presented),current:Ue(t.current)};case"not_leader":return{type:"not_leader",presented:Ue(t.presented),current:Ue(t.current)};case"promotion_failed":return{type:"promotion_failed",generation:Ue(t.generation),detail:typeof t.detail=="string"?t.detail:""};default:return null}}function Ue(n){return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):"0"}function kn(n){let e=n.MeshSession;if(!(e!==null&&(typeof e=="object"||typeof e=="function")&&"open"in e&&typeof e.open=="function"))throw new Error("this net-mesh-leaf bundle has no MeshSession: leader election and the follower proxy need a wasm build from Stage 5 slice 3 or later");return n}var Nr="stale stream handle: the leader changed; reopen the stream",Nt=class{constructor(e){this.inner=e;this.streamGeneration=e.generation(),e.on_event(t=>this.hub.deliver(t,xn)),this.hub.onAny(t=>_t(this.attempts,t)),this.hub.onAny(t=>{if(t.type==="leader_lost"||t.type==="not_leader"){this.orgHandles.retireAll(new ne(this.streamGeneration)),this.endStreams(Nr);return}let r=this.inner.generation();if(r===this.streamGeneration)return;let s=this.streamGeneration;this.streamGeneration=r,this.orgHandles.retireAll(new ne(s)),this.endStreams(Nr)})}inner;hub=new Te;streams=new Set;attempts=new qe(()=>this.inner.node_id_hex()??null);streamGeneration;orgHandles=new De;closed=!1;role(){return this.inner.role()==="leader"?"leader":"follower"}generation(){return this.inner.generation()}nodeIdHex(){return this.inner.node_id_hex()??null}fingerprint(){return this.inner.fingerprint()}scope(){return this.inner.scope()}interruptionMs(){return this.inner.interruption_ms()??null}async call(e,t,r){return await this.guard(()=>this.inner.call(e,t,r))}async subscribe(e){await this.guard(()=>this.inner.subscribe(e))}async unsubscribe(e){await this.guard(()=>this.inner.unsubscribe(e))}async publish(e,t){await this.guard(()=>this.inner.publish(e,t))}async announce(e){await this.guard(()=>this.inner.announce([...e]))}async query(e){return Mt(await this.guard(()=>this.inner.query(e)))}async counters(){return Dt(await this.guard(()=>this.inner.counters_json()))}async enroll(){await this.guard(()=>this.inner.enroll())}async isEnrolled(){return await this.guard(()=>this.inner.is_enrolled())}async signal(e,t,r,s){await this.guard(()=>this.inner.signal(Ee(e,"peer"),Ee(t,"dialog"),r,s))}async connectPeer(e){return this.attempts.connect(e,async()=>{try{return await this.inner.peer_direct_dialog(e)??void 0}catch{return}},()=>st(e,this.peerPrimitives(),be),()=>Pt(e,this.peerPrimitives(),be))}async acceptPeer(e){return this.attempts.accept(e,()=>it(e,this.peerPrimitives(),be))}peerPrimitives(){return{offer:e=>this.guard(()=>this.inner.peer_offer(e)),acceptOffer:e=>this.guard(()=>this.inner.peer_accept_offer(e)),candidate:(e,t)=>this.guard(()=>this.inner.peer_candidate(e,t)),handshake:(e,t)=>this.guard(()=>this.inner.peer_handshake(e,t))}}async openStream(e){let t=this.inner.generation(),r=new We(await this.guard(()=>this.inner.open_stream(e)));return this.closed||this.inner.generation()!==t?(r.close(),r):(this.streams.add(r),r)}async callOrg(e,t,r){return await this.guard(()=>this.inner.call_org(e,t,se(r)))}async callOrgStreaming(e,t,r){let s=this.inner.generation(),i;try{let o=await this.inner.call_org_streaming(e,t,se(r));i=new xe(o,()=>o.cancel(),()=>this.orgHandles.delete(i))}catch(o){throw S(o)}return this.closed||this.inner.generation()!==s?(i.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(s)),i):(this.orgHandles.add(i),i)}async callOrgClientStream(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_client_stream(e,se(t));s=new Me(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(r)),s):(this.orgHandles.add(s),s)}async callOrgDuplex(e,t){let r=this.inner.generation(),s;try{let i=await this.inner.call_org_duplex(e,se(t));s=new Ne(i,()=>this.orgHandles.delete(s))}catch(i){throw S(i)}return this.closed||this.inner.generation()!==r?(s.retire(this.closed?new D("org:rpc:cancelled: the session is closed"):new ne(r)),s):(this.orgHandles.add(s),s)}serveOrg(e,t,r,s){try{let i=new ee(this.inner.serve_org(e,t,et(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgStreaming(e,t,r,s){try{let i=new ee(this.inner.serve_org_streaming(e,t,tt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgClientStream(e,t,r,s){try{let i=new ee(this.inner.serve_org_client_stream(e,t,nt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}serveOrgDuplex(e,t,r,s){try{let i=new ee(this.inner.serve_org_duplex(e,t,rt(r),ie(s)),()=>this.orgHandles.delete(i));return this.orgHandles.add(i),i}catch(i){throw S(i)}}on(e,t){return this.hub.on(e,t)}onEvent(e){return this.hub.onAny(e)}onLifecycle(e){return this.hub.onAny(t=>{En(t)&&e(t)})}events(){return this.hub.events()}close(){this.closed||(this.closed=!0,this.orgHandles.retireAll(new D("org:rpc:cancelled: the session is closed")),this.endStreams(),this.hub.close(),this.inner.close())}endStreams(e){let t=[...this.streams];this.streams.clear();for(let r of t)e===void 0?r.close():r.retire(e)}async guard(e){try{return await e()}catch(t){throw S(t)}}};async function qi(n){let e=kn(await ot(n)),t={...Tt(n),...n.capabilities?{capabilities:[...n.capabilities]}:{},...n.subscriptions?{subscriptions:[...n.subscriptions]}:{},...n.dbName===void 0?{}:{dbName:n.dbName},...n.lockScope===void 0?{}:{lockScope:n.lockScope}};if(t.lockScope===void 0&&t.entitySecretHex!==void 0&&n.lockIdentity!==!1){let r=await vn(t.entitySecretHex);r!==null&&(t.lockScope=r)}try{return new Nt(await e.MeshSession.open(t))}catch(r){throw S(r)}}var An=["invalid-data","version-mismatch","forbidden","not-ready","capacity","timeout","aborted","indeterminate","owner-lost","closed","action-rejected","result-expired"],f=class extends Error{code;constructor(e,t,r){super(t,r),this.name="StoreError",this.code=e}};function at(n){return(n instanceof Error?n.message:String(n)).includes("stale stream handle")}var Wt=Object.freeze({$hidden:!0});function qt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.keys(n).length===1&&n.$hidden===!0}function Ui(n){return e=>qt(e)?Wt:n(e)}var Wr=Object.freeze({"card-game":Object.freeze({"players.*.hand":"owner",deck:"nobody","deck.length":"everyone"})}),Bi=/^(\*|[^.*]+)$/;function ke(n){let e;if(n==="open")e={};else if(typeof n=="string"){let s=Wr[n];if(s===void 0)throw new f("invalid-data",`unknown visibility preset '${n}'`);e={...s}}else if(typeof n=="object"&&n!==null){let{preset:s,...i}=n;if(e={},s!==void 0){let o=Wr[s];if(o===void 0)throw new f("invalid-data",`unknown visibility preset '${String(s)}'`);Object.assign(e,o)}Object.assign(e,i)}else throw new f("invalid-data","visibility is a preset name or an object of path \u2192 rule");let t=[],r=!1;for(let[s,i]of Object.entries(e)){let o=s.split(".");if(s.length===0||!o.every(l=>Bi.test(l)))throw new f("invalid-data",`visibility path '${s}' is not dot-separated keys and '*'`);let a=o.length>1&&o[o.length-1]==="length";if(!(i==="everyone"||i==="nobody"||i==="owner"||Array.isArray(i)&&i.length>0&&i.every(l=>typeof l=="string"&&l.length>0)))throw new f("invalid-data",`visibility rule for '${s}' must be 'everyone', 'nobody', 'owner' or a non-empty list of audiences`);if(i==="owner"){if(!o.includes("*"))throw new f("invalid-data",`'owner' needs a '*' in the path to name the owner: '${s}'`);r=!0}t.push(Object.freeze({path:s,segments:Object.freeze(o),rule:i,counts:a}))}return t.sort((s,i)=>s.segments.length-i.segments.length),Object.freeze({rules:Object.freeze(t),perPlayer:r})}function qr(n,e,t){return n==="everyone"?!0:n==="nobody"||t===null?!1:n==="owner"?e[0]===t.peer:n.some(r=>t.audience.includes(r))}function $i(n,e){let t=[],r=(s,i,o,a)=>{if(i===e.length){t.push({keys:[...o],captures:[...a],value:s});return}if(typeof s!="object"||s===null)return;let c=e[i];if(c==="*"){let l=Array.isArray(s)?s.map((d,u)=>[u,d]):Object.entries(s);for(let[d,u]of l)r(u,i+1,[...o,d],[...a,String(d)]);return}Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,c)||r(s[c],i+1,[...o,c],a)};return r(n,0,[],[]),t}var Rn=Symbol("drop");function Fi(n,e,t){let r=n;for(let s of e){let i=r.children.get(s);i===void 0&&(i={children:new Map},r.children.set(s,i)),r=i}r.value=t}function _n(n,e){if("value"in e)return e.value;if(e.children.size===0||typeof n!="object"||n===null)return n;if(Array.isArray(n)){let r=[];return n.forEach((s,i)=>{let o=e.children.get(i),a=o===void 0?s:_n(s,o);a!==Rn&&r.push(a)}),r}let t={};for(let[r,s]of Object.entries(n)){let i=e.children.get(r),o=i===void 0?s:_n(s,i);o!==Rn&&(t[r]=o)}return t}var Ur="\0";function Ae(n,e,t){if(n.rules.length===0)return e;let r={children:new Map},s=new Set,i=!1;for(let o of n.rules){if(o.counts)continue;let a=n.rules.find(l=>l.counts&&l.segments.length===o.segments.length+1&&l.segments.slice(0,-1).every((d,u)=>d===o.segments[u])),c=o.segments[o.segments.length-1]==="*";for(let l of $i(e,o.segments)){let d="",u=!1;for(let h=0;h<l.keys.length-1&&!u;h+=1)d=h===0?String(l.keys[0]):`${d}${Ur}${String(l.keys[h])}`,u=s.has(d);if(u||qr(o.rule,l.captures,t))continue;let p=c?Rn:Wt;a!==void 0&&Array.isArray(l.value)&&qr(a.rule,l.captures,t)&&(p=l.value.map(()=>Wt)),Fi(r,l.keys,p),s.add(l.keys.map(String).join(Ur)),i=!0}}return i?_n(e,r):e}function Br(n,e,t){return n.visibility===void 0?e:Ae(ke(n.visibility),e,t)}function Ji(n,e,t,r){let s=Br(n,e,t);for(let i of r){let o=s;for(let c of i.split(".")){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,c)){o=void 0;break}o=o[c]}if(o!==void 0&&!qt(o)&&!(Array.isArray(o)&&o.every(c=>qt(c))))throw new Error(`'${i}' is visible to ${t===null?"nobody in particular":t.peer}`)}}function Vi(n){if(n.id.length===0)throw new f("invalid-data","a store definition needs a non-empty id");if(!Number.isSafeInteger(n.version)||n.version<1)throw new f("invalid-data",`store '${n.id}' needs a positive integer version, got ${String(n.version)}`);let e;try{e=n.empty()}catch(t){throw new f("invalid-data",`store '${n.id}' could not build its empty state: ${String(t)}`,{cause:t})}try{n.state(e)}catch(t){throw new f("invalid-data",`store '${n.id}': empty() is not a valid state, so a replica could not clear a projection with it: ${String(t)}`,{cause:t})}if(n.visibility!==void 0)try{ke(n.visibility)}catch(t){throw new f("invalid-data",`store '${n.id}': ${t instanceof Error?t.message:String(t)}`,{cause:t})}if(n.interest!==void 0){for(let[t,r]of Object.entries(n.interest))if(t.length===0||t.includes(".")||typeof r!="function")throw new f("invalid-data",`store '${n.id}': interest maps a top-level collection name to a key function, got '${t}'`)}if(n.entities!==void 0)for(let[t,r]of Object.entries(n.entities)){if(t.length===0||t.includes(".")||typeof r!="function")throw new f("invalid-data",`store '${n.id}': entities maps a top-level collection name to a per-entity parser, got '${t}'`);let s=e[t];if(s!==void 0&&!Ut(s))throw new f("invalid-data",`store '${n.id}': entities names '${t}', but empty().${t} is not a record of entities`)}return Object.freeze({...n})}function Ut(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Ki=16;var T=class extends Error{constructor(t,r){super(t);this.reason=t;this.at=r}reason;at};function Re(n){let e=new Pn(n);try{return{ok:!0,value:e.document()}}catch(t){if(t instanceof T)return{ok:!1,reason:t.reason,at:t.at};throw t}}var Pn=class{constructor(e){this.src=e}src;i=0;document(){if(this.skipWhitespace(),this.i>=this.src.length)throw new T("empty",this.i);let e=this.value(0);if(this.skipWhitespace(),this.i!==this.src.length)throw new T("trailing-content",this.i);return e}value(e){let t=this.src.charCodeAt(this.i);switch(t){case 123:return this.object(e+1);case 91:return this.array(e+1);case 34:return this.string();default:break}if(t===45||t>=48&&t<=57)return this.number();if(this.src.startsWith("true",this.i))return this.i+=4,!0;if(this.src.startsWith("false",this.i))return this.i+=5,!1;if(this.src.startsWith("null",this.i))return this.i+=4,null;throw new T(Number.isNaN(t)?"unexpected-end":"literal",this.i)}object(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=Object.create(null);if(this.skipWhitespace(),this.peek()===125)return this.i+=1,t;for(;;){if(this.skipWhitespace(),this.peek()!==34)throw new T("unexpected-token",this.i);let r=this.i,s=this.string();if(Object.prototype.hasOwnProperty.call(t,s))throw new T("duplicate-key",r);if(this.skipWhitespace(),this.peek()!==58)throw new T("unexpected-token",this.i);this.i+=1,this.skipWhitespace(),t[s]=this.value(e),this.skipWhitespace();let i=this.peek();if(i===44){this.i+=1;continue}if(i===125)return this.i+=1,t;throw new T(i===-1?"unexpected-end":"unexpected-token",this.i)}}array(e){if(e>16)throw new T("depth-exceeded",this.i);this.i+=1;let t=[];if(this.skipWhitespace(),this.peek()===93)return this.i+=1,t;for(;;){this.skipWhitespace(),t.push(this.value(e)),this.skipWhitespace();let r=this.peek();if(r===44){this.i+=1;continue}if(r===93)return this.i+=1,t;throw new T(r===-1?"unexpected-end":"unexpected-token",this.i)}}string(){this.i+=1;let e="";for(;;){if(this.i>=this.src.length)throw new T("unexpected-end",this.i);let t=this.src.charCodeAt(this.i);if(t===34)return this.i+=1,e;if(t===92){e+=this.escape();continue}if(t<32)throw new T("string-control-char",this.i);e+=this.src[this.i],this.i+=1}}escape(){this.i+=1;let e=this.src[this.i];switch(this.i+=1,e){case'"':return'"';case"\\":return"\\";case"/":return"/";case"b":return"\b";case"f":return"\f";case"n":return`
2
+ `;case"r":return"\r";case"t":return" ";case"u":{let t=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t))throw new T("string-escape",this.i);return this.i+=4,String.fromCharCode(Number.parseInt(t,16))}default:throw new T("string-escape",this.i-1)}}number(){let e=this.i;if(this.peek()===45&&(this.i+=1),this.peek()===48){if(this.i+=1,this.isDigit(this.peek()))throw new T("number-grammar",e)}else if(this.isDigit(this.peek()))for(;this.isDigit(this.peek());)this.i+=1;else throw new T("number-grammar",e);if(this.peek()===46){if(this.i+=1,!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let t=this.src[this.i];if(t==="e"||t==="E"){this.i+=1;let s=this.peek();if((s===43||s===45)&&(this.i+=1),!this.isDigit(this.peek()))throw new T("number-grammar",e);for(;this.isDigit(this.peek());)this.i+=1}let r=Number(this.src.slice(e,this.i));if(!Number.isFinite(r))throw new T("number-not-finite",e);return r}isDigit(e){return e>=48&&e<=57}peek(){return this.i>=this.src.length?-1:this.src.charCodeAt(this.i)}skipWhitespace(){for(;;){let e=this.peek();if(e===32||e===9||e===10||e===13){this.i+=1;continue}return}}};var jn=1,Y=32,pe=16,$t=16,Fr=32,Jr=128,Vr=256,Kr=64,Se=1024*1024,oe=255,Ft=256,Jt=8,Ke=64,Xr=256,Gr=18446744073709551615n,Xi=20,zr=["join","resume","resync","act","in","aud","alive","leave","int"],Yr=["man","snap","delta","res","ok","no"],Gi={join:{required:["v","k","q","def","ver","store","key","aud"],optional:["int"]},resume:{required:["v","k","q","h","aud"],optional:["int"]},int:{required:["v","k","q","h","int"],optional:[]},resync:{required:["v","k","q","h","g","have"],optional:[]},aud:{required:["v","k","q","h","aud"],optional:[]},alive:{required:["v","k","q","h"],optional:[]},leave:{required:["v","k","q","h"],optional:[]},act:{required:["v","k","q","h","s","name","in"],optional:[]},in:{required:["v","k","h","name","s","in"],optional:[]},man:{required:["v","k","h","inc","g","r","n","bytes"],optional:["q"]},snap:{required:["v","k","h","g","r","i","n","d"],optional:[]},delta:{required:["v","k","h","g","base","r","ops"],optional:[]},res:{required:["v","k","q","h","s","out"],optional:[]},ok:{required:["v","k","q","h"],optional:[]},no:{required:["v","k","code"],optional:["q","h","s","detail"]}},zi={join:["v","k","q","def","ver","store","key","aud","int"],resume:["v","k","q","h","aud","int"],int:["v","k","q","h","int"],resync:["v","k","q","h","g","have"],aud:["v","k","q","h","aud"],alive:["v","k","q","h"],leave:["v","k","q","h"],act:["v","k","q","h","s","name","in"],in:["v","k","h","name","s","in"],man:["v","k","q","h","inc","g","r","n","bytes"],snap:["v","k","h","g","r","i","n","d"],delta:["v","k","h","g","base","r","ops"],res:["v","k","q","h","s","out"],ok:["v","k","q","h"],no:["v","k","q","h","code","s","detail"]},In=new Set(zr),$r=new Set(Yr),Yi=new Set(An),Qi=/^[A-Za-z0-9+/]+={0,2}$/;function F(n,e,t="invalid-data"){return{ok:!1,code:t,stage:n,reason:e}}var Bt=class{constructor(e){this.refusal=e}refusal};function L(n,e,t="invalid-data"){return new Bt(F(n,e,t))}function O(n){return n instanceof Bt}function N(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.codePointAt(t);r>65535&&(t+=1),e+=r<=127?1:r<=2047?2:r<=65535?3:4}return e}function _e(n,e){if(N(n)>e.maxBytes)return F("bytes","frame-too-large","capacity");let r=Re(n);if(!r.ok)return F("json",r.reason);let s=r.value;if(typeof s!="object"||s===null||Array.isArray(s))return F("json","not-an-object");let i=s;if(i.v!==jn)return F("envelope","unknown-version");let o=i.k;if(typeof o!="string"||!(In.has(o)||$r.has(o)))return F("envelope","unknown-kind");let a=o;if(!(e.as==="owner"?In:$r).has(a))return F("direction",`wrong-direction:${a}`);let l=Gi[a],d=new Set([...l.required,...l.optional]);for(let u of Object.keys(i))if(!d.has(u))return F("payload","unknown-field");for(let u of l.required)if(!Object.prototype.hasOwnProperty.call(i,u))return F("payload","missing-field");return Zi(a,i)}function Zi(n,e){let t=(l,d)=>{let u=e[l];return typeof u!="string"||u.length!==d||!Qr(u)?L("payload",`non-canonical-hex:${l}`):u},r=l=>{let d=e[l];return typeof d!="string"||!Hn(d)?L("payload",`non-canonical-decimal:${l}`):d},s=(l,d,u)=>{let p=e[l];return typeof p!="number"||!Number.isInteger(p)||p<d||p>u?L("payload",`bad-integer:${l}`):p},i=l=>{let d=e[l];return typeof d!="string"||d.length===0?L("payload",`bad-string:${l}`):d},o=l=>{let d=e[l];return typeof d!="object"||d===null||Array.isArray(d)?L("payload",`bad-object:${l}`):d},a=()=>{let l=e.aud;if(!Array.isArray(l))return L("payload","bad-audience");if(l.length>Fr)return L("payload","audience-too-many","capacity");let d=[];for(let u of l){if(typeof u!="string"||u.length===0)return L("payload","bad-audience-label");if(N(u)>Jr)return L("payload","audience-label-too-long","capacity");d.push(u)}return d},c=l=>{if(!Object.prototype.hasOwnProperty.call(e,"int"))return l?L("payload","missing-field"):void 0;let d=e.int;if(!Array.isArray(d))return L("payload","bad-interest");if(d.length>Vr)return L("payload","interest-too-many","capacity");let u=[];for(let p of d){if(typeof p!="string"||p.length===0)return L("payload","bad-interest-key");if(N(p)>Kr)return L("payload","interest-key-too-long","capacity");u.push(p)}return u};switch(n){case"int":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=c(!0);return O(u)?u.refusal:{ok:!0,message:{k:n,q:l,h:d,int:u}}}case"join":{let l=t("q",pe);if(O(l))return l.refusal;let d=i("def");if(O(d))return d.refusal;let u=s("ver",0,Number.MAX_SAFE_INTEGER);if(O(u))return u.refusal;let p=i("store");if(O(p))return p.refusal;let h=i("key");if(O(h))return h.refusal;let y=a();if(O(y))return y.refusal;let m=c(!1);return O(m)?m.refusal:{ok:!0,message:m===void 0?{k:n,q:l,def:d,ver:u,store:p,key:h,aud:y}:{k:n,q:l,def:d,ver:u,store:p,key:h,aud:y,int:m}}}case"resume":case"aud":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=a();if(O(u))return u.refusal;if(n==="resume"){let p=c(!1);return O(p)?p.refusal:{ok:!0,message:p===void 0?{k:n,q:l,h:d,aud:u}:{k:n,q:l,h:d,aud:u,int:p}}}return{ok:!0,message:{k:n,q:l,h:d,aud:u}}}case"resync":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("have");return O(p)?p.refusal:{ok:!0,message:{k:n,q:l,h:d,g:u,have:p}}}case"alive":case"leave":case"ok":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);return O(d)?d.refusal:{ok:!0,message:{k:n,q:l,h:d}}}case"act":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=i("name");if(O(p))return p.refusal;let h=o("in");return O(h)?h.refusal:{ok:!0,message:{k:n,q:l,h:d,s:u,name:p,in:h}}}case"in":{let l=t("h",Y);if(O(l))return l.refusal;let d=i("name");if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("in");return O(p)?p.refusal:{ok:!0,message:{k:n,h:l,name:d,s:u,in:p}}}case"res":{let l=t("q",pe);if(O(l))return l.refusal;let d=t("h",Y);if(O(d))return d.refusal;let u=r("s");if(O(u))return u.refusal;let p=o("out");return O(p)?p.refusal:{ok:!0,message:{k:n,q:l,h:d,s:u,out:p}}}case"man":{let l=t("h",Y);if(O(l))return l.refusal;let d=t("inc",$t);if(O(d))return d.refusal;let u=r("g");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let h=s("n",1,oe);if(O(h))return h.refusal;let y=r("bytes");if(O(y))return y.refusal;if(BigInt(y)>BigInt(Se))return F("payload","snapshot-too-large","capacity");if(Object.prototype.hasOwnProperty.call(e,"q")){let m=t("q",pe);return O(m)?m.refusal:{ok:!0,message:{k:n,q:m,h:l,inc:d,g:u,r:p,n:h,bytes:y}}}return{ok:!0,message:{k:n,h:l,inc:d,g:u,r:p,n:h,bytes:y}}}case"snap":{let l=t("h",Y);if(O(l))return l.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("r");if(O(u))return u.refusal;let p=s("n",1,oe);if(O(p))return p.refusal;let h=s("i",0,p-1);if(O(h))return h.refusal;let y=e.d;return typeof y!="string"||!Vt(y)?F("payload","non-canonical-base64:d"):{ok:!0,message:{k:n,h:l,g:d,r:u,i:h,n:p,d:y}}}case"delta":{let l=t("h",Y);if(O(l))return l.refusal;let d=r("g");if(O(d))return d.refusal;let u=r("base");if(O(u))return u.refusal;let p=r("r");if(O(p))return p.refusal;let h=eo(e.ops);return O(h)?h.refusal:{ok:!0,message:{k:n,h:l,g:d,base:u,r:p,ops:h}}}case"no":{let l=e.code;if(typeof l!="string"||!Yi.has(l))return F("payload","unknown-code");let d=Object.prototype.hasOwnProperty.call(e,"q"),u=Object.prototype.hasOwnProperty.call(e,"h"),p=Object.prototype.hasOwnProperty.call(e,"s");if(!d&&!u)return F("payload","no-names-nothing");if(!d){if(l!=="closed"&&l!=="owner-lost")return F("payload","unsolicited-no-must-be-closed-or-owner-lost");if(p)return F("payload","unsolicited-no-carries-no-sequence")}let h={k:"no",code:l};if(d){let y=t("q",pe);if(O(y))return y.refusal;h.q=y}if(u){let y=t("h",Y);if(O(y))return y.refusal;h.h=y}if(p){let y=r("s");if(O(y))return y.refusal;h.s=y}if(Object.prototype.hasOwnProperty.call(e,"detail")){let y=e.detail;if(typeof y!="string")return F("payload","bad-string:detail");if(N(y)>Xr)return F("payload","detail-too-long","capacity");h.detail=y}return{ok:!0,message:h}}}}function eo(n){if(!Array.isArray(n))return L("payload","bad-ops");if(n.length>Ft)return L("payload","ops-too-many","capacity");let e=[];for(let t of n){if(typeof t!="object"||t===null||Array.isArray(t))return L("payload","bad-op");let r=t,s=r.o;if(s!=="r"&&s!=="x")return L("payload","bad-op-kind");let i=s==="r"?["o","p","val"]:["o","p"];for(let c of Object.keys(r))if(!i.includes(c))return L("payload","unknown-field");if(s==="r"&&!Object.prototype.hasOwnProperty.call(r,"val"))return L("payload","missing-field");let o=r.p;if(!Array.isArray(o))return L("payload","bad-path");if(o.length>Jt)return L("payload","path-too-deep","capacity");let a=[];for(let c of o){if(typeof c!="string"||c.length===0)return L("payload","bad-segment");if(N(c)>Ke)return L("payload","segment-too-long","capacity");a.push(c)}e.push(s==="r"?{o:s,p:a,val:r.val}:{o:s,p:a})}return e}function Qr(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e),r=t>=48&&t<=57,s=t>=97&&t<=102;if(!r&&!s)return!1}return n.length>0}function Hn(n){if(n.length===0||n.length>Xi)return!1;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t<48||t>57)return!1}return n.length>1&&n.charCodeAt(0)===48?!1:BigInt(n)<=Gr}function Vt(n){if(n.length===0)return!0;if(n.length%4!==0||!Qi.test(n))return!1;let e=n.endsWith("==")?2:n.endsWith("=")?1:0;if(e===0)return!0;let t=n.charCodeAt(n.length-e-1),r=to(t);return r<0?!1:(r&(e===2?15:3))===0}function to(n){return n>=65&&n<=90?n-65:n>=97&&n<=122?n-97+26:n>=48&&n<=57?n-48+52:n===43?62:n===47?63:-1}function ae(n){if(!Hn(n))throw new RangeError(`not a canonical decimal: ${JSON.stringify(n)}`);return BigInt(n)}function Kt(n,e){return Cn(n,e,new Set)}function Cn(n,e,t){if(n===null)return null;switch(typeof n){case"boolean":case"string":return null;case"number":return Number.isFinite(n)?null:`non-finite-number:${e}`;case"object":{let r=n;if(t.has(r))return`circular:${e}`;if("toJSON"in r)return`to-json-transform:${e}`;if(r instanceof Map||r instanceof Set||r instanceof WeakMap||r instanceof WeakSet)return`map-or-set:${e}`;if(Object.getOwnPropertySymbols(r).length>0)return`symbol-key:${e}`;t.add(r);try{if(Array.isArray(n)){for(let s=0;s<n.length;s+=1){let i=Cn(n[s],`${e}[${s}]`,t);if(i!==null)return i}return null}for(let[s,i]of Object.entries(n)){let o=Cn(i,`${e}.${s}`,t);if(o!==null)return o}return null}finally{t.delete(r)}}default:return`not-json:${e}`}}function no(n){switch(n.k){case"act":case"in":return[["in",n.in]];case"res":return[["out",n.out]];case"delta":return n.ops.flatMap((e,t)=>e.o==="r"?[[`ops[${t}].val`,e.val]]:[]);default:return[]}}function P(n){for(let[o,a]of no(n)){let c=Kt(a,o);if(c!==null)throw new RangeError(`refusing to encode an invalid ${n.k}: ${c}`)}let e={v:jn,k:n.k},t=n;for(let o of zi[n.k]){if(o==="v"||o==="k"||!Object.prototype.hasOwnProperty.call(t,o))continue;let a=t[o];a!==void 0&&(e[o]=a)}let r=JSON.stringify(e),s=In.has(n.k)?"owner":"replica",i=_e(r,{maxBytes:Number.MAX_SAFE_INTEGER,as:s});if(!i.ok)throw new RangeError(`refusing to encode an invalid ${n.k}: ${i.reason}`);return r}var es=192,Ln=1024,Tn=197;function ts(n){return Math.floor((n-es)/4)*3}function Dn(n){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new f("capacity",`the transport reported no usable event size (${String(n)})`);if(Tn>n)throw new f("capacity",`the frozen envelopes need ${Tn} B and the transport allows ${n} B`);let e=ts(n);if(e<Ln)throw new f("capacity",`a ${n} B event leaves ${e} B per chunk, below the ${Ln} B floor`);if(e*oe<Se)throw new f("capacity",`a ${n} B event leaves ${e} B per chunk: ${oe} of them cover ${e*oe} B, below the ${Se} B snapshot bound`);return e}function Mn(n,e){if(e<1)throw new f("capacity",`a chunk budget of ${e} B cannot carry anything`);try{let i=Kt(n,"state");if(i!==null)throw new f("invalid-data",`the projected state is not JSON: ${i}`)}catch(i){throw i instanceof f?i:new f("invalid-data",`the projected state is not JSON: ${String(i)}`,{cause:i})}let t;try{t=JSON.stringify(n)}catch(i){throw new f("invalid-data","the projected state is not JSON",{cause:i})}if(t===void 0)throw new f("invalid-data","the projected state is not JSON");let r=new TextEncoder().encode(t);if(r.length>Se)throw new f("capacity",`the projection is ${r.length} B and the bound is ${Se} B`);let s=[];for(let i=0;i<r.length;i+=e)s.push(ns(r.subarray(i,i+e)));if(s.length>oe)throw new f("capacity",`the projection needs ${s.length} chunks and the bound is ${oe}`);return{bytes:r.length,n:s.length,pieces:s}}var Zr=32768;function ns(n){let e="";for(let t=0;t<n.length;t+=Zr)e+=String.fromCharCode(...n.subarray(t,t+Zr));return btoa(e)}function Nn(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function ro(n){let e=JSON.stringify(n);if(e===void 0)throw new f("invalid-data","not JSON");return N(e)}var Gt=1e4,rs=8*1024*1024;function X(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,fatal:e}}var Xt=class{constructor(e,t){this.manifest=e;this.openedAt=t;this.pieces=new Array(e.n),this.encoded=new Array(e.n)}manifest;openedAt;pieces;encoded;admitted=0;held=0;closed=!1;get bytesHeld(){return this.held}get bytesReserved(){return this.closed?0:Math.max(Number(this.manifest.bytes),this.held)}get have(){return this.admitted}get reclaimed(){return this.closed}reclaim(){this.closed=!0,this.pieces.fill(void 0),this.encoded.fill(void 0),this.admitted=0,this.held=0}expired(e){return e-this.openedAt>=Gt}accept(e,t,r){if(this.closed)return X("chunk-wrong-assembly",!1);if(this.expired(r))return this.reclaim(),X("deadline",!0,"timeout");let s=this.manifest;if(e.h!==s.h||e.g!==s.g||e.r!==s.r||e.n!==s.n)return X("chunk-wrong-assembly",!1);if(!Number.isInteger(e.i)||e.i<0||e.i>=s.n)return X("chunk-index",!1);if(!Vt(e.d))return X("chunk-non-canonical",!1);let i=this.encoded[e.i];if(i!==void 0)return i===e.d?{ok:!0,done:!1,have:this.admitted}:(this.reclaim(),X("chunk-conflict",!0));let o=Nn(e.d),a=Number(s.bytes);if(this.held+o.length>a)return this.reclaim(),X("byte-total-mismatch",!0);if(this.encoded[e.i]=e.d,this.pieces[e.i]=o,this.admitted+=1,this.held+=o.length,this.admitted<s.n)return{ok:!0,done:!1,have:this.admitted};if(this.held!==a)return this.reclaim(),X("byte-total-mismatch",!0);let c=new Uint8Array(this.held),l=0;for(let p of this.pieces){if(p===void 0)return this.reclaim(),X("byte-total-mismatch",!0);c.set(p,l),l+=p.length}let d=new TextDecoder("utf-8",{fatal:!0}),u;try{let p=Re(d.decode(c));if(!p.ok)return this.reclaim(),X("assembled-not-json",!0);u=p.value}catch{return this.reclaim(),X("assembled-not-json",!0)}try{t(u)}catch{return this.reclaim(),X("assembled-invalid",!0)}return this.reclaim(),{ok:!0,done:!0,document:u}}},lt=class n{constructor(e=rs){this.maxTotalBytes=e}maxTotalBytes;live=new Map;static key(e,t){return`${e}/${t}`}get bytesHeld(){let e=0;for(let t of this.live.values())e+=t.bytesHeld;return e}get bytesReserved(){let e=0;for(let t of this.live.values())e+=t.bytesReserved;return e}get size(){return this.live.size}get(e,t){return this.live.get(n.key(e,t))}open(e,t){if(!Number.isInteger(e.n)||e.n<1||e.n>oe)return X("manifest-chunk-count",!0);let r=Number(e.bytes);if(!Number.isSafeInteger(r)||r<0||r>Se)return X("manifest-bytes",!0,"capacity");let s=n.key(e.h,e.g),i=this.live.get(s),o=i?.bytesReserved??0;if(this.bytesReserved-o+r>this.maxTotalBytes)return X("assembly-too-large",!0,"capacity");i?.reclaim(),this.live.delete(s);let a=new Xt(e,t);return this.live.set(s,a),a}reclaim(e,t){let r=n.key(e,t);this.live.get(r)?.reclaim(),this.live.delete(r)}reclaimHandle(e){for(let[t,r]of[...this.live])t.startsWith(`${e}/`)&&(r.reclaim(),this.live.delete(t))}sweep(e){let t=0;for(let[r,s]of[...this.live])s.expired(e)&&(s.reclaim(),this.live.delete(r),t+=1);return t}clear(){for(let e of this.live.values())e.reclaim();this.live.clear()}};function fe(n,e){if(Object.is(n,e))return e;if(Array.isArray(e)){let t=e;if(!Array.isArray(n))return is(t,void 0);let r=is(t,n);return n.length===t.length&&so(n,r)?n:r}if(ss(e)){if(!ss(n))return os(e,void 0);let t=os(e,n),r=Object.keys(e);return r.length===Object.keys(n).length&&r.every(s=>as(n,s)&&Object.is(n[s],t[s]))?n:t}return e}function zt(n,e){let t=Object.keys(e);if(t.length===0)return n;let r=!1,s={...n};for(let i of t){let o=ls(n,i),a=fe(o,e[i]);Object.is(o,a)||(Object.defineProperty(s,i,{value:a,enumerable:!0,writable:!0,configurable:!0}),r=!0)}return r?Object.freeze(s):n}function ss(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function so(n,e){for(let t=0;t<e.length;t+=1)if(!Object.is(n[t],e[t]))return!1;return!0}function is(n,e){let t=new Array(n.length);for(let r=0;r<n.length;r+=1)t[r]=fe(e?.[r],n[r]);return Object.freeze(t)}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function ls(n,e){if(n!==void 0)return as(n,e)?n[e]:void 0}function os(n,e){let t={};for(let r of Object.keys(n))Object.defineProperty(t,r,{value:fe(ls(e,r),n[r]),enumerable:!0,writable:!1,configurable:!1});return Object.freeze(t)}var cs=["__proto__","constructor","prototype"],io=new Set(cs);function he(n,e,t="invalid-data"){return{ok:!1,code:t,reason:n,resync:e}}function Wn(n,e,t){if(e.length>Ft)return he("ops-too-many",!1,"capacity");for(let a of e){if(a.p.length>Jt)return he("path-too-deep",!1,"capacity");for(let c of a.p){if(N(c)>Ke)return he("segment-too-long",!1,"capacity");if(io.has(c))return he("segment-forbidden",!1)}if(a.o==="x"&&a.p.length===0)return he("root-remove",!1)}let r=n,s=new WeakSet;for(let a of e){if(a.p.length===0){a.o==="r"&&(r=a.val);continue}if(!ps(r))return he("parent-not-object",!0);let c=fs(r,s);r=c;let l=oo(c,a.p.slice(0,-1),s);if(l===ds)return he("missing-parent",!0);if(l===us)return he("parent-not-object",!0);let d=l,u=a.p[a.p.length-1];if(a.o==="x"){if(!Object.prototype.hasOwnProperty.call(d,u))return he("missing-key",!0);delete d[u];continue}d[u]=a.val}let i;try{i=t(r)}catch{return he("invalid-state",!0)}let o=fe(n,i);return{ok:!0,next:o,changed:!Object.is(o,n)}}var ds=Symbol("missing-parent"),us=Symbol("parent-not-object");function oo(n,e,t){let r=n;for(let s of e){let i=r;if(!Object.prototype.hasOwnProperty.call(i,s))return ds;let o=i[s];if(!ps(o))return us;let a=fs(o,t);i[s]=a,r=a}return r}function ps(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function fs(n,e){if(e.has(n))return n;let t=Object.assign(Object.create(null),n);return e.add(t),t}var we=class{#e;#t=new Set;#r=new Set;#n;#s;#g=0;#o=null;#a=0;#u=!1;constructor(e){this.#e=e.definition,this.#n=fe(void 0,this.#d(e.initialState)),this.#s=Object.freeze({phase:e.phase??"ready",stale:!1,error:null})}getState(){return this.#n}get revision(){return this.#g}get inTransaction(){return this.#o!==null&&this.#o.active}subscribe(e,t,r){let s=t===void 0?this.#y(e):this.#O(e,t,r);this.#t.add(s);let i=!0;return()=>{i&&(i=!1,this.#t.delete(s))}}getStatus(){return this.#s}subscribeStatus(e){this.#r.add(e);let t=!0;return()=>{t&&(t=!1,this.#r.delete(e))}}setStatus(e){let t=this.#s,r={phase:e.phase??t.phase,stale:e.stale??t.stale,error:e.error===void 0?t.error:e.error};if(!(r.phase===t.phase&&r.stale===t.stale&&Object.is(r.error,t.error))){this.#s=Object.freeze(r);for(let s of[...this.#r])this.#r.has(s)&&Yt(()=>s(this.#s,t))}}transact(e,t){if(this.#l(),this.#o!==null)throw new f("action-rejected","a store transaction is already open on this store; handlers are synchronous and must not nest");let r={staged:this.#n,active:!0};this.#o=r;try{let s=e(this.#c(r,t));if(ao(s))throw new f("action-rejected","a store handler returned a thenable; handlers are synchronous so that a throw can discard the whole transaction");return this.#b(r.staged),s}finally{r.active=!1,this.#o=null}}applyOwnerUpdate(e){this.#l();let t=this.#o;if(t!==null&&t.active){t.staged=this.#f(t.staged,e);return}let r=this.#f(this.#n,e);this.#b(r)}applySnapshot(e){this.#l();let t=this.#o;if(t!==null&&t.active){t.staged=this.#d(e);return}this.#b(this.#d(e))}applyEntities(e,t){this.#l();let r=this.#e.entities?.[e];if(r===void 0||!Object.prototype.hasOwnProperty.call(this.#e.entities,e))throw new f("invalid-data",`store '${this.#e.id}' declares no per-entity parser for '${e}'; declare it in \`entities\` or write through setState`);let s=this.#o,i=s!==null&&s.active?s.staged:this.#n,o=i[e];if(o!==void 0&&!Ut(o))throw new f("invalid-data",`store '${this.#e.id}': '${e}' is not an entity map in the current state`);let a=[];for(let p of Object.keys(t)){if(p.length===0)throw new f("invalid-data",`store '${this.#e.id}': an entity id in '${e}' is empty`);let h=t[p];if(h===void 0){a.push([p,void 0]);continue}try{a.push([p,this.runReadOnly(()=>r(h))])}catch(y){throw y instanceof f?y:new f("invalid-data",`entity '${e}.${p}' failed the '${this.#e.id}' entity validator: ${String(y)}`,{cause:y})}}if(s!==null&&s.active){let p={...o??{}};for(let[h,y]of a)y===void 0?delete p[h]:qn(p,h,y);s.staged=zt(i,{[e]:p});return}let c=!1,l=[];for(let[p,h]of a){let y=o!==void 0&&Object.prototype.hasOwnProperty.call(o,p),m=y?o[p]:void 0;if(h===void 0){y&&(c=!0),l.push([p,void 0]);continue}let A=fe(m,h);Object.is(m,A)||(c=!0),l.push([p,A])}if(!c)return;let d={...o??{}};for(let[p,h]of l)h===void 0?delete d[p]:qn(d,p,h);let u={...i};qn(u,e,Object.freeze(d)),this.#p(Object.freeze(u))}applyDelta(e){this.#l();let t=Wn(this.#n,e,r=>this.#d(r));return t.ok&&t.changed&&this.#h(t.next),t}runReadOnly(e){this.#a+=1;try{return e()}finally{this.#a-=1}}close(){this.#u||(this.#u=!0,this.setStatus({phase:"closed",stale:!0}),this.#t.clear(),this.#r.clear())}#c(e,t){return{peer:t,getState:()=>(this.#w(e),e.staged),setState:r=>{if(this.#w(e),this.#a>0)throw new f("action-rejected","a read-only store callback may not write state; validators, authorize, project and update functions run with setters fenced");e.staged=this.#f(e.staged,r)}}}#f(e,t){let r=typeof t=="function"?this.runReadOnly(()=>t(e)):t;return zt(e,r)}#b(e){this.#h(this.#d(e))}#h(e){let t=fe(this.#n,e);Object.is(t,this.#n)||this.#p(t)}#p(e){let t=this.#n;this.#n=e,this.#g+=1;for(let r of[...this.#t])this.#t.has(r)&&r.notify(e,t)}#d(e){try{return this.runReadOnly(()=>this.#e.state(e))}catch(t){throw t instanceof f?t:new f("invalid-data",`state failed the '${this.#e.id}' validator: ${String(t)}`,{cause:t})}}#y(e){return{notify:(t,r)=>{Yt(()=>e(t,r))}}}#O(e,t,r){let s=r?.equality??Object.is,i=this.runReadOnly(()=>e(this.#n));return r?.fireImmediately===!0&&Yt(()=>t(i,i)),{notify:o=>{let a=this.runReadOnly(()=>e(o)),c=i;s(a,c)||(i=a,Yt(()=>t(a,c)))}}}#w(e){if(!e.active)throw new f("action-rejected","this store transaction has already ended; its context cannot read or write from a later turn")}#l(){if(this.#u)throw new f("closed","this store handle is closed")}};function ao(n){return n===null||typeof n!="object"&&typeof n!="function"?!1:typeof n.then=="function"}function Yt(n){try{n()}catch(e){console.error("[@net-mesh/browser] store listener threw",e)}}function qn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}var hs=32,ys=64*1024,gs=6e4,ms=2048,bs=(1n<<64n)-1n,lo="";function Bn(n,e){return`${n}${lo}${Un(e)}`}function Un(n){if(n===null||typeof n=="boolean")return String(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new f("invalid-data","a canonical request cannot contain a non-finite number");return String(n)}if(typeof n=="string")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(s=>Un(s)).join(",")}]`;let e=n;return`{${Object.keys(e).sort().map(s=>`${JSON.stringify(s)}:${Un(e[s])}`).join(",")}}`}function Ss(n){return new TextEncoder().encode(n).byteLength}function en(n){return Ss(n)>ms}function $n(n){if(en(n))throw new f("invalid-data","this canonical form needs the digest path");return{form:"inline",value:n}}async function Fn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t=new Uint8Array(e),r="";for(let s of t)r+=s.toString(16).padStart(2,"0");return{form:"digest",value:r}}function co(n,e){return n.form===e.form&&n.value===e.value}var Qt=class{constructor(e=hs,t=ys,r=gs){this.maxEntries=e;this.maxBytes=t;this.maxAgeMs=r}maxEntries;maxBytes;maxAgeMs;#e=0n;#t=new Map;#r=0;get floor(){return this.#e.toString()}get size(){return this.#t.size}get bytesHeld(){return this.#r}disposition(e,t,r){if(this.expire(r),e>=bs)return{kind:"exhausted"};let s=this.#t.get(e.toString());return s!==void 0?co(s.binding,t)?{kind:"replay",outcome:s.outcome}:{kind:"conflict"}:e<=this.#e?{kind:"expired"}:{kind:"execute"}}retain(e,t,r,s){let i=uo(t,r);this.#t.set(e.toString(),{s:e,binding:t,outcome:r,bytes:i,at:s}),this.#r+=i,this.evict(s)}expire(e){for(let t of this.ordered()){if(e-t.at<this.maxAgeMs)break;this.drop(t)}}evict(e){for(this.expire(e);this.#t.size>this.maxEntries||this.#r>this.maxBytes;){let t=this.ordered()[0];if(t===void 0)return;this.drop(t)}}drop(e){this.#t.delete(e.s.toString()),this.#r-=e.bytes,e.s>this.#e&&(this.#e=e.s)}ordered(){return[...this.#t.values()].sort((e,t)=>e.s<t.s?-1:e.s>t.s?1:0)}};function uo(n,e){let t=e.kind==="result"?JSON.stringify(e.out):e.code;return N(n.value)+N(t)}var Zt=class{#e=new Map;#t=0;get dropped(){return this.#t}admit(e,t){let r=this.#e.get(e);return r!==void 0&&t<=r?(this.#t+=1,!1):(this.#e.set(e,t),!0)}latest(e){let t=this.#e.get(e);return t===void 0?null:t.toString()}},ct=class{#e=new Map;#t=new Map;ledger(e){let t=this.#e.get(e);return t===void 0&&(t=new Qt,this.#e.set(e,t)),t}inputs(e){let t=this.#t.get(e);return t===void 0&&(t=new Zt,this.#t.set(e,t)),t}forget(e){this.#e.delete(e),this.#t.delete(e)}get size(){return this.#e.size}};var Os=32,xs=256,po=16,Jn=6e4,Es=256;function ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var fo="0".repeat(16),ho="0".repeat(32),dt=class{constructor(e){this.deps=e;if(this.chunkBytes=Dn(e.maxEventBytes),this.incarnation=e.newIncarnation(),this.incarnation.length!==$t)throw new f("invalid-data","newIncarnation must return 16 lowercase hex");let t=(typeof e.project=="function"?1:0)+(typeof e.projectFor=="function"?1:0),r=e.definition.visibility;if(t>1||t===0&&r===void 0)throw new f("invalid-data","a host needs one of `project` and `projectFor`, or a definition that declares `visibility`");this.visibility=r===void 0?null:ke(r),this.perPlayer=typeof e.projectFor=="function"||this.visibility?.perPlayer===!0,this.core=new we({definition:e.definition,initialState:e.definition.empty()})}deps;handles=new Map;counters={};chunkBytes;incarnation;core;pending=0;ledgers=new ct;deferred=new Map;revisionBeforeCommit=0;perPlayer;visibility;warned=new Set;warnOnce(e){if(!(this.deps.warn===void 0||this.warned.has(e))){this.warned.add(e);try{this.deps.warn(e)}catch{}}}viewKey(e,t){return this.perPlayer?JSON.stringify([e,t]):JSON.stringify(t)}get sparseViews(){return this.sparseViewCount}sparseViewCount=0;snapshotCounters(){return{...this.counters}}get handleCount(){return this.handles.size}handle(e){return this.handles.get(e)}commit(e){let t=this.core.inTransaction,r=this.core.getState();if(t||(this.revisionBeforeCommit=this.core.revision),this.core.applySnapshot(e),t)return this.accept([]);let s=this.core.getState();return Object.is(r,s)?this.accept([]):this.accept(this.propagate(r,s))}commitEntities(e,t){let r=this.core.inTransaction,s=this.core.getState();if(r||(this.revisionBeforeCommit=this.core.revision),this.core.applyEntities(e,t),r)return this.accept([]);let i=this.core.getState();return Object.is(s,i)?this.accept([]):this.accept(this.propagate(s,i))}propagate(e,t){let r=[],s=String(this.core.revision),i=new Map,o=new Map,a;for(let c of[...this.handles.values()]){if(this.deferred.has(c.h))continue;if(!this.permitsRead(c.peer,c.audience,c.key)){this.forget(c.h,"refused"),r.push(this.no(c.peer,c.h,"closed",null));continue}let l=this.viewKey(c.peer,c.audience),d;if(this.interestFns.length>0&&c.interest!==null){let h=i.get(l);if(h===void 0){if(a===void 0&&(a=this.entityDelta(e,t)),h=a===null?void 0:this.sparseInterestDiff(c.peer,c.audience,a),h===void 0){let y=this.project(c.peer,c.audience,e),m=this.project(c.peer,c.audience,t);h=y===null||m===null?null:this.interestDiff(y,m)}else this.sparseViewCount+=1;i.set(l,h)}d=h===null?null:this.interestOps(h,c.interest)}else if(d=o.get(l),d===void 0){let h=this.project(c.peer,c.audience,e),y=this.project(c.peer,c.audience,t);d=h===null||y===null?null:ws(h,y),o.set(l,d)}if(d===null){this.forget(c.h),r.push(this.no(c.peer,c.h,"closed",null));continue}if(d.length===0)continue;let u=vs({k:"delta",h:c.h,g:String(c.generation),base:String(c.revision),r:s,ops:d},this.deps.maxEventBytes);if(u!==null){r.push({peer:c.peer,h:c.h,frame:u}),this.handles.set(c.h,{...c,revision:this.core.revision});continue}let p=this.install(c,null);if(p===null){this.forget(c.h),r.push(this.no(c.peer,c.h,"closed",null));continue}r.push(...p)}return r}getState(){return this.core.getState()}subscribe(e){return this.core.subscribe((t,r)=>{e(t,r)})}get currentRevision(){return this.core.revision}localRead(e,t){return this.permitsRead(e,t)}localView(e,t,r=null){let s=this.project(e,t);return s===null?null:this.filterInterest(s,r)}localAct(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,e))return{outcome:{kind:"refusal",code:"invalid-data"},dispatched:this.refuse("local-act-unknown-name")};if(!this.permitsAction(r,e,t))return{outcome:{kind:"refusal",code:"forbidden"},dispatched:this.refuse("local-act-forbidden")};let s=this.deps.definition.actions[e],i=this.core.getState();this.revisionBeforeCommit=this.core.revision;let o;try{let l=this.deps.actions[e];o={kind:"result",out:this.core.transact(u=>{let p=s.output(l(s.input(t),u)),h=P({k:"res",q:fo,h:ho,s:"1",out:p});if(N(h)>this.deps.maxEventBytes)throw new f("capacity","the result does not fit the message budget");return p},r)}}catch(l){o={kind:"refusal",code:l instanceof f&&l.code==="capacity"?"capacity":"action-rejected"}}let a=this.core.getState(),c=Object.is(i,a)?[]:this.propagate(i,a);return{outcome:o,dispatched:o.kind==="refusal"?this.refuse(`local-act-${o.code}`,c):this.accept(c)}}localInput(e,t,r){if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,e))return this.refuse("local-in-unknown-name");if(!this.permitsInput(r,e,t))return this.refuse("local-in-forbidden");let s=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(o=>{let a=this.deps.definition.inputs[e],c=this.deps.inputs[e];c(a(t),o)},r)}catch{return this.refuse("local-in-rejected")}let i=this.core.getState();return this.accept(Object.is(s,i)?[]:this.propagate(s,i))}receive(e,t,r=this.deps.now()){let s=_e(e,{maxBytes:this.deps.maxEventBytes,as:"owner"});if(!s.ok)return this.refuse(s.reason,[]);let i=s.message;if(i.k==="join")return this.join(i,t,r);let o=this.bind(i.h,t,r);if(typeof o=="string")return this.refuse(o,[this.no(t,i.h,"closed",mo(i))]);switch(i.k){case"alive":return this.handles.set(o.h,{...o,lastSeen:r}),this.accept([{peer:t,h:o.h,frame:P({k:"ok",q:i.q,h:o.h})}]);case"leave":return this.forget(o.h,"left"),this.accept([{peer:t,h:o.h,frame:P({k:"ok",q:i.q,h:o.h})}]);case"int":return this.interestChange(i,o,t,r);case"act":return this.action(i,o,t,r);case"in":return this.input(i,o,t,r);case"resync":{if(!this.permitsRead(t,o.audience,o.key))return this.refuse("resync-forbidden",[this.no(t,o.h,"forbidden",i.q)]);let a={...o,lastSeen:r};this.handles.set(o.h,a);let c=this.install(a,i.q);return c===null?(this.forget(o.h),this.refuse("resync-projection-capacity",[this.no(t,o.h,"capacity",i.q)])):this.accept(c)}case"aud":case"resume":{if(!this.permitsRead(t,i.aud,o.key))return this.refuse(`${i.k}-forbidden`,[this.no(t,o.h,"forbidden",i.q)]);let a={...o,audience:[...i.aud],interest:i.k==="resume"&&i.int!==void 0?[...i.int]:o.interest,lastSeen:r};if(this.handles.set(a.h,a),!this.deps.canProject())return this.deferred.set(a.h,{q:i.q,peer:t}),this.accept([]);let c=this.install(a,i.q);return c===null?(this.forget(a.h),this.refuse(`${i.k}-projection-capacity`,[this.no(t,a.h,"capacity",i.q)])):this.accept(c)}default:return this.refuse("unreachable-kind")}}action(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.actions,i))return this.refuse("act-unknown-name",[this.no(r,t.h,"invalid-data",e.q)]);let o;try{o=Bn(i,e.in)}catch{return this.refuse("act-uncanonical",[this.no(r,t.h,"invalid-data",e.q)])}if(!en(o))return this.decide(e,t,r,s,$n(o));if(this.pending>=Os)return this.refuse("act-pending-bound",[this.no(r,t.h,"capacity",e.q)]);this.pending+=1;let a=Fn(o).then(c=>{let l=this.deps.now(),d=this.bind(e.h,r,l);return typeof d=="string"?this.refuse(d,[this.no(r,e.h,"closed",e.q)]):this.decide(e,d,r,l,c)}).catch(()=>this.refuse("act-digest-failed",[this.no(r,e.h,"indeterminate",e.q)])).finally(()=>{this.pending-=1});return{out:[],refused:null,deferred:a}}decide(e,t,r,s,i){let o=this.ledgers.ledger(t.h),a=ae(e.s),c=o.disposition(a,i,s);switch(c.kind){case"exhausted":return this.refuse("act-sequence-exhausted",[this.no(r,t.h,"capacity",e.q)]);case"conflict":return this.refuse("act-binding-mismatch",[this.no(r,t.h,"invalid-data",e.q)]);case"expired":return this.refuse("act-result-expired",[this.no(r,t.h,"result-expired",e.q)]);case"replay":return this.permitsAction(r,e.name,e.in)?(this.renew(t,s),this.accept([this.reply(t,r,e.q,a,c.outcome)])):this.refuse("act-forbidden-replay",[this.no(r,t.h,"forbidden",e.q)]);case"execute":break}if(!this.permitsAction(r,e.name,e.in))return o.retain(a,i,{kind:"refusal",code:"forbidden"},s),this.renew(t,s),this.refuse("act-forbidden",[this.no(r,t.h,"forbidden",e.q)]);let l=this.deps.definition.actions[e.name],d=this.core.getState();this.revisionBeforeCommit=this.core.revision;let u;try{let y=this.deps.actions[e.name];u={kind:"result",out:this.core.transact(A=>{let k=l.input(e.in),I=l.output(y(k,A)),M=P({k:"res",q:e.q,h:t.h,s:e.s,out:I});if(N(M)>this.deps.maxEventBytes)throw new f("capacity","the result does not fit the message budget");return I},r)}}catch(y){u={kind:"refusal",code:y instanceof f&&y.code==="capacity"?"capacity":"action-rejected"}}o.retain(a,i,u,s),this.renew(t,s);let p=this.core.getState(),h=Object.is(d,p)?[]:this.propagate(d,p);return this.accept([this.reply(t,r,e.q,a,u),...h])}input(e,t,r,s){let i=e.name;if(!Object.prototype.hasOwnProperty.call(this.deps.definition.inputs,i))return this.refuse("in-unknown-name");if(!this.ledgers.inputs(t.h).admit(i,ae(e.s)))return this.refuse("in-stale-sequence");if(!this.permitsInput(r,i,e.in))return this.refuse("in-forbidden");let o=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(c=>{let l=this.deps.definition.inputs[i],d=this.deps.inputs[i];d(l(e.in),c)},r)}catch{return this.refuse("in-rejected")}this.renew(t,s);let a=this.core.getState();return this.accept(Object.is(o,a)?[]:this.propagate(o,a))}reply(e,t,r,s,i){let o=i.kind==="result"?P({k:"res",q:r,h:e.h,s:s.toString(),out:i.out}):P({k:"no",q:r,h:e.h,code:i.code,s:s.toString()});return{peer:t,h:e.h,frame:o}}permitsAction(e,t,r){let s={type:"action",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}permitsInput(e,t,r){let s={type:"input",peer:e,name:t,input:r};try{return this.deps.authorize(s)===!0}catch{return!1}}renew(e,t){let r=this.handles.get(e.h);r!==void 0&&this.handles.set(e.h,{...r,lastSeen:t})}forget(e,t="dropped"){let r=this.handles.get(e);this.handles.delete(e),this.ledgers.forget(e),this.deferred.delete(e),r!==void 0&&(this.presenceChanged(r.peer,t),this.membershipChanged())}present=new Set;localPlayers=new Set;pendingEvents=[];areas=new Map;areasAt=-1;ending=!1;get wantsEvents(){return this.deps.onEvent!==void 0||this.deps.areaOf!==void 0}isPresent(e){if(this.localPlayers.has(e))return!0;for(let t of this.handles.values())if(t.peer===e)return!0;return!1}presenceChanged(e,t,r=[]){if(!this.wantsEvents||this.ending)return;let s=this.isPresent(e),i=this.present.has(e);s!==i&&(s?(this.present.add(e),this.pendingEvents.push(Object.freeze({type:"join",peer:e,audience:Object.freeze([...r])}))):(this.present.delete(e),this.areas.delete(e),this.pendingEvents.push(Object.freeze({type:"leave",peer:e,reason:t??"dropped"}))))}localPresence(e,t,r=[],s="left"){t?this.localPlayers.add(e):this.localPlayers.delete(e),this.presenceChanged(e,t?null:s,r)}detectAreas(){let e=this.deps.areaOf;if(e===void 0||this.ending||this.areasAt===this.core.revision&&[...this.present].every(r=>this.areas.has(r)))return;this.areasAt=this.core.revision;let t=this.core.getState();for(let r of this.present){let s;try{let a=this.core.runReadOnly(()=>e(t,r));s=typeof a=="string"?a:null}catch{s=null}let i=this.areas.has(r),o=i?this.areas.get(r)??null:null;this.areas.set(r,s),(i?o!==s:s!==null)&&this.pendingEvents.push(Object.freeze({type:"area",peer:r,from:o,to:s}))}}drainEvents(){let e=[];if(!this.wantsEvents)return this.accept(e);for(let t=0;;t+=1){this.pendingEvents.length===0&&this.detectAreas();let r=this.pendingEvents.shift();if(r===void 0)break;if(t>=Es){this.pendingEvents.length=0,this.counters["event-rounds-bound"]=(this.counters["event-rounds-bound"]??0)+1;break}let s=this.deps.onEvent;if(s===void 0)continue;let i=this.core.getState();this.revisionBeforeCommit=this.core.revision;try{this.core.transact(a=>s(r,a),r.peer)}catch{this.counters["event-rejected"]=(this.counters["event-rejected"]??0)+1;continue}let o=this.core.getState();Object.is(i,o)||e.push(...this.propagate(i,o))}return this.accept(e)}membership=new Set;membershipChanged(){for(let e of[...this.membership])try{e()}catch{}}onMembership(e){return this.membership.add(e),()=>{this.membership.delete(e)}}peers(){return[...new Set([...this.handles.values()].map(e=>e.peer))]}reauthorize(){let e=[];for(let t of[...this.handles.values()])this.permitsRead(t.peer,t.audience,t.key)||(this.forget(t.h,"refused"),e.push(this.no(t.peer,t.h,"closed",null)));return this.accept(e)}resumeDeferred(e=this.deps.now()){if(!this.deps.canProject())return this.accept([]);let t=[];for(let[r,s]of[...this.deferred]){this.deferred.delete(r);let i=this.bind(r,s.peer,e);if(typeof i=="string"){this.counters[`deferred-${i}`]=(this.counters[`deferred-${i}`]??0)+1;continue}let o=this.install(i,s.q);if(o===null){this.forget(r),t.push(this.no(s.peer,r,"capacity",s.q));continue}t.push(...o)}return this.accept(t)}get deferredCount(){return this.deferred.size}get ledgerCount(){return this.ledgers.size}accept(e,t=null){return{out:e,refused:null,deferred:t}}sweep(e){let t=[];for(let[r,s]of[...this.handles])e-s.lastSeen>=Jn&&(this.forget(r,"expired"),t.push({h:r,peer:s.peer}));return t}farewell(){this.ending=!0,this.pendingEvents.length=0;let e=[];for(let[t,r]of[...this.handles])this.forget(t),e.push(this.no(r.peer,t,"owner-lost",null));return e}get incarnationHex(){return this.incarnation}join(e,t,r){if(e.store!==this.deps.store)return this.refuse("join-other-store",[]);if(e.def!==this.deps.definition.id)return this.refuse("join-wrong-definition",[this.no(t,null,"version-mismatch",e.q)]);if(e.ver!==this.deps.definition.version)return this.refuse("join-wrong-version",[this.no(t,null,"version-mismatch",e.q)]);if(this.handles.size>=xs)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);let s=0;for(let c of this.handles.values())c.peer===t&&(s+=1);if(s>=po)return this.refuse("join-capacity",[this.no(t,null,"capacity",e.q)]);if(!this.permitsRead(t,e.aud,e.key))return this.refuse("join-forbidden",[this.no(t,null,"forbidden",e.q)]);let i=this.newHandle();if(i===null||i.length!==Y||this.handles.has(i))return this.refuse("join-handle-unusable",[this.no(t,null,"owner-lost",e.q)]);let o={h:i,inc:this.incarnation,peer:t,audience:[...e.aud],key:e.key,interest:e.int===void 0?null:[...e.int],generation:0,revision:this.core.revision,lastSeen:r};this.handles.set(i,o);let a=this.install(o,e.q);return a===null?(this.forget(i),this.refuse("join-projection-capacity",[this.no(t,null,"capacity",e.q)])):(this.presenceChanged(t,null,e.aud),this.membershipChanged(),this.accept(a))}install(e,t){let r=this.project(e.peer,e.audience),s=r===null?null:this.filterInterest(r,e.interest);if(s===null)return null;let i;try{i=Mn(s,this.chunkBytes)}catch{return null}let o=e.generation+1;this.handles.set(e.h,{...e,generation:o,revision:this.core.revision});let a=String(o),c=String(this.core.revision),l=[{peer:e.peer,h:e.h,frame:P(t===null?{k:"man",h:e.h,inc:e.inc,g:a,r:c,n:i.n,bytes:String(i.bytes)}:{k:"man",q:t,h:e.h,inc:e.inc,g:a,r:c,n:i.n,bytes:String(i.bytes)})}];for(let d=0;d<i.n;d+=1)l.push({peer:e.peer,h:e.h,frame:P({k:"snap",h:e.h,g:a,r:c,i:d,n:i.n,d:i.pieces[d]})});return l}permitsRead(e,t,r){let s=r===void 0?{type:"read",peer:e,audience:[...t]}:{type:"read",peer:e,audience:[...t],key:r};try{return this.deps.authorize(s)===!0}catch{return!1}}newHandle(){try{return this.deps.newHandle()}catch{return null}}get interestFns(){return this.#e??=Object.entries(this.deps.definition.interest??{}).map(([e,t])=>[e,t]),this.#e}#e;interestKey(e,t,r){try{let s=this.core.runReadOnly(()=>e(t,r));return typeof s=="string"?s:null}catch{return null}}filterInterest(e,t){if(t===null||this.interestFns.length===0)return e;let r=new Set(t),s={...e};for(let[i,o]of this.interestFns){let a=s[i];if(!ve(a))continue;let c={};for(let[l,d]of Object.entries(a)){let u=this.interestKey(o,d,l);(u===null||r.has(u))&&(c[l]=d)}s[i]=c}return s}entityDelta(e,t){if(this.deps.project!==void 0||this.deps.projectFor!==void 0)return null;let r=this.deps.definition.entities;if(r===void 0)return null;let s=new Set(this.interestFns.map(([c])=>c)),i=e,o=t,a=[];for(let c of new Set([...Object.keys(i),...Object.keys(o)])){let l=Object.prototype.hasOwnProperty.call(i,c)?i[c]:void 0,d=Object.prototype.hasOwnProperty.call(o,c)?o[c]:void 0;if(Object.is(l,d))continue;if(!s.has(c)||!Object.prototype.hasOwnProperty.call(r,c)||!ve(l)||!ve(d))return null;let u=[];for(let p of new Set([...Object.keys(l),...Object.keys(d)])){let h=Object.prototype.hasOwnProperty.call(l,p)?l[p]:void 0,y=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0;Object.is(h,y)||u.push(p)}a.push({collection:c,ids:u,before:l,after:d})}return{collections:a}}sparseInterestDiff(e,t,r){let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=(h,y,m)=>{Object.defineProperty(h,y,{value:m,enumerable:!0,writable:!0,configurable:!0})},o={},a={};for(let{collection:h,ids:y,before:m,after:A}of r.collections){let k={},I={};for(let M of y)Object.prototype.hasOwnProperty.call(m,M)&&i(k,M,m[M]),Object.prototype.hasOwnProperty.call(A,M)&&i(I,M,A[M]);i(o,h,k),i(a,h,I)}let c=this.visibility===null?o:Ae(this.visibility,o,s),l=this.visibility===null?a:Ae(this.visibility,a,s),d=new Map(this.interestFns),u=this.deps.definition.entities,p=[];for(let{collection:h,ids:y}of r.collections){let m=c[h],A=l[h];if(!ve(m)||!ve(A))return;let k=u[h],I=d.get(h),M=(E,_)=>{if(E===void 0||!_)return{ok:!0,value:E};try{return{ok:!0,value:this.core.runReadOnly(()=>k(E))}}catch{return{ok:!1,value:void 0}}};for(let E of y){let _=M(Object.prototype.hasOwnProperty.call(m,E)?m[E]:void 0,c!==o),C=M(Object.prototype.hasOwnProperty.call(A,E)?A[E]:void 0,l!==a);if(!_.ok||!C.ok)return;Object.is(_.value,C.value)||_.value!==void 0&&C.value!==void 0&&JSON.stringify(_.value)===JSON.stringify(C.value)||p.push({collection:h,id:E,before:_.value,after:C.value,beforeKey:_.value===void 0?null:this.interestKey(I,_.value,E),afterKey:C.value===void 0?null:this.interestKey(I,C.value,E)})}}return{rest:[],entities:p,whole:[]}}interestDiff(e,t){let r=new Set(this.interestFns.map(([c])=>c)),s=c=>{let l={};for(let[d,u]of Object.entries(c))r.has(d)||(l[d]=u);return l},i=ws(s(e),s(t)),o=[],a=[];for(let[c,l]of this.interestFns){let d=e[c],u=t[c];if(!ve(d)||!ve(u)){JSON.stringify(d)!==JSON.stringify(u)&&a.push({collection:c,after:u});continue}for(let p of new Set([...Object.keys(d),...Object.keys(u)])){let h=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0,y=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0;Object.is(h,y)||h!==void 0&&y!==void 0&&JSON.stringify(h)===JSON.stringify(y)||o.push({collection:c,id:p,before:h,after:y,beforeKey:h===void 0?null:this.interestKey(l,h,p),afterKey:y===void 0?null:this.interestKey(l,y,p)})}}return{rest:i,entities:o,whole:a}}interestOps(e,t){let r=new Set(t),s=o=>o===null||r.has(o),i=[...e.rest];for(let o of e.entities){let a=o.before!==void 0&&s(o.beforeKey);o.after!==void 0&&s(o.afterKey)?i.push({o:"r",p:[o.collection,o.id],val:o.after}):a&&i.push({o:"x",p:[o.collection,o.id]})}for(let o of e.whole){let a=this.filterInterest({[o.collection]:o.after},t);i.push({o:"r",p:[o.collection],val:a[o.collection]})}return i}interestChange(e,t,r,s){let i={...t,interest:[...e.int],lastSeen:s};this.handles.set(i.h,i);let o={peer:r,h:t.h,frame:P({k:"ok",q:e.q,h:t.h})};if(this.interestFns.length===0||this.deferred.has(t.h))return this.accept([o]);let a=this.project(r,t.audience);if(a===null)return this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)]);let c=this.filterInterest(a,t.interest),l=this.filterInterest(a,i.interest),d=[];for(let[y]of this.interestFns){let m=c[y],A=l[y];if(!(!ve(m)||!ve(A))){for(let k of Object.keys(A))Object.prototype.hasOwnProperty.call(m,k)||d.push({o:"r",p:[y,k],val:A[k]});for(let k of Object.keys(m))Object.prototype.hasOwnProperty.call(A,k)||d.push({o:"x",p:[y,k]})}}if(d.length===0)return this.accept([o]);let u=String(this.core.revision),p=t.revision===this.core.revision?vs({k:"delta",h:t.h,g:String(t.generation),base:u,r:u,ops:d},this.deps.maxEventBytes):null;if(p!==null)return this.accept([{peer:r,h:t.h,frame:p},o]);let h=this.install(i,null);return h===null?(this.forget(t.h),this.refuse("int-projection-capacity",[this.no(r,t.h,"capacity",e.q)])):this.accept([...h,o])}project(e,t,r=this.core.getState()){try{let s=Object.freeze({peer:e,audience:Object.freeze([...t])}),i=this.deps.projectFor!==void 0?this.deps.projectFor(r,s):this.deps.project!==void 0?this.deps.project(r,t):r;this.visibility===null&&i===r&&this.warnOnce(`store '${this.deps.definition.id}': every player receives the full state. Declare \`visibility: 'open'\` on the definition if that is intended, or rules for what is secret.`);let o=this.visibility===null?i:Ae(this.visibility,i,s);if(o===r)return r;try{return this.deps.definition.state(o)}catch(a){throw this.warnOnce(`store '${this.deps.definition.id}': a projection failed the state validator, so the player got empty() \u2014 ${a instanceof Error?a.message:String(a)}`+(this.visibility===null?"":" (a hidden field is the HIDDEN marker: wrap its parser with hiddenOr)")),a}}catch{try{return this.deps.definition.empty()}catch{return null}}}bind(e,t,r){let s=this.handles.get(e);return s===void 0?"handle-unknown":r-s.lastSeen>=Jn?(this.forget(e,"expired"),"handle-expired"):s.peer!==t?"handle-foreign-peer":s}no(e,t,r,s){return{peer:e,h:t,frame:P(s===null?{k:"no",h:t,code:r}:t===null?{k:"no",q:s,code:r}:{k:"no",q:s,h:t,code:r})}}refuse(e,t=[]){return this.counters[e]=(this.counters[e]??0)+1,{out:t,refused:e,deferred:null}}};function ws(n,e){let t=[];for(let r of Object.keys(e)){let s=e[r];if(Object.prototype.hasOwnProperty.call(n,r)&&Object.is(n[r],s))continue;let i=Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0,o=i===void 0?null:go(r,i,s);if(o!==null){t.push(...o);continue}i!==void 0&&JSON.stringify(i)===JSON.stringify(s)||t.push({o:"r",p:[r],val:s})}for(let r of Object.keys(n))Object.prototype.hasOwnProperty.call(e,r)||t.push({o:"x",p:[r]});return t}var yo=128;function go(n,e,t){let r=a=>typeof a=="object"&&a!==null&&!Array.isArray(a);if(!r(e)||!r(t))return null;let s=[],i=Math.min(yo,Math.max(1,Math.floor(Object.keys(t).length/2))),o=a=>N(a)<=Ke&&!["__proto__","constructor","prototype"].includes(a);for(let a of Object.keys(t)){let c=t[a];if(!(Object.prototype.hasOwnProperty.call(e,a)&&(Object.is(e[a],c)||JSON.stringify(e[a])===JSON.stringify(c)))&&(!o(a)||(s.push({o:"r",p:[n,a],val:c}),s.length>i)))return null}for(let a of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,a)&&(!o(a)||(s.push({o:"x",p:[n,a]}),s.length>i)))return null;return s}function vs(n,e){let t;try{t=P(n)}catch{return null}return N(t)<=e?t:null}function mo(n){return"q"in n&&typeof n.q=="string"?n.q:null}var Rs=5e3,Kn=500;function ut(n){let e=/^\d+$/.test(n),t=/^(0x)?[0-9a-f]{1,16}$/i.test(n),r;try{if(e)r=BigInt(n).toString(16).padStart(16,"0");else if(t)r=BigInt(n.startsWith("0x")?n:`0x${n}`).toString(16).padStart(16,"0");else return null}catch{return null}return r.length===16?r:null}function Be(n){return/^[0-9a-f]{16}$/i.test(n)?n.toLowerCase():ut(n)}var Vn=new WeakMap,tn=new WeakMap;function bo(n){try{let e=JSON.parse(n);return e!==null&&typeof e=="object"&&e.k!=="join"&&typeof e.h=="string"?e.h:null}catch{return null}}var _s=new WeakMap;function pt(n){return _s.get(n)}function ks(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var As=new TextEncoder,So=new TextDecoder;function Xn(n){let e=n.streamId??`store/${n.definition.id}`,t=n.store??n.definition.id,r=Vn.get(n.transport)??new Set;if(r.has(t))throw new f("invalid-data",`a store named ${t} is already hosted on this transport: name each store of one definition, or a join for that name is ambiguous`);r.add(t),Vn.set(n.transport,r);let s=new dt({definition:n.definition,store:t,authorize:n.authorize,project:n.project,projectFor:n.projectFor,onEvent:n.onEvent,areaOf:n.areaOf,warn:n.dev===!0?w=>console.warn(`[@net-mesh/browser] ${w}`):typeof n.dev=="function"?n.dev:void 0,actions:n.actions,inputs:n.inputs,maxEventBytes:n.maxEventBytes,now:n.now??(()=>Date.now()),newHandle:n.newHandle??(()=>ks(16)),newIncarnation:n.newIncarnation??(()=>ks(8)),canProject:n.canProject??(()=>!0)});if(n.definition.visibility!==void 0){let w=Ae(ke(n.definition.visibility),n.initialState,null);try{n.definition.state(w)}catch(R){throw new f("invalid-data",`store '${n.definition.id}': the state validator rejects a view with secrets hidden \u2014 wrap each field a rule hides with hiddenOr(\u2026): ${R instanceof Error?R.message:String(R)}`,{cause:R})}}s.commit(n.initialState);let i=new Map,o=null,a=new Map,c={},l=!1,d=null;async function u(w){let R=i.get(w);if(R!==void 0)return R;let j=a.get(w);if(j!==void 0)return j;let K=Promise.resolve(n.transport.openStream({reliability:"reliable",peer:w,label:e})).then(V=>{if(a.delete(w),l){try{V.close()}catch{}throw new f("closed","the store closed while its stream was opening")}return i.set(w,V),V}).catch(V=>{throw a.delete(w),V});return a.set(w,K),K}async function p(w){for(let R of w){if(l)return;let j=As.encode(R.frame),U=await u(R.peer);try{await U.send(j)}catch(K){if(l)return;if(!at(K))throw K;if(i.get(R.peer)===U){i.delete(R.peer),a.delete(R.peer),c["reopened-stream"]=(c["reopened-stream"]??0)+1;try{U.close()}catch{}}await(await u(R.peer)).send(j)}}}function h(w){w.catch(()=>{c["send-failed"]=(c["send-failed"]??0)+1})}function y(w){h(p(w.out)),w.deferred!==null&&h(w.deferred.then(R=>y(R))),A()}let m=!1;function A(){if(!(m||l)){m=!0;try{let w=s.drainEvents();w.out.length>0&&h(p(w.out))}finally{m=!1}}}let k=tn.get(n.transport)??new Set;k.add(s),tn.set(n.transport,k);let I=n.transport.onEvent(w=>{if(w.type!=="stream_data")return;let R=w.peerNode;if(typeof R!="string"||R.length===0){c["no-authenticated-peer"]=(c["no-authenticated-peer"]??0)+1;return}let j=w.payload;if(j===void 0){c["no-payload"]=(c["no-payload"]??0)+1;return}let U=w.streamId;if(o!==null&&U!==void 0&&U!==o){c["foreign-stream"]=(c["foreign-stream"]??0)+1;return}let K;try{K=So.decode(j)}catch{c["undecodable-frame"]=(c["undecodable-frame"]??0)+1;return}let V=ut(R);if(V===null){c["unusable-peer"]=(c["unusable-peer"]??0)+1;return}let B=tn.get(n.transport);if(B!==void 0&&B.size>1){let b=bo(K);if(b!==null&&s.handle(b)===void 0){let x=!1;for(let v of B)v!==s&&v.handle(b)!==void 0&&(x=!0);if(x||B.values().next().value!==s){c["sibling-handle"]=(c["sibling-handle"]??0)+1;return}}}let g=s.receive(K,V);U!==void 0&&o===null&&g.refused===null&&(o=U),y(g)}),M=n.schedule??((w,R)=>{let j=setInterval(w,R);return()=>{clearInterval(j)}}),E=M(()=>{if(l)return;let w=(n.now??(()=>Date.now()))(),R=s.sweep(w);R.length>0&&h(p(R.filter(j=>i.has(j.peer)).map(j=>({peer:j.peer,h:j.h,frame:P({k:"no",h:j.h,code:"closed"})})))),y(s.resumeDeferred(w))},Rs);async function _(){l=!0,E(),I();let w=s.farewell();await Promise.all(w.map(async R=>{let j=i.get(R.peer);if(j===void 0){c["farewell-unreachable"]=(c["farewell-unreachable"]??0)+1;return}try{await C(Promise.resolve(j.send(As.encode(R.frame))))}catch{c["farewell-failed"]=(c["farewell-failed"]??0)+1}}));for(let R of i.values())try{R.close()}catch{c["stream-close-failed"]=(c["stream-close-failed"]??0)+1}i.clear(),a.clear(),Vn.get(n.transport)?.delete(t),tn.get(n.transport)?.delete(s)}function C(w){return new Promise((R,j)=>{let U=()=>{B(),j(new f("timeout","the farewell did not flush before the deadline"))},K=M(U,Kn),V=setTimeout(U,Kn),B=()=>{K(),clearTimeout(V)};w.then(()=>{B(),R()},g=>{B(),j(g instanceof Error?g:new Error(String(g)))})})}let W=n.transport.nodeIdHex()??s.incarnationHex,Q=new Set,le={authority:W,definition:n.definition,getState:()=>s.getState(),subscribe:w=>s.subscribe(w),setState:w=>{y(s.commit(w))},setEntities:(w,R)=>{y(s.commitEntities(w,R))},setEntity:(w,R,j)=>{let U={};Object.defineProperty(U,R,{value:j,enumerable:!0,writable:!0,configurable:!0}),y(s.commitEntities(w,U))},counts:()=>({handles:s.handleCount,ledgers:s.ledgerCount,deferred:s.deferredCount,sparseViews:s.sparseViews}),counters:()=>({...s.snapshotCounters(),...c}),close:()=>{if(d===null){d=_();for(let w of[...Q])w();Q.clear()}return d}};return _s.set(le,{owner:s,peer:Be(W)??W,maxEventBytes:n.maxEventBytes,dispatched:y,isClosed:()=>l,onClose:w=>{Q.add(w)}}),le}var Ps=3,ft=class{constructor(e){this.deps=e;this.#d=[...e.audience],this.#l=e.interest===void 0?null:[...e.interest]}deps;#e="joining";#t=null;#r=null;#n=null;#s=null;#g=null;#o=0n;#a=null;#u=!1;#c=null;#f=null;#b=0;#h=0;#p=null;#d;#y=0;#O=new lt;#w={};#l;get interest(){return this.#l===null?null:[...this.#l]}set interest(e){this.#l=e===null?null:[...e]}get desired(){return[...this.#d]}get waiters(){return this.#y}get state(){return this.#e}get handle(){return this.#t}get installed(){return this.#n===null?null:this.#n.toString()}get revision(){return this.#s===null?null:this.#s.toString()}get retired(){return this.#o.toString()}get skipped(){return this.#a===null?null:this.#a.toString()}get dropped(){return{...this.#w}}join(){if(this.#e==="closed")throw new f("closed","a closed replica cannot join again");this.#h+=1,this.#y=1,this.#k();let e=this.deps.newQ();return this.#c=e,this.#f=this.deps.now(),this.#b=0,this.#e="joining",this.deps.core.setStatus({phase:"connecting",stale:this.#v()}),{kind:"join",q:e,frame:P({k:"join",q:e,def:this.deps.definition.id,store:this.deps.store,ver:this.deps.definition.version,key:this.deps.key,aud:[...this.#d],...this.#l===null?{}:{int:[...this.#l]}})}}setAudience(e){if(this.#e==="closed")throw new f("closed","a closed replica cannot change audience");this.#h+=1;let t=[...e];if(this.#e==="installing"&&vo(t,this.#d))return this.#y+=1,[];this.#d=t;let r=this.#t;if(this.#m(),this.#n=null,this.#s=null,this.#a=null,this.#u=!1,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:"syncing",stale:!1,error:null}),r===null)return this.#y=1,[this.join()];let s=this.deps.newQ();return this.#c=s,this.#f=this.deps.now(),this.#y=1,this.#e="installing",[{kind:"aud",q:s,frame:P({k:"aud",q:s,h:r,aud:t})}]}reconnect(){if(this.#e==="closed")throw new f("closed","a closed replica cannot reconnect");this.#h+=1;let e=this.#t;if(this.#m(),e===null)return[this.join()];let t=this.deps.newQ();return this.#c=t,this.#e="installing",this.deps.core.setStatus({phase:"reconnecting",stale:this.#v()}),[{kind:"resume",q:t,frame:P({k:"resume",q:t,h:e,aud:[...this.#d],...this.#l===null?{}:{int:[...this.#l]}})}]}cancelWaiter(){this.#y>0&&(this.#y-=1),!(this.#y>0)&&this.#e==="installing"&&this.cancel()}receive(e){if(this.#e==="closed")return this.#i("closed");let t=_e(e,{maxBytes:this.deps.maxEventBytes,as:"replica"});if(!t.ok)return this.#i(t.reason);let r=t.message;if("h"in r&&r.h!==void 0&&this.#t!==null&&r.h!==this.#t)return this.#i("foreign-handle");switch(r.k){case"man":return this.#A(r);case"snap":return this.#R(r);case"delta":return this.#P(r);case"no":return this.#I(r.code,r.q);case"ok":case"res":return this.#i("unimplemented-kind")}}tick(){let e=this.deps.now();if(this.#e==="installing"&&this.#p!==null)return this.#p.expired(e)?this.#E("assembly-deadline"):[];if(this.#f===null||e-this.#f<Gt)return[];if(this.#e!=="joining"&&this.#e!=="installing")return[];if(this.#b>=Ps)return this.#f=null,this.#e="fenced",this.#c=null,this.#m(),this.#S("failed",new f("timeout",`no store named ${this.deps.store} answered the join`)),[];let t=this.#b,r=this.join();return this.#b=t+1,[r]}cancel(){this.#e!=="closed"&&(this.#h+=1,this.#m(),this.#c=null,this.#e="fenced",this.#a=null,this.#u=!1,this.#S("failed"))}#A(e){let t=ae(e.g),r=e.q!==void 0&&e.q===this.#c;if(e.q!==void 0&&!r)return this.#i("stale-correlation");if(t<=this.#o)return this.#i("stale-generation");if(r){if(this.#e!=="joining"&&this.#e!=="installing"&&this.#e!=="fenced")return this.#i("unexpected-manifest")}else{if(this.#e==="fenced")return this.#i("fenced");if(this.#e!=="ready")return this.#a=this.#a===null?t:wo(this.#a,t),this.#i("mid-transition")}if(this.#t===null)this.#t=e.h,this.#r=e.inc;else if(this.#r!==null&&e.inc!==this.#r)return this.#i("foreign-incarnation");this.#m(),this.#o=t;let s={h:e.h,g:e.g,r:e.r,n:e.n,bytes:e.bytes},i=this.#O.open(s,this.deps.now());return"accept"in i?(this.#g=t,this.#p=i,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),{out:[],dropped:null}):{out:this.#E(i.reason),dropped:i.reason}}#R(e){let t=this.#p;if(t===null)return this.#i("no-open-assembly");let r=this.#h,s=t.accept({h:e.h,g:e.g,r:e.r,n:e.n,i:e.i,d:e.d},i=>this.deps.definition.state(i),this.deps.now());return this.#h!==r?this.#i("superseded-installation"):s.ok?s.done?this.#_(s.document,e.g,e.r,r):{out:[],dropped:null}:s.fatal?{out:this.#E(s.reason),dropped:s.reason}:this.#i(s.reason)}#_(e,t,r,s){return this.deps.core.applySnapshot(e),this.#g=null,this.#p=null,this.#O.reclaim(this.#t,t),this.#h!==s?(this.#n=null,this.#s=null,this.#S("failed"),this.#i("superseded-installation")):(this.#n=ae(t),this.#s=ae(r),this.#c=null,this.#e="ready",this.deps.core.setStatus({phase:"ready",stale:!1,error:null}),{out:this.#C(),dropped:null})}#P(e){if(this.#e!=="ready")return this.#u=!0,this.#i("not-ready");let t=ae(e.g),r=this.#n;if(r===null||t!==r)return r!==null&&t>r?{out:this.#x("generation-ahead"),dropped:"generation-ahead"}:this.#i("stale-generation");if(this.#s===null||ae(e.base)!==this.#s)return{out:this.#x("gap"),dropped:"gap"};let s=this.deps.core.applyDelta(e.ops);return s.ok?(this.#s=ae(e.r),{out:[],dropped:null}):{out:this.#x(s.reason),dropped:s.reason}}#I(e,t){if(e==="owner-lost")return this.#m(),this.#e="closed",this.#t=null,this.#S("closed"),{out:[],dropped:"owner-lost"};if(e==="closed"){let r=this.#e==="fenced";return this.#k(),r?(this.#S("failed"),{out:[],dropped:"closed-while-fenced"}):(this.#S("connecting"),{out:[this.join()],dropped:"closed"})}return t===void 0||t!==this.#c?this.#i("stale-correlation"):(this.#m(),this.#c=null,this.#e="fenced",this.#S("failed",new f(e,`the request was refused: ${e}`)),{out:[],dropped:`refused-${e}`})}#E(e){return this.#m(),this.#g=null,this.#e="installing",this.deps.core.setStatus({phase:"syncing",stale:this.#v()}),this.#x(e)}#x(e){let t=this.#t;if(t===null)return[];let r=this.deps.newQ();return this.#c=r,this.#f=this.deps.now(),this.#e="installing",this.#a=null,this.#u=!1,this.deps.core.setStatus({phase:this.#v()?"reconnecting":"syncing",stale:this.#v()}),[{kind:"resync",q:r,frame:P({k:"resync",q:r,h:t,g:this.#n===null?"0":this.#n.toString(),have:this.#s===null?"0":this.#s.toString()})}]}#C(){let e=this.#a,t=this.#u;return!t&&(e===null||this.#n===null||e<=this.#n)?(this.#a=null,this.#u=!1,[]):this.#x(t?"behind":"skipped-refresh")}#k(){this.#m(),this.#t=null,this.#r=null,this.#n=null,this.#s=null,this.#o=0n,this.#a=null,this.#u=!1,this.#c=null}#m(){this.#p!==null&&(this.#p.reclaim(),this.#p=null),this.#t!==null&&this.#O.reclaimHandle(this.#t),this.#g=null}#v(){return this.#n!==null}#S(e,t=null){this.#n=null,this.#s=null,this.deps.core.applySnapshot(this.deps.definition.empty()),this.deps.core.setStatus({phase:e,stale:!1,error:t})}#i(e){return this.#w[e]=(this.#w[e]??0)+1,{out:[],dropped:e}}};function wo(n,e){return n>e?n:e}function vo(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Cs=2e4,Gn=1e4,js=6e4,Hs=1e3,zn=64,Is=new TextEncoder,Oo=new TextDecoder;function ht(n){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}function Yn(n){let e=n.transport.nodeIdHex(),t=Be(n.host);if(e!==null&&t!==null&&Be(e)===t)throw new f("invalid-data","a replica cannot join the node it runs on: hold the hostStore handle instead");let r=n.streamId??`store/${n.definition.id}`,s=n.now??(()=>Date.now()),i=n.schedule??((g,b)=>{let x=setInterval(g,b);return()=>{clearInterval(x)}}),o=new we({definition:n.definition,initialState:n.definition.empty()}),a=new ft({definition:n.definition,core:o,maxEventBytes:n.maxEventBytes,now:s,newQ:()=>(n.newQ??(()=>ht(8)))(),audience:n.audience,store:n.store??n.definition.id,key:n.key,...n.interest===void 0?{}:{interest:n.interest}}),c=new Map,l=new Map,d=0n,u=!1,p=null,h=null,y=0,m=[],A=null;async function k(){if(p!==null)return p;if(h!==null)return h;if(t===null)return Promise.reject(new f("invalid-data",`the host id is not a node id: ${n.host}`));let g=y;return h=Promise.resolve(n.transport.connectPeer?.(t)).catch(()=>{}).then(()=>n.transport.openStream({reliability:"reliable",peer:t,label:r})).then(b=>{if(g!==y){try{b.close()}catch{}throw new f("aborted","the stream open was superseded by reconnect()")}if(h=null,u){try{b.close()}catch{}throw new f("closed","the store closed while its stream was opening")}return p=b,b}).catch(b=>{throw g===y&&(h=null),b}),h}async function I(g){for(let b of g){if(u)return;let x=Is.encode(b),v=await k();try{await v.send(x)}catch(H){if(u)return;if(!at(H))throw H;if(p===v){p=null,h=null;try{v.close()}catch{}}await(await k()).send(x)}}}function M(g){let b=g instanceof f?g:new f("indeterminate",`the transport could not carry a store frame: ${String(g)}`);for(let x of m.splice(0,m.length))x.reject(b);W(b);for(let[x,v]of[...c])c.delete(x),v.reject(b)}function E(g){I(g).catch(M)}let _=g=>g.map(b=>b.frame);function C(g){if(a.state==="ready"){W(null);for(let x of m.splice(0,m.length))x.resolve();return}if(a.state!=="fenced"&&a.state!=="closed")return;let b=g??new f(a.state==="closed"?"owner-lost":"aborted",`the store handle is ${a.state}`);W(b);for(let x of m.splice(0,m.length))x.reject(b)}function W(g){let b=A;if(b!==null){A=null,b.q!==null&&c.delete(b.q);for(let x of[...b.calls])b.calls.delete(x),g===null?x.resolve():x.reject(g)}}function Q(g){return W(new f("aborted","a newer transition superseded this one before it installed")),A={q:g,calls:new Set},g===null?null:c.size>=zn?new f("capacity","too many requests are already outstanding"):(c.set(g,{resolve:()=>W(null),reject:b=>W(b),at:s(),transition:!0}),null)}function le(){return new Promise((g,b)=>{let x={resolve:g,reject:b,deadlineAt:s()+js},v=A??{q:null,calls:new Set};A=v,v.calls.add(x)})}let w=n.transport.onEvent(g=>{if(u||g.type!=="stream_data"||typeof g.peerNode!="string"||t===null||ut(g.peerNode)!==t)return;let b=g.payload;if(b===void 0)return;let x=Oo.decode(b),v=_e(x,{maxBytes:n.maxEventBytes,as:"replica"});if(v.ok&&"q"in v.message&&typeof v.message.q=="string"){let Z=c.get(v.message.q);if(Z!==void 0&&(v.message.k==="res"||v.message.k==="ok")){c.delete(v.message.q),Z.resolve(v.message.k==="res"?v.message.out:void 0);return}Z!==void 0&&v.message.k==="no"&&(c.delete(v.message.q),Z.reject(new f(v.message.code,`the store refused: ${v.message.code}`)))}let H=null;v.ok&&v.message.k==="no"&&(H=new f(v.message.code,`the store refused: ${v.message.code}`));let G=a.receive(x);E(_(G.out)),C(H)}),R=i(()=>{if(u)return;let g=a.handle;g!==null&&E([P({k:"alive",q:ht(8),h:g})])},Cs),j=i(()=>{if(u)return;let g=s(),b=A;if(b!==null){for(let x of[...b.calls])g<x.deadlineAt||(b.calls.delete(x),a.cancelWaiter(),x.reject(new f("indeterminate","the transition did not install before its deadline")));b.q!==null&&b.calls.size===0&&W(null)}for(let[x,v]of[...c])v.transition||g-v.at<Gn||(c.delete(x),v.reject(new f("indeterminate","the store did not answer before the deadline")))},Gn),U=i(()=>{u||(E(_(a.tick())),C(o.getStatus().error??null))},Hs),K;try{K=a.join()}catch(g){throw new f("invalid-data","the join request cannot be encoded",{cause:g})}Q(null),E(_([K]));function V(g){return c.size>=zn?Promise.reject(new f("capacity","too many requests are already outstanding")):new Promise((b,x)=>{c.set(g,{resolve:v=>{b(v)},reject:x,at:s(),transition:!1})})}let B={getState:()=>o.getState(),subscribe:g=>o.subscribe(g),getStatus:()=>o.getStatus(),subscribeStatus:g=>o.subscribeStatus(g),ready:()=>new Promise((g,b)=>{if(u){b(new f("closed","this store handle is closed"));return}if(a.state==="ready"){g();return}if(a.state==="closed"){b(new f("owner-lost","the store owner closed this handle"));return}m.push({resolve:g,reject:b})}),act:async(g,b)=>{if(u)throw new f("closed","this store handle is closed");if(a.state==="closed")throw new f("owner-lost","the store owner closed this handle");let x=a.handle;if(x===null)throw new f("not-ready","no handle yet: the join has not been answered");d+=1n;let v=(n.newQ??(()=>ht(8)))(),H;try{H=P({k:"act",q:v,h:x,s:d.toString(),name:g,in:b})}catch(Z){throw new f("invalid-data",`the input for '${g}' cannot be encoded`,{cause:Z})}let G=V(v);return G.catch(()=>{}),await I([H]),await G},input:(g,b)=>{if(u)return{type:"dropped",reason:"not-ready"};let x=a.handle;if(x===null||a.state!=="ready")return{type:"dropped",reason:"not-ready"};let v=(l.get(g)??0n)+1n;l.set(g,v);let H;try{H=P({k:"in",h:x,s:v.toString(),name:g,in:b})}catch(G){throw new f("invalid-data",`the input for '${g}' cannot be encoded`,{cause:G})}return E([H]),{type:v===1n?"queued":"replaced"}},setAudience:async g=>{if(u)throw new f("closed","this store handle is closed");let b;try{b=a.setAudience(g)}catch(H){throw new f("invalid-data","the audience cannot be encoded",{cause:H})}let x=b[0];if(x!==void 0){let H=Q(x.q);if(H!==null)throw H}let v=le();v.catch(()=>{}),x!==void 0&&await I(_(b)),await v},setInterest:async g=>{if(u)throw new f("closed","this store handle is closed");let b=[...g],x="0".repeat(32),v;try{v=P({k:"int",q:"0".repeat(16),h:x,int:b})}catch(ce){throw new f("invalid-data","the interest set cannot be encoded",{cause:ce})}if(N(v)>n.maxEventBytes)throw new f("capacity","the interest set does not fit one message");a.interest=b;let H=a.handle;if(H===null||a.state!=="ready")return await B.ready(),a.interest===null||a.interest.join("\0")!==b.join("\0")?void 0:B.setInterest(b);let G=(n.newQ??(()=>ht(8)))(),Z=V(G);Z.catch(()=>{}),await I([P({k:"int",q:G,h:H,int:b})]),await Z},reconnect:async()=>{if(u)throw new f("closed","this store handle is closed");let g=p;if(p=null,y+=1,h=null,g!==null)try{g.close()}catch{}let b;try{b=a.reconnect()}catch(x){throw new f("invalid-data","the reconnect request cannot be encoded",{cause:x})}b[0]!==void 0&&Q(null),await I(_(b))},close:async()=>{if(u)return;u=!0,R(),j(),U();let g=a.handle;if(g!==null)try{await(await k()).send(Is.encode(P({k:"leave",q:ht(8),h:g})))}catch{}w(),W(new f("aborted","the store handle closed before this request was answered"));for(let b of c.values())b.reject(new f("aborted","the store handle closed before this request was answered"));c.clear();for(let b of m.splice(0,m.length))b.reject(new f("closed","the store handle closed before a view was installed"));p?.close(),p=null,o.close()}};return B}var Ts="0".repeat(16),Qn="0".repeat(32);function Ls(n,e,t){let r;try{r=t==="act"?P({k:"act",q:Ts,h:Qn,s:"1",name:n,in:e}):P({k:"in",h:Qn,s:"1",name:n,in:e})}catch(i){throw new f("invalid-data",`the input for '${n}' cannot be encoded`,{cause:i})}let s=Re(r);if(!s.ok||typeof s.value!="object"||s.value===null||Array.isArray(s.value))throw new f("invalid-data",`the input for '${n}' cannot be encoded`);return s.value.in}function xo(n){let e=Re(JSON.stringify(n));return e.ok?e.value:n}function Zn(n,e){let t=pt(n);if(t===void 0)throw new f("invalid-data","hostPlayer needs a handle returned by hostStore");let{owner:r,peer:s}=t,i=n.definition,o=new we({definition:i,initialState:i.empty(),phase:"syncing"}),a=[...e.audience],c=e.interest===void 0?null:[...e.interest],l=!1,d=!1,u=new Map;function p(E,_){d=!0,_?.code==="forbidden"&&queueMicrotask(()=>A("refused")),o.applySnapshot(i.empty()),o.setStatus({phase:E,stale:!1,error:_})}function h(){if(l||d)return;if(t.isClosed()){p("closed",null);return}if(!r.localRead(s,a)){p("failed",new f("forbidden","the store refused: forbidden"));return}let E=r.localView(s,a,c);if(E===null){p("failed",new f("capacity","the store refused: capacity"));return}o.applySnapshot(E),o.setStatus({phase:"ready",stale:!1,error:null})}let y=r.subscribe(()=>{h()});t.onClose(()=>{y(),!l&&!d&&p("closed",null)}),h();let m=!1;o.getStatus().phase==="ready"&&(m=!0,r.localPresence(s,!0,a),t.dispatched({out:[],refused:null,deferred:null}));function A(E){!m||t.isClosed()||(m=!1,r.localPresence(s,!1,a,E),t.dispatched({out:[],refused:null,deferred:null}))}function k(){return l?new f("closed","this store handle is closed"):t.isClosed()?new f("owner-lost","the store owner closed this handle"):d?o.getStatus().error??new f("owner-lost","the store owner closed this handle"):null}function I(){let E=[...u];if(u.clear(),k()===null)for(let[_,C]of E)t.dispatched(r.localInput(_,C,s))}function M(E,_,C){return _===void 0?o.subscribe(E):o.subscribe(E,_,C)}return{getState:()=>o.getState(),subscribe:M,getStatus:()=>o.getStatus(),subscribeStatus:E=>o.subscribeStatus(E),ready:()=>{let E=o.getStatus();return E.phase==="ready"?Promise.resolve():Promise.reject(E.error??new f(l?"closed":"owner-lost","this store handle is not ready"))},act:async(E,_)=>{let C=k();if(C!==null)throw C;let W=Ls(E,_,"act");await Promise.resolve();let Q=k();if(Q!==null)throw Q;let{outcome:le,dispatched:w}=r.localAct(E,W,s);if(t.dispatched(w),le.kind==="refusal")throw new f(le.code,`the store refused: ${le.code}`);return xo(le.out)},input:(E,_)=>{if(k()!==null||o.getStatus().phase!=="ready")return{type:"dropped",reason:"not-ready"};let C=Ls(E,_,"in"),W=u.size===0,Q=u.has(E);return u.set(E,C),W&&queueMicrotask(I),{type:Q?"replaced":"queued"}},setAudience:async E=>{let _=k();if(_!==null)throw _;try{P({k:"aud",q:Ts,h:Qn,aud:[...E]})}catch(W){throw new f("invalid-data","the audience cannot be encoded",{cause:W})}await Promise.resolve();let C=k();if(C!==null)throw C;if(!r.localRead(s,E))throw new f("forbidden","the store refused: forbidden");a=[...E],h()},setInterest:async E=>{let _=k();if(_!==null)throw _;let C=[...E];await Promise.resolve(),c=C,h()},reconnect:()=>Promise.resolve(),close:()=>(l||(l=!0,A("left"),u.clear(),y(),o.close()),Promise.resolve())}}var ye=class extends Error{constructor(t,r){super(r);this.code=t;this.name="InventoryError"}code},er=64,tr=Object.freeze({});function Eo(){return tr}function Ds(n){if(typeof n!="string"||n.length===0||n.length>er||n==="__proto__")throw new ye("invalid",`an item id is 1-${er} characters, got ${JSON.stringify(n)}`)}function Ms(n){if(!Number.isSafeInteger(n)||n<1)throw new ye("invalid",`a count is a whole number of at least 1, got ${String(n)}`)}function ko(n,e){let t=e?.maxCount;return t===void 0?Number.MAX_SAFE_INTEGER:typeof t=="number"?t:Object.prototype.hasOwnProperty.call(t,n)?t[n]:Number.MAX_SAFE_INTEGER}function nn(n,e){return n===void 0||!Object.prototype.hasOwnProperty.call(n,e)?0:n[e]??0}function Ao(n,e,t=1){return nn(n,e)>=t}function Ns(n,e,t,r){Ds(e),Ms(t);let s=nn(n,e),i=s+t;if(!Number.isSafeInteger(i)||i>ko(e,r))throw new ye("full",`no room for ${String(t)} more ${e}`);if(s===0&&r?.maxKinds!==void 0&&Object.keys(n).length>=r.maxKinds)throw new ye("full",`no room for another kind of item (${String(r.maxKinds)} at most)`);return Object.freeze({...n,[e]:i})}function Ro(n,e,t){Ds(e),Ms(t);let r=nn(n,e);if(r<t)throw new ye("insufficient",`has ${String(r)} ${e}, needs ${String(t)}`);let s={...n};return r===t?delete s[e]:s[e]=r-t,Object.freeze(s)}function _o(n,e){if(typeof n!="object"||n===null||Array.isArray(n))throw new ye("invalid","an inventory is an object of item id \u2192 count");let t=tr;for(let[r,s]of Object.entries(n)){if(typeof s!="number")throw new ye("invalid",`the count of ${r} is not a number`);t=Ns(t,r,s,e)}return t}function Po(n,e){return Object.prototype.hasOwnProperty.call(n,e)?n[e]:tr}function Io(n,e){return Object.prototype.hasOwnProperty.call(n,e)?{[e]:n[e]}:{}}function Ws(n){if(!(n>0)||!Number.isFinite(n))throw new RangeError(`a cell size is a positive number, got ${String(n)}`)}function Co(n,e,t){return Ws(t),`${String(Math.floor(n/t))}:${String(Math.floor(e/t))}`}function jo(n){let e=/^(-?\d+):(-?\d+)$/.exec(n);return e===null?null:[Number(e[1]),Number(e[2])]}function qs(n,e,t){Ws(t.size);let r=t.radius??1,s=Math.floor(n/t.size),i=Math.floor(e/t.size),o=[`${String(s)}:${String(i)}`];for(let a=-r;a<=r;a+=1)for(let c=-r;c<=r;c+=1)(a!==0||c!==0)&&o.push(`${String(s+a)}:${String(i+c)}`);return o}function Ho(n,e,t,r){let s=qs(e,t,r),o=(r.radius??1)+(r.margin??1),a=Math.floor(e/r.size),c=Math.floor(t/r.size),l=new Set(s);for(let d of n){if(l.has(d))continue;let u=jo(d);u!==null&&Math.abs(u[0]-a)<=o&&Math.abs(u[1]-c)<=o&&(s.push(d),l.add(d))}return s}function Lo(n,e){if(n.length!==e.length)return!1;let t=new Set(n);return e.every(r=>t.has(r))}var J=class extends Error{constructor(t,r){super(r);this.code=t;this.name="LobbyError"}code},Us=64,Bs=256,nr=512,$s=256,rn="ABCDEFGHJKMNPQRSTUVWXYZ23456789",rr=6,Js=3e4,sn=1e3,Vs=8e3,Ks=8104,To=/^[a-z0-9][a-z0-9._-]{0,63}$/,Xs=1,yt=new TextEncoder,Do=new TextDecoder;function sr(n){if(!To.test(n))throw new J("invalid",`a game name is 1-64 of a-z 0-9 . _ - (starting with a letter or digit), got ${JSON.stringify(n)}`)}function ir(n){let e=n.toUpperCase().replace(/[\s-]/g,"");if(e.length!==rr||[...e].some(t=>!rn.includes(t)))throw new J("invalid",`not a lobby code: ${JSON.stringify(n)}`);return e}function Mo(){let n=256-256%rn.length,e="";for(;e.length<rr;){let t=new Uint8Array(16);crypto.getRandomValues(t);for(let r of t)r<n&&e.length<rr&&(e+=rn[r%rn.length])}return e}function No(n,e){return`net-lobby:${n}:seek:${e}`}function Gs(n){return`net-lobby:${n}`}function or(n){return`net-lobby:${n}:rec:`}async function zs(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",yt.encode(`net-lobby${n}${e}`))),r="";for(let s of t.subarray(0,16))r+=s.toString(16).padStart(2,"0");return`net-lobby:${n}:code:${r}`}function Wo(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qo(n){if(!/^[A-Za-z0-9_-]*$/.test(n))return null;try{let e=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(e,t=>t.charCodeAt(0))}catch{return null}}function Ys(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new J("invalid","lobby info is a flat object of strings, numbers and booleans");let e={};for(let[t,r]of Object.entries(n)){if(typeof r=="number"?!Number.isFinite(r):typeof r!="string"&&typeof r!="boolean")throw new J("invalid",`lobby info.${t} must be a string, a finite number or a boolean`);e[t]=r}if(yt.encode(JSON.stringify(e)).length>Bs)throw new J("invalid",`lobby info is over ${Bs} bytes of JSON`);return Object.freeze(e)}function Qs(n){if(typeof n!="string"||n.trim().length===0||[...n].length>Us)throw new J("invalid",`a lobby name is 1-${Us} characters`);return n}function Zs(n){if(typeof n!="number"||!Number.isInteger(n)||n<1||n>$s)throw new J("invalid",`capacity is a whole number from 1 to ${$s}`);return n}function Fs(n,e){let t=JSON.stringify({v:Xs,c:e.code,n:e.name,p:e.players,m:e.capacity,s:e.store,i:e.info}),r=or(n)+Wo(yt.encode(t));if(yt.encode(r).length>nr)throw new J("invalid",`the lobby record is over ${nr} bytes: shorten the name or info`);return r}function Uo(n,e){if(yt.encode(e).length>nr)return null;let t=qo(e.slice(or(n).length));if(t===null)return null;let r;try{r=JSON.parse(Do.decode(t))}catch{return null}if(typeof r!="object"||r===null)return null;let s=r;try{if(s.v!==Xs||typeof s.c!="string"||typeof s.s!="string"||s.s.length>200)return null;let i=Zs(s.m),o=s.p;return typeof o!="number"||!Number.isInteger(o)||o<0||o>i?null:{code:ir(s.c),name:Qs(s.n),players:o,capacity:i,store:s.s,info:Ys(s.i??{})}}catch{return null}}function on(n){let e=Be(n);if(e!==null)return e;throw new J("invalid",`not a peer id: ${JSON.stringify(n)}`)}async function yc(n){let{node:e,game:t}=n;sr(t);let r=Qs(n.name),s=Zs(n.capacity),i=Ys(n.info??{}),o=n.visibility??"public",a=Mo(),c=`${n.definition.id}@${n.definition.version}`,l=await zs(t,a);Fs(t,{code:a,name:r,players:s,capacity:s,store:c,info:i});let d=e.nodeIdHex();if(d===null)throw new J("invalid","the node has no id yet: connect it before opening a lobby");let u=on(d),p=new Set,h=n.authorize??(()=>!0),y=()=>[],m=q=>{let re=q.peer;return p.has(re)||q.type==="read"&&re!==u&&!y().includes(re)&&1+y().filter(ai=>ai!==u).length>=s?!1:h(q)},{audience:A,tags:k,announceEveryMs:I,maxEventBytes:M}=n,{node:E,game:_,name:C,capacity:W,visibility:Q,info:le,audience:w,tags:R,announceEveryMs:j,maxEventBytes:U,authorize:K,...V}=n,B=Xn({...V,transport:e,maxEventBytes:M??Ks,authorize:m}),g=pt(B);y=()=>g.owner.peers();let b=Zn(B,{audience:A??[]});function x(){return[u,...g.owner.peers().filter(q=>q!==u)]}let v=new Set,H=!1,G=null,Z=!1,ce=null,gt=sn;function si(){let q=[...k??[],l];return o==="public"&&q.push(Gs(t),Fs(t,{code:a,name:r,players:x().length,capacity:s,store:c,info:i})),q}function Xe(){if(!H){if(G!==null){Z=!0;return}ce!==null&&(clearTimeout(ce),ce=null),G=e.announce(si()).then(()=>{gt=sn}).catch(()=>{H||ce!==null||(ce=setTimeout(()=>{ce=null,Xe()},gt),gt=Math.min(gt*2,Vs))}).finally(()=>{G=null,Z&&(Z=!1,Xe())})}}let ar=x().join(),ii=g.owner.onMembership(()=>{queueMicrotask(()=>{if(H)return;let q=x();if(q.join()!==ar){ar=q.join(),Xe();for(let re of[...v])try{re(q)}catch{}}})});Xe();let oi=setInterval(Xe,I??Js);return{code:a,game:t,visibility:o,host:B,self:b,players:x,subscribePlayers:q=>(v.add(q),()=>{v.delete(q)}),link:q=>{let re=new URL(q??globalThis.location?.href??"about:blank");return re.searchParams.set("lobby",a),re.toString()},kick:q=>{let re=on(q);if(re===u)throw new J("invalid","the host cannot kick itself; close the lobby instead");p.add(re),g.dispatched(g.owner.reauthorize())},close:async()=>{H||(H=!0,clearInterval(oi),ce!==null&&clearTimeout(ce),ii(),v.clear(),await b.close(),await B.close(),await e.announce([...k??[]]).catch(()=>{}))}}}async function gc(n){sr(n.game);let e=or(n.game),t=[],r=new Set;for(let s of await n.node.query(Gs(n.game))){if(r.has(s.peerIdHex))continue;let i=s.capabilities.find(a=>a.startsWith(e));if(i===void 0)continue;let o=Uo(n.game,i);o!==null&&(r.add(s.peerIdHex),t.push({...o,host:s.peerIdHex}))}return t}async function mc(n){sr(n.game);let e;if(n.lobby!==void 0)e=on(n.lobby.host);else if(n.code!==void 0){let m=await zs(n.game,ir(n.code)),A=Date.now()+(n.timeoutMs??2e4),k=[];for(;k=[...new Set((await n.node.query(m)).map(I=>I.peerIdHex))],!(k.length>0||Date.now()>=A);)await new Promise(I=>setTimeout(I,250));if(k.length===0)throw new J("not-found",`no lobby answered to code ${n.code}`);if(k.length>1)throw new J("ambiguous",`${k.length} nodes claim code ${n.code}; join from the list instead`);e=k[0]}else throw new J("invalid","joinLobby needs a code or a lobby");let t=n.node.nodeIdHex();if(t!==null&&on(t)===e)throw new f("invalid-data","this node hosts that lobby: use lobby.self to play in it");let r=n.node,s=[...n.tags??[]],i=[...s,No(n.game,e)],o=null,a=new Set,c=null,l=sn,d=()=>{if(o!==null)return;c!==null&&(clearTimeout(c),c=null);let m=r.announce(i).then(()=>{l=sn},()=>{o!==null||c!==null||(c=setTimeout(()=>{c=null,d()},l),l=Math.min(l*2,Vs))});a.add(m),m.finally(()=>a.delete(m))};d();let u=setInterval(d,n.announceEveryMs??Js),p=()=>(o!==null||(clearInterval(u),c!==null&&clearTimeout(c),o=Promise.all(a).then(()=>r.announce(s)).catch(()=>{})),o);if(r.connectPeer!==void 0){let m=Date.now()+(n.timeoutMs??2e4);for(;;)try{await r.connectPeer(e);break}catch(A){if(Date.now()>=m)throw p(),new J("not-found",`could not reach the lobby's host ${e}: ${String(A?.message??A)}`);await new Promise(k=>setTimeout(k,500))}}let h;try{h=Yn({definition:n.definition,transport:r,host:e,audience:n.audience??[],key:n.key??"player",maxEventBytes:n.maxEventBytes??Ks,...n.interest===void 0?{}:{interest:n.interest}})}catch(m){throw p(),m}let y=h.close.bind(h);return h.close=async()=>{let m=p();await y(),await m},h}function bc(n){try{let e=new URL(n??globalThis.location?.href??"").searchParams.get("lobby");return e===null?null:ir(e)}catch{return null}}var ni="net-mesh:identity";function ei(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var ti=/^[0-9a-f]{64}$/;function Bo(n){if(n===null)return null;try{let e=JSON.parse(n);if(typeof e.entitySecretHex=="string"&&typeof e.noiseSecretHex=="string"&&ti.test(e.entitySecretHex)&&ti.test(e.noiseSecretHex))return{entitySecretHex:e.entitySecretHex,noiseSecretHex:e.noiseSecretHex}}catch{}return null}function $o(n=ni,e){let t=e;try{t??=globalThis.localStorage}catch{t=void 0}let r=null;try{r=Bo(t?.getItem(n)??null)}catch{t=void 0}if(r!==null)return r;let s={entitySecretHex:ei(32),noiseSecretHex:ei(32)};try{t?.setItem(n,JSON.stringify(s))}catch{}return s}var $e=class extends Error{constructor(t,r,s=null){super(r);this.kind=t;this.status=s}kind;status;name="CredentialRequestError"},ri={unknown_game:"unknown-game",rate_limited:"rate-limited",malformed_request:"malformed-request"};async function Fo(n){let e=n.fetch??globalThis.fetch;if(typeof e!="function")throw new $e("unreachable","requestCredential needs fetch");let t=`${n.anchorUrl.replace(/\/+$/,"")}/credential`,r;try{r=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({game:n.game}),...n.signal===void 0?{}:{signal:n.signal}})}catch(o){throw n.signal?.aborted?o:new $e("unreachable",`could not reach ${t}: ${String(o)}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){let o=s?.refusal,a=s?.message,c=typeof o=="string"&&o in ri?ri[o]:r.status===404?"unreachable":"unexpected",l=c==="unreachable"?`${t} issues no credentials (is the anchor started with --game?)`:typeof a=="string"?a:`the anchor answered ${r.status}`;throw new $e(c,l,r.status)}let i=s;if(typeof i?.credentialB64!="string"||typeof i.bootstrapUrl!="string"||typeof i.game!="string")throw new $e("unexpected","the anchor answered without a credential",r.status);return{credentialB64:i.credentialB64,bootstrapUrl:i.bootstrapUrl,game:i.game}}export{Cs as ALIVE_INTERVAL_MS,Vs as ANNOUNCE_RETRY_MAX_MS,sn as ANNOUNCE_RETRY_MS,Gt as ASSEMBLY_DEADLINE_MS,Xt as Assembly,lt as AssemblyTable,Pe as AsyncQueue,ms as BINDING_INLINE_MAX_BYTES,Lt as BrowserNode,zr as CALLER_KINDS,bt as ControlPlaneError,$e as CredentialRequestError,ni as DEFAULT_IDENTITY_KEY,Te as EventHub,Kn as FAREWELL_DEADLINE_MS,cs as FORBIDDEN_SEGMENTS,Y as HANDLE_HEX_LENGTH,Jn as HANDLE_LEASE_MS,Wt as HIDDEN,Rs as HOST_SWEEP_MS,Qt as HandleLedger,$t as INCARNATION_HEX_LENGTH,St as IceServerConflictError,me as IdentityError,Zt as InputSequences,ye as InventoryError,Tn as LARGEST_FROZEN_ENVELOPE,gs as LEDGER_MAX_AGE_MS,ys as LEDGER_MAX_BYTES,hs as LEDGER_MAX_ENTRIES,Js as LOBBY_ANNOUNCE_MS,rn as LOBBY_CODE_ALPHABET,rr as LOBBY_CODE_LENGTH,z as LeafError,We as LeafStream,ct as LedgerTable,J as LobbyError,rs as MAX_ASSEMBLY_BYTES_TOTAL,Fr as MAX_AUDIENCE_LABELS,Jr as MAX_AUDIENCE_LABEL_BYTES,Gr as MAX_DECIMAL,Xr as MAX_DETAIL_BYTES,Es as MAX_EVENT_ROUNDS,xs as MAX_HANDLES,Vr as MAX_INTEREST_KEYS,Kr as MAX_INTEREST_KEY_BYTES,er as MAX_ITEM_ID_CHARS,Ps as MAX_JOIN_REASKS,Ki as MAX_JSON_DEPTH,$s as MAX_LOBBY_CAPACITY,Bs as MAX_LOBBY_INFO_BYTES,Us as MAX_LOBBY_NAME_CHARS,nr as MAX_LOBBY_RECORD_TAG_BYTES,zn as MAX_OUTSTANDING,Ft as MAX_PATCH_OPS,Jt as MAX_PATH_SEGMENTS,Ke as MAX_PATH_SEGMENT_BYTES,Os as MAX_PENDING_ACTIONS,bs as MAX_SEQUENCE,Se as MAX_SNAPSHOT_BYTES,oe as MAX_SNAPSHOT_CHUNKS,Ln as MIN_CHUNK_BYTES,Nt as MeshSession,pn as NO_ANNOUNCEMENT_PREFIX,vr as NO_LIVE_ATTEMPT_PREFIX,Or as NO_OFFER_PREFIX,wt as NotLeaderError,ci as ORG_SINK_BUDGET_REFUSAL,Et as ORG_SINK_CLOSED_REFUSAL,di as ORG_UPLOAD_SINK_BUDGET_REFUSAL,li as ORG_UPLOAD_SINK_CLOSED_REFUSAL,Yr as OWNER_KINDS,ge as OrgAdmissionDeniedError,D as OrgCancelledError,Ne as OrgDuplex,De as OrgHandleRegistry,Ge as OrgIndeterminateError,Ie as OrgInternalError,ne as OrgLeaderLostError,Je as OrgMalformedError,ze as OrgRefusedError,Qe as OrgRequests,je as OrgRevokedError,ee as OrgServe,Le as OrgSessionLostError,Ye as OrgSink,xe as OrgStream,te as OrgStreamError,He as OrgTimeoutError,Me as OrgUpload,kr as PEER_OFFER_WAIT_MS,Er as PEER_TICK_MS,qe as PeerAttempts,xr as REPLACED_ATTEMPT_MARKER,Gn as REQUEST_DEADLINE_MS,pe as REQUEST_HEX_LENGTH,vt as RpcError,ue as RtcError,es as SNAP_ENVELOPE_RESERVE,An as STORE_ERROR_CODES,mn as STUN_NO_RESPONSE_CODE,Ce as SessionError,we as StoreCore,f as StoreError,dt as StoreOwner,ft as StoreReplica,Rt as StreamIdentityError,Hs as TICK_INTERVAL_MS,js as TRANSITION_DEADLINE_MS,yr as U64_EVENT_KEYS,Fe as UnknownLeafError,jn as WIRE_VERSION,mt as WireError,it as acceptPeer,Ns as addItems,Wn as applyPatch,Ae as applyVisibility,kn as asSessionModule,Dn as assertChunkingFits,Ji as assertHidden,ns as base64,Tt as buildConnectRequest,yn as candidateLineIsReflexive,Ss as canonicalBytes,Bn as canonicalRequest,Co as cellKey,qs as cellsAround,ts as chunkBytesFor,Mn as chunkSnapshot,Ri as classifyRtcError,Ir as classifyRtcFailure,jt as classifyRtcFailureAll,nt as clientStreamOrgTrampoline,Ot as coarseAdmissionReason,ke as compileVisibility,Hi as connect,st as connectPeer,nn as countItems,yc as createLobby,ae as decimalValue,_e as decodeMessage,Vi as defineStore,jr as diagnosticStunUrl,Fn as digestBinding,Ct as driveAttempt,rt as duplexOrgTrampoline,Eo as emptyInventory,P as encodeMessage,gr as fromBase64,S as fromWasmError,It as handshakePeer,Ao as hasItems,Ui as hiddenOr,pt as hostInternals,Zn as hostPlayer,Xn as hostStore,Ee as idArg,Kt as inadmissibleValue,$n as inlineBinding,Po as inventoryOf,Vt as isCanonicalBase64,Hn as isCanonicalDecimal,Qr as isCanonicalHex,Ut as isEntityMap,qt as isHidden,En as isLifecycleEvent,at as isStaleStream,bi as isUdpBlocked,mc as joinLobby,Yn as joinStore,ro as jsonByteLength,gc as listLobbies,ot as loadLeafWasm,bc as lobbyCodeFromUrl,zt as mergeShallow,en as needsDigest,Be as nodeHexOf,ir as normalizeLobbyCode,Io as onlyOwn,qi as openSession,pi as orgRetireError,kt as orgRetireReason,an as orgTerminalError,be as parseAttemptStatus,Dt as parseCounters,Mt as parseDescriptors,Oe as parseEvent,_o as parseInventory,At as parseJsonPreservingU64,ur as parseLeafError,Ze as parseOrgCaller,cr as parseOrgError,Mr as parseRetryReport,fr as parseRpcFailure,pr as parseRtcFailure,Dr as parseRtcStats,xn as parseSessionEvent,Re as parseStoreJson,ut as peerHexOf,Tr as peerIdHex,Sn as probeBootstrapReachable,gn as probeEventAnswers,Cr as probeStunBinding,bn as probeStunBindings,Br as projectVisible,fe as reconcile,On as refineIceFailure,Hr as reflexiveAddress,$o as rememberedIdentity,Ro as removeItems,Fo as requestCredential,Lo as sameCells,Ho as stickyCells,tt as streamingOrgTrampoline,Ai as stunProbeAnswered,_r as stunProbeVerdict,un as toBase64,se as toWasmOrgCallOptions,ie as toWasmOrgServeOptions,xt as udpBlockedEvidence,et as unaryOrgTrampoline,N as utf8Length};