snapback2 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  function Z(t,e){return{code:t,family:"owner",message:e,guide:"owner/connect"}}var En=Symbol.for("snapback2.SnapbackRefusal"),v=class extends Error{constructor(n,r=!1,i){super(n.message);this.retryable=r;this.status=i;this.name="SnapbackRefusal",this.envelope=n,this.code=n.code}[En]=!0;envelope;code};function _(t){return typeof t=="object"&&t!==null&&t.name==="SnapbackRefusal"&&t[En]===!0}function P(t){return new v({code:"E_WIRE_SHAPE",family:"op",message:t,guide:"op/wire-shape"})}function M(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw P(`${e} must be an object`);return t}function X(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function G(t,e,n){if(!X(t,e))throw P(`${n} is missing ${e}`);return t[e]}function V(t,e,n){let r=G(t,e,n);if(typeof r!="string"||r.length===0)throw P(`${n}.${e} must be a non-empty string`);return r}function ve(t,e,n){let r=G(t,e,n);if(typeof r!="number"||!Number.isFinite(r))throw P(`${n}.${e} must be a number`);return r}function An(t,e,n){if(!X(t,e))return;let r=t[e];if(typeof r!="string")throw P(`${n}.${e} must be a string`);return r}function On(t,e,n){if(!X(t,e))return;let r=t[e];if(typeof r!="number"||!Number.isFinite(r))throw P(`${n}.${e} must be a number`);return r}function Sn(t,e,n){let r=G(t,e,n);if(r!==null&&typeof r!="string")throw P(`${n}.${e} must be a string or null`);return r}function ge(t,e){let n=M(t,e),r={code:V(n,"code",e),family:V(n,"family",e),message:V(n,"message",e),guide:V(n,"guide",e)};for(let o of["site","rule","rewrite"]){let a=An(n,o,e);a!==void 0&&(r[o]=a)}let i=An(n,"which",e);i!==void 0&&(r.which=i);let s=On(n,"cap",e);return s!==void 0&&(r.cap=s),r}function z(t){let e={code:t.code,family:t.family,message:t.message,guide:t.guide};return t.site!==void 0&&(e.site=t.site),t.rule!==void 0&&(e.rule=t.rule),t.rewrite!==void 0&&(e.rewrite=t.rewrite),t.which!==void 0&&(e.which=t.which),t.cap!==void 0&&(e.cap=t.cap),e}function F(t){return t.code==="E_AUTH_SESSION"&&t.family==="auth"}function ce(t,e="query response"){let n=M(t,e);switch(V(n,"state",e)){case"complete":return{state:"complete",data:G(n,"data",e),seq:ve(n,"seq",e),next:Sn(n,"next",e)};case"capped":for(let r of["site","take","reason"])if(X(n,r))throw P(`${e}.capped must not carry ${r}`);return{state:"capped",data:G(n,"data",e),seq:ve(n,"seq",e),next:Sn(n,"next",e)};case"partial":{if(X(n,"next"))throw P(`${e}.partial must not carry next`);let r={state:"partial",seq:ve(n,"seq",e),reason:V(n,"reason",e)};return X(n,"data")?{...r,data:n.data}:r}case"denied":if(X(n,"next"))throw P(`${e}.denied must not carry next`);return{state:"denied",seq:ve(n,"seq",e),rule:V(n,"rule",e)};default:throw P(`${e}.state must be complete, capped, partial, or denied`)}}function Ft(t){let e="mutation response",n=M(t,e);if(X(n,"next"))throw P(`${e} must not carry next`);switch(V(n,"state",e)){case"committed":return{state:"committed",data:G(n,"data",e),seq:ve(n,"seq",e)};case"rejected":return{state:"rejected",...ge(n,"mutation rejected response")};default:throw P(`${e}.state must be committed or rejected`)}}function Ge(t){let e="subscription delivery",n=ht(t,e);if(V(n,"state",e)==="refused"){if(X(n,"next"))throw P(`${e}.refused must not carry next`);let r=ge(n,`${e} refusal`),i=On(n,"seq",e);return{state:"refused",live:!1,...r,...i===void 0?{}:{seq:i}}}return{...ce(n,e),live:!0}}function Ut(t){let e="channel delivery",n=ht(t,e);return n.state==="refused"?{state:"refused",...ge(n,`${e} refusal`)}:{from:V(n,"from",e),payload:G(n,"payload",e),at:ve(n,"at",e)}}function Pn(t){let e="channel publish response",n=M(t,e);if(n.ok===!0)return{ok:!0};if(n.state!=="refused")throw P(`${e} must contain ok: true or state: refused`);return{state:"refused",...ge(n,`${e} refusal`)}}function Tn(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.state!=="rejected"&&e.state!=="refused"||e.state==="rejected"&&e.reason==="conflict")return;let n=ge(e,"terminal session response");return F(n)?n:void 0}function In(t,e){let n=M(t,e);return{token:V(n,"token",e),viewer:V(n,"viewer",e)}}function Lt(t){let e="auth me response",n=M(t,e);return{viewer:V(n,"viewer",e),kind:V(n,"kind",e)}}function $n(t){let e="auth logout response",n=M(t,e);if(typeof G(n,"ok",e)!="boolean")throw P(`${e}.ok must be a boolean`);return{ok:n.ok}}function _n(t){let e="manifest response",n=M(t,e),r=M(G(n,"ops",e),`${e}.ops`);for(let[s,o]of Object.entries(r)){let a=M(o,`${e}.ops.${s}`);V(a,"kind",`${e}.ops.${s}`),V(a,"planHash",`${e}.ops.${s}`),G(a,"args",`${e}.ops.${s}`)}let i={generation:V(n,"generation",e),programGeneration:V(n,"programGeneration",e),ops:r,channels:M(G(n,"channels",e),`${e}.channels`),auth:M(G(n,"auth",e),`${e}.auth`)};return typeof n.schemaHash=="string"&&(i.schemaHash=n.schemaHash),n.tables&&typeof n.tables=="object"&&!Array.isArray(n.tables)&&(i.tables=n.tables),n.schema&&typeof n.schema=="object"&&!Array.isArray(n.schema)&&(i.schema=n.schema),i}function Cn(t){let e="asset session response",n=M(t,e);return{token:V(n,"token",e),expiresAt:ve(n,"expiresAt",e)}}async function Ve(t){let e;try{e=await t.json()}catch{throw new v(Z("E_TRANSPORT",`HTTP ${t.status} did not contain a refusal envelope`),!0,t.status)}if(!e||typeof e!="object"||Array.isArray(e)||!["code","family","guide"].some(n=>X(e,n)))throw new v(Z("E_TRANSPORT",`HTTP ${t.status} did not contain a refusal envelope`),!0,t.status);return new v(ge(e,`HTTP ${t.status} refusal`),!1,t.status)}function ht(t,e){try{return M(JSON.parse(t),e)}catch(n){throw _(n)?n:P(`${e} must contain valid JSON`)}}function E(t){if(!t?.aborted)return;let e=t.reason;if(e instanceof Error)throw e;let n=new Error(typeof e=="string"?e:"The operation was aborted");throw n.name="AbortError",n}var Ht=Symbol.for("snapback.referencePath"),jn=new Map;function Vn(t){let e=t.join("."),n=jn.get(e);if(n)return n;let r=Object.assign({},{op:e,[Ht]:e}),i=new Proxy(r,{get(s,o){if(o===Ht)return e;if(o===Symbol.toStringTag)return"SnapbackOp";if(o!=="then")return o==="op"&&t.length>=2?e:typeof o=="string"?Vn([...t,o]):void 0}});return jn.set(e,i),i}function le(t){return t[Ht]}var Kr=Vn([]);var x=class extends Error{constructor(n,r){super(r);this.code=n;this.name="AssetInputError"}};function ee(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qn(t){return J(t)&&(typeof globalThis.File=="function"&&t instanceof globalThis.File||typeof globalThis.Blob=="function"&&t instanceof globalThis.Blob)}function J(t){return ee(t)&&typeof t.size=="number"&&typeof t.arrayBuffer=="function"&&typeof t.stream=="function"}function Re(t){return ee(t)&&typeof t.uri=="string"&&t.uri.length>0}function yt(t,e=new Set){if(J(t)||Re(t))return!0;if(typeof t!="object"||t===null||e.has(t))return!1;e.add(t);let n=Array.isArray(t)?t.some(r=>yt(r,e)):Object.values(t).some(r=>yt(r,e));return e.delete(t),n}function Yr(t){if(ee(t))for(let[e,n]of[["Image","image"],["Video","video"]]){let r=t[e];if(!ee(r)||Object.keys(t).length!==1)continue;let i=r.max;if(typeof i=="number"&&Number.isSafeInteger(i)&&i>0)return{kind:n,max:i}}}var Xr=new Set(["Ref","Text","Bytes","Json","Enum","Decimal","Money","Int","Bool","Time","Id","Principal","Cursor","Scalar"]);function Zr(t){if(typeof t=="string")return!0;if(!ee(t))return!1;let e=Object.keys(t);return e.length===1&&Xr.has(e[0])}function pt(t,e,n,r){let i=Yr(e);if(i){(J(t)||Re(t))&&r.push({path:n,max:i.max,source:t});return}if(!ee(e)){if(J(t)||Re(t))throw new x("E_ASSET_TYPE",`asset upload source at ${n.join(".")||"<root>"} may only be used at an image or video argument`);return}if(Object.keys(e).length===1&&"Optional"in e){t!=null&&pt(t,e.Optional,n,r);return}if(Object.keys(e).length===1&&ee(e.List)&&Array.isArray(t)){for(let s=0;s<t.length;s+=1)pt(t[s],e.List.of,[...n,s],r);return}if(J(t)||Re(t)&&Zr(e))throw new x("E_ASSET_TYPE",`asset upload source at ${n.join(".")||"<root>"} may only be used at an image or video argument`);if(ee(t))for(let[s,o]of Object.entries(e))pt(t[s],o,[...n,s],r)}function Qe(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new x("E_ASSET_TYPE",`${e} must have a positive integer byte length`);return t}async function ei(t){let e;try{e=await import("expo-file-system")}catch(n){throw new x("E_ASSET_NOT_READY",`cannot open native asset URI ${t.uri} with expo-file-system: ${n instanceof Error?n.message:String(n)}`)}if(typeof e.File!="function")throw new x("E_ASSET_NATIVE_FILE_API","native asset URIs require expo-file-system >=19 (Expo SDK 54), whose package root exports the File constructor");try{return new e.File(t.uri)}catch(n){throw new x("E_ASSET_NOT_READY",`cannot open native asset URI ${t.uri} with expo-file-system: ${n instanceof Error?n.message:String(n)}`)}}async function Nn(){try{let t=await import("expo/fetch");if(typeof t.fetch!="function")throw new TypeError("expo/fetch does not export fetch");return t.fetch}catch(t){throw new x("E_ASSET_NOT_READY",`native asset upload requires expo/fetch: ${t instanceof Error?t.message:String(t)}`)}}async function ti(t){let e;try{e=await globalThis.fetch(t.uri)}catch(i){throw new x("E_ASSET_NOT_READY",`cannot open native asset URI ${t.uri}: ${i instanceof Error?i.message:String(i)}`)}if(!e.ok)throw new x("E_ASSET_NOT_READY",`native asset URI ${t.uri} returned HTTP ${e.status}`);if(!e.body)throw new x("E_ASSET_TYPE",`native asset URI ${t.uri} has no streaming body`);let n=t.size??t.fileSize,r=n===void 0?Qe(Number(e.headers.get("Content-Length")),`Content-Length for ${t.uri}`):Qe(n,t.size===void 0?"native asset source.fileSize":"native asset source.size");return{source:t,bytes:r,body:e.body}}async function mt(t){if(J(t))return{source:t,bytes:Qe(t.size,"File/Blob size")};if(!Re(t))throw new x("E_ASSET_TYPE","asset source must be a File or { uri, size?/fileSize?, type?/mimeType? }");if(/^(?:data|https?):/i.test(t.uri))return ti(t);let e=await ei(t),n=t.size??t.fileSize,r=n===void 0?Qe(e.size,`expo-file-system File.size for ${t.uri}`):Qe(n,t.size===void 0?"native asset source.fileSize":"native asset source.size");if(e.size!==r)throw new x("E_ASSET_TYPE",`native asset source declared ${r} bytes but expo-file-system reports ${e.size}`);return{source:t,bytes:r,body:e}}async function Bn(t,e){let n=[];pt(t,e,[],n);let r=await Promise.all(n.map(async i=>({...i,prepared:await mt(i.source)})));for(let i of r)if(i.prepared.bytes>i.max)throw new x("E_ASSET_TOO_LARGE",`asset argument at ${i.path.join(".")||"<root>"} has ${i.prepared.bytes} bytes, over its ${i.max} byte bound`);return r.map(({path:i,max:s,prepared:o})=>({path:i,max:s,prepared:o}))}async function Dn(t){if(J(t.source))return t.source;if(t.body)return t.body;let e=(await mt(t.source)).body;if(!e)throw new x("E_ASSET_TYPE",`native asset URI ${t.source.uri} has no body`);return e}function Mn(t,e,n){let r=n.onProgress;if(!r)return t;let s=(J(t)?t.stream():t).getReader(),o=0;return r({loaded:o,total:e}),new ReadableStream({async pull(a){let u=await s.read();if(u.done){o=e,r({loaded:o,total:e}),a.close();return}o=Math.min(e,o+u.value.byteLength),r({loaded:o,total:e}),a.enqueue(u.value)},cancel(a){return s.cancel(a)}})}function Gt(t,e,n){if(e.length===0)return n;let[r,...i]=e;if(Array.isArray(t)&&typeof r=="number"){let s=[...t];return s[r]=Gt(s[r],i,n),s}if(ee(t)&&typeof r=="string")return{...t,[r]:Gt(t[r],i,n)};throw new x("E_ASSET_TYPE",`asset argument path ${e.join(".")} no longer matches its manifest descriptor`)}function Fn(t,e,n){if(e.length!==n.length)throw new x("E_ASSET_NOT_READY","an asset upload did not produce a record");return e.reduce((r,i,s)=>Gt(r,i.path,n[s]),t)}function Wt(t,e,n){let r=t[e];if(typeof r!="number"||!Number.isSafeInteger(r)||r<=0)throw new x("E_ASSET_TYPE",`${n}.${e} must be a positive integer`);return r}function Un(t,e){if(!ee(t))throw new x("E_ASSET_TYPE",`${e} must be an asset record`);let n=Object.keys(t).sort(),r=Object.hasOwn(t,"duration"),i=r?["duration","height","id","width"]:["height","id","width"];if(n.length!==i.length||n.some((o,a)=>o!==i[a]))throw new x("E_ASSET_TYPE",`${e} must contain exactly ${i.join(", ")}`);if(typeof t.id!="string"||!/^s2id-[0-9a-f]{32}-[0-9a-f]{16}$/.test(t.id)||/-0{16}$/.test(t.id))throw new x("E_ASSET_TYPE",`${e}.id must be an engine-minted id`);let s={id:t.id,width:Wt(t,"width",e),height:Wt(t,"height",e)};return r?{...s,duration:Wt(t,"duration",e)}:s}function Ln(t){return Un(t,"upload response")}function Qt(t,e,n,r){let i=Un(e,"asset URL record");if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new x("E_ASSET_TYPE","asset width must be a positive integer");let s=new URLSearchParams;if(n!==void 0&&s.set("w",String(n)),r!==void 0){if(!("duration"in i))throw new x("E_ASSET_CARRIER_IMAGE","image asset URLs never carry a session token; fetch the URL with assetHeaders or assetBlob");s.set("s",r)}let o=s.size===0?"":`?${s}`;return`${t}/api/asset/${encodeURIComponent(i.id)}${o}`}var y=class extends Error{constructor(n,r,i=null){super(`${n}: ${r}`);this.code=n;this.authoredCode=i}};function Hn(t,e,n,r){if(n!==r)throw new y("E_INPUT",`${t} ${e} key ${n} does not match row id ${r}`)}function qe(t){de(t,["tables","maintains","channels","auth","effects"],"schema");let e={tables:ke(t.tables??{},ii),maintains:(t.maintains??[]).map(ni)};return t.channels!==void 0&&Object.keys(t.channels).length>0&&(e.channels=ke(t.channels,oi)),t.auth!==void 0&&t.auth!==null&&de(t.auth,["password","guests"],"auth"),t.auth!==void 0&&(t.auth.password||t.auth.guests)&&(e.auth={password:t.auth.password,guests:t.auth.guests}),t.effects!==void 0&&t.effects.length>0&&(e.effects=t.effects),JSON.stringify(e)}function de(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new y("E_SCHEMA",`${n} must be an object`);let r=Object.keys(t).filter(i=>!e.includes(i));if(r.length>0)throw new y("E_SCHEMA",`unknown ${n} field ${r.join(", ")}: a schema shape newer than this evaluator`)}function te(t,e,n){de(t,e,n);let r={};for(let i of e)t[i]!==void 0&&(r[i]=t[i]);return r}function xe(t){return Array.isArray(t)?t.map(xe):typeof t!="object"||t===null?t:ke(t,xe)}function Wn(t){return JSON.stringify(ne(t))}function ni(t){return de(t,["kind","source","by","target","readable"],"maintain"),{kind:ri(t.kind),source:t.source,by:t.by,target:t.target,readable:t.readable===null||t.readable===void 0?null:ne(t.readable)}}function ri(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t);return{[e]:e==="Sum"?te(n,["of"],"maintain.kind.Sum"):xe(n)}}function ii(t){return de(t,["columns","indexes","rules","constraints","retain"],"table"),{columns:ke(t.columns??{},gt),indexes:ke(t.indexes??{},si),rules:ai(t.rules),constraints:(t.constraints??[]).map(ui),retain:t.retain??"until-revoked"}}function si(t){return te(t,["columns","unique"],"index")}function oi(t){return de(t,["args","publish","subscribe","ttl_ms"],"channel"),{args:ke(t.args??{},Jt),publish:ne(t.publish),subscribe:ne(t.subscribe),ttl_ms:t.ttl_ms}}function ai(t){return t==null?t:(de(t,["read","insert","update","delete"],"rules"),{read:ne(t.read),insert:ne(t.insert),update:ne(t.update),delete:ne(t.delete)})}function ne(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t);switch(e){case"Eq":case"Ne":return{[e]:n.map(zt)};case"And":case"Or":return{[e]:n.map(ne)};case"Not":return{[e]:ne(n)};case"Exists":case"Created":return{[e]:{...te(n,["table","index","key","provenance"],`rule.${e}`),key:n.key.map(zt)}};case"Public":return{Public:te(n,["reason"],"rule.Public")};default:return{[e]:xe(n)}}}function zt(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t);return e==="Literal"?{Literal:Kt(n)}:e==="Field"||e==="OldField"||e==="NextField"?t:{[e]:xe(n)}}function ui(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t),r=`constraint.${e}`;switch(e){case"Unique":return{Unique:te(n,["index"],r)};case"Cap":return{Cap:te(n,["by","max"],r)};case"Immutable":return{Immutable:te(n,["fields"],r)};case"Text":return de(n,["field","min","format"],r),{Text:{field:n.field,min:n.min??0,...n.format===void 0||n.format===null?{}:{format:n.format}}};case"FinalExistsOnInsert":return{FinalExistsOnInsert:{...te(n,["table","index","key"],r),key:n.key.map(zt)}};default:return{[e]:xe(n)}}}function gt(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t);if(e==="Optional")return{Optional:gt(n)};let r=`column.${e}`;if(e==="List")return{List:{...te(n,["of","max"],r),of:gt(n.of)}};let i=ci[e];return{[e]:i===void 0?xe(n):te(n,i,r)}}var ci={Text:["max"],Bytes:["max"],Image:["max"],Video:["max"],Enum:["variants"],Decimal:["scale"],Money:["currency","scale"],Ref:["table"],Json:["max_bytes"]};function Jt(t){if(typeof t!="object"||t===null)return t;let[e,n]=Ae(t);return e==="Optional"?{Optional:Jt(n)}:e==="List"?(de(n,["of","max"],"arg.List"),{List:{...n.of===null||n.of===void 0?{}:{of:Jt(n.of)},max:n.max}}):gt(t)}function Kt(t){if(typeof t=="string")return t;let[e,n]=Ae(t);return e==="Array"?{Array:n.map(Kt)}:e==="Row"||e==="Map"?{[e]:ke(n,Kt)}:t}function ke(t,e){let n=Object.create(null);for(let r of Object.keys(t).sort(li))n[r]=e(t[r]);return n}function Ae(t){let e=Object.keys(t);if(e.length!==1)throw new Error("E_TRACE_SUBSET: malformed externally tagged IR");return[e[0],t[e[0]]]}function li(t,e){let n=Array.from(t,i=>i.codePointAt(0)),r=Array.from(e,i=>i.codePointAt(0));for(let i=0;i<Math.min(n.length,r.length);i+=1)if(n[i]!==r[i])return n[i]-r[i];return n.length-r.length}function ie(t){let e=Qn(t),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);let r=Math.floor(n/4294967296),i=n>>>0;for(let a=24;a>=0;a-=8)e.push(r>>>a&255);for(let a=24;a>=0;a-=8)e.push(i>>>a&255);let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],o=new Array(64);for(let a=0;a<e.length;a+=64){for(let m=0;m<16;m+=1){let b=a+m*4;o[m]=(e[b]<<24|e[b+1]<<16|e[b+2]<<8|e[b+3])>>>0}for(let m=16;m<64;m+=1){let b=o[m-15],S=o[m-2],R=re(b,7)^re(b,18)^b>>>3,I=re(S,17)^re(S,19)^S>>>10;o[m]=o[m-16]+R+o[m-7]+I>>>0}let[u,c,l,d,h,f,p,g]=s;for(let m=0;m<64;m+=1){let b=re(h,6)^re(h,11)^re(h,25),S=h&f^~h&p,R=g+b+S+di[m]+o[m]>>>0,I=re(u,2)^re(u,13)^re(u,22),be=u&c^u&l^c&l,Mt=I+be>>>0;g=p,p=f,f=h,h=d+R>>>0,d=l,l=c,c=u,u=R+Mt>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+c>>>0,s[2]=s[2]+l>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+h>>>0,s[5]=s[5]+f>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(a=>a.toString(16).padStart(8,"0")).join("")}function Gn(t){return Qn(t).length}function re(t,e){return t>>>e|t<<32-e}function Qn(t){let e=[];for(let n of t){let r=n.codePointAt(0);r<=127?e.push(r):r<=2047?e.push(192|r>>6,128|r&63):r<=65535?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}var di=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Yt(t){return ie(qe(t))}var Q=class extends TypeError{constructor(n,r){super(`${n}: ${r}`);this.path=n;this.name="DeliveryEnvelopeDecodeError"}};function tn(t){he(t,"$",["protocol","generation","schemaHash","planHash","authority","state","data","next","seq","rows","receipt","validator"],["reason","rule"]),t.protocol!==1&&k("$.protocol","unsupported delivery protocol"),Se(t.generation,"$.generation"),Se(t.schemaHash,"$.schemaHash"),Se(t.planHash,"$.planHash"),he(t.authority,"$.authority",["principal","authEpoch"]),K(t.authority.principal,"$.authority.principal"),bt(t.authority.authEpoch,"$.authority.authEpoch"),["complete","capped","partial","denied"].includes(String(t.state))||k("$.state","expected complete, capped, partial, or denied"),t.state==="partial"?K(t.reason,"$.reason"):t.reason!==void 0&&k("$.reason","is only valid for partial state"),t.state==="denied"?K(t.rule,"$.rule"):t.rule!==void 0&&k("$.rule","is only valid for denied state"),Ee(t.data,"$.data"),t.next!==null&&K(t.next,"$.next"),bt(t.seq,"$.seq"),fe(t.rows,"$.rows");let e=new Set;return t.rows.forEach((n,r)=>{he(n,`$.rows[${r}]`,["table","id","row"]),K(n.table,`$.rows[${r}].table`),K(n.id,`$.rows[${r}].id`),he(n.row,`$.rows[${r}].row`,[],[],!0),Ee(n.row,`$.rows[${r}].row`);let i=Ne(n.table,n.id);e.has(i)&&k(`$.rows[${r}]`,"duplicates a pooled row"),e.add(i)}),fi(t.receipt,e,t.authority),wt(t.data,e,"$.data"),Se(t.validator,"$.validator"),t}function zn(t){let e=tn(t),n=new Map(e.rows.map(i=>[Ne(i.table,i.id),i.row])),r=i=>{if(Yn(i)){let s=n.get(Ne(i.$row.table,i.$row.id));return s===void 0&&k("$.data",`references missing row ${i.$row.table}/${i.$row.id}`),wi(s)}return Xn(i)?Object.fromEntries(Object.entries(i.$row.$value).map(([s,o])=>[s,r(o)])):Array.isArray(i)?i.map(r):q(i)?Object.fromEntries(Object.entries(i).map(([s,o])=>[s,r(o)])):i};return r(e.data)}function fi(t,e,n){he(t,"$.receipt",["ranges","absences","verdicts"]),fe(t.ranges,"$.receipt.ranges"),t.ranges.forEach((r,i)=>{let s=`$.receipt.ranges[${i}]`;he(r,s,["site","table","index","prefix","order","take","after","before","gt","gte","lt","lte","ruleHash","rowIds","stop","absence"],["haloId"]);for(let a of["site","table","index","ruleHash"])K(r[a],`${s}.${a}`);Se(r.ruleHash,`${s}.ruleHash`),fe(r.prefix,`${s}.prefix`),r.prefix.forEach((a,u)=>Ee(a,`${s}.prefix[${u}]`)),["Asc","Desc"].includes(String(r.order))||k(`${s}.order`,"expected Asc or Desc"),bt(r.take,`${s}.take`);for(let a of["after","before","gt","gte","lt","lte"])r[a]!==null&&Ee(r[a],`${s}.${a}`);fe(r.rowIds,`${s}.rowIds`);let o=new Set;r.rowIds.forEach((a,u)=>{K(a,`${s}.rowIds[${u}]`),o.has(a)&&k(`${s}.rowIds[${u}]`,"duplicates a row id"),o.add(a),e.has(Ne(r.table,a))||k(`${s}.rowIds[${u}]`,"references a missing same-table pooled row")}),["Limit","Exhausted"].includes(String(r.stop))||k(`${s}.stop`,"expected Limit or Exhausted"),en(r.absence,`${s}.absence`),r.haloId!==void 0&&(K(r.haloId,`${s}.haloId`),e.has(Ne(r.table,r.haloId))||k(`${s}.haloId`,"references a missing pooled row"))}),fe(t.absences,"$.receipt.absences"),t.absences.forEach((r,i)=>{let s=`$.receipt.absences[${i}]`;fe(r,s),r.length!==3&&k(s,"expected [table, index, key]"),K(r[0],`${s}[0]`),r[1]!=="byId"&&k(`${s}[1]`,"only primary byId absences may be delivered"),fe(r[2],`${s}[2]`),r[2].forEach((o,a)=>Ee(o,`${s}[2][${a}]`))}),fe(t.verdicts,"$.receipt.verdicts"),t.verdicts.forEach((r,i)=>{let s=`$.receipt.verdicts[${i}]`;he(r,s,["ruleHash","pinnedInputsDigest","principal","authEpoch","result"]),Se(r.ruleHash,`${s}.ruleHash`),Se(r.pinnedInputsDigest,`${s}.pinnedInputsDigest`),K(r.principal,`${s}.principal`),bt(r.authEpoch,`${s}.authEpoch`),en(r.result,`${s}.result`),r.principal!==n.principal&&k(`${s}.principal`,"does not match envelope authority"),r.authEpoch!==n.authEpoch&&k(`${s}.authEpoch`,"does not match envelope authority")})}function vt(t,e,n){return hi(t,e,n)}function nn(t,e,n,r,i=0){return Xt(t,e,n,r,i)}function Jn(t,e,n){return pi(t,e,n)}function Kn(t,e,n){return ze(t,e,n)}function hi(t,e,n){let r=t?.tables?.[e]?.columns;q(r)||k(`schema.tables.${e}.columns`,"is missing");let i=Object.create(null);for(let[s,o]of Object.entries(n))s in r||k(`rows.${e}.${s}`,"is not a declared column"),i[s]=ze(r[s],o,`rows.${e}.${s}`);return{Row:i}}function Xt(t,e,n,r,i){let s=gi(t,e,n);return r.map((o,a)=>{let u=s[i+a];return u===void 0&&k(`schema.tables.${e}.indexes.${n}`,"has too few columns"),ze(t.tables[e].columns[u],o,`${e}.${n}[${i+a}]`)})}function pi(t,e,n){return n===null?null:Array.isArray(n)?{Array:Xt(t,e.table,e.index,n,e.prefix.length)}:Xt(t,e.table,e.index,[n],e.prefix.length)[0]}function ze(t,e,n){if(q(t)&&"Optional"in t)return e===null?"Null":ze(t.Optional,e,n);if(e===null)return"Null";if(t==="Id"||t==="Principal"||q(t)&&"Ref"in t)return typeof e!="string"&&k(n,"expected id string"),{Id:e};if(q(t)&&("Text"in t||"Enum"in t))return typeof e!="string"&&k(n,"expected text string"),{String:e};if(["Int","Time"].includes(String(t))||q(t)&&("Decimal"in t||"Money"in t))return rn(e,n),{Int:e};if(t==="Bool")return en(e,n),{Bool:e};if(q(t)&&"Bytes"in t){let r=q(e)&&"Bytes"in e?e.Bytes:void 0;return(!q(e)||Object.keys(e).length!==1||typeof r!="string"||!/^(?:[0-9a-f]{2})*$/.test(r))&&k(n,"expected canonical Bytes"),{Bytes:r}}if(q(t)&&"List"in t)return fe(e,n),{Array:e.map((r,i)=>ze(t.List.of,r,`${n}[${i}]`))};if(q(t)&&("Image"in t||"Video"in t)){he(e,n,[],[],!0);let r="Image"in t?"Image":"Video",i=yi[r],s=Object.keys(e);return(s.length!==Object.keys(i).length||s.some(o=>!(o in i)))&&k(n,`must contain exactly ${Object.keys(i).sort().join(", ")}`),{Map:Object.fromEntries(Object.entries(e).map(([o,a])=>[o,mi(i[o],a,`${n}.${o}`)]))}}if(q(t)&&"Json"in t)return Zt(e);k(n,"has an unsupported schema descriptor")}function Zt(t){return t===null?"Null":typeof t=="boolean"?{Bool:t}:typeof t=="number"?{Int:t}:typeof t=="string"?{String:t}:Array.isArray(t)?{Array:t.map(Zt)}:{Map:Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Zt(n)]))}}var yi={Image:{id:"String",width:"Int",height:"Int"},Video:{id:"String",width:"Int",height:"Int",duration:"Int"}};function mi(t,e,n){return t==="String"?(typeof e!="string"&&k(n,"expected string"),{String:e}):(rn(e,n),{Int:e})}function gi(t,e,n){let r=t?.tables?.[e]?.indexes?.[n]?.columns;return(!Array.isArray(r)||!r.every(i=>typeof i=="string"))&&k(`schema.tables.${e}.indexes.${n}`,"is missing columns"),r}function wt(t,e,n){if(Yn(t)){e.has(Ne(t.$row.table,t.$row.id))||k(n,"references a missing pooled row");return}if(Xn(t)){for(let[r,i]of Object.entries(t.$row.$value))wt(i,e,`${n}.$row.$value.${r}`);return}if(Array.isArray(t))t.forEach((r,i)=>wt(r,e,`${n}[${i}]`));else if(q(t)){"$row"in t&&k(n,"has a malformed reserved $row value");for(let[r,i]of Object.entries(t))wt(i,e,`${n}.${r}`)}}function Ee(t,e){if(!(t===null||typeof t=="boolean"||typeof t=="string")){if(typeof t=="number"){rn(t,e);return}if(Array.isArray(t)){t.forEach((n,r)=>Ee(n,`${e}[${r}]`));return}he(t,e,[],[],!0);for(let[n,r]of Object.entries(t))Ee(r,`${e}.${n}`)}}function Yn(t){return q(t)&&Object.keys(t).length===1&&q(t.$row)&&Object.keys(t.$row).sort().join(",")==="id,table"&&typeof t.$row.table=="string"&&typeof t.$row.id=="string"}function Xn(t){return q(t)&&Object.keys(t).length===1&&q(t.$row)&&Object.keys(t.$row).length===1&&q(t.$row.$value)}function he(t,e,n,r=[],i=!1){q(t)||k(e,"expected object");for(let s of n)s in t||k(`${e}.${s}`,"is required");if(!i)for(let s of Object.keys(t))!n.includes(s)&&!r.includes(s)&&k(`${e}.${s}`,"is unknown")}function fe(t,e){Array.isArray(t)||k(e,"expected array")}function K(t,e){(typeof t!="string"||t.length===0)&&k(e,"expected non-empty string")}function en(t,e){typeof t!="boolean"&&k(e,"expected boolean")}function bt(t,e){(!Number.isSafeInteger(t)||Number(t)<0)&&k(e,"expected non-negative safe integer")}function rn(t,e){Number.isSafeInteger(t)||k(e,"expected safe integer")}function Se(t,e){(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))&&k(e,"expected lowercase SHA-256 digest")}function q(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null)}function Ne(t,e){return`${t.length}:${t}${e}`}function wi(t){return structuredClone(t)}function k(t,e){throw new Q(t,e)}var Zn=/^s2id-([0-9a-f]{32})-([0-9a-f]{16})$/,Je=class extends Error{constructor(n,r,i,s){super(r);this.code=n;this.site=i;this.rewrite=s;this.name="OutboxRefusal"}};function Ke(){return{points:[],verdicts:[]}}function er(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.grant;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(!(typeof n.id!="string"||typeof n.from!="string"||!Zn.test(n.from)||!Number.isSafeInteger(n.count)||Number(n.count)<=0||!Number.isSafeInteger(n.mintedAt)||!Number.isSafeInteger(n.expiresAt)))return{id:n.id,from:n.from,count:n.count,mintedAt:n.mintedAt,expiresAt:n.expiresAt,used:0}}function bi(t,e,n){let r=Zn.exec(t.from);if(!r||n<=0||e<0||e+n>t.count)return[];let i=r[1],s=BigInt(`0x${r[2]}`)+BigInt(e),o=[];for(let a=0;a<n;a+=1)o.push(`s2id-${i}-${(s+BigInt(a)).toString(16).padStart(16,"0")}`);return o}function vi(t,e){return`${t}:${e}`}function Ri(t,e,n,r){let{response:i,...s}=t;return{...s,state:e,...n===void 0?{}:{response:n},updatedAt:r}}var Rt=class{constructor(e,n){this.store=e;this.options=n}listeners=new Set;resumedAt;trustGeneration=0;tail=Promise.resolve();fenceTimer;fenceProbe=0;subscribe(e){return this.listeners.add(e),this.armFence(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.close()}}notify(){this.armFence();for(let e of[...this.listeners])try{e()}catch{}}close(){this.fenceProbe+=1,clearTimeout(this.fenceTimer)}armFence(){if(this.close(),!this.listeners.size)return;let e=this.fenceProbe;this.grant().then(n=>{if(e!==this.fenceProbe||!n)return;let r=Math.min(n.expiresAt,this.trustEndsAt(n)+1)-this.options.now();r<=0||(this.fenceTimer=setTimeout(()=>this.notify(),Math.min(r,2147483647)),this.fenceTimer.unref?.())},()=>{})}entries(){return this.store.outbox.all()}async queued(){return(await this.entries()).filter(e=>e.state==="queued")}grant(){return this.store.outbox.grant()}async grantById(e){return(await this.store.outbox.grants()).find(n=>n.id===e)}adopt(e){return this.serial(async()=>{if(await this.grantById(e.id)){await this.store.commit({grants:{current:e.id}}),this.notify();return}let r=(await this.store.outbox.grants()).filter(s=>s.id!==e.id).map(s=>s.id),i=new Set((await this.queued()).map(s=>s.grant));await this.store.commit({grants:{put:[e],current:e.id,remove:r.filter(s=>!i.has(s))}}),this.notify()})}recordBounds(e,n){for(let[r,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new TypeError(`write bound for ${r} must be a non-negative integer`);return this.serial(async()=>{await this.store.commit({bounds:e,...n===void 0?{}:{programs:n}}),this.notify()})}async ready(e){let n=await this.grant();if(!n||this.expired(n))return!1;if(e===void 0)return!0;let r=(await this.store.outbox.bounds())[e];return r!==void 0&&n.used+1+r<=n.count}write(e){return this.serial(e)}pastFence(e){let n=e.mintedAt+this.options.fenceMs;return this.options.now()>n&&!this.resumedSince(n)}expired(e){return this.options.now()>=e.expiresAt}trustEndsAt(e){let n=e.mintedAt+this.options.fenceMs;return this.resumedAt!==void 0&&this.resumedAt>=n?this.resumedAt+this.options.fenceMs:n}resumedSince(e){return this.resumedAt!==void 0&&this.resumedAt>=e&&this.options.now()-this.resumedAt<=this.options.fenceMs}resetTrust(){this.trustGeneration+=1,this.resumedAt=void 0,this.notify()}get generation(){return this.trustGeneration}async canReplay(e){if(e.reason==="fence"&&!this.resumedSince(e.createdAt))return!1;let n=await this.grantById(e.grant);return n?!this.pastFence(n):this.resumedSince(e.createdAt)}async fence(){for(let n of await this.queued())if(!await this.canReplay(n))return"past";let e=await this.grant();return e&&this.pastFence(e)?"past":"inside"}resumeSucceeded(e){return e!==this.trustGeneration?!1:(this.resumedAt=this.options.now(),this.notify(),!0)}enqueue(e,n){return this.serial(async()=>{let r=await this.grant();if(!r)throw new Je("E_OFFLINE_ID_BLOCK","this device holds no replay grant; log in, or drain a query online, before writing","client.outbox.enqueue","resume as this principal for a grant (a login, or a query with { drain: true } reaching its watermark), then send again");let i=(await this.store.outbox.bounds())[e.op];if(i===void 0)throw new Je("E_OFFLINE_ID_BLOCK",`the write bound for ${e.op} is unknown on this device: its certificate was never recorded here, so the slice size cannot be priced`,"client.outbox.enqueue","reach the owner once so /api/program is recorded, then enqueue a new intent");let s=1+i;if(r.used+s>r.count)throw new Je("E_OFFLINE_ID_BLOCK",`the replay grant has ${r.count-r.used} ids left and this write needs ${s}`,"client.outbox.enqueue","resume online for a fresh grant, then enqueue a new intent");let o=bi(r,r.used,s),a=this.pastFence(r),u=n===void 0||a?void 0:await n(o),c=this.options.now(),l={intent:vi(r.id,r.used),grant:r.id,offset:r.used,count:s,ids:o,op:e.op,args:structuredClone(e.args),issuedSeq:e.issuedSeq,state:"queued",...u?.predicted?{predicted:!0}:{},...a?{predicted:!1,reason:"fence"}:{},...u?.predicted&&u.omitted!==void 0&&u.omitted.length>0?{omitted:[...u.omitted]}:{},trace:a?Ke():u?.trace??e.trace??Ke(),createdAt:c,updatedAt:c};return await this.store.commit({grants:{put:[{...r,used:r.used+s}]},outbox:{put:[l]},...u?.predicted?{overlay:{put:{[l.intent]:u.overlay}}}:{}}),this.notify(),await this.store.outbox.get(l.intent)??l})}serial(e){let n=this.tail.then(e);return this.tail=n.then(()=>{},()=>{}),n}settle(e,n,r){return Ri(e,n,r,this.options.now())}dismiss(e){return this.serial(async()=>{let n=await this.store.outbox.get(e);!n||n.state==="queued"||(await this.store.commit({outbox:{remove:[e]}}),this.notify())})}};function tr(t){return{op:t.op,args:t.args,replay:{grant:t.grant,offset:t.offset,count:t.count,intent:t.intent,trace:t.trace??Ke()}}}var Xe=/^s2id-[0-9a-f]{32}-[0-9a-f]{16}$/;function rr(t,e){return e===null?t:`${t}.w${e}`}function nr(t){return`${t.table}\0${t.id}`}function xi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function ki(t){if(!t||typeof t!="object"||typeof t.assetId!="string"||!Xe.test(t.assetId))throw new TypeError("byte cache put must name an engine-minted asset id");if(t.width!==null&&!xi(t.width))throw new TypeError("byte cache put width must be null or a positive integer");if(!(t.bytes instanceof Uint8Array))throw new TypeError("byte cache put bytes must be a Uint8Array");if(typeof t.type!="string")throw new TypeError("byte cache put type must be a string")}function Ai(t){let e=t;return typeof e.readBytes=="function"&&typeof e.bytes=="function"&&typeof e.rowsReferencing=="function"&&typeof e.viewedAsset=="function"&&typeof e.viewedRows=="function"&&typeof e.touchBytes=="function"}function Ye(t){if(typeof t!="string"||!Xe.test(t))throw new TypeError("asset id must be engine-minted");return t}var xt=class{constructor(e,n){this.store=e;this.options=n}session=new Map;partition;custody=0;custodyListeners=new Set;getCustody=()=>this.custody;subscribeCustody=e=>(this.custodyListeners.add(e),()=>{this.custodyListeners.delete(e)});admissions=Promise.resolve();bind(e){this.partition!==e&&this.forget(),this.partition=e}forget(){this.custody++,this.session.clear();for(let e of this.custodyListeners)e()}async get(e,n,r){let i=await this.getBytes(e,n,r);return i?new Blob([i.bytes],{type:i.type}):void 0}async getBytes(e,n,r){let i=this.custody;Ye(e);let s=this.carrier();if(!s)return;if(await s.viewedAsset(e)){let a=await this.sessionBytes(e,n,r);return i===this.custody?a:void 0}if(await this.viewOnce(e))return;let o=await s.readBytes(e,n);if(o)return await s.touchBytes([rr(e,n)]).catch(()=>{}),await this.canServe(e,r)&&i===this.custody?o:void 0}async canServe(e,n){let r=this.custody,i=this.carrier();if(!i)return!1;let s=await i.rowsReferencing(e);if(s.length===0)return!1;let o=await i.viewedAsset(e),a=s.every(c=>this.options.viewOnce?.(c.table,c.row)===!0),u=!o&&!a||[...this.session.entries()].some(([c,l])=>l.viewing===n&&c.startsWith(this.sessionKey(e)));return r===this.custody&&u}async viewed(e){Ye(e);let n=this.carrier();return n?n.viewedAsset(e):!1}async viewOnce(e){Ye(e);let n=this.carrier();if(!n)return!1;let r=await this.viewOnceRows(e);if(r.length===0)return!1;let i=new Set((await n.viewedRows()).map(nr));return r.some(s=>!i.has(nr(s)))}async markViewed(e){Ye(e);let n=this.carrier();if(!n)return!1;let r=await this.viewOnceRows(e);return r.length===0?!1:(await n.commit({viewed:r}),!0)}async put(e,n,r,i){let s=this.custody,o=new Uint8Array(await r.arrayBuffer());return s!==this.custody?"refused":this.putBytes(e,n,{bytes:o,type:r.type},i)}putBytes(e,n,r,i){let s=this.custody,o=this.admissions.then(()=>s===this.custody?this.admit(e,n,r,i):"refused");return this.admissions=o.catch(()=>{}),o}async admit(e,n,r,i){let s=this.custody;Ye(e),ki({assetId:e,width:n,...r});let o=this.carrier();if(!o)return"unleased";if(await o.viewedAsset(e))return"refused";let a=await o.rowsReferencing(e);if(a.length===0||s!==this.custody)return"unleased";let u=a.filter(l=>this.options.viewOnce?.(l.table,l.row)===!0).map(({table:l,id:d})=>({table:l,id:d}));if(u.length>0&&!i)return"refused";if(u.length===a.length){try{await o.commit({viewed:u})}catch{return"refused"}return s!==this.custody||(await o.rowsReferencing(e)).length===0||!await o.viewedAsset(e)||s!==this.custody?"unleased":(this.session.size>=8&&this.session.delete(this.session.keys().next().value),i&&this.session.set(this.sessionKey(e,n),{viewing:i,value:{bytes:r.bytes.slice(),type:r.type}}),"viewed")}try{await o.commit({...u.length===0?{}:{viewed:u},bytes:{put:[{assetId:e,width:n,...r}],ceiling:this.options.maxAssetBytes}})}catch{return"refused"}let c=await o.bytes();return s===this.custody&&c.entries.some(l=>l.assetId===e&&l.width===n)?"cached":"refused"}async status(){let e=this.carrier();return e?e.bytes():{entries:[],totalBytes:0,viewed:[]}}carrier(){return this.partition!==void 0&&Ai(this.store)?this.store:void 0}sessionKey(e,n){return`${this.partition}\0${e}\0${n===void 0?"":n}`}async sessionBytes(e,n,r){let i=this.carrier();if(!i)return;let s=this.sessionKey(e,n),o=this.session.get(s);if(!(!r||o?.viewing!==r)){if((await i.rowsReferencing(e)).length>0)return o.value;this.session.delete(s)}}async viewOnceRows(e){let n=this.carrier();return n?(await n.rowsReferencing(e)).filter(i=>this.options.viewOnce?.(i.table,i.row)===!0).map(({table:i,id:s})=>({table:i,id:s})):[]}};function Ze(t){return t===void 0?"undefined":t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(Ze).join(",")}]`:`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Ze(t[e])}`).join(",")}}`}function Be(t,e){return`${t}\0${Ze(e===void 0?e:Si(e))}`}function Si(t){return JSON.parse(JSON.stringify(t))}function De(t){return[...t].sort((e,n)=>(e.order??Number.MAX_SAFE_INTEGER)-(n.order??Number.MAX_SAFE_INTEGER)||e.updatedAt-n.updatedAt||Be(e.op,e.args).localeCompare(Be(n.op,n.args)))[0]}var kt={systemPrincipalId:"system",retentionPolicies:["until-revoked","delivered-history"],valueModelVersion:"i53-codepoint-bytes-v2"};var ir=1,sn=4096,et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function on(t){un(t.suffix,t.values);let e=Oi(JSON.stringify([ir,t.table,t.index,t.order,t.suffix.map(r=>({name:r.name,kind:St(r.kind)})),t.values.map(Et)]));e.length>sn&&T("cursor token exceeds 4096 bytes");let n="";for(let r=0;r<e.length;r+=3){let i=e[r],s=e[r+1],o=e[r+2];n+=et[i>>2],n+=et[(i&3)<<4|(s??0)>>4],s!==void 0&&(n+=et[(s&15)<<2|(o??0)>>6]),o!==void 0&&(n+=et[o&63])}return n}function an(t){t.length>Math.ceil(sn*4/3)&&T("cursor token exceeds 4096 bytes"),(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)&&T("cursor token is not canonical base64url");let e=[];for(let h=0;h<t.length;h+=4){let f=t.slice(h,h+4),p=Array.from(f,m=>et.indexOf(m)),g=p[0]<<18|(p[1]??0)<<12|(p[2]??0)<<6|(p[3]??0);e.push(g>>16&255),f.length>=3&&e.push(g>>8&255),f.length===4&&e.push(g&255)}e.length>sn&&T("cursor token exceeds 4096 bytes");let n;try{n=JSON.parse(Pi(e))}catch{T("cursor token is not the canonical tagged encoding")}(!Array.isArray(n)||n.length!==6)&&T("cursor token is not the canonical tagged encoding");let[r,i,s,o,a,u]=n;r!==ir&&T(`cursor token version ${String(r)} is unsupported`),(typeof i!="string"||typeof s!="string"||!["Asc","Desc"].includes(o)||!Array.isArray(a)||!Array.isArray(u))&&T("cursor token is not the canonical tagged encoding");let c=a.map(h=>((!se(h)||Object.keys(h).length!==2||typeof h.name!="string"||!("kind"in h))&&T("cursor token is not the canonical tagged encoding"),{name:h.name,kind:St(h.kind)})),l=u.map(Et),d={table:i,index:s,order:o,suffix:c,values:l};return un(c,l),on(d)!==t&&T("cursor token is not canonical"),d}function Ot(t,e){let n=an(t);return(n.table!==e.table||n.index!==e.index||n.order!==e.order||JSON.stringify(n.suffix)!==JSON.stringify(e.suffix))&&T("cursor token describes a different table, index, order, or suffix"),{Array:n.values}}function tt(t,e){let n=t.tables?.[e.table],r=n?.indexes?.[e.index];return(!n||!r)&&T(`cursor names missing index ${e.table}.${e.index}`),r.columns.slice(e.prefix.length).map(i=>({name:i,kind:n.columns[i]}))}function un(t,e){t.length!==e.length&&T("cursor token values do not match its typed suffix"),t.forEach((n,r)=>{let i=e[r],s=n.kind;if(s?.Optional!==void 0){if(i==="Null")return;un([{name:n.name,kind:s.Optional}],[i]);return}(s==="Id"||s==="Principal"||s?.Ref!==void 0?Me(i,"Id"):s?.Text!==void 0||s?.Enum!==void 0?Me(i,"String"):s==="Int"||s==="Time"||s?.Decimal!==void 0||s?.Money!==void 0?Me(i,"Int"):s==="Bool"?Me(i,"Bool"):s?.Bytes!==void 0?Me(i,"Bytes"):s?.Json!==void 0?["Bool","Int","String","Id","Bytes"].some(a=>Me(i,a)):!1)||T("cursor token values do not match its typed suffix")})}function St(t){if(["Id","Principal","Int","Bool","Time"].includes(t))return t;(!se(t)||Object.keys(t).length!==1)&&T("cursor token is not the canonical tagged encoding");let e=Object.keys(t)[0],n=t[e];if(e==="Text"||e==="Bytes"||e==="Json"){let r=e==="Json"?"max_bytes":"max";return(!se(n)||Object.keys(n).length!==1||!At(n[r]))&&T("cursor token is not the canonical tagged encoding"),{[e]:{[r]:n[r]}}}if(e==="Ref")return(!se(n)||Object.keys(n).length!==1||typeof n.table!="string")&&T("cursor token is not the canonical tagged encoding"),{Ref:{table:n.table}};if(e==="Decimal")return(!se(n)||Object.keys(n).length!==1||!At(n.scale))&&T("cursor token is not the canonical tagged encoding"),{Decimal:{scale:n.scale}};if(e==="Money")return(!se(n)||Object.keys(n).length!==2||typeof n.currency!="string"||!At(n.scale))&&T("cursor token is not the canonical tagged encoding"),{Money:{currency:n.currency,scale:n.scale}};if(e==="Enum")return(!se(n)||Object.keys(n).length!==1||!Array.isArray(n.variants)||!n.variants.every(r=>typeof r=="string"))&&T("cursor token is not the canonical tagged encoding"),{Enum:{variants:n.variants.slice()}};if(e==="Optional")return{Optional:St(n)};if(e==="List")return(!se(n)||Object.keys(n).length!==2||!("of"in n)||!At(n.max))&&T("cursor token is not the canonical tagged encoding"),{List:{of:St(n.of),max:n.max}};T("cursor token is not the canonical tagged encoding")}function Et(t){if(t==="Null")return t;(!se(t)||Object.keys(t).length!==1)&&T("cursor token is not the canonical tagged encoding");let e=Object.keys(t)[0],n=t[e];if(e==="Bool"&&typeof n=="boolean")return{Bool:n};if(e==="Int"&&Number.isSafeInteger(n))return{Int:n};if((e==="String"||e==="Id"||e==="Bytes")&&typeof n=="string")return{[e]:n};if(e==="Array"&&Array.isArray(n))return{Array:n.map(Et)};if((e==="Row"||e==="Map")&&se(n)){let r={};for(let i of Object.keys(n))r[i]=Et(n[i]);return{[e]:r}}T("cursor token is not the canonical tagged encoding")}function Oi(t){let e=[];for(let n of t){let r=n.codePointAt(0);r<=127?e.push(r):r<=2047?e.push(192|r>>6,128|r&63):r<=65535?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function Pi(t){let e="";for(let n=0;n<t.length;){let r=t[n++],i;r<128?i=r:(r&224)===192&&n<t.length?i=(r&31)<<6|t[n++]&63:(r&240)===224&&n+1<t.length?i=(r&15)<<12|(t[n++]&63)<<6|t[n++]&63:(r&248)===240&&n+2<t.length?i=(r&7)<<18|(t[n++]&63)<<12|(t[n++]&63)<<6|t[n++]&63:T("cursor token is not canonical UTF-8"),(i>=55296&&i<=57343||i>1114111)&&T("cursor token is not canonical UTF-8"),e+=String.fromCodePoint(i)}return JSON.stringify(e).includes("\uFFFD")&&T("cursor token is not canonical UTF-8"),e}function Me(t,e){return t!=="Null"&&e in t}function se(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function At(t){return Number.isInteger(t)&&t>=0}function T(t){throw new y("E_INPUT",t)}var sr=9007199254740991,Ti=-sr;function $(t){if(t==="Null")return'"Null"';let e=ae(t),n=t[e];if(e==="Bool"||e==="Int")return`{"${e}":${JSON.stringify(n)}}`;if(e==="String"||e==="Id")return`{"${e}":${JSON.stringify(n)}}`;if(e==="Bytes"){if(!it(n))throw new y("E_INPUT","Bytes is not canonical lowercase base16");return`{"Bytes":${JSON.stringify(n)}}`}if(e==="Array")return`{"Array":${oe(n)}}`;let r=Object.keys(n).sort(U).map(i=>`${JSON.stringify(i)}:${$(n[i])}`).join(",");return`{"${e}":{${r}}}`}function oe(t){return`[${t.map($).join(",")}]`}function Pe(t,e,n){if(!w(n,"Row"))return O(n);let r=Object.assign(Object.create(null),n.Row);for(let[i,s]of Object.entries(t.tables?.[e]?.columns??{}))s?.Optional!==void 0&&!Fe(r,i)&&(r[i]="Null");return st(r)}function st(t){let e=Object.create(null);for(let n of Object.keys(t).sort(U))e[n]=O(t[n]);return{Row:e}}function A(t,e){let n=Te(t);if(!Fe(n,e))throw new y("E_FIELD",`missing field ${e}`);return n[e]}function Y(t,e){let n=Te(t);return Fe(n,e)?n[e]:"Null"}function Te(t){if(w(t,"Row"))return t.Row;if(w(t,"Map"))return t.Map;throw new y("E_TYPE","expected row or map")}function ye(t){if(!w(t,"Array"))throw new y("E_TYPE","expected array");return t.Array}function j(t){if(w(t,"String"))return t.String;if(w(t,"Id"))return t.Id;throw new y("E_TYPE","expected string or id")}function B(t){if(!w(t,"Int"))throw new y("E_TYPE","expected int");return t.Int}function ue(t){if(!w(t,"Bool"))throw new y("E_TYPE","expected bool");return t.Bool}function N(t){return{Int:It(t)}}function It(t){if(!Number.isSafeInteger(t)||t<Ti||t>sr)throw new y("E_OVERFLOW",`${t} is outside the i53 value model`);return t}function D(t,e){let n=["Null","Bool","Int","String","Id","Bytes","Row","Array","Map"],r=ae(t),i=ae(e),s=n.indexOf(r)-n.indexOf(i);if(s!==0)return Math.sign(s);if(r==="Null")return 0;let o=t[r],a=e[i];if(r==="Bool"||r==="Int")return nt(o,a);if(r==="String"||r==="Id")return U(o,a);if(r==="Bytes"){if(!it(o)||!it(a))throw new y("E_INPUT","Bytes is not canonical lowercase base16");return U(o,a)}if(r==="Array")return $t(o,a);let u=Object.keys(o).sort(U),c=Object.keys(a).sort(U),l=nt(u.length,c.length);if(l!==0)return l;for(let d=0;d<u.length;d+=1){let h=U(u[d],c[d]);if(h!==0)return h;let f=D(o[u[d]],a[c[d]]);if(f!==0)return f}return 0}function $t(t,e){let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){let i=D(t[r],e[r]);if(i!==0)return i}return nt(t.length,e.length)}function U(t,e){let n=Array.from(t,s=>s.codePointAt(0)),r=Array.from(e,s=>s.codePointAt(0)),i=Math.min(n.length,r.length);for(let s=0;s<i;s+=1){let o=nt(n[s],r[s]);if(o!==0)return o}return nt(n.length,r.length)}function nt(t,e){return t<e?-1:t>e?1:0}function rt(t,e){if(t.length<=1)return t;let n=Math.floor(t.length/2),r=rt(t.slice(0,n),e),i=rt(t.slice(n),e),s=[];for(;r.length>0&&i.length>0;)s.push(e(r[0],i[0])<=0?r.shift():i.shift());return s.concat(r,i)}function L(t){if(typeof t=="string")return[t,null];let e=Object.keys(t);if(e.length!==1)throw new y("E_CORPUS","invalid externally tagged variant");return[e[0],t[e[0]]]}function pe(t){let[e,n]=L(t);switch(e){case"Null":return null;case"Bool":case"Int":case"String":case"Id":return n;case"Bytes":return{Bytes:n};case"Row":case"Map":return Object.fromEntries(Object.keys(n).sort(U).map(r=>[r,pe(n[r])]));case"Array":return n.map(pe);default:throw new y("E_INPUT",`unsupported value kind ${e}`)}}function or(t){return ie(JSON.stringify(pe(t)))}function ot(t,e){return ie(`[${JSON.stringify(ie(qe(t)))},${Wn(e)}]`)}function ae(t){if(t==="Null")return"Null";let e=Object.keys(t);if(e.length!==1)throw new y("E_INPUT","invalid externally tagged value");return e[0]}function w(t,e){return t!=="Null"&&ae(t)===e}function H(t,e){return oe(t)===oe(e)}function ar(t,e){let n=ae(t),r=ae(e);if(["Bytes","Row","Array","Map"].includes(n))throw new y("E_TYPE",`SameValueZero expects primitive operands, got ${n}`);if(["Bytes","Row","Array","Map"].includes(r))throw new y("E_TYPE",`SameValueZero expects primitive operands, got ${r}`);if((n==="String"||n==="Id")&&(r==="String"||r==="Id")){let i=w(t,"String")?t.String:t.Id,s=w(e,"String")?e.String:e.Id;return i===s}return $(t)===$(e)}function ur(t,e){return e.every((n,r)=>t[r]===n)}function cr(t){let e=t.startsWith("https://")?t.slice(8):t.startsWith("http://")?t.slice(7):"";return e.length>0&&!/[\p{White_Space}\p{Cc}]/u.test(e)}function we(t){return Array.isArray(t)?`[${t.map(we).join(",")}]`:t!==null&&typeof t=="object"?`{${Object.keys(t).sort(U).map(e=>`${JSON.stringify(e)}:${we(t[e])}`).join(",")}}`:JSON.stringify(t)}function Ue(t,e,n){let r=t.tables?.[e]?.columns;if(r===void 0)throw new y("E_SCHEMA",`missing table ${e}`);let i=Te(n);if(!Fe(i,"id"))throw new y("E_SCHEMA",`${e} row lacks id`);let s=Object.keys(i).find(o=>!Fe(r,o));if(s!==void 0)throw new y("E_INPUT",`${e} row contains undeclared field ${s}`);for(let[o,a]of Object.entries(r)){let u=Fe(i,o)?i[o]:void 0;if(u===void 0&&a?.Optional===void 0)throw new y("E_INPUT",`${e}.${o} is required`);u!==void 0&&Tt(a,u,`${e}.${o}`,!1)}}function fn(t,e,n){for(let[r,i]of Object.entries(e.args??{})){let s=n[r];if(s===void 0)throw new y("E_INPUT",`missing arg ${r}`);Tt(i,s,`arg ${r}`,!0)}Ii(t,e.body,n)}function Ii(t,e,n){let r=(s,o)=>{if(Array.isArray(s)){for(let u of s)r(u,o);return}if(s===null||typeof s!="object")return;let a=s.Scan;if(a?.opaque_cursor){if(a.before!==null)throw new y("E_INPUT","opaque cursors only support after");let u=a.after===null?"Null":$i(a.after,o);if(u!=="Null"){if(!w(u,"String"))throw new y("E_INPUT","opaque cursor must be a string");Ot(u.String,{table:a.table,index:a.index,order:a.order,suffix:tt(t,a)})}}for(let u of Object.values(s))r(u,o)},i=(s,o)=>{for(let a of s){if(a===null||typeof a!="object")continue;let u=a.Const??a.Let??a.Assign;if(u){r(u.value,o);let c=lr(u.value,o);c===void 0?delete o[u.name]:o[u.name]=c;continue}if(a.If){r(a.If.condition,o);let c={...o},l={...o};i(a.If.then_body,c),i(a.If.else_body,l);for(let d of Object.keys(o))(!(d in c)||!(d in l)||$(c[d])!==$(l[d]))&&delete o[d];continue}if(a.For){r(a.For.domain,o),i(a.For.body,{...o});continue}r(a,o)}};i(e,{...n})}function $i(t,e){let n=lr(t,e);if(n!==void 0)return n;throw new y("E_INPUT","opaque cursor expression must derive from an operation argument")}function lr(t,e){if(t?.Variable!==void 0)return e[t.Variable];if(t?.Literal!==void 0)return t.Literal}function Tt(t,e,n,r){if(dn(e,n),Pt(e))throw new y("E_INPUT",`${n} cannot carry the reserved system principal`);if(cn(t)){ln(t,e,n);return}if(t?.Optional!==void 0){e!=="Null"&&Tt(t.Optional,e,n,r);return}if(t?.List!==void 0){if(!w(e,"Array"))throw new y("E_INPUT",`${n} must be a list`);if(e.Array.length>t.List.max)throw new y(r?"E_FANOUT":"E_INPUT",`${n} exceeds list max ${t.List.max}`);if(t.List.of!==null&&t.List.of!==void 0)for(let i of e.Array)Tt(t.List.of,i,n,r);return}if(t==="Cursor"){if(!w(e,"String"))throw new y("E_INPUT",`${n} must be a cursor string`);an(e.String);return}if(t!=="Scalar"){if(t==="Id"||t==="Principal"||t?.Ref!==void 0){if(!w(e,"Id"))throw new y("E_INPUT",`${n} must be an id`);return}if(t?.Text!==void 0){if(!w(e,"String"))throw new y("E_INPUT",`${n} must be text`);let i=_i(e.String);if(i!==void 0)throw new y("E_INPUT",`${n} contains disallowed control character U+${i.toString(16).toUpperCase().padStart(4,"0")}`);if(Array.from(e.String).length>t.Text.max)throw new y("E_INPUT",`${n} exceeds text max ${t.Text.max}`);return}if(t?.Bytes!==void 0){if(!w(e,"Bytes")||!it(e.Bytes))throw new y("E_INPUT",`${n} must be bytes`);if(e.Bytes.length/2>t.Bytes.max)throw new y("E_INPUT",`${n} exceeds bytes max ${t.Bytes.max}`);return}if(["Int","Time"].includes(t)||t?.Decimal!==void 0||t?.Money!==void 0){if(!w(e,"Int")||!Number.isSafeInteger(e.Int))throw new y("E_INPUT",`${n} must be an i53 integer`);return}if(t==="Bool"){if(!w(e,"Bool"))throw new y("E_INPUT",`${n} must be a boolean`);return}if(t?.Json!==void 0){if(Gn($(e))>t.Json.max_bytes)throw new y("E_INPUT",`${n} exceeds JSON max ${t.Json.max_bytes} bytes`);return}if(t?.Enum!==void 0){if(!w(e,"String")||!t.Enum.variants.includes(e.String))throw new y("E_INPUT",`${n} is not a declared enum value`);return}throw new y("E_SCHEMA",`unsupported type for ${n}`)}}function _i(t){for(let e of t){let n=e.codePointAt(0);if(n<32&&![9,10,13].includes(n))return n}}function cn(t){return t?.Image!==void 0||t?.Video!==void 0?!0:t?.Optional!==void 0?cn(t.Optional):t?.List?.of!==null&&t?.List?.of!==void 0?cn(t.List.of):!1}function ln(t,e,n){if(t?.Optional!==void 0)return e==="Null"?[]:ln(t.Optional,e,n);if(t?.List!==void 0){if(!w(e,"Array"))throw Oe(`${n} must be a list`);if(e.Array.length>t.List.max)throw Oe(`${n} exceeds list max ${t.List.max}`);let u=e.Array.flatMap((d,h)=>ln(t.List.of,d,`${n}[${h}]`)),c=new Set,l=u.find(d=>c.has(d)||!c.add(d));if(l!==void 0)throw Oe(`${n} repeats asset id ${l}; asset ids in a list must be unique`);return u}let r=t?.Image!==void 0?"image":t?.Video!==void 0?"video":null;if(r===null)throw new y("E_SCHEMA",`unsupported asset type for ${n}`);if(!w(e,"Map"))throw Oe(`${n} must be a closed ${r} asset map`);let i=r==="image"?["height","id","width"]:["duration","height","id","width"],s=Object.keys(e.Map).sort(U);if(s.length!==i.length||s.some((u,c)=>u!==i[c]))throw Oe(`${n} must contain exactly ${i.join(", ")}`);let o=e.Map.id,a=w(o,"String")?o.String:"";if(!Ci(a))throw Oe(`${n}.id must be a minted s2id`);for(let u of r==="image"?["width","height"]:["width","height","duration"]){let c=e.Map[u];if(!w(c,"Int")||!Number.isSafeInteger(c.Int)||c.Int<=0)throw Oe(`${n}.${u} must be a positive i53 integer`)}return[a]}function Ci(t){return/^s2id-[0-9a-f]{32}-[0-9a-f]{16}$/.test(t)&&!t.endsWith("-0000000000000000")}function Oe(t){return new y("E_ASSET_TYPE",t)}function dn(t,e){if(t==="Null")return;let n=ae(t),r=t[n];if(!(n==="Bool"&&typeof r=="boolean")&&!(n==="Int"&&Number.isSafeInteger(r))&&!((n==="String"||n==="Id")&&typeof r=="string")&&!(n==="Bytes"&&it(r))){if(n==="Array"&&Array.isArray(r)){for(let i of r)dn(i,e);return}if((n==="Row"||n==="Map")&&r!==null&&typeof r=="object"&&!Array.isArray(r)){for(let i of Object.values(r))dn(i,e);return}throw new y("E_INPUT",`${e} is not a valid value`)}}function Pt(t){return w(t,"Id")?t.Id===kt.systemPrincipalId:w(t,"Array")?t.Array.some(Pt):w(t,"Row")?Object.values(t.Row).some(Pt):w(t,"Map")?Object.values(t.Map).some(Pt):!1}function it(t){return typeof t=="string"&&/^(?:[0-9a-f]{2})*$/.test(t)}function Fe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function O(t){return t==null?t:JSON.parse(JSON.stringify(t))}function dr(t){switch(t){case"Len":case"Sort":case"DedupeById":case"MentionTokens":case"Count":case"CountCapped":case"Sum":return 1;case"Concat":case"Min":case"Max":case"Divmod":return 2;case"Slice":case"DeterministicShare":return 3;default:throw new y("E_OPAQUE",`unsupported builtin ${t}`)}}function _t(t){return t==="Null"?"null":w(t,"Bool")?String(t.Bool):w(t,"Int")?String(t.Int):w(t,"String")?t.String:w(t,"Id")?t.Id:w(t,"Bytes")?t.Bytes:w(t,"Array")?t.Array.map(_t).join(","):"[object Object]"}function hn(t){return t==="_"||/[\p{L}\p{N}]/u.test(t)}function fr(t){let e=[],n="";for(let r of t)ji(r.codePointAt(0))?(n.length>0&&e.push(n),n=""):n+=r;return n.length>0&&e.push(n),e}function ji(t){return t>=9&&t<=13||t===32||t===133||t===160||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}var Ls=kt.valueModelVersion,hr={kind:"next"},at=class{constructor(e,n,r,i){this.store=e;this.schema=n;this.certificate=i;this.env=new Map;this.consts=new Set;this.trace={ranges:[],absences:[],points:[],merges:[],verdicts:[]};this.ruleMemo=new Map;this.pendingVerdicts=[];this.tracedVerdicts=new Set;this.writes=new Map;this.partial=new Set;this.authorityMissSerial=0;this.unheldMaintainTargets=[];this.createdRows=new Set;this.insertedRows=[];this.createdPoints=[];this.context=O(r);for(let[s,o]of Object.entries(r.args))this.env.set(s,O(o))}execute(e){let n=this.statements(e.body);return this.checkFinalConstraints(),{result:this.partial.size===0&&n.kind==="return"?n.value:"Null",trace:this.trace,next:Vi(this.schema,this.certificate,this.trace),writes:[...this.writes.values()]}}coverageMisses(){return Array.from(this.partial).sort(U)}authorityMisses(){return{maintainTargets:[...this.unheldMaintainTargets],other:this.authorityMissSerial-this.unheldMaintainTargets.length}}statements(e){for(let n of e){let[r,i]=L(n),s=hr;switch(r){case"Const":this.env.set(i.name,this.expr(i.value)),this.consts.add(i.name);break;case"Let":this.env.set(i.name,this.expr(i.value));break;case"Assign":if(this.consts.has(i.name))throw new y("E_INPUT",`cannot assign to const binding ${i.name}`);this.env.set(i.name,this.expr(i.value));break;case"Push":{let o=this.env.get(i.target);if(o===void 0||!w(o,"Array"))throw new y("E_TYPE","push target is not an array");o.Array.push(this.expr(i.value));break}case"If":s=this.statements(ue(this.expr(i.condition))?i.then_body:i.else_body);break;case"For":{for(let o of this.domain(i.domain)){this.env.set(i.binding,o);let a=this.statements(i.body);if(!(a.kind==="continue"||a.kind==="next")){if(a.kind==="break")break;s=a;break}}break}case"Require":if(!ue(this.expr(i.condition)))throw new y("E_REQUIRE","program requirement failed",i.code);break;case"Insert":this.insert(i.table,this.expr(i.row));break;case"Update":this.update(i.table,this.expr(i.key),this.expr(i.patch));break;case"Upsert":{let o=this.expr(i.key),a=this.expr(i.row);this.validateAddressedRowId(i.table,o,a),this.store.byId(i.table,j(o))===null?this.insert(i.table,a):this.replace(i.table,o,a);break}case"Delete":this.delete(i.table,j(this.expr(i.key)));break;case"Emit":if(this.expr(i.payload),this.context.new_ids.shift()===void 0)throw new y("E_INPUT","newId envelope exhausted");break;case"Return":s={kind:"return",value:this.expr(i)};break;case"Break":s={kind:"break"};break;case"Continue":s={kind:"continue"};break;default:throw new y("E_OPAQUE",`unsupported statement ${r}`)}if(s.kind!=="next")return s}return hr}domain(e){let[n,r]=L(e);switch(n){case"Page":return ye(this.scan(r));case"LiteralRange":{let i=[];for(let s=r.start;s<r.end_exclusive;s+=1)i.push(N(s));return i}case"ArgList":{let i=ye(this.requiredEnv(r.name));if(i.length>r.max)throw new y("E_FANOUT","argument list bound");return i}case"DerivedArray":{let i=ye(this.expr(r.value));if(i.length>r.max)throw new y("E_FANOUT","derived array bound");return i}case"Recurse":return this.recurse(r);default:throw new y("E_OPAQUE",`unsupported loop domain ${n}`)}}recurse(e){let n=[[this.expr(e.seed),0]],r=new Set,i=[];for(;n.length>0;){let[s,o]=n.shift(),a=$(s);if(o>e.depth||r.has(a))continue;r.add(a);let u=this.get({site:e.site,table:e.table,index:e.index,key:[{Literal:s}],provenance:e.provenance});if(u==="Null")continue;let c=A(u,e.next_field);if(i.push(u),c==="Null")continue;let l=w(c,"Array")?c.Array:[c];if(l.length>e.fanout)throw new y("E_FANOUT","recursive fanout exceeded");for(let d of l)n.push([d,o+1])}return i}expr(e){let[n,r]=L(e);switch(n){case"Literal":return O(r);case"Variable":return O(this.requiredEnv(r));case"Input":return this.input(r);case"Field":return O(A(this.expr(r.base),r.name));case"Array":return{Array:r.map(i=>this.expr(i))};case"Object":{let i=Object.create(null);for(let s of Object.keys(r).sort(U))i[s]=this.expr(r[s]);return{Row:i}}case"Binary":return this.binary(r);case"Unary":{let i=this.expr(r.value);if(r.op==="Not")return{Bool:!ue(i)};if(r.op==="Neg")return N(-B(i));throw new y("E_OPAQUE",`unsupported unary ${r.op}`)}case"Builtin":{let i=L(r.builtin)[0],s=dr(i);if(r.args.length!==s)throw new y("E_INPUT",`${i} requires ${s} arguments, received ${r.args.length}`);return this.builtin(r.builtin,r.args.map(o=>this.expr(o)))}case"Get":return this.get(r);case"Exists":return{Bool:this.get(r)!=="Null"};case"Scan":return this.scan(r);default:throw new y("E_OPAQUE",`unsupported expression ${n}`)}}input(e){switch(e){case"Viewer":return{Id:this.context.viewer};case"Now":if(this.context.now===null)throw new y("E_INPUT","now was not pinned");return N(this.context.now);case"NewId":{let n=this.context.new_ids.shift();if(n===void 0)throw new y("E_INPUT","newId envelope exhausted");return{Id:n}}case"ReadTime":if(this.context.read_time===null)throw new y("E_INPUT","readTime was not pinned");return N(this.context.read_time);default:throw new y("E_INPUT",`unknown modeled input ${e}`)}}binary(e){let n=this.expr(e.left);if(e.op==="And"&&!ue(n))return{Bool:!1};if(e.op==="Or"&&ue(n))return{Bool:!0};let r=this.expr(e.right);switch(e.op){case"Eq":return{Bool:$(n)===$(r)};case"Ne":return{Bool:$(n)!==$(r)};case"SameValueZero":return{Bool:ar(n,r)};case"Lt":return{Bool:D(n,r)<0};case"Lte":return{Bool:D(n,r)<=0};case"Gt":return{Bool:D(n,r)>0};case"Gte":return{Bool:D(n,r)>=0};case"Add":return N(B(n)+B(r));case"Sub":return N(B(n)-B(r));case"Mul":return N(B(n)*B(r));case"And":return{Bool:ue(n)&&ue(r)};case"Or":return{Bool:ue(n)||ue(r)};default:throw new y("E_OPAQUE",`unsupported binary ${e.op}`)}}builtin(e,n){let[r,i]=L(e);switch(r){case"Len":{let s=n[0];if(w(s,"String"))return N(Array.from(s.String).length);if(w(s,"Id"))return N(Array.from(s.Id).length);if(w(s,"Array"))return N(s.Array.length);if(w(s,"Row"))return N(Object.keys(s.Row).length);if(w(s,"Map"))return N(Object.keys(s.Map).length);throw new y("E_TYPE","len expects string, array, or map")}case"Slice":{let s=Math.max(0,B(n[1])),o=Math.max(0,B(n[2]));if(w(n[0],"Array"))return{Array:n[0].Array.slice(s,o)};if(w(n[0],"String"))return{String:Array.from(n[0].String).slice(s,o).join("")};throw new y("E_TYPE","slice expects array or string")}case"Concat":{let[s,o]=n;if(w(s,"String")||w(o,"String"))return{String:_t(s)+_t(o)};if(w(s,"Id")&&w(o,"Id"))return{Id:oe([s,o])};if(w(s,"Array")&&w(o,"Array"))return{Array:s.Array.concat(o.Array)};throw new y("E_TYPE","concat operands differ")}case"Min":return D(n[0],n[1])<=0?n[0]:n[1];case"Max":return D(n[0],n[1])>=0?n[0]:n[1];case"Divmod":{let s=B(n[0]),o=B(n[1]);if(o===0)throw new y("E_DIV_ZERO","division by zero");let a=Math.trunc(s/o),u=s-a*o;return u<0&&(o>0?(a-=1,u+=o):(a+=1,u-=o)),st({quotient:N(a),remainder:N(u),sink:{String:i.remainder_sink}})}case"Sort":{let s=ye(n[0]).slice();for(let o of s)for(let a of i.keys)A(o,a.field);return{Array:rt(s,(o,a)=>{for(let u of i.keys){let c=D(A(o,u.field),A(a,u.field));if(u.order==="Desc"&&(c=-c),c!==0)return c}return 0})}}case"DedupeById":{let s=new Set,o=[];for(let l of ye(n[0])){let d=j(A(l,"id"));s.has(d)||(s.add(d),o.push(l))}let a=this.certificate?.result_page_site,u=this.certificate?.merge_sites?.find(l=>l.site===i.site)?.take,c=a?.merge&&a.site===i.site&&Number.isInteger(u)?o.slice(0,u).at(-1):void 0;return this.trace.merges.push({site:i.site,deduplicated_union_len:o.length,last_returned_suffix:c===void 0?null:a.suffix.map(l=>O(A(c,l.name)))}),{Array:o}}case"MentionTokens":{let s=new Set,o=[];for(let a of fr(j(n[0]))){if(!a.startsWith("@"))continue;let u=Array.from(a.slice(1));for(;u.length>0&&!hn(u[0]);)u.shift();for(;u.length>0&&!hn(u[u.length-1]);)u.pop();let c=u.join("");c.length>0&&!s.has(c)&&(s.add(c),o.push({String:c}))}return{Array:o}}case"DeterministicShare":{let s=B(n[0]),o=rt(ye(n[1]).slice(),D);if(o.length===0)throw new y("E_DIV_ZERO","no recipients");if(new Set(o.map($)).size!==o.length)throw new y("E_INPUT","share recipients must be unique");let a=n[2],u=o.findIndex(d=>$(d)===$(a));if(u<0)throw new y("E_INPUT","recipient missing from shares");let c=Math.floor(s/o.length),l=s-c*o.length;return N(c+(u<l?1:0))}case"Count":case"CountCapped":return N(ye(n[0]).length);case"Sum":{let s=0;for(let o of ye(n[0]))s=It(s+B(o));return N(s)}default:throw new y("E_OPAQUE",`unsupported builtin ${r}`)}}get(e){let n=e.key.map(s=>this.expr(s)),r=this.store.lookup(e.table,e.index,n),i=r!==null&&this.checkRule(e.table,"read",null,r);return this.trace.points.push({site:e.site,table:e.table,index:e.index,key:n.map(O),digest:i?or(r):null,...typeof e.provenance=="string"?{provenance:e.provenance}:{}}),r===null?(this.trace.absences.push({site:e.site,table:e.table,index:e.index,key:n,...typeof e.provenance=="string"?{provenance:e.provenance}:{}}),"Null"):i?O(r):"Null"}scan(e){let n=e.prefix.map(p=>this.expr(p)),r=e.after===null?null:this.expr(e.after),i=e.before===null?null:this.expr(e.before);if(e.opaque_cursor&&r==="Null")r=null;else if(e.opaque_cursor&&r!==null){if(!w(r,"String"))throw new y("E_INPUT","opaque cursor must be a string");r=Ot(r.String,{table:e.table,index:e.index,order:e.order,suffix:tt(this.schema,e)})}let s=e.range===null?null:this.evaluateRange(e.range),[o,a]=L(e.take),u=o==="Literal"?a:B(this.context.args[a.name]??this.requiredEnv(a.name));if(!Number.isInteger(u)||u<0||o==="Arg"&&u>a.max)throw new y("E_FANOUT","scan take exceeded");let c=this.store.scan(e.table,e.index,n,r,i,s,e.order,u+2),l=c.length>u?"limit":"exhausted",h=c.filter(p=>this.checkRule(e.table,"read",null,p)).slice(0,u),f=tt(this.schema,e);return this.trace.ranges.push({site:e.site,table:e.table,index:e.index,...typeof e.provenance=="string"?{provenance:e.provenance}:{},prefix:n,order:e.order,take:u,after:r,before:i,gt:s?.gt??null,gte:s?.gte??null,lt:s?.lt??null,lte:s?.lte??null,rule_hash:ot(this.schema,this.schema.tables[e.table].rules.read),stop:l,lastReturnedSuffix:h.length===0?null:f.map(p=>O(A(h[h.length-1],p.name)))}),{Array:h.map(O)}}evaluateRange(e){return{gt:e.gt===null?null:this.expr(e.gt),gte:e.gte===null?null:this.expr(e.gte),lt:e.lt===null?null:this.expr(e.lt),lte:e.lte===null?null:this.expr(e.lte)}}insert(e,n){if(n=Pe(this.schema,e,n),Ue(this.schema,e,n),!this.checkRule(e,"insert",null,n))throw new y("E_RULE",`${e} insert`);if(this.checkConstraints(e,null,n,"insert"),this.store.byId(e,j(A(n,"id")))!==null)throw new y("E_CONSTRAINT",`duplicate id on ${e}`);this.store.put(e,n),this.recordWrite(e,n),this.rememberCreatedRow(e,n),this.insertedRows.push({table:e,row:O(n)}),this.ruleMemo.clear(),this.maintain(e,null,n)}update(e,n,r){let i=this.store.byId(e,j(n));if(i===null){this.missingWriteRow(e,j(n));return}let s={...Te(i),...Te(r)};this.replace(e,n,st(s))}replace(e,n,r){let i=this.store.byId(e,j(n));if(i===null)throw new y("E_INPUT",`missing ${e} row`);if(r=Pe(this.schema,e,r),Ue(this.schema,e,r),this.validateAddressedRowId(e,n,r),!this.checkRule(e,"update",i,r))throw new y("E_RULE",`${e} update`);this.checkConstraints(e,i,r,"update"),this.store.put(e,r),this.recordWrite(e,r),this.refreshCreatedPoints(e,r),this.ruleMemo.clear(),this.maintain(e,i,r)}delete(e,n){let r=this.store.byId(e,n);if(r===null){this.missingWriteRow(e,n);return}if(!this.checkRule(e,"delete",null,r))throw new y("E_RULE",`${e} delete`);this.checkConstraints(e,r,r,"delete"),this.store.remove(e,n),this.writes.set(`${e}\0${n}`,{table:e,id:n,row:null}),this.forgetCreatedPoints(e,n),this.ruleMemo.clear(),this.maintain(e,r,null)}missingWriteRow(e,n){if(!this.store.authorityAbsence(e,n)){this.partial.add("missing-authority"),this.authorityMissSerial+=1;return}throw new y("E_REQUIRE","program requirement failed","NOT_FOUND")}maintain(e,n,r){for(let i of this.schema.maintains??[])i.source===e&&(n!==null&&this.applyAggregate(i,n,-1),r!==null&&this.applyAggregate(i,r,1))}applyAggregate(e,n,r){n=Pe(this.schema,e.source,n);let i=e.by.map(p=>O(A(n,p))),s=oe(i),[o,a]=L(e.kind),u=o==="Count"?r:It(r*B(A(n,a.of))),c=this.store.byId(e.target,s);if(c===null&&!this.store.authorityAbsence(e.target,s)){this.partial.add("missing-authority"),this.authorityMissSerial+=1,this.unheldMaintainTargets.push(e.target);return}let l=c===null?0:B(A(c,"value")),d=Object.assign(Object.create(null),{id:{Id:s},value:N(l+u)});e.by.forEach((p,g)=>{d[p]=i[g]});let h=Pe(this.schema,e.target,st(d)),f=c===null?"insert":"update";Ue(this.schema,e.target,h),this.checkConstraints(e.target,c,h,f),this.store.put(e.target,h),this.recordWrite(e.target,h),c===null?(this.rememberCreatedRow(e.target,h),this.insertedRows.push({table:e.target,row:O(h)})):this.refreshCreatedPoints(e.target,h),this.ruleMemo.clear()}recordWrite(e,n){let r=j(A(n,"id"));this.writes.set(`${e}\0${r}`,{table:e,id:r,row:O(n)})}validateAddressedRowId(e,n,r){Hn(e,"addressed write",j(n),j(A(r,"id")))}rememberCreatedRow(e,n){let r=j(A(n,"id"));this.createdRows.add(`${e}\0${r}`),this.refreshCreatedPoints(e,n)}refreshCreatedPoints(e,n){let r=j(A(n,"id"));if(this.createdRows.has(`${e}\0${r}`)){this.forgetCreatedPoints(e,r);for(let[i,s]of Object.entries(this.schema.tables[e]?.indexes??{}))this.createdPoints.push({table:e,index:i,key:oe(s.columns.map(o=>Y(n,o))),rowId:r})}}forgetCreatedPoints(e,n){this.createdPoints=this.createdPoints.filter(r=>r.table!==e||r.rowId!==n)}checkConstraints(e,n,r,i){let s=this.schema.tables[e];for(let o of s.constraints??[]){let[a,u]=L(o);if(a==="AppendOnly"&&i!=="insert")throw new y("E_CONSTRAINT",`${e} is appendOnly`);if(a==="Immutable"&&i==="update"&&u.fields.some(c=>$(A(n,c))!==$(A(r,c))))throw new y("E_CONSTRAINT",`${e} immutable fields changed`);if(a==="Unique"&&this.checkUnique(e,u.index,n,r),a==="Cap"){if(!(i==="insert"||i==="update"&&u.by.some(f=>$(A(n,f))!==$(A(r,f)))))continue;let l=Object.entries(s.indexes).find(([,f])=>ur(f.columns,u.by));if(l===void 0)throw new y("E_SCHEMA","cap index missing");let d=u.by.map(f=>A(r,f));if(this.store.scan(e,l[0],d,null,null,null,"Asc",u.max).length>=u.max)throw new y("E_CONSTRAINT",`${e} cap reached`);this.store.hasCompleteRange(e,l[0],d)||this.partial.add(`${e}.${l[0]}`)}if(a==="Text"&&(i==="insert"||i==="update")){let c=Te(r)[u.field];if(c!==void 0&&c!=="Null"){let l=j(c);if(Array.from(l).length<(u.min??0))throw new y("E_CONSTRAINT",`${e}.${u.field} must contain at least ${u.min??0} characters`);if(!(u.format===void 0||u.format===null||u.format==="handle"&&/^[a-z0-9_]*$/.test(l)||u.format==="url"&&cr(l)))throw new y("E_CONSTRAINT",`${e}.${u.field} has invalid ${String(u.format)} format`)}}}for(let[o,a]of Object.entries(s.indexes))a.unique&&this.checkUnique(e,o,n,r)}checkFinalConstraints(){for(let{table:e,row:n}of this.insertedRows)for(let r of this.schema.tables[e]?.constraints??[]){let[i,s]=L(r);if(i!=="FinalExistsOnInsert")continue;let o=s.key.map(a=>this.ruleTerm(a,null,n));if(this.store.lookup(s.table,s.index,o)===null)throw new y("E_CONSTRAINT",`${e} insert requires final row at ${s.table}.${s.index}`)}}checkUnique(e,n,r,i){let o=this.schema.tables[e].indexes[n].columns.map(u=>Y(i,u)),a=this.store.lookup(e,n,o);if(a!==null&&(r===null||j(A(a,"id"))!==j(A(r,"id"))))throw new y("E_CONSTRAINT",`sealed unique conflict on ${e}.${n}`);n!=="byId"&&a===null&&!this.store.hasAbsence(e,n,o)&&!this.store.hasCompleteRange(e,n,o)&&this.partial.add(`${e}.${n}`)}checkRule(e,n,r,i){if(n==="read"&&this.store.readable(e))return!0;let s=this.schema.tables[e].rules[n],o=this.authorityMissSerial,a=this.pendingVerdicts;this.pendingVerdicts=[];let u=this.evaluateRule(s,ot(this.schema,s),r,i,n==="insert")&&this.authorityMissSerial===o;if(u)for(let c of this.pendingVerdicts){let l=`${c.rule_hash}\0${c.inputs_digest}\0${c.result}`;this.tracedVerdicts.has(l)||(this.tracedVerdicts.add(l),this.trace.verdicts.push(c))}return this.pendingVerdicts=a,u}evaluateRule(e,n,r,i,s){let[o,a]=L(e);switch(o){case"Public":case"Allow":return!0;case"Deny":return!1;case"Eq":return $(this.ruleTerm(a[0],r,i))===$(this.ruleTerm(a[1],r,i));case"Ne":return $(this.ruleTerm(a[0],r,i))!==$(this.ruleTerm(a[1],r,i));case"And":return a.every(u=>this.evaluateRule(u,n,r,i,s));case"Or":return a.some(u=>this.evaluateRule(u,n,r,i,s));case"Not":return!this.evaluateRule(a,n,r,i,s);case"Exists":{let u=a.key.map(p=>this.ruleTerm(p,r,i)),c=ie(we([a.table,a.index,u.map(pe)])),l=`${n}:${c}`,d=this.ruleMemo.get(l);if(d!==void 0)return this.pendingVerdicts.push({rule_hash:n,inputs_digest:c,result:d}),d;if(!this.ruleInputIsReadable(a)){let p=this.store.verdict(n,c,this.context);return p!==null?(this.ruleMemo.set(l,p),this.pendingVerdicts.push({rule_hash:n,inputs_digest:c,result:p}),p):(this.partial.add("missing-authority"),this.authorityMissSerial+=1,!1)}let h=this.store.lookup(a.table,a.index,u);if(h===null&&!this.store.hasAbsence(a.table,a.index,u))return this.partial.add(`${a.table}.${a.index}`),this.ruleMemo.set(l,!1),!1;let f=h!==null;return this.ruleMemo.set(l,f),this.pendingVerdicts.push({rule_hash:n,inputs_digest:c,result:f}),f}case"Created":{if(!s)throw new y("E_SCHEMA","created-row probe evaluated outside a table insert rule");let u=a.key.map(l=>this.ruleTerm(l,r,i)),c=oe(u);return this.createdPoints.some(l=>l.table===a.table&&l.index===a.index&&l.key===c)}default:throw new y("E_OPAQUE",`unsupported rule ${o}`)}}ruleInputIsReadable(e){let n=this.schema.tables[e.table],r=n?.indexes?.[e.index];if(!n||!r)return!1;let i=s=>{let[o,a]=L(s);if(o==="Public"||o==="Allow")return!0;if(o==="Eq"){let u=pn(a[0],r.columns,e.key),c=pn(a[1],r.columns,e.key);return u!==null&&c!==null&&we(u)===we(c)}if(o==="And")return a.length>0&&a.every(i);if(o==="Or")return a.some(i);if(o==="Exists"&&a.table===e.table&&a.index===e.index){let u=a.key.map(c=>pn(c,r.columns,e.key));return u.every(c=>c!==null)&&we(u)===we(e.key)}return!1};return i(n.rules.read)}ruleTerm(e,n,r){let[i,s]=L(e);if(i==="Field")return O(A(r,s));if(i==="NextField"){if(n===null)throw new y("E_SCHEMA","next-row rule term evaluated outside an update rule");return O(A(r,s))}if(i==="OldField"){if(n===null)throw new y("E_SCHEMA","old-row rule term evaluated outside an update rule");return O(A(n,s))}if(i==="Viewer")return{Id:this.context.viewer};if(i==="Literal")return O(s);throw new y("E_OPAQUE",`unsupported rule term ${i}`)}requiredEnv(e){let n=this.env.get(e);if(n===void 0)throw new y("E_INPUT",`unknown variable ${e}`);return n}};function pn(t,e,n){let[r,i]=L(t);if(r==="OldField"||r==="NextField")return null;if(r!=="Field")return O(t);let s=e.indexOf(i);return s<0||s>=n.length?null:O(n[s])}function Vi(t,e,n){let r=e?.result_page_site;if(!r||!yr(e,n))return null;let i=r.merge?n.merges.slice().reverse().find(s=>s.site===r.site)?.last_returned_suffix:n.ranges.slice().reverse().find(s=>s.site===r.site)?.lastReturnedSuffix;return i==null?null:on({table:r.table,index:r.index,order:r.order,suffix:r.suffix,values:i})}function pr(t,e){return yr(t,e)?"capped":"complete"}function yr(t,e){return t.completeness==="Capped"||e.ranges.some(n=>n.stop==="limit"||!t.read_sites?.find(r=>r.site===n.site)?.hoist)?!0:(t.merge_sites??[]).some(n=>{let r=e.merges.find(o=>o.site===n.site),i=r===void 0||r.deduplicated_union_len>n.take,s=e.ranges.some(o=>n.lane_sites.includes(o.site)&&o.stop!=="exhausted");return i||s})}function mr(t,e,n,r,i){return t.find(o=>o.rule_hash===e&&o.pinned_inputs_digest===n&&o.principal===r&&o.auth_epoch===i)?.result??null}function gr(t,e,n,r){return t.some(([i,s,o])=>i===e&&s==="byId"&&r(o,[{Id:n}]))}var Ct=class t{constructor(e,n,r={}){this.schema=e;this.options=r;this.tables=new Map;this.rangeDeletions=new Map;this.readableTables=new Set(r.readable??[]),this.coverage=this.receiptForSchema(n),this.seedReceipt(n)}readable(e){return this.readableTables.has(e)}applyMutation(e,n){fn(this.schema,e,n.args);let r=this.fork(),i=r.coveredIndexKeys(),s=new at(r,this.schema,n,null),o;try{o=s.execute(e)}catch(l){if(s.coverageMisses().includes("missing-authority"))return{state:"partial",partialSites:["missing-authority"],execution:{result:"Null",trace:s.trace,next:null,writes:[]}};throw l instanceof y&&(l.trace=s.trace,l.partialSites=this.uncoveredSites(s.trace,s.coverageMisses())),l}let a=s.coverageMisses(),u=this.uncoveredSites(o.trace);if(a.length>0)return{state:"partial",partialSites:a,execution:o,uncoveredSites:u,authorityMisses:s.authorityMisses()};let c=r.coveredIndexKeys();for(let l=0;l<i.length;l+=1)for(let[d,h]of i[l]){let f=c[l].get(d);if(f===void 0||!H(h,f)){let p=r.coverage.ranges[l].site;r.rangeDeletions.set(p,(r.rangeDeletions.get(p)??0)+1)}}return this.tables=r.tables,this.coverage=r.coverage,this.rangeDeletions=r.rangeDeletions,this.drained=void 0,{state:"predicted",partialSites:[],execution:o,uncoveredSites:u}}reexecute(e,n,r=null){fn(this.schema,e,n.args);let i=new at(this,this.schema,n,r),s;try{s=i.execute(e)}catch(a){throw a instanceof y&&(a.trace=i.trace,a.partialSites=this.uncoveredSites(i.trace,i.coverageMisses())),a}let o=this.uncoveredSites(s.trace,i.coverageMisses());return o.length>0&&(s.next=null),{state:o.length===0?"fresh":"partial",partialSites:o,execution:s}}uncoveredSites(e,n=[]){let r=new Set(n);for(let i of e.ranges)(!(this.coverage.ranges.some(o=>yn(o)&&qi(o,i))||this.drainedPrefixCovers(i.table,i.index,i.prefix,i.rule_hash))||(this.rangeDeletions.get(i.site)??0)>1)&&r.add(i.site);for(let i of e.absences)this.coverage.absences.some(([o,a,u])=>o===i.table&&a===i.index&&H(u,i.key))||this.lookup(i.table,i.index,i.key)!==null||r.add(i.site);return Array.from(r).sort(U)}rehydrate(e){let n=this.allIds();this.tables=new Map,this.coverage=this.receiptForSchema(e),this.rangeDeletions=new Map,this.drained=void 0,this.seedReceipt(e);let r=this.allIds(),i=0;for(let s of n)r.has(s)||(i+=1);return i}rows(e){return Array.from(this.tables.get(e)?.values()??[])}lookup(e,n,r){let i=this.index(e,n);if(r.length!==i.columns.length)throw new y("E_TYPE",`point read ${e}.${n} supplied ${r.length} of ${i.columns.length} key columns`);r.forEach((s,o)=>{ut(s,`point read ${e}.${n} key component ${o+1}`)});for(let s of this.rows(e)){let o=i.columns.map(a=>Y(s,a));if(H(o,r))return s}return null}scan(e,n,r,i,s,o,a,u){let c=this.index(e,n);if(r.length>c.columns.length)throw new y("E_TYPE",`scan ${e}.${n} prefix has too many columns`);r.forEach((b,S)=>{ut(b,`scan ${e}.${n} prefix component ${S+1}`)});for(let[b,S]of Object.entries(o??{}))S!=null&&ut(S,`scan ${e}.${n} range.${b}`);let l=r.length,d=c.columns.length-l;if(d===0&&(i!==null||s!==null))throw new y("E_TYPE",`scan ${e}.${n} prefix names every index column, so a cursor has no position to compare; remove after/before or shorten the prefix`);let h=b=>{let S;if(w(b,"Array")){if(b.Array.length!==d)throw new y("E_TYPE",`cursor supplied ${b.Array.length} of ${d} remaining index columns`);S=b.Array}else if(d===1)S=[b];else throw new y("E_TYPE",`cursor for ${d} remaining index columns must be an array`);return S.forEach((R,I)=>{let be=c.columns[l+I];Ni(this.schema,e,n,be,R)}),S},f=i===null?null:h(i),p=s===null?null:h(s),g=this.rows(e).filter(b=>{let S=c.columns.map(be=>Y(b,be));if(!H(S.slice(0,r.length),r))return!1;if(l>=S.length)return!0;let R=S[l],I=S.slice(l);return!(f!==null&&$t(I,f)*(a==="Asc"?1:-1)<=0||p!==null&&$t(I,p)*(a==="Asc"?1:-1)>=0||o?.gt!==null&&o?.gt!==void 0&&D(R,o.gt)<=0||o?.gte!==null&&o?.gte!==void 0&&D(R,o.gte)<0||o?.lt!==null&&o?.lt!==void 0&&D(R,o.lt)>=0||o?.lte!==null&&o?.lte!==void 0&&D(R,o.lte)>0)}),m=a==="Asc"?1:-1;return g.sort((b,S)=>{for(let R of c.columns){let I=D(Y(b,R),Y(S,R));if(I!==0)return I*m}return U(j(A(b,"id")),j(A(S,"id")))*m}),g.slice(0,u)}put(e,n){let r=Pe(this.schema,e,n);Ue(this.schema,e,r);for(let[o,a]of Object.entries(this.schema.tables?.[e]?.indexes??{}))for(let u of a.columns)ut(Y(r,u),`indexed column ${e}.${o}.${u}`);let i=j(A(r,"id")),s=this.tables.get(e);s===void 0&&(s=new Map,this.tables.set(e,s)),s.set(i,r)}remove(e,n){let r=this.tables.get(e),i=r?.get(n)??null;return r?.delete(n),i}byId(e,n){return this.tables.get(e)?.get(n)??null}verdict(e,n,r){return mr(this.coverage.verdicts,e,n,r.viewer,r.auth_epoch)}authorityAbsence(e,n){return gr(this.coverage.absences,e,n,H)}hasAbsence(e,n,r){return this.coverage.absences.some(([i,s,o])=>i===e&&s===n&&H(o,r))}hasCompleteRange(e,n,r){let i=this.schema.tables?.[e]?.rules?.read;return i!==void 0&&this.drainedPrefixCovers(e,n,r,ot(this.schema,i))?!0:this.coverage.ranges.some(s=>yn(s)&&s.table===e&&s.index===n&&H(s.prefix,r)&&s.order==="Asc"&&s.after===null&&s.before===null&&s.gt===null&&s.gte===null&&s.lt===null&&s.lte===null&&s.stop==="Exhausted")}drainedPrefixCovers(e,n,r,i){let s=this.schema.tables?.[e]?.indexes?.[n]?.columns;return s?this.drainedPrefixes().some(o=>o.table===e&&o.ruleHash===i&&o.columns.every((a,u)=>{let c=s.indexOf(a);return c>=0&&c<r.length&&H([r[c]],[o.prefix[u]])})):!1}drainedPrefixes(){if(this.drained)return this.drained;let e=new Map;for(let r of this.coverage.ranges){if(r.before!==null||r.gt!==null||r.gte!==null||r.lt!==null||r.lte!==null)continue;let i=[r.table,r.index,r.order,r.rule_hash,oe(r.prefix)].join("\0"),s=e.get(i);s||e.set(i,s=[]),s.push(r)}let n=[];for(let r of e.values()){let i=r.filter(h=>h.after===null);if(i.length===0)continue;let s=this.schema.tables?.[i[0].table]?.indexes?.[i[0].index];if(!s)continue;let o=s.columns.slice(i[0].prefix.length),a=o[o.length-1]==="id",u=r.filter(h=>h.after!==null),c=h=>w(h.after,"Array")?h.after.Array:[h.after],l=h=>{let f=h.row_ids[h.row_ids.length-1];if(f===void 0)return;let p=this.byId(h.table,f);if(p!==null){let g=o.map(m=>Y(p,m));return u.find(m=>H(c(m),g))}if(a)return u.find(g=>{let m=c(g);return m.length===o.length&&H([m[m.length-1]],[{Id:f}])})};i.some(h=>{let f=new Set,p=h;for(;p!==void 0&&!f.has(p);){if(!yn(p))return!1;if(f.add(p),p.stop==="Exhausted")break;p=l(p)}if(p===void 0||p.stop!=="Exhausted")return!1;let g=new Set;for(let m of f)for(let b of m.row_ids)g.add(b);return r.every(m=>f.has(m)||m.row_ids.every(b=>g.has(b)))})&&n.push({table:i[0].table,ruleHash:i[0].rule_hash,columns:s.columns.slice(0,i[0].prefix.length),prefix:i[0].prefix})}return this.drained=n,n}seedReceipt(e){for(let n of e.rows)this.put(n.table,n.row)}receiptForSchema(e){let n=O(e);return n.schema_hash!==ie(qe(this.schema))&&(n.absences=[]),n}fork(){let e=new t(this.schema,{rows:[],ranges:[],absences:[],verdicts:[]},this.options);return e.tables=new Map(Array.from(this.tables,([n,r])=>[n,new Map(Array.from(r,([i,s])=>[i,O(s)]))])),e.coverage=O(this.coverage),e.rangeDeletions=new Map(this.rangeDeletions),e}coveredIndexKeys(){return this.coverage.ranges.map(e=>{let n=new Set(e.row_ids);e.halo!==null&&n.add(e.halo.id);let r=this.index(e.table,e.index),i=new Map;for(let s of this.rows(e.table)){let o=j(A(s,"id"));n.has(o)&&i.set(o,r.columns.map(a=>O(Y(s,a))))}return i})}allIds(){let e=new Set;for(let[n,r]of this.tables)for(let i of r.keys())e.add(`${n}:${i}`);return e}index(e,n){let r=this.schema.tables?.[e]?.indexes?.[n];if(r===void 0)throw new y("E_SCHEMA",`missing index ${e}.${n}`);return r}};function yn(t){return t.evicted_ids===void 0||t.evicted_ids.length===0}function Le(t,e){return t===null?e===null:e!==null&&H([t],[e])}function qi(t,e){return t.site===e.site&&t.table===e.table&&t.index===e.index&&H(t.prefix,e.prefix)&&t.order===e.order&&t.take===e.take&&Le(t.after,e.after)&&Le(t.before,e.before)&&Le(t.gt,e.gt)&&Le(t.gte,e.gte)&&Le(t.lt,e.lt)&&Le(t.lte,e.lte)&&t.rule_hash===e.rule_hash}function Ni(t,e,n,r,i){ut(i,`cursor component for ${e}.${n} column ${r}`);let s=ae(i);if(s==="Null")return;let o=t.tables?.[e]?.columns?.[r],a=wr(o);if(!(a==="scalar"||a===s))throw new y("E_TYPE",`cursor component for ${e}.${n} column ${r} must be ${a}, got ${s.toLowerCase()}`)}function ut(t,e){let n=ae(t);if(!["Null","Bool","Int","String","Id","Bytes"].includes(n))throw new y("E_TYPE",`${n.toLowerCase()} is not an indexable scalar (${e})`)}function wr(t){return t?.Optional!==void 0?wr(t.Optional):t==="Id"||t==="Principal"||t?.Ref!==void 0?"Id":t?.Text!==void 0||t?.Enum!==void 0?"String":["Int","Time"].includes(t)||t?.Decimal!==void 0||t?.Money!==void 0?"Int":t==="Bool"?"Bool":t?.Bytes!==void 0?"Bytes":"scalar"}function jt(t){return`${t.table} ${t.id}`}var br=new WeakMap;function Bi(t){let e=typeof t=="object"&&t!==null?br.get(t):void 0;if(e!==void 0)return e;let n=Yt(t);return typeof t=="object"&&t!==null&&br.set(t,n),n}function vr(t,e,n){let r=Bi(e);if(n!==void 0&&n!==r)throw new Q("schema",`hash ${r} does not match the held program's ${n}`);let i=new Map;for(let s of t.rows)i.set(jt(s),{table:s.table,id:s.id,row:vt(e,s.table,s.row)});return{schema_hash:r,rows:[...i.values()],ranges:t.ranges.map(s=>Di(e,s,i)),absences:t.absences.map(([s,o,a])=>[s,o,nn(e,s,o,a,0)]),verdicts:t.verdicts.map(s=>{let o=s;return{rule_hash:String(o.ruleHash),pinned_inputs_digest:String(o.pinnedInputsDigest),principal:String(o.principal),auth_epoch:Number(o.authEpoch),result:o.result===!0}})}}function Di(t,e,n){let r=s=>s==null?null:Jn(t,e,s),i=e.haloId===void 0?void 0:n.get(jt({table:e.table,id:e.haloId}));return{site:e.site,table:e.table,index:e.index,prefix:nn(t,e.table,e.index,e.prefix,0),order:e.order,take:e.take,after:r(e.after),before:r(e.before),gt:r(e.gt),gte:r(e.gte),lt:r(e.lt),lte:r(e.lte),rule_hash:e.ruleHash,row_ids:[...e.rowIds],stop:e.stop,absence:e.absence,halo:i===void 0?null:structuredClone(i),n2_key:null,...e.evictedIds===void 0||e.evictedIds.length===0?{}:{evicted_ids:[...e.evictedIds]}}}function Rr(t,e,n){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&"Optional"in t)return e==null?"Null":Rr(t.Optional,e,n);if(t==="Cursor"){if(e==null)return"Null";if(typeof e!="string")throw new TypeError(`${n} must be an opaque cursor string`);return{String:e}}if(e===void 0)throw new TypeError(`${n} is required`);return Kn(t,e,n)}function xr(t,e){let n=Object.create(null);if(t===null||typeof t!="object")return n;let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};for(let[i,s]of Object.entries(t))n[i]=Rr(s,r[i],`args.${i}`);return n}function ct(t,e,n){let r=new Set((n.evicted??[]).map(jt)),i=new Set(n.ranges.filter(s=>(s.evictedIds?.length??0)>0).map(s=>s.table));return t.map(s=>{let o=e.absences.find(c=>c.site===s),a=e.ranges.find(c=>c.site===s),u=o?.provenance??a?.provenance;if(o&&o.index==="byId"){let c=o.key[0],l=c!==null&&typeof c=="object"&&"Id"in c?String(c.Id):void 0;if(l!==void 0&&r.has(jt({table:o.table,id:l})))return{site:s,reason:"evicted"}}return a&&i.has(a.table)?{site:s,reason:"evicted"}:u==="Shape"?{site:s,reason:"computed-key"}:{site:s,reason:"never-held"}})}function mn(t,...e){try{return t(...e)}catch(n){if(!(n instanceof TypeError||n instanceof y))throw n;globalThis.__snapbackTwinLast=`tagged:${String(n)}`}}function me(t){globalThis.__snapbackTwinLast=t}var Vt=class{constructor(e){this.sources=e}async evaluate(e,n){let r=await this.hydrate();if(!r)return me("hydrate");let i=r.program.programs[e];if(!i||i.kind!=="query")return me("unknown-op");let s=i.ir,o=this.context(r,s,n,[]);if(!o)return me("context");let a=r.coverage.deliveredAt,u={seq:this.sources.seq(),...a===void 0?{}:{since:a},...r.predicted.length?{predicted:r.predicted}:{}},c=(l,d,h)=>{let f=ct(l,d,r.coverage);return{state:"partial",...h===void 0?{}:{data:h},reason:f[0]?.reason??"never-held",...f[0]===void 0?{}:{site:f[0].site},sites:f,...u}};try{let l=r.store.reexecute(s,o,i.certificate),d=l.execution.result,h=d==="Null"&&l.state!=="fresh"?void 0:pe(d);return l.state==="fresh"?{state:pr(i.certificate,l.execution.trace),data:h,next:l.execution.next,...u}:c(l.partialSites,l.execution.trace,h)}catch(l){if(!(l instanceof y))throw l;if(l.trace&&l.partialSites?.length)return c(l.partialSites,l.trace);if(l.code==="E_REQUIRE")return{state:"denied",rule:l.authoredCode??l.code,...u};throw l}}async predict(e,n,r){let i={predicted:!1,overlay:[],trace:Ke(),partialRanges:[],uncovered:[],omitted:[]},s=await this.hydrate();if(!s)return i;let o=s.program.programs[e];if(!o||o.kind!=="mutation")return i;let a=o.ir,u=this.context(s,a,n,r);if(!u)return i;let c;try{c=s.store.applyMutation(a,u)}catch(m){if(!(m instanceof y))throw m;return{...i,uncovered:m.trace&&m.partialSites?ct(m.partialSites,m.trace,s.coverage):[]}}let l=c.execution.trace,d=c.authorityMisses,h=c.state==="partial"&&c.partialSites.every(m=>m==="missing-authority")&&d?.other===0&&d.maintainTargets.length;if(c.state!=="predicted"&&!h)return{...i,uncovered:ct(c.partialSites,l,s.coverage)};let f=new Set(l.ranges.map(m=>m.site)),p=c.uncoveredSites??[],g=p.filter(m=>!f.has(m)||l.absences.some(b=>b.site===m));return g.length?{...i,uncovered:ct(g,l,s.coverage)}:{predicted:!0,overlay:c.execution.writes.map(m=>m.row===null?{table:m.table,id:m.id,row:{},removed:!0}:{table:m.table,id:m.id,row:pe(m.row)}),trace:{points:l.points.map(m=>({table:m.table,index:m.index,key:m.key.map(pe),digest:m.digest})),verdicts:l.verdicts.map(m=>({ruleHash:m.rule_hash,inputsDigest:m.inputs_digest,result:m.result}))},partialRanges:p,uncovered:[],omitted:[...new Set(d?.maintainTargets??[])]}}context(e,n,r,i){let s=this.sources.principal();if(s===void 0)throw new TypeError("no partition is open");let o=mn(xr,n.args,r);return o&&{viewer:s,principal_kind:"user",auth_epoch:e.coverage.facts?.authEpoch??0,args:o,now:this.sources.now(),new_ids:[...i],read_time:null}}async hydrate(){let e=this.sources.program();if(!e)return me("no-program");let n=await this.sources.coverage();if(!n)return me("no-coverage");if(n.superseded)return me("superseded");if(n.facts&&(n.facts.generation!==e.generation||n.facts.schemaHash!==e.schemaHash))return me(`facts:${n.facts.generation}/${e.generation}`);let r=Object.keys(e.schema.tables??{}).filter(c=>e.schema.tables[c]?.retain==="delivered-history"),i=await this.sources.overlay(),s=await this.sources.entries(),o=[],a=mn(vr,n,e.schema,e.schemaHash);if(!a)return me("closure");let u=new Ct(e.schema,a,{readable:r});for(let c of s){let l=i[c.intent];if(l){for(let d of l)if(d.removed)u.remove(d.table,d.id);else{let h=mn(vt,e.schema,d.table,d.row);if(!h)return me(`overlay-row:${d.table}`);u.put(d.table,h)}o.push(c.intent)}}return{program:e,coverage:n,store:u,predicted:o}}};function Mi(t){if(!C(t))return;let e=t.certificate;if(!C(e)||!Array.isArray(e.write_sites))return;let n=0;for(let r of e.write_sites)C(r)&&(r.kind==="Insert"||r.kind==="Upsert")&&Number.isSafeInteger(r.max_rows)&&(n+=Number(r.max_rows));return n}function Fi(t){if(!C(t))return;let{generation:e,schemaHash:n,schema:r,programs:i}=t;if(typeof e!="string"||typeof n!="string"||!C(r)||!C(r.tables)||!C(i))return;let s={};for(let[o,a]of Object.entries(i))!C(a)||a.kind!=="query"&&a.kind!=="mutation"||typeof a.planHash!="string"||!C(a.ir)||!C(a.certificate)||a.certificate.plan_hash===a.planHash&&(s[o]={kind:a.kind,planHash:a.planHash,ir:a.ir,certificate:a.certificate});return{generation:e,schemaHash:n,schema:r,programs:s}}var Ie=class extends Error{code="E_OFFLINE_AUTHORITY";constructor(e){super(e),this.name="OfflineAuthorityError"}};function C(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ui(t){if(C(t))for(let e of Object.keys(t).sort()){let n=t[e];if(n==="Cursor"||C(n)&&n.Optional==="Cursor")return e}}function Ar(t){return`${t.table}\0${t.id}`}function qt(t,e,n){if(!C(t))return Array.isArray(t)&&Array.isArray(e)?e.map((i,s)=>qt(t[s],i,n)):e;let r=t.$row;if(C(r)&&Object.keys(t).length===1){if(typeof r.table=="string"&&typeof r.id=="string"&&Object.keys(r).length===2)return n.has(Ar({table:r.table,id:r.id}))?null:e;if(C(r.$value)&&C(e))return qt(r.$value,e,n)}return C(e)?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,qt(t[i],s,n)])):e}function kr(t,e,n){return t?t===e||t===Be(e,n):!1}var Nt=class{constructor(e){this.options=e;this.store=e.store(),this.fenceDays=e.fenceDays??7,this.maxAssetBytes=e.maxAssetBytes??256*1024*1024,this.bytes=new xt(this.store,{maxAssetBytes:this.maxAssetBytes,viewOnce:e.viewOnce}),this.outbox=new Rt(this.store,{now:()=>Date.now(),fenceMs:this.fenceDays*24*60*60*1e3}),this.twin=new Vt({program:()=>this.held,coverage:()=>this.coverage(),overlay:()=>this.store.outbox.overlay(),entries:()=>this.outbox.entries(),principal:()=>this.partition,now:()=>Date.now(),seq:()=>this.latestSeq})}store;fenceDays;maxAssetBytes;bytes;outbox;drainTail=Promise.resolve();drainOutcome=Promise.resolve();twin;partition;retention={};cursors={};schema;facts;superseded;latestSeq=0;sessionEpoch;pendingGrant;pendingBounds;pendingProgram;held;standIn;resumeQueries=[];tail=Promise.resolve();coverageRevision=0;get principal(){return this.partition}get programGeneration(){return this.held?.generation}get resetNeeded(){return this.superseded!==void 0}async evaluate(e,n){if(this.partition!==void 0)return this.twin.evaluate(e,n)}async predict(e,n,r){return this.twin.predict(e,n,r)}get seq(){return this.latestSeq}async open(e,n=!1){this.partition!==e&&this.outbox.resetTrust(),this.partition!==void 0&&this.partition!==e&&this.bytes.forget(),await this.serial(async()=>{this.partition!==e&&(this.outbox.resetTrust(),this.facts=void 0,this.superseded=void 0,this.held=void 0,this.standIn=void 0,this.drainOutcome=Promise.resolve()),this.partition!==void 0&&this.partition!==e&&await this.store.wipe(this.partition),this.partition!==e&&(this.coverageRevision+=1,this.facts=this.superseded=this.held=void 0,this.latestSeq=0,this.sessionEpoch=void 0),await this.store.open(e),n&&await this.store.unseal(),this.partition=e,this.bytes.bind(e),await this.loadFacts(),await this.loadProgram(),await this.flushGrant(),await this.flushBounds(),this.outbox.notify()})}async reauthenticate(e){await this.serial(async()=>{if(this.partition!==e)throw new Ie(`authenticated principal ${e} does not match the open offline partition`);await this.store.unseal(),await this.loadFacts(),await this.loadProgram(),await this.flushGrant(),await this.flushBounds(),this.outbox.notify()})}noteGrant(e){let n=er(e);return n&&(this.pendingGrant=n),e}async adoptPendingGrant(){await this.serial(()=>this.flushGrant())}standInLog(e){return this.standIn!==void 0&&this.standIn===Be(e.op,e.args)}async queuedIntents(){return this.partition===void 0?[]:this.outbox.queued()}async seal(){this.outbox.resetTrust(),this.partition!==void 0&&await this.serial(async()=>{this.bytes.forget(),await this.store.seal(),this.outbox.notify()})}async wipe(){this.outbox.resetTrust(),await this.serial(async()=>{if(this.partition===void 0)return;let e=this.partition;this.coverageRevision+=1,this.partition=void 0,this.facts=void 0,this.superseded=void 0,this.held=void 0,this.sessionEpoch=void 0,this.bytes.bind(void 0),await this.store.wipe(e),this.outbox.notify()})}async close(){this.outbox.resetTrust(),await this.tail,this.outbox.close(),this.bytes.forget(),await this.store.close?.()}manifest(e){let n=e.tables??e.schema?.tables??{},r={};for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object")continue;let a=o.retain;(a==="until-revoked"||a==="delivered-history")&&(r[s]=a)}this.retention=r;let i={};for(let[s,o]of Object.entries(e.ops??{})){let a=Ui(o?.args);a!==void 0&&(i[s]=a)}this.cursors=i,this.resumeQueries=Object.entries(e.ops??{}).flatMap(([s,o])=>o.kind!=="query"||!C(o.args)?[]:Object.values(o.args).every(a=>C(a)&&"Optional"in a)?[{op:s,args:Object.fromEntries(Object.keys(o.args).map(a=>[a,null])),drain:!1}]:[]),e.schema?.tables&&(this.schema=e.schema)}cursorArg(e){return this.cursors[e]??"c"}async program(e,n){if(E(n),!C(e)||!C(e.programs))return;let r={};for(let[s,o]of Object.entries(e.programs)){let a=Mi(o);a!==void 0&&(r[s]=a)}let i=Fi(e);await this.serial(()=>(E(n),this.outbox.write(async()=>{E(n),this.partition!==void 0?(await this.store.commit({bounds:r,...i?{programs:{[i.generation]:i}}:{}}),E(n)):(this.pendingBounds=r,this.pendingProgram=i),i&&(this.held=i,this.schema=i.schema),this.outbox.notify()})))}async accept(e,n,r){if(C(r)&&r.state==="unchanged"){if(Object.keys(r).sort().join(",")!=="seq,state,validator"||!Number.isSafeInteger(r.seq)||Number(r.seq)<0||typeof r.validator!="string"||!/^[0-9a-f]{64}$/.test(r.validator))throw new Q("$","conditional delivery must be { state, seq, validator }");let o=await this.answer(e,n);if(!o||o.validator!==r.validator)throw new Q("$.validator","does not match the held answer");return{result:{state:o.state,...o.data===void 0?{}:{data:o.data},...o.next===void 0?{}:{next:o.next},seq:r.seq,...o.reason===void 0?{}:{reason:o.reason},...o.rule===void 0?{}:{rule:o.rule}},refresh:{op:e,args:n,seq:r.seq,validator:r.validator,deliveredAt:Date.now()}}}if(!C(r)||r.protocol===void 0)return{result:r};let i=tn(r);return{result:{state:i.state,...i.state==="denied"?{}:{data:await this.expandUnviewed(i)},...i.state==="complete"||i.state==="capped"?{next:i.next}:{},seq:i.seq,...i.reason===void 0?{}:{reason:i.reason},...i.rule===void 0?{}:{rule:i.rule}},envelope:i}}async commit(e,n,r,i=this.coverageRevision,s){return this.commitMany([{op:e,args:n,accepted:r}],void 0,void 0,i,s)}async commitMany(e,n,r,i,s,o){if(e.length===0&&!n&&!r&&o===void 0)return!1;let a=async()=>{if(s&&!s()||i!==void 0&&i!==this.coverageRevision)return!1;if(this.partition===void 0)throw new Ie("an offline partition must be opened before committing a delivery");let u=[],c=[],l=[],d=this.facts,h=this.superseded,f=!1;for(let{op:m,args:b,accepted:S}of e){let R=S.envelope;if(R&&R.authority.principal!==this.partition)throw new Ie(`delivery principal ${R.authority.principal} does not match open partition ${this.partition}`);if(S.refresh){c.push(S.refresh);continue}if(R){if(this.sessionEpoch!==void 0&&R.authority.authEpoch!==this.sessionEpoch)throw new Ie("delivery auth epoch does not match the authenticated session");if(!d&&this.held&&(d={generation:this.held.generation,schemaHash:this.held.schemaHash,authEpoch:this.sessionEpoch??R.authority.authEpoch}),d&&(R.generation!==d.generation||R.schemaHash!==d.schemaHash)){h={generation:R.generation,schemaHash:R.schemaHash,authEpoch:R.authority.authEpoch},f=!0;continue}if(d&&R.authority.authEpoch!==d.authEpoch)throw new Ie("delivery auth epoch does not match the open coverage");d={generation:R.generation,schemaHash:R.schemaHash,authEpoch:R.authority.authEpoch}}let I=R??S.result;u.push({cursorArg:this.cursorArg(m),op:m,args:b,state:I.state,...I.data===void 0?{}:{data:I.data},...I.next===void 0?{}:{next:I.next},seq:I.seq,...R?.validator===void 0?{}:{validator:R.validator},...R?.receipt===void 0?{}:{receipt:R.receipt},...R?.rows===void 0?{}:{rows:R.rows},..."reason"in I&&typeof I.reason=="string"?{reason:I.reason}:{},..."rule"in I&&typeof I.rule=="string"?{rule:I.rule}:{},deliveredAt:Date.now()});for(let be of R?.rows??[])for(let Mt of this.options.onTombstone?.(be)??[])l.push({...Mt,seq:R.seq})}let p=f?void 0:r,g=!f&&n?{...n,cursorArg:this.cursorArg(n.op),...d?.generation===void 0?{}:{generation:d.generation},...d?.schemaHash===void 0?{}:{schemaHash:d.schemaHash},...d?.authEpoch===void 0?{}:{authEpoch:d.authEpoch},updatedAt:Date.now()}:void 0;await this.store.commit({deliveries:u,refreshes:c,tombstones:l,retention:this.retention,schema:this.schema,...g?{watermark:g}:{},...p?{outbox:p}:{},...o===void 0||f?{}:{resumeSeq:o},...d&&d!==this.facts?{facts:d}:{},...h&&h!==this.superseded?{superseded:h}:{}}),this.facts=d,this.sessionEpoch??=d?.authEpoch,this.superseded=h;for(let m of[...u,...c])this.latestSeq=Math.max(this.latestSeq,m.seq);return this.outbox.notify(),f};return this.serial(()=>r?this.outbox.write(a):a())}async answer(e,n){if(!this.coverageCurrent())return;let r=this.coverageRevision,i=await this.store.answer(e,n);return r===this.coverageRevision&&this.coverageCurrent()?i:void 0}coverageCurrent(){return this.partition!==void 0&&this.superseded===void 0&&(!this.facts||!this.held||this.facts.generation===this.held.generation&&this.facts.schemaHash===this.held.schemaHash)}async expandUnviewed(e){let n=zn(e),r=this.store;if(this.partition===void 0||typeof r.viewedRows!="function")return n;let i=new Set((await r.viewedRows()).map(Ar));return i.size===0?n:qt(e.data,n,i)}async markWatermark(e,n,r,i,s=this.coverageRevision){this.partition!==void 0&&await this.commitMany([],{op:e,args:n,watermark:r,...i===void 0?{}:{validator:i}},void 0,s)}async resumeRequest(e,n={}){if(this.partition===void 0||!this.facts)return;if(!this.coverageCurrent())return{protocol:1,...this.facts,mounted:[]};let r=await this.store.coverage(),i=De(r.watermarks),s=Math.max(0,Math.min(32,Number.isSafeInteger(n.cap)?n.cap:32)),o=e.filter(d=>!d.drain&&d.op!==i?.op&&!kr(n.which,d.op,d.args)),a=n.which?.match(/^mounted\[(\d+)\]$/)?.[1];a!==void 0&&o.splice(Number(a),1);let u=(await Promise.all(o.slice(0,s).map(async d=>({query:d,answer:await this.answer(d.op,d.args)})))).filter(d=>typeof d.answer?.validator=="string");if(!this.facts)return;if(!this.coverageCurrent())return{protocol:1,...this.facts,mounted:[]};let c=n.which==="log"||i!==void 0&&kr(n.which,i.op,i.args),l=!i&&!c?u.shift():void 0;if(this.standIn=l?Be(l.query.op,l.query.args):void 0,!(!i&&!l&&(await this.queuedIntents()).length===0))return{protocol:1,...this.facts,...l?{log:{op:l.query.op,args:l.query.args,watermark:null,validator:l.answer.validator}}:!i||c?{}:{log:{op:i.op,args:i.args,watermark:i.watermark,...i.validator===void 0?{}:{validator:i.validator}}},mounted:u.map(({query:d,answer:h})=>({op:d.op,args:d.args,validator:h.validator}))}}async resetCoverage(e,n){this.outbox.resetTrust(),this.partition!==void 0&&await this.serial(async()=>{E(n);let r=e??this.sessionEpoch??this.facts?.authEpoch,i=this.held&&r!==void 0?{generation:this.held.generation,schemaHash:this.held.schemaHash,authEpoch:r}:void 0,s=i??this.superseded??this.facts;await this.store.commit({resetCoverage:!0,facts:i,superseded:s}),this.coverageRevision+=1,this.facts=i,this.sessionEpoch=r,this.superseded=s})}async completeReset(e,n){return this.serial(async()=>(E(n),e!==this.coverageRevision?!1:this.superseded?!this.facts||!this.held||this.facts.generation!==this.held.generation||this.facts.schemaHash!==this.held.schemaHash||this.superseded.generation!==this.held.generation||this.superseded.schemaHash!==this.held.schemaHash?!1:(await this.store.commit({superseded:null}),this.superseded=void 0,!0):!0))}async coverage(){return this.partition===void 0?void 0:this.store.coverage()}async resumeSeed(e){if(this.partition===void 0)return;let n=await this.store.coverage(),r=De(n.watermarks),i=e.find(s=>s.drain);if(i)return i;if(r)return{op:r.op,args:r.args,drain:!0};for(let s of Object.keys(this.cursors)){let o=e.find(a=>a.op===s)??this.resumeQueries.find(a=>a.op===s);if(o)return o}return this.resumeQueries[0]??e[0]}async flushGrant(){let e=this.pendingGrant;if(!(!e||this.partition===void 0)){this.pendingGrant=void 0;try{await this.outbox.adopt(e)}catch(n){throw this.pendingGrant=e,n}}}async flushBounds(){let e=this.pendingBounds;if(!e||this.partition===void 0)return;let n=this.pendingProgram;this.pendingBounds=void 0,this.pendingProgram=void 0;try{await this.outbox.recordBounds(e,n===void 0?void 0:{[n.generation]:n})}catch(r){throw this.pendingBounds=e,this.pendingProgram=n,r}}async loadProgram(){let e;try{e=await this.store.outbox.programs()}catch{return}let n=Object.values(e)[0];n&&(this.held=n),n&&this.schema===void 0&&(this.schema=n.schema)}async loadFacts(){let e=await this.store.coverage();if(this.superseded=e.superseded,e.facts){this.facts=e.facts,this.sessionEpoch??=e.facts.authEpoch;return}let n=De(e.watermarks);n?.generation&&n.schemaHash&&n.authEpoch!==void 0&&(this.facts={generation:n.generation,schemaHash:n.schemaHash,authEpoch:n.authEpoch})}serial(e){let n=this.tail.then(e);return this.tail=n.then(()=>{},()=>{}),n}};function Sr(t,e){let n=t!==void 0&&(t.state==="complete"||t.state==="capped");if(!(e!==void 0&&!(e.state==="partial"&&n)&&!t?.retained)){if(!t)return{state:"hydrating",live:!1,connection:"offline"};let{op:a,args:u,receipt:c,validator:l,deliveredAt:d,...h}=t;return{...h,live:!1,connection:"offline",stale:{since:d}}}let{since:i,...s}=e,o=t===void 0?{}:{seq:t.seq,...t.caughtUp===void 0?{}:{caughtUp:t.caughtUp},...t.watermark===void 0?{}:{watermark:t.watermark}};return{...s,...o,live:!1,connection:"offline",stale:{since:t?.deliveredAt??i??Date.now()}}}function Or(t,e){return t?t.noteGrant(e):e}function Li(t){let e="replayed mutation response",n=M(t,e),r=typeof n.intent=="string"?{intent:n.intent}:{};if(n.state==="rejected"&&n.reason==="conflict"){if(n.site!==void 0&&typeof n.site!="string")throw P(`${e}.site must be a string`);let s=n.site;return{state:"rejected",reason:"conflict",code:"E_OFFLINE_CONFLICT",family:"offline",message:`the rows this write read have changed${s?` at ${s}`:""}`,...s===void 0?{}:{site:s},rewrite:"read the current row, then send the write again as a new intent",guide:"offline",...r}}let i=Ft(t);return i.state==="rejected"&&typeof n.reason=="string"?{...i,reason:n.reason,...r}:{...i,...r}}async function Pr(t){let{runtime:e}=t,n=async()=>Ft(await t.json("/api/mutation",{method:"POST",body:JSON.stringify({op:t.op,args:t.args})}));if(!e||e.principal===void 0)return n();let r=async()=>{try{return await e.outbox.enqueue({op:t.op,args:t.args,issuedSeq:e.seq},u=>e.predict(t.op,t.args,u))}catch(u){throw t.failure(u)}},i=u=>({state:"queued",intent:u.intent,ids:u.ids});if(t.offline)return i(await r());if((await e.queuedIntents()).length>0){let u=!0;try{({stopped:u}=await t.drain())}catch{u=!0}if(u)return i(await r())}let s=await r(),o;try{({stopped:o}=await t.drain())}catch(u){let c=await e.store.outbox.get(s.intent);if(c&&c.state!=="queued")return Er(c,e);throw u}let a=await e.store.outbox.get(s.intent);return!a||a.state==="queued"?i(s):Er(a,e)}async function Er(t,e){if(await e.outbox.dismiss(t.intent),t.state==="expired")throw new v({code:"E_OFFLINE_INTENT_EXPIRED",family:"offline",message:"the owner refused this intent because its replay grant is unknown, foreign, or older than thirty days",site:"client.outbox.replay",rewrite:"dismiss this intent, resume online for a fresh grant, then send again",guide:"offline"});return t.response}function He(t){let{runtime:e}=t,n=e.drainTail.then(()=>Hi(t));e.drainTail=n.then(()=>{},()=>{});let r=n.then(i=>i.reason==="fence"?{stopped:"fence"}:void 0);return r.catch(()=>{}),e.drainOutcome=r,n}async function Hi(t){let{runtime:e}=t;if(E(t.signal),e.principal===void 0)return{stopped:!1};for(let n of await e.outbox.queued()){E(t.signal);let r=await e.store.outbox.get(n.intent);if(E(t.signal),!r||r.state!=="queued")continue;if(!await e.outbox.canReplay(r))return{stopped:!0,reason:"fence"};E(t.signal);let i;try{i=await t.json("/api/mutation",{method:"POST",body:JSON.stringify(tr(r))})}catch(o){if(_(o)&&o.retryable)return{stopped:!0};if(_(o)&&o.envelope.family==="offline"){await gn(t,r,o.code==="E_OFFLINE_INTENT_EXPIRED"?"expired":"rejected",{state:"rejected",...ge(o.envelope,"offline refusal"),intent:r.intent});continue}throw o}E(t.signal);let s=Li(i);if(s.state==="committed"){let o=e.coverageRevision,a;try{a=await Wi(t,o)}catch(u){if(_(u)&&u.retryable)return{stopped:!0};throw u}if(E(t.signal),o!==e.coverageRevision)return{stopped:!0};if(!await gn(t,r,"committed",s,a,o))return{stopped:!0}}else await gn(t,r,"rejected",s)}return{stopped:!1}}async function gn(t,e,n,r,i,s=t.runtime.coverageRevision){let o=t.runtime.outbox.settle(e,n,r);try{E(t.signal);let a=await t.runtime.commitMany(i?[i]:[],void 0,{put:[o]},s,()=>!t.signal?.aborted);return E(t.signal),!a&&s===t.runtime.coverageRevision}catch(a){throw t.failure(a)}}async function Wi(t,e){let{runtime:n}=t,r=await n.coverage();if(E(t.signal),e!==n.coverageRevision)return;let i=r?De(r.watermarks):void 0;if(!i)return;let s=i.cursorArg??n.cursorArg(i.op),o=i.watermark===null?i.args:{...i.args,[s]:i.watermark},a=await n.answer(i.op,o);if(E(t.signal),e!==n.coverageRevision)return;let u=await t.json("/api/query?receipt=1",{method:"POST",body:JSON.stringify(a?.validator?{op:i.op,args:o,validator:a.validator}:{op:i.op,args:o})});if(E(t.signal),e!==n.coverageRevision)return;let c;try{c=await n.accept(i.op,o,u)}catch(l){throw l instanceof Q?t.shape(l.message):l}return ce(c.result),{op:i.op,args:o,accepted:c}}function Tr(t,e,n=async()=>{}){let r=async()=>{if(!t||t.principal===void 0)return[];try{return await t.outbox.entries()}catch(i){if(i instanceof Error&&/sealed/.test(i.message))return[];throw i}};return{entries:r,dismiss:async i=>{t&&t.principal!==void 0&&await t.outbox.dismiss(i)},subscribe:i=>{let s=!0,o=0,a=()=>{let c=++o,l=t?.principal;r().then(d=>{s&&c===o&&l===t?.principal&&i(d)},()=>{})};a();let u=t?.outbox.subscribe(a);return()=>{s=!1,u?.()}},ready:async i=>{if(await n().catch(()=>{}),!t||t.principal===void 0)return!0;try{return await t.outbox.ready(i===void 0?void 0:le(i))}catch(s){if(s instanceof Error&&/sealed/.test(s.message))return!1;throw s}},fence:async()=>{if(await n().catch(()=>{}),!t||t.principal===void 0)return"inside";try{return await t.outbox.fence()}catch(i){if(i instanceof Error&&/sealed/.test(i.message))return"past";throw i}},drain:async()=>(await e()).reason==="fence"?{stopped:"fence"}:void 0,settled:async()=>t?.drainOutcome}}var Bt=class{constructor(e){this.options=e;this.start(null)}waiters=new Set;tail;last;watermark=null;cursorName="c";closed=!1;generation=0;close(){if(this.closed)return;this.closed=!0,this.tail?.close();let e=new Error("subscription closed");e.name="AbortError",this.fail(e)}reset(){this.closed||(this.tail?.close(),this.tail=void 0,this.watermark=null,this.last=void 0,this.start(null))}until(e,n=3e4){return this.last&&e(this.last)?Promise.resolve(this.last):this.closed?Promise.reject(new Error("subscription closed")):new Promise((r,i)=>{let s={predicate:e,resolve:r,reject:i,timer:setTimeout(()=>{this.waiters.delete(s),i(new Error(`subscription condition timed out after ${n} ms`))},n)};this.waiters.add(s)})}start(e){let n=++this.generation;this.drain(e,n).catch(r=>{this.current(n)&&this.fail(r)})}current(e){return!this.closed&&e===this.generation}async drain(e,n){let r=e,i=!1,s;for(;this.current(n);){if(this.cursorName=await this.options.cursor?.()??"c",!this.current(n))return;let o={...this.options.args,[this.cursorName]:r},a=await this.options.query(o);if(!this.current(n))return;if(a.state==="hydrating"){this.deliver(a);return}if(a.state!=="complete"&&a.state!=="capped"){this.deliver(a);return}let u=a;if(u.connection==="offline"&&(i=!0,s===void 0&&typeof u.watermark=="string"&&(s=u.watermark)),a.next!==null){this.watermark=a.next,this.deliver({...a,live:!1,caughtUp:!1,watermark:this.watermark}),r=a.next;continue}if(i&&s!==void 0&&(this.watermark=s),await this.options.mark(this.watermark,()=>this.current(n),i),!this.current(n))return;this.deliver({...a,live:!1,caughtUp:!0,watermark:this.watermark}),this.watchTail(n);return}}watchTail(e){if(!this.current(e))return;this.tail?.close();let n={...this.options.args,[this.cursorName]:this.watermark};this.tail=this.options.subscribe(n,r=>{if(this.current(e)){if((r.state==="complete"||r.state==="capped")&&r.next!==null){this.watermark=r.next,this.deliver({...r,caughtUp:!1,watermark:this.watermark}),this.tail?.close(),this.tail=void 0,this.start(this.watermark);return}r.state==="complete"||r.state==="capped"?this.deliver({...r,caughtUp:!0,watermark:this.watermark}):this.deliver(r)}})}deliver(e){this.last=e;try{this.options.onEvent(e)}catch{}for(let n of[...this.waiters]){let r=!1;try{r=n.predicate(e)}catch(i){clearTimeout(n.timer),this.waiters.delete(n),n.reject(i instanceof Error?i:new Error(String(i)))}r&&(clearTimeout(n.timer),this.waiters.delete(n),n.resolve(e))}}fail(e){let n=e instanceof Error?e:new Error(String(e));for(let r of this.waiters)clearTimeout(r.timer),r.reject(n);this.waiters.clear()}};function Oo(){return{state:"hydrating",live:!1}}function $e(t){return t===void 0?"undefined":t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map($e).join(",")}]`:`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$e(t[e])}`).join(",")}}`}function We(t){return $e(t)}function Po(t,e){let n="data"in e?e.data:void 0,r="data"in t?t.data:void 0,i=$e(n)===$e(r)?r:n,s="live"in e?e.live:!1,o={..."stale"in e&&e.stale!==void 0?{stale:e.stale}:{},..."retained"in e&&e.retained!==void 0?{retained:e.retained}:{},..."caughtUp"in e&&e.caughtUp!==void 0?{caughtUp:e.caughtUp}:{},..."watermark"in e&&e.watermark!==void 0?{watermark:e.watermark}:{},..."predicted"in e&&e.predicted!==void 0?{predicted:e.predicted}:{}},a;switch(e.state){case"complete":a={state:"complete",live:s,data:i,seq:e.seq,next:e.next,...o};break;case"capped":a={state:"capped",live:s,data:i,seq:e.seq,next:e.next,...o};break;case"partial":a=i===void 0?{state:"partial",live:s,seq:e.seq,reason:e.reason,...o}:{state:"partial",live:s,data:i,seq:e.seq,reason:e.reason,...o};break;case"denied":a={state:"denied",live:s,rule:e.rule,seq:e.seq,...o};break;case"hydrating":a={state:"hydrating",live:!1};break;case"refused":{let u={code:e.code,family:e.family,message:e.message,guide:e.guide};e.site!==void 0&&(u.site=e.site),e.rule!==void 0&&(u.rule=e.rule),e.rewrite!==void 0&&(u.rewrite=e.rewrite),a={state:"refused",live:!1,refusal:u};break}case"stale":a=i===void 0?{state:"stale",live:!1,...e.seq===void 0?{}:{seq:e.seq},since:e.since}:{state:"stale",live:!1,data:i,...e.seq===void 0?{}:{seq:e.seq},since:e.since};break}return $e(t)===$e(a)?t:a}function wn(t){if(t!==void 0){if(!t||typeof t!="object"||typeof t.store!="function")throw new TypeError("createClient offline.store must be a carrier factory");if(t.fenceDays!==void 0&&(!Number.isInteger(t.fenceDays)||t.fenceDays<1||t.fenceDays>30))throw new TypeError("createClient offline.fenceDays must be an integer from 1 through 30");if(t.maxAssetBytes!==void 0&&(!Number.isSafeInteger(t.maxAssetBytes)||t.maxAssetBytes<1))throw new TypeError("createClient offline.maxAssetBytes must be a positive safe integer");if(t.viewOnce!==void 0&&typeof t.viewOnce!="function")throw new TypeError("createClient offline.viewOnce must be a (table, row) => boolean predicate")}}function Cr(t){return wn(t),t?new Nt(t):void 0}function jr(t,e){if(_(t))return t;let n=t&&typeof t=="object"?t.code:void 0;if(n==="E_OFFLINE_ID_BLOCK"){let o=t;return new v({code:n,family:"offline",message:o.message,site:o.site??"client.outbox.enqueue",rewrite:o.rewrite??"resume online for a fresh grant, then enqueue a new intent",guide:"offline"})}if(n==="E_OFFLINE_AUTHORITY")return new v({code:n,family:"offline",message:t instanceof Error?t.message:String(t),site:"RangeStore.commit",rewrite:"keep the held coverage; a delivery for another principal or auth epoch is refused, not committed \u2014 open the partition it belongs to (another generation is not refused: it supersedes the held coverage until the next resume resets it)",guide:"offline"});let r=n==="E_OFFLINE_LOCK"||n==="E_OFFLINE_CARRIER"?n:"E_OFFLINE_CARRIER",i=t?.rewrite,s=typeof i=="string"?i:r==="E_OFFLINE_LOCK"?e==="SQLite"?"this account is open in another client; close it and try again":"this account is open in another tab":`install or configure the ${e} carrier`;return new v({code:r,family:"offline",message:t instanceof Error?t.message:String(t),site:"RangeStore.open",rewrite:s,guide:"offline"})}function Ce(){return new v({code:"E_NETWORK",family:"owner",message:"client transport is offline",rewrite:"call client.online() to restore this device transport",guide:"offline"},!0)}async function _e(t,e,n,r,i){if(!t)return{result:r};try{return await t.accept(e,n,r)}catch(s){throw s instanceof Q?i(s.message):s}}async function lt(t,e,n,r,i,s,o){if(!t)return!1;try{return await t.commit(e,n,r,s,o)}catch(a){throw i(a)}}async function Vr(t){let e=ht(t.data,"subscription delivery"),n=await _e(t.runtime,t.op,t.args,e,t.shape),r=n.envelope||n.refresh?{...ce(n.result,"subscription delivery"),live:!0}:Ge(t.data);return r.state!=="refused"&&(await lt(t.runtime,t.op,t.args,n,t.failure,t.revision,t.current)&&t.superseded?.(),(!t.current||t.current())&&await t.observe?.()),r}function qr(t,e,n){if(t.state==="refused"&&F(t))throw new v(z(t));return e(),n({connection:"connected",lastRefusal:t.state==="refused"?z(t):void 0}),t.state==="refused"?void 0:"data"in t?{seq:t.seq,data:t.data}:{seq:t.seq}}async function je(t,e,n,r){try{let i=await t?.answer(e,n),s=i?.retained?void 0:await t?.evaluate(e,n);return Sr(i,s)}catch(i){throw r(i)}}function Nr(t){let e=`${t.op}\0${We(t.args)}`;t.mounted.set(e,{op:t.op,args:t.args,drain:!0});let n=new Bt({args:t.args,query:t.query,subscribe:t.subscribe,cursor:async()=>(await t.ready?.catch(()=>{}),t.runtime?.cursorArg(t.op)??"c"),mark:async(s,o,a)=>{if(!t.runtime||a)return;let u=t.runtime.coverageRevision,c={...t.args,[t.runtime.cursorArg(t.op)]:s},l=await t.runtime.answer(t.op,c);o()&&(await t.runtime.markWatermark(t.op,t.args,s,l?.validator,u),o()&&(await t.observe?.(),t.resume&&!await t.runtime.outbox.grant()&&await t.resume().catch(()=>{})))},onEvent:t.callback}),r=t.track(n),i=r.close.bind(r);return r.close=()=>{t.mounted.delete(e),i()},r}async function Br(t){await t.ready,t.ensureOpen(),t.force(!0),t.connection("offline"),t.reconnect()}async function Dr(t){await t.ready,t.ensureOpen(),t.force(!1),t.connection("reconnecting");let e=await t.authority(),n=t.resume(e);t.setResume(n.then(()=>{},()=>{}));try{await n}finally{t.reconnect()}}async function Mr(t){await t.ready,t.ensureOpen();let e=t.forced();await t.shutdown();let n=t.create();return await n.ready,e&&await n.offline(),n}async function Fr(t){let e=t.principal;e&&await t.open(e);try{if(t.bearer&&(e=await t.confirm(t.authority),await t.open(e,!0)),!e)return;await t.metadata(t.authority),await t.resume(t.authority)}catch(n){if(!t.ignore(n))throw n}}function Gi(t){return t instanceof Error&&typeof t.code=="string"?t:void 0}function Ir(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw n(`${e} must be an object`);return t}function Qi(t){let e=typeof t.envelope?.which=="string"?t.envelope.which:void 0,n=Number.isSafeInteger(t.envelope?.cap)&&Number(t.envelope?.cap)>=0?Number(t.envelope?.cap):void 0;return{...e===void 0?{}:{which:e},...n===void 0?{}:{cap:n}}}async function bn(t,e={},n=!0){let r=()=>E(t.signal);if(r(),!t.runtime)return!1;let i=t.runtime.coverageRevision,s=t.runtime.outbox.generation,o=await t.runtime.resumeRequest([...t.mounted.values()],e);if(r(),!o){if((await t.runtime.queuedIntents()).length===0)return!1;if(r(),await t.runtime.outbox.fence()==="inside")return r(),await He(_r(t)),r(),!1;r();let p=await t.runtime.resumeSeed([...t.mounted.values()]);if(r(),!p)throw $r("no query with known arguments can establish resume facts");let g=await t.json("/api/query?receipt=1",{method:"POST",body:JSON.stringify({op:p.op,args:p.args}),signal:t.signal},t.authority);r();let m=await _e(t.runtime,p.op,p.args,g,t.shape);if(r(),ce(m.result),await lt(t.runtime,p.op,p.args,m,t.failure??(b=>b),i,()=>!t.signal?.aborted),r(),o=await t.runtime.resumeRequest([...t.mounted.values()],e),r(),!o)throw $r("the owner query did not deliver the facts required for resume")}let a=o.log!==void 0&&t.runtime.standInLog(o.log),u=async()=>{r(),await t.reload?.(t.authority),r(),await t.runtime.resetCoverage(o.authEpoch,t.signal),r();for(let p of[...t.subscriptions])p.reset?.();return!0},c;try{c=await t.json("/api/resume",{method:"POST",body:JSON.stringify(o),signal:t.signal},t.authority),r()}catch(p){r();let g=Gi(p);if(g?.code==="E_OFFLINE_RESET")return u();if(g?.status===404){if((await t.runtime.queuedIntents()).length>0)throw p;return!1}if(g?.code==="E_OFFLINE_RESUME"&&n)return bn(t,Qi(g),!1);throw p}let l=Ir(c,"resume response",t.shape);if(l.generation!==o.generation||l.schemaHash!==o.schemaHash)throw t.shape("resume response generation does not match the request");let d=Ir(l.authority,"resume response.authority",t.shape);if(d.principal!==t.runtime.principal||d.authEpoch!==o.authEpoch)throw t.shape("resume response authority does not match the open partition");if(t.runtime.resetNeeded)return u();if(t.bearerConfirmed&&await t.runtime.reauthenticate(d.principal),r(),!Array.isArray(l.mounted))throw t.shape("resume response.mounted must be an array");let h=[],f;if(l.log&&typeof l.log=="object"&&!Array.isArray(l.log)&&l.log.unchanged!==!0&&o.log){let{watermark:p,...g}=l.log;if(p!==null&&typeof p!="string")throw t.shape("resume response.log.watermark must be a string or null");let m=o.log.watermark===null?o.log.args:{...o.log.args,[t.runtime.cursorArg(o.log.op)]:o.log.watermark},b=await _e(t.runtime,o.log.op,m,g,t.shape);r(),h.push({op:o.log.op,args:m,accepted:b}),a||(f={op:o.log.op,args:o.log.args,watermark:p,...b.envelope?.validator===void 0?{}:{validator:b.envelope.validator}})}for(let[p,g]of l.mounted.entries()){if(g&&typeof g=="object"&&!Array.isArray(g)&&g.unchanged===!0)continue;let m=o.mounted[p];if(!m)throw t.shape("resume response returned an unrequested mounted query");h.push({op:m.op,args:m.args,accepted:await _e(t.runtime,m.op,m.args,g,t.shape)}),r()}if(!Number.isSafeInteger(l.seq)||Number(l.seq)<0)throw t.shape("resume response.seq must be a non-negative safe integer");await t.runtime.commitMany(h,f,void 0,i,()=>!t.signal?.aborted,Number(l.seq)),r(),t.validated(t.authority),t.runtime.noteGrant(l);try{await t.runtime.adoptPendingGrant(),r()}catch(p){throw t.failure?t.failure(p):p}return t.runtime.outbox.resumeSucceeded(s)&&(await He(_r(t)),r()),!1}function $r(t){return new v({code:"E_OFFLINE_RESUME",family:"offline",message:t,site:"client.online.resume",guide:"offline",rewrite:"query an authorized operation online with receipt support, then call online() again; queued writes are kept"})}function _r(t){return{runtime:t.runtime,signal:t.signal,json:(e,n)=>t.json(e,n,t.authority),shape:t.shape,failure:t.failure??(e=>e instanceof Error?e:new Error(String(e)))}}function vn(t,e){let n;try{n=new URL(e)}catch{throw new x("E_ASSET_TYPE","asset blob URL must be absolute")}let r=new URL(t);if(n.origin!==r.origin||!n.pathname.startsWith("/api/asset/")||n.searchParams.has("s"))throw new x("E_ASSET_TYPE","asset blob fetch requires a tokenless URL issued by this client");let i=decodeURIComponent(n.pathname.slice(11)),s=n.searchParams.get("w"),o=null;if(s!==null&&(o=Number(s),!Number.isSafeInteger(o)||o<=0))throw new x("E_ASSET_TYPE","asset width must be a positive integer");return{url:e,assetId:Xe.test(i)?i:"",width:o}}function Ur(t){return new v({code:"E_ASSET_VIEWED",family:"offline",message:`asset ${t} belongs to a view-once row that was already viewed on this device`,site:"assetBlob",rewrite:"render a view-once row once; do not fetch its bytes again",guide:"offline"})}async function Lr(t,e){let n=new Set;return t&&await Promise.all(e.map(async r=>{Xe.test(r)&&await t.viewed(r)&&n.add(r)})),n}async function Hr(t,e,n,r,i,s){let o=await Rn(t,e,async()=>{let a=await n();return{bytes:new Uint8Array(await a.arrayBuffer()),type:a.type}},r,i,s);return new Blob([o.bytes],{type:o.type})}async function Rn(t,e,n,r,i,s){if(!t||e.assetId==="")return n();let o=await t.getBytes(e.assetId,e.width,s);if(i(),o)return o;let a=await t.viewed(e.assetId);if(i(),a){let g=Ur(e.assetId);throw r(g.envelope),g}let u=await t.viewOnce(e.assetId);if(u&&!s){let g=new v({code:"E_ASSET_TYPE",family:"input",site:"assetBlob",message:"view-once bytes require a mounted viewing instance",rewrite:"pass the same viewing token for the lifetime of the mounted consumer",guide:"assets/client"});throw r(g.envelope),g}let c=u||await t.canServe(e.assetId);i();let l=await n();i();let d=await t.putBytes(e.assetId,e.width,l,s);i();let h=await t.viewOnce(e.assetId),f=await t.viewed(e.assetId),p=await t.canServe(e.assetId,s);if(i(),h&&d!=="viewed"&&d!=="cached"||(c||h||f||d==="viewed")&&!p){if(f&&!p){let m=Ur(e.assetId);throw r(m.envelope),m}let g=new v({code:"E_OFFLINE_CARRIER",family:"offline",site:"assetBytes",message:"asset viewing allowance was not durably admitted or its row lease changed",rewrite:"restore the carrier and fetch a currently held, unviewed row",guide:"offline"});throw r(g.envelope),g}return l}async function Wr(t,e,n,r){let i=await mt(e).catch(s=>{throw W(t,s)});return xn(t,i,n,r)}async function Gr(t,e,n,r){let i=Array.isArray(e)?e:e==null?[]:[e],s=await Lr(t.assetCache,i.map(c=>c.id));t.ensureAuthority(r);let o=i.filter(c=>!s.has(c.id)),a=n.carrier===!0||n.download===!0;if(a&&o.some(c=>!("duration"in c)))throw W(t,new x("E_ASSET_CARRIER_IMAGE","image asset URLs never carry a session token; fetch the URL with assetHeaders or assetBlob"));let u;a&&o.length>0&&(r.token!==void 0||t.persona!==void 0)&&(u=await Ji(t,r));try{return Array.isArray(e)?o.map(c=>Qt(t.url,c,n.width,u)):e==null||s.has(e.id)?void 0:Qt(t.url,e,n.width,u)}catch(c){throw W(t,c)}}function Qr(t,e){let n={};return e.token&&(n.Authorization=`Bearer ${e.token}`),t.persona&&(n["X-Snapback-As"]=t.persona),n}async function zr(t,e,n,r,i,s){let o;try{o=vn(t.url,r)}catch(a){throw W(t,a)}return Hr(e,o,async()=>{if(n())throw Ce();let a=t.headers(s);a.set("Accept","*/*"),a.set("Cache-Control","no-store");let u=await Dt(t,r,{headers:a,signal:i.signal,cache:"no-store"},s);return t.validated(s),u.blob()},a=>t.recordRefusal(a),()=>t.ensureAuthority(s),i.viewing)}async function Jr(t,e,n,r,i,s){let o;try{o=vn(t.url,r)}catch(a){throw W(t,a)}return Rn(e,o,async()=>{if(n())throw Ce();let a=t.headers(s);a.set("Accept","*/*"),a.set("Cache-Control","no-store");let u=await Dt(t,r,{headers:a,signal:i.signal,cache:"no-store"},s),c=new Uint8Array(await u.arrayBuffer());return t.ensureAuthority(s),t.validated(s),{bytes:c,type:u.headers.get("Content-Type")??"application/octet-stream"}},a=>t.recordRefusal(a),()=>t.ensureAuthority(s),i.viewing)}async function xn(t,e,n,r){t.ensureAuthority(r);let i;if(n.onProgress&&qn(e.source)&&!t.customFetch&&typeof XMLHttpRequest=="function")i=await zi(t,e.source,e.bytes,n,r);else{let o;try{o=await Dn(e)}catch(c){throw W(t,c)}let a=t.headers(r);if(a.set("Content-Length",String(e.bytes)),Re(e.source)&&!/^(?:data|https?):/i.test(e.source.uri)&&J(o)){let c;try{c=await Nn()}catch(l){throw W(t,l)}n.onProgress?.({loaded:0,total:e.bytes}),i=await Dt(t,`${t.url}/api/upload`,{method:"POST",headers:a,body:o},r,c),n.onProgress?.({loaded:e.bytes,total:e.bytes})}else{o=Mn(o,e.bytes,n);let c=!J(o);i=await Dt(t,`${t.url}/api/upload`,{method:"POST",headers:a,body:o,...c?{duplex:"half"}:{}},r)}}let s;try{s=await i.json()}catch{throw W(t,new x("E_ASSET_TYPE","upload response must contain valid JSON"))}try{let o=Ln(s),a=Object.hasOwn(o,"duration")?"video":"image";if(n.kind&&n.kind!==a)throw new x("E_ASSET_TYPE",`upload produced ${a==="image"?"an image":"a video"} asset but kind ${n.kind} was requested`);return t.validated(r),o}catch(o){throw W(t,o)}}function zi(t,e,n,r,i){return new Promise((s,o)=>{let a=new XMLHttpRequest;a.open("POST",`${t.url}/api/upload`);for(let[u,c]of t.headers(i))a.setRequestHeader(u,c);r.onProgress?.({loaded:0,total:n}),a.upload.onprogress=u=>r.onProgress?.({loaded:Math.min(n,u.loaded),total:n}),a.onerror=()=>o(t.networkRefusal("asset upload failed")),a.onabort=()=>o(t.networkRefusal("asset upload was aborted")),a.onload=()=>{try{t.ensureAuthority(i),r.onProgress?.({loaded:n,total:n}),s(new Response(a.responseText,{status:a.status,headers:{"Content-Type":a.getResponseHeader("Content-Type")??"application/json"}}))}catch(u){o(u)}},a.send(e)}).then(async s=>{if(s.ok)return s;if(s.status>=400&&s.status<500){let o=await Ve(s);throw t.recordRefusal(o.envelope),o}throw t.transportRefusal(`/api/upload returned HTTP ${s.status}`)})}async function Dt(t,e,n,r,i=t.fetchImpl){let s;try{s=await i(e,n)}catch(o){throw t.ensureAuthority(r),t.networkRefusal(o instanceof Error?o.message:String(o))}if(t.ensureAuthority(r),s.ok)return s;if(s.status>=400&&s.status<500){let o=await Ve(s);throw t.recordRefusal(o.envelope),o}throw t.transportRefusal(`${new URL(e).pathname} returned HTTP ${s.status}`)}async function Ji(t,e){let n=Date.now()+6e4;if(t.carrier&&t.carrier.authGeneration===e.authGeneration&&t.carrier.custodyGeneration===e.custodyGeneration&&t.carrier.fence===e.fence&&t.carrier.expiresAt>n)return t.carrier.token;let r=Cn(await t.json("/api/auth/asset-session",{method:"POST",body:JSON.stringify({})},e));return t.ensureAuthority(e),t.carrier={token:r.token,expiresAt:r.expiresAt,authGeneration:e.authGeneration,custodyGeneration:e.custodyGeneration,fence:e.fence},r.token}function W(t,e){if(_(e))return e;let n=e instanceof x?e:new x("E_ASSET_TYPE",e instanceof Error?e.message:String(e)),r=new v({code:n.code,family:"input",message:n.message,rewrite:"pass a File or { uri, size?/fileSize?, type?/mimeType? } only to a matching manifest asset argument",guide:"assets/client"});return t.recordRefusal(r.envelope),r}function dt(){let t=new Error("subscription closed");return t.name="AbortError",t}async function Ki(t,e){if(e.aborted)throw dt();await new Promise((n,r)=>{let i=()=>{clearTimeout(s),r(dt())},s=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);e.addEventListener("abort",i,{once:!0})})}async function*Yi(t,e,n){if(!t.body)throw new Error("SSE response has no body");let r=t.body.getReader(),i=new TextDecoder,s="",o=[],a,u=!1,c=d=>{let h=d.endsWith("\r")?d.slice(0,-1):d;if(h===""){if(o.length===0)return;let m={id:a,data:o.join(`
2
2
  `)};return o=[],a=void 0,n(),m}if(h.startsWith(":")){n();return}let f=h.indexOf(":"),p=f<0?h:h.slice(0,f),g=f<0?"":h.slice(f+1);g.startsWith(" ")&&(g=g.slice(1)),p==="data"&&o.push(g),p==="id"&&!g.includes("\0")&&(a=g)},l=()=>{r.cancel().catch(()=>{})};e.addEventListener("abort",l,{once:!0});try{for(;;){let h=await r.read();s+=i.decode(h.value,{stream:!h.done});let f=s.indexOf(`
3
3
  `);for(;f>=0;){let p=c(s.slice(0,f));s=s.slice(f+1),p&&(yield p),f=s.indexOf(`
4
- `)}if(e.aborted)throw dt();if(h.done){u=!0;break}}if(s.length>0){let h=c(s);h&&(yield h)}let d=c("");d&&(yield d)}finally{e.removeEventListener("abort",l),u||await r.cancel().catch(()=>{}),r.releaseLock()}}var ft=class{constructor(e){this.options=e;this.start()}controller=new AbortController;waiters=new Set;last;lastEventId;terminalFailure;closed=!1;activeAttempt;retryNow;resets=0;running;close(){if(!this.closed){this.closed=!0,this.controller.abort();for(let e of this.waiters)clearTimeout(e.timer),e.reject(dt());this.waiters.clear()}}reconnect(){this.closed||(this.activeAttempt?.abort(),this.retryNow?.())}reset(){this.closed||(this.terminalFailure=void 0,this.resets+=1,this.lastEventId=void 0,this.last=void 0,this.reconnect(),this.start())}until(e,n=3e4){return this.terminalFailure?Promise.reject(this.terminalFailure):this.last!==void 0&&e(this.last)?Promise.resolve(this.last):this.closed?Promise.reject(dt()):new Promise((r,i)=>{let s={predicate:e,resolve:r,reject:i,timer:setTimeout(()=>{this.waiters.delete(s),i(new Error(`subscription condition timed out after ${n} ms`))},n)};this.waiters.add(s)})}deliver(e,n=!0){this.last=e;try{this.options.onEvent?.(e)}catch{}if(n)for(let r of[...this.waiters]){let i=!1;try{i=r.predicate(e)}catch(s){clearTimeout(r.timer),this.waiters.delete(r),r.reject(s instanceof Error?s:new Error(String(s)));continue}i&&(clearTimeout(r.timer),this.waiters.delete(r),r.resolve(e))}}fail(e){this.terminalFailure=e;for(let n of this.waiters)clearTimeout(n.timer),n.reject(e);this.waiters.clear()}start(){if(this.closed||this.running)return;let e=this.resets,n=this.run();this.running=n,n.finally(()=>{this.running=void 0,!this.closed&&!this.terminalFailure&&e!==this.resets&&this.start()}).catch(()=>{})}async run(){let e=250,n=!1,r=!1;for(;!this.closed;){let i=this.resets,s=new AbortController;this.activeAttempt=s;let o=()=>s.abort();this.controller.signal.addEventListener("abort",o,{once:!0});let a,u=!1,c,l=()=>!this.closed&&i===this.resets&&!s.signal.aborted,d=()=>{a!==void 0&&clearTimeout(a),a=setTimeout(()=>{u=!0,s.abort()},3e4)};try{d();let h=await this.options.open(this.lastEventId,s.signal);if(!h.ok)throw h;for await(let f of Yi(h,s.signal,d)){if(this.closed||s.signal.aborted){let m;try{m=this.options.bufferedTerminal?.(f)}catch{}if(m!==void 0){try{await this.options.onError(m,n)}catch{}return}continue}try{c=this.options.bufferedTerminal?.(f)}catch{c=void 0}let p=await this.options.decode(f,l);if(c=void 0,!l())continue;f.id!==void 0&&(this.lastEventId=f.id),this.deliver(p),n=!0,r=!1,e=250;let g=this.options.terminal?.(p);if(g!==void 0){this.fail(g);return}}if(this.closed)return;if(i===this.resets&&!r){let f=this.options.onLoss(this.last);f!==void 0&&this.deliver(f),r=!0}}catch(h){if(c&&!l()){let g=await this.options.onError(c,n);this.closed||(g.event!==void 0&&this.deliver(g.event,g.failure===void 0),g.failure!==void 0&&this.fail(g.failure));return}if(this.closed||this.controller.signal.aborted)return;if(i!==this.resets)continue;let f=u?new Error("SSE stream idle for 30000 ms"):h,p=await this.options.onError(f,n);if(this.closed||this.controller.signal.aborted||(p.event!==void 0&&this.deliver(p.event,p.failure===void 0),p.failure!==void 0&&this.fail(p.failure),!p.retry))return;if(!r){let g=this.options.onLoss(this.last);g!==void 0&&this.deliver(g),r=!0}}finally{a!==void 0&&clearTimeout(a),this.controller.signal.removeEventListener("abort",o),this.activeAttempt===s&&(this.activeAttempt=void 0)}if(i===this.resets){try{await Promise.race([Ki(e,this.controller.signal),new Promise(h=>{this.retryNow=h})])}catch{return}finally{this.retryNow=void 0}e=Math.min(e*2,5e3)}}}};function Xi(t,e){if(!t||typeof t.getItem!="function"||typeof t.setItem!="function"||typeof t.removeItem!="function")throw new TypeError("browserTokenStore requires an explicit Storage implementation");if(!e)throw new TypeError("browserTokenStore requires a non-empty key");return{load:()=>t.getItem(e),save:n=>{n===null?t.removeItem(e):t.setItem(e,n)},loadPrincipal:()=>t.getItem(`${e}:principal`),savePrincipal:n=>{n===null?t.removeItem(`${e}:principal`):t.setItem(`${e}:principal`,n)}}}var kn=class t{auth;outbox;ready;url;fetchImpl;customFetch;tokenStore;persona;createOptions;offlineRuntime;mounted=new Map;offlineMetadataLoaded=!1;resumeTail=Promise.resolve();resumeFlight;resumeController;resetRefusal;supersessionQueries=new Map;forcedOffline=!1;currentToken;currentPrincipal;authGeneration=0;custodyGeneration=0;operationFence=0;transitionTail=Promise.resolve();custodyTail=Promise.resolve();currentSnapshot;statusListeners=new Set;subscriptions=new Set;writes=new Set;carrier;closed=!1;closing=Promise.resolve();constructor(e){if(!e?.url)throw new TypeError("createClient requires url");if(e.as!==void 0&&(e.token!==void 0||e.tokenStore!==void 0))throw new TypeError("createClient cannot combine dev persona `as` with bearer token custody");if(this.createOptions=e,this.url=e.url.replace(/\/+$/,""),this.fetchImpl=e.fetch??globalThis.fetch,this.customFetch=e.fetch!==void 0,typeof this.fetchImpl!="function")throw new TypeError("createClient requires a fetch implementation");this.tokenStore=e.tokenStore,this.persona=e.as,this.forcedOffline=e.startOffline===!0,this.currentSnapshot={authGeneration:0,persona:e.as,connection:this.forcedOffline?"offline":"reconnecting"},wn(e.offline);try{this.offlineRuntime=Cr(e.offline)}catch(n){throw this.offlineRefusal(n)}this.outbox=Tr(this.offlineRuntime,()=>this.drainNow(),()=>this.ready),this.auth={signup:n=>this.session("/api/auth/signup",n),login:n=>this.session("/api/auth/login",n),guest:()=>this.session("/api/auth/guest",{}),logout:()=>this.logout(),me:()=>this.me()},this.ready=this.hydrate(e.token).then(()=>this.initializeOffline())}get snapshot(){return this.currentSnapshot}async query(e,n){let r=await this.operationAuthority(!1),i=le(e);if(this.forcedOffline)return this.patchSnapshot({connection:"offline"}),je(this.offlineRuntime,i,n,o=>this.offlineRefusal(o));await this.ensureOfflineMetadata(r),this.scheduleSupersessionReset(r);let s=50;for(let o=1;;o+=1)try{let a=await this.offlineRuntime?.answer(i,n),u=this.offlineRuntime?.coverageRevision,c=await this.json(this.offlineRuntime?"/api/query?receipt=1":"/api/query",{method:"POST",body:JSON.stringify(this.offlineRuntime&&a?.validator?{op:i,args:n,validator:a.validator}:{op:i,args:n})},r),l=await _e(this.offlineRuntime,i,n,c,P),d=ce(l.result),h=await lt(this.offlineRuntime,i,n,l,f=>this.offlineRefusal(f),u);if(this.validated(r),(h||u!==this.offlineRuntime?.coverageRevision)&&this.scheduleSupersessionReset(r,{op:i,args:n}),this.offlineRuntime&&this.createOptions.offlineReadObserver){let f=await je(this.offlineRuntime,i,n,p=>this.offlineRefusal(p));this.createOptions.offlineReadObserver(e,n,f)}return d}catch(a){if(_(a)&&a.retryable&&this.offlineRuntime&&o>=3)return this.patchSnapshot({connection:"offline"}),je(this.offlineRuntime,i,n,u=>this.offlineRefusal(u));if(!_(a)||a.code!=="E_TRANSPORT"&&a.code!=="E_NETWORK"||!a.retryable||o>=3)throw a;await new Promise(u=>setTimeout(u,s)),this.ensureAuthority(r),s*=2}}async mutation(e,n){let r=await this.operationAuthority();return this.trackWrite(async()=>{try{let i=n;if(yt(n)){let o=le(e),a=await this.manifestFor(r),u=a.ops[o]?.args;if(u===void 0)throw W(this,new x("E_ASSET_TYPE",`manifest generation ${a.generation} has no argument descriptor for ${o}`));let c=await Bn(n,u).catch(l=>{throw W(this,l)});if(c.length>0){let l=[];for(let h of c)l.push(await xn(this,h.prepared,{},r));let d=await this.manifestFor(r);if(d.generation!==a.generation)throw W(this,new x("E_ASSET_NOT_READY",`descriptor generation changed from ${a.generation} to ${d.generation} during asset upload`));i=Fn(n,c,l)}}let s=await Pr({runtime:this.offlineRuntime,offline:this.forcedOffline,op:le(e),args:i,json:(o,a)=>this.json(o,a,r),failure:o=>this.offlineRefusal(o),drain:()=>this.drainNow()});if(s.state==="rejected"&&F(s)){let o=this.authorityCurrent(r),a=await this.expireSession(r);if(!o||!this.expirationCurrent(a))throw this.supersededRefusal();return this.recordRefusal(s),s}return this.validated(r),s}catch(i){if(_(i)&&i.code==="E_WIRE_SHAPE"){let s=new v(z(i.envelope),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:s.envelope}),s}throw i}})}async upload(e,n={}){let r=await this.operationAuthority();return this.trackWrite(()=>Wr(this,e,n,r))}async assetUrl(e,n={}){return Gr(this,e,n,await this.operationAuthority())}async assetHeaders(){return Qr(this,await this.operationAuthority())}async assetBlob(e,n={}){let r=await this.operationAuthority();return zr(this,this.offlineRuntime?.bytes,()=>this.forcedOffline,e,n,r)}async assetBytes(e,n={}){let r=await this.operationAuthority();return Jr(this,this.offlineRuntime?.bytes,()=>this.forcedOffline,e,n,r)}get assetCache(){return this.offlineRuntime?.bytes}subscribe(e,n,r,i={}){return i.drain?this.drain(e,n,r):this.subscribeRegular(e,n,r)}subscribeRegular(e,n,r){let i=le(e),s=`${i}\0${We(n)}`;this.mounted.set(s,{op:i,args:n,drain:!1});let o,a,u,c,l=f=>(o=qr(f,()=>this.ensureAuthority(u),p=>this.patchSnapshot({...p,lastRefusal:p.lastRefusal??this.resetRefusal})),f);c=new ft({open:async(f,p)=>{if(u??=await this.operationAuthority(),this.forcedOffline)throw Ce();await this.ensureOfflineMetadata(u),this.scheduleSupersessionReset(u),a=this.offlineRuntime?.coverageRevision;let g=await this.offlineRuntime?.answer(i,n),m=`/api/subscribe?op=${encodeURIComponent(i)}&args=${encodeURIComponent(JSON.stringify(n))}`;return this.offlineRuntime&&(m+="&receipt=1"),g?.validator&&(m+=`&validator=${encodeURIComponent(g.validator)}`),this.stream(m,f,p,u)},decode:({data:f},p)=>{let g=a;return this.offlineRuntime?Vr({runtime:this.offlineRuntime,op:i,args:n,data:f,shape:P,failure:m=>this.offlineRefusal(m),revision:g,current:p,superseded:()=>this.scheduleSupersessionReset(u,{op:i,args:n}),observe:this.createOptions.offlineReadObserver?async()=>this.createOptions.offlineReadObserver(e,n,await je(this.offlineRuntime,i,n,m=>this.offlineRefusal(m))):void 0}).then(m=>p()||m.state==="refused"&&F(m)?l(m):m):l(Ge(f))},bufferedTerminal:({data:f})=>{let p=Ge(f);return p.state==="refused"&&F(p)?new v(z(p)):void 0},onError:async f=>{let{retry:p,event:g,refusal:m}=await this.subscriptionError(f,u,c);if(p&&this.offlineRuntime){this.patchSnapshot({connection:"offline"});let b=await je(this.offlineRuntime,i,n,S=>this.offlineRefusal(S));return{retry:p,event:b,failure:m}}return{retry:p,event:g===void 0?void 0:{...g,live:!1},failure:m}},onLoss:()=>{if(this.authorityCurrent(u)&&(this.patchSnapshot({connection:this.transportFailureState()}),!this.offlineRuntime&&o))return"data"in o?{state:"stale",live:!1,since:Date.now(),seq:o.seq,data:o.data}:{state:"stale",live:!1,since:Date.now(),seq:o.seq}},terminal:f=>f.state==="refused"?new v(z(f)):void 0,onEvent:r});let d=this.track(c),h=d.close.bind(d);return d.close=()=>{this.mounted.delete(s),h()},d}drain(e,n,r){let i=le(e);return Nr({ref:e,op:i,args:n,callback:r,runtime:this.offlineRuntime,ready:this.ready,mounted:this.mounted,query:s=>this.query(e,s),subscribe:(s,o)=>this.subscribeRegular(e,s,o),track:s=>this.track(s),resume:async()=>this.performResume(await this.operationAuthority()),observe:this.offlineRuntime&&this.createOptions.offlineReadObserver?async()=>this.createOptions.offlineReadObserver(e,n,await je(this.offlineRuntime,i,n,s=>this.offlineRefusal(s))):void 0})}channel(e,n){let r=le(e),i=encodeURIComponent(r.startsWith("channels.")?r.slice(9):r);return{publish:async s=>{let o=await this.operationAuthority();return this.trackWrite(async()=>{let a=Pn(await this.json(`/api/channel/${i}/publish`,{method:"POST",body:JSON.stringify({args:n,payload:s})},o));if("state"in a){if(F(a)){let u=this.authorityCurrent(o),c=await this.expireSession(o);if(!u||!this.expirationCurrent(c))throw this.supersededRefusal()}this.recordRefusal(a)}else this.validated(o);return a})},subscribe:s=>{let o=`/api/channel/${i}/subscribe?args=${encodeURIComponent(JSON.stringify(n))}`,a,u;return u=new ft({open:async(c,l)=>(a??=await this.operationAuthority(),this.stream(o,c,l,a)),decode:({data:c})=>{let l=Ut(c);if("state"in l&&l.state==="refused"&&F(l))throw new v(z(l));return this.ensureAuthority(a),this.patchSnapshot({connection:"connected",lastRefusal:"state"in l&&l.state==="refused"?z(l):void 0}),l},bufferedTerminal:({data:c})=>{let l=Ut(c);return"state"in l&&l.state==="refused"&&F(l)?new v(z(l)):void 0},onError:async c=>{let l=await this.subscriptionError(c,a,u);return{retry:l.retry,event:l.event,failure:l.refusal}},onLoss:()=>{this.authorityCurrent(a)&&this.patchSnapshot({connection:this.transportFailureState()})},terminal:c=>"state"in c&&c.state==="refused"?new v(z(c)):void 0,onEvent:s}),this.track(u)}}}async manifest(){let e=await this.operationAuthority();return this.manifestFor(e)}async offline(){return Br({ready:this.ready,ensureOpen:()=>this.ensureOpen(),force:e=>{this.forcedOffline=e},connection:e=>{this.patchSnapshot({connection:e})},reconnect:()=>this.reconnectTransports()})}async online(){return Dr({ready:this.ready,ensureOpen:()=>this.ensureOpen(),force:e=>{this.forcedOffline=e},connection:e=>{this.patchSnapshot({connection:e})},authority:()=>this.operationAuthority(),resume:e=>this.performResume(e),setResume:e=>{this.resumeTail=e},reconnect:()=>this.reconnectTransports()})}async restart(){return Mr({ready:this.ready,ensureOpen:()=>this.ensureOpen(),forced:()=>this.forcedOffline,shutdown:async()=>{this.closed=!0,this.abortResume(),this.operationFence+=1,this.closeTransports(),this.patchSnapshot({connection:"offline"}),await this.offlineRuntime?.close()},create:()=>{let e=this.createOptions.offline,n=this.persona!==void 0?{url:this.url,as:this.persona,fetch:this.fetchImpl,offline:e,startOffline:this.forcedOffline,offlineReadObserver:this.createOptions.offlineReadObserver}:{url:this.url,token:this.currentToken,tokenStore:this.tokenStore,fetch:this.fetchImpl,offline:e,offlinePrincipal:this.currentPrincipal,startOffline:this.forcedOffline,offlineReadObserver:this.createOptions.offlineReadObserver};return new t(n)}})}subscribeStatus(e){this.statusListeners.add(e);try{e(this.currentSnapshot)}catch(n){throw this.statusListeners.delete(e),n}return()=>this.statusListeners.delete(e)}close(){return this.closed?this.closing:(this.closed=!0,this.abortResume(),this.operationFence+=1,this.closeTransports(),this.patchSnapshot({connection:"offline"}),this.closing=this.offlineRuntime?.close()??Promise.resolve(),this.closing)}track(e){this.subscriptions.add(e);let n=e.close.bind(e);return e.close=()=>{this.subscriptions.delete(e),n()},e}async session(e,n){return this.ensureBearerTransition(e.slice(10)),this.transition(async r=>{let i=In(Or(this.offlineRuntime,await this.json(e,{method:"POST",body:JSON.stringify(n)},r,!1,!1)),`${e.slice(5)} response`);await this.openOffline(i.viewer,!0),await this.installToken(i.token),this.ensureOpen();try{await this.ensureOfflineMetadata({authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken})}catch(s){if(!_(s)||!s.retryable)throw s}return this.validated(void 0),i})}async logout(){return this.ensureBearerTransition("logout"),this.transition(async e=>{let n,r;try{n=$n(await this.json("/api/auth/logout",{method:"POST"},e,!1,!1))}catch(s){r=s}let i;try{await this.wipeOffline()}catch(s){i=s}if(await this.clearToken(),this.ensureOpen(),r!==void 0)throw r;if(i!==void 0)throw i;return this.validated(void 0),n})}async me(){let e=await this.operationAuthority(),n=Lt(await this.json("/api/auth/me",{},e));return await this.openOffline(n.viewer,!0),this.validated(e),n}async hydrate(e){let n=e,r;if(n===void 0&&this.tokenStore)try{let[i,s]=await Promise.all([this.tokenStore.load(),this.tokenStore.loadPrincipal?.()]);n=i??void 0,r=s}catch(i){throw this.storageRefusal("load",i)}if(n!==void 0&&(typeof n!="string"||n.length===0))throw this.storageRefusal("load",new TypeError("stored token must be a non-empty string or null"));e!==void 0&&await this.saveToken(n),!this.closed&&(this.currentToken=n,n!==void 0&&r&&(this.currentPrincipal=r),this.authGeneration+=1,this.publishAuthSnapshot())}headers(e,n=!1,r=!1){let i=new Headers;return i.set("Accept",n?"text/event-stream":"application/json"),r&&i.set("Content-Type","application/json"),e.token&&i.set("Authorization",`Bearer ${e.token}`),this.persona&&i.set("X-Snapback-As",this.persona),i}async manifestFor(e,n){E(n);let r=_n(await this.json("/api/manifest",{signal:n},e));return E(n),this.validated(e),this.patchSnapshot({generation:r.generation}),this.offlineRuntime?.manifest(r),this.offlineRuntime&&this.offlineRuntime.programGeneration!==r.programGeneration&&(this.offlineMetadataLoaded=!1),r}async ensureOfflineMetadata(e,n=!1,r=!0,i){if(E(i),!this.offlineRuntime||this.offlineMetadataLoaded&&!n)return;let s;try{s=await this.manifestFor(e,i),E(i)}catch(o){if(!n&&_(o)&&o.retryable)return;throw o}if(this.offlineRuntime.programGeneration!==s.programGeneration||n)try{let o=await this.json(`/api/program?generation=${encodeURIComponent(s.programGeneration)}`,{signal:i},e);E(i),await this.offlineRuntime.program(o,i),E(i)}catch(o){if(!_(o)||o.status!==404)throw o;if(n){if(r)return this.ensureOfflineMetadata(e,!0,!1,i);throw o}}this.offlineMetadataLoaded=!0}networkRefusal(e){let n=new v(Z("E_NETWORK",e),!0);return this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:n.envelope}),n}transportRefusal(e){let n=new v(Z("E_TRANSPORT",e),!0);return this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:n.envelope}),n}async json(e,n,r,i=!0,s=!0){if(i?this.ensureAuthority(r):this.ensureOpen(),this.forcedOffline)throw Ce();let o;try{o=await this.fetchImpl(`${this.url}${e}`,{...n,headers:this.headers(r,!1,n.body!==void 0&&n.body!==null)})}catch(c){i?this.ensureAuthority(r):this.ensureOpen();let l=new v(Z("E_NETWORK",c instanceof Error?c.message:String(c)),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:l.envelope}),l}if(!o.ok){if(o.status>=400&&o.status<500){let l;try{l=await Ve(o)}catch(f){throw _(f)&&(i?this.ensureAuthority(r):this.ensureOpen(),f.retryable&&this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:f.envelope})),f}let d=!i||this.authorityCurrent(r),h;throw s&&F(l.envelope)&&(h=await this.expireSession(r)),i&&(!d||h!==void 0&&!this.expirationCurrent(h))?this.supersededRefusal():(i&&!(s&&F(l.envelope))?this.ensureAuthority(r):this.ensureOpen(),this.patchSnapshot({connection:"connected"}),this.recordRefusal(l.envelope),l)}i?this.ensureAuthority(r):this.ensureOpen();let c=new v(Z("E_TRANSPORT",`${e} returned HTTP ${o.status}`),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:c.envelope}),c}let a;try{a=await o.json()}catch{i?this.ensureAuthority(r):this.ensureOpen();let c=P(`${e} must contain valid JSON`);throw this.recordRefusal(c.envelope),c}let u;try{u=s?Tn(a):void 0}catch(c){throw i?this.ensureAuthority(r):this.ensureOpen(),c}if(u!==void 0&&i&&!this.authorityCurrent(r))throw await this.expireSession(r),this.supersededRefusal();return i?this.ensureAuthority(r):this.ensureOpen(),this.patchSnapshot({connection:"connected"}),a}async stream(e,n,r,i){if(this.ensureAuthority(i),this.forcedOffline)throw Ce();let s=this.headers(i,!0);n!==void 0&&s.set("Last-Event-ID",n);try{let o=await this.fetchImpl(`${this.url}${e}`,{headers:s,signal:r});if(!o.ok){if(o.status>=400&&o.status<500){let a;try{a=await Ve(o)}catch(u){if(_(u)&&!u.retryable)throw u}if(a!==void 0)throw F(a.envelope)&&(r.aborted||!this.authorityCurrent(i))?(await this.expireSession(i),this.supersededRefusal()):(F(a.envelope)||this.ensureAuthority(i),a)}throw this.ensureAuthority(i),new v(Z("E_HTTP",`${e} returned HTTP ${o.status}`),!0)}return this.ensureAuthority(i),E(r),this.patchSnapshot({connection:"connected"}),o}catch(o){if(_(o)&&F(o.envelope)||(this.ensureAuthority(i),r.aborted))throw o;if(_(o))throw this.patchSnapshot({connection:o.retryable?this.transportFailureState():"connected",lastRefusal:o.envelope}),o;let a=new v(Z("E_NETWORK",o instanceof Error?o.message:String(o)),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:a.envelope}),a}}async subscriptionError(e,n,r){let i=_(e)?e:new v(Z("E_NETWORK",e instanceof Error?e.message:String(e)),!0);if(i.code==="E_AUTH_SUPERSEDED")return{retry:!1,refusal:i};if(F(i.envelope)&&n!==void 0){let s=this.authorityCurrent(n),o;try{o=await this.expireSession(n,r)}catch(a){if(this.closed)return{retry:!1,refusal:this.supersededRefusal()};let u=_(a)?a:new v({code:"E_AUTH_TOKEN_STORE",family:"auth",message:`token store clear failed: ${a instanceof Error?a.message:String(a)}`,guide:"auth/session"});return this.patchSnapshot({connection:"connected",lastRefusal:u.envelope}),{retry:!1,refusal:u,event:{state:"refused",...u.envelope}}}if(this.closed)return{retry:!1,refusal:this.supersededRefusal()};if(!s||!this.expirationCurrent(o))return{retry:!1,refusal:this.supersededRefusal()}}return this.closed?{retry:!1,refusal:this.supersededRefusal()}:i.retryable?(this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:i.envelope}),{retry:!0}):(this.patchSnapshot({connection:"connected",lastRefusal:i.envelope}),{retry:!1,refusal:i,event:{state:"refused",...i.envelope}})}async initializeOffline(){if(!this.offlineRuntime)return;let e={authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken};return Fr({principal:this.persona===void 0?this.createOptions.offlinePrincipal??this.currentPrincipal:`dev:${this.persona}`,bearer:this.persona===void 0&&this.currentToken!==void 0,authority:e,open:(n,r)=>this.openOffline(n,r),confirm:async n=>Lt(await this.json("/api/auth/me",{},n)).viewer,metadata:n=>this.ensureOfflineMetadata(n),resume:n=>this.performResume(n),ignore:n=>_(n)&&(n.retryable||n.code==="E_OFFLINE_RESUME"||n.code==="E_OFFLINE_RESET")})}async openOffline(e,n=!1){if(this.offlineRuntime)try{let r=this.offlineRuntime.principal!==e;await this.offlineRuntime.open(e,n),n&&await this.offlineRuntime.reauthenticate(e),this.currentPrincipal=e,r&&(this.supersessionQueries.clear(),this.offlineMetadataLoaded=!1)}catch(r){throw this.offlineRefusal(r)}}async sealOffline(){if(this.offlineRuntime)try{await this.offlineRuntime.seal()}catch(e){throw this.offlineRefusal(e)}}async wipeOffline(){if(this.offlineRuntime){this.abortResume(),this.supersessionQueries.clear();try{await this.offlineRuntime.wipe(),this.currentPrincipal=void 0}catch(e){throw this.offlineRefusal(e)}}}scheduleSupersessionReset(e,n){let r=this.offlineRuntime?.principal;!this.authorityCurrent(e)||r===void 0||(n&&this.supersessionQueries.set(`${r}\0${n.op}\0${We(n.args)}`,{principal:r,...n}),!(this.forcedOffline||!this.offlineRuntime?.resetNeeded&&this.supersessionQueries.size===0)&&this.performResume(e).catch(()=>{}))}performResume(e){if(!this.offlineRuntime||this.forcedOffline)return Promise.resolve();if(this.resumeFlight)return this.resumeFlight;let n=new AbortController;this.resumeController=n;let r=this.resumeOffline(e,n.signal).then(()=>{E(n.signal),this.ensureAuthority(e),this.resetRefusal=void 0,this.validated(e)},i=>{if(this.authorityCurrent(e)){let s=this.offlineRefusal(i);this.resetRefusal=s.envelope}throw i});return this.resumeFlight=r,r.then(()=>{this.resumeFlight===r&&(this.resumeFlight=void 0,this.resumeController=void 0,this.scheduleSupersessionReset(e))},()=>{this.resumeFlight===r&&(this.resumeFlight=void 0,this.resumeController=void 0)}),r}abortResume(){this.resumeController?.abort(),this.resumeController=void 0,this.resumeFlight=void 0}async resumeOffline(e,n){let r=this.offlineRuntime,i=()=>{E(n),this.ensureAuthority(e)},s=async(o,a)=>{i();let u=await this.json(o,{...a,signal:n},e);return i(),u};await this.ensureOfflineMetadata(e,!1,!0,n),i();for(let o=0;o<3;o++){let a=await bn({runtime:r,mounted:this.mounted,authority:e,signal:n,bearerConfirmed:e.token!==void 0,json:s,validated:f=>{i(),this.validated(f)},shape:P,failure:f=>this.offlineRefusal(f),subscriptions:this.subscriptions,reload:f=>this.ensureOfflineMetadata(f,!0,!0,n)});if(i(),a)for(let f of this.mounted.values()){let p=r.principal,g=`${p}\0${f.op}\0${We(f.args)}`;this.supersessionQueries.has(g)||this.supersessionQueries.set(g,{principal:p,op:f.op,args:f.args})}let u=[...this.supersessionQueries],c=r.coverageRevision,l=!1;for(let[,f]of u){if(i(),f.principal!==r.principal)continue;let p=await s("/api/query?receipt=1",{method:"POST",body:JSON.stringify({op:f.op,args:f.args})});i();let g=await _e(r,f.op,f.args,p,P);if(i(),ce(g.result),l=await lt(r,f.op,f.args,g,m=>this.offlineRefusal(m),c,()=>!n.aborted),i(),l||c!==r.coverageRevision)break}if(l||c!==r.coverageRevision)continue;let d=!1;if(a){let f=await He({runtime:r,json:s,signal:n,shape:P,failure:p=>this.offlineRefusal(p)});i(),d=f.reason==="fence"}let h=await r.completeReset(c,n);if(i(),!!h){for(let[f,p]of u)this.supersessionQueries.get(f)===p&&this.supersessionQueries.delete(f);if(this.supersessionQueries.size===0&&!r.resetNeeded&&!d)return}}throw new v({code:"E_OFFLINE_RESET",family:"offline",message:"the program changed during three coverage rebuild attempts",site:"client.resume",rewrite:"retry online() after the program stops rotating",guide:"offline"})}async drainNow(){let e=await this.operationAuthority();return this.offlineRuntime?He({runtime:this.offlineRuntime,json:(n,r)=>this.json(n,r,e),shape:P,failure:n=>this.offlineRefusal(n)}):{stopped:!1}}offlineRefusal(e){let n=this.createOptions?.offline?.store.carrier??this.createOptions?.offline?.store.name??"configured",r=jr(e,n);return this.recordRefusal(r.envelope),r}recordRefusal(e){this.patchSnapshot({lastRefusal:e})}validated(e){e!==void 0?this.ensureAuthority(e):this.ensureOpen(),this.forcedOffline||this.patchSnapshot({connection:"connected",lastRefusal:this.resetRefusal})}async operationAuthority(e=!0){for(await this.ready;;){let n=this.transitionTail;if(await n,n===this.transitionTail)break}return e&&await this.resumeTail,this.ensureOpen(),{authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken}}transition(e,n=!0,r){this.operationFence+=1,this.supersessionQueries.clear(),this.abortResume(),this.resetRefusal=void 0,this.closeTransports(r);let i=this.transitionTail.then(async()=>{await this.ready,this.ensureOpen(),n&&await this.settleWrites();let s={authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken};try{return await e(s)}finally{this.authGeneration+=1,this.publishAuthSnapshot()}});return this.transitionTail=i.then(()=>{},()=>{}),i}async expireSession(e,n){return e.token===void 0?{cleared:!1}:this.custody(async()=>{if(this.currentToken!==e.token||this.custodyGeneration!==e.custodyGeneration)return{cleared:!1};this.operationFence+=1;let r=this.operationFence,i=this.authGeneration+1;this.closeTransports(n);let s;try{try{await this.sealOffline()}catch(o){s=o}if(await this.clearTokenNow(),s!==void 0)throw s}finally{this.authGeneration+=1,this.publishAuthSnapshot()}return{cleared:!0,authGeneration:i,fence:r}})}expirationCurrent(e){return e.cleared&&!this.closed&&this.currentToken===void 0&&this.operationFence===e.fence&&this.authGeneration===e.authGeneration}async installToken(e){await this.custody(async()=>{this.ensureOpen(),await this.saveToken(e),await this.tokenStore?.savePrincipal?.(this.currentPrincipal??null),this.custodyGeneration+=1,this.ensureOpen(),this.currentToken=e})}custody(e){let n=this.custodyTail.then(e);return this.custodyTail=n.then(()=>{},()=>{}),n}async saveToken(e){if(this.tokenStore)try{await this.tokenStore.save(e)}catch(n){throw this.storageRefusal("save",n)}}async clearToken(){await this.custody(()=>this.clearTokenNow())}async clearTokenNow(){let e;if(this.tokenStore)try{await this.tokenStore.save(null),await this.tokenStore.savePrincipal?.(null)}catch(n){e=this.storageRefusal("clear",n)}if(this.currentToken=void 0,this.currentPrincipal=void 0,e)throw e}storageRefusal(e,n){let r=new v({code:"E_AUTH_TOKEN_STORE",family:"auth",message:`token store ${e} failed: ${n instanceof Error?n.message:String(n)}`,guide:"auth/session"});return this.recordRefusal(r.envelope),r}ensureBearerTransition(e){if(this.persona===void 0)return;let n=new v({code:"E_AUTH_PERSONA_TRANSITION",family:"auth",message:`dev persona clients cannot ${e} a bearer session`,guide:"auth/personas"});throw this.recordRefusal(n.envelope),n}trackWrite(e){let n=e();return this.writes.add(n),n.finally(()=>this.writes.delete(n)).catch(()=>{}),n}async settleWrites(){for(;this.writes.size>0;)await Promise.allSettled([...this.writes])}closeTransports(e){for(let n of[...this.subscriptions])n!==e&&n.close()}reconnectTransports(){for(let e of this.subscriptions)e.reconnect?.()}authorityCurrent(e){return e!==void 0&&!this.closed&&e.fence===this.operationFence&&e.authGeneration===this.authGeneration&&e.custodyGeneration===this.custodyGeneration&&e.token===this.currentToken}ensureAuthority(e){if(!this.authorityCurrent(e))throw this.supersededRefusal()}supersededRefusal(){return new v({code:"E_AUTH_SUPERSEDED",family:"auth",message:"operation belonged to a previous authentication generation",guide:"auth/session"})}ensureOpen(){if(this.closed)throw new v({code:"E_CLIENT_CLOSED",family:"owner",message:"client is closed",guide:"owner/connect"})}publishAuthSnapshot(){this.patchSnapshot({authGeneration:this.authGeneration,token:this.currentToken})}transportFailureState(){return this.forcedOffline||typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting"}patchSnapshot(e){let n={...this.currentSnapshot,...e};if(e.token===void 0&&"token"in e&&delete n.token,e.lastRefusal===void 0&&"lastRefusal"in e&&delete n.lastRefusal,JSON.stringify(n)===JSON.stringify(this.currentSnapshot))return this.currentSnapshot;this.currentSnapshot=n;for(let r of this.statusListeners)try{r(n)}catch{}return n}};function sa(t){return new kn(t)}export{v as SnapbackRefusal,Kr as api,Xi as browserTokenStore,sa as createClient,Oo as initialQueryState,_ as isSnapbackRefusal,Po as reduceQueryState,We as stableSerialize};
4
+ `)}if(e.aborted)throw dt();if(h.done){u=!0;break}}if(s.length>0){let h=c(s);h&&(yield h)}let d=c("");d&&(yield d)}finally{e.removeEventListener("abort",l),u||await r.cancel().catch(()=>{}),r.releaseLock()}}var ft=class{constructor(e){this.options=e;this.start()}controller=new AbortController;waiters=new Set;last;lastEventId;terminalFailure;closed=!1;activeAttempt;retryNow;resets=0;running;close(){if(!this.closed){this.closed=!0,this.controller.abort();for(let e of this.waiters)clearTimeout(e.timer),e.reject(dt());this.waiters.clear()}}reconnect(){this.closed||(this.activeAttempt?.abort(),this.retryNow?.())}reset(){this.closed||(this.terminalFailure=void 0,this.resets+=1,this.lastEventId=void 0,this.last=void 0,this.reconnect(),this.start())}until(e,n=3e4){return this.terminalFailure?Promise.reject(this.terminalFailure):this.last!==void 0&&e(this.last)?Promise.resolve(this.last):this.closed?Promise.reject(dt()):new Promise((r,i)=>{let s={predicate:e,resolve:r,reject:i,timer:setTimeout(()=>{this.waiters.delete(s),i(new Error(`subscription condition timed out after ${n} ms`))},n)};this.waiters.add(s)})}deliver(e,n=!0){this.last=e;try{this.options.onEvent?.(e)}catch{}if(n)for(let r of[...this.waiters]){let i=!1;try{i=r.predicate(e)}catch(s){clearTimeout(r.timer),this.waiters.delete(r),r.reject(s instanceof Error?s:new Error(String(s)));continue}i&&(clearTimeout(r.timer),this.waiters.delete(r),r.resolve(e))}}fail(e){this.terminalFailure=e;for(let n of this.waiters)clearTimeout(n.timer),n.reject(e);this.waiters.clear()}start(){if(this.closed||this.running)return;let e=this.resets,n=this.run();this.running=n,n.finally(()=>{this.running=void 0,!this.closed&&!this.terminalFailure&&e!==this.resets&&this.start()}).catch(()=>{})}async run(){let e=250,n=!1,r=!1;for(;!this.closed;){let i=this.resets,s=new AbortController;this.activeAttempt=s;let o=()=>s.abort();this.controller.signal.addEventListener("abort",o,{once:!0});let a,u=!1,c,l=()=>!this.closed&&i===this.resets&&!s.signal.aborted,d=()=>{a!==void 0&&clearTimeout(a),a=setTimeout(()=>{u=!0,s.abort()},3e4)};try{d();let h=await this.options.open(this.lastEventId,s.signal);if(!h.ok)throw h;for await(let f of Yi(h,s.signal,d)){if(this.closed||s.signal.aborted){let m;try{m=this.options.bufferedTerminal?.(f)}catch{}if(m!==void 0){try{await this.options.onError(m,n)}catch{}return}continue}try{c=this.options.bufferedTerminal?.(f)}catch{c=void 0}let p=await this.options.decode(f,l);if(c=void 0,!l())continue;f.id!==void 0&&(this.lastEventId=f.id),this.deliver(p),n=!0,r=!1,e=250;let g=this.options.terminal?.(p);if(g!==void 0){this.fail(g);return}}if(this.closed)return;if(i===this.resets&&!r){let f=this.options.onLoss(this.last);f!==void 0&&this.deliver(f),r=!0}}catch(h){if(c&&!l()){let g=await this.options.onError(c,n);this.closed||(g.event!==void 0&&this.deliver(g.event,g.failure===void 0),g.failure!==void 0&&this.fail(g.failure));return}if(this.closed||this.controller.signal.aborted)return;if(i!==this.resets)continue;let f=u?new Error("SSE stream idle for 30000 ms"):h,p=await this.options.onError(f,n);if(this.closed||this.controller.signal.aborted||(p.event!==void 0&&this.deliver(p.event,p.failure===void 0),p.failure!==void 0&&this.fail(p.failure),!p.retry))return;if(!r){let g=this.options.onLoss(this.last);g!==void 0&&this.deliver(g),r=!0}}finally{a!==void 0&&clearTimeout(a),this.controller.signal.removeEventListener("abort",o),this.activeAttempt===s&&(this.activeAttempt=void 0)}if(i===this.resets){try{await Promise.race([Ki(e,this.controller.signal),new Promise(h=>{this.retryNow=h})])}catch{return}finally{this.retryNow=void 0}e=Math.min(e*2,5e3)}}}};function Xi(t,e){if(!t||typeof t.getItem!="function"||typeof t.setItem!="function"||typeof t.removeItem!="function")throw new TypeError("browserTokenStore requires an explicit Storage implementation");if(!e)throw new TypeError("browserTokenStore requires a non-empty key");return{load:()=>t.getItem(e),save:n=>{n===null?t.removeItem(e):t.setItem(e,n)},loadPrincipal:()=>t.getItem(`${e}:principal`),savePrincipal:n=>{n===null?t.removeItem(`${e}:principal`):t.setItem(`${e}:principal`,n)}}}var kn=class t{auth;outbox;ready;url;fetchImpl;customFetch;tokenStore;persona;createOptions;offlineRuntime;mounted=new Map;offlineMetadataLoaded=!1;resumeTail=Promise.resolve();resumeFlight;resumeController;resetRefusal;supersessionQueries=new Map;forcedOffline=!1;currentToken;currentPrincipal;authGeneration=0;custodyGeneration=0;operationFence=0;transitionTail=Promise.resolve();custodyTail=Promise.resolve();currentSnapshot;statusListeners=new Set;subscriptions=new Set;writes=new Set;carrier;closed=!1;closing=Promise.resolve();constructor(e){if(!e?.url)throw new TypeError("createClient requires url");if(e.as!==void 0&&(e.token!==void 0||e.tokenStore!==void 0))throw new TypeError("createClient cannot combine dev persona `as` with bearer token custody");if(this.createOptions=e,this.url=e.url.replace(/\/+$/,""),this.fetchImpl=e.fetch??globalThis.fetch?.bind(globalThis),this.customFetch=e.fetch!==void 0,typeof this.fetchImpl!="function")throw new TypeError("createClient requires a fetch implementation");this.tokenStore=e.tokenStore,this.persona=e.as,this.forcedOffline=e.startOffline===!0,this.currentSnapshot={authGeneration:0,persona:e.as,connection:this.forcedOffline?"offline":"reconnecting"},wn(e.offline);try{this.offlineRuntime=Cr(e.offline)}catch(n){throw this.offlineRefusal(n)}this.outbox=Tr(this.offlineRuntime,()=>this.drainNow(),()=>this.ready),this.auth={signup:n=>this.session("/api/auth/signup",n),login:n=>this.session("/api/auth/login",n),guest:()=>this.session("/api/auth/guest",{}),logout:()=>this.logout(),me:()=>this.me()},this.ready=this.hydrate(e.token).then(()=>this.initializeOffline())}get snapshot(){return this.currentSnapshot}async query(e,n){let r=await this.operationAuthority(!1),i=le(e);if(this.forcedOffline)return this.patchSnapshot({connection:"offline"}),je(this.offlineRuntime,i,n,o=>this.offlineRefusal(o));await this.ensureOfflineMetadata(r),this.scheduleSupersessionReset(r);let s=50;for(let o=1;;o+=1)try{let a=await this.offlineRuntime?.answer(i,n),u=this.offlineRuntime?.coverageRevision,c=await this.json(this.offlineRuntime?"/api/query?receipt=1":"/api/query",{method:"POST",body:JSON.stringify(this.offlineRuntime&&a?.validator?{op:i,args:n,validator:a.validator}:{op:i,args:n})},r),l=await _e(this.offlineRuntime,i,n,c,P),d=ce(l.result),h=await lt(this.offlineRuntime,i,n,l,f=>this.offlineRefusal(f),u);if(this.validated(r),(h||u!==this.offlineRuntime?.coverageRevision)&&this.scheduleSupersessionReset(r,{op:i,args:n}),this.offlineRuntime&&this.createOptions.offlineReadObserver){let f=await je(this.offlineRuntime,i,n,p=>this.offlineRefusal(p));this.createOptions.offlineReadObserver(e,n,f)}return d}catch(a){if(_(a)&&a.retryable&&this.offlineRuntime&&o>=3)return this.patchSnapshot({connection:"offline"}),je(this.offlineRuntime,i,n,u=>this.offlineRefusal(u));if(!_(a)||a.code!=="E_TRANSPORT"&&a.code!=="E_NETWORK"||!a.retryable||o>=3)throw a;await new Promise(u=>setTimeout(u,s)),this.ensureAuthority(r),s*=2}}async mutation(e,n){let r=await this.operationAuthority();return this.trackWrite(async()=>{try{let i=n;if(yt(n)){let o=le(e),a=await this.manifestFor(r),u=a.ops[o]?.args;if(u===void 0)throw W(this,new x("E_ASSET_TYPE",`manifest generation ${a.generation} has no argument descriptor for ${o}`));let c=await Bn(n,u).catch(l=>{throw W(this,l)});if(c.length>0){let l=[];for(let h of c)l.push(await xn(this,h.prepared,{},r));let d=await this.manifestFor(r);if(d.generation!==a.generation)throw W(this,new x("E_ASSET_NOT_READY",`descriptor generation changed from ${a.generation} to ${d.generation} during asset upload`));i=Fn(n,c,l)}}let s=await Pr({runtime:this.offlineRuntime,offline:this.forcedOffline,op:le(e),args:i,json:(o,a)=>this.json(o,a,r),failure:o=>this.offlineRefusal(o),drain:()=>this.drainNow()});if(s.state==="rejected"&&F(s)){let o=this.authorityCurrent(r),a=await this.expireSession(r);if(!o||!this.expirationCurrent(a))throw this.supersededRefusal();return this.recordRefusal(s),s}return this.validated(r),s}catch(i){if(_(i)&&i.code==="E_WIRE_SHAPE"){let s=new v(z(i.envelope),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:s.envelope}),s}throw i}})}async upload(e,n={}){let r=await this.operationAuthority();return this.trackWrite(()=>Wr(this,e,n,r))}async assetUrl(e,n={}){return Gr(this,e,n,await this.operationAuthority())}async assetHeaders(){return Qr(this,await this.operationAuthority())}async assetBlob(e,n={}){let r=await this.operationAuthority();return zr(this,this.offlineRuntime?.bytes,()=>this.forcedOffline,e,n,r)}async assetBytes(e,n={}){let r=await this.operationAuthority();return Jr(this,this.offlineRuntime?.bytes,()=>this.forcedOffline,e,n,r)}get assetCache(){return this.offlineRuntime?.bytes}subscribe(e,n,r,i={}){return i.drain?this.drain(e,n,r):this.subscribeRegular(e,n,r)}subscribeRegular(e,n,r){let i=le(e),s=`${i}\0${We(n)}`;this.mounted.set(s,{op:i,args:n,drain:!1});let o,a,u,c,l=f=>(o=qr(f,()=>this.ensureAuthority(u),p=>this.patchSnapshot({...p,lastRefusal:p.lastRefusal??this.resetRefusal})),f);c=new ft({open:async(f,p)=>{if(u??=await this.operationAuthority(),this.forcedOffline)throw Ce();await this.ensureOfflineMetadata(u),this.scheduleSupersessionReset(u),a=this.offlineRuntime?.coverageRevision;let g=await this.offlineRuntime?.answer(i,n),m=`/api/subscribe?op=${encodeURIComponent(i)}&args=${encodeURIComponent(JSON.stringify(n))}`;return this.offlineRuntime&&(m+="&receipt=1"),g?.validator&&(m+=`&validator=${encodeURIComponent(g.validator)}`),this.stream(m,f,p,u)},decode:({data:f},p)=>{let g=a;return this.offlineRuntime?Vr({runtime:this.offlineRuntime,op:i,args:n,data:f,shape:P,failure:m=>this.offlineRefusal(m),revision:g,current:p,superseded:()=>this.scheduleSupersessionReset(u,{op:i,args:n}),observe:this.createOptions.offlineReadObserver?async()=>this.createOptions.offlineReadObserver(e,n,await je(this.offlineRuntime,i,n,m=>this.offlineRefusal(m))):void 0}).then(m=>p()||m.state==="refused"&&F(m)?l(m):m):l(Ge(f))},bufferedTerminal:({data:f})=>{let p=Ge(f);return p.state==="refused"&&F(p)?new v(z(p)):void 0},onError:async f=>{let{retry:p,event:g,refusal:m}=await this.subscriptionError(f,u,c);if(p&&this.offlineRuntime){this.patchSnapshot({connection:"offline"});let b=await je(this.offlineRuntime,i,n,S=>this.offlineRefusal(S));return{retry:p,event:b,failure:m}}return{retry:p,event:g===void 0?void 0:{...g,live:!1},failure:m}},onLoss:()=>{if(this.authorityCurrent(u)&&(this.patchSnapshot({connection:this.transportFailureState()}),!this.offlineRuntime&&o))return"data"in o?{state:"stale",live:!1,since:Date.now(),seq:o.seq,data:o.data}:{state:"stale",live:!1,since:Date.now(),seq:o.seq}},terminal:f=>f.state==="refused"?new v(z(f)):void 0,onEvent:r});let d=this.track(c),h=d.close.bind(d);return d.close=()=>{this.mounted.delete(s),h()},d}drain(e,n,r){let i=le(e);return Nr({ref:e,op:i,args:n,callback:r,runtime:this.offlineRuntime,ready:this.ready,mounted:this.mounted,query:s=>this.query(e,s),subscribe:(s,o)=>this.subscribeRegular(e,s,o),track:s=>this.track(s),resume:async()=>this.performResume(await this.operationAuthority()),observe:this.offlineRuntime&&this.createOptions.offlineReadObserver?async()=>this.createOptions.offlineReadObserver(e,n,await je(this.offlineRuntime,i,n,s=>this.offlineRefusal(s))):void 0})}channel(e,n){let r=le(e),i=encodeURIComponent(r.startsWith("channels.")?r.slice(9):r);return{publish:async s=>{let o=await this.operationAuthority();return this.trackWrite(async()=>{let a=Pn(await this.json(`/api/channel/${i}/publish`,{method:"POST",body:JSON.stringify({args:n,payload:s})},o));if("state"in a){if(F(a)){let u=this.authorityCurrent(o),c=await this.expireSession(o);if(!u||!this.expirationCurrent(c))throw this.supersededRefusal()}this.recordRefusal(a)}else this.validated(o);return a})},subscribe:s=>{let o=`/api/channel/${i}/subscribe?args=${encodeURIComponent(JSON.stringify(n))}`,a,u;return u=new ft({open:async(c,l)=>(a??=await this.operationAuthority(),this.stream(o,c,l,a)),decode:({data:c})=>{let l=Ut(c);if("state"in l&&l.state==="refused"&&F(l))throw new v(z(l));return this.ensureAuthority(a),this.patchSnapshot({connection:"connected",lastRefusal:"state"in l&&l.state==="refused"?z(l):void 0}),l},bufferedTerminal:({data:c})=>{let l=Ut(c);return"state"in l&&l.state==="refused"&&F(l)?new v(z(l)):void 0},onError:async c=>{let l=await this.subscriptionError(c,a,u);return{retry:l.retry,event:l.event,failure:l.refusal}},onLoss:()=>{this.authorityCurrent(a)&&this.patchSnapshot({connection:this.transportFailureState()})},terminal:c=>"state"in c&&c.state==="refused"?new v(z(c)):void 0,onEvent:s}),this.track(u)}}}async manifest(){let e=await this.operationAuthority();return this.manifestFor(e)}async offline(){return Br({ready:this.ready,ensureOpen:()=>this.ensureOpen(),force:e=>{this.forcedOffline=e},connection:e=>{this.patchSnapshot({connection:e})},reconnect:()=>this.reconnectTransports()})}async online(){return Dr({ready:this.ready,ensureOpen:()=>this.ensureOpen(),force:e=>{this.forcedOffline=e},connection:e=>{this.patchSnapshot({connection:e})},authority:()=>this.operationAuthority(),resume:e=>this.performResume(e),setResume:e=>{this.resumeTail=e},reconnect:()=>this.reconnectTransports()})}async restart(){return Mr({ready:this.ready,ensureOpen:()=>this.ensureOpen(),forced:()=>this.forcedOffline,shutdown:async()=>{this.closed=!0,this.abortResume(),this.operationFence+=1,this.closeTransports(),this.patchSnapshot({connection:"offline"}),await this.offlineRuntime?.close()},create:()=>{let e=this.createOptions.offline,n=this.persona!==void 0?{url:this.url,as:this.persona,fetch:this.fetchImpl,offline:e,startOffline:this.forcedOffline,offlineReadObserver:this.createOptions.offlineReadObserver}:{url:this.url,token:this.currentToken,tokenStore:this.tokenStore,fetch:this.fetchImpl,offline:e,offlinePrincipal:this.currentPrincipal,startOffline:this.forcedOffline,offlineReadObserver:this.createOptions.offlineReadObserver};return new t(n)}})}subscribeStatus(e){this.statusListeners.add(e);try{e(this.currentSnapshot)}catch(n){throw this.statusListeners.delete(e),n}return()=>this.statusListeners.delete(e)}close(){return this.closed?this.closing:(this.closed=!0,this.abortResume(),this.operationFence+=1,this.closeTransports(),this.patchSnapshot({connection:"offline"}),this.closing=this.offlineRuntime?.close()??Promise.resolve(),this.closing)}track(e){this.subscriptions.add(e);let n=e.close.bind(e);return e.close=()=>{this.subscriptions.delete(e),n()},e}async session(e,n){return this.ensureBearerTransition(e.slice(10)),this.transition(async r=>{let i=In(Or(this.offlineRuntime,await this.json(e,{method:"POST",body:JSON.stringify(n)},r,!1,!1)),`${e.slice(5)} response`);await this.openOffline(i.viewer,!0),await this.installToken(i.token),this.ensureOpen();try{await this.ensureOfflineMetadata({authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken})}catch(s){if(!_(s)||!s.retryable)throw s}return this.validated(void 0),i})}async logout(){return this.ensureBearerTransition("logout"),this.transition(async e=>{let n,r;try{n=$n(await this.json("/api/auth/logout",{method:"POST"},e,!1,!1))}catch(s){r=s}let i;try{await this.wipeOffline()}catch(s){i=s}if(await this.clearToken(),this.ensureOpen(),r!==void 0)throw r;if(i!==void 0)throw i;return this.validated(void 0),n})}async me(){let e=await this.operationAuthority(),n=Lt(await this.json("/api/auth/me",{},e));return await this.openOffline(n.viewer,!0),this.validated(e),n}async hydrate(e){let n=e,r;if(n===void 0&&this.tokenStore)try{let[i,s]=await Promise.all([this.tokenStore.load(),this.tokenStore.loadPrincipal?.()]);n=i??void 0,r=s}catch(i){throw this.storageRefusal("load",i)}if(n!==void 0&&(typeof n!="string"||n.length===0))throw this.storageRefusal("load",new TypeError("stored token must be a non-empty string or null"));e!==void 0&&await this.saveToken(n),!this.closed&&(this.currentToken=n,n!==void 0&&r&&(this.currentPrincipal=r),this.authGeneration+=1,this.publishAuthSnapshot())}headers(e,n=!1,r=!1){let i=new Headers;return i.set("Accept",n?"text/event-stream":"application/json"),r&&i.set("Content-Type","application/json"),e.token&&i.set("Authorization",`Bearer ${e.token}`),this.persona&&i.set("X-Snapback-As",this.persona),i}async manifestFor(e,n){E(n);let r=_n(await this.json("/api/manifest",{signal:n},e));return E(n),this.validated(e),this.patchSnapshot({generation:r.generation}),this.offlineRuntime?.manifest(r),this.offlineRuntime&&this.offlineRuntime.programGeneration!==r.programGeneration&&(this.offlineMetadataLoaded=!1),r}async ensureOfflineMetadata(e,n=!1,r=!0,i){if(E(i),!this.offlineRuntime||this.offlineMetadataLoaded&&!n)return;let s;try{s=await this.manifestFor(e,i),E(i)}catch(o){if(!n&&_(o)&&o.retryable)return;throw o}if(this.offlineRuntime.programGeneration!==s.programGeneration||n)try{let o=await this.json(`/api/program?generation=${encodeURIComponent(s.programGeneration)}`,{signal:i},e);E(i),await this.offlineRuntime.program(o,i),E(i)}catch(o){if(!_(o)||o.status!==404)throw o;if(n){if(r)return this.ensureOfflineMetadata(e,!0,!1,i);throw o}}this.offlineMetadataLoaded=!0}networkRefusal(e){let n=new v(Z("E_NETWORK",e),!0);return this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:n.envelope}),n}transportRefusal(e){let n=new v(Z("E_TRANSPORT",e),!0);return this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:n.envelope}),n}async json(e,n,r,i=!0,s=!0){if(i?this.ensureAuthority(r):this.ensureOpen(),this.forcedOffline)throw Ce();let o;try{o=await this.fetchImpl(`${this.url}${e}`,{...n,headers:this.headers(r,!1,n.body!==void 0&&n.body!==null)})}catch(c){i?this.ensureAuthority(r):this.ensureOpen();let l=new v(Z("E_NETWORK",c instanceof Error?c.message:String(c)),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:l.envelope}),l}if(!o.ok){if(o.status>=400&&o.status<500){let l;try{l=await Ve(o)}catch(f){throw _(f)&&(i?this.ensureAuthority(r):this.ensureOpen(),f.retryable&&this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:f.envelope})),f}let d=!i||this.authorityCurrent(r),h;throw s&&F(l.envelope)&&(h=await this.expireSession(r)),i&&(!d||h!==void 0&&!this.expirationCurrent(h))?this.supersededRefusal():(i&&!(s&&F(l.envelope))?this.ensureAuthority(r):this.ensureOpen(),this.patchSnapshot({connection:"connected"}),this.recordRefusal(l.envelope),l)}i?this.ensureAuthority(r):this.ensureOpen();let c=new v(Z("E_TRANSPORT",`${e} returned HTTP ${o.status}`),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:c.envelope}),c}let a;try{a=await o.json()}catch{i?this.ensureAuthority(r):this.ensureOpen();let c=P(`${e} must contain valid JSON`);throw this.recordRefusal(c.envelope),c}let u;try{u=s?Tn(a):void 0}catch(c){throw i?this.ensureAuthority(r):this.ensureOpen(),c}if(u!==void 0&&i&&!this.authorityCurrent(r))throw await this.expireSession(r),this.supersededRefusal();return i?this.ensureAuthority(r):this.ensureOpen(),this.patchSnapshot({connection:"connected"}),a}async stream(e,n,r,i){if(this.ensureAuthority(i),this.forcedOffline)throw Ce();let s=this.headers(i,!0);n!==void 0&&s.set("Last-Event-ID",n);try{let o=await this.fetchImpl(`${this.url}${e}`,{headers:s,signal:r});if(!o.ok){if(o.status>=400&&o.status<500){let a;try{a=await Ve(o)}catch(u){if(_(u)&&!u.retryable)throw u}if(a!==void 0)throw F(a.envelope)&&(r.aborted||!this.authorityCurrent(i))?(await this.expireSession(i),this.supersededRefusal()):(F(a.envelope)||this.ensureAuthority(i),a)}throw this.ensureAuthority(i),new v(Z("E_HTTP",`${e} returned HTTP ${o.status}`),!0)}return this.ensureAuthority(i),E(r),this.patchSnapshot({connection:"connected"}),o}catch(o){if(_(o)&&F(o.envelope)||(this.ensureAuthority(i),r.aborted))throw o;if(_(o))throw this.patchSnapshot({connection:o.retryable?this.transportFailureState():"connected",lastRefusal:o.envelope}),o;let a=new v(Z("E_NETWORK",o instanceof Error?o.message:String(o)),!0);throw this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:a.envelope}),a}}async subscriptionError(e,n,r){let i=_(e)?e:new v(Z("E_NETWORK",e instanceof Error?e.message:String(e)),!0);if(i.code==="E_AUTH_SUPERSEDED")return{retry:!1,refusal:i};if(F(i.envelope)&&n!==void 0){let s=this.authorityCurrent(n),o;try{o=await this.expireSession(n,r)}catch(a){if(this.closed)return{retry:!1,refusal:this.supersededRefusal()};let u=_(a)?a:new v({code:"E_AUTH_TOKEN_STORE",family:"auth",message:`token store clear failed: ${a instanceof Error?a.message:String(a)}`,guide:"auth/session"});return this.patchSnapshot({connection:"connected",lastRefusal:u.envelope}),{retry:!1,refusal:u,event:{state:"refused",...u.envelope}}}if(this.closed)return{retry:!1,refusal:this.supersededRefusal()};if(!s||!this.expirationCurrent(o))return{retry:!1,refusal:this.supersededRefusal()}}return this.closed?{retry:!1,refusal:this.supersededRefusal()}:i.retryable?(this.patchSnapshot({connection:this.transportFailureState(),lastRefusal:i.envelope}),{retry:!0}):(this.patchSnapshot({connection:"connected",lastRefusal:i.envelope}),{retry:!1,refusal:i,event:{state:"refused",...i.envelope}})}async initializeOffline(){if(!this.offlineRuntime)return;let e={authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken};return Fr({principal:this.persona===void 0?this.createOptions.offlinePrincipal??this.currentPrincipal:`dev:${this.persona}`,bearer:this.persona===void 0&&this.currentToken!==void 0,authority:e,open:(n,r)=>this.openOffline(n,r),confirm:async n=>Lt(await this.json("/api/auth/me",{},n)).viewer,metadata:n=>this.ensureOfflineMetadata(n),resume:n=>this.performResume(n),ignore:n=>_(n)&&(n.retryable||n.code==="E_OFFLINE_RESUME"||n.code==="E_OFFLINE_RESET")})}async openOffline(e,n=!1){if(this.offlineRuntime)try{let r=this.offlineRuntime.principal!==e;await this.offlineRuntime.open(e,n),n&&await this.offlineRuntime.reauthenticate(e),this.currentPrincipal=e,r&&(this.supersessionQueries.clear(),this.offlineMetadataLoaded=!1)}catch(r){throw this.offlineRefusal(r)}}async sealOffline(){if(this.offlineRuntime)try{await this.offlineRuntime.seal()}catch(e){throw this.offlineRefusal(e)}}async wipeOffline(){if(this.offlineRuntime){this.abortResume(),this.supersessionQueries.clear();try{await this.offlineRuntime.wipe(),this.currentPrincipal=void 0}catch(e){throw this.offlineRefusal(e)}}}scheduleSupersessionReset(e,n){let r=this.offlineRuntime?.principal;!this.authorityCurrent(e)||r===void 0||(n&&this.supersessionQueries.set(`${r}\0${n.op}\0${We(n.args)}`,{principal:r,...n}),!(this.forcedOffline||!this.offlineRuntime?.resetNeeded&&this.supersessionQueries.size===0)&&this.performResume(e).catch(()=>{}))}performResume(e){if(!this.offlineRuntime||this.forcedOffline)return Promise.resolve();if(this.resumeFlight)return this.resumeFlight;let n=new AbortController;this.resumeController=n;let r=this.resumeOffline(e,n.signal).then(()=>{E(n.signal),this.ensureAuthority(e),this.resetRefusal=void 0,this.validated(e)},i=>{if(this.authorityCurrent(e)){let s=this.offlineRefusal(i);this.resetRefusal=s.envelope}throw i});return this.resumeFlight=r,r.then(()=>{this.resumeFlight===r&&(this.resumeFlight=void 0,this.resumeController=void 0,this.scheduleSupersessionReset(e))},()=>{this.resumeFlight===r&&(this.resumeFlight=void 0,this.resumeController=void 0)}),r}abortResume(){this.resumeController?.abort(),this.resumeController=void 0,this.resumeFlight=void 0}async resumeOffline(e,n){let r=this.offlineRuntime,i=()=>{E(n),this.ensureAuthority(e)},s=async(o,a)=>{i();let u=await this.json(o,{...a,signal:n},e);return i(),u};await this.ensureOfflineMetadata(e,!1,!0,n),i();for(let o=0;o<3;o++){let a=await bn({runtime:r,mounted:this.mounted,authority:e,signal:n,bearerConfirmed:e.token!==void 0,json:s,validated:f=>{i(),this.validated(f)},shape:P,failure:f=>this.offlineRefusal(f),subscriptions:this.subscriptions,reload:f=>this.ensureOfflineMetadata(f,!0,!0,n)});if(i(),a)for(let f of this.mounted.values()){let p=r.principal,g=`${p}\0${f.op}\0${We(f.args)}`;this.supersessionQueries.has(g)||this.supersessionQueries.set(g,{principal:p,op:f.op,args:f.args})}let u=[...this.supersessionQueries],c=r.coverageRevision,l=!1;for(let[,f]of u){if(i(),f.principal!==r.principal)continue;let p=await s("/api/query?receipt=1",{method:"POST",body:JSON.stringify({op:f.op,args:f.args})});i();let g=await _e(r,f.op,f.args,p,P);if(i(),ce(g.result),l=await lt(r,f.op,f.args,g,m=>this.offlineRefusal(m),c,()=>!n.aborted),i(),l||c!==r.coverageRevision)break}if(l||c!==r.coverageRevision)continue;let d=!1;if(a){let f=await He({runtime:r,json:s,signal:n,shape:P,failure:p=>this.offlineRefusal(p)});i(),d=f.reason==="fence"}let h=await r.completeReset(c,n);if(i(),!!h){for(let[f,p]of u)this.supersessionQueries.get(f)===p&&this.supersessionQueries.delete(f);if(this.supersessionQueries.size===0&&!r.resetNeeded&&!d)return}}throw new v({code:"E_OFFLINE_RESET",family:"offline",message:"the program changed during three coverage rebuild attempts",site:"client.resume",rewrite:"retry online() after the program stops rotating",guide:"offline"})}async drainNow(){let e=await this.operationAuthority();return this.offlineRuntime?He({runtime:this.offlineRuntime,json:(n,r)=>this.json(n,r,e),shape:P,failure:n=>this.offlineRefusal(n)}):{stopped:!1}}offlineRefusal(e){let n=this.createOptions?.offline?.store.carrier??this.createOptions?.offline?.store.name??"configured",r=jr(e,n);return this.recordRefusal(r.envelope),r}recordRefusal(e){this.patchSnapshot({lastRefusal:e})}validated(e){e!==void 0?this.ensureAuthority(e):this.ensureOpen(),this.forcedOffline||this.patchSnapshot({connection:"connected",lastRefusal:this.resetRefusal})}async operationAuthority(e=!0){for(await this.ready;;){let n=this.transitionTail;if(await n,n===this.transitionTail)break}return e&&await this.resumeTail,this.ensureOpen(),{authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken}}transition(e,n=!0,r){this.operationFence+=1,this.supersessionQueries.clear(),this.abortResume(),this.resetRefusal=void 0,this.closeTransports(r);let i=this.transitionTail.then(async()=>{await this.ready,this.ensureOpen(),n&&await this.settleWrites();let s={authGeneration:this.authGeneration,custodyGeneration:this.custodyGeneration,fence:this.operationFence,token:this.currentToken};try{return await e(s)}finally{this.authGeneration+=1,this.publishAuthSnapshot()}});return this.transitionTail=i.then(()=>{},()=>{}),i}async expireSession(e,n){return e.token===void 0?{cleared:!1}:this.custody(async()=>{if(this.currentToken!==e.token||this.custodyGeneration!==e.custodyGeneration)return{cleared:!1};this.operationFence+=1;let r=this.operationFence,i=this.authGeneration+1;this.closeTransports(n);let s;try{try{await this.sealOffline()}catch(o){s=o}if(await this.clearTokenNow(),s!==void 0)throw s}finally{this.authGeneration+=1,this.publishAuthSnapshot()}return{cleared:!0,authGeneration:i,fence:r}})}expirationCurrent(e){return e.cleared&&!this.closed&&this.currentToken===void 0&&this.operationFence===e.fence&&this.authGeneration===e.authGeneration}async installToken(e){await this.custody(async()=>{this.ensureOpen(),await this.saveToken(e),await this.tokenStore?.savePrincipal?.(this.currentPrincipal??null),this.custodyGeneration+=1,this.ensureOpen(),this.currentToken=e})}custody(e){let n=this.custodyTail.then(e);return this.custodyTail=n.then(()=>{},()=>{}),n}async saveToken(e){if(this.tokenStore)try{await this.tokenStore.save(e)}catch(n){throw this.storageRefusal("save",n)}}async clearToken(){await this.custody(()=>this.clearTokenNow())}async clearTokenNow(){let e;if(this.tokenStore)try{await this.tokenStore.save(null),await this.tokenStore.savePrincipal?.(null)}catch(n){e=this.storageRefusal("clear",n)}if(this.currentToken=void 0,this.currentPrincipal=void 0,e)throw e}storageRefusal(e,n){let r=new v({code:"E_AUTH_TOKEN_STORE",family:"auth",message:`token store ${e} failed: ${n instanceof Error?n.message:String(n)}`,guide:"auth/session"});return this.recordRefusal(r.envelope),r}ensureBearerTransition(e){if(this.persona===void 0)return;let n=new v({code:"E_AUTH_PERSONA_TRANSITION",family:"auth",message:`dev persona clients cannot ${e} a bearer session`,guide:"auth/personas"});throw this.recordRefusal(n.envelope),n}trackWrite(e){let n=e();return this.writes.add(n),n.finally(()=>this.writes.delete(n)).catch(()=>{}),n}async settleWrites(){for(;this.writes.size>0;)await Promise.allSettled([...this.writes])}closeTransports(e){for(let n of[...this.subscriptions])n!==e&&n.close()}reconnectTransports(){for(let e of this.subscriptions)e.reconnect?.()}authorityCurrent(e){return e!==void 0&&!this.closed&&e.fence===this.operationFence&&e.authGeneration===this.authGeneration&&e.custodyGeneration===this.custodyGeneration&&e.token===this.currentToken}ensureAuthority(e){if(!this.authorityCurrent(e))throw this.supersededRefusal()}supersededRefusal(){return new v({code:"E_AUTH_SUPERSEDED",family:"auth",message:"operation belonged to a previous authentication generation",guide:"auth/session"})}ensureOpen(){if(this.closed)throw new v({code:"E_CLIENT_CLOSED",family:"owner",message:"client is closed",guide:"owner/connect"})}publishAuthSnapshot(){this.patchSnapshot({authGeneration:this.authGeneration,token:this.currentToken})}transportFailureState(){return this.forcedOffline||typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting"}patchSnapshot(e){let n={...this.currentSnapshot,...e};if(e.token===void 0&&"token"in e&&delete n.token,e.lastRefusal===void 0&&"lastRefusal"in e&&delete n.lastRefusal,JSON.stringify(n)===JSON.stringify(this.currentSnapshot))return this.currentSnapshot;this.currentSnapshot=n;for(let r of this.statusListeners)try{r(n)}catch{}return n}};function sa(t){return new kn(t)}export{v as SnapbackRefusal,Kr as api,Xi as browserTokenStore,sa as createClient,Oo as initialQueryState,_ as isSnapbackRefusal,Po as reduceQueryState,We as stableSerialize};
5
5
  //# sourceMappingURL=client.mjs.map