jazz-tools 2.0.0-alpha.66 → 2.0.0-alpha.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./esm-D_R-EGgt.js","./esm-xNe3wI_B.js","./create-legacy-browser-delegate-Bf58kV5i.js","./esm-DEBYi0LL.js","./trace-api-BctnwbUf.js","./esm-D-TBoHij.js","./src-wuDHsXUe.js","./src-Cq8gSOLx.css","./esm-WihpI9g6.js","./esm-DT3MY99S.js"])))=>i.map(i=>d[i]);
2
- import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as D,N as O,Nt as ee,O as te,Ot as ne,P as re,Pt as ie,Q as ae,Qt as k,R as oe,Rt as se,S as ce,St as le,T as ue,Tt as A,U as de,Ut as fe,V as pe,Vt as me,W as he,Wt as j,X as ge,Xt as _e,Y as ve,Yt as M,Z as ye,Zt as be,_ as xe,_t as Se,an as N,at as Ce,b as we,bt as Te,cn as Ee,dt as De,en as Oe,et as ke,ft as Ae,g as je,gt as Me,h as Ne,ht as Pe,in as Fe,it as Ie,j as Le,jt as P,k as Re,kt as ze,m as Be,mt as Ve,nn as He,nt as Ue,on as We,ot as Ge,pt as Ke,q as qe,qt as Je,rn as Ye,rt as Xe,st as Ze,t as Qe,tn as $e,tt as et,ut as tt,v as nt,vt as rt,w as it,wt as at,x as ot,xt as F,y as st,yt as ct,z as lt,zt as ut}from"./src-wuDHsXUe.js";var dt=N(),I=Ee(We(),1),ft=new WeakMap;function pt(e){let t=ft.get(e)??-2;if(!Number.isSafeInteger(t))throw Error(`Inspector request identifiers exhausted`);return ft.set(e,t-1),t}function mt(e,t,n,r){let i=!1,a=new Map,o=new Set,s=new Map,c=new Map,l=({data:e})=>{if(e.type===`error`||e.type===`auth-failure`||e.type===`storage-invalidated`||e.type===`storage-reset`){u();return}if(e.type!==`inspector-query-result`&&e.type!==`result`||e.id>=-1)return;let t=e.error&&He(e.error),n=s.get(e.id);if(n){s.delete(e.id),t?n.reject(t):e.type===`inspector-query-result`?n.resolve(e.value):n.reject(Error(`Unexpected Inspector query response`));return}let r=c.get(e.id);r&&(t||e.type===`inspector-query-result`)&&r.callback?.(t??e.value)},u=()=>{if(i)return;i=!0,t.removeEventListener(`message`,l),t.removeEventListener(`messageerror`,d);let e=Error(`Inspector cache connection closed`);for(let t of s.values())t.reject(e);s.clear(),a.clear(),o.clear();for(let[r,i]of c){try{i.started&&t.postMessage({type:`inspect-unsubscribe`,id:r,binding:n})}catch{}try{i.callback?.(e)}catch(e){console.error(`Inspector subscription close callback failed`,e)}}c.clear()},d=()=>u();t.addEventListener(`message`,l),t.addEventListener(`messageerror`,d);let f=e=>e===`local-only`,p=e=>i?Promise.reject(Error(`Inspector cache connection closed`)):new Promise((r,i)=>{let a=pt(t);s.set(a,{resolve:r,reject:i});try{t.postMessage({...e,id:a,binding:n})}catch(e){s.delete(a),i(e)}});return new Proxy(e,{get(e,s){if(s===`beginTransaction`)return(e,t)=>{if(i)throw Error(`Inspector cache connection closed`);if(e!==`mergeable`)throw Error(`Inspector edits require a mergeable transaction`);if(a.has(t))throw Error(`Inspector transaction already exists`);return a.set(t,[]),t};if(s===`rollbackTransaction`)return async e=>a.delete(e);if(s===`commitTransaction`)return async e=>{let t=a.get(e);if(!t)throw Error(`Inspector transaction is not open`);a.delete(e);let n=await p({type:`inspect-commit`,edits:t});return o.add(n),n};if(s===`waitForTransaction`)return async(t,n,r)=>{let i=await t;if(!o.has(i))return e.waitForTransaction(i,n,r);await Promise.all([r?.ready,p({type:`inspect-wait`,txId:i,tier:n})])};if(s===`insert`||s===`update`||s===`delete`)return(...e)=>{let t=e[0],n=s===`insert`,i=JSON.parse(e[n?2:s===`update`?3:2]??`{}`),o=i.transaction_id,c=a.get(o);if(!c)throw Error(`Inspector writes require an open transaction`);if(i.branch_view||i.target_branch_name||i.attribution)throw Error(`Inspector edits do not support branch or attributed writes`);let l=n?e[3]??crypto.randomUUID():e[1],u=n?e[1]:e[2];c.push(structuredClone({operation:s,table:t,rowId:l,...s===`delete`?{}:{values:u},updatedAt:i.updated_at}));let d={kind:`staged`,openTransactionId:o};if(!n)return d;let f=r[t]?.columns;if(!f)throw Error(`Unknown Inspector table ${t}`);return{...d,id:l,values:f.filter(e=>!e.name.startsWith(`$`)).map(e=>u[e.name]??e.default??{type:`Null`})}};if(s===`upsert`||s===`restore`||s===`updateLargeValues`||s===`streamingMutation`)return()=>{throw Error(`This mutation is not supported by the Inspector`)};if(s===`query`)return(t,n,r,a)=>f(r)?i?Promise.reject(Error(`Inspector cache connection closed`)):p({type:`inspect-query`,query:t,options:a}):e.query(t,n,r,a);if(s===`createSubscription`)return(n,r,a,o)=>{if(!f(a))return e.createSubscription(n,r,a,o);if(i)throw Error(`Inspector cache connection closed`);let s=pt(t);return c.set(s,{query:n,options:o,started:!1}),s};if(s===`executeSubscription`)return(r,i)=>{let a=c.get(r);if(!a)return e.executeSubscription(r,i);if(a.callback=i,!a.started){a.started=!0;try{t.postMessage({type:`inspect-subscribe`,id:r,binding:n,query:a.query,options:a.options})}catch(e){throw c.delete(r),a.started=!1,e}}};if(s===`unsubscribe`)return r=>{let i=c.get(r);if(!i)return e.unsubscribe(r);c.delete(r),i.started&&t.postMessage({type:`inspect-unsubscribe`,id:r,binding:n})};if(s===`close`)return()=>(u(),e.close());if(s===`discard`)return()=>(u(),e.discard());let l=Reflect.get(e,s,e);return typeof l==`function`?l.bind(e):l}})}var ht=BigInt(0),gt=BigInt(1);function _t(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}" `;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function vt(e){if(typeof e==`bigint`){if(!Ot(e))throw Error(`positive bigint expected, got `+e)}else Je(e);return e}function yt(e,t=``){if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw Error(n+`expected safe integer, got type=`+typeof e)}}function bt(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?ht:BigInt(`0x`+e)}function xt(e){return bt(x(e))}function St(e){return bt(x(Et(C(e)).reverse()))}function Ct(e,t){Je(t),e=vt(e);let n=_e(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function wt(e,t){return Ct(e,t).reverse()}function Tt(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function Et(e){return Uint8Array.from(e)}function Dt(e){return Uint8Array.from(e,(t,n)=>{let r=t.charCodeAt(0);if(t.length!==1||r>127)throw Error(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r})}var Ot=e=>typeof e==`bigint`&&ht<=e;function kt(e,t,n){return Ot(e)&&Ot(t)&&Ot(n)&&t<=e&&e<n}function At(e,t,n,r){if(!kt(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function jt(e){let t;for(t=0;e>ht;e>>=gt,t+=1);return t}var Mt=e=>(gt<<BigInt(e))-gt;function Nt(e,t={},n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}let i=(e,t)=>Object.entries(e).forEach(([e,n])=>r(e,n,t));i(t,!1),i(n,!0)}var Pt=()=>{throw Error(`not implemented`)};function Ft(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var L=BigInt(0),R=BigInt(1),It=BigInt(2),Lt=BigInt(3),Rt=BigInt(4),zt=BigInt(5),Bt=BigInt(7),Vt=BigInt(8),Ht=BigInt(9),Ut=BigInt(16);function z(e,t){let n=e%t;return n>=L?n:t+n}function Wt(e,t,n){let r=e;for(;t-- >L;)r*=r,r%=n;return r}function Gt(e,t){if(e===L)throw Error(`invert: expected non-zero number`);if(t<=L)throw Error(`invert: expected positive modulus, got `+t);let n=z(e,t),r=t,i=L,a=R,o=R,s=L;for(;n!==L;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==R)throw Error(`invert: does not exist`);return z(i,t)}function Kt(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function qt(e,t){let n=(e.ORDER+R)/Rt,r=e.pow(t,n);return Kt(e,r,t),r}function Jt(e,t){let n=(e.ORDER-zt)/Vt,r=e.mul(t,It),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,It),i),s=e.mul(a,e.sub(o,e.ONE));return Kt(e,s,t),s}function Yt(e){let t=sn(e),n=Xt(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Bt)/Ut;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Kt(e,p,t),p}}function Xt(e){if(e<Lt)throw Error(`sqrt is not defined for small field`);let t=e-R,n=0;for(;t%It===L;)t/=It,n++;let r=It,i=sn(e);for(;rn(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return qt;let a=i.pow(r,t),o=(t+R)/It;return function(e,r){if(e.is0(r))return r;if(rn(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=R<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function Zt(e){return e%Rt===Lt?qt:e%Vt===zt?Jt:e%Ut===Ht?Yt(e):Xt(e)}var Qt=(e,t)=>(z(e,t)&R)===R,$t=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function en(e){return Nt(e,$t.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,BYTES:`number`,BITS:`number`})),e}function tn(e,t,n){if(n<L)throw Error(`invalid exponent, negatives unsupported`);if(n===L)return e.ONE;if(n===R)return t;let r=e.ONE,i=t;for(;n>L;)n&R&&(r=e.mul(r,i)),i=e.sqr(i),n>>=R;return r}function nn(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function rn(e,t){let n=(e.ORDER-R)/It,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function an(e,t){t!==void 0&&Je(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}var on=class{ORDER;BITS;BYTES;isLE;ZERO=L;ONE=R;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=L)throw Error(`invalid field: expected ORDER > 0, got `+e);let n;this.isLE=!1,typeof t==`object`&&t&&(typeof t.BITS==`number`&&(n=t.BITS),typeof t.sqrt==`function`&&(this.sqrt=t.sqrt),typeof t.isLE==`boolean`&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes==`boolean`&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:i}=an(e,n);if(i>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return z(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return L<=e&&e<this.ORDER}is0(e){return e===L}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&R)===R}neg(e){return z(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return z(e*e,this.ORDER)}add(e,t){return z(e+t,this.ORDER)}sub(e,t){return z(e-t,this.ORDER)}mul(e,t){return z(e*t,this.ORDER)}pow(e,t){return tn(this,e,t)}div(e,t){return z(e*Gt(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Gt(e,this.ORDER)}sqrt(e){return this._sqrt||=Zt(this.ORDER),this._sqrt(this,e)}toBytes(e){return this.isLE?wt(e,this.BYTES):Ct(e,this.BYTES)}fromBytes(e,t=!1){C(e);let{_lengths:n,BYTES:r,isLE:i,ORDER:a,_mod:o}=this;if(n){if(!n.includes(e.length)||e.length>r)throw Error(`Field.fromBytes: expected `+n+` bytes, got `+e.length);let t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw Error(`Field.fromBytes: expected `+r+` bytes, got `+e.length);let s=i?St(e):xt(e);if(o&&(s=z(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return nn(this,e)}cmov(e,t,n){return n?t:e}};function sn(e,t={}){return new on(e,t)}function cn(e,t){if(!e.isOdd)throw Error(`Field doesn't have isOdd`);let n=e.sqrt(t);return e.isOdd(n)?e.neg(n):n}function ln(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function un(e){let t=ln(e);return t+Math.ceil(t/2)}function dn(e,t,n=!1){C(e);let r=e.length,i=ln(t),a=un(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=z(n?St(e):xt(e),t-R)+R;return n?wt(o,i):Ct(o,i)}var fn=BigInt(0),pn=BigInt(1);function mn(e,t){let n=t.negate();return e?n:t}function hn(e,t){let n=nn(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function gn(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function _n(e,t){gn(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:Mt(e),maxNumber:i,shiftBy:BigInt(e)}}function vn(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=pn);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function yn(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function bn(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var xn=new WeakMap,Sn=new WeakMap;function Cn(e){return Sn.get(e)||1}function wn(e){if(e!==fn)throw Error(`invalid wNAF`)}var Tn=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>fn;)t&pn&&(n=n.add(r)),r=r.double(),t>>=pn;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=_n(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=_n(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=vn(n,e,a);n=o,c?i=i.add(mn(u,t[d])):r=r.add(mn(l,t[s]))}return wn(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=_n(e,this.bits);for(let e=0;e<i.windows&&n!==fn;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=vn(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return wn(n),r}getPrecomputes(e,t,n){let r=xn.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),xn.set(t,r))),r}cached(e,t,n){let r=Cn(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Cn(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){gn(t,this.bits),Sn.set(e,t),xn.delete(e)}hasCache(e){return Cn(e)!==1}};function En(e,t,n){let r=e.Fn;yn(t,e),bn(n,r);let i=t.length,a=n.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=jt(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=Mt(c),u=Array(Number(l)+1).fill(o),d=Math.floor((r.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let r=0;r<a;r++){let i=n[r],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(t[r])}let r=o;for(let e=u.length-1,t=o;e>0;e--)t=t.add(u[e]),r=r.add(t);if(f=f.add(r),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function Dn(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return en(t),t}else return sn(e,{isLE:n})}function On(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>fn))throw Error(`CURVE.${e} must be positive bigint`)}let i=Dn(t.p,n.Fp,r),a=Dn(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}function kn(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var An=BigInt(0),B=BigInt(1),jn=BigInt(2),Mn=BigInt(8);function Nn(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function Pn(e,t={}){let n=On(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;Nt(t,{},{uvRatio:`function`});let s=jn<<BigInt(i.BYTES*8)-B,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch{return{isValid:!1,value:An}}});if(!Nn(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?B:An;return At(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`EdwardsPoint expected`)}let f=Ft((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?Mn:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:An,y:B};if(u!==B)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=Ft(e=>{let{a:t,d:n}=a;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:i,Z:o,T:s}=e,l=c(r*r),u=c(i*i),d=c(o*o),f=c(d*d);if(c(d*c(c(l*t)+u))!==c(f+c(n*c(l*u))))throw Error(`bad point: equation left != right (1)`);if(c(r*i)!==c(o*s))throw Error(`bad point: equation left != right (2)`);return!0});class m{static BASE=new m(a.Gx,a.Gy,B,c(a.Gx*a.Gy));static ZERO=new m(An,B,B,An);static Fp=r;static Fn=i;X;Y;Z;T;constructor(e,t,n,r){this.X=u(`x`,e),this.Y=u(`y`,t),this.Z=u(`z`,n,!0),this.T=u(`t`,r),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){if(e instanceof m)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return u(`x`,t),u(`y`,n),new m(t,n,B,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=Et(C(e,n,`point`)),_t(t,`zip215`);let u=Et(e),d=e[n-1];u[n-1]=d&-129;let f=St(u);At(`point.y`,f,An,t?s:r.ORDER);let p=c(f*f),{isValid:h,value:g}=l(c(p-B),c(o*p-i));if(!h)throw Error(`bad point: invalid y coordinate`);let _=(g&B)===B,v=(d&128)!=0;if(!t&&g===An&&v)throw Error(`bad point: x=0 and x_0=1`);return v!==_&&(g=c(-g)),m.fromAffine({x:g,y:f})}static fromHex(e,t=!1){return m.fromBytes(_e(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return h.createCache(this,e),t||this.multiply(jn),this}assertValidity(){p(this)}equals(e){d(e);let{X:t,Y:n,Z:r}=this,{X:i,Y:a,Z:o}=e,s=c(t*o),l=c(i*r),u=c(n*o),f=c(a*r);return s===l&&u===f}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:e}=a,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),s=c(jn*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),f=l+o,p=f-s,h=l-o,g=c(d*p),_=c(f*h),v=c(d*h);return new m(g,_,c(p*f),v)}add(e){d(e);let{a:t,d:n}=a,{X:r,Y:i,Z:o,T:s}=this,{X:l,Y:u,Z:f,T:p}=e,h=c(r*l),g=c(i*u),_=c(s*n*p),v=c(o*f),y=c((r+i)*(l+u)-h-g),b=v-_,x=v+_,S=c(g-t*h),C=c(y*b),w=c(x*S),T=c(y*S);return new m(C,w,c(b*x),T)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw Error(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=h.cached(this,e,e=>hn(m,e));return hn(m,[t,n])[0]}multiplyUnsafe(e,t=m.ZERO){if(!i.isValid(e))throw Error(`invalid scalar: expected 0 <= sc < curve.n`);return e===An?m.ZERO:this.is0()||e===B?this:h.unsafe(this,e,e=>hn(m,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return h.unsafe(this,a.n).is0()}toAffine(e){return f(this,e)}clearCofactor(){return o===B?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&B?128:0,n}toHex(){return x(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let h=new Tn(m,i.BITS);return m.BASE.precompute(8),m}var Fn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Pt()}static fromHex(e){Pt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return x(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}};function In(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);Nt(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||k,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(_t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(St(e))}function d(e){let n=y.secretKey;C(e,y.secretKey,`secretKey`);let r=C(t(e),2*n,`hashedSecretKey`),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){return u(t(l(M(...n),C(e,void 0,`context`),!!r)))}function h(e,t,n={}){e=C(e,void 0,`message`),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);return C(M(u,o.toBytes(p)),y.signature,`result`)}let g={zip215:!0};function _(t,n,a,o=g){let{context:s,zip215:c}=o,l=y.signature;t=C(t,l,`signature`),n=C(n,void 0,`message`),a=C(a,y.publicKey,`publicKey`),c!==void 0&&_t(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=St(t.subarray(u,l)),p,h,_;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),_=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(_).clearCofactor().is0()}let v=a.BYTES,y={secretKey:v,publicKey:v,signature:2*v,seed:v};function b(e=s(y.seed)){return C(e,y.seed,`seed`)}function x(e){return be(e)&&e.length===o.BYTES}function S(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let w={getExtendedPublicKey:f,randomSecretKey:b,isValidSecretKey:x,isValidPublicKey:S,toMontgomery(t){let{y:n}=e.fromBytes(t),r=y.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let o=i?a.div(B+n,B-n):a.div(n-B,n+B);return a.toBytes(o)},toMontgomerySecret(e){let n=y.secretKey;return C(e,n),c(t(e.subarray(0,n))).subarray(0,n)}};return Object.freeze({keygen:kn(b,p),getPublicKey:p,sign:h,verify:_,utils:w,Point:e,lengths:y})}var Ln=xt;function Rn(e,t){if(yt(e),yt(t),e<0||e>=1<<8*t)throw Error(`invalid I2OSP input: `+e);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function zn(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Bn(e){if(!be(e)&&typeof e!=`string`)throw Error(`DST must be Uint8Array or ascii string`);return typeof e==`string`?Dt(e):e}function Vn(e,t,n,r){C(e),yt(n),t=Bn(t),t.length>255&&(t=r(M(Dt(`H2C-OVERSIZE-DST-`),t)));let{outputLen:i,blockLen:a}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw Error(`expand_message_xmd: invalid lenInBytes`);let s=M(t,Rn(t.length,1)),c=Rn(0,a),l=Rn(n,2),u=Array(o),d=r(M(c,e,l,Rn(0,1),s));u[0]=r(M(d,Rn(1,1),s));for(let e=1;e<=o;e++)u[e]=r(M(zn(d,u[e-1]),Rn(e+1,1),s));return M(...u).slice(0,n)}function Hn(e,t,n,r,i){if(C(e),yt(n),t=Bn(t),t.length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(Dt(`H2C-OVERSIZE-DST-`)).update(t).digest()}if(n>65535||t.length>255)throw Error(`expand_message_xof: invalid lenInBytes`);return i.create({dkLen:n}).update(e).update(Rn(n,2)).update(t).update(Rn(t.length,1)).digest()}function Un(e,t,n){Nt(n,{p:`bigint`,m:`number`,k:`number`,hash:`function`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;yt(o.outputLen,`valid hash`),C(e),yt(t);let l=r.toString(2).length,u=Math.ceil((l+i)/8),d=t*a*u,f;if(s===`xmd`)f=Vn(e,c,d,o);else if(s===`xof`)f=Hn(e,c,d,i,o);else if(s===`_internal_pass`)f=e;else throw Error(`expand must be "xmd" or "xof"`);let p=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=u*(n+e*a);t[n]=z(Ln(f.subarray(i,i+u)),r)}p[e]=t}return p}var Wn=Dt(`HashToScalar-`);function Gn(e,t,n){if(typeof t!=`function`)throw Error(`mapToCurve() must be defined`);function r(n){return e.fromAffine(t(n))}function i(t){let n=t.clearCofactor();return n.equals(e.ZERO)?e.ZERO:(n.assertValidity(),n)}return{defaults:Object.freeze(n),Point:e,hashToCurve(e,t){let a=Un(e,2,Object.assign({},n,t)),o=r(a[0]),s=r(a[1]);return i(o.add(s))},encodeToCurve(e,t){let a=n.encodeDST?{DST:n.encodeDST}:{};return i(r(Un(e,1,Object.assign({},n,a,t))[0]))},mapToCurve(e){if(n.m===1){if(typeof e!=`bigint`)throw Error(`expected bigint (m=1)`);return i(r([e]))}if(!Array.isArray(e))throw Error(`expected array of bigints`);for(let t of e)if(typeof t!=`bigint`)throw Error(`expected array of bigints`);return i(r(e))},hashToScalar(t,r){let i=e.Fn.ORDER;return Un(t,1,Object.assign({},n,{p:i,m:1,DST:Wn},r))[0][0]}}}function Kn(e){Nt(e,{name:`string`,hash:`function`,hashToScalar:`function`,hashToGroup:`function`});let{name:t,Point:n,hash:r}=e,{Fn:i}=n,a=(t,n)=>e.hashToGroup(t,{DST:M(Dt(`HashToGroup-`),n)}),o=(t,n)=>e.hashToScalar(t,{DST:M(Wn,n)}),s=(e=k)=>{let t=dn(e(un(i.ORDER)),i.ORDER,i.isLE);return i.isLE?St(t):xt(t)},c=(e,t)=>En(n,e,t),l=e=>M(Dt(`OPRFV1-`),new Uint8Array([e]),Dt(`-`+t)),u=l(0),d=l(1),f=l(2);function p(...e){let t=[];for(let n of e)typeof n==`number`?t.push(Ct(n,2)):typeof n==`string`?t.push(Dt(n)):(C(n),t.push(Ct(n.length,2),n));return M(...t)}let m=(...e)=>r(p(...e,`Finalize`));function h(e,t,n,i){let a=r(p(e.toBytes(),M(Dt(`Seed-`),i))),s=[];for(let e=0;e<t.length;e++){let r=t[e].toBytes(),c=n[e].toBytes(),l=o(p(a,e,r,c,`Composite`),i);s.push(l)}return s}function g(e,t,n,r){let i=h(e,t,n,r);return{M:c(t,i),Z:c(n,i)}}function _(e,t,n,r,i){let a=c(n,h(t,n,r,i));return{M:a,Z:a.multiply(e)}}function v(e,t,n,r,i,a){let[s,c,l,u,d]=[e,t,n,r,i].map(e=>e.toBytes());return o(p(s,c,l,u,d,`Challenge`),a)}function y(e,t,r,a,o,c){let{M:l,Z:u}=_(t,r,a,o,e),d=s(c),f=v(r,l,u,n.BASE.multiply(d),l.multiply(d),e);return M(...[f,i.sub(d,i.mul(f,t))].map(e=>i.toBytes(e)))}function b(e,t,r,a,o){C(o,2*i.BYTES);let{M:s,Z:c}=g(t,r,a,e),[l,u]=[o.subarray(0,i.BYTES),o.subarray(i.BYTES)].map(e=>i.fromBytes(e)),d=v(t,s,c,n.BASE.multiply(u).add(t.multiply(l)),s.multiply(u).add(c.multiply(l)),e);if(!i.eql(l,d))throw Error(`proof verification failed`)}function x(){let e=s(),t=n.BASE.multiply(e);return{secretKey:i.toBytes(e),publicKey:t.toBytes()}}function S(t,r,a){let o=M(Dt(`DeriveKeyPair`),t),s=M(r,p(a),Uint8Array.of(0));for(let t=0;t<=255;t++){s[s.length-1]=t;let r=e.hashToScalar(s,{DST:o});if(!i.is0(r))return{secretKey:i.toBytes(r),publicKey:n.BASE.multiply(r).toBytes()}}throw Error(`Cannot derive key`)}function w(e,t,r=k){let o=s(r),c=a(t,e);if(c.equals(n.ZERO))throw Error(`Input point at infinity`);let l=c.multiply(o);return{blind:i.toBytes(o),blinded:l.toBytes()}}function T(e,t,r){let o=i.fromBytes(t),s=a(r,e);if(s.equals(n.ZERO))throw Error(`Input point at infinity`);return m(r,s.multiply(o).toBytes())}let E={generateKeyPair:x,deriveKeyPair:(e,t)=>S(u,e,t),blind:(e,t=k)=>w(u,e,t),blindEvaluate(e,t){let r=i.fromBytes(e);return n.fromBytes(t).multiply(r).toBytes()},finalize(e,t,r){let a=i.fromBytes(t);return m(e,n.fromBytes(r).multiply(i.inv(a)).toBytes())},evaluate:(e,t)=>T(u,e,t)};return Object.freeze({name:t,oprf:E,voprf:{generateKeyPair:x,deriveKeyPair:(e,t)=>S(d,e,t),blind:(e,t=k)=>w(d,e,t),blindEvaluateBatch(e,t,r,a=k){if(!Array.isArray(r))throw Error(`expected array`);let o=i.fromBytes(e),s=n.fromBytes(t),c=r.map(n.fromBytes),l=c.map(e=>e.multiply(o)),u=y(d,o,s,c,l,a);return{evaluated:l.map(e=>e.toBytes()),proof:u}},blindEvaluate(e,t,n,r=k){let i=this.blindEvaluateBatch(e,t,[n],r);return{evaluated:i.evaluated[0],proof:i.proof}},finalizeBatch(e,t,r){if(!Array.isArray(e))throw Error(`expected array`);return b(d,n.fromBytes(t),e.map(e=>e.blinded).map(n.fromBytes),e.map(e=>e.evaluated).map(n.fromBytes),r),e.map(e=>E.finalize(e.input,e.blind,e.evaluated))},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate:(e,t)=>T(d,e,t)},poprf:e=>{let t=o(p(`Info`,e),f),r=n.BASE.multiply(t);return{generateKeyPair:x,deriveKeyPair:(e,t)=>S(f,e,t),blind(e,t,o=k){let c=n.fromBytes(t),l=r.add(c);if(l.equals(n.ZERO))throw Error(`tweakedKey point at infinity`);let u=s(o),d=a(e,f);if(d.equals(n.ZERO))throw Error(`Input point at infinity`);let p=d.multiply(u);return{blind:i.toBytes(u),blinded:p.toBytes(),tweakedKey:l.toBytes()}},blindEvaluateBatch(e,r,a=k){if(!Array.isArray(r))throw Error(`expected array`);let o=i.fromBytes(e),s=i.add(o,t),c=i.inv(s),l=r.map(n.fromBytes),u=l.map(e=>e.multiply(c)),d=y(f,s,n.BASE.multiply(s),u,l,a);return{evaluated:u.map(e=>e.toBytes()),proof:d}},blindEvaluate(e,t,n=k){let r=this.blindEvaluateBatch(e,[t],n);return{evaluated:r.evaluated[0],proof:r.proof}},finalizeBatch(t,r,a){if(!Array.isArray(t))throw Error(`expected array`);let o=t.map(e=>e.evaluated).map(n.fromBytes);return b(f,n.fromBytes(a),o,t.map(e=>e.blinded).map(n.fromBytes),r),t.map((t,n)=>{let r=i.fromBytes(t.blind),a=o[n].multiply(i.inv(r)).toBytes();return m(t.input,e,a)})},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate(r,o){let s=i.fromBytes(r),c=a(o,f);if(c.equals(n.ZERO))throw Error(`Input point at infinity`);let l=i.add(s,t),u=i.inv(l);return m(o,e,c.multiply(u).toBytes())}}},__tests:{Fn:i}})}var qn=BigInt(0),Jn=BigInt(1),Yn=BigInt(2),Xn=BigInt(3),Zn=BigInt(5),Qn=BigInt(8),$n=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),er={p:$n,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:Qn,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function tr(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=$n,o=e*e%a*e%a,s=Wt(Wt(o,Yn,a)*o%a,Jn,a)*e%a,c=Wt(s,Zn,a)*s%a,l=Wt(c,t,a)*c%a,u=Wt(l,n,a)*l%a,d=Wt(u,r,a)*u%a;return{pow_p_5_8:Wt(Wt(Wt(Wt(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,Yn,a)*e%a,b2:o}}function nr(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var rr=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function ir(e,t){let n=$n,r=z(t*t*t,n),i=tr(e*z(r*r*t,n)).pow_p_5_8,a=z(e*r*i,n),o=z(t*a*a,n),s=a,c=z(a*rr,n),l=o===e,u=o===z(-e,n),d=o===z(-e*rr,n);return l&&(a=s),(u||d)&&(a=c),Qt(a,n)&&(a=z(-a,n)),{isValid:l||u,value:a}}var ar=Pn(er,{uvRatio:ir}),V=ar.Fp,or=ar.Fn;function sr(e){return In(ar,j,Object.assign({adjustScalarBytes:nr},e))}var cr=sr({}),lr=($n+Xn)/Qn,ur=V.pow(Yn,lr),dr=V.sqrt(V.neg(V.ONE));function fr(e){let t=($n-Zn)/Qn,n=BigInt(486662),r=V.sqr(e);r=V.mul(r,Yn);let i=V.add(r,V.ONE),a=V.neg(n),o=V.sqr(i),s=V.mul(o,i),c=V.mul(r,n);c=V.mul(c,a),c=V.add(c,o),c=V.mul(c,a);let l=V.sqr(s);o=V.sqr(l),l=V.mul(l,s),l=V.mul(l,c),o=V.mul(o,l);let u=V.pow(o,t);u=V.mul(u,l);let d=V.mul(u,dr);o=V.sqr(u),o=V.mul(o,s);let f=V.eql(o,c),p=V.cmov(d,u,f),m=V.mul(a,r),h=V.mul(u,e);h=V.mul(h,ur);let g=V.mul(h,dr),_=V.mul(c,r);o=V.sqr(h),o=V.mul(o,s);let v=V.eql(o,_),y=V.cmov(g,h,v);o=V.sqr(p),o=V.mul(o,s);let b=V.eql(o,c),x=V.cmov(m,a,b),S=V.cmov(y,p,b),C=V.isOdd(S);return S=V.cmov(S,V.neg(S),b!==C),{xMn:x,xMd:i,yMn:S,yMd:Jn}}var pr=cn(V,V.neg(BigInt(486664)));function mr(e){let{xMn:t,xMd:n,yMn:r,yMd:i}=fr(e),a=V.mul(t,i);a=V.mul(a,pr);let o=V.mul(n,r),s=V.sub(t,n),c=V.add(t,n),l=V.mul(o,c),u=V.eql(l,V.ZERO);a=V.cmov(a,V.ZERO,u),o=V.cmov(o,V.ONE,u),s=V.cmov(s,V.ONE,u),c=V.cmov(c,V.ONE,u);let[d,f]=nn(V,[o,c],!0);return{x:V.mul(a,d),y:V.mul(s,f)}}Gn(ar,e=>mr(e[0]),{DST:`edwards25519_XMD:SHA-512_ELL2_RO_`,encodeDST:`edwards25519_XMD:SHA-512_ELL2_NU_`,p:$n,m:1,k:128,expand:`xmd`,hash:j});var hr=rr,gr=BigInt(`25063068953384623474111414158702152701244531502492656460079210482610430750235`),_r=BigInt(`54469307008909316920995813868745141605393597292927456921205312896311721017578`),vr=BigInt(`1159843021668779879193775521855586647937357759715417654439879720876111806838`),yr=BigInt(`40440834346308536858101042469323190826248399146238708352240133220865137265952`),br=e=>ir(Jn,e),xr=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),Sr=e=>V.create(St(e)&xr);function Cr(e){let{d:t}=er,n=$n,r=e=>V.create(e),i=r(hr*e*e),a=r((i+Jn)*vr),o=BigInt(-1),s=r((o-t*i)*r(i+t)),{isValid:c,value:l}=ir(a,s),u=r(l*e);Qt(u,n)||(u=r(-u)),c||(l=u),c||(o=i);let d=r(o*(i-Jn)*yr-s),f=l*l,p=r((l+l)*s),m=r(d*gr),h=r(Jn-f),g=r(Jn+f);return new ar(r(p*g),r(h*m),r(m*g),r(p*h))}var wr=class e extends Fn{static BASE=new e(ar.BASE);static ZERO=new e(ar.ZERO);static Fp=V;static Fn=or;constructor(e){super(e)}static fromAffine(t){return new e(ar.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw Error(`RistrettoPoint expected`)}init(t){return new e(t)}static fromBytes(t){C(t,32);let{a:n,d:r}=er,i=$n,a=e=>V.create(e),o=Sr(t);if(!Tt(V.toBytes(o),t)||Qt(o,i))throw Error(`invalid ristretto255 encoding 1`);let s=a(o*o),c=a(Jn+n*s),l=a(Jn-n*s),u=a(c*c),d=a(l*l),f=a(n*r*u-d),{isValid:p,value:m}=br(a(f*d)),h=a(m*l),g=a(m*h*f),_=a((o+o)*h);Qt(_,i)&&(_=a(-_));let v=a(c*g),y=a(_*v);if(!p||Qt(y,i)||v===qn)throw Error(`invalid ristretto255 encoding 2`);return new e(new ar(_,v,Jn,y))}static fromHex(t){return e.fromBytes(_e(t))}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=$n,a=e=>V.create(e),o=a(a(n+t)*a(n-t)),s=a(e*t),{value:c}=br(a(o*a(s*s))),l=a(c*o),u=a(c*s),d=a(l*u*r),f;if(Qt(r*d,i)){let n=a(t*hr),r=a(e*hr);e=n,t=r,f=a(l*_r)}else f=u;Qt(e*d,i)&&(t=a(-t));let p=a((n-t)*f);return Qt(p,i)&&(p=a(-p)),V.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>V.create(e),o=a(t*i)===a(n*r),s=a(n*i)===a(t*r);return o||s}is0(){return this.equals(e.ZERO)}},Tr={Point:wr,hashToCurve(e,t){let n=Vn(e,t?.DST||`ristretto255_XMD:SHA-512_R255MAP_RO_`,64,j);return Tr.deriveToCurve(n)},hashToScalar(e,t={DST:Wn}){let n=Vn(e,t.DST,64,j);return or.create(St(n))},deriveToCurve(e){C(e,64);let t=Cr(Sr(e.subarray(0,32))),n=Cr(Sr(e.subarray(32,64)));return new wr(t.add(n))}};Kn({name:`ristretto255-SHA512`,Point:wr,hash:j,hashToGroup:Tr.hashToCurve,hashToScalar:Tr.hashToScalar});var Er=`urn:jazz:local-first`,Dr=`jazz-auth-sign-v1`,Or=fe(`jazz-auth-key-v1`),kr=3600,Ar=class extends Error{constructor(e){super(e),this.name=`LocalFirstTokenError`}};function jr(e,t){let n=new Uint8Array(e.length+t.length);n.set(e),n.set(t,e.length);let r=h(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,_(r)}var Mr=Uint8Array.from([107,167,184,16,157,173,17,209,128,180,0,192,79,212,48,200]),Nr=[/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/i,/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i,/^urn:uuid:([0-9a-fA-F]{8})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{12})$/];function Pr(e){if(typeof e!=`string`||e.length===0)throw TypeError(`audience must be a non-empty string`);for(let t of Nr){let n=t.exec(e);if(n)return n.slice(1).join(`-`).toLowerCase()}return jr(Mr,fe(e))}function Fr(e){let t=a(e),n=fe(Dr),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),j(r).slice(0,32)}function Ir(e){return jr(Or,e)}var Lr=()=>Math.floor(Date.now()/1e3);function Rr(e,t){let n=Pr(t.audience),r=t.ttlSeconds??kr;if(!Number.isSafeInteger(r)||r<=0)throw new Ar(`ttlSeconds must be a positive integer`);let i=t.now??Lr();if(!Number.isSafeInteger(i)||i<0)throw new Ar(`now must be a non-negative integer`);let a=Fr(e),o=cr.getPublicKey(a),s=me(fe(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=me(fe(JSON.stringify({iss:Er,sub:Ir(o),aud:n,jazz_pub_key:me(o),iat:i,exp:i+r})));return`${s}.${c}.${me(cr.sign(fe(`${s}.${c}`),a))}`}function H(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Br(e.serverUrl):zr)}var zr=`local`;function Br(e){let n;try{n=new t(et(e.trim()))}catch{throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`)}if(n.protocol===`ws:`&&(n.protocol=`http:`),n.protocol===`wss:`&&(n.protocol=`https:`),n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`);return`${n.origin}${n.pathname.replace(/\/+$/,``)}`}function Vr(){return import.meta.url}function Hr(){let e=import.meta.url;return new URL(`../worker/jazz-broker-worker.js`,e).href}function Ur(){return null}function Wr(){return null}function Gr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`}function Kr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`blob:`}function qr(e){return new URL(`/`,e).href}function Jr(e,t){try{return new URL(e).href}catch{}if(t)try{return new URL(e,t).href}catch{}return e}function Yr(e,t){if(!t?.wasmVersion)return e;try{let n=new URL(e);return n.searchParams.set(`jazz-runtime-version`,t.wasmVersion),n.href}catch{return e}}function Xr(e,t){try{return new URL(e).href}catch{}return t?new URL(e,t).href:null}function Zr(e,t,n){return!t||Gr(e)||!n&&Kr(t)?null:new URL(`jazz_wasm_bg.wasm`,qr(t)).href}function Qr(e){return e?.wasmModule?{module:e.wasmModule}:e?.wasmSource?{module:e.wasmSource}:null}function $r(e,t,n){if(n?.wasmUrl)return Yr(Jr(n.wasmUrl,t),n);if(n?.baseUrl){let e=Xr(n.baseUrl,t);if(e)return Yr(new URL(`jazz_wasm_bg.wasm`,e).href,n)}return Zr(typeof e==`function`?e():e,t,!1)}function ei(e,t,n){if(n?.brokerWorkerUrl)return Yr(Jr(n.brokerWorkerUrl,t),n);if(n?.baseUrl){let e=Xr(n.baseUrl,t);if(e)return Yr(new URL(`worker/jazz-broker-worker.js`,e).href,n)}return!t||Gr(e)?Yr(new URL(`../worker/jazz-broker-worker.js`,e).href,n):Yr(new URL(`worker/jazz-broker-worker.js`,qr(t)).href,n)}function ti(){let e=typeof process<`u`;return ni(e?{}.VITE_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.NEXT_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.EXPO_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(void 0)}function ni(e){return e?.trim()||void 0}var ri=new WeakMap,ii=256,ai=5e3,oi=1,si={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17};function ci(e,t){let n=e.trim().replace(/\/+$/,``),r=`/v1/${t}`;return n.endsWith(`/v1/logs`)?`${n.slice(0,-8)}${r}`:n.endsWith(`/v1/traces`)?`${n.slice(0,-10)}${r}`:`${n}${r}`}function li(e){if(!e.collectorUrl)return()=>void 0;let t={traceUrl:ci(e.collectorUrl,`traces`),logUrl:ci(e.collectorUrl,`logs`)},{runtimeThread:n,wasmModule:r}=e;if(!pi(r))return console.warn(`[jazz] WASM telemetry unavailable: trace entry hooks are missing.`),()=>void 0;let i=ri.get(r);if(i){if(i.closing)throw Error(`WASM telemetry collector is closing`);if(i.runtimeThread!==n)throw Error(`incompatible WASM telemetry runtime thread`);if(i.identity.traceUrl!==t.traceUrl||i.identity.logUrl!==t.logUrl)throw Error(`incompatible WASM telemetry collector`);return ui(r,i)}i={identity:t,runtimeThread:n,leases:new Set,nextLeaseId:0,closing:!1,unsubscribe:null,exporter:null,exportTail:Promise.resolve(),shutdownScheduled:!1,drainMicrotaskPending:!1},ri.set(r,i);let a=()=>{let e=r.drainTraceEntries();!Array.isArray(e)||e.length===0||di(i,e)},o=()=>{i.closing||i.drainMicrotaskPending||(i.drainMicrotaskPending=!0,queueMicrotask(()=>{i.drainMicrotaskPending=!1,!i.closing&&a()}))},s=!1;try{return i.unsubscribe=r.subscribeTraceEntries(o),s=!0,r.setTraceEntryCollectionEnabled(!0),ui(r,i)}catch(e){if(s)try{r.setTraceEntryCollectionEnabled(!1)}catch{}try{i.unsubscribe?.()}catch{}throw i.unsubscribe=null,ri.get(r)===i&&ri.delete(r),e}}function ui(e,t){let n=t.nextLeaseId++;t.leases.add(n);let r=!1;return()=>{if(r||(r=!0,t.leases.delete(n),t.leases.size>0||t.closing))return;t.closing=!0;let i;try{t.unsubscribe?.()}catch(e){i=e}finally{try{let n=e.drainTraceEntries();Array.isArray(n)&&n.length>0&&di(t,n)}catch(e){i??=e}finally{try{e.setTraceEntryCollectionEnabled(!1)}catch(e){i??=e}finally{t.unsubscribe=null,fi(t),!i&&ri.get(e)===t&&ri.delete(e)}}}if(i)throw i}}function di(e,t){e.exportTail=e.exportTail.catch(()=>void 0).then(async()=>{e.exporter||=hi(e.identity.traceUrl,e.identity.logUrl);try{let n=await e.exporter;for(let r of t)try{mi(n,e.runtimeThread,r)}catch(e){console.warn(`[jazz] WASM telemetry export failed:`,e)}}catch(t){e.exporter=null,console.warn(`[jazz] WASM telemetry export failed:`,t)}})}function fi(e){e.shutdownScheduled||(e.shutdownScheduled=!0,e.exportTail.catch(()=>void 0).then(async()=>{try{await(e.exporter?await e.exporter:void 0)?.shutdown()}catch(e){console.warn(`[jazz] WASM telemetry shutdown failed:`,e)}}))}function pi(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.subscribeTraceEntries==`function`&&typeof t.drainTraceEntries==`function`&&typeof t.setTraceEntryCollectionEnabled==`function`}function mi(e,t,n){if(n.kind===`span`){let r={"jazz.runtime_thread":t,"jazz.span.sequence":n.sequence,"jazz.span.level":n.level,"jazz.span.target":n.target,"jazz.span.fields":yi(n.fields)};e.tracer.startSpan(n.name||`wasm span`,{kind:oi,startTime:n.startUnixNano,attributes:vi(n.fields)?{...gi(n.fields),...r}:r}).end(n.endUnixNano);return}if(n.kind===`log`){let r={"jazz.runtime_thread":t,"jazz.log.sequence":n.sequence,"jazz.log.target":n.target,"jazz.log.fields":yi(n.fields)};e.logger.emit({timestamp:n.timestampUnixNano,severityNumber:_i(n.level),severityText:n.level,body:n.message,attributes:vi(n.fields)?{...gi(n.fields),...r}:r});return}e.logger.emit({severityNumber:si.WARN,severityText:`WARN`,body:`Dropped ${n.count} WASM telemetry records`,attributes:{"jazz.runtime_thread":t,"jazz.telemetry.dropped_count":n.count}})}async function hi(t,n){let[{OTLPTraceExporter:r},{BasicTracerProvider:i,BatchSpanProcessor:a},{OTLPLogExporter:o},{LoggerProvider:s,BatchLogRecordProcessor:c},{resourceFromAttributes:l}]=await Promise.all([e(()=>import(`./esm-D_R-EGgt.js`),__vite__mapDeps([0,1,2]),import.meta.url),e(()=>import(`./esm-DEBYi0LL.js`),__vite__mapDeps([3,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-WihpI9g6.js`),__vite__mapDeps([8,1,2]),import.meta.url),e(()=>import(`./esm-DT3MY99S.js`),__vite__mapDeps([9,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-D-TBoHij.js`).then(e=>e.t),__vite__mapDeps([5,6,7,1]),import.meta.url)]),u=l({"service.name":`jazz-browser`,"telemetry.sdk.language":`webjs`}),d={maxExportBatchSize:ii,maxQueueSize:ai,scheduledDelayMillis:1e3},f=new i({resource:u,spanProcessors:[new a(new r({url:t}),d)]}),p=new s({resource:u,processors:[new c(new o({url:n}),d)]});return{tracer:f.getTracer(`jazz-wasm.tracing`),logger:p.getLogger(`jazz-wasm.tracing`),shutdown:async()=>{await Promise.all([typeof f.shutdown==`function`?f.shutdown():void 0,typeof p.shutdown==`function`?p.shutdown():void 0])}}}function gi(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))n.startsWith(`jazz.`)||r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:t[n]=JSON.stringify(r));return t}function _i(e){switch(e.toUpperCase()){case`TRACE`:return si.TRACE;case`DEBUG`:return si.DEBUG;case`INFO`:return si.INFO;case`WARN`:case`WARNING`:return si.WARN;case`ERROR`:return si.ERROR;default:return 0}}function vi(e){if(!e)return!1;for(let t in e)return!0;return!1}function yi(e){return vi(e)?JSON.stringify(e):`{}`}var bi=`jazz-shared-runtime-v2`,xi=`idbtree-v1`,Si=new WeakMap;function Ci(e){if(e?.brokerWorkerUrl||e?.baseUrl)return ei(Vr(),typeof location<`u`?location.href:void 0,e);let t=Di(Vr());return t?e?.wasmVersion?`${t}&jazz-runtime-version=${encodeURIComponent(e.wasmVersion)}`:t:Yr(Jr(Hr(),typeof location<`u`?location.href:void 0),e)}var wi=/^(.*?\/)node_modules\/\.vite\/(?:.*\/)?deps(?:_[^/]*)?\/[^/]+$/,Ti=`worker_file&type=module`,Ei=`jazz-tools/_worker/broker`;function Di(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`http:`&&t.protocol!==`https:`)return;let n=wi.exec(t.pathname);return n?`${t.origin}${n[1]}@id/${Ei}?${Ti}`:void 0}function Oi(e){if(!e)return ki(e);if((e.baseUrl||e.wasmUrl&&!Ai(e.wasmUrl)||e.brokerWorkerUrl)&&!e.wasmVersion)throw Error(`Configured browser runtime assets require runtimeSources.wasmVersion. Use an immutable build version that changes whenever the WASM or worker bytes change.`);let t=Mi(e);if(t)return{...e,workerWasmAssetIdentity:t};let n=$r(Vr(),typeof location<`u`?location.href:void 0,e);return n?{...e,wasmUrl:n}:ki(e)}function ki(e){let t=Ur();return t?{...e,wasmUrl:t}:e}function Ai(e){return e===Ur()}function ji(e){let t=Oi(e);return JSON.stringify({protocolVersion:bi,workerUrl:Ci(t),wasmAsset:Ni(t)})}function Mi(e){let[t,n]=e.wasmModule?[e.wasmModule,`module`]:e.wasmSource?[e.wasmSource,`source`]:[];if(!t||!n)return;let r=Si.get(t);return r||(r=`${n}:${crypto.randomUUID()}`,Si.set(t,r)),r}function Ni(e){return e?.wasmModule?`module:${e.workerWasmAssetIdentity??`unscoped`}`:e?.wasmSource?`source:${e.workerWasmAssetIdentity??`unscoped`}`:`url:${e?.wasmUrl??`worker-local`}`}function Pi(e,t,n){let r=e.telemetryCollectorUrl?.trim()||void 0;return JSON.stringify({protocolVersion:bi,storageFormatVersion:xi,appId:H(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Hi(e),workerUrl:Ci(e.runtimeSources),workerAssetScope:ji(e.runtimeSources),telemetryCollector:r?{traceUrl:ci(r,`traces`),logUrl:ci(r,`logs`)}:void 0,wasmLogLevel:e.logLevel??`warn`})}function Fi(e){if(e.adminSecret)return{kind:`system`};let t=rt({appId:H(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:A(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:t.authMode,user:ze(t.issuer,t.user_id,t.account_id)}}function Ii(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Li(e)}:Fi(e)}function Li(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function Ri(e){return JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Fi(e),...e.accountId?{registry:Li(e)}:{}})}function zi(e){return JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Ii(e)})}function Bi(e,t){if(zi(e)!==zi(t)||Ri(e)!==Ri(t))throw Error(`Cannot change the authenticated user of a live persistent browser Db; shut it down and reopen for the new user, or explicitly reset its storage`)}function Vi(e,t){let n=JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Ii(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Hi(e){if(e.adminSecret)return`admin`;let t=rt({appId:H(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:A(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${t.authMode}:${ze(t.issuer,t.user_id,t.account_id)}`}var Ui=`Jazz's local-first client needs its Metro setup on Expo web: wrap your Metro config in withJazz from jazz-tools/expo/metro (module.exports = withJazz(getDefaultConfig(__dirname))) and restart Metro with --clear.`,Wi=` Under Metro (Expo web), Jazz's worker is the Expo worker chunk withJazz from jazz-tools/expo/metro builds: check that metro.config.js wraps getDefaultConfig from expo/metro-config in withJazz, restart Metro with --clear, and leave runtimeSources.brokerWorkerUrl unset (a URL set there is started as a module script, not as Metro's chunk).`;function Gi(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var Ki=class{transport;onError;timer;deadline;closed=!1;constructor(e,t){this.transport=e,this.onError=t}refresh(){if(!this.closed)try{let e=this.transport.auxiliaryReceiveTimeoutMs?.();if(e==null){this.clear();return}if(!Number.isFinite(e)||e<0||!this.transport.expireAuxiliaryReceive)throw Error(`Invalid auxiliary receive deadline capability`);let t=performance.now()+e;if(this.deadline!==void 0&&this.deadline<=t)return;this.clear(),this.deadline=t,this.timer=setTimeout(()=>{if(this.timer=void 0,this.deadline=void 0,!this.closed)try{this.transport.expireAuxiliaryReceive(),this.refresh()}catch(e){this.fail(e)}},e)}catch(e){this.fail(e)}}close(){this.closed=!0,this.clear()}clear(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,this.deadline=void 0}fail(e){this.close(),this.onError(e)}},qi=1024*1024,Ji=class{runtime;transport;sendFrames;onError;onAuxiliaryTrace;receiveDeadline;scheduled=!1;running=!1;runAgain=!1;closed=!1;outboundDrainScheduled=!1;inboundRouting=Promise.resolve();requestedGeneration=0;completedGeneration=0;flushWaiters=new Set;removeWorkListener;handleRuntimeWork=e=>this.schedule(e??!1);constructor(e,t,n,r,i){this.runtime=e,this.transport=t,this.sendFrames=n,this.onError=r,this.onAuxiliaryTrace=i,this.receiveDeadline=new Ki(t,e=>{this.close(),this.onError(e)}),this.removeWorkListener=e.onPeerTransportWork(this.handleRuntimeWork);try{this.transport.setAuxiliaryTraceEnabled?.(i!==void 0),this.transport.setOutboundScheduler?.(()=>this.scheduleOutboundDrain())}catch(e){this.closed=!0;try{this.removeWorkListener()}finally{try{this.transport.clearOutboundScheduler?.()}finally{this.transport.setAuxiliaryTraceEnabled?.(!1)}}throw e}this.watchAuxiliaryOutbound().catch(e=>{this.closed||this.onError(e)}),this.schedule(!0)}receive(e){this.closed||e.length===0||(this.inboundRouting=this.inboundRouting.then(()=>this.routeInboundFrames(e)).catch(e=>{this.closed||this.onError(e)}))}schedule(e=!0){if(!this.closed){if(this.requestedGeneration+=1,this.running){this.runAgain||=e;return}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.pump().catch(e=>{this.closed||this.onError(e)})}))}}close(){if(!this.closed){this.closed=!0,this.receiveDeadline.close(),this.removeWorkListener(),this.transport.clearOutboundScheduler?.(),this.transport.setAuxiliaryTraceEnabled?.(!1),this.runtime.retirePeerTransport(this.transport).catch(this.onError);for(let e of this.flushWaiters)e.resolve();this.flushWaiters.clear()}}async flush(){if(this.closed)return;this.schedule();let e=this.requestedGeneration;this.completedGeneration>=e||await new Promise(t=>this.flushWaiters.add({target:e,resolve:t}))}drainOutboundFrames(){if(this.closed)return!1;let e=Xi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=Xi(t.call(this.transport,8,qi));return n.length>0&&this.sendFrames(n),this.publishAuxiliaryTrace(),n.length>0}scheduleOutboundDrain(){this.closed||this.outboundDrainScheduled||(this.outboundDrainScheduled=!0,queueMicrotask(()=>{this.outboundDrainScheduled=!1,this.closed||this.drainOutboundFrames()}))}async pump(){if(this.closed||this.running)return;this.running=!0;let e=this.requestedGeneration;try{if(this.drainOutboundFrames(),await this.runtime.progressPeerTransport(),this.closed)return;this.drainOutboundFrames()}finally{this.running=!1,this.completedGeneration=Math.max(this.completedGeneration,e);for(let e of this.flushWaiters)e.target>this.completedGeneration||(this.flushWaiters.delete(e),e.resolve())}this.closed||this.runAgain&&(this.runAgain=!1,this.schedule())}async routeInboundFrames(e){if(this.closed)return;let t=[];for(let n of e){let e=this.transport.routeAuxiliaryWireFrame?await this.transport.routeAuxiliaryWireFrame(n):n;if(this.receiveDeadline.refresh(),this.closed)return;e!=null&&t.push(Zi(e))}if(!this.closed){if(t.length>0)if(this.transport.sendWireFrames)this.transport.sendWireFrames(t);else for(let e of t)this.transport.sendWireFrame(e);this.runtime.notifyPeerTransportActivity?.(),this.publishAuxiliaryTrace(),this.schedule()}}publishAuxiliaryTrace(){if(!this.onAuxiliaryTrace)return;let e=this.transport.takeAuxiliaryTrace?.();!e||e.length===0||this.onAuxiliaryTrace(e)}async watchAuxiliaryOutbound(){for(;!this.closed;){let e=this.transport.auxiliaryOutboundReady?.();if(!e||typeof e==`boolean`||(await e,this.closed))return;this.drainOutboundFrames()&&await Qi()}}};function Yi(e){return e.map(e=>e.slice())}function Xi(e){return e.map(Zi)}function Zi(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`Browser worker transport received a non-binary wire frame`)}function Qi(){return new Promise(e=>setTimeout(e,0))}var $i=new WeakMap;function ea(e,t){let n=$i.get(e);if(!n||n.databaseName!==t||!n.active()||n.claimed)throw Error(`IndexedDB reclamation requires an unclaimed live database Web Lock`);return n.claimed=!0,n.active}var ta=`jazz-idb-tree`,na=`pages`,ra=`metadata`,U=`storage-manifest`,ia=`epoch`,aa=`browser-runtime-owner`,oa=`browser-worker-epoch-v1`,sa=`jazz-browser-worker-epoch-v1`,ca=`replica-node-v1`,la=`foreground-node-leases-v1`,ua=`jazz-foreground-node-leases-v1`,da=(1n<<64n)-1n,fa=`current`,pa=1024,ma=2147483648,ha={storageEpoch:1,adapterId:`jazz-idb-tree`,adapterFormatVersion:1,requiredCodecIds:[`jazz.sqlite-storage.v1`],pageSize:16*1024,pageChecksum:`xxh3-64-le`,pageFormatMagic:`IDBTREE\0`,pageFormatVersion:1},ga=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},_a=class extends Error{code=`storage`;constructor(e){super(`browser storage: could not write to IndexedDB (QuotaExceededError); the browser may be out of storage space for this site`,{cause:e}),this.name=`IndexedDbStorageFullError`}};function va(e,t){return e?.name===`QuotaExceededError`?new _a(e):e??Error(t)}var ya=class e{db;name;invalidated=!1;reclamationOwnership=null;treeClaims=new Set;nextTreeToken=0;treeTransactions=new Set;ownershipRevision=0;claimTreeOwnership(){if(this.assertValid(),this.reclamationOwnership&&(this.treeClaims.size>0||this.treeTransactions.size>0))throw Error(`IndexedDB reclamation owner already has a tree or pending transaction`);if(this.nextTreeToken===2**53-1)throw Error(`IndexedDB tree token space exhausted`);let e=++this.nextTreeToken;return this.treeClaims.add(e),e}releaseTreeOwnership(e){this.treeClaims.delete(e)}isTreeOwnershipActive(e){return!this.invalidated&&this.treeClaims.has(e)&&(this.reclamationOwnership===null||this.reclamationOwnership())}async retireTreeOwnership(){this.treeClaims.clear(),await Promise.allSettled(this.treeTransactions)}get canReclaimObsoletePages(){return!this.invalidated&&this.treeClaims.size===1&&this.reclamationOwnership?.()===!0}replicaNodeBytes=null;invalidationListeners=new Set;constructor(e,t,n){this.db=e,this.name=t,n&&this.invalidationListeners.add(n),e.addEventListener(`versionchange`,this.handleVersionChange),e.addEventListener(`close`,this.handleUnexpectedClose)}onInvalidated(e){return this.invalidationListeners.add(e),()=>this.invalidationListeners.delete(e)}static async open(t,n={}){let r=indexedDB.open(t,3),i=!1;r.onupgradeneeded=e=>{if(e.oldVersion!==0){i=!0,r.result.close(),r.transaction?.abort();return}let t=r.result;if(t.objectStoreNames.contains(`pages`)||t.createObjectStore(na),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(ra),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(U);r.transaction&&(e.put(ha,ia),e.put(xa().buffer,ca))}};let a;try{a=await W(r)}catch(e){throw i?Error(`Missing or invalid IndexedDB storage epoch manifest`):e}let o=new e(a,t,n.onInvalidated);try{return await o.assertStorageManifest(),n.owner&&await o.claimBrowserRuntimeOwner(n.owner),o.replicaNodeBytes=await o.readReplicaNodeBytes(),o}catch(e){throw o.close(),e}}get replicaNode(){if(!this.replicaNodeBytes)throw Error(`IndexedDB replica node is unavailable before storage admission`);return this.replicaNodeBytes.slice()}async acquireForegroundNodeLease(e=!1){return await this.updateForegroundNodeLeasePool(t=>{if(e){for(let e of t.active)t.retired.push(e.node);t.active=[]}let n=t.reusable.pop(),r={leaseId:crypto.randomUUID(),node:n?.node??Sa(xa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),wa(r)})}async returnForegroundNodeLease(e,t){if(!Aa(e)||!Na(t))throw Error(`Invalid IndexedDB foreground node lease handoff`);await this.updateForegroundNodeLeasePool(n=>{let r=n.active.findIndex(t=>t.leaseId===e);if(r<0)throw Error(`Unknown IndexedDB foreground node lease`);let[i]=n.active.splice(r,1);if(!i)throw Error(`Unknown IndexedDB foreground node lease`);let a=BigInt(i.confirmedTxTime);n.reusable.push({...i,confirmedTxTime:(t>a?t:a).toString()})})}async retireForegroundNodeLease(e){if(!Aa(e))throw Error(`Invalid IndexedDB foreground node lease`);await this.updateForegroundNodeLeasePool(t=>{let n=t.active.findIndex(t=>t.leaseId===e);if(n<0)return;let[r]=t.active.splice(n,1);r&&t.retired.push(r.node)})}async foregroundNodeLeaseNodeState(e){if(e.byteLength!==16)throw Error(`Invalid IndexedDB foreground node identity`);this.assertValid();let t=this.db.transaction(U,`readonly`),n=Ia(t);try{let r=await W(t.objectStore(U).get(la));if(await n,r===void 0)return`missing`;let i=Ta(r),a=Pa(Sa(e));return i.active.some(e=>Pa(e.node)===a)?`active`:i.reusable.some(e=>Pa(e.node)===a)?`reusable`:i.retired.some(e=>Pa(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!ja(e))throw Error(`Invalid browser worker epoch`);if(this.assertValid(),t&&(t.id!==e||this.treeClaims.size>0))throw Error(`IndexedDB reclamation ownership must precede tree construction`);let n=this.ownershipRevision,r=t?ea(t,this.name):null,i=this.db.transaction(U,`readwrite`),a=Ia(i);if(i.objectStore(U).put({format:sa,epoch:e},oa),await a,this.assertValid(),n!==this.ownershipRevision)throw Error(`IndexedDB worker ownership was released while claiming`);this.reclamationOwnership=r}async releaseBrowserWorkerEpoch(e){if(this.treeClaims.clear(),this.ownershipRevision++,this.reclamationOwnership=null,!ja(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(U,`readwrite`),n=Ia(t),r=t.objectStore(U),i=await W(r.get(oa));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(oa),await n}async metadata(){this.assertValid();let e=this.db.transaction(ra,`readonly`),t=Ia(e),n=await W(e.objectStore(ra).get(fa));return await t,n===void 0?null:(Ra(n),n)}async assertStorageManifest(){let e=this.db.transaction(U,`readonly`),t=Ia(e),n=await W(e.objectStore(U).get(ia));await t,Ba(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(U,`readwrite`),n=Ia(t),r=t.objectStore(U),i=await W(r.get(aa));if(i===void 0){r.put(e,aa),await n;return}if(i===e){await n;return}throw t.abort(),await n.catch(()=>void 0),Error(`IndexedDB database ${this.name} is already owned by a different Jazz browser session; this indicates a wrong physical root or namespace derivation error. Reset this scoped database only if you intend to discard its cache`)}async readReplicaNodeBytes(){let e=this.db.transaction(U,`readonly`),t=Ia(e),n=await W(e.objectStore(U).get(ca));if(await t,!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n))throw Error(`Missing or invalid IndexedDB replica node identity`);let r=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(r.byteLength!==16)throw Error(`Missing or invalid IndexedDB replica node identity`);return r.slice()}async updateForegroundNodeLeasePool(e){this.assertValid();let t=ba(this.db,[U]),n=Ia(t),r=t.objectStore(U);try{let t=await W(r.get(la)),i=t===void 0?Ca():Ta(t),a=e(i);return Da(i),r.put(i,la),await n,a}catch(e){try{t.abort()}catch{}throw await n.catch(()=>void 0),e}}async readPage(e){return(await this.readPages([e]))[0]}async readPages(e){this.assertValid();for(let t of e)Ha(t);if(e.length===0)return[];let t=this.db.transaction(na,`readonly`),n=Ia(t),r=t.objectStore(na),i;try{i=await Promise.all(e.map(e=>W(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Fa(e[n],t))}async commit(e,t){if(this.assertValid(),za(e),t!==void 0&&!this.isTreeOwnershipActive(t))throw Error(`IndexedDB tree ownership has expired`);let n=(e.deletedPageIds?.length??0)>0;if(n&&!this.canReclaimObsoletePages)throw Error(`IndexedDB page reclamation ownership is not active`);let r=ba(this.db,[na,ra]),i=Ia(r),a=r.objectStore(na),o=r.objectStore(ra),s=await W(o.get(fa)),c=s===void 0?0:La(s);if(c!==e.expectedGeneration)throw r.abort(),await i.catch(()=>void 0),Error(`IndexedDB B-tree generation changed: expected ${e.expectedGeneration}, found ${c}`);let l={...e.metadata,formatMagic:ta,formatVersion:1,generation:c+1};Ra(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await W(a.get(l.rootPageId))===void 0)throw Error(`IndexedDB B-tree root page ${l.rootPageId} is missing`);if(t!==void 0&&!this.isTreeOwnershipActive(t))throw Error(`IndexedDB tree ownership expired before publication`);if(n&&!this.canReclaimObsoletePages)throw Error(`IndexedDB page reclamation ownership expired before publication`);for(let[t,n]of e.pages){if(n.byteLength>l.pageSize)throw Error(`IndexedDB B-tree page ${t} exceeds configured page size`);a.put(n.slice().buffer,t)}for(let t of e.deletedPageIds??[])a.delete(t);return o.put(l,fa),await i,l}catch(e){try{r.abort()}catch{}throw await i.catch(()=>void 0),e}}commitPages(e,t,n,r,i,a,o,s){if(i.length!==a.length)return Promise.reject(Error(`IDBTree page ids and page bytes have different lengths`));let c=this.commit({expectedGeneration:e,metadata:{pageSize:t,rootPageId:n<0?null:n,nextPageId:r},pages:new Map(i.map((e,t)=>[e,a[t]])),deletedPageIds:o},s);return s!==void 0&&(this.treeTransactions.add(c),c.then(()=>this.treeTransactions.delete(c),()=>this.treeTransactions.delete(c))),c}close(){this.treeClaims.clear(),this.invalidated=!0,this.ownershipRevision++,this.reclamationOwnership=null,this.removeInvalidationListeners(),this.db.close()}async clear(){this.assertValid();let e=ba(this.db,[na,ra]),t=Ia(e);e.objectStore(na).clear(),e.objectStore(ra).clear(),await t}static async destroy(e){let t=indexedDB.deleteDatabase(e);await new Promise((n,r)=>{t.onsuccess=()=>n(),t.onerror=()=>r(t.error??Error(`IndexedDB deletion failed`)),t.onblocked=()=>r(Error(`IndexedDB deletion was blocked by an open connection: ${e}`))})}handleVersionChange=()=>{this.db.close(),this.invalidate()};handleUnexpectedClose=()=>{this.invalidate()};invalidate(){if(this.invalidated)return;this.invalidated=!0,this.treeClaims.clear(),this.reclamationOwnership=null,this.removeInvalidationListeners();let e=new ga(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new ga(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function ba(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function xa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return ie(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Sa(e){return e.slice().buffer}function Ca(){return{format:ua,active:[],reusable:[],retired:[]}}function wa(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Ta(e){return Da(e),{format:e.format,active:e.active.map(Ea),reusable:e.reusable.map(Ea),retired:e.retired.map(e=>e.slice(0))}}function Ea(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Da(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease pool`);let t=e;if(t.format!==`jazz-foreground-node-leases-v1`||!Array.isArray(t.active)||!Array.isArray(t.reusable)||!Array.isArray(t.retired))throw Error(`Invalid IndexedDB foreground node lease pool`);let n=new Set,r=new Set;for(let e of[...t.active,...t.reusable]){Oa(e);let t=Pa(e.node);if(r.has(e.leaseId)||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);r.add(e.leaseId),n.add(t)}for(let e of t.retired){let t=ka(e)?Pa(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function Oa(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!Aa(t.leaseId)||!ka(t.node)||!Ma(t.confirmedTxTime)||!Na(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function ka(e){return e instanceof ArrayBuffer&&e.byteLength===16}function Aa(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function ja(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Ma(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Na(e){return e>=0n&&e<=da}function Pa(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Fa(e,t){if(t===void 0)return null;if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw Error(`IndexedDB B-tree page ${e} is not binary data`);return(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).slice()}function W(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(va(e.error,`IndexedDB request failed`))})}function Ia(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(va(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(va(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function La(e){return Ra(e),e.generation}function Ra(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB B-tree metadata`);let t=e;if(t.formatMagic!==`jazz-idb-tree`||t.formatVersion!==1||!Va(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Ua(t.rootPageId)||!Number.isSafeInteger(t.nextPageId)||Number(t.nextPageId)<0||t.rootPageId!==null&&Number(t.rootPageId)>=Number(t.nextPageId))throw Error(`Invalid IndexedDB B-tree metadata`)}function za(e){if(!Number.isSafeInteger(e.expectedGeneration)||e.expectedGeneration<0)throw Error(`Invalid IndexedDB B-tree expected generation`);let{pageSize:t,rootPageId:n,nextPageId:r}=e.metadata;if(!Va(t)||t!==16384||!Ua(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Ua(n)||n>=r))throw Error(`Invalid IndexedDB B-tree commit root page id`);let i=new Set;for(let[n,a]of e.pages){if(!Ua(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Ua(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Ba(e){if(!e||typeof e!=`object`)throw Error(`Missing or invalid IndexedDB storage epoch manifest`);let t=e,n=Object.keys(t).sort(),r=Object.keys(ha).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==ha.storageEpoch||t.adapterId!==ha.adapterId||t.adapterFormatVersion!==ha.adapterFormatVersion||t.pageSize!==ha.pageSize||t.pageChecksum!==ha.pageChecksum||t.pageFormatMagic!==ha.pageFormatMagic||t.pageFormatVersion!==ha.pageFormatVersion||!Array.isArray(t.requiredCodecIds)||!t.requiredCodecIds.every(e=>typeof e==`string`))throw Error(`Missing or invalid IndexedDB storage epoch manifest`);let i=t.requiredCodecIds,a=ha.requiredCodecIds;if(i.length!==a.length||i.some((e,t)=>e!==a[t])){let e=a.filter(e=>!i.includes(e)),t=i.filter(e=>!a.includes(e));throw new Ye(e,t,`Missing or invalid IndexedDB storage epoch manifest: unsupported storage format: this epoch-1 root lacks codec families ${JSON.stringify(e)} required by this build and declares ${JSON.stringify(t)} that this build does not read`)}}function Va(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=pa&&e<=ma&&Number.isInteger(Math.log2(e))}function Ha(e){if(!Ua(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Ua(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Wa(){return Error(`Inspector control opening was cancelled`)}function Ga(e){try{e.postMessage({type:`close`})}catch{}e.close()}function Ka(e,t){return t?t.aborted?Promise.reject(Wa()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Wa())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var qa=Object.freeze({intervalMs:3e4,replyMs:3e4}),Ja=1e3,Ya=class{runtime;port;dbName;callbacks;traceRelay;pump=null;pendingFrames=[];readyPromise;inspectorAttachmentPhysicalDbName=null;peerAuthority;workerRealmId;pending=new Map;nextRequestId=1;closed=!1;failed=null;disposeQueryCoverageTrace;disposeLocalSettlementObserver;localSettlementsPending=!1;resumeProbePending=!1;established=!1;connectionId=crypto.randomUUID();nextProbeNonce=1;probeNonce=null;watchdogTimer=null;watchdogEpoch=0;constructor(e,t,n,r,i,a=!1,o){this.runtime=e,this.port=t,this.dbName=r,this.callbacks=i,this.traceRelay=a,t.addEventListener(`message`,this.onMessage),t.addEventListener(`messageerror`,this.onMessageError),t.start(),globalThis.addEventListener?.(`pageshow`,this.onResume),globalThis.document?.addEventListener(`visibilitychange`,this.onVisibilityChange),globalThis.document?.addEventListener(`resume`,this.onResume),this.disposeLocalSettlementObserver=e.onLocalSettlementChange(e=>{this.localSettlementsPending=e,this.wantsWatchdog()?this.armWatchdog():this.clearWatchdog()}),this.disposeQueryCoverageTrace=a?e.onQueryCoverageTrace(e=>{this.closed||this.port.postMessage({type:`diagnostic-query-coverage`,...e})}):null;let c=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),l=(async()=>{await c;let t=await e.connectUpstreamPeer(this.peerAuthority);if(this.closed||this.failed)throw await e.retirePeerTransport(t),this.failed??Error(`Browser follower connection is closed`);this.pump=new Ji(e,t,e=>{let t=Yi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=s(t);this.failed||this.closed||(e.reportRemoteServerTransportError(n),this.fail(n))},a?e=>{console.debug(`JAZZ_AUX_RELAY`,e.map(e=>({...e,hop:`tab-worker`})))}:void 0);for(let e of this.pendingFrames.splice(0))this.pump.receive(e)})();this.readyPromise=Promise.all([c,l]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(s(e)))}async ready(){if(await this.readyPromise,this.failed)throw this.failed;if(this.closed)throw Error(`Browser follower connection is closed`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.inspectorAttachmentPhysicalDbName}async waitForServerConnection(){await this.ready(),await this.request({type:`wait-server`})}async disconnect(){await this.ready(),await this.request({type:`disconnect`})}async deleteStorage(){if(await this.ready(),!this.dbName)throw Error(`Browser storage reset requires its IndexedDB name`);let e=await this.request({type:`prepare-storage-reset`});try{await ya.destroy(this.dbName)}catch(e){throw await this.request({type:`abort-storage-reset`}).catch(()=>void 0),e}return await this.request({type:`finish-storage-reset`}),{pendingUploads:e?.pendingUploads}}async storePendingUploads(){return await this.ready(),(await this.request({type:`store-pending-uploads`}))?.pendingUploads}async openInspectorControlPort(e){if(await Ka(this.ready(),e),e?.aborted)throw Wa();let t=new MessageChannel,n=this.nextRequestId++,r=()=>{},i=new Promise((e,t)=>{r=t,this.pending.set(n,{type:`open-inspector-control`,resolve:()=>e(),reject:t})}),a=!1,o=()=>{a||(a=!0,Ga(t.port1))},c=()=>{this.pending.delete(n)&&(o(),r(Wa()))};e?.addEventListener(`abort`,c,{once:!0}),this.armWatchdog();try{this.port.postMessage({type:`open-inspector-control`,id:n,port:t.port2},[t.port2])}catch(e){t.port2.close(),this.fail(s(e))}try{if(await i,e?.aborted)throw o(),Wa();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,c)}}async reconnect(e,t){await this.ready(),await this.request({type:`reconnect`,authJson:e,sessionClaims:t}),await this.request({type:`wait-server`}),this.runtime.clearRemoteServerTransportError()}updateAuth(e,t){this.closed||this.failed||this.ready().then(()=>{this.port.postMessage({type:`update-auth`,authJson:e,sessionClaims:t})}).catch(e=>this.fail(s(e)))}async shutdown(e=!1){this.closed||(await this.request({type:`close`,releaseContext:e}),this.dispose(Error(`Browser follower connection is closed`)))}leaveForPageCache(){if(this.closed||this.failed||!this.established||this.hasPendingWork())return!1;try{this.port.postMessage({type:`close`,releaseContext:!0})}catch{}return this.dispose(Error(`Browser follower connection left for the back/forward cache`)),!0}async waitForPendingWrites(){await this.flushLocal(),await this.request({type:`flush-pending-writes`})}async flushLocal(){await this.ready(),await this.pump.flush();let e=this.request({type:`flush-local`});await this.runtime.flushLocalSettlements(),this.port.postMessage({type:`flush-local-observed`}),await e}detachForReconnect(){this.dispose(Error(`Browser follower connection is reconnecting`))}request(e){if(this.failed)return Promise.reject(this.failed);if(this.closed)return Promise.reject(Error(`Browser follower connection is closed`));let t=this.nextRequestId++,n={...e,id:t},r=new Promise((n,r)=>{this.pending.set(t,{type:e.type,resolve:n,reject:r})});this.armWatchdog();try{this.port.postMessage(n)}catch(e){this.fail(s(e))}return r}clearWatchdog(){this.watchdogTimer!==null&&clearTimeout(this.watchdogTimer),this.watchdogTimer=null,this.probeNonce=null,this.watchdogEpoch++}armWatchdog(){this.closed||this.failed||!this.wantsWatchdog()||this.watchdogTimer!==null||this.scheduleWatchdog(qa.intervalMs,!1)}scheduleWatchdog(e,t){let n=++this.watchdogEpoch,r=Date.now()+e;this.watchdogTimer=setTimeout(()=>{if(n!==this.watchdogEpoch||this.closed||this.failed)return;if(this.watchdogTimer=null,!this.wantsWatchdog()){this.clearWatchdog();return}if(!t||Date.now()>r+Ja){this.sendProbe();return}let e=new $e(`Browser worker connection is unresponsive. Pending operation outcomes are unknown; operations were not retried.`);this.runtime.reportRemoteServerTransportError(e),this.fail(e)},e)}sendProbe(){if(this.clearWatchdog(),this.closed||this.failed||!this.wantsWatchdog())return;let e=this.nextProbeNonce++;this.probeNonce=e,this.scheduleWatchdog(qa.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(s(e))}}onResume=()=>{this.resumeProbePending=!0,this.sendProbe()};hasPendingWork(){return this.pending.size>0||this.localSettlementsPending||this.resumeProbePending}wantsWatchdog(){return this.hasPendingWork()||this.established&&globalThis.document?.visibilityState===`visible`}onVisibilityChange=()=>{globalThis.document?.visibilityState===`visible`&&this.onResume()};onMessage=e=>{if(this.closed||this.failed)return;let t=e.data;if(t.type===`runtime-pong`){if(t.connectionId!==this.connectionId||t.nonce!==this.probeNonce)return;this.resumeProbePending=!1,this.clearWatchdog(),this.armWatchdog();return}if(t.type===`frames`){this.pump?this.pump.receive(t.frames):this.pendingFrames.push(t.frames);return}if(t.type===`auth-failure`){this.callbacks.onAuthFailure(t.reason);return}if(t.type===`auth-restored`){this.callbacks.onAuthRestored();return}if(t.type===`transport-state`){this.callbacks.onExplicitOfflineChange?.(t.explicitlyDisconnected);return}if(t.type===`remote-link`){t.state===`connected`&&this.runtime.clearRemoteServerTransportError(),this.callbacks.onRemoteLinkChange?.(t.state,t.link);return}if(t.type===`mutation-error`){this.runtime.reportRemoteMutationError(t.event);return}if(t.type===`storage-failure`){this.runtime.reportLocalStorageFailure(t.message);return}if(t.type===`transport-error`){this.runtime.reportRemoteServerTransportError(He(t.error),t.retrying===!0);return}if(t.type===`storage-reset`){for(let[e,t]of this.pending)t.type===`finish-storage-reset`&&(this.pending.delete(e),t.resolve());this.wantsWatchdog()||this.clearWatchdog(),this.port.postMessage({type:`storage-reset-observed`,resetId:t.resetId}),this.callbacks.onStorageReset?.(t.resetId);return}if(t.type===`storage-invalidated`){this.callbacks.onStorageInvalidated?.(),this.dispose(Error(`IndexedDB storage was externally invalidated`));return}if(t.type===`relay-trace`){this.traceRelay&&console.debug(`JAZZ_AUX_RELAY`,t.entries);return}if(t.type===`error`){this.fail(He(t.error));return}if(t.type===`inspector-binding`||t.type===`inspector-query-result`)return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),this.wantsWatchdog()||this.clearWatchdog(),t.error?n.reject(He(t.error)):(this.inspectorAttachmentPhysicalDbName??=t.inspectorAttachmentPhysicalDbName??null,n.type===`init`&&(this.peerAuthority=t.peerAuthority,this.workerRealmId=t.workerRealmId),n.resolve({pendingUploads:t.pendingUploads})))};onMessageError=()=>{this.fail(Error(`Browser follower port message error`))};getWorkerRealmId(){return this.workerRealmId}fail(e){if(!(this.failed||this.closed)){this.failed=e;try{this.port.postMessage({type:`close`})}catch{}try{this.callbacks.onFailure(e)}finally{this.dispose(e)}}}dispose(e){if(!this.closed){this.closed=!0,this.clearWatchdog(),globalThis.removeEventListener?.(`pageshow`,this.onResume),globalThis.document?.removeEventListener(`visibilitychange`,this.onVisibilityChange),globalThis.document?.removeEventListener(`resume`,this.onResume),this.disposeLocalSettlementObserver(),this.port.removeEventListener(`message`,this.onMessage),this.port.removeEventListener(`messageerror`,this.onMessageError),this.disposeQueryCoverageTrace?.(),this.pump?.close(),this.pendingFrames.length=0,this.port.close();for(let t of this.pending.values())t.reject(e);this.pending.clear()}}},Xa=e=>`jazz:store-generation:${e}`;function Za(e){try{globalThis.localStorage?.setItem(Xa(e),crypto.randomUUID())}catch{}}function Qa(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Xa(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Xa(e),r),r}catch{return null}}function $a(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Xa(e))!==t}catch{return!0}}var eo=class extends Error{name=`BrowserWorkerScriptLoadError`};async function to(e){let t=e.moduleUrl!==null&&Di(e.moduleUrl)!==void 0,n=e.workerUrl?await no(e.workerUrl,e.fetch??globalThis.fetch):null;return new eo(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?Wi:t?` Jazz runs from the Vite dev server's dependency pre-bundle, so it asks the dev server to resolve the worker from the jazz-tools package; that needs jazz-tools to be a dependency the dev server resolves from your project. Otherwise, add "jazz-tools" to optimizeDeps.exclude in your Vite config, next to "jazz-wasm".`:e.workerUrl?` Serve jazz-tools' dist/worker/jazz-broker-worker.js at that URL as JavaScript, or point runtimeSources.brokerWorkerUrl at where it is served.`:` Your bundler or server did not serve jazz-tools' dist/worker/jazz-broker-worker.js as JavaScript; a single-page-app fallback that answers unknown paths with index.html is a common cause. Point runtimeSources.brokerWorkerUrl at where the worker is served.`} The local-first client cannot start without it.`)}async function no(e,t){if(!t)return null;try{let n=await t(e,{cache:`no-store`});n.body?.cancel().catch(()=>void 0);let r=n.headers.get(`content-type`)??``;return/\btext\/html\b/i.test(r)?`the server answered with an HTML page (HTTP ${n.status}) instead of JavaScript`:n.ok?null:`the server answered HTTP ${n.status}`}catch{return null}}function ro(e,t){if(ao(e))return new SharedWorker(Ci(e),{type:(io(e)?null:Wr())??`module`,name:t});let n=Di(Vr());if(n)return new SharedWorker(n,{type:`module`,name:t});let r=new SharedWorker(new URL(``+new URL(`jazz-broker-worker-nRxyqRt5.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Ui);return r}function io(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function ao(e){return io(e)||Wr()!==null}function oo(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),to({workerUrl:ao(t)?Ci(t):Di(Vr()),moduleUrl:Vr(),metro:Gi()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var so=1e4,co=8,lo=8,uo=25,fo=250,po=5*6e4,mo=1e3,ho=new Map;function go(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function _o(e,t){return[`jazz-runtime`,t,ji(e)].join(`:`)}function vo(e,t){return`${e}\u0000${t}`}var yo=class e{node;confirmedTxTime;leaseId;workerRealmId;worker=null;port=null;closed=!1;terminalError=null;finishPromise=null;finishWaiter=null;listeningForFinish=!1;terminalRequestSent=!1;constructor(e,t,n,r){this.node=e,this.confirmedTxTime=t,this.leaseId=n,this.workerRealmId=r}static async acquire(e){let t=Oi(e.runtimeSources),n=_o(t,e.dbName),r=vo(n,e.storageOwner);if(ho.has(r))throw Error(`Shared browser foreground lease cancellation cleanup is still pending for this database; wait for the previous worker admission to finish`);let i=e=>ro(t,e),a=Date.now()+so,o=So(n),s=0,c=null;for(let l=0;l<co;l+=1)for(;;){let l=a-Date.now();if(l<=0)throw Error(c??`Shared browser runtime did not issue a foreground node lease`);let u=i(`${n}:generation-${o}`),d=await this.acquireFromWorkerGeneration(u,e,r,crypto.randomUUID(),l,go(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=Co(n,o);break}if(c=d.message,s+=1,s>=lo)throw Error(c);let f=Math.min(uo*2**(s-1),fo,Math.max(0,a-Date.now()));if(f<=0)throw Error(c);await new Promise(e=>setTimeout(e,f))}throw Error(c??`Shared browser foreground lease worker did not answer after closing`)}static async acquireFromPort(e,t){let n=await this.acquireFromWorkerGeneration({port:e},t,`inspector:${t.dbName}:${t.storageOwner}`,crypto.randomUUID(),so);if(n.type!==`ready`)throw Error(`Inspector worker is no longer available`);return n.lease}static acquireFromWorkerGeneration(t,n,r,i,a,o,s){let c=t.port;return new Promise((l,u)=>{let d=!1,f=!1,p=null,m=null,h=Error(`Shared browser runtime did not issue a foreground node lease`),g=e=>{f||(f=!0,u(e))},_=()=>setTimeout(()=>{d=!0,p=Symbol(`foreground-lease-cleanup`),ho.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&ho.get(r)===p&&ho.delete(r),c.removeEventListener(`message`,y),c.removeEventListener(`messageerror`,b)},y=r=>{let a=r.data;if(a?.type===`foreground-node-lease-worker-alive`){if(a.attemptId!==i||m===null)return;c.postMessage({type:`acquire-foreground-node-lease`,attemptId:i,dbName:n.dbName,storageOwner:n.storageOwner});return}if(a?.type===`foreground-node-lease-worker-closing`){if(a.attemptId!==i)return;v(),c.close(),f=!0,l({type:`worker-closing`});return}if(a?.type===`foreground-node-lease-busy`){v(),c.close(),f=!0,l({type:`busy`,message:a.message});return}if(a?.type===`foreground-node-lease-error`){v(),c.close(),g(He(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?He(a.error):h);return}if(a?.type!==`foreground-node-lease-ready`||d)return;if(!/^(0|[1-9][0-9]*)$/.test(a.confirmedTxTime)){v(),g(Error(`Shared browser runtime returned an invalid foreground lease high-water`));return}v();let o=new e(a.node.slice(),BigInt(a.confirmedTxTime),a.leaseId,a.workerRealmId);o.worker=t,o.port=c,f=!0,l({type:`ready`,lease:o})},b=()=>{v(),c.close(),g(Error(`Shared browser foreground lease port message error`))},x=oo(t,s,e=>{v(),c.close(),g(e)});c.addEventListener(`message`,y),c.addEventListener(`messageerror`,b),c.start(),m=_(),c.postMessage({type:`probe-foreground-node-lease-worker`,attemptId:i,...o?{wasmPrefetch:o}:{}})})}async returnWithHighWater(e){if(this.terminalError)throw this.terminalError;if(e<0n)throw Error(`Invalid foreground transaction high-water`);await this.finish({type:`return-foreground-node-lease`,confirmedTxTime:e.toString()})}async retire(){if(this.terminalError)throw this.terminalError;this.closed||await this.finish({type:`retire-foreground-node-lease`})}abandonAfterWorkerFailure(e){if(!this.terminalError&&(this.terminalError=e,this.finishWaiter?.reject(e),this.finishWaiter=null,!(this.closed||!this.port)&&(this.listenForFinish(),!this.terminalRequestSent))){this.terminalRequestSent=!0;try{this.port.postMessage({type:`retire-foreground-node-lease`})}catch{this.closeFinishPort()}}}releaseAfterStorageReset(e){this.failFinish(e)}releaseAfterWorkerReplacement(e){this.failFinish(e)}failFinish(e){this.terminalError??=e,this.finishWaiter?.reject(this.terminalError),this.closeFinishPort()}finish(e){if(this.terminalError)return Promise.reject(this.terminalError);if(this.closed)return Promise.reject(Error(`Shared browser foreground lease is already closed`));if(this.finishPromise)return this.finishPromise;let t=this.port;if(!t)return Promise.reject(Error(`Shared browser foreground lease port is unavailable`));this.listenForFinish(),this.finishPromise=new Promise((e,t)=>{this.finishWaiter={resolve:e,reject:t}}),this.terminalRequestSent=!0;try{t.postMessage(e)}catch(e){this.failFinish(s(e))}return this.finishPromise}listenForFinish(){this.listeningForFinish||(this.listeningForFinish=!0,this.port?.addEventListener(`message`,this.onFinishResult),this.port?.addEventListener(`messageerror`,this.onFinishError))}onFinishResult=e=>{let t=e.data;t?.type===`foreground-node-lease-result`&&(t.error?this.failFinish(He(t.error)):(this.finishWaiter?.resolve(),this.closeFinishPort()))};onFinishError=()=>{this.failFinish(Error(`Shared browser foreground lease port message error`))};closeFinishPort(){this.finishWaiter=null,this.closed=!0,this.port?.removeEventListener(`message`,this.onFinishResult),this.port?.removeEventListener(`messageerror`,this.onFinishError),this.worker?.port.close(),this.port=null,this.worker=null}},bo=class{callbacks;worker=null;readyPromise;initialConfigurationAdmissionRejected=!1;heldByAnotherSignIn=!1;readyError=null;connection=null;closed=!1;workerName;connectedGeneration=null;cancelBootstrap=null;releaseLivenessLock=null;dbName;storeGenerationWhenLeft=null;constructor(e,t,n,r){this.callbacks=r;let i=Oi(t.runtimeSources),a=_o(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>ro(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=s(e),this.releaseLivenessLock?.(),r.onFailure(this.readyError)})}holdLivenessLock(){let e=globalThis.navigator?.locks;if(!e)return;let t=`jazz-tab-alive:${crypto.randomUUID()}`,n,r=new Promise(e=>n=e);this.releaseLivenessLock=n;let i=new Promise((n,i)=>{e.request(t,()=>(n(),r)).catch(i)});return i.catch(()=>void 0),{name:t,granted:i}}announceLivenessLock(e,t){e.granted.then(()=>{this.closed||this.worker?.port!==t||t.postMessage({type:`liveness-lock`,name:e.name})},()=>void 0)}async connect(e,t,n,r,i){let a=this.holdLivenessLock(),o=So(r);for(let s=0;s<co;s+=1){if(this.closed)return;let s=`${r}:generation-${o}`,c=await this.connectOnce(e,t,n,s,i);if(c.error)throw c.error;if(this.closed)return;if(c.connected){this.connectedGeneration=o,a&&this.worker&&this.announceLivenessLock(a,this.worker.port);return}o=Co(r,o)}throw Error(`Shared browser runtime did not answer after its previous realm closed`)}connectOnce(e,t,n,r,i){let a=i(r);this.worker=a;let o=a.port;return o.start(),new Promise(r=>{let i=!1,c=!1,l=!1,u=Date.now(),d=u+po,f=typeof document<`u`&&document.hidden,p,m=e=>{i||(i=!0,x(),this.cancelBootstrap===g&&(this.cancelBootstrap=null),r(e))},h=e=>{if(!i){c=!0,m(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{w(),o.close()}}},g=()=>h({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=g;let _=()=>{u=Date.now(),d=u+po},v=()=>{let e=typeof document<`u`&&document.hidden;f&&!e&&_(),f=e},y=()=>_(),b=()=>{let e=Date.now();if((f||e-u>mo*2)&&_(),u=e,e>=d){h({connected:!1,error:new $e(`Shared browser runtime did not finish initialization within five minutes`)});return}p=setTimeout(b,Math.min(mo,d-e))},x=()=>{clearTimeout(p),p=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,v),typeof window<`u`&&window.removeEventListener(`pageshow`,y)},S=n=>{if(c){if(n.data?.type===`runtime-ready`){if(l)return;l=!0,o.postMessage({type:`close`,id:0,releaseContext:!0});return}else if(n.data?.type!==`runtime-bootstrap-cancelled`&&n.data?.type!==`runtime-error`&&n.data?.type!==`worker-closing`&&!(n.data?.type===`result`&&n.data.id===0))return;w(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){w(),o.close(),this.worker===a&&(this.worker=null);let e=He(n.data.error);this.heldByAnotherSignIn=e.message===Oe,this.initialConfigurationAdmissionRejected=e.message===`incompatible persistent browser configuration`||this.heldByAnotherSignIn,m({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;w(),this.cancelBootstrap===g&&(this.cancelBootstrap=null);let r=new Ya(e,o,t.sessionClaims,t.dbName,{onAuthFailure:this.callbacks.onAuthFailure,onAuthRestored:this.callbacks.onAuthRestored,onExplicitOfflineChange:this.callbacks.onExplicitOfflineChange,onRemoteLinkChange:this.callbacks.onRemoteLinkChange,onFailure:this.callbacks.onFailure,onStorageReset:e=>{Za(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{Za(this.dbName),this.callbacks.onStorageInvalidated?.()}},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>m({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})})},C=()=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:Error(`Shared browser runtime port message error`)})},w=()=>{x(),T(),o.removeEventListener(`message`,S),o.removeEventListener(`messageerror`,C)},T=oo(a,t.runtimeSources,e=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:e})});o.addEventListener(`message`,S),o.addEventListener(`messageerror`,C),typeof document<`u`&&document.addEventListener(`visibilitychange`,v),typeof window<`u`&&window.addEventListener(`pageshow`,y),p=setTimeout(b,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})}})}getWorkerRealmId(){return this.connection?.getWorkerRealmId()}ready(){return this.readyPromise.then(()=>{if(this.readyError)throw this.readyError})}async waitForServerConnection(){await this.ready(),await this.connection?.waitForServerConnection()}async updateAuth(e,t){await this.ready(),this.connection?.updateAuth(e,t)}async disconnect(){await this.ready(),await this.connection?.disconnect()}async reconnect(e,t){await this.ready(),await this.connection?.reconnect(e,t)}canRetryInitialConfigurationAdmission(){return this.initialConfigurationAdmissionRejected}waitsForAnotherSignIn(){return this.heldByAnotherSignIn}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=Qa(this.dbName);return e===null||!this.connection.leaveForPageCache()?!1:(this.storeGenerationWhenLeft=e,this.closed=!0,this.connection=null,this.worker=null,this.releaseLivenessLock?.(),!0)}storeChangedSinceLeaving(){return $a(this.dbName,this.storeGenerationWhenLeft)}async shutdown(){if(!this.closed){this.closed=!0,this.cancelBootstrap?.();try{await this.connection?.shutdown(!0)}finally{this.connection=null,this.worker?.port.close(),this.worker=null,this.releaseLivenessLock?.()}}}async waitForPendingWrites(){await this.ready(),await this.connection?.waitForPendingWrites()}async flushLocal(){await this.ready(),await this.connection?.flushLocal()}async deleteStorage(){await this.ready(),Za(this.dbName);try{return await this.connection?.deleteStorage()}finally{Za(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await Ka(this.ready(),e),!this.connection)throw Error(`Shared browser runtime is not connected`);let t=await this.connection.openInspectorControlPort(e),n=this.connectedGeneration;return n!==null&&xo(t,this.workerName,n),t}};function xo(e,t,n){e.addEventListener(`message`,e=>{e.data?.type!==`result`||e.data.workerTerminated!==!0||Co(t,n)})}function So(e){try{let t=Number.parseInt(localStorage.getItem(wo(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function Co(e,t){try{let n=wo(e);return So(e)===t&&localStorage.setItem(n,String(t+1)),So(e)}catch{return t+1}}function wo(e){return`jazz:shared-worker-generation:${e}`}function To(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Eo(e){return[...new Set([...To(e)].map(e=>e.namespace))].sort()}function Do(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function Oo(e,t){let n=[...To(e)],r=Eo(e);if(n.length===0)throw Error(`No live Jazz storage contexts are available on this page.`);let i=t?.trim();if(!i){if(r.length===1){let[e]=r;return n.find(t=>t.namespace===e).db}throw Error(`Multiple live Jazz storage contexts are available. Call window.__jazz.clearStorage("<namespace>").${Do(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${Do(r)}`);return a.db}var ko=new Map;function Ao(){let e=()=>[...ko.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...ko.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...ko].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...ko.keys()].map(t=>t.waitForSync(e)))}}}function jo(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(ko.set(e,t),Lo(n),()=>{ko.delete(e)})}var Mo=Symbol.for(`jazz-tools.window-jazz`);function No(e){return`window.__jazz is Jazz's page handle (window.__jazz.status(), waitForSync(), clearStorage()), but this page already has a window.__jazz that Jazz didn't set (${e===null?`null`:typeof e}). Jazz leaves it as it is and works without its page handle; rename your app's global to get the handle back.`}var Po=new WeakSet;function Fo(e){let t=e.__jazz;return t===void 0||Io(t)?!1:(Po.has(e)||(Po.add(e),console.warn(No(t))),!0)}function Io(e){if(!e||typeof e!=`object`)return!1;if(Mo in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function Lo(e){let t=Fo(e),n=(t?void 0:e.__jazz)??{};n[Mo]=!0;let r=Object.assign(n,Ao(),{async clearStorage(t){await Oo(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Eo(e)},async shutdown(t){let n=[...To(e)];if(n.length===0)return;let r=t?.trim(),i=r?n.filter(e=>e.namespace===r):n;await Promise.all(i.map(e=>e.db.shutdown()))}});return t||(e.__jazz=r),r}var Ro=`history.`;function zo(e){return Bo(e)!==void 0}function Bo(e){return e.startsWith(Ro)?e.slice(8):void 0}var Vo=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Ho=new WeakMap;function G(e,t){let n=Bo(t);if(n===void 0)return e[t];if(zo(n)||!Object.hasOwn(e,n))return;let r=Ho.get(e);r||Ho.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Vo],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Uo=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Wo=class extends Error{code;status;constructor(e,t,n=e){super(n),this.code=e,this.status=t,this.name=`AccountAuthError`}},Go=new WeakMap;function Ko(e){let t=Me(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!r(t.iss)||!r(t.sub))throw new Wo(`invalid_identity_token`);return{issuer:t.iss,subject:t.sub}}function qo(e,t){return e.issuer===t.issuer&&e.subject===t.subject}async function Jo(e,t){if(typeof e==`string`)return e;let n;try{return await Promise.race([Promise.resolve().then(()=>e.getToken(t)),new Promise((e,t)=>{n=setTimeout(()=>t(new Wo(`credential_refresh_timeout`)),3e4)})])}finally{n&&clearTimeout(n)}}async function Yo(e,t,n){let r=Go.get(e);if(!r||r.registry!==t)throw new Wo(`invalid_account_handle`);if(r.delegated)throw new Wo(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new Wo(`backend_account_requires_backend_host`);let i=await Jo(r.auth,n);if(Go.get(e)!==r)throw new Wo(`account_logged_out`);if(!qo(Ko(i),e.identity))throw new Wo(`credential_identity_changed`);return i}function Xo(e){let t=Go.get(e);if(!t)throw new Wo(`invalid_account_handle`);return t.registry}var Zo=new WeakMap;function Qo(e){return $o(e),Zo.get(e)?.bearer}function $o(e){let t=Zo.get(e);if((t!==void 0||e.accountId!==void 0||e.accountRegistryAuthority!==void 0)&&(!t||t.id!==e.accountId||t.registry!==e.accountRegistryAuthority||t.inspectorPort!==void 0&&t.inspectorPort!==e.runtimeSources?.browserWorkerPort))throw new Wo(`account_handle_required`)}function es(e,t){if($o(e),e.accountId!==void 0){if(t.accountId!==e.accountId||t.accountRegistryAuthority!==e.accountRegistryAuthority||Zo.get(e)?.inspectorPort!==void 0&&t.runtimeSources?.browserWorkerPort!==Zo.get(e)?.inspectorPort)throw new Wo(`account_application_mismatch`);Zo.set(t,Zo.get(e))}}function ts(e){let t=e.runtimeSources?.browserWorkerPort;if(!e.accountId||!e.accountRegistryAuthority||!t)throw new Wo(`account_handle_required`);Zo.set(e,{id:e.accountId,registry:e.accountRegistryAuthority,inspectorPort:t})}var ns=Object.freeze({pending:0,oldestPendingAt:null,rejected:0,lastRejection:null});function rs(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function is(e,t){if(e.state!==`offline`||e.reason===`disconnected`)return null;let n={network:`The server is unreachable; retrying.`,auth:`The server refused this client's credential.`,stopped:`The link stopped for good; only db.reconnect() tries again.`,"authority-changed":`The server serves another history than this client's local store.`,"held-by-another-tab":`Another tab holds this account's local store under another sign-in.`}[e.reason];return{kind:e.reason,message:t||n,at:Date.now()}}function as(e,t){return e===t?!0:!e||!t?!1:e.kind===t.kind&&e.at===t.at&&e.message===t.message&&(e.kind!==`rejected`||t.kind===`rejected`&&e.code===t.code)}var os=Object.freeze({state:`local-only`}),ss=Object.freeze({state:`connecting`}),cs=Object.freeze({state:`connected`});function K(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function ls(e){switch(e?.phase??`noServer`){case`noServer`:return os;case`offline`:return K(`disconnected`);case`live`:return cs;case`connecting`:case`backoff`:return e.outagePublished?K(`network`):ss;case`awaitingCredential`:return K(`auth`);case`stopped`:return K(`stopped`)}}function us(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`?!0:e.reason===t.reason&&e.retrying===t.retrying:!1}function ds(e,t=ns,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:rs(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function fs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&as(e.lastError,t.lastError)&&us(e.link,t.link)}function ps(e,t){return e.pending===t.pending&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&e.lastRejection?.at===t.lastRejection?.at&&e.lastRejection?.code===t.lastRejection?.code}var ms=class{read;same;listeners=new Set;published;scheduled=!1;constructor(e,t=Object.is){this.read=e,this.same=t}subscribe(e,t){t.aborted||(this.listeners.size===0&&(this.published=this.read()),this.listeners.add(e),t.addEventListener(`abort`,()=>this.listeners.delete(e),{once:!0}))}get hasListeners(){return this.listeners.size>0}changed(){this.scheduled||this.listeners.size===0||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1;let e=this.read();if(!(this.published!==void 0&&this.same(e,this.published))){this.published=e;for(let t of[...this.listeners])t(e)}}))}};function hs(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function gs(e){if(typeof e==`string`)return e;let t;try{t=JSON.stringify(e)}catch(e){throw Error(`JSON values must be serializable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw Error(`JSON values must be serializable`);return t}function _s(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid relationship "${t}"; use s.rel(...) or s.reverse(...).`);let n=e,r=n.kind===`forward`?`column`:n.kind===`reverse`?`relation`:void 0;if(!r||typeof n.table!=`string`||!n.table||typeof n[r]!=`string`||!n[r])throw Error(`Invalid relationship "${t}": table and ${r??`column/relation`} must be nonempty strings.`)}var vs=class extends Error{},ys=class extends Error{};function bs(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=new Set;for(let t of r.columns){if(e.has(t.name))throw new ys(`Table "${n}" has duplicate column descriptor "${t.name}".`);e.add(t.name)}t.set(n,[]);for(let t of Object.keys(r.relations??{}))if(!t||[`__proto__`,`constructor`,`prototype`].includes(t)||t.startsWith(`$`)||t===`id`||e.has(t))throw new vs(`Relationship "${n}.${t}" collides with a stored/public output column.`)}for(let[n,r]of Object.entries(e))for(let[i,a]of Object.entries(r.relations??{})){if(_s(a,`${n}.${i}`),!Object.hasOwn(e,a.table))throw Error(`Relationship "${n}.${i}" references unknown table "${a.table}".`);let o=a.kind===`forward`?a:e[a.table].relations?.[a.relation];if(!o||o.kind!==`forward`)throw Error(`Reverse relationship "${n}.${i}" must reference a named forward relation on "${a.table}".`);if(a.kind===`reverse`&&o.table!==n)throw Error(`Reverse relationship "${n}.${i}" references a forward relation targeting "${o.table}", not "${n}".`);let s=(a.kind===`forward`?r:e[a.table]).columns.find(e=>e.name===o.column);if(!s)throw Error(`Relationship "${n}.${i}" references unknown column "${o.column}".`);let c=s.column_type.type===`Array`&&s.column_type.element.type===`Uuid`;if(s.column_type.type!==`Uuid`&&!c)throw Error(`Relationship "${n}.${i}" requires UUID or UUID[] column "${o.column}".`);if(s.references&&s.references!==o.table)throw Error(`Relationship "${n}.${i}" conflicts with column reference target "${s.references}".`);t.get(n).push({name:i,type:a.kind,fromTable:n,toTable:a.table,fromColumn:a.kind===`forward`?o.column:`id`,toColumn:a.kind===`forward`?`id`:o.column,isArray:a.kind===`reverse`||c,nullable:a.kind===`forward`&&s.nullable})}return t}function xs(){return{type:`Row`,columns:[{name:`account`,column_type:{type:`Uuid`},nullable:!1},{name:`identity`,nullable:!1,column_type:{type:`Row`,columns:[{name:`issuer`,column_type:{type:`Text`},nullable:!1},{name:`subject`,column_type:{type:`Text`},nullable:!1}]}}]}}var Ss=[`$canRead`],Cs=[`$createdBy`,`$createdAt`,`$updatedBy`,`$updatedAt`,`$createdBy.account`,`$createdBy.identity`,`$createdBy.identity.issuer`,`$createdBy.identity.subject`,`$updatedBy.account`,`$updatedBy.identity`,`$updatedBy.identity.issuer`,`$updatedBy.identity.subject`];function ws(e){return Ss.includes(e)}function Ts(e){return Cs.includes(e)}function Es(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return xs();if(e===`$createdAt`||e===`$updatedAt`||e===`$deletedAt`)return{type:`Timestamp`};let[t,...n]=e.split(`.`);if((t===`$createdBy`||t===`$updatedBy`||t===`$deletedBy`)&&n.length){let e=xs();for(let t of n){if(e.type!==`Row`)return;let n=e.columns.find(e=>e.name===t);if(!n)return;e=n.column_type}return e}}var Ds=`__jazz_requireIncludes`;function Os(e){return Array.isArray(e)?e.filter(e=>F(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function ks(e){return Array.isArray(e)?e.filter(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&(e[1]===`asc`||e[1]===`desc`)):[]}function As(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function js(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ms(e){if(!F(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!F(r))throw Error(`Invalid large-value selection for column "${n}".`);let e=Object.keys(r);if(typeof r.at==`string`&&e.length===1)t[n]={at:r.at};else if(js(r.from)&&js(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(js(r.fromUtf8)&&js(r.toUtf8)&&e.length===2)t[n]={fromUtf8:r.fromUtf8,toUtf8:r.toUtf8};else throw Error(`Invalid large-value selection for column "${n}".`)}return t}function Ns(e){let t=F(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!F(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...F(e)&&e.seed?{seed:Ps(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:Os(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Ps(e){if(!F(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:Os(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ns(e.gather),...Array.isArray(e.orderBy)?{orderBy:ks(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return F(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!F(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ps(e.input)}])}),t}function Fs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function Is(e){let t={...e};return delete t[Ds],Bs(t)}function Ls(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Rs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function zs(e){if(e===!0)return Fs();if(!F(e))return null;if(Ls(e)){let t=Vs(e);return{table:t.table||void 0,conditions:t.conditions,includes:t.includes,requireIncludes:t.requireIncludes,select:t.select,partialSelect:t.partialSelect,orderBy:t.orderBy,limit:t.limit,offset:t.offset,hops:t.hops,gather:t.gather}}if(Rs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:Os(e.conditions),includes:Bs(e.includes),requireIncludes:e[Ds]===!0,select:As(e.select),partialSelect:Ms(e.partialSelect??e.select),orderBy:ks(e.orderBy),limit:typeof e.limit==`number`?e.limit:void 0,offset:typeof e.offset==`number`?e.offset:void 0,hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ns(e.gather)};let t=Fs();return t.requireIncludes=e[Ds]===!0,t.includes=Is(e),t}function Bs(e){if(!F(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=zs(r);e&&(t[n]=e)}return t}function Vs(e){let t=F(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Ms(t.partialSelect??t.select);return{table:t.table,conditions:Os(t.conditions),includes:Bs(t.includes),requireIncludes:t[Ds]===!0,select:Array.isArray(t.select)?As(t.select):Object.keys(n),partialSelect:n,orderBy:ks(t.orderBy),limit:typeof t.limit==`number`?t.limit:void 0,offset:typeof t.offset==`number`?t.offset:void 0,includeDeleted:t.includeDeleted===!0,hops:Array.isArray(t.hops)?t.hops.filter(e=>typeof e==`string`):[],gather:Ns(t.gather),...F(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!F(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ps(e.input)}])}}:{}}}var Hs=`__jazz_include_`;function Us(e){return`${Hs}${e}`}function Ws(e,t,n){let r=G(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);if(!n||n.length===0)return r.columns.map(e=>e.name);let i=new Set(r.columns.map(e=>e.name)),a={explicitColumnsInSchema:new Set,explicitColumnsNotInSchema:new Set,hasWildcard:!1};for(let e of n){if(e===`*`){a.hasWildcard=!0;continue}e!==`id`&&(i.has(e)?a.explicitColumnsInSchema.add(e):a.explicitColumnsNotInSchema.add(e))}if(!a.hasWildcard){let e=[...a.explicitColumnsInSchema,...a.explicitColumnsNotInSchema];return e.length===0&&n.includes(`id`)?[`id`]:e}return a.explicitColumnsNotInSchema.size===0?[...i]:[...i,...a.explicitColumnsNotInSchema]}function Gs(e,t){return t?{scope:t,column:e}:{column:e}}function Ks(e,t,n){let r=G(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:Gs(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:Gs(e.name,t)}}))]}function qs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=Es(n);if(r)return r;let i=G(e,t);if(i)return i.columns.find(e=>e.name===n)?.column_type}function Js(e){if(e instanceof Date){let t=e.getTime();if(!Number.isFinite(t))throw Error(`Invalid Date value for timestamp condition`);return t}if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid number value for timestamp condition`);return e}if(typeof e==`string`){let t=e.trim();if(/^-?\d+(\.\d+)?$/.test(t)){let e=Number(t);if(Number.isFinite(e))return e}let n=Date.parse(t);if(Number.isFinite(n))return n}throw Error(`Invalid timestamp condition. Expected Date, ISO string, or finite number.`)}function Ys(e){return Js(e)}function Xs(e,t){if(e==null)return{type:`Null`};if(t.type===`Json`)return{type:`Text`,value:gs(e)};if(t.type===`Timestamp`&&e instanceof Date)return{type:`Timestamp`,value:Ys(e)};if(t.type===`Bytea`){if(e instanceof Uint8Array)return{type:`Bytea`,value:[...e]};if(Array.isArray(e))return{type:`Bytea`,value:e.map(e=>{let t=Number(e);if(!Number.isInteger(t)||t<0||t>255)throw Error(`Bytea values must contain integers in range 0..255`);return t})};throw Error(`Bytea values must be Uint8Array or byte arrays`)}if(Array.isArray(e)){if(t.type!==`Array`)throw Error(`Unexpected array value for scalar column`);return{type:`Array`,value:e.map(e=>Xs(e,t.element))}}if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`){if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Ys(e)};if(t.type===`BigInt`){if(!Number.isSafeInteger(e))throw Error(`BIGINT query values must be bigint or safe integer numbers`);return{type:`BigInt`,value:BigInt(e)}}if(t.type===`Double`||t.type===`Integer`)return{type:t.type,value:e}}if(typeof e==`bigint`){if(t.type!==`BigInt`)throw Error(`Unexpected bigint value for non-BIGINT column`);return{type:`BigInt`,value:e}}if(typeof e==`string`){if(t?.type===`BigInt`)try{return{type:`BigInt`,value:BigInt(e)}}catch{throw Error(`BIGINT query values must be signed integer strings`)}if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Ys(e)};if(t?.type===`Uuid`)return{type:`Uuid`,value:e};if(t?.type===`Enum`&&!t.variants.includes(e))throw Error(`Invalid enum value "${e}". Expected one of: ${t.variants.join(`, `)}`);return{type:`Text`,value:e}}throw Error(`Unsupported value type: ${typeof e}`)}function Zs(e,t){if(!(!t||e.type!==`forward`||e.nullable))return e.isArray?`MatchCorrelationCardinality`:`AtLeastOne`}function Qs(e,t,n,r){let i=qs(n,r,e);if(!i)throw Error(`Unknown column "${e}" in partial select.`);if(`at`in t){if(i.type!==`Json`)throw Error(`JSON pointer selection requires a JSON column, got "${e}".`);return{kind:`json_pointer`,column:e,at:t.at}}if(`fromUtf8`in t){if(t.toUtf8<t.fromUtf8)throw Error(`Invalid UTF-8 range for column "${e}": toUtf8 must be >= fromUtf8.`);if(i.type!==`Text`)throw Error(`UTF-8 text selection requires a Text column, got "${e}".`);return{kind:`text_utf8`,column:e,from:t.fromUtf8,to:t.toUtf8}}if(t.to<t.from)throw Error(`Invalid range for column "${e}": to must be >= from.`);if(i.type===`Bytea`)return{kind:`bytes`,column:e,from:t.from,to:t.to};if(i.type===`Text`)return{kind:`text_utf16`,column:e,from:t.from,to:t.to};throw Error(`Range selection requires a bytes or Text column, got "${e}".`)}function $s(e,t={},n,r){let i=e.filter(e=>!Object.hasOwn(t,e)).map(e=>({kind:`full`,column:e})),a=n&&r?Object.entries(t).map(([e,t])=>Qs(e,t,n,r)):[];return i.length+a.length>0?[...i,...a]:null}function ec(e){return e.length>0?[...e]:null}function tc(e,t,n){if(t.table&&t.table!==e.toTable)throw Error(`Include builder for relation "${n}" must target table "${e.toTable}", got "${t.table}".`);if(typeof t.offset==`number`&&t.offset!==0)throw Error(`Include builder for relation "${n}" does not support offset().`);if(t.hops.length>0)throw Error(`Include builder for relation "${n}" does not support hopTo(...).`);if(t.gather)throw Error(`Include builder for relation "${n}" does not support gather(...).`);if(Object.keys(t.partialSelect).length>0)throw Error(`Include builder for relation "${n}" does not support partial large-value selections.`)}function nc(e,t,n,r,i){let a=n.get(t)||[],o=[],s=i?.requireIncludes===!0;for(let[i,c]of Object.entries(e)){let e=a.find(e=>e.name===i);if(!e)throw Error(`Unknown relation "${i}" on table "${t}"`);tc(e,c,i);let l=c.select.length>0?Ws(e.toTable,r,c.select):[],u=c.conditions.map(t=>rc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[hs(e),t===`desc`?`Descending`:`Ascending`]),f=nc(c.includes,e.toTable,n,r,{requireIncludes:c.requireIncludes}),p=ec(l),m=r[t]?.columns.some(e=>e.name===i)?Us(i):i;if(e.type===`forward`){let n=Zs(e,s);o.push({column_name:m,table:e.toTable,inner_column:`id`,outer_column:`${t}.${e.fromColumn}`,filters:u,joins:[],select_columns:p,order_by:d,limit:c.limit??null,...n?{requirement:n}:{},nested_arrays:f})}else o.push({column_name:m,table:e.toTable,inner_column:e.toColumn,outer_column:`${t}.id`,filters:u,joins:[],select_columns:p,order_by:d,limit:c.limit??null,nested_arrays:f})}return o}function rc(e,t,n,r){let i=Gs(hs(e.column),r),a=hs(e.column),o=qs(t,n,a);if(!o)throw Error(`Unknown column "${a}" in table "${n}"`);let s=e.value===void 0?!0:e.value;if(e.op===`isNull`){if(typeof s!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return s?{IsNull:{column:i}}:{IsNotNull:{column:i}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:i}};if(e.op===`ne`)return{IsNotNull:{column:i}}}if(o.type===`Row`&&Es(a)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${a}" only supports eq/ne operators.`);let i=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw Error(`Invalid structured author condition for "${a}".`);return e},o=a===`$createdBy`||a===`$updatedBy`||a===`$deletedBy`,s=o?i(e.value,[`account`,`identity`]):void 0,c=i(s?s.identity:e.value,[`issuer`,`subject`]);if(typeof c.issuer!=`string`||typeof c.subject!=`string`||s&&typeof s.account!=`string`)throw Error(`Invalid structured author condition for "${a}".`);ze(c.issuer,c.subject,s?.account);let l={And:[...s?[{column:`${a}.account`,op:`eq`,value:s.account}]:[],{column:`${a}${o?`.identity`:``}.issuer`,op:`eq`,value:c.issuer},{column:`${a}${o?`.identity`:``}.subject`,op:`eq`,value:c.subject}].map(e=>rc(e,t,n,r))};return e.op===`eq`?l:{Not:l}}if(e.op===`in`||e.op===`notIn`){if(!Array.isArray(e.value))throw Error(`"${e.op}" operator requires an array value.`);if(e.value.some(e=>e===null))throw Error(`"${e.op}" does not accept null membership values; use isNull or isNotNull separately.`);let t={In:{left:i,values:e.value.map(e=>({Literal:Xs(e,o)}))}};return e.op===`notIn`?{Not:t}:t}let c=e.op===`contains`&&o.type===`Array`?o.element:o,l=ic(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:Xs(e.value,c)};if(o.type===`Bytea`&&[`gt`,`gte`,`lt`,`lte`].includes(e.op))throw Error(`BYTEA column "${a}" only supports eq/ne operators.`);if(o.type===`Bytea`&&e.op===`contains`)throw Error(`BYTEA column "${a}" does not support contains filters.`);if(o.type===`Json`&&[`gt`,`gte`,`lt`,`lte`,`contains`].includes(e.op))throw Error(`JSON column "${a}" only supports eq/ne/in/isNull operators.`);switch(e.op){case`eq`:return{Cmp:{left:i,op:`Eq`,right:l}};case`ne`:return{Cmp:{left:i,op:`Ne`,right:l}};case`gt`:return{Cmp:{left:i,op:`Gt`,right:l}};case`gte`:return{Cmp:{left:i,op:`Ge`,right:l}};case`lt`:return{Cmp:{left:i,op:`Lt`,right:l}};case`lte`:return{Cmp:{left:i,op:`Le`,right:l}};case`contains`:return{Contains:{left:i,right:l}};default:throw Error(`Unknown operator: ${e.op}`)}}function ic(e){return typeof e!=`object`||!e?!1:e.__jazz_ir_frontier_row_id===!0}function ac(e,t,n,r){return e.length===0?`True`:e.length===1?rc(e[0],t,n,r):{And:e.map(e=>rc(e,t,n,r))}}function oc(e,t){return t===`True`?e:{Filter:{input:e,predicate:t}}}function sc(e,t,n,r,i){if(n.length===0)return e;let a=e,o=t,s=t;for(let e=0;e<n.length;e+=1){let t=n[e],i=(r.get(o)??[]).find(e=>e.name===t);if(!i)throw Error(`Unknown relation "${t}" on table "${o}"`);let c=`__hop_${e}`,l=i.type===`forward`?{left:Gs(i.fromColumn,s),right:Gs(`id`,c)}:{left:Gs(`id`,s),right:Gs(i.toColumn,c)};a={Join:{left:a,right:{TableScan:{table:i.toTable,alias:c}},on:[l],join_kind:`Inner`}},o=i.toTable,s=c}return{Project:{input:a,columns:Ks(o,s,i)}}}function cc(e,t,n,r,i){if(!i[e.step_table])throw Error(`Unknown gather step table "${e.step_table}"`);if(!Number.isInteger(e.max_depth)||e.max_depth<0)throw Error(`gather(...) max_depth must be a non-negative integer.`);let a=Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[];if(a.length!==1)throw Error(`gather(...) currently requires exactly one hopTo(...) step.`);let o=r.get(e.step_table)??[],s=a[0],c=o.find(e=>e.name===s);if(!c)throw Error(`Unknown relation "${s}" on table "${e.step_table}"`);if(c.type!==`forward`)throw Error(`gather(...) currently only supports forward hopTo(...) relations.`);if(c.toTable!==t)throw Error(`gather(...) step must hop back to "${t}" rows, got "${c.toTable}".`);let l={TableScan:{table:e.step_table}},u=Array.isArray(e.step_conditions)?e.step_conditions:[],d=e.step_table,f=oc(l,ac([...u,{column:hs(e.step_current_column),op:`eq`,value:{__jazz_ir_frontier_row_id:!0}}],i,e.step_table,d)),p=`__recursive_hop_0`;return{Gather:{seed:n,step:{Project:{input:{Join:{left:f,right:{TableScan:{table:c.toTable,alias:p}},on:[{left:Gs(c.fromColumn,e.step_table),right:Gs(`id`,p)}],join_kind:`Inner`}},columns:Ks(t,p,i)}},frontier_key:{RowId:`Current`},bound:{MaxDepth:e.max_depth},dedupe_key:[{RowId:`Current`}]}}}function lc(e,t,n){let r=e;for(let e of t){let t=(n.get(r)??[]).find(t=>t.name===e);if(!t)throw Error(`Unknown relation "${e}" on table "${r}"`);r=t.toTable}return r}function uc(e,t,n,r=!1){if(e.union){let r=e.union.inputs.map(e=>uc(e.input,t,n,!0)),i=r[0];if(!i)throw Error(`union(...) requires at least one seed relation.`);if(r.some(e=>e.outputTable!==i.outputTable))throw Error(`union(...) requires all seed relations to output the same table.`);return{expr:dc({Union:{inputs:e.union.inputs.map((e,t)=>({label:e.label,input:r[t].expr}))}},e,i.outputTable,i.outputTable,n),outputTable:i.outputTable}}if(!e.table)throw Error(`gather(...) seed relation is missing table metadata.`);let i={TableScan:{table:e.table}};i=oc(i,ac(e.conditions??[],n,e.table,e.table));let a=e.table;if(e.gather){let r=e.gather.seed?uc(e.gather.seed,t,n):{expr:i,outputTable:a};i=cc(e.gather,r.outputTable,r.expr,t,n),a=r.outputTable}let o=e.hops??[];i=sc(i,a,o,t,n),a=lc(a,o,t);let s=o.length?`__hop_${o.length-1}`:a;return r&&o.length===0&&!e.gather&&(i={Project:{input:i,columns:Ks(a,s,n)}}),i=dc(i,e,a,s,n),{expr:i,outputTable:a}}function dc(e,t,n,r,i){let a=e;return t.orderBy?.length&&(a={OrderBy:{input:a,terms:mc(t.orderBy,i,n).map(({column:e,direction:t})=>({column:Gs(e,r),direction:t}))}}),t.offset!==void 0&&t.offset>0&&(a={Offset:{input:a,offset:t.offset}}),t.limit!==void 0&&(a={Limit:{input:a,limit:t.limit}}),a}function fc(e,t){let n=Vs(JSON.parse(e)),r=bs(t),i=n.hops;if(n.gather&&Object.keys(n.includes).length>0)throw Error(`gather(...) does not yet support include(...).`);if(i.length>0&&Object.keys(n.includes).length>0)throw Error(`hopTo(...) does not yet support include(...).`);let a,o;if(n.gather?.seed){let e=uc(n.gather.seed,r,t);a=cc(n.gather,e.outputTable,e.expr,r,t),o=e.outputTable,a=oc(a,ac(n.conditions,t,o,o)),a=sc(a,o,i,r,t),o=lc(o,i,r)}else{let e=uc({table:n.table,conditions:n.conditions,hops:n.hops,gather:n.gather,union:n.union},r,t);a=e.expr,o=e.outputTable}if(Array.isArray(n.orderBy)&&n.orderBy.length>0){for(let[e]of n.orderBy){let n=qs(t,o,hs(e));if(n?.type===`Bytea`)throw Error(`BYTEA column "${e}" cannot be used in orderBy().`);if(n?.type===`Json`)throw Error(`JSON column "${e}" cannot be used in orderBy().`)}a={OrderBy:{input:a,terms:n.orderBy.map(([e,t])=>({column:Gs(hs(e),i.length>0?`__hop_${i.length-1}`:o),direction:t===`desc`?`Desc`:`Asc`}))}}}return typeof n.offset==`number`&&n.offset>0&&(a={Offset:{input:a,offset:n.offset}}),typeof n.limit==`number`&&(a={Limit:{input:a,limit:n.limit}}),{relation:a,outputTable:o}}function pc(e){return e.union!==void 0||e.hops.length>0||e.gather!==void 0}function mc(e,t,n){return e.map(([e,r])=>{let i=hs(e),a=qs(t,n,i);if(a?.type===`Bytea`)throw Error(`BYTEA column "${e}" cannot be used in orderBy().`);if(a?.type===`Json`)throw Error(`JSON column "${e}" cannot be used in orderBy().`);return{column:i,direction:r===`desc`?`Desc`:`Asc`}})}function hc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}function gc(e,t,n){return e.map(e=>rc(e,t,n))}function _c(e,t,n){let r=n??Vs(JSON.parse(e)),i=bs(t),a=pc(r)?fc(e,t):void 0,o=a?.outputTable??r.table,s=$s(r.select.length>0?Ws(o,t,r.select):[],r.partialSelect,t,o),c=nc(r.includes,r.table,i,t,{requireIncludes:r.requireIncludes});if(a)return hc({table:o,array_subqueries:c,relation_ir:a.relation,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{}});let l=mc(r.orderBy,t,r.table),u=typeof r.limit==`number`?r.limit:void 0,d=typeof r.offset==`number`?r.offset:void 0;return hc({table:r.table,conditions:gc(r.conditions,t,r.table),array_subqueries:c,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{},...l.length>0?{order_by:l}:{},...u===void 0?{}:{limit:u},...d===void 0?{}:{offset:d}})}function vc(e,t){if(t.union){let n=t.union.inputs[0];if(!n)throw Error(`union(...) requires at least one relation.`);let r=vc(e,n.input);for(let n of t.union.inputs.slice(1))if(vc(e,n.input)!==r)throw Error(`union(...) requires all relations to output the same table.`);return r}let n=t.gather?.seed?vc(e,t.gather.seed):t.table;if(!n)throw Error(`gather(...) seed relation is missing table metadata.`);let r=n;if(t.hops?.length)for(let n of t.hops){let t=e[r]?.relations?.[n];if(!t)throw Error(`Unknown relation "${n}" on table "${r}"`);r=t.table}return r}function yc(e,t){if(e)return e instanceof Map?e.get(t)??e.get(`user_${t}`):e[t]??e[`user_${t}`]}function bc(e,t){return e?e instanceof Map?e.has(t)||e.has(`user_${t}`):t in e||`user_${t}`in e:!1}function xc(e,t,n){let r=G(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return Ws(e,t,n).map(e=>{let t=Es(e);if(t)return{name:e,columnType:t};if(ws(e))return{name:e,columnType:{type:`Boolean`}};let n=r.columns.find(t=>t.name===e);return n?{name:n.name,columnType:n.column_type}:null}).filter(e=>e!==null)}function Sc(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`Invalid Bytea array value. Expected integers in range 0..255.`);return e});return new Uint8Array(t)}throw Error(`Invalid Bytea value. Expected Uint8Array or byte array.`)}function Cc(e,t,n){let r=n.get(e)||[],i=[];for(let[a,o]of Object.entries(t)){let t=r.find(e=>e.name===a);if(!t)throw Error(`Unknown relation "${a}" on table "${e}"`);let s=Cc(t.toTable,o.includes,n);i.push({relation:t,nested:s,nestedRelationNames:s.map(e=>e.relation.name),projection:o.select.length>0?o.select:void 0})}return i}function wc(e,t,n=[],r,i){if(!t)return e;for(let a in t){if(!Object.hasOwn(t,a)||!(a in e)||n.includes(a))continue;let o=t[a];o.computed||(e[a]=r?.has(a)&&(!i||!Object.hasOwn(i,a))?r.get(a):o.from(e[a]))}return e}function Tc(e,t,n,r){if(e.type!==`Array`)return Oc(e);let i=e.value.map(e=>{if(e.type!==`Row`)return Oc(e);let i=e.value.id,a=e.value.values,o=e.value.valuesByColumn;return t.baseColumns??=xc(t.relation.toTable,n,t.projection),Ec(a,n,t.relation.toTable,t.nested,t.baseColumns,i,o,r,t.nestedRelationNames)});return t.relation.isArray?i:i[0]??null}function Ec(e,t,n,r,i,a,o,s,c=[],l=!0){if(!G(t,n))throw Error(`Unknown table "${n}" in schema`);let u={};a!==void 0&&(u.id=a);for(let t=0;t<i.length;t++){let n=i[t];if(!n)continue;let r=bc(o,n.name)?yc(o,n.name):o?void 0:e[t];r!==void 0&&(u[n.name]=Oc(r,n.columnType,n.name))}for(let n=0;n<r.length;n++){let a=r[n];if(!a)continue;let c=Us(a.relation.name),l=bc(o,c)?yc(o,c):bc(o,a.relation.name)?yc(o,a.relation.name):o?void 0:e[i.length+n];if(l===void 0){u[a.relation.name]=a.relation.isArray?[]:null;continue}u[a.relation.name]=Tc(l,a,t,s)}let d=l?s?.[n]:void 0;return d?wc(u,d,c):u}function Dc(e,t){return new Date(e)}function Oc(e,t,n){switch(e.type){case`Text`:if(t?.type===`Json`)try{return JSON.parse(e.value)}catch(e){throw Error(`Invalid stored JSON value: ${e instanceof Error?e.message:String(e)}`)}return e.value;case`Uuid`:return e.value;case`Boolean`:return e.value;case`Integer`:case`Double`:return e.value;case`BigInt`:return typeof e.value==`bigint`?e.value:BigInt(e.value);case`Timestamp`:return Dc(e.value,n);case`Bytea`:return Sc(e.value);case`Null`:return null;case`Array`:return t?.type===`Array`?e.value.map(e=>Oc(e,t.element)):e.value.map(e=>Oc(e));case`Row`:return t?.type===`Row`&&n&&(Ts(n)||n===`$deletedBy`||n.startsWith(`$deletedBy.`))?Object.fromEntries(t.columns.map((t,r)=>[t.name,Oc(e.value.values[r],t.column_type,`${n}.${t.name}`)])):t?.type===`Row`?e.value.values.map((e,n)=>Oc(e,t.columns[n]?.column_type)):e.value.values.map(e=>Oc(e))}}function kc(e,t,n,r){if(!G(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Cc(t,Bs(n),r??bs(e));return{includePlans:i,includedRelationNames:i.map(e=>e.relation.name)}}function Ac(e,t,n,r,i,a,o){return e.baseColumns??=xc(r,n,i),Ec(t.values,n,r,e.includePlans,e.baseColumns,t.id,t.valuesByColumn,a,e.includedRelationNames,o)}function jc(e,t,n,r={},i,a,o=!0){let s=kc(t,n,r);return e.map(e=>Ac(s,e,t,n,i,a,o))}function Mc(e,t,n={},r,i,a=!0,o){let s;return c=>(s??=kc(e,t,n,o),Ac(s,c,e,t,r,i,a))}function Nc(e,t,n,r={},i,a,o=!0){let s=jc([e],t,n,r,i,a,o)[0];if(s===void 0)throw Error(`Failed to transform row for table "${n}"`);return s}var Pc=class{failClosed;pending;error;failed=!1;get failure(){return this.error}set failure(e){this.failed=!0,this.error=e}cancelled=!1;constructor(e=!1){this.failClosed=e}run(e){let t=()=>{if(this.failed)throw this.failure;return e()},n=this.pending?this.pending.then(t):t();if(n instanceof Promise){let e=n.then(()=>{},e=>{this.failClosed&&(this.failure=e)});this.pending=e,e.then(()=>{this.pending===e&&(this.pending=void 0)})}return n}async drain(){if(await this.pending,this.failed)throw this.failure}},Fc=new WeakMap;function Ic(e){return Fc.get(e.preparationOwner?.()??e)}function Lc(e){let t=e.preparationOwner?.()??e,n=Fc.get(t);return n||Fc.set(t,n=new Pc),n}function q(e,t){let n=Ic(e);if(n?.pending)return n.run(t);let r=t();return r instanceof Promise?Lc(e).run(()=>r):r}function Rc(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`?t:void 0}var zc=new Set([`schema`,`query`,`write_rejected`,`transaction_conflict`,`storage`,`protocol`,`backpressure`,`not_observed`,`historical_read_requires_server`,`unsupported_storage_codecs`,`authority_changed`,`store_opened_without_migrations`]);function Bc(e){let t=Rc(e);return t!==void 0&&zc.has(t)?t:void 0}var Vc=new Set([`authorization_denied`,`client_clock_too_far_ahead`,`serialization_conflict`,`row_already_deleted`,`row_already_exists`,`row_not_deleted`,`missing_required`,`branch_move`,`missing_chunks`,`predecessor_rejected`,`schema_version_not_deployed`,`identity_mismatch`]);function Hc(e){if(!e||typeof e!=`object`)return;let t=e.reason;return typeof t==`string`&&Vc.has(t)?t:void 0}function Uc(e,t){let n=e.toUpperCase();return Object.assign(Error(`${e} failed: WriteError("authorization_denied: read policy denied ${n} on table ${t}: the row does not exist or the session may not read it")`),{code:`permission_denied`})}function Wc(e,t,n,r){let i=n.filter(e=>!e.name.startsWith(Hs)),a=new Map;for(let e of i)a.set(e.name,r[e.name]??e.default??{type:`Null`});return Object.defineProperty({table:e,id:t,values:i.filter(e=>!Ts(e.name)).map(e=>a.get(e.name))},`valuesByColumn`,{value:a,configurable:!0})}var Gc=new WeakMap;function Kc(e){let t=Gc.get(e);return t||(t=Object.keys(e).filter(t=>e[t].computed),Gc.set(e,t)),t}var qc=class extends Error{constructor(e){super(`Computed dependency "${e}" is unavailable.`)}},Jc=new WeakMap,Yc=class{dependencies=new Map;version=0;observedColumns(e){let t=this.dependencies.get(e);return t||(t=new Set(Jc.get(e)),this.dependencies.set(e,t)),t}observe(e,t){let n=this.observedColumns(e);if(!n.has(t)){n.add(t),this.version++;let r=Jc.get(e);r||Jc.set(e,r=new Set),r.add(t)}}storedColumns(e,t){let n=new Set,r=new Set,i=t=>{if(r.has(t))return;r.add(t);let a=Object.hasOwn(e,t)?e[t]:void 0;if(a?.computed)for(let e of this.observedColumns(a))i(e);else n.add(t)};return i(t),n}};function Xc(e,t,n){if(e===t)return!0;if(typeof e!=`object`||!e||ArrayBuffer.isView(e)||n?.has(e))return!1;if((n??=new Set).add(e),e instanceof Map){for(let[r,i]of e)if(Xc(r,t,n)||Xc(i,t,n))return!0}else if(e instanceof Set){for(let r of e)if(Xc(r,t,n))return!0}for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);if(i&&`value`in i&&Xc(i.value,t,n))return!0}return!1}function Zc(e,t,n,r,i){let a=new Map,o=new Set,s,c=e=>{if(!Object.hasOwn(n,e)||i&&Object.hasOwn(i,e))throw s=new qc(e),s;return n[e]},l=t=>{if(s)throw s;if(a.has(t))return a.get(t);if(o.has(t))throw Error(`Cyclic computed dependency at "${t}".`);o.add(t);try{let n=Object.hasOwn(e,t)?e[t]:void 0,i;if(n?.computed){let e=n.rowColumns??[],a,o=()=>{throw TypeError(`Computed callback rows are read-only.`)},c=i=>{if(a)return Reflect.get(a,i);if(!e.includes(i)){if(Object.hasOwn(Object.prototype,i))return Reflect.get(Object.prototype,i);if(i===`toJSON`)return;if(i===t)return l(i);throw Error(`Unknown computed dependency "${i}".`)}return r?.observe(n,i),l(i)},u=new Proxy(Object.create(null),{get:(e,t)=>typeof t==`string`?c(t):void 0,has:(t,n)=>typeof n==`string`&&e.includes(n),ownKeys:()=>[...e],getOwnPropertyDescriptor:(t,n)=>typeof n==`string`&&e.includes(n)?{configurable:!0,enumerable:!0,get:()=>c(n)}:void 0,set:o,deleteProperty:o,defineProperty:o,setPrototypeOf:o,preventExtensions:o});try{i=n.from(void 0,u)}catch(e){throw s??e}if(i&&(typeof i==`object`||typeof i==`function`)&&`then`in i&&typeof i.then==`function`)throw Promise.resolve(i).catch(()=>{}),TypeError(`Computed field "${t}" must return synchronously.`);if(s)throw s;Xc(i,u)&&(a={...u},i===u&&(i=a))}else{let e=c(t);i=n?n.from(e):e}return a.set(t,i),i}finally{o.delete(t)}};for(let e of t)l(e);return a}var Qc=-(1n<<63n),$c=(1n<<63n)-1n,el=-2147483648,tl=2147483647;function nl(e){let t=Number(e);if(!Number.isInteger(t)||t<el||t>tl)throw Error(`Integer values must be signed 32-bit integers between ${el} and ${tl}; received ${String(e)}`);return t}function rl(e){let t=typeof e==`bigint`?e:typeof e==`number`&&Number.isSafeInteger(e)?BigInt(e):null;if(t==null)throw Error(`Invalid BigInt value. Expected bigint or safe integer number.`);if(t<Qc||t>$c)throw Error(`Invalid BigInt value. Expected signed 64-bit integer range.`);return t}function il(e){let t=e instanceof Date?e.getTime():Number(e);if(!Number.isFinite(t))throw Error(`Invalid timestamp value. Expected Date or finite number.`);return t}function al(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e)){let t=e.map(e=>{let t=Number(e);if(!Number.isInteger(t)||t<0||t>255)throw Error(`Bytea arrays must contain integers in range 0..255`);return t});return new Uint8Array(t)}throw Error(`Expected Uint8Array or byte array for Bytea column type`)}function ol(e,t){if(e==null)return{type:`Null`};switch(t.type){case`Text`:return{type:`Text`,value:String(e)};case`Boolean`:return{type:`Boolean`,value:!!e};case`Integer`:return{type:`Integer`,value:nl(e)};case`BigInt`:return{type:`BigInt`,value:rl(e)};case`Double`:return{type:`Double`,value:Number(e)};case`Timestamp`:return{type:`Timestamp`,value:il(e)};case`Uuid`:return{type:`Uuid`,value:String(e)};case`Bytea`:return{type:`Bytea`,value:al(e)};case`Json`:return{type:`Text`,value:gs(e)};case`Enum`:{let n=String(e);if(!t.variants.includes(n))throw Error(`Invalid enum value "${n}". Expected one of: ${t.variants.join(`, `)}`);return{type:`Text`,value:n}}case`Array`:{if(!Array.isArray(e))throw Error(`Expected array for Array column type, got ${typeof e}`);let n=t.element;return{type:`Array`,value:e.map(e=>ol(e,n))}}case`Row`:{if(typeof e!=`object`||!e)throw Error(`Expected object for Row column type, got ${typeof e}`);let n=e;return{type:`Row`,value:{values:t.columns.map(e=>ol(n[e.name],e.column_type))}}}default:throw Error(`Unsupported column type: ${t.type}`)}}function sl(e,t,n){let r=t[n];if(!r)throw Error(`Unknown table "${n}"`);let i={};for(let[t,a]of Object.entries(e)){if(a===void 0)continue;let e=r.columns.find(e=>e.name===t);if(!e)throw Error(`Unknown column "${t}" on table "${n}"`);if(a===null&&!e.nullable)throw Error(`Cannot set required field '${t}' to null`);e.column_type.type===`Json`&&cl(t,a,e.column_type.schema),i[t]=ol(a,e.column_type)}return i}function cl(e,t,n){if(!n)return;let r=ll(t,n);if(r)throw Error(`encoding error: JSON schema validation failed for column \`${e}\`: ${r}`)}function ll(e,t){let n=t.type;if(n===`object`){if(typeof e!=`object`||!e||Array.isArray(e))return`${JSON.stringify(e)} is not an object`;let n=e,r=ul(t),i=new Set(dl(t.required));for(let e of i)if(!Object.hasOwn(n,e))return`missing required property ${JSON.stringify(e)}`;if(t.additionalProperties===!1){for(let e of Object.keys(n))if(!Object.hasOwn(r,e))return`unexpected property ${JSON.stringify(e)}`}for(let[e,t]of Object.entries(r))if(Object.hasOwn(n,e)){let r=ll(n[e],t);if(r)return r}return null}if(n===`string`){if(typeof e!=`string`)return`${JSON.stringify(e)} is not a string`;let n=fl(t.minLength);if(n!=null&&e.length<n)return`${JSON.stringify(e)} is shorter than ${n} character${n===1?``:`s`}`;let r=fl(t.maxLength);if(r!=null&&e.length>r)return`${JSON.stringify(e)} is longer than ${r} characters`;let i=pl(t.pattern);return i&&!new RegExp(i).test(e)?`${JSON.stringify(e)} does not match ${JSON.stringify(ml(i))}`:null}if(n===`integer`){if(typeof e!=`number`||!Number.isInteger(e))return`${JSON.stringify(e)} is not an integer`;let n=fl(t.minimum);if(n!=null&&e<n)return`${e} is less than the minimum of ${n}`;let r=fl(t.maximum);return r!=null&&e>r?`${e} is greater than the maximum of ${r}`:null}return null}function ul(e){return typeof e.properties!=`object`||e.properties===null||Array.isArray(e.properties)?{}:Object.fromEntries(Object.entries(e.properties).filter(e=>{let[,t]=e;return typeof t==`object`&&!!t&&!Array.isArray(t)}))}function dl(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function fl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function pl(e){return typeof e==`string`?e:null}function ml(e){return e.replaceAll(`\\d`,`[0-9]`)}var hl=1e3,gl=5*6e4;function _l(e){return Math.min(gl,hl*2**Math.min(e,20))}var vl=class{streak=0;next(){let e=this.streak++;return e===0?0:_l(e-1)}reset(){this.streak=0}},yl=new WeakMap;function bl(e){let t=yl.get(e);if(t?.size)for(let e of[...t])try{e()}catch(e){console.error(`Jazz local write observer failed`,e)}}var xl=Symbol.for(`jazz-tools.shippedMigrations`);function Sl(e){return e[xl]}function Cl(e){return!!e.adminSecret}function wl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,policies:void 0}]))}var Tl=new WeakMap;function El(e){let t=Tl.get(e);if(t)return t;let n=wl(e);return Tl.set(e,n),n}var Dl=class{host;client=null;clientSchema=null;disposeRuntimeTelemetry=null;remoteLinkHintBinding=null;clientCreatedListeners=new Set;syncStatusListeners=new Set;syncStatusBinding=null;foregroundNodeLease;constructor(e){this.host=e}getClient(e){let{config:t,runtimeSource:n}=this.host,r=n.supportsPolicyBypass&&Cl(t)?El(e):e,i=qe(r);if(this.client){if(!this.clientSchema||qe(this.clientSchema)!==i)throw Error(`Db is already initialized with a different schema. Create a separate Db for each schema/app.`);return this.client}this.installRuntimeTelemetry();let a={...t};es(t,a),l(a,A(t));let o=n.createClient({config:a,schema:r,migrations:Sl(e),onAuthFailure:e=>this.host.markUnauthenticated(e),foregroundNodeLease:this.foregroundNodeLease});o.onMutationError(e=>this.host.onMutationError(e)),pe(o,e=>this.host.renewsCredential?.(e)===!0),this.client=o,this.clientSchema=r,this.bindRemoteLinkHint(o),this.bindSyncStatus(),this.onClientCreated({schemaKey:i,schema:r,client:o});for(let e of[...this.clientCreatedListeners])e();return o}getCurrentClient(){return this.client}getRuntimeSchema(){return this.client?.getSchema()??null}get clientEntry(){return!this.client||!this.clientSchema?null:{schemaKey:qe(this.clientSchema),schema:this.clientSchema,client:this.client}}onClientCreated(e){}explicitOfflineListeners=new Set;onExplicitOfflineChange(e,t){t.aborted||(this.explicitOfflineListeners.add(e),t.addEventListener(`abort`,()=>this.explicitOfflineListeners.delete(e),{once:!0}))}publishExplicitOfflineState(){let e=this.isExplicitlyOffline();for(let t of[...this.explicitOfflineListeners])t(e)}remoteLinkState(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?`none`:this.isExplicitlyOffline()?`unavailable`:this.transportLinkState()}transportLinkState(){let e=this.getCurrentClient()?.getRuntime().remoteLinkState?.()??`connecting`;return e===`none`?`connecting`:e}onRemoteLinkStateChange(e,t){if(t.aborted)return;let n=this.remoteLinkState(),r=()=>{if(t.aborted)return;let r=this.remoteLinkState();r!==n&&(n=r,e(r))};this.onExplicitOfflineChange(r,t),this.onTransportLinkStateChange(r,t)}bindRemoteLinkHint(e){this.remoteLinkHintBinding?.abort();let t=e.getRuntime?.();if(!t?.setRemoteLinkHint)return;let n=new AbortController;this.remoteLinkHintBinding=n;let r=e=>{n.signal.aborted||t.setRemoteLinkHint?.(e)};this.onRemoteLinkStateChange(r,n.signal),r(this.remoteLinkState())}onTransportLinkStateChange(e,t){if(t.aborted)return;let n=()=>{this.getCurrentClient()?.getRuntime().onRemoteLinkStateChange?.(e,t),e()};if(this.getCurrentClient()){n();return}let r=()=>this.clientCreatedListeners.delete(i),i=()=>{r(),t.removeEventListener(`abort`,r),t.aborted||n()};this.clientCreatedListeners.add(i),t.addEventListener(`abort`,r,{once:!0})}syncStatus(){let e=this.linkStatus();if(e.state===`local-only`)return ds(e);let t=this.client?.getRuntime();return ds(e,t?.uploadStatus?.()??ns,t?.lastLinkFailure?.()??null)}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?os:this.isExplicitlyOffline()?K(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??ss;return e.state===`local-only`?ss:e}onSyncStatusChange(e,t){t.aborted||(this.syncStatusListeners.add(e),t.addEventListener(`abort`,()=>{this.syncStatusListeners.delete(e),this.syncStatusListeners.size===0&&this.unbindSyncStatus()},{once:!0}),this.onExplicitOfflineChange(e,t),this.bindSyncStatus())}notifySyncStatus(){for(let e of[...this.syncStatusListeners])e()}bindSyncStatus(){if(this.syncStatusBinding||!this.client||this.syncStatusListeners.size===0)return;let e=new AbortController;this.syncStatusBinding=e,this.client.getRuntime().onSyncStatusChange?.(()=>this.notifySyncStatus(),e.signal),this.notifySyncStatus()}unbindSyncStatus(){this.syncStatusBinding?.abort(),this.syncStatusBinding=null}async waitForSync(e){let t=this.getCurrentClient()?.getRuntime();if(!(!t||this.linkStatus().state===`local-only`)){if(!t.waitForPendingWrites)throw Error(`Runtime does not support waiting for sync`);await t.waitForPendingWrites(`global`,{throughOutage:!0,signal:e,sync:{}})}}initialExplicitOfflineState(){return null}openInspectorControlPort(e){return Promise.reject(Error(`This runtime has no shared browser worker`))}refreshAccountAuth(e,t){let n={mode:`bearer`,jwtToken:e,trustedReservedSession:t};this.host.runtimeSource.refreshAccountToken(e)?this.client?.acceptAuthUpdate(n):(this.host.runtimeSource.assertAuthUpdateAllowed(),this.updateAuth(n))}updateAuth(e){if(e.mode===`bearer`){e.jwtToken&&e.trustedReservedSession?this.client?.updateTrustedAuthToken(e.jwtToken,e.trustedReservedSession):this.client?.updateAuthToken(e.jwtToken);return}this.client?.updateCookieSession(e.cookieSession)}async storePendingUploads(){}isUsable(){return!0}async shutdownClient(){try{await this.client?.shutdown()}finally{this.clearClient()}}clearClient(){this.remoteLinkHintBinding?.abort(),this.remoteLinkHintBinding=null,this.unbindSyncStatus();let e=this.client!==null;this.client=null,this.clientSchema=null,e&&this.notifySyncStatus()}detachClient(){let e=this.client;return this.clearClient(),e}telemetryCollectorUrl(){return ti()??this.host.config.telemetryCollectorUrl}installRuntimeTelemetry(){let e=this.telemetryCollectorUrl();!e||this.disposeRuntimeTelemetry||(this.disposeRuntimeTelemetry=this.host.runtimeSource.installTelemetry?.({config:this.host.config,collectorUrl:e,runtimeThread:`main`})??null)}async waitForPendingWrites(e={}){let t=this.getCurrentClient()?.getRuntime();if(t){if(!t.waitForPendingWrites)throw Error(`Runtime does not support graceful sync shutdown`);await t.waitForPendingWrites(`global`,{inFlightStreams:e.inFlightStreams})}}async shutdown(){this.disposeRuntimeTelemetry?.(),this.disposeRuntimeTelemetry=null,await this.shutdownClient()}},Ol=class extends Dl{isDisconnected=!1;awaitingCredential=!1;reconnectWaiters=new Set;transportTransition=Promise.resolve();constructor(e){super(e)}async start(){this.foregroundNodeLease=await this.host.runtimeSource.acquireForegroundNodeLease(this.host.config)}async shutdown(){let e=this.foregroundNodeLease;this.foregroundNodeLease=void 0;let t=this.getCurrentClient();try{if(e){let n=t?.getRuntime();n?n.quiesceForegroundTxTimeHighWater?await e.returnWithHighWater(await n.quiesceForegroundTxTimeHighWater()):await e.retire():await e.returnWithHighWater(e.confirmedTxTime)}}catch{await e?.retire().catch(()=>void 0)}finally{await super.shutdown()}}onClientCreated({client:e}){if(this.isExplicitlyOffline()){if(this.host.runtimeSource?.nativeConnection)return;this.enqueueTransportTransition(()=>e.disconnectTransport()).catch(()=>void 0);return}this.connectClient(e)}connectClient(e,t=this.host.config){let{config:n}=this.host;if(this.host.runtimeSource?.nativeConnection||!n.serverUrl)return;let r={jwt_token:t.jwtToken,admin_secret:n.adminSecret,backend_session:t.cookieSession};this.awaitingCredential=!r.jwt_token&&!r.admin_secret&&!r.backend_session,!this.awaitingCredential&&e.connectTransport(n.serverUrl,r)}updateAuth(e){super.updateAuth(e);let t=this.clientEntry?.client;!this.awaitingCredential||!t||this.isExplicitlyOffline()||this.connectClient(t,e.mode===`bearer`?{jwtToken:e.jwtToken}:{cookieSession:e.cookieSession})}async ensureReady(e,t){if(e!==`runtime`)for(;;){for(await this.host.runtimeSource?.nativeConnection?.waitForTransportTransition?.();this.isExplicitlyOffline();)if(await this.waitForReconnect(t),t?.aborted)return;if(await this.transportTransition,!this.isExplicitlyOffline()||t?.aborted)return}}shouldDeferSubscriptionStart(e){return!1}isExplicitlyOffline(){return this.host.runtimeSource?.nativeConnection?.isExplicitlyOffline?.()??this.isDisconnected}onExplicitOfflineChange(e,t){let n=this.host.runtimeSource?.nativeConnection;if(n?.onExplicitOfflineChange){n.onExplicitOfflineChange(e,t);return}super.onExplicitOfflineChange(e,t)}async waitForReconnect(e){if(e?.aborted)return;let t=this.host.runtimeSource?.nativeConnection;if(t?.waitForReconnect){await t.waitForReconnect(e);return}!this.isDisconnected&&(await this.transportTransition,!this.isDisconnected)||await new Promise(t=>{let n=()=>{this.reconnectWaiters.delete(n),e?.removeEventListener(`abort`,r),t()},r=()=>n();e?.addEventListener(`abort`,r,{once:!0}),this.reconnectWaiters.add(n)})}async disconnect(){if(!this.host.config.serverUrl&&!this.host.runtimeSource?.nativeConnection?.configured())throw Error(`Db.disconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{this.host.runtimeSource?.nativeConnection?await this.host.runtimeSource?.nativeConnection.disconnect():await this.clientEntry?.client.disconnectTransport(),this.isDisconnected=!0,this.publishExplicitOfflineState()})}async reconnect(){if(!this.host.config.serverUrl&&!this.host.runtimeSource?.nativeConnection?.configured())throw Error(`Db.reconnect() requires a configured serverUrl.`);if(await this.enqueueTransportTransition(async()=>{let e=this.clientEntry?.client;this.host.runtimeSource?.nativeConnection?await this.host.runtimeSource?.nativeConnection.reconnect():e&&this.connectClient(e),this.isDisconnected=!1,this.publishExplicitOfflineState()}),!this.isDisconnected){let e=Array.from(this.reconnectWaiters);this.reconnectWaiters.clear();for(let t of e)t()}}enqueueTransportTransition(e){let t=this.transportTransition.then(e,e);return this.transportTransition=t.catch(()=>void 0),t}async deleteClientStorage(){if((this.host.config.driver??{type:`persistent`}).type!==`persistent`)throw Error(`deleteClientStorage() is only available when driver.type='persistent'.`);let e=this.getCurrentClient();if(typeof window>`u`&&!e?.supportsClientStorageReset()){console.error(`deleteClientStorage() is only available in browser runtimes.`);return}let t=e??this.getClient({});try{let e=await t.clearClientStorage();return await t.shutdown(),e}finally{this.clearClient()}}},kl=`jazz:indexeddb-invalidation-reload`,Al=1e4;function jl(e={}){let t=(e.now??Date.now)();try{let n=e.storage??globalThis.sessionStorage,r=Number(n.getItem(kl)??0);if(Number.isFinite(r)&&t-r<Al)return!1;n.setItem(kl,String(t))}catch{}return(e.reload??(()=>globalThis.location.reload()))(),!0}async function Ml(e){let t=!1,n;for(let r of e)try{await r()}catch(e){t||(t=!0,n=e)}if(t)throw n}var Nl=`store_held_by_another_tab`,Pl=class extends Error{name=`StoreHeldByAnotherTabError`;code=Nl;constructor(e=`Another tab holds this account's local store under another sign-in: close or reload that other tab. This tab joins once it lets go; reloading this tab first loses its unsynced writes`,t){super(e,t)}},Fl=Symbol.for(`jazz.browser-inspector-control-registry`);function Il(){let e=globalThis;return e[Fl]??={factories:new Map,nextFactoryId:1}}function Ll(e,t){e.getConfig=t;let n=Il(),r=n.nextFactoryId++;return n.factories.set(r,e),()=>n.factories.delete(r)}var Rl=[],zl=!1,Bl=Promise.resolve(),Vl=!1;function Hl(e){return typeof window>`u`||typeof window.addEventListener!=`function`?()=>{}:(Ul(),Rl.push(e),()=>{let t=Rl.indexOf(e);t!==-1&&Rl.splice(t,1)})}function Ul(){Vl||(Vl=!0,window.addEventListener(`pagehide`,e=>{e.persisted&&Wl()}),window.addEventListener(`pageshow`,e=>{e.persisted&&Gl()}))}function Wl(){if(!zl){zl=!0;for(let e of[...Rl])try{e.leave()}catch(e){console.warn(`Jazz could not let go of a page lock for the back/forward cache.`,e)}}}function Gl(){if(!zl)return;zl=!1;let e=[...Rl];Bl=Bl.then(async()=>{for(let t of e){if(zl)return;if(Rl.includes(t))try{if(await t.return()===`stop`)return}catch(e){console.warn(`Jazz could not take a page lock again after the back/forward cache.`,e)}}})}var Kl=class e extends Dl{earlyLease;connection=null;connectionReady=null;initialExplicitOfflineStateKnown=!1;connectionError=null;disconnected=!1;workerRemoteLink=`connecting`;workerLinkStatus=null;workerRemoteLinkListeners=new Set;reconnectWaiters=new Set;transportTransition=Promise.resolve();storageReset=null;storageResetError=null;connectionScope=null;unregisterInspectorControl=null;browserConnectionInput=null;recoverableConnectionFailure=!1;workerRecoveryTimer=null;workerRecoveryDelayMs=250;observedConfigurationAdmissionFailure=null;configurationAdmissionRetry=null;readinessByConnection=new WeakMap;replacementWaiters=new Set;heldPatienceTimer=null;heldTooLong=!1;pageAway=null;stopHoldingAcrossPageCache=null;shutdownStarted=!1;shutdownFailure=null;constructor(e,t){super(e),this.earlyLease=t}async start(){this.foregroundNodeLease=await(this.earlyLease??this.host.runtimeSource.acquireBrowserForegroundNodeLease(this.host.config))}getClient(e){if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);if(this.storageResetError)throw this.storageResetError;if(this.storageReset)throw Error(`Browser storage reset is still in progress`);return super.getClient(e)}onClientCreated(e){this.browserConnectionInput=e,this.openBrowserWorkerConnection(),this.stopHoldingAcrossPageCache??=Hl({leave:()=>this.leaveForPageCache(),return:()=>this.returnFromPageCache()})}leaveForPageCache(){let e=this.connection;if(!e||this.pageAway||this.shutdownStarted||this.host.isShuttingDown||this.storageReset||this.recoverableConnectionFailure||this.configurationAdmissionRetry||this.connectionScope?.inspectorAttachment||!e.leaveForPageCache?.())return;let t;this.pageAway={left:e,reopened:new Promise(e=>t=e),reopen:t},this.clearWorkerRecoveryTimer(),this.unregisterInspectorControl?.(),this.unregisterInspectorControl=null,this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.initialExplicitOfflineStateKnown=!1}returnFromPageCache(){let e=this.pageAway;if(e){if(this.pageAway=null,this.shutdownStarted||this.host.isShuttingDown||!this.browserConnectionInput){e.reopen(null);return}if(e.left.storeChangedSinceLeaving?.())return this.connectionError=Error(`This page's store was reset while the page was in the back/forward cache: reload the page`),jl(),e.reopen(null),`stop`;try{e.reopen(this.openBrowserWorkerConnection())}catch(t){throw e.reopen(null),t}}}openBrowserWorkerConnection(){if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);let e=this.browserConnectionInput;if(!e)throw Error(`Browser worker connection requires an initialized client`);this.host.clearAuthenticatedInspectorLocalReads();let t={...this.host.config};es(this.host.config,t),l(t,A(this.host.config));let n,r=this.host.runtimeSource.createBrowserWorkerConnection({config:t,schema:e.schema,client:e.client,onAuthFailure:t=>{lt(e.client,t),this.host.markUnauthenticated(t)},onAuthRestored:()=>this.host.clearAuthError(),onExplicitOfflineChange:e=>this.setExplicitOffline(r,e),onRemoteLinkChange:(e,t)=>this.setWorkerRemoteLink(r,e,t),onFailure:e=>this.observeConnectionFailure(r,s(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r)});n={connection:r,lease:this.foregroundNodeLease,inspectorAttachment:t.runtimeSources?.inspectorBinding!==void 0,resetReason:null,leaseWorkerReplaced:!1},this.connectionScope=n,this.connection=r,this.wakeReplacementWaiters(),this.setWorkerRemoteLink(r,`connecting`),this.observedConfigurationAdmissionFailure=null,this.unregisterInspectorControl?.(),this.unregisterInspectorControl=Ll(e=>r.openInspectorControlPort(e),()=>this.host.config),this.initialExplicitOfflineStateKnown=!1;let i=r.ready();if(this.readinessByConnection.set(r,i),this.connectionReady=i.then(()=>{let e=r.getWorkerRealmId?.();if(n.leaseWorkerReplaced=e!==void 0&&n.lease?.workerRealmId!==void 0&&e!==n.lease.workerRealmId,this.connection!==r)return;let t=r.getAuthenticatedInspectorAttachmentPhysicalDbName?.();t&&this.host.enableAuthenticatedInspectorLocalReads(t),this.initialExplicitOfflineStateKnown=!0,this.connectionError=null,this.recoverableConnectionFailure=!1,this.clearWorkerRecoveryTimer(),this.workerRecoveryDelayMs=250,this.clearHeldPatience()},e=>{this.observeConnectionFailure(r,s(e)),this.connection}),this.disconnected){let e=this.connectionReady;this.enqueueTransportTransition(async()=>{await e,await r.disconnect()}).catch(()=>void 0)}return r}observeConnectionFailure(e,t){if(this.shutdownFailure?.connection===e){t instanceof $e&&this.shutdownFailure.abandon(t);return}if(this.connection!==e)return;this.connectionError=t,this.recoverableConnectionFailure=!0,this.rejectReconnectWaiters(t),this.notifyWorkerRemoteLink();let n=this.admissionRefused(e);n?this.startHeldPatience():t instanceof $e||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof $e||n)&&this.scheduleWorkerRecovery(e)}static HELD_BY_ANOTHER_TAB_PATIENCE_MS=3e4;startHeldPatience(){this.heldPatienceTimer!==null||this.heldTooLong||(this.heldPatienceTimer=setTimeout(()=>{this.heldPatienceTimer=null,!(this.shutdownStarted||this.host.isShuttingDown)&&(this.heldTooLong=!0,this.wakeReplacementWaiters(),this.notifyWorkerRemoteLink())},e.HELD_BY_ANOTHER_TAB_PATIENCE_MS))}clearHeldPatience(){this.heldPatienceTimer!==null&&clearTimeout(this.heldPatienceTimer),this.heldPatienceTimer=null,this.heldTooLong&&(this.heldTooLong=!1,this.notifyWorkerRemoteLink())}admissionRefused(e){return!!e?.waitsForAnotherSignIn?.()}replacementOf(e,t){return new Promise(n=>{let r=()=>{this.connection===e&&!this.heldTooLong&&!this.shutdownStarted&&!this.host.isShuttingDown&&!t?.aborted||(this.replacementWaiters.delete(r),t?.removeEventListener(`abort`,r),n())};this.replacementWaiters.add(r),t?.addEventListener(`abort`,r,{once:!0}),r()})}wakeReplacementWaiters(){for(let e of[...this.replacementWaiters])e()}scheduleWorkerRecovery(e){if(this.workerRecoveryTimer!==null||this.shutdownStarted||this.host.isShuttingDown||this.storageReset||this.connectionScope?.inspectorAttachment&&!this.admissionRefused(e))return;let t=this.workerRecoveryDelayMs;this.workerRecoveryDelayMs=Math.min(t*2,3e4),this.workerRecoveryTimer=setTimeout(()=>{this.workerRecoveryTimer=null,this.enqueueTransportTransition(async()=>{if(!(this.connection!==e||this.shutdownStarted||this.host.isShuttingDown||this.storageReset)){if(this.admissionRefused(e)){await this.retryConfigurationAdmission(e),await this.connectionReady;return}this.connectionError instanceof $e&&(this.reopenFailedFollower(),await this.connectionReady)}}).catch(e=>{this.connectionError??=s(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.host.isShuttingDown||t?.aborted)return;let n=this.storageReset,r=n?null:this.connection,i=r!==null&&this.observedConfigurationAdmissionFailure===r;if(await n,this.storageResetError)throw this.storageResetError;if(!(this.host.isShuttingDown||t?.aborted)&&(r??=this.connection??await this.pageAway?.reopened??await this.configurationAdmissionRetry,i&&r&&(r=await this.retryConfigurationAdmission(r)),!(this.host.isShuttingDown||t?.aborted))){for(;;)try{await(r?this.readinessByConnection.get(r):this.connectionReady);break}catch(e){if(r&&this.admissionRefused(r)&&!t?.aborted){if(this.heldTooLong)throw new Pl(void 0,{cause:e});if(await this.replacementOf(r,t),this.host.isShuttingDown||this.shutdownStarted||t?.aborted)return;r=this.connection??await this.configurationAdmissionRetry;continue}throw r===this.connection&&r?.canRetryInitialConfigurationAdmission?.()&&(this.observedConfigurationAdmissionFailure=r),e}if(await this.connectionReady,!this.host.isShuttingDown){if(this.connectionError)throw this.connectionError;if(e!==`runtime`)for(;;){for(;this.disconnected;)if(await this.waitForReconnect(t),this.host.isShuttingDown||t?.aborted)return;if(await this.transportTransition,!this.disconnected||this.host.isShuttingDown||t?.aborted)break}this.host.config.serverUrl&&e===`server`&&await this.connection?.waitForServerConnection()}}}retryConfigurationAdmission(e){if(this.configurationAdmissionRetry)return this.configurationAdmissionRetry;if(e!==this.connection)return Promise.resolve(this.connection);let t=(async()=>(await e.shutdown(),this.host.isShuttingDown||e!==this.connection?null:(this.connection=null,this.connectionReady=null,this.connectionError=null,this.observedConfigurationAdmissionFailure=null,this.openBrowserWorkerConnection())))();return this.configurationAdmissionRetry=t,t.finally(()=>{this.configurationAdmissionRetry===t&&(this.configurationAdmissionRetry=null)}).catch(()=>void 0),t}shouldDeferSubscriptionStart(e){return e===`server`}isExplicitlyOffline(){return this.disconnected}initialExplicitOfflineState(){return this.initialExplicitOfflineStateKnown?null:this.connectionReady}async waitForReconnect(e){if(!e?.aborted){if(!this.disconnected){if(await this.transportTransition,this.connectionError)throw this.connectionError;if(!this.disconnected)return}await new Promise((t,n)=>{let r=!1,i=o=>{r||(r=!0,this.reconnectWaiters.delete(i),e?.removeEventListener(`abort`,a),o?n(o):t())},a=()=>i();e?.addEventListener(`abort`,a,{once:!0}),this.reconnectWaiters.add(i),e?.aborted?i():this.connectionError&&i(this.connectionError)})}}async disconnect(){if(!this.host.config.serverUrl)throw Error(`Db.disconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{await this.connectionReady,await this.connection?.disconnect(),this.disconnected=!0,this.publishExplicitOfflineState()})}async reconnect(){if(!this.host.config.serverUrl)throw Error(`Db.reconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);if(this.pageAway&&await this.pageAway.reopened,this.recoverableConnectionFailure&&this.reopenFailedFollower(),await this.connectionReady,this.connectionError)throw this.connectionError;let e=this.connection;if(!e)throw Error(`Browser worker connection is unavailable`);await e.reconnect(JSON.stringify(ql(this.host.config)),Jl(this.host.config)),this.disconnected=!1,this.publishExplicitOfflineState()}),this.disconnected||this.resolveReconnectWaiters()}updateAuth(e){let t={...this.host.config,...e.mode===`bearer`?{jwtToken:e.jwtToken,cookieSession:void 0}:{jwtToken:void 0,cookieSession:e.cookieSession}};l(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Bi(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(ql(t)),Jl(t)).catch(e=>{this.observeConnectionFailure(n,s(e))})}async deleteClientStorage(){if(this.storageReset)return this.storageReset;!this.connection&&!this.getCurrentClient()&&this.getClient({});let e=this.connection;if(e&&this.heldTooLong&&this.admissionRefused(e)&&await this.retryConfigurationAdmission(e),await this.ensureReady(`runtime`),this.storageReset)return this.storageReset;if(!this.connection)throw Error(`deleteClientStorage(): the browser worker is not connected`);let t=await this.connection.deleteStorage();return await this.storageReset,t}async storePendingUploads(){if(!(!this.connection||this.storageReset))return await this.connection.storePendingUploads?.().catch(()=>void 0)??void 0}isUsable(){return!this.shutdownStarted&&!this.storageReset&&!this.storageResetError}async openInspectorControlPort(e){if(await Ka(this.connectionReady??Promise.resolve(),e),!this.connection)throw Error(`Shared browser runtime is not connected`);return this.connection.openInspectorControlPort(e)}beginStorageReset(e,t){if(e.resetReason||this.connectionScope!==e&&this.shutdownFailure?.scope!==e)return;e.resetReason=Error(`Browser foreground lease released after storage reset ${t}`),this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.foregroundNodeLease=void 0,this.initialExplicitOfflineStateKnown=!1;let n=this.detachClient(),r=Ml([()=>n?.discard(),()=>e.lease?.releaseAfterStorageReset(e.resetReason),()=>{this.shutdownFailure?.scope===e&&this.shutdownFailure.reset()},()=>e.connection.shutdown(),async()=>{if(this.shutdownStarted||this.connectionScope!==e)return;if(e.inspectorAttachment){this.storageResetError=Error(`Inspector storage was reset; a new attachment is required`);return}let t=await this.host.runtimeSource.acquireBrowserForegroundNodeLease(this.host.config);this.shutdownStarted||this.connectionScope!==e?await t.retire():this.foregroundNodeLease=t}]).finally(()=>{this.storageReset===r&&(this.storageReset=null,this.connectionScope===e&&(this.connectionScope=null))});this.storageReset=r,r.catch(e=>{this.storageResetError??=s(e)})}reopenFailedFollower(){this.recoverableConnectionFailure&&(this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.connectionError=null,this.initialExplicitOfflineStateKnown=!1,this.recoverableConnectionFailure=!1,this.openBrowserWorkerConnection())}reloadAfterStorageInvalidation(e){this.connection===e&&(this.connectionError=Error(`IndexedDB storage was externally invalidated`),jl())}async waitForPendingWrites(){await(this.connection??await this.pageAway?.reopened)?.waitForPendingWrites()}async shutdown(){if(this.shutdownStarted)return;this.shutdownStarted=!0,this.clearWorkerRecoveryTimer(),this.stopHoldingAcrossPageCache?.(),this.stopHoldingAcrossPageCache=null,this.pageAway?.reopen(null),this.pageAway=null,this.heldPatienceTimer!==null&&clearTimeout(this.heldPatienceTimer),this.heldPatienceTimer=null,this.wakeReplacementWaiters();let e=this.connection,t=this.connectionScope,n=this.connectionError;this.connection=null,this.connectionReady=null,this.browserConnectionInput=null,this.initialExplicitOfflineStateKnown=!1,this.resolveReconnectWaiters();let r=this.unregisterInspectorControl;this.unregisterInspectorControl=null;let i=this.foregroundNodeLease;this.foregroundNodeLease=void 0;let a=this.getCurrentClient(),o=null,s=!1,c,l=new Promise(e=>{c=e}),u=e=>{if(!o){o=e;try{this.detachClient()?.discard()}catch{}finally{i?.abandonAfterWorkerFailure(e),c()}}};this.shutdownFailure={connection:e,scope:t,abandon:u,reset:c},n instanceof $e&&u(n);try{await Ml([()=>{if(o)throw o},()=>r?.(),()=>this.storageReset??void 0,async()=>{if(o)throw o;if(!t?.resetReason&&!n)try{await Promise.race([e?.flushLocal(),l.then(()=>{if(o)throw o})])}catch(e){throw s=!0,o||(e instanceof $e&&u(e),e)}},async()=>{if(o)throw o;if(t?.resetReason||!i)return;let e=!1,n;await Promise.race([(async()=>{try{let e=a?.getRuntime();if(!e)s?await i.retire():await i.returnWithHighWater(i.confirmedTxTime);else if(!e.quiesceForegroundTxTimeHighWater)await i.retire();else{let n=await e.quiesceForegroundTxTimeHighWater();if(t?.resetReason)return;t?.leaseWorkerReplaced&&i.releaseAfterWorkerReplacement?i.releaseAfterWorkerReplacement(Error(`Foreground lease owner was replaced`)):s?await i.retire():await i.returnWithHighWater(n)}}catch(r){if(r===t?.resetReason)return;throw e=!0,n=o??r,await i.retire().catch(()=>void 0),n}})(),l.then(()=>{if(e)throw n;if(o)throw o})])},()=>{this.detachClient()?.discard()},()=>super.shutdown(),()=>t?.resetReason?void 0:e?.shutdown(),()=>this.storageReset??void 0,()=>{if(o)throw o}])}finally{this.shutdownFailure=null,this.connectionScope===t&&(this.connectionScope=null)}}resolveReconnectWaiters(){let e=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let t of e)t()}rejectReconnectWaiters(e){let t=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let n of t)n(e)}setExplicitOffline(e,t){this.connection===e&&(this.disconnected=t,this.publishExplicitOfflineState(),t||this.resolveReconnectWaiters())}transportLinkState(){return this.heldTooLong?`unavailable`:this.connectionError&&this.admissionRefused(this.connection)?`connecting`:this.connectionError?`unavailable`:this.workerRemoteLink}onTransportLinkStateChange(e,t){t.aborted||(this.workerRemoteLinkListeners.add(e),t.addEventListener(`abort`,()=>this.workerRemoteLinkListeners.delete(e),{once:!0}))}transportLinkStatus(){if(this.heldTooLong)return K(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return ss;if(this.connectionError)return K(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?ss:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return cs;case`unavailable`:return K(`network`);default:return ss}}setWorkerRemoteLink(e,t,n=null){this.connection===e&&(this.workerRemoteLink=t,this.workerLinkStatus=n,this.notifyWorkerRemoteLink())}notifyWorkerRemoteLink(){for(let e of[...this.workerRemoteLinkListeners])e();this.notifySyncStatus()}enqueueTransportTransition(e){let t=this.transportTransition.then(e,e);return this.transportTransition=t.catch(()=>void 0),t}};function ql(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function Jl(e){return rt({...e,trustedReservedSession:A(e)})?.claims??{}}var Yl=new WeakMap,Xl=new WeakSet;function Zl(e){return Xl.has(typeof e?.current==`function`?e.current():e)}async function Ql(e,t){if(typeof e!=`object`||!e)throw TypeError(`upgradeToLocalFirst was called without its Db: call it as db.upgradeToLocalFirst(loader), not destructured from the Db`);let n=Yl.get(e);if(n)return await n(t);if(Zl(e))throw Error(`This thin Db was not opened by a Jazz provider. Use upgradeToLocalFirst from jazz-tools/thin, which returns the local-first Db.`)}var $l=class extends Error{reason;constructor(e){super(`This Db was replaced by its Jazz session (${e===`signed-out`?`its user signed out or switched accounts`:`it swapped in another client`}), so it no longer reads or writes. In React, read the current Db with useDb() in the component that uses it, instead of keeping an earlier one in a ref, a variable or a closure. Without a framework provider, read it from session.getSnapshot().client inside session.subscribe(...) and subscribe to your queries again there.`),this.name=`DbReplacedError`,this.reason=e}},eu=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}};function tu(e){return e??{type:`persistent`}}function nu(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function ru(e){let t=tu(e.driver);return nu((t.type===`persistent`?t.dbName:void 0)??e.dbName)??H(e)}function iu(e){return Vi(e,ru(e))}function au(e){if(!e)return;let t=e;oe(t.tier);let n={};v(t.tier)&&(n.tier=t.tier);let r=w(t.firstLoadRemoteWaitMs);r!==void 0&&(n.firstLoadRemoteWaitMs=r),t.branch!==void 0&&(n.branch=t.branch),t.base!==void 0&&(n.base=t.base);let i=t.splices;if(i!==void 0){if(!Array.isArray(i)||!i.every(e=>typeof e==`string`))throw Error(`splices must be an array of column names.`);i.length>0&&(n.splices=[...i])}return it(e)&&(n.tier=`local-only`),n}var ou=new WeakMap,su=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getLocalFirstIdentityProof.onAuthChanged.onMutationError.textAnchors.getSyncStatus.waitForSync.getConfig.setDevMode.disconnect.reconnect.getActiveQuerySubscriptions.onActiveQuerySubscriptionsChange.getRuntimeSchema.openInspectorControlPort.insert.insertStreaming.updateStreaming.upsertStreaming.restore.upsert.update.delete.canInsert.canRead.canUpdate.canDelete.createTransaction.captureSnapshot.beginTransaction.beginSerializableTransaction.transaction.serializableTransaction.upgradeToLocalFirst.deleteClientStorage.storePendingUploads.logout.all.allInternal.one.subscribe.subscribeDelta`.split(`.`);function cu(e){let t=ou.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function lu(e,t){let n=Object.values(e).flatMap(e=>e.columns).filter(e=>e.name===t)[0];if(!n)throw Error(`Unknown branch column "${t}".`);return n}function uu(e,t,n,r){let i=G(e,t);if(!i)throw Error(`Unknown table "${t}".`);let a=i.branchBy??[],o=r===`table`?new Set(a):new Set(Object.values(e).flatMap(e=>e.branchBy??[])),s=typeof n==`object`&&n&&!Array.isArray(n)?n:o.size===1?{[[...o][0]]:n}:(()=>{throw Error(`A scalar branch selector requires exactly one ${r===`table`?`table`:`schema`} branch column.`)})(),c=Object.keys(s);if(c.length!==o.size||c.some(e=>!o.has(e)))throw Error(`Branch selector must provide exactly: ${[...o].sort().join(`, `)||`no columns`}.`);return{values:Object.fromEntries(c.map(t=>[t,ol(s[t],lu(e,t).column_type)]))}}function du(e,t,n,r){let i=uu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:uu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:uu(e,t,r,`schema`)}}}function fu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:uu(e,t,r,`table`)}}function pu(e,t,n){if(!n)return;let{branch:r,base:i,...a}=n;if(r===void 0){if(i!==void 0)throw Error(`A branch base requires a branch head.`);return a}return{...a,branch:du(e,t,r,i)}}function mu(e){return{get _table(){return e._table},get _schema(){return e._schema},get _columnTransforms(){return e._columnTransforms},get _columnTransformsByTable(){return e._columnTransformsByTable},get _rowType(){return e._rowType},_build(){let t=JSON.parse(e._build());return t.limit=1,JSON.stringify(t)}}}function hu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function gu(e){if(!e)return e;let t=e.split(`
2
+ import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as D,N as O,Nt as ee,O as te,Ot as ne,P as re,Pt as ie,Q as ae,Qt as k,R as oe,Rt as se,S as ce,St as le,T as ue,Tt as A,U as de,Ut as fe,V as pe,Vt as me,W as he,Wt as j,X as ge,Xt as _e,Y as ve,Yt as M,Z as ye,Zt as be,_ as xe,_t as Se,an as N,at as Ce,b as we,bt as Te,cn as Ee,dt as De,en as Oe,et as ke,ft as Ae,g as je,gt as Me,h as Ne,ht as Pe,in as Fe,it as Ie,j as Le,jt as P,k as Re,kt as ze,m as Be,mt as Ve,nn as He,nt as Ue,on as We,ot as Ge,pt as Ke,q as qe,qt as Je,rn as Ye,rt as Xe,st as Ze,t as Qe,tn as $e,tt as et,ut as tt,v as nt,vt as rt,w as it,wt as at,x as ot,xt as F,y as st,yt as ct,z as lt,zt as ut}from"./src-wuDHsXUe.js";var dt=N(),I=Ee(We(),1),ft=new WeakMap;function pt(e){let t=ft.get(e)??-2;if(!Number.isSafeInteger(t))throw Error(`Inspector request identifiers exhausted`);return ft.set(e,t-1),t}function mt(e,t,n,r){let i=!1,a=new Map,o=new Set,s=new Map,c=new Map,l=({data:e})=>{if(e.type===`error`||e.type===`auth-failure`||e.type===`storage-invalidated`||e.type===`storage-reset`){u();return}if(e.type!==`inspector-query-result`&&e.type!==`result`||e.id>=-1)return;let t=e.error&&He(e.error),n=s.get(e.id);if(n){s.delete(e.id),t?n.reject(t):e.type===`inspector-query-result`?n.resolve(e.value):n.reject(Error(`Unexpected Inspector query response`));return}let r=c.get(e.id);r&&(t||e.type===`inspector-query-result`)&&r.callback?.(t??e.value)},u=()=>{if(i)return;i=!0,t.removeEventListener(`message`,l),t.removeEventListener(`messageerror`,d);let e=Error(`Inspector cache connection closed`);for(let t of s.values())t.reject(e);s.clear(),a.clear(),o.clear();for(let[r,i]of c){try{i.started&&t.postMessage({type:`inspect-unsubscribe`,id:r,binding:n})}catch{}try{i.callback?.(e)}catch(e){console.error(`Inspector subscription close callback failed`,e)}}c.clear()},d=()=>u();t.addEventListener(`message`,l),t.addEventListener(`messageerror`,d);let f=e=>e===`local-only`,p=e=>i?Promise.reject(Error(`Inspector cache connection closed`)):new Promise((r,i)=>{let a=pt(t);s.set(a,{resolve:r,reject:i});try{t.postMessage({...e,id:a,binding:n})}catch(e){s.delete(a),i(e)}});return new Proxy(e,{get(e,s){if(s===`beginTransaction`)return(e,t)=>{if(i)throw Error(`Inspector cache connection closed`);if(e!==`mergeable`)throw Error(`Inspector edits require a mergeable transaction`);if(a.has(t))throw Error(`Inspector transaction already exists`);return a.set(t,[]),t};if(s===`rollbackTransaction`)return async e=>a.delete(e);if(s===`commitTransaction`)return async e=>{let t=a.get(e);if(!t)throw Error(`Inspector transaction is not open`);a.delete(e);let n=await p({type:`inspect-commit`,edits:t});return o.add(n),n};if(s===`waitForTransaction`)return async(t,n,r)=>{let i=await t;if(!o.has(i))return e.waitForTransaction(i,n,r);await Promise.all([r?.ready,p({type:`inspect-wait`,txId:i,tier:n})])};if(s===`insert`||s===`update`||s===`delete`)return(...e)=>{let t=e[0],n=s===`insert`,i=JSON.parse(e[n?2:s===`update`?3:2]??`{}`),o=i.transaction_id,c=a.get(o);if(!c)throw Error(`Inspector writes require an open transaction`);if(i.branch_view||i.target_branch_name||i.attribution)throw Error(`Inspector edits do not support branch or attributed writes`);let l=n?e[3]??crypto.randomUUID():e[1],u=n?e[1]:e[2];c.push(structuredClone({operation:s,table:t,rowId:l,...s===`delete`?{}:{values:u},updatedAt:i.updated_at}));let d={kind:`staged`,openTransactionId:o};if(!n)return d;let f=r[t]?.columns;if(!f)throw Error(`Unknown Inspector table ${t}`);return{...d,id:l,values:f.filter(e=>!e.name.startsWith(`$`)).map(e=>u[e.name]??e.default??{type:`Null`})}};if(s===`upsert`||s===`restore`||s===`updateLargeValues`||s===`streamingMutation`)return()=>{throw Error(`This mutation is not supported by the Inspector`)};if(s===`query`)return(t,n,r,a)=>f(r)?i?Promise.reject(Error(`Inspector cache connection closed`)):p({type:`inspect-query`,query:t,options:a}):e.query(t,n,r,a);if(s===`createSubscription`)return(n,r,a,o)=>{if(!f(a))return e.createSubscription(n,r,a,o);if(i)throw Error(`Inspector cache connection closed`);let s=pt(t);return c.set(s,{query:n,options:o,started:!1}),s};if(s===`executeSubscription`)return(r,i)=>{let a=c.get(r);if(!a)return e.executeSubscription(r,i);if(a.callback=i,!a.started){a.started=!0;try{t.postMessage({type:`inspect-subscribe`,id:r,binding:n,query:a.query,options:a.options})}catch(e){throw c.delete(r),a.started=!1,e}}};if(s===`unsubscribe`)return r=>{let i=c.get(r);if(!i)return e.unsubscribe(r);c.delete(r),i.started&&t.postMessage({type:`inspect-unsubscribe`,id:r,binding:n})};if(s===`close`)return()=>(u(),e.close());if(s===`discard`)return()=>(u(),e.discard());let l=Reflect.get(e,s,e);return typeof l==`function`?l.bind(e):l}})}var ht=BigInt(0),gt=BigInt(1);function _t(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}" `;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function vt(e){if(typeof e==`bigint`){if(!Ot(e))throw Error(`positive bigint expected, got `+e)}else Je(e);return e}function yt(e,t=``){if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw Error(n+`expected safe integer, got type=`+typeof e)}}function bt(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?ht:BigInt(`0x`+e)}function xt(e){return bt(x(e))}function St(e){return bt(x(Et(C(e)).reverse()))}function Ct(e,t){Je(t),e=vt(e);let n=_e(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function wt(e,t){return Ct(e,t).reverse()}function Tt(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function Et(e){return Uint8Array.from(e)}function Dt(e){return Uint8Array.from(e,(t,n)=>{let r=t.charCodeAt(0);if(t.length!==1||r>127)throw Error(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r})}var Ot=e=>typeof e==`bigint`&&ht<=e;function kt(e,t,n){return Ot(e)&&Ot(t)&&Ot(n)&&t<=e&&e<n}function At(e,t,n,r){if(!kt(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function jt(e){let t;for(t=0;e>ht;e>>=gt,t+=1);return t}var Mt=e=>(gt<<BigInt(e))-gt;function Nt(e,t={},n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}let i=(e,t)=>Object.entries(e).forEach(([e,n])=>r(e,n,t));i(t,!1),i(n,!0)}var Pt=()=>{throw Error(`not implemented`)};function Ft(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var L=BigInt(0),R=BigInt(1),It=BigInt(2),Lt=BigInt(3),Rt=BigInt(4),zt=BigInt(5),Bt=BigInt(7),Vt=BigInt(8),Ht=BigInt(9),Ut=BigInt(16);function z(e,t){let n=e%t;return n>=L?n:t+n}function Wt(e,t,n){let r=e;for(;t-- >L;)r*=r,r%=n;return r}function Gt(e,t){if(e===L)throw Error(`invert: expected non-zero number`);if(t<=L)throw Error(`invert: expected positive modulus, got `+t);let n=z(e,t),r=t,i=L,a=R,o=R,s=L;for(;n!==L;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==R)throw Error(`invert: does not exist`);return z(i,t)}function Kt(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function qt(e,t){let n=(e.ORDER+R)/Rt,r=e.pow(t,n);return Kt(e,r,t),r}function Jt(e,t){let n=(e.ORDER-zt)/Vt,r=e.mul(t,It),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,It),i),s=e.mul(a,e.sub(o,e.ONE));return Kt(e,s,t),s}function Yt(e){let t=sn(e),n=Xt(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Bt)/Ut;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Kt(e,p,t),p}}function Xt(e){if(e<Lt)throw Error(`sqrt is not defined for small field`);let t=e-R,n=0;for(;t%It===L;)t/=It,n++;let r=It,i=sn(e);for(;rn(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return qt;let a=i.pow(r,t),o=(t+R)/It;return function(e,r){if(e.is0(r))return r;if(rn(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=R<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function Zt(e){return e%Rt===Lt?qt:e%Vt===zt?Jt:e%Ut===Ht?Yt(e):Xt(e)}var Qt=(e,t)=>(z(e,t)&R)===R,$t=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function en(e){return Nt(e,$t.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,BYTES:`number`,BITS:`number`})),e}function tn(e,t,n){if(n<L)throw Error(`invalid exponent, negatives unsupported`);if(n===L)return e.ONE;if(n===R)return t;let r=e.ONE,i=t;for(;n>L;)n&R&&(r=e.mul(r,i)),i=e.sqr(i),n>>=R;return r}function nn(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function rn(e,t){let n=(e.ORDER-R)/It,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function an(e,t){t!==void 0&&Je(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}var on=class{ORDER;BITS;BYTES;isLE;ZERO=L;ONE=R;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=L)throw Error(`invalid field: expected ORDER > 0, got `+e);let n;this.isLE=!1,typeof t==`object`&&t&&(typeof t.BITS==`number`&&(n=t.BITS),typeof t.sqrt==`function`&&(this.sqrt=t.sqrt),typeof t.isLE==`boolean`&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes==`boolean`&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:i}=an(e,n);if(i>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return z(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return L<=e&&e<this.ORDER}is0(e){return e===L}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&R)===R}neg(e){return z(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return z(e*e,this.ORDER)}add(e,t){return z(e+t,this.ORDER)}sub(e,t){return z(e-t,this.ORDER)}mul(e,t){return z(e*t,this.ORDER)}pow(e,t){return tn(this,e,t)}div(e,t){return z(e*Gt(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Gt(e,this.ORDER)}sqrt(e){return this._sqrt||=Zt(this.ORDER),this._sqrt(this,e)}toBytes(e){return this.isLE?wt(e,this.BYTES):Ct(e,this.BYTES)}fromBytes(e,t=!1){C(e);let{_lengths:n,BYTES:r,isLE:i,ORDER:a,_mod:o}=this;if(n){if(!n.includes(e.length)||e.length>r)throw Error(`Field.fromBytes: expected `+n+` bytes, got `+e.length);let t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw Error(`Field.fromBytes: expected `+r+` bytes, got `+e.length);let s=i?St(e):xt(e);if(o&&(s=z(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return nn(this,e)}cmov(e,t,n){return n?t:e}};function sn(e,t={}){return new on(e,t)}function cn(e,t){if(!e.isOdd)throw Error(`Field doesn't have isOdd`);let n=e.sqrt(t);return e.isOdd(n)?e.neg(n):n}function ln(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function un(e){let t=ln(e);return t+Math.ceil(t/2)}function dn(e,t,n=!1){C(e);let r=e.length,i=ln(t),a=un(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=z(n?St(e):xt(e),t-R)+R;return n?wt(o,i):Ct(o,i)}var fn=BigInt(0),pn=BigInt(1);function mn(e,t){let n=t.negate();return e?n:t}function hn(e,t){let n=nn(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function gn(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function _n(e,t){gn(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:Mt(e),maxNumber:i,shiftBy:BigInt(e)}}function vn(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=pn);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function yn(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function bn(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var xn=new WeakMap,Sn=new WeakMap;function Cn(e){return Sn.get(e)||1}function wn(e){if(e!==fn)throw Error(`invalid wNAF`)}var Tn=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>fn;)t&pn&&(n=n.add(r)),r=r.double(),t>>=pn;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=_n(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=_n(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=vn(n,e,a);n=o,c?i=i.add(mn(u,t[d])):r=r.add(mn(l,t[s]))}return wn(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=_n(e,this.bits);for(let e=0;e<i.windows&&n!==fn;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=vn(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return wn(n),r}getPrecomputes(e,t,n){let r=xn.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),xn.set(t,r))),r}cached(e,t,n){let r=Cn(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Cn(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){gn(t,this.bits),Sn.set(e,t),xn.delete(e)}hasCache(e){return Cn(e)!==1}};function En(e,t,n){let r=e.Fn;yn(t,e),bn(n,r);let i=t.length,a=n.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=jt(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=Mt(c),u=Array(Number(l)+1).fill(o),d=Math.floor((r.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let r=0;r<a;r++){let i=n[r],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(t[r])}let r=o;for(let e=u.length-1,t=o;e>0;e--)t=t.add(u[e]),r=r.add(t);if(f=f.add(r),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function Dn(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return en(t),t}else return sn(e,{isLE:n})}function On(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>fn))throw Error(`CURVE.${e} must be positive bigint`)}let i=Dn(t.p,n.Fp,r),a=Dn(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}function kn(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var An=BigInt(0),B=BigInt(1),jn=BigInt(2),Mn=BigInt(8);function Nn(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function Pn(e,t={}){let n=On(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;Nt(t,{},{uvRatio:`function`});let s=jn<<BigInt(i.BYTES*8)-B,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch{return{isValid:!1,value:An}}});if(!Nn(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?B:An;return At(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`EdwardsPoint expected`)}let f=Ft((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?Mn:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:An,y:B};if(u!==B)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=Ft(e=>{let{a:t,d:n}=a;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:i,Z:o,T:s}=e,l=c(r*r),u=c(i*i),d=c(o*o),f=c(d*d);if(c(d*c(c(l*t)+u))!==c(f+c(n*c(l*u))))throw Error(`bad point: equation left != right (1)`);if(c(r*i)!==c(o*s))throw Error(`bad point: equation left != right (2)`);return!0});class m{static BASE=new m(a.Gx,a.Gy,B,c(a.Gx*a.Gy));static ZERO=new m(An,B,B,An);static Fp=r;static Fn=i;X;Y;Z;T;constructor(e,t,n,r){this.X=u(`x`,e),this.Y=u(`y`,t),this.Z=u(`z`,n,!0),this.T=u(`t`,r),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){if(e instanceof m)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return u(`x`,t),u(`y`,n),new m(t,n,B,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=Et(C(e,n,`point`)),_t(t,`zip215`);let u=Et(e),d=e[n-1];u[n-1]=d&-129;let f=St(u);At(`point.y`,f,An,t?s:r.ORDER);let p=c(f*f),{isValid:h,value:g}=l(c(p-B),c(o*p-i));if(!h)throw Error(`bad point: invalid y coordinate`);let _=(g&B)===B,v=(d&128)!=0;if(!t&&g===An&&v)throw Error(`bad point: x=0 and x_0=1`);return v!==_&&(g=c(-g)),m.fromAffine({x:g,y:f})}static fromHex(e,t=!1){return m.fromBytes(_e(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return h.createCache(this,e),t||this.multiply(jn),this}assertValidity(){p(this)}equals(e){d(e);let{X:t,Y:n,Z:r}=this,{X:i,Y:a,Z:o}=e,s=c(t*o),l=c(i*r),u=c(n*o),f=c(a*r);return s===l&&u===f}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:e}=a,{X:t,Y:n,Z:r}=this,i=c(t*t),o=c(n*n),s=c(jn*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-o),f=l+o,p=f-s,h=l-o,g=c(d*p),_=c(f*h),v=c(d*h);return new m(g,_,c(p*f),v)}add(e){d(e);let{a:t,d:n}=a,{X:r,Y:i,Z:o,T:s}=this,{X:l,Y:u,Z:f,T:p}=e,h=c(r*l),g=c(i*u),_=c(s*n*p),v=c(o*f),y=c((r+i)*(l+u)-h-g),b=v-_,x=v+_,S=c(g-t*h),C=c(y*b),w=c(x*S),T=c(y*S);return new m(C,w,c(b*x),T)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw Error(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=h.cached(this,e,e=>hn(m,e));return hn(m,[t,n])[0]}multiplyUnsafe(e,t=m.ZERO){if(!i.isValid(e))throw Error(`invalid scalar: expected 0 <= sc < curve.n`);return e===An?m.ZERO:this.is0()||e===B?this:h.unsafe(this,e,e=>hn(m,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return h.unsafe(this,a.n).is0()}toAffine(e){return f(this,e)}clearCofactor(){return o===B?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&B?128:0,n}toHex(){return x(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let h=new Tn(m,i.BITS);return m.BASE.precompute(8),m}var Fn=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Pt()}static fromHex(e){Pt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return x(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}};function In(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);Nt(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||k,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(_t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(St(e))}function d(e){let n=y.secretKey;C(e,y.secretKey,`secretKey`);let r=C(t(e),2*n,`hashedSecretKey`),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){return u(t(l(M(...n),C(e,void 0,`context`),!!r)))}function h(e,t,n={}){e=C(e,void 0,`message`),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);return C(M(u,o.toBytes(p)),y.signature,`result`)}let g={zip215:!0};function _(t,n,a,o=g){let{context:s,zip215:c}=o,l=y.signature;t=C(t,l,`signature`),n=C(n,void 0,`message`),a=C(a,y.publicKey,`publicKey`),c!==void 0&&_t(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=St(t.subarray(u,l)),p,h,_;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),_=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(_).clearCofactor().is0()}let v=a.BYTES,y={secretKey:v,publicKey:v,signature:2*v,seed:v};function b(e=s(y.seed)){return C(e,y.seed,`seed`)}function x(e){return be(e)&&e.length===o.BYTES}function S(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let w={getExtendedPublicKey:f,randomSecretKey:b,isValidSecretKey:x,isValidPublicKey:S,toMontgomery(t){let{y:n}=e.fromBytes(t),r=y.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let o=i?a.div(B+n,B-n):a.div(n-B,n+B);return a.toBytes(o)},toMontgomerySecret(e){let n=y.secretKey;return C(e,n),c(t(e.subarray(0,n))).subarray(0,n)}};return Object.freeze({keygen:kn(b,p),getPublicKey:p,sign:h,verify:_,utils:w,Point:e,lengths:y})}var Ln=xt;function Rn(e,t){if(yt(e),yt(t),e<0||e>=1<<8*t)throw Error(`invalid I2OSP input: `+e);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function zn(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Bn(e){if(!be(e)&&typeof e!=`string`)throw Error(`DST must be Uint8Array or ascii string`);return typeof e==`string`?Dt(e):e}function Vn(e,t,n,r){C(e),yt(n),t=Bn(t),t.length>255&&(t=r(M(Dt(`H2C-OVERSIZE-DST-`),t)));let{outputLen:i,blockLen:a}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw Error(`expand_message_xmd: invalid lenInBytes`);let s=M(t,Rn(t.length,1)),c=Rn(0,a),l=Rn(n,2),u=Array(o),d=r(M(c,e,l,Rn(0,1),s));u[0]=r(M(d,Rn(1,1),s));for(let e=1;e<=o;e++)u[e]=r(M(zn(d,u[e-1]),Rn(e+1,1),s));return M(...u).slice(0,n)}function Hn(e,t,n,r,i){if(C(e),yt(n),t=Bn(t),t.length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(Dt(`H2C-OVERSIZE-DST-`)).update(t).digest()}if(n>65535||t.length>255)throw Error(`expand_message_xof: invalid lenInBytes`);return i.create({dkLen:n}).update(e).update(Rn(n,2)).update(t).update(Rn(t.length,1)).digest()}function Un(e,t,n){Nt(n,{p:`bigint`,m:`number`,k:`number`,hash:`function`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;yt(o.outputLen,`valid hash`),C(e),yt(t);let l=r.toString(2).length,u=Math.ceil((l+i)/8),d=t*a*u,f;if(s===`xmd`)f=Vn(e,c,d,o);else if(s===`xof`)f=Hn(e,c,d,i,o);else if(s===`_internal_pass`)f=e;else throw Error(`expand must be "xmd" or "xof"`);let p=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=u*(n+e*a);t[n]=z(Ln(f.subarray(i,i+u)),r)}p[e]=t}return p}var Wn=Dt(`HashToScalar-`);function Gn(e,t,n){if(typeof t!=`function`)throw Error(`mapToCurve() must be defined`);function r(n){return e.fromAffine(t(n))}function i(t){let n=t.clearCofactor();return n.equals(e.ZERO)?e.ZERO:(n.assertValidity(),n)}return{defaults:Object.freeze(n),Point:e,hashToCurve(e,t){let a=Un(e,2,Object.assign({},n,t)),o=r(a[0]),s=r(a[1]);return i(o.add(s))},encodeToCurve(e,t){let a=n.encodeDST?{DST:n.encodeDST}:{};return i(r(Un(e,1,Object.assign({},n,a,t))[0]))},mapToCurve(e){if(n.m===1){if(typeof e!=`bigint`)throw Error(`expected bigint (m=1)`);return i(r([e]))}if(!Array.isArray(e))throw Error(`expected array of bigints`);for(let t of e)if(typeof t!=`bigint`)throw Error(`expected array of bigints`);return i(r(e))},hashToScalar(t,r){let i=e.Fn.ORDER;return Un(t,1,Object.assign({},n,{p:i,m:1,DST:Wn},r))[0][0]}}}function Kn(e){Nt(e,{name:`string`,hash:`function`,hashToScalar:`function`,hashToGroup:`function`});let{name:t,Point:n,hash:r}=e,{Fn:i}=n,a=(t,n)=>e.hashToGroup(t,{DST:M(Dt(`HashToGroup-`),n)}),o=(t,n)=>e.hashToScalar(t,{DST:M(Wn,n)}),s=(e=k)=>{let t=dn(e(un(i.ORDER)),i.ORDER,i.isLE);return i.isLE?St(t):xt(t)},c=(e,t)=>En(n,e,t),l=e=>M(Dt(`OPRFV1-`),new Uint8Array([e]),Dt(`-`+t)),u=l(0),d=l(1),f=l(2);function p(...e){let t=[];for(let n of e)typeof n==`number`?t.push(Ct(n,2)):typeof n==`string`?t.push(Dt(n)):(C(n),t.push(Ct(n.length,2),n));return M(...t)}let m=(...e)=>r(p(...e,`Finalize`));function h(e,t,n,i){let a=r(p(e.toBytes(),M(Dt(`Seed-`),i))),s=[];for(let e=0;e<t.length;e++){let r=t[e].toBytes(),c=n[e].toBytes(),l=o(p(a,e,r,c,`Composite`),i);s.push(l)}return s}function g(e,t,n,r){let i=h(e,t,n,r);return{M:c(t,i),Z:c(n,i)}}function _(e,t,n,r,i){let a=c(n,h(t,n,r,i));return{M:a,Z:a.multiply(e)}}function v(e,t,n,r,i,a){let[s,c,l,u,d]=[e,t,n,r,i].map(e=>e.toBytes());return o(p(s,c,l,u,d,`Challenge`),a)}function y(e,t,r,a,o,c){let{M:l,Z:u}=_(t,r,a,o,e),d=s(c),f=v(r,l,u,n.BASE.multiply(d),l.multiply(d),e);return M(...[f,i.sub(d,i.mul(f,t))].map(e=>i.toBytes(e)))}function b(e,t,r,a,o){C(o,2*i.BYTES);let{M:s,Z:c}=g(t,r,a,e),[l,u]=[o.subarray(0,i.BYTES),o.subarray(i.BYTES)].map(e=>i.fromBytes(e)),d=v(t,s,c,n.BASE.multiply(u).add(t.multiply(l)),s.multiply(u).add(c.multiply(l)),e);if(!i.eql(l,d))throw Error(`proof verification failed`)}function x(){let e=s(),t=n.BASE.multiply(e);return{secretKey:i.toBytes(e),publicKey:t.toBytes()}}function S(t,r,a){let o=M(Dt(`DeriveKeyPair`),t),s=M(r,p(a),Uint8Array.of(0));for(let t=0;t<=255;t++){s[s.length-1]=t;let r=e.hashToScalar(s,{DST:o});if(!i.is0(r))return{secretKey:i.toBytes(r),publicKey:n.BASE.multiply(r).toBytes()}}throw Error(`Cannot derive key`)}function w(e,t,r=k){let o=s(r),c=a(t,e);if(c.equals(n.ZERO))throw Error(`Input point at infinity`);let l=c.multiply(o);return{blind:i.toBytes(o),blinded:l.toBytes()}}function T(e,t,r){let o=i.fromBytes(t),s=a(r,e);if(s.equals(n.ZERO))throw Error(`Input point at infinity`);return m(r,s.multiply(o).toBytes())}let E={generateKeyPair:x,deriveKeyPair:(e,t)=>S(u,e,t),blind:(e,t=k)=>w(u,e,t),blindEvaluate(e,t){let r=i.fromBytes(e);return n.fromBytes(t).multiply(r).toBytes()},finalize(e,t,r){let a=i.fromBytes(t);return m(e,n.fromBytes(r).multiply(i.inv(a)).toBytes())},evaluate:(e,t)=>T(u,e,t)};return Object.freeze({name:t,oprf:E,voprf:{generateKeyPair:x,deriveKeyPair:(e,t)=>S(d,e,t),blind:(e,t=k)=>w(d,e,t),blindEvaluateBatch(e,t,r,a=k){if(!Array.isArray(r))throw Error(`expected array`);let o=i.fromBytes(e),s=n.fromBytes(t),c=r.map(n.fromBytes),l=c.map(e=>e.multiply(o)),u=y(d,o,s,c,l,a);return{evaluated:l.map(e=>e.toBytes()),proof:u}},blindEvaluate(e,t,n,r=k){let i=this.blindEvaluateBatch(e,t,[n],r);return{evaluated:i.evaluated[0],proof:i.proof}},finalizeBatch(e,t,r){if(!Array.isArray(e))throw Error(`expected array`);return b(d,n.fromBytes(t),e.map(e=>e.blinded).map(n.fromBytes),e.map(e=>e.evaluated).map(n.fromBytes),r),e.map(e=>E.finalize(e.input,e.blind,e.evaluated))},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate:(e,t)=>T(d,e,t)},poprf:e=>{let t=o(p(`Info`,e),f),r=n.BASE.multiply(t);return{generateKeyPair:x,deriveKeyPair:(e,t)=>S(f,e,t),blind(e,t,o=k){let c=n.fromBytes(t),l=r.add(c);if(l.equals(n.ZERO))throw Error(`tweakedKey point at infinity`);let u=s(o),d=a(e,f);if(d.equals(n.ZERO))throw Error(`Input point at infinity`);let p=d.multiply(u);return{blind:i.toBytes(u),blinded:p.toBytes(),tweakedKey:l.toBytes()}},blindEvaluateBatch(e,r,a=k){if(!Array.isArray(r))throw Error(`expected array`);let o=i.fromBytes(e),s=i.add(o,t),c=i.inv(s),l=r.map(n.fromBytes),u=l.map(e=>e.multiply(c)),d=y(f,s,n.BASE.multiply(s),u,l,a);return{evaluated:u.map(e=>e.toBytes()),proof:d}},blindEvaluate(e,t,n=k){let r=this.blindEvaluateBatch(e,[t],n);return{evaluated:r.evaluated[0],proof:r.proof}},finalizeBatch(t,r,a){if(!Array.isArray(t))throw Error(`expected array`);let o=t.map(e=>e.evaluated).map(n.fromBytes);return b(f,n.fromBytes(a),o,t.map(e=>e.blinded).map(n.fromBytes),r),t.map((t,n)=>{let r=i.fromBytes(t.blind),a=o[n].multiply(i.inv(r)).toBytes();return m(t.input,e,a)})},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate(r,o){let s=i.fromBytes(r),c=a(o,f);if(c.equals(n.ZERO))throw Error(`Input point at infinity`);let l=i.add(s,t),u=i.inv(l);return m(o,e,c.multiply(u).toBytes())}}},__tests:{Fn:i}})}var qn=BigInt(0),Jn=BigInt(1),Yn=BigInt(2),Xn=BigInt(3),Zn=BigInt(5),Qn=BigInt(8),$n=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),er={p:$n,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:Qn,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function tr(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=$n,o=e*e%a*e%a,s=Wt(Wt(o,Yn,a)*o%a,Jn,a)*e%a,c=Wt(s,Zn,a)*s%a,l=Wt(c,t,a)*c%a,u=Wt(l,n,a)*l%a,d=Wt(u,r,a)*u%a;return{pow_p_5_8:Wt(Wt(Wt(Wt(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,Yn,a)*e%a,b2:o}}function nr(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var rr=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function ir(e,t){let n=$n,r=z(t*t*t,n),i=tr(e*z(r*r*t,n)).pow_p_5_8,a=z(e*r*i,n),o=z(t*a*a,n),s=a,c=z(a*rr,n),l=o===e,u=o===z(-e,n),d=o===z(-e*rr,n);return l&&(a=s),(u||d)&&(a=c),Qt(a,n)&&(a=z(-a,n)),{isValid:l||u,value:a}}var ar=Pn(er,{uvRatio:ir}),V=ar.Fp,or=ar.Fn;function sr(e){return In(ar,j,Object.assign({adjustScalarBytes:nr},e))}var cr=sr({}),lr=($n+Xn)/Qn,ur=V.pow(Yn,lr),dr=V.sqrt(V.neg(V.ONE));function fr(e){let t=($n-Zn)/Qn,n=BigInt(486662),r=V.sqr(e);r=V.mul(r,Yn);let i=V.add(r,V.ONE),a=V.neg(n),o=V.sqr(i),s=V.mul(o,i),c=V.mul(r,n);c=V.mul(c,a),c=V.add(c,o),c=V.mul(c,a);let l=V.sqr(s);o=V.sqr(l),l=V.mul(l,s),l=V.mul(l,c),o=V.mul(o,l);let u=V.pow(o,t);u=V.mul(u,l);let d=V.mul(u,dr);o=V.sqr(u),o=V.mul(o,s);let f=V.eql(o,c),p=V.cmov(d,u,f),m=V.mul(a,r),h=V.mul(u,e);h=V.mul(h,ur);let g=V.mul(h,dr),_=V.mul(c,r);o=V.sqr(h),o=V.mul(o,s);let v=V.eql(o,_),y=V.cmov(g,h,v);o=V.sqr(p),o=V.mul(o,s);let b=V.eql(o,c),x=V.cmov(m,a,b),S=V.cmov(y,p,b),C=V.isOdd(S);return S=V.cmov(S,V.neg(S),b!==C),{xMn:x,xMd:i,yMn:S,yMd:Jn}}var pr=cn(V,V.neg(BigInt(486664)));function mr(e){let{xMn:t,xMd:n,yMn:r,yMd:i}=fr(e),a=V.mul(t,i);a=V.mul(a,pr);let o=V.mul(n,r),s=V.sub(t,n),c=V.add(t,n),l=V.mul(o,c),u=V.eql(l,V.ZERO);a=V.cmov(a,V.ZERO,u),o=V.cmov(o,V.ONE,u),s=V.cmov(s,V.ONE,u),c=V.cmov(c,V.ONE,u);let[d,f]=nn(V,[o,c],!0);return{x:V.mul(a,d),y:V.mul(s,f)}}Gn(ar,e=>mr(e[0]),{DST:`edwards25519_XMD:SHA-512_ELL2_RO_`,encodeDST:`edwards25519_XMD:SHA-512_ELL2_NU_`,p:$n,m:1,k:128,expand:`xmd`,hash:j});var hr=rr,gr=BigInt(`25063068953384623474111414158702152701244531502492656460079210482610430750235`),_r=BigInt(`54469307008909316920995813868745141605393597292927456921205312896311721017578`),vr=BigInt(`1159843021668779879193775521855586647937357759715417654439879720876111806838`),yr=BigInt(`40440834346308536858101042469323190826248399146238708352240133220865137265952`),br=e=>ir(Jn,e),xr=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),Sr=e=>V.create(St(e)&xr);function Cr(e){let{d:t}=er,n=$n,r=e=>V.create(e),i=r(hr*e*e),a=r((i+Jn)*vr),o=BigInt(-1),s=r((o-t*i)*r(i+t)),{isValid:c,value:l}=ir(a,s),u=r(l*e);Qt(u,n)||(u=r(-u)),c||(l=u),c||(o=i);let d=r(o*(i-Jn)*yr-s),f=l*l,p=r((l+l)*s),m=r(d*gr),h=r(Jn-f),g=r(Jn+f);return new ar(r(p*g),r(h*m),r(m*g),r(p*h))}var wr=class e extends Fn{static BASE=new e(ar.BASE);static ZERO=new e(ar.ZERO);static Fp=V;static Fn=or;constructor(e){super(e)}static fromAffine(t){return new e(ar.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw Error(`RistrettoPoint expected`)}init(t){return new e(t)}static fromBytes(t){C(t,32);let{a:n,d:r}=er,i=$n,a=e=>V.create(e),o=Sr(t);if(!Tt(V.toBytes(o),t)||Qt(o,i))throw Error(`invalid ristretto255 encoding 1`);let s=a(o*o),c=a(Jn+n*s),l=a(Jn-n*s),u=a(c*c),d=a(l*l),f=a(n*r*u-d),{isValid:p,value:m}=br(a(f*d)),h=a(m*l),g=a(m*h*f),_=a((o+o)*h);Qt(_,i)&&(_=a(-_));let v=a(c*g),y=a(_*v);if(!p||Qt(y,i)||v===qn)throw Error(`invalid ristretto255 encoding 2`);return new e(new ar(_,v,Jn,y))}static fromHex(t){return e.fromBytes(_e(t))}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=$n,a=e=>V.create(e),o=a(a(n+t)*a(n-t)),s=a(e*t),{value:c}=br(a(o*a(s*s))),l=a(c*o),u=a(c*s),d=a(l*u*r),f;if(Qt(r*d,i)){let n=a(t*hr),r=a(e*hr);e=n,t=r,f=a(l*_r)}else f=u;Qt(e*d,i)&&(t=a(-t));let p=a((n-t)*f);return Qt(p,i)&&(p=a(-p)),V.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>V.create(e),o=a(t*i)===a(n*r),s=a(n*i)===a(t*r);return o||s}is0(){return this.equals(e.ZERO)}},Tr={Point:wr,hashToCurve(e,t){let n=Vn(e,t?.DST||`ristretto255_XMD:SHA-512_R255MAP_RO_`,64,j);return Tr.deriveToCurve(n)},hashToScalar(e,t={DST:Wn}){let n=Vn(e,t.DST,64,j);return or.create(St(n))},deriveToCurve(e){C(e,64);let t=Cr(Sr(e.subarray(0,32))),n=Cr(Sr(e.subarray(32,64)));return new wr(t.add(n))}};Kn({name:`ristretto255-SHA512`,Point:wr,hash:j,hashToGroup:Tr.hashToCurve,hashToScalar:Tr.hashToScalar});var Er=`urn:jazz:local-first`,Dr=`jazz-auth-sign-v1`,Or=fe(`jazz-auth-key-v1`),kr=3600,Ar=class extends Error{constructor(e){super(e),this.name=`LocalFirstTokenError`}};function jr(e,t){let n=new Uint8Array(e.length+t.length);n.set(e),n.set(t,e.length);let r=h(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,_(r)}var Mr=Uint8Array.from([107,167,184,16,157,173,17,209,128,180,0,192,79,212,48,200]),Nr=[/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i,/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/i,/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i,/^urn:uuid:([0-9a-fA-F]{8})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{4})-([0-9a-fA-F]{12})$/];function Pr(e){if(typeof e!=`string`||e.length===0)throw TypeError(`audience must be a non-empty string`);for(let t of Nr){let n=t.exec(e);if(n)return n.slice(1).join(`-`).toLowerCase()}return jr(Mr,fe(e))}function Fr(e){let t=a(e),n=fe(Dr),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),j(r).slice(0,32)}function Ir(e){return jr(Or,e)}var Lr=()=>Math.floor(Date.now()/1e3);function Rr(e,t){let n=Pr(t.audience),r=t.ttlSeconds??kr;if(!Number.isSafeInteger(r)||r<=0)throw new Ar(`ttlSeconds must be a positive integer`);let i=t.now??Lr();if(!Number.isSafeInteger(i)||i<0)throw new Ar(`now must be a non-negative integer`);let a=Fr(e),o=cr.getPublicKey(a),s=me(fe(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=me(fe(JSON.stringify({iss:Er,sub:Ir(o),aud:n,jazz_pub_key:me(o),iat:i,exp:i+r})));return`${s}.${c}.${me(cr.sign(fe(`${s}.${c}`),a))}`}function H(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Br(e.serverUrl):zr)}var zr=`local`;function Br(e){let n;try{n=new t(et(e.trim()))}catch{throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`)}if(n.protocol===`ws:`&&(n.protocol=`http:`),n.protocol===`wss:`&&(n.protocol=`https:`),n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`);return`${n.origin}${n.pathname.replace(/\/+$/,``)}`}function Vr(){return import.meta.url}function Hr(){let e=import.meta.url;return new URL(`../worker/jazz-broker-worker.js`,e).href}function Ur(){return null}function Wr(){return null}function Gr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`}function Kr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`blob:`}function qr(e){return new URL(`/`,e).href}function Jr(e,t){try{return new URL(e).href}catch{}if(t)try{return new URL(e,t).href}catch{}return e}function Yr(e,t){if(!t?.wasmVersion)return e;try{let n=new URL(e);return n.searchParams.set(`jazz-runtime-version`,t.wasmVersion),n.href}catch{return e}}function Xr(e,t){try{return new URL(e).href}catch{}return t?new URL(e,t).href:null}function Zr(e,t,n){return!t||Gr(e)||!n&&Kr(t)?null:new URL(`jazz_wasm_bg.wasm`,qr(t)).href}function Qr(e){return e?.wasmModule?{module:e.wasmModule}:e?.wasmSource?{module:e.wasmSource}:null}function $r(e,t,n){if(n?.wasmUrl)return Yr(Jr(n.wasmUrl,t),n);if(n?.baseUrl){let e=Xr(n.baseUrl,t);if(e)return Yr(new URL(`jazz_wasm_bg.wasm`,e).href,n)}return Zr(typeof e==`function`?e():e,t,!1)}function ei(e,t,n){if(n?.brokerWorkerUrl)return Yr(Jr(n.brokerWorkerUrl,t),n);if(n?.baseUrl){let e=Xr(n.baseUrl,t);if(e)return Yr(new URL(`worker/jazz-broker-worker.js`,e).href,n)}return!t||Gr(e)?Yr(new URL(`../worker/jazz-broker-worker.js`,e).href,n):Yr(new URL(`worker/jazz-broker-worker.js`,qr(t)).href,n)}function ti(){let e=typeof process<`u`;return ni(e?{}.VITE_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.NEXT_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(e?{}.EXPO_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??ni(void 0)}function ni(e){return e?.trim()||void 0}var ri=new WeakMap,ii=256,ai=5e3,oi=1,si={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17};function ci(e,t){let n=e.trim().replace(/\/+$/,``),r=`/v1/${t}`;return n.endsWith(`/v1/logs`)?`${n.slice(0,-8)}${r}`:n.endsWith(`/v1/traces`)?`${n.slice(0,-10)}${r}`:`${n}${r}`}function li(e){if(!e.collectorUrl)return()=>void 0;let t={traceUrl:ci(e.collectorUrl,`traces`),logUrl:ci(e.collectorUrl,`logs`)},{runtimeThread:n,wasmModule:r}=e;if(!pi(r))return console.warn(`[jazz] WASM telemetry unavailable: trace entry hooks are missing.`),()=>void 0;let i=ri.get(r);if(i){if(i.closing)throw Error(`WASM telemetry collector is closing`);if(i.runtimeThread!==n)throw Error(`incompatible WASM telemetry runtime thread`);if(i.identity.traceUrl!==t.traceUrl||i.identity.logUrl!==t.logUrl)throw Error(`incompatible WASM telemetry collector`);return ui(r,i)}i={identity:t,runtimeThread:n,leases:new Set,nextLeaseId:0,closing:!1,unsubscribe:null,exporter:null,exportTail:Promise.resolve(),shutdownScheduled:!1,drainMicrotaskPending:!1},ri.set(r,i);let a=()=>{let e=r.drainTraceEntries();!Array.isArray(e)||e.length===0||di(i,e)},o=()=>{i.closing||i.drainMicrotaskPending||(i.drainMicrotaskPending=!0,queueMicrotask(()=>{i.drainMicrotaskPending=!1,!i.closing&&a()}))},s=!1;try{return i.unsubscribe=r.subscribeTraceEntries(o),s=!0,r.setTraceEntryCollectionEnabled(!0),ui(r,i)}catch(e){if(s)try{r.setTraceEntryCollectionEnabled(!1)}catch{}try{i.unsubscribe?.()}catch{}throw i.unsubscribe=null,ri.get(r)===i&&ri.delete(r),e}}function ui(e,t){let n=t.nextLeaseId++;t.leases.add(n);let r=!1;return()=>{if(r||(r=!0,t.leases.delete(n),t.leases.size>0||t.closing))return;t.closing=!0;let i;try{t.unsubscribe?.()}catch(e){i=e}finally{try{let n=e.drainTraceEntries();Array.isArray(n)&&n.length>0&&di(t,n)}catch(e){i??=e}finally{try{e.setTraceEntryCollectionEnabled(!1)}catch(e){i??=e}finally{t.unsubscribe=null,fi(t),!i&&ri.get(e)===t&&ri.delete(e)}}}if(i)throw i}}function di(e,t){e.exportTail=e.exportTail.catch(()=>void 0).then(async()=>{e.exporter||=hi(e.identity.traceUrl,e.identity.logUrl);try{let n=await e.exporter;for(let r of t)try{mi(n,e.runtimeThread,r)}catch(e){console.warn(`[jazz] WASM telemetry export failed:`,e)}}catch(t){e.exporter=null,console.warn(`[jazz] WASM telemetry export failed:`,t)}})}function fi(e){e.shutdownScheduled||(e.shutdownScheduled=!0,e.exportTail.catch(()=>void 0).then(async()=>{try{await(e.exporter?await e.exporter:void 0)?.shutdown()}catch(e){console.warn(`[jazz] WASM telemetry shutdown failed:`,e)}}))}function pi(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.subscribeTraceEntries==`function`&&typeof t.drainTraceEntries==`function`&&typeof t.setTraceEntryCollectionEnabled==`function`}function mi(e,t,n){if(n.kind===`span`){let r={"jazz.runtime_thread":t,"jazz.span.sequence":n.sequence,"jazz.span.level":n.level,"jazz.span.target":n.target,"jazz.span.fields":yi(n.fields)};e.tracer.startSpan(n.name||`wasm span`,{kind:oi,startTime:n.startUnixNano,attributes:vi(n.fields)?{...gi(n.fields),...r}:r}).end(n.endUnixNano);return}if(n.kind===`log`){let r={"jazz.runtime_thread":t,"jazz.log.sequence":n.sequence,"jazz.log.target":n.target,"jazz.log.fields":yi(n.fields)};e.logger.emit({timestamp:n.timestampUnixNano,severityNumber:_i(n.level),severityText:n.level,body:n.message,attributes:vi(n.fields)?{...gi(n.fields),...r}:r});return}e.logger.emit({severityNumber:si.WARN,severityText:`WARN`,body:`Dropped ${n.count} WASM telemetry records`,attributes:{"jazz.runtime_thread":t,"jazz.telemetry.dropped_count":n.count}})}async function hi(t,n){let[{OTLPTraceExporter:r},{BasicTracerProvider:i,BatchSpanProcessor:a},{OTLPLogExporter:o},{LoggerProvider:s,BatchLogRecordProcessor:c},{resourceFromAttributes:l}]=await Promise.all([e(()=>import(`./esm-D_R-EGgt.js`),__vite__mapDeps([0,1,2]),import.meta.url),e(()=>import(`./esm-DEBYi0LL.js`),__vite__mapDeps([3,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-WihpI9g6.js`),__vite__mapDeps([8,1,2]),import.meta.url),e(()=>import(`./esm-DT3MY99S.js`),__vite__mapDeps([9,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-D-TBoHij.js`).then(e=>e.t),__vite__mapDeps([5,6,7,1]),import.meta.url)]),u=l({"service.name":`jazz-browser`,"telemetry.sdk.language":`webjs`}),d={maxExportBatchSize:ii,maxQueueSize:ai,scheduledDelayMillis:1e3},f=new i({resource:u,spanProcessors:[new a(new r({url:t}),d)]}),p=new s({resource:u,processors:[new c(new o({url:n}),d)]});return{tracer:f.getTracer(`jazz-wasm.tracing`),logger:p.getLogger(`jazz-wasm.tracing`),shutdown:async()=>{await Promise.all([typeof f.shutdown==`function`?f.shutdown():void 0,typeof p.shutdown==`function`?p.shutdown():void 0])}}}function gi(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))n.startsWith(`jazz.`)||r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t[n]=r:t[n]=JSON.stringify(r));return t}function _i(e){switch(e.toUpperCase()){case`TRACE`:return si.TRACE;case`DEBUG`:return si.DEBUG;case`INFO`:return si.INFO;case`WARN`:case`WARNING`:return si.WARN;case`ERROR`:return si.ERROR;default:return 0}}function vi(e){if(!e)return!1;for(let t in e)return!0;return!1}function yi(e){return vi(e)?JSON.stringify(e):`{}`}var bi=`jazz-shared-runtime-v2`,xi=`idbtree-v1`,Si=new WeakMap;function Ci(e){if(e?.brokerWorkerUrl||e?.baseUrl)return ei(Vr(),typeof location<`u`?location.href:void 0,e);let t=Di(Vr());return t?e?.wasmVersion?`${t}&jazz-runtime-version=${encodeURIComponent(e.wasmVersion)}`:t:Yr(Jr(Hr(),typeof location<`u`?location.href:void 0),e)}var wi=/^(.*?\/)node_modules\/\.vite\/(?:.*\/)?deps(?:_[^/]*)?\/[^/]+$/,Ti=`worker_file&type=module`,Ei=`jazz-tools/_worker/broker`;function Di(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`http:`&&t.protocol!==`https:`)return;let n=wi.exec(t.pathname);return n?`${t.origin}${n[1]}@id/${Ei}?${Ti}`:void 0}function Oi(e){if(!e)return ki(e);if((e.baseUrl||e.wasmUrl&&!Ai(e.wasmUrl)||e.brokerWorkerUrl)&&!e.wasmVersion)throw Error(`Configured browser runtime assets require runtimeSources.wasmVersion. Use an immutable build version that changes whenever the WASM or worker bytes change.`);let t=Mi(e);if(t)return{...e,workerWasmAssetIdentity:t};let n=$r(Vr(),typeof location<`u`?location.href:void 0,e);return n?{...e,wasmUrl:n}:ki(e)}function ki(e){let t=Ur();return t?{...e,wasmUrl:t}:e}function Ai(e){return e===Ur()}function ji(e){let t=Oi(e);return JSON.stringify({protocolVersion:bi,workerUrl:Ci(t),wasmAsset:Ni(t)})}function Mi(e){let[t,n]=e.wasmModule?[e.wasmModule,`module`]:e.wasmSource?[e.wasmSource,`source`]:[];if(!t||!n)return;let r=Si.get(t);return r||(r=`${n}:${crypto.randomUUID()}`,Si.set(t,r)),r}function Ni(e){return e?.wasmModule?`module:${e.workerWasmAssetIdentity??`unscoped`}`:e?.wasmSource?`source:${e.workerWasmAssetIdentity??`unscoped`}`:`url:${e?.wasmUrl??`worker-local`}`}function Pi(e,t,n){let r=e.telemetryCollectorUrl?.trim()||void 0;return JSON.stringify({protocolVersion:bi,storageFormatVersion:xi,appId:H(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Hi(e),workerUrl:Ci(e.runtimeSources),workerAssetScope:ji(e.runtimeSources),telemetryCollector:r?{traceUrl:ci(r,`traces`),logUrl:ci(r,`logs`)}:void 0,wasmLogLevel:e.logLevel??`warn`})}function Fi(e){if(e.adminSecret)return{kind:`system`};let t=rt({appId:H(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:A(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:t.authMode,user:ze(t.issuer,t.user_id,t.account_id)}}function Ii(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Li(e)}:Fi(e)}function Li(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function Ri(e){return JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Fi(e),...e.accountId?{registry:Li(e)}:{}})}function zi(e){return JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Ii(e)})}function Bi(e,t){if(zi(e)!==zi(t)||Ri(e)!==Ri(t))throw Error(`Cannot change the authenticated user of a live persistent browser Db; shut it down and reopen for the new user, or explicitly reset its storage`)}function Vi(e,t){let n=JSON.stringify({version:1,appId:H(e),env:e.env??`dev`,auth:Ii(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Hi(e){if(e.adminSecret)return`admin`;let t=rt({appId:H(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:A(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${t.authMode}:${ze(t.issuer,t.user_id,t.account_id)}`}var Ui=`Jazz's local-first client needs its Metro setup on Expo web: wrap your Metro config in withJazz from jazz-tools/expo/metro (module.exports = withJazz(getDefaultConfig(__dirname))) and restart Metro with --clear.`,Wi=` Under Metro (Expo web), Jazz's worker is the Expo worker chunk withJazz from jazz-tools/expo/metro builds: check that metro.config.js wraps getDefaultConfig from expo/metro-config in withJazz, restart Metro with --clear, and leave runtimeSources.brokerWorkerUrl unset (a URL set there is started as a module script, not as Metro's chunk).`;function Gi(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var Ki=class{transport;onError;timer;deadline;closed=!1;constructor(e,t){this.transport=e,this.onError=t}refresh(){if(!this.closed)try{let e=this.transport.auxiliaryReceiveTimeoutMs?.();if(e==null){this.clear();return}if(!Number.isFinite(e)||e<0||!this.transport.expireAuxiliaryReceive)throw Error(`Invalid auxiliary receive deadline capability`);let t=performance.now()+e;if(this.deadline!==void 0&&this.deadline<=t)return;this.clear(),this.deadline=t,this.timer=setTimeout(()=>{if(this.timer=void 0,this.deadline=void 0,!this.closed)try{this.transport.expireAuxiliaryReceive(),this.refresh()}catch(e){this.fail(e)}},e)}catch(e){this.fail(e)}}close(){this.closed=!0,this.clear()}clear(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0,this.deadline=void 0}fail(e){this.close(),this.onError(e)}},qi=1024*1024,Ji=class{runtime;transport;sendFrames;onError;onAuxiliaryTrace;receiveDeadline;scheduled=!1;running=!1;runAgain=!1;closed=!1;outboundDrainScheduled=!1;inboundRouting=Promise.resolve();requestedGeneration=0;completedGeneration=0;flushWaiters=new Set;removeWorkListener;handleRuntimeWork=e=>this.schedule(e??!1);constructor(e,t,n,r,i){this.runtime=e,this.transport=t,this.sendFrames=n,this.onError=r,this.onAuxiliaryTrace=i,this.receiveDeadline=new Ki(t,e=>{this.close(),this.onError(e)}),this.removeWorkListener=e.onPeerTransportWork(this.handleRuntimeWork);try{this.transport.setAuxiliaryTraceEnabled?.(i!==void 0),this.transport.setOutboundScheduler?.(()=>this.scheduleOutboundDrain())}catch(e){this.closed=!0;try{this.removeWorkListener()}finally{try{this.transport.clearOutboundScheduler?.()}finally{this.transport.setAuxiliaryTraceEnabled?.(!1)}}throw e}this.watchAuxiliaryOutbound().catch(e=>{this.closed||this.onError(e)}),this.schedule(!0)}receive(e){this.closed||e.length===0||(this.inboundRouting=this.inboundRouting.then(()=>this.routeInboundFrames(e)).catch(e=>{this.closed||this.onError(e)}))}schedule(e=!0){if(!this.closed){if(this.requestedGeneration+=1,this.running){this.runAgain||=e;return}this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.pump().catch(e=>{this.closed||this.onError(e)})}))}}close(){if(!this.closed){this.closed=!0,this.receiveDeadline.close(),this.removeWorkListener(),this.transport.clearOutboundScheduler?.(),this.transport.setAuxiliaryTraceEnabled?.(!1),this.runtime.retirePeerTransport(this.transport).catch(this.onError);for(let e of this.flushWaiters)e.resolve();this.flushWaiters.clear()}}async flush(){if(this.closed)return;this.schedule();let e=this.requestedGeneration;this.completedGeneration>=e||await new Promise(t=>this.flushWaiters.add({target:e,resolve:t}))}drainOutboundFrames(){if(this.closed)return!1;let e=Xi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=Xi(t.call(this.transport,8,qi));return n.length>0&&this.sendFrames(n),this.publishAuxiliaryTrace(),n.length>0}scheduleOutboundDrain(){this.closed||this.outboundDrainScheduled||(this.outboundDrainScheduled=!0,queueMicrotask(()=>{this.outboundDrainScheduled=!1,this.closed||this.drainOutboundFrames()}))}async pump(){if(this.closed||this.running)return;this.running=!0;let e=this.requestedGeneration;try{if(this.drainOutboundFrames(),await this.runtime.progressPeerTransport(),this.closed)return;this.drainOutboundFrames()}finally{this.running=!1,this.completedGeneration=Math.max(this.completedGeneration,e);for(let e of this.flushWaiters)e.target>this.completedGeneration||(this.flushWaiters.delete(e),e.resolve())}this.closed||this.runAgain&&(this.runAgain=!1,this.schedule())}async routeInboundFrames(e){if(this.closed)return;let t=[];for(let n of e){let e=this.transport.routeAuxiliaryWireFrame?await this.transport.routeAuxiliaryWireFrame(n):n;if(this.receiveDeadline.refresh(),this.closed)return;e!=null&&t.push(Zi(e))}if(!this.closed){if(t.length>0)if(this.transport.sendWireFrames)this.transport.sendWireFrames(t);else for(let e of t)this.transport.sendWireFrame(e);this.runtime.notifyPeerTransportActivity?.(),this.publishAuxiliaryTrace(),this.schedule()}}publishAuxiliaryTrace(){if(!this.onAuxiliaryTrace)return;let e=this.transport.takeAuxiliaryTrace?.();!e||e.length===0||this.onAuxiliaryTrace(e)}async watchAuxiliaryOutbound(){for(;!this.closed;){let e=this.transport.auxiliaryOutboundReady?.();if(!e||typeof e==`boolean`||(await e,this.closed))return;this.drainOutboundFrames()&&await Qi()}}};function Yi(e){return e.map(e=>e.slice())}function Xi(e){return e.map(Zi)}function Zi(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`Browser worker transport received a non-binary wire frame`)}function Qi(){return new Promise(e=>setTimeout(e,0))}var $i=new WeakMap;function ea(e,t){let n=$i.get(e);if(!n||n.databaseName!==t||!n.active()||n.claimed)throw Error(`IndexedDB reclamation requires an unclaimed live database Web Lock`);return n.claimed=!0,n.active}var ta=`jazz-idb-tree`,na=`pages`,ra=`metadata`,U=`storage-manifest`,ia=`epoch`,aa=`browser-runtime-owner`,oa=`browser-worker-epoch-v1`,sa=`jazz-browser-worker-epoch-v1`,ca=`replica-node-v1`,la=`foreground-node-leases-v1`,ua=`jazz-foreground-node-leases-v1`,da=(1n<<64n)-1n,fa=`current`,pa=1024,ma=2147483648,ha={storageEpoch:1,adapterId:`jazz-idb-tree`,adapterFormatVersion:1,requiredCodecIds:[`jazz.sqlite-storage.v1`],pageSize:16*1024,pageChecksum:`xxh3-64-le`,pageFormatMagic:`IDBTREE\0`,pageFormatVersion:1},ga=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},_a=class extends Error{code=`storage`;constructor(e){super(`browser storage: could not write to IndexedDB (QuotaExceededError); the browser may be out of storage space for this site`,{cause:e}),this.name=`IndexedDbStorageFullError`}};function va(e,t){return e?.name===`QuotaExceededError`?new _a(e):e??Error(t)}var ya=class e{db;name;invalidated=!1;reclamationOwnership=null;treeClaims=new Set;nextTreeToken=0;treeTransactions=new Set;ownershipRevision=0;claimTreeOwnership(){if(this.assertValid(),this.reclamationOwnership&&(this.treeClaims.size>0||this.treeTransactions.size>0))throw Error(`IndexedDB reclamation owner already has a tree or pending transaction`);if(this.nextTreeToken===2**53-1)throw Error(`IndexedDB tree token space exhausted`);let e=++this.nextTreeToken;return this.treeClaims.add(e),e}releaseTreeOwnership(e){this.treeClaims.delete(e)}isTreeOwnershipActive(e){return!this.invalidated&&this.treeClaims.has(e)&&(this.reclamationOwnership===null||this.reclamationOwnership())}async retireTreeOwnership(){this.treeClaims.clear(),await Promise.allSettled(this.treeTransactions)}get canReclaimObsoletePages(){return!this.invalidated&&this.treeClaims.size===1&&this.reclamationOwnership?.()===!0}replicaNodeBytes=null;invalidationListeners=new Set;constructor(e,t,n){this.db=e,this.name=t,n&&this.invalidationListeners.add(n),e.addEventListener(`versionchange`,this.handleVersionChange),e.addEventListener(`close`,this.handleUnexpectedClose)}onInvalidated(e){return this.invalidationListeners.add(e),()=>this.invalidationListeners.delete(e)}static async open(t,n={}){let r=indexedDB.open(t,3),i=!1;r.onupgradeneeded=e=>{if(e.oldVersion!==0){i=!0,r.result.close(),r.transaction?.abort();return}let t=r.result;if(t.objectStoreNames.contains(`pages`)||t.createObjectStore(na),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(ra),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(U);r.transaction&&(e.put(ha,ia),e.put(xa().buffer,ca))}};let a;try{a=await W(r)}catch(e){throw i?Error(`Missing or invalid IndexedDB storage epoch manifest`):e}let o=new e(a,t,n.onInvalidated);try{return await o.assertStorageManifest(),n.owner&&await o.claimBrowserRuntimeOwner(n.owner),o.replicaNodeBytes=await o.readReplicaNodeBytes(),o}catch(e){throw o.close(),e}}get replicaNode(){if(!this.replicaNodeBytes)throw Error(`IndexedDB replica node is unavailable before storage admission`);return this.replicaNodeBytes.slice()}async acquireForegroundNodeLease(e=!1){return await this.updateForegroundNodeLeasePool(t=>{if(e){for(let e of t.active)t.retired.push(e.node);t.active=[]}let n=t.reusable.pop(),r={leaseId:crypto.randomUUID(),node:n?.node??Sa(xa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),wa(r)})}async returnForegroundNodeLease(e,t){if(!Aa(e)||!Na(t))throw Error(`Invalid IndexedDB foreground node lease handoff`);await this.updateForegroundNodeLeasePool(n=>{let r=n.active.findIndex(t=>t.leaseId===e);if(r<0)throw Error(`Unknown IndexedDB foreground node lease`);let[i]=n.active.splice(r,1);if(!i)throw Error(`Unknown IndexedDB foreground node lease`);let a=BigInt(i.confirmedTxTime);n.reusable.push({...i,confirmedTxTime:(t>a?t:a).toString()})})}async retireForegroundNodeLease(e){if(!Aa(e))throw Error(`Invalid IndexedDB foreground node lease`);await this.updateForegroundNodeLeasePool(t=>{let n=t.active.findIndex(t=>t.leaseId===e);if(n<0)return;let[r]=t.active.splice(n,1);r&&t.retired.push(r.node)})}async foregroundNodeLeaseNodeState(e){if(e.byteLength!==16)throw Error(`Invalid IndexedDB foreground node identity`);this.assertValid();let t=this.db.transaction(U,`readonly`),n=Ia(t);try{let r=await W(t.objectStore(U).get(la));if(await n,r===void 0)return`missing`;let i=Ta(r),a=Pa(Sa(e));return i.active.some(e=>Pa(e.node)===a)?`active`:i.reusable.some(e=>Pa(e.node)===a)?`reusable`:i.retired.some(e=>Pa(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!ja(e))throw Error(`Invalid browser worker epoch`);if(this.assertValid(),t&&(t.id!==e||this.treeClaims.size>0))throw Error(`IndexedDB reclamation ownership must precede tree construction`);let n=this.ownershipRevision,r=t?ea(t,this.name):null,i=this.db.transaction(U,`readwrite`),a=Ia(i);if(i.objectStore(U).put({format:sa,epoch:e},oa),await a,this.assertValid(),n!==this.ownershipRevision)throw Error(`IndexedDB worker ownership was released while claiming`);this.reclamationOwnership=r}async releaseBrowserWorkerEpoch(e){if(this.treeClaims.clear(),this.ownershipRevision++,this.reclamationOwnership=null,!ja(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(U,`readwrite`),n=Ia(t),r=t.objectStore(U),i=await W(r.get(oa));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(oa),await n}async metadata(){this.assertValid();let e=this.db.transaction(ra,`readonly`),t=Ia(e),n=await W(e.objectStore(ra).get(fa));return await t,n===void 0?null:(Ra(n),n)}async assertStorageManifest(){let e=this.db.transaction(U,`readonly`),t=Ia(e),n=await W(e.objectStore(U).get(ia));await t,Ba(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(U,`readwrite`),n=Ia(t),r=t.objectStore(U),i=await W(r.get(aa));if(i===void 0){r.put(e,aa),await n;return}if(i===e){await n;return}throw t.abort(),await n.catch(()=>void 0),Error(`IndexedDB database ${this.name} is already owned by a different Jazz browser session; this indicates a wrong physical root or namespace derivation error. Reset this scoped database only if you intend to discard its cache`)}async readReplicaNodeBytes(){let e=this.db.transaction(U,`readonly`),t=Ia(e),n=await W(e.objectStore(U).get(ca));if(await t,!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n))throw Error(`Missing or invalid IndexedDB replica node identity`);let r=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(r.byteLength!==16)throw Error(`Missing or invalid IndexedDB replica node identity`);return r.slice()}async updateForegroundNodeLeasePool(e){this.assertValid();let t=ba(this.db,[U]),n=Ia(t),r=t.objectStore(U);try{let t=await W(r.get(la)),i=t===void 0?Ca():Ta(t),a=e(i);return Da(i),r.put(i,la),await n,a}catch(e){try{t.abort()}catch{}throw await n.catch(()=>void 0),e}}async readPage(e){return(await this.readPages([e]))[0]}async readPages(e){this.assertValid();for(let t of e)Ha(t);if(e.length===0)return[];let t=this.db.transaction(na,`readonly`),n=Ia(t),r=t.objectStore(na),i;try{i=await Promise.all(e.map(e=>W(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Fa(e[n],t))}async commit(e,t){if(this.assertValid(),za(e),t!==void 0&&!this.isTreeOwnershipActive(t))throw Error(`IndexedDB tree ownership has expired`);let n=(e.deletedPageIds?.length??0)>0;if(n&&!this.canReclaimObsoletePages)throw Error(`IndexedDB page reclamation ownership is not active`);let r=ba(this.db,[na,ra]),i=Ia(r),a=r.objectStore(na),o=r.objectStore(ra),s=await W(o.get(fa)),c=s===void 0?0:La(s);if(c!==e.expectedGeneration)throw r.abort(),await i.catch(()=>void 0),Error(`IndexedDB B-tree generation changed: expected ${e.expectedGeneration}, found ${c}`);let l={...e.metadata,formatMagic:ta,formatVersion:1,generation:c+1};Ra(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await W(a.get(l.rootPageId))===void 0)throw Error(`IndexedDB B-tree root page ${l.rootPageId} is missing`);if(t!==void 0&&!this.isTreeOwnershipActive(t))throw Error(`IndexedDB tree ownership expired before publication`);if(n&&!this.canReclaimObsoletePages)throw Error(`IndexedDB page reclamation ownership expired before publication`);for(let[t,n]of e.pages){if(n.byteLength>l.pageSize)throw Error(`IndexedDB B-tree page ${t} exceeds configured page size`);a.put(n.slice().buffer,t)}for(let t of e.deletedPageIds??[])a.delete(t);return o.put(l,fa),await i,l}catch(e){try{r.abort()}catch{}throw await i.catch(()=>void 0),e}}commitPages(e,t,n,r,i,a,o,s){if(i.length!==a.length)return Promise.reject(Error(`IDBTree page ids and page bytes have different lengths`));let c=this.commit({expectedGeneration:e,metadata:{pageSize:t,rootPageId:n<0?null:n,nextPageId:r},pages:new Map(i.map((e,t)=>[e,a[t]])),deletedPageIds:o},s);return s!==void 0&&(this.treeTransactions.add(c),c.then(()=>this.treeTransactions.delete(c),()=>this.treeTransactions.delete(c))),c}close(){this.treeClaims.clear(),this.invalidated=!0,this.ownershipRevision++,this.reclamationOwnership=null,this.removeInvalidationListeners(),this.db.close()}async clear(){this.assertValid();let e=ba(this.db,[na,ra]),t=Ia(e);e.objectStore(na).clear(),e.objectStore(ra).clear(),await t}static async destroy(e){let t=indexedDB.deleteDatabase(e);await new Promise((n,r)=>{t.onsuccess=()=>n(),t.onerror=()=>r(t.error??Error(`IndexedDB deletion failed`)),t.onblocked=()=>r(Error(`IndexedDB deletion was blocked by an open connection: ${e}`))})}handleVersionChange=()=>{this.db.close(),this.invalidate()};handleUnexpectedClose=()=>{this.invalidate()};invalidate(){if(this.invalidated)return;this.invalidated=!0,this.treeClaims.clear(),this.reclamationOwnership=null,this.removeInvalidationListeners();let e=new ga(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new ga(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function ba(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function xa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return ie(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Sa(e){return e.slice().buffer}function Ca(){return{format:ua,active:[],reusable:[],retired:[]}}function wa(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Ta(e){return Da(e),{format:e.format,active:e.active.map(Ea),reusable:e.reusable.map(Ea),retired:e.retired.map(e=>e.slice(0))}}function Ea(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Da(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease pool`);let t=e;if(t.format!==`jazz-foreground-node-leases-v1`||!Array.isArray(t.active)||!Array.isArray(t.reusable)||!Array.isArray(t.retired))throw Error(`Invalid IndexedDB foreground node lease pool`);let n=new Set,r=new Set;for(let e of[...t.active,...t.reusable]){Oa(e);let t=Pa(e.node);if(r.has(e.leaseId)||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);r.add(e.leaseId),n.add(t)}for(let e of t.retired){let t=ka(e)?Pa(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function Oa(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!Aa(t.leaseId)||!ka(t.node)||!Ma(t.confirmedTxTime)||!Na(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function ka(e){return e instanceof ArrayBuffer&&e.byteLength===16}function Aa(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function ja(e){return typeof e==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Ma(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Na(e){return e>=0n&&e<=da}function Pa(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Fa(e,t){if(t===void 0)return null;if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw Error(`IndexedDB B-tree page ${e} is not binary data`);return(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).slice()}function W(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(va(e.error,`IndexedDB request failed`))})}function Ia(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(va(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(va(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function La(e){return Ra(e),e.generation}function Ra(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB B-tree metadata`);let t=e;if(t.formatMagic!==`jazz-idb-tree`||t.formatVersion!==1||!Va(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Ua(t.rootPageId)||!Number.isSafeInteger(t.nextPageId)||Number(t.nextPageId)<0||t.rootPageId!==null&&Number(t.rootPageId)>=Number(t.nextPageId))throw Error(`Invalid IndexedDB B-tree metadata`)}function za(e){if(!Number.isSafeInteger(e.expectedGeneration)||e.expectedGeneration<0)throw Error(`Invalid IndexedDB B-tree expected generation`);let{pageSize:t,rootPageId:n,nextPageId:r}=e.metadata;if(!Va(t)||t!==16384||!Ua(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Ua(n)||n>=r))throw Error(`Invalid IndexedDB B-tree commit root page id`);let i=new Set;for(let[n,a]of e.pages){if(!Ua(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Ua(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Ba(e){if(!e||typeof e!=`object`)throw Error(`Missing or invalid IndexedDB storage epoch manifest`);let t=e,n=Object.keys(t).sort(),r=Object.keys(ha).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==ha.storageEpoch||t.adapterId!==ha.adapterId||t.adapterFormatVersion!==ha.adapterFormatVersion||t.pageSize!==ha.pageSize||t.pageChecksum!==ha.pageChecksum||t.pageFormatMagic!==ha.pageFormatMagic||t.pageFormatVersion!==ha.pageFormatVersion||!Array.isArray(t.requiredCodecIds)||!t.requiredCodecIds.every(e=>typeof e==`string`))throw Error(`Missing or invalid IndexedDB storage epoch manifest`);let i=t.requiredCodecIds,a=ha.requiredCodecIds;if(i.length!==a.length||i.some((e,t)=>e!==a[t])){let e=a.filter(e=>!i.includes(e)),t=i.filter(e=>!a.includes(e));throw new Ye(e,t,`Missing or invalid IndexedDB storage epoch manifest: unsupported storage format: this epoch-1 root lacks codec families ${JSON.stringify(e)} required by this build and declares ${JSON.stringify(t)} that this build does not read`)}}function Va(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=pa&&e<=ma&&Number.isInteger(Math.log2(e))}function Ha(e){if(!Ua(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Ua(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Wa(){return Error(`Inspector control opening was cancelled`)}function Ga(e){try{e.postMessage({type:`close`})}catch{}e.close()}function Ka(e,t){return t?t.aborted?Promise.reject(Wa()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Wa())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var qa=Object.freeze({intervalMs:3e4,replyMs:3e4}),Ja=1e3,Ya=class{runtime;port;dbName;callbacks;traceRelay;pump=null;pendingFrames=[];readyPromise;inspectorAttachmentPhysicalDbName=null;peerAuthority;workerRealmId;pending=new Map;nextRequestId=1;closed=!1;failed=null;disposeQueryCoverageTrace;disposeLocalSettlementObserver;localSettlementsPending=!1;resumeProbePending=!1;established=!1;connectionId=crypto.randomUUID();nextProbeNonce=1;probeNonce=null;watchdogTimer=null;watchdogEpoch=0;constructor(e,t,n,r,i,a=!1,o){this.runtime=e,this.port=t,this.dbName=r,this.callbacks=i,this.traceRelay=a,t.addEventListener(`message`,this.onMessage),t.addEventListener(`messageerror`,this.onMessageError),t.start(),globalThis.addEventListener?.(`pageshow`,this.onResume),globalThis.document?.addEventListener(`visibilitychange`,this.onVisibilityChange),globalThis.document?.addEventListener(`resume`,this.onResume),this.disposeLocalSettlementObserver=e.onLocalSettlementChange(e=>{this.localSettlementsPending=e,this.wantsWatchdog()?this.armWatchdog():this.clearWatchdog()}),this.disposeQueryCoverageTrace=a?e.onQueryCoverageTrace(e=>{this.closed||this.port.postMessage({type:`diagnostic-query-coverage`,...e})}):null;let c=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),l=(async()=>{await c;let t=await e.connectUpstreamPeer(this.peerAuthority);if(this.closed||this.failed)throw await e.retirePeerTransport(t),this.failed??Error(`Browser follower connection is closed`);this.pump=new Ji(e,t,e=>{let t=Yi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=s(t);this.failed||this.closed||(e.reportRemoteServerTransportError(n),this.fail(n))},a?e=>{console.debug(`JAZZ_AUX_RELAY`,e.map(e=>({...e,hop:`tab-worker`})))}:void 0);for(let e of this.pendingFrames.splice(0))this.pump.receive(e)})();this.readyPromise=Promise.all([c,l]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(s(e)))}async ready(){if(await this.readyPromise,this.failed)throw this.failed;if(this.closed)throw Error(`Browser follower connection is closed`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.inspectorAttachmentPhysicalDbName}async waitForServerConnection(){await this.ready(),await this.request({type:`wait-server`})}async disconnect(){await this.ready(),await this.request({type:`disconnect`})}async deleteStorage(){if(await this.ready(),!this.dbName)throw Error(`Browser storage reset requires its IndexedDB name`);let e=await this.request({type:`prepare-storage-reset`});try{await ya.destroy(this.dbName)}catch(e){throw await this.request({type:`abort-storage-reset`}).catch(()=>void 0),e}return await this.request({type:`finish-storage-reset`}),{pendingUploads:e?.pendingUploads}}async storePendingUploads(){return await this.ready(),(await this.request({type:`store-pending-uploads`}))?.pendingUploads}async openInspectorControlPort(e){if(await Ka(this.ready(),e),e?.aborted)throw Wa();let t=new MessageChannel,n=this.nextRequestId++,r=()=>{},i=new Promise((e,t)=>{r=t,this.pending.set(n,{type:`open-inspector-control`,resolve:()=>e(),reject:t})}),a=!1,o=()=>{a||(a=!0,Ga(t.port1))},c=()=>{this.pending.delete(n)&&(o(),r(Wa()))};e?.addEventListener(`abort`,c,{once:!0}),this.armWatchdog();try{this.port.postMessage({type:`open-inspector-control`,id:n,port:t.port2},[t.port2])}catch(e){t.port2.close(),this.fail(s(e))}try{if(await i,e?.aborted)throw o(),Wa();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,c)}}async reconnect(e,t){await this.ready(),await this.request({type:`reconnect`,authJson:e,sessionClaims:t}),await this.request({type:`wait-server`}),this.runtime.clearRemoteServerTransportError()}updateAuth(e,t){this.closed||this.failed||this.ready().then(()=>{this.port.postMessage({type:`update-auth`,authJson:e,sessionClaims:t})}).catch(e=>this.fail(s(e)))}async shutdown(e=!1){this.closed||(await this.request({type:`close`,releaseContext:e}),this.dispose(Error(`Browser follower connection is closed`)))}leaveForPageCache(){if(this.closed||this.failed||!this.established||this.hasPendingWork())return!1;try{this.port.postMessage({type:`close`,releaseContext:!0})}catch{}return this.dispose(Error(`Browser follower connection left for the back/forward cache`)),!0}async waitForPendingWrites(){await this.flushLocal(),await this.request({type:`flush-pending-writes`})}async flushLocal(){await this.ready(),await this.pump.flush();let e=this.request({type:`flush-local`});await this.runtime.flushLocalSettlements(),this.port.postMessage({type:`flush-local-observed`}),await e}detachForReconnect(){this.dispose(Error(`Browser follower connection is reconnecting`))}request(e){if(this.failed)return Promise.reject(this.failed);if(this.closed)return Promise.reject(Error(`Browser follower connection is closed`));let t=this.nextRequestId++,n={...e,id:t},r=new Promise((n,r)=>{this.pending.set(t,{type:e.type,resolve:n,reject:r})});this.armWatchdog();try{this.port.postMessage(n)}catch(e){this.fail(s(e))}return r}clearWatchdog(){this.watchdogTimer!==null&&clearTimeout(this.watchdogTimer),this.watchdogTimer=null,this.probeNonce=null,this.watchdogEpoch++}armWatchdog(){this.closed||this.failed||!this.wantsWatchdog()||this.watchdogTimer!==null||this.scheduleWatchdog(qa.intervalMs,!1)}scheduleWatchdog(e,t){let n=++this.watchdogEpoch,r=Date.now()+e;this.watchdogTimer=setTimeout(()=>{if(n!==this.watchdogEpoch||this.closed||this.failed)return;if(this.watchdogTimer=null,!this.wantsWatchdog()){this.clearWatchdog();return}if(!t||Date.now()>r+Ja){this.sendProbe();return}let e=new $e(`Browser worker connection is unresponsive. Pending operation outcomes are unknown; operations were not retried.`);this.runtime.reportRemoteServerTransportError(e),this.fail(e)},e)}sendProbe(){if(this.clearWatchdog(),this.closed||this.failed||!this.wantsWatchdog())return;let e=this.nextProbeNonce++;this.probeNonce=e,this.scheduleWatchdog(qa.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(s(e))}}onResume=()=>{this.resumeProbePending=!0,this.sendProbe()};hasPendingWork(){return this.pending.size>0||this.localSettlementsPending||this.resumeProbePending}wantsWatchdog(){return this.hasPendingWork()||this.established&&globalThis.document?.visibilityState===`visible`}onVisibilityChange=()=>{globalThis.document?.visibilityState===`visible`&&this.onResume()};onMessage=e=>{if(this.closed||this.failed)return;let t=e.data;if(t.type===`runtime-pong`){if(t.connectionId!==this.connectionId||t.nonce!==this.probeNonce)return;this.resumeProbePending=!1,this.clearWatchdog(),this.armWatchdog();return}if(t.type===`frames`){this.pump?this.pump.receive(t.frames):this.pendingFrames.push(t.frames);return}if(t.type===`auth-failure`){this.callbacks.onAuthFailure(t.reason);return}if(t.type===`auth-restored`){this.callbacks.onAuthRestored();return}if(t.type===`transport-state`){this.callbacks.onExplicitOfflineChange?.(t.explicitlyDisconnected);return}if(t.type===`remote-link`){t.state===`connected`&&this.runtime.clearRemoteServerTransportError(),this.callbacks.onRemoteLinkChange?.(t.state,t.link);return}if(t.type===`mutation-error`){this.runtime.reportRemoteMutationError(t.event);return}if(t.type===`storage-failure`){this.runtime.reportLocalStorageFailure(t.message);return}if(t.type===`transport-error`){this.runtime.reportRemoteServerTransportError(He(t.error),t.retrying===!0);return}if(t.type===`storage-reset`){for(let[e,t]of this.pending)t.type===`finish-storage-reset`&&(this.pending.delete(e),t.resolve());this.wantsWatchdog()||this.clearWatchdog(),this.port.postMessage({type:`storage-reset-observed`,resetId:t.resetId}),this.callbacks.onStorageReset?.(t.resetId);return}if(t.type===`storage-invalidated`){this.callbacks.onStorageInvalidated?.(),this.dispose(Error(`IndexedDB storage was externally invalidated`));return}if(t.type===`relay-trace`){this.traceRelay&&console.debug(`JAZZ_AUX_RELAY`,t.entries);return}if(t.type===`error`){this.fail(He(t.error));return}if(t.type===`inspector-binding`||t.type===`inspector-query-result`)return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),this.wantsWatchdog()||this.clearWatchdog(),t.error?n.reject(He(t.error)):(this.inspectorAttachmentPhysicalDbName??=t.inspectorAttachmentPhysicalDbName??null,n.type===`init`&&(this.peerAuthority=t.peerAuthority,this.workerRealmId=t.workerRealmId),n.resolve({pendingUploads:t.pendingUploads})))};onMessageError=()=>{this.fail(Error(`Browser follower port message error`))};getWorkerRealmId(){return this.workerRealmId}fail(e){if(!(this.failed||this.closed)){this.failed=e;try{this.port.postMessage({type:`close`})}catch{}try{this.callbacks.onFailure(e)}finally{this.dispose(e)}}}dispose(e){if(!this.closed){this.closed=!0,this.clearWatchdog(),globalThis.removeEventListener?.(`pageshow`,this.onResume),globalThis.document?.removeEventListener(`visibilitychange`,this.onVisibilityChange),globalThis.document?.removeEventListener(`resume`,this.onResume),this.disposeLocalSettlementObserver(),this.port.removeEventListener(`message`,this.onMessage),this.port.removeEventListener(`messageerror`,this.onMessageError),this.disposeQueryCoverageTrace?.(),this.pump?.close(),this.pendingFrames.length=0,this.port.close();for(let t of this.pending.values())t.reject(e);this.pending.clear()}}},Xa=e=>`jazz:store-generation:${e}`;function Za(e){try{globalThis.localStorage?.setItem(Xa(e),crypto.randomUUID())}catch{}}function Qa(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Xa(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Xa(e),r),r}catch{return null}}function $a(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Xa(e))!==t}catch{return!0}}var eo=class extends Error{name=`BrowserWorkerScriptLoadError`};async function to(e){let t=e.moduleUrl!==null&&Di(e.moduleUrl)!==void 0,n=e.workerUrl?await no(e.workerUrl,e.fetch??globalThis.fetch):null;return new eo(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?Wi:t?` Jazz runs from the Vite dev server's dependency pre-bundle, so it asks the dev server to resolve the worker from the jazz-tools package; that needs jazz-tools to be a dependency the dev server resolves from your project. Otherwise, add "jazz-tools" to optimizeDeps.exclude in your Vite config, next to "jazz-wasm".`:e.workerUrl?` Serve jazz-tools' dist/worker/jazz-broker-worker.js at that URL as JavaScript, or point runtimeSources.brokerWorkerUrl at where it is served.`:` Your bundler or server did not serve jazz-tools' dist/worker/jazz-broker-worker.js as JavaScript; a single-page-app fallback that answers unknown paths with index.html is a common cause. Point runtimeSources.brokerWorkerUrl at where the worker is served.`} The local-first client cannot start without it.`)}async function no(e,t){if(!t)return null;try{let n=await t(e,{cache:`no-store`});n.body?.cancel().catch(()=>void 0);let r=n.headers.get(`content-type`)??``;return/\btext\/html\b/i.test(r)?`the server answered with an HTML page (HTTP ${n.status}) instead of JavaScript`:n.ok?null:`the server answered HTTP ${n.status}`}catch{return null}}function ro(e,t){if(ao(e))return new SharedWorker(Ci(e),{type:(io(e)?null:Wr())??`module`,name:t});let n=Di(Vr());if(n)return new SharedWorker(n,{type:`module`,name:t});let r=new SharedWorker(new URL(``+new URL(`jazz-broker-worker-OYLmDTMs.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Ui);return r}function io(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function ao(e){return io(e)||Wr()!==null}function oo(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),to({workerUrl:ao(t)?Ci(t):Di(Vr()),moduleUrl:Vr(),metro:Gi()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var so=1e4,co=8,lo=8,uo=25,fo=250,po=5*6e4,mo=1e3,ho=new Map;function go(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function _o(e,t){return[`jazz-runtime`,t,ji(e)].join(`:`)}function vo(e,t){return`${e}\u0000${t}`}var yo=class e{node;confirmedTxTime;leaseId;workerRealmId;worker=null;port=null;closed=!1;terminalError=null;finishPromise=null;finishWaiter=null;listeningForFinish=!1;terminalRequestSent=!1;constructor(e,t,n,r){this.node=e,this.confirmedTxTime=t,this.leaseId=n,this.workerRealmId=r}static async acquire(e){let t=Oi(e.runtimeSources),n=_o(t,e.dbName),r=vo(n,e.storageOwner);if(ho.has(r))throw Error(`Shared browser foreground lease cancellation cleanup is still pending for this database; wait for the previous worker admission to finish`);let i=e=>ro(t,e),a=Date.now()+so,o=So(n),s=0,c=null;for(let l=0;l<co;l+=1)for(;;){let l=a-Date.now();if(l<=0)throw Error(c??`Shared browser runtime did not issue a foreground node lease`);let u=i(`${n}:generation-${o}`),d=await this.acquireFromWorkerGeneration(u,e,r,crypto.randomUUID(),l,go(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=Co(n,o);break}if(c=d.message,s+=1,s>=lo)throw Error(c);let f=Math.min(uo*2**(s-1),fo,Math.max(0,a-Date.now()));if(f<=0)throw Error(c);await new Promise(e=>setTimeout(e,f))}throw Error(c??`Shared browser foreground lease worker did not answer after closing`)}static async acquireFromPort(e,t){let n=await this.acquireFromWorkerGeneration({port:e},t,`inspector:${t.dbName}:${t.storageOwner}`,crypto.randomUUID(),so);if(n.type!==`ready`)throw Error(`Inspector worker is no longer available`);return n.lease}static acquireFromWorkerGeneration(t,n,r,i,a,o,s){let c=t.port;return new Promise((l,u)=>{let d=!1,f=!1,p=null,m=null,h=Error(`Shared browser runtime did not issue a foreground node lease`),g=e=>{f||(f=!0,u(e))},_=()=>setTimeout(()=>{d=!0,p=Symbol(`foreground-lease-cleanup`),ho.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&ho.get(r)===p&&ho.delete(r),c.removeEventListener(`message`,y),c.removeEventListener(`messageerror`,b)},y=r=>{let a=r.data;if(a?.type===`foreground-node-lease-worker-alive`){if(a.attemptId!==i||m===null)return;c.postMessage({type:`acquire-foreground-node-lease`,attemptId:i,dbName:n.dbName,storageOwner:n.storageOwner});return}if(a?.type===`foreground-node-lease-worker-closing`){if(a.attemptId!==i)return;v(),c.close(),f=!0,l({type:`worker-closing`});return}if(a?.type===`foreground-node-lease-busy`){v(),c.close(),f=!0,l({type:`busy`,message:a.message});return}if(a?.type===`foreground-node-lease-error`){v(),c.close(),g(He(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?He(a.error):h);return}if(a?.type!==`foreground-node-lease-ready`||d)return;if(!/^(0|[1-9][0-9]*)$/.test(a.confirmedTxTime)){v(),g(Error(`Shared browser runtime returned an invalid foreground lease high-water`));return}v();let o=new e(a.node.slice(),BigInt(a.confirmedTxTime),a.leaseId,a.workerRealmId);o.worker=t,o.port=c,f=!0,l({type:`ready`,lease:o})},b=()=>{v(),c.close(),g(Error(`Shared browser foreground lease port message error`))},x=oo(t,s,e=>{v(),c.close(),g(e)});c.addEventListener(`message`,y),c.addEventListener(`messageerror`,b),c.start(),m=_(),c.postMessage({type:`probe-foreground-node-lease-worker`,attemptId:i,...o?{wasmPrefetch:o}:{}})})}async returnWithHighWater(e){if(this.terminalError)throw this.terminalError;if(e<0n)throw Error(`Invalid foreground transaction high-water`);await this.finish({type:`return-foreground-node-lease`,confirmedTxTime:e.toString()})}async retire(){if(this.terminalError)throw this.terminalError;this.closed||await this.finish({type:`retire-foreground-node-lease`})}abandonAfterWorkerFailure(e){if(!this.terminalError&&(this.terminalError=e,this.finishWaiter?.reject(e),this.finishWaiter=null,!(this.closed||!this.port)&&(this.listenForFinish(),!this.terminalRequestSent))){this.terminalRequestSent=!0;try{this.port.postMessage({type:`retire-foreground-node-lease`})}catch{this.closeFinishPort()}}}releaseAfterStorageReset(e){this.failFinish(e)}releaseAfterWorkerReplacement(e){this.failFinish(e)}failFinish(e){this.terminalError??=e,this.finishWaiter?.reject(this.terminalError),this.closeFinishPort()}finish(e){if(this.terminalError)return Promise.reject(this.terminalError);if(this.closed)return Promise.reject(Error(`Shared browser foreground lease is already closed`));if(this.finishPromise)return this.finishPromise;let t=this.port;if(!t)return Promise.reject(Error(`Shared browser foreground lease port is unavailable`));this.listenForFinish(),this.finishPromise=new Promise((e,t)=>{this.finishWaiter={resolve:e,reject:t}}),this.terminalRequestSent=!0;try{t.postMessage(e)}catch(e){this.failFinish(s(e))}return this.finishPromise}listenForFinish(){this.listeningForFinish||(this.listeningForFinish=!0,this.port?.addEventListener(`message`,this.onFinishResult),this.port?.addEventListener(`messageerror`,this.onFinishError))}onFinishResult=e=>{let t=e.data;t?.type===`foreground-node-lease-result`&&(t.error?this.failFinish(He(t.error)):(this.finishWaiter?.resolve(),this.closeFinishPort()))};onFinishError=()=>{this.failFinish(Error(`Shared browser foreground lease port message error`))};closeFinishPort(){this.finishWaiter=null,this.closed=!0,this.port?.removeEventListener(`message`,this.onFinishResult),this.port?.removeEventListener(`messageerror`,this.onFinishError),this.worker?.port.close(),this.port=null,this.worker=null}},bo=class{callbacks;worker=null;readyPromise;initialConfigurationAdmissionRejected=!1;heldByAnotherSignIn=!1;readyError=null;connection=null;closed=!1;workerName;connectedGeneration=null;cancelBootstrap=null;releaseLivenessLock=null;dbName;storeGenerationWhenLeft=null;constructor(e,t,n,r){this.callbacks=r;let i=Oi(t.runtimeSources),a=_o(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>ro(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=s(e),this.releaseLivenessLock?.(),r.onFailure(this.readyError)})}holdLivenessLock(){let e=globalThis.navigator?.locks;if(!e)return;let t=`jazz-tab-alive:${crypto.randomUUID()}`,n,r=new Promise(e=>n=e);this.releaseLivenessLock=n;let i=new Promise((n,i)=>{e.request(t,()=>(n(),r)).catch(i)});return i.catch(()=>void 0),{name:t,granted:i}}announceLivenessLock(e,t){e.granted.then(()=>{this.closed||this.worker?.port!==t||t.postMessage({type:`liveness-lock`,name:e.name})},()=>void 0)}async connect(e,t,n,r,i){let a=this.holdLivenessLock(),o=So(r);for(let s=0;s<co;s+=1){if(this.closed)return;let s=`${r}:generation-${o}`,c=await this.connectOnce(e,t,n,s,i);if(c.error)throw c.error;if(this.closed)return;if(c.connected){this.connectedGeneration=o,a&&this.worker&&this.announceLivenessLock(a,this.worker.port);return}o=Co(r,o)}throw Error(`Shared browser runtime did not answer after its previous realm closed`)}connectOnce(e,t,n,r,i){let a=i(r);this.worker=a;let o=a.port;return o.start(),new Promise(r=>{let i=!1,c=!1,l=!1,u=Date.now(),d=u+po,f=typeof document<`u`&&document.hidden,p,m=e=>{i||(i=!0,x(),this.cancelBootstrap===g&&(this.cancelBootstrap=null),r(e))},h=e=>{if(!i){c=!0,m(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{w(),o.close()}}},g=()=>h({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=g;let _=()=>{u=Date.now(),d=u+po},v=()=>{let e=typeof document<`u`&&document.hidden;f&&!e&&_(),f=e},y=()=>_(),b=()=>{let e=Date.now();if((f||e-u>mo*2)&&_(),u=e,e>=d){h({connected:!1,error:new $e(`Shared browser runtime did not finish initialization within five minutes`)});return}p=setTimeout(b,Math.min(mo,d-e))},x=()=>{clearTimeout(p),p=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,v),typeof window<`u`&&window.removeEventListener(`pageshow`,y)},S=n=>{if(c){if(n.data?.type===`runtime-ready`){if(l)return;l=!0,o.postMessage({type:`close`,id:0,releaseContext:!0});return}else if(n.data?.type!==`runtime-bootstrap-cancelled`&&n.data?.type!==`runtime-error`&&n.data?.type!==`worker-closing`&&!(n.data?.type===`result`&&n.data.id===0))return;w(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){w(),o.close(),this.worker===a&&(this.worker=null);let e=He(n.data.error);this.heldByAnotherSignIn=e.message===Oe,this.initialConfigurationAdmissionRejected=e.message===`incompatible persistent browser configuration`||this.heldByAnotherSignIn,m({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;w(),this.cancelBootstrap===g&&(this.cancelBootstrap=null);let r=new Ya(e,o,t.sessionClaims,t.dbName,{onAuthFailure:this.callbacks.onAuthFailure,onAuthRestored:this.callbacks.onAuthRestored,onExplicitOfflineChange:this.callbacks.onExplicitOfflineChange,onRemoteLinkChange:this.callbacks.onRemoteLinkChange,onFailure:this.callbacks.onFailure,onStorageReset:e=>{Za(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{Za(this.dbName),this.callbacks.onStorageInvalidated?.()}},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>m({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})})},C=()=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:Error(`Shared browser runtime port message error`)})},w=()=>{x(),T(),o.removeEventListener(`message`,S),o.removeEventListener(`messageerror`,C)},T=oo(a,t.runtimeSources,e=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:e})});o.addEventListener(`message`,S),o.addEventListener(`messageerror`,C),typeof document<`u`&&document.addEventListener(`visibilitychange`,v),typeof window<`u`&&window.addEventListener(`pageshow`,y),p=setTimeout(b,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})}})}getWorkerRealmId(){return this.connection?.getWorkerRealmId()}ready(){return this.readyPromise.then(()=>{if(this.readyError)throw this.readyError})}async waitForServerConnection(){await this.ready(),await this.connection?.waitForServerConnection()}async updateAuth(e,t){await this.ready(),this.connection?.updateAuth(e,t)}async disconnect(){await this.ready(),await this.connection?.disconnect()}async reconnect(e,t){await this.ready(),await this.connection?.reconnect(e,t)}canRetryInitialConfigurationAdmission(){return this.initialConfigurationAdmissionRejected}waitsForAnotherSignIn(){return this.heldByAnotherSignIn}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=Qa(this.dbName);return e===null||!this.connection.leaveForPageCache()?!1:(this.storeGenerationWhenLeft=e,this.closed=!0,this.connection=null,this.worker=null,this.releaseLivenessLock?.(),!0)}storeChangedSinceLeaving(){return $a(this.dbName,this.storeGenerationWhenLeft)}async shutdown(){if(!this.closed){this.closed=!0,this.cancelBootstrap?.();try{await this.connection?.shutdown(!0)}finally{this.connection=null,this.worker?.port.close(),this.worker=null,this.releaseLivenessLock?.()}}}async waitForPendingWrites(){await this.ready(),await this.connection?.waitForPendingWrites()}async flushLocal(){await this.ready(),await this.connection?.flushLocal()}async deleteStorage(){await this.ready(),Za(this.dbName);try{return await this.connection?.deleteStorage()}finally{Za(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await Ka(this.ready(),e),!this.connection)throw Error(`Shared browser runtime is not connected`);let t=await this.connection.openInspectorControlPort(e),n=this.connectedGeneration;return n!==null&&xo(t,this.workerName,n),t}};function xo(e,t,n){e.addEventListener(`message`,e=>{e.data?.type!==`result`||e.data.workerTerminated!==!0||Co(t,n)})}function So(e){try{let t=Number.parseInt(localStorage.getItem(wo(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function Co(e,t){try{let n=wo(e);return So(e)===t&&localStorage.setItem(n,String(t+1)),So(e)}catch{return t+1}}function wo(e){return`jazz:shared-worker-generation:${e}`}function To(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Eo(e){return[...new Set([...To(e)].map(e=>e.namespace))].sort()}function Do(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function Oo(e,t){let n=[...To(e)],r=Eo(e);if(n.length===0)throw Error(`No live Jazz storage contexts are available on this page.`);let i=t?.trim();if(!i){if(r.length===1){let[e]=r;return n.find(t=>t.namespace===e).db}throw Error(`Multiple live Jazz storage contexts are available. Call window.__jazz.clearStorage("<namespace>").${Do(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${Do(r)}`);return a.db}var ko=new Map;function Ao(){let e=()=>[...ko.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...ko.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...ko].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...ko.keys()].map(t=>t.waitForSync(e)))}}}function jo(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(ko.set(e,t),Lo(n),()=>{ko.delete(e)})}var Mo=Symbol.for(`jazz-tools.window-jazz`);function No(e){return`window.__jazz is Jazz's page handle (window.__jazz.status(), waitForSync(), clearStorage()), but this page already has a window.__jazz that Jazz didn't set (${e===null?`null`:typeof e}). Jazz leaves it as it is and works without its page handle; rename your app's global to get the handle back.`}var Po=new WeakSet;function Fo(e){let t=e.__jazz;return t===void 0||Io(t)?!1:(Po.has(e)||(Po.add(e),console.warn(No(t))),!0)}function Io(e){if(!e||typeof e!=`object`)return!1;if(Mo in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function Lo(e){let t=Fo(e),n=(t?void 0:e.__jazz)??{};n[Mo]=!0;let r=Object.assign(n,Ao(),{async clearStorage(t){await Oo(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Eo(e)},async shutdown(t){let n=[...To(e)];if(n.length===0)return;let r=t?.trim(),i=r?n.filter(e=>e.namespace===r):n;await Promise.all(i.map(e=>e.db.shutdown()))}});return t||(e.__jazz=r),r}var Ro=`history.`;function zo(e){return Bo(e)!==void 0}function Bo(e){return e.startsWith(Ro)?e.slice(8):void 0}var Vo=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Ho=new WeakMap;function G(e,t){let n=Bo(t);if(n===void 0)return e[t];if(zo(n)||!Object.hasOwn(e,n))return;let r=Ho.get(e);r||Ho.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Vo],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Uo=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Wo=class extends Error{code;status;constructor(e,t,n=e){super(n),this.code=e,this.status=t,this.name=`AccountAuthError`}},Go=new WeakMap;function Ko(e){let t=Me(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!r(t.iss)||!r(t.sub))throw new Wo(`invalid_identity_token`);return{issuer:t.iss,subject:t.sub}}function qo(e,t){return e.issuer===t.issuer&&e.subject===t.subject}async function Jo(e,t){if(typeof e==`string`)return e;let n;try{return await Promise.race([Promise.resolve().then(()=>e.getToken(t)),new Promise((e,t)=>{n=setTimeout(()=>t(new Wo(`credential_refresh_timeout`)),3e4)})])}finally{n&&clearTimeout(n)}}async function Yo(e,t,n){let r=Go.get(e);if(!r||r.registry!==t)throw new Wo(`invalid_account_handle`);if(r.delegated)throw new Wo(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new Wo(`backend_account_requires_backend_host`);let i=await Jo(r.auth,n);if(Go.get(e)!==r)throw new Wo(`account_logged_out`);if(!qo(Ko(i),e.identity))throw new Wo(`credential_identity_changed`);return i}function Xo(e){let t=Go.get(e);if(!t)throw new Wo(`invalid_account_handle`);return t.registry}var Zo=new WeakMap;function Qo(e){return $o(e),Zo.get(e)?.bearer}function $o(e){let t=Zo.get(e);if((t!==void 0||e.accountId!==void 0||e.accountRegistryAuthority!==void 0)&&(!t||t.id!==e.accountId||t.registry!==e.accountRegistryAuthority||t.inspectorPort!==void 0&&t.inspectorPort!==e.runtimeSources?.browserWorkerPort))throw new Wo(`account_handle_required`)}function es(e,t){if($o(e),e.accountId!==void 0){if(t.accountId!==e.accountId||t.accountRegistryAuthority!==e.accountRegistryAuthority||Zo.get(e)?.inspectorPort!==void 0&&t.runtimeSources?.browserWorkerPort!==Zo.get(e)?.inspectorPort)throw new Wo(`account_application_mismatch`);Zo.set(t,Zo.get(e))}}function ts(e){let t=e.runtimeSources?.browserWorkerPort;if(!e.accountId||!e.accountRegistryAuthority||!t)throw new Wo(`account_handle_required`);Zo.set(e,{id:e.accountId,registry:e.accountRegistryAuthority,inspectorPort:t})}var ns=Object.freeze({pending:0,oldestPendingAt:null,rejected:0,lastRejection:null});function rs(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function is(e,t){if(e.state!==`offline`||e.reason===`disconnected`)return null;let n={network:`The server is unreachable; retrying.`,auth:`The server refused this client's credential.`,stopped:`The link stopped for good; only db.reconnect() tries again.`,"authority-changed":`The server serves another history than this client's local store.`,"held-by-another-tab":`Another tab holds this account's local store under another sign-in.`}[e.reason];return{kind:e.reason,message:t||n,at:Date.now()}}function as(e,t){return e===t?!0:!e||!t?!1:e.kind===t.kind&&e.at===t.at&&e.message===t.message&&(e.kind!==`rejected`||t.kind===`rejected`&&e.code===t.code)}var os=Object.freeze({state:`local-only`}),ss=Object.freeze({state:`connecting`}),cs=Object.freeze({state:`connected`});function K(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function ls(e){switch(e?.phase??`noServer`){case`noServer`:return os;case`offline`:return K(`disconnected`);case`live`:return cs;case`connecting`:case`backoff`:return e.outagePublished?K(`network`):ss;case`awaitingCredential`:return K(`auth`);case`stopped`:return K(`stopped`)}}function us(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`?!0:e.reason===t.reason&&e.retrying===t.retrying:!1}function ds(e,t=ns,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:rs(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function fs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&as(e.lastError,t.lastError)&&us(e.link,t.link)}function ps(e,t){return e.pending===t.pending&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&e.lastRejection?.at===t.lastRejection?.at&&e.lastRejection?.code===t.lastRejection?.code}var ms=class{read;same;listeners=new Set;published;scheduled=!1;constructor(e,t=Object.is){this.read=e,this.same=t}subscribe(e,t){t.aborted||(this.listeners.size===0&&(this.published=this.read()),this.listeners.add(e),t.addEventListener(`abort`,()=>this.listeners.delete(e),{once:!0}))}get hasListeners(){return this.listeners.size>0}changed(){this.scheduled||this.listeners.size===0||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1;let e=this.read();if(!(this.published!==void 0&&this.same(e,this.published))){this.published=e;for(let t of[...this.listeners])t(e)}}))}};function hs(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function gs(e){if(typeof e==`string`)return e;let t;try{t=JSON.stringify(e)}catch(e){throw Error(`JSON values must be serializable: ${e instanceof Error?e.message:String(e)}`)}if(t===void 0)throw Error(`JSON values must be serializable`);return t}function _s(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid relationship "${t}"; use s.rel(...) or s.reverse(...).`);let n=e,r=n.kind===`forward`?`column`:n.kind===`reverse`?`relation`:void 0;if(!r||typeof n.table!=`string`||!n.table||typeof n[r]!=`string`||!n[r])throw Error(`Invalid relationship "${t}": table and ${r??`column/relation`} must be nonempty strings.`)}var vs=class extends Error{},ys=class extends Error{};function bs(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=new Set;for(let t of r.columns){if(e.has(t.name))throw new ys(`Table "${n}" has duplicate column descriptor "${t.name}".`);e.add(t.name)}t.set(n,[]);for(let t of Object.keys(r.relations??{}))if(!t||[`__proto__`,`constructor`,`prototype`].includes(t)||t.startsWith(`$`)||t===`id`||e.has(t))throw new vs(`Relationship "${n}.${t}" collides with a stored/public output column.`)}for(let[n,r]of Object.entries(e))for(let[i,a]of Object.entries(r.relations??{})){if(_s(a,`${n}.${i}`),!Object.hasOwn(e,a.table))throw Error(`Relationship "${n}.${i}" references unknown table "${a.table}".`);let o=a.kind===`forward`?a:e[a.table].relations?.[a.relation];if(!o||o.kind!==`forward`)throw Error(`Reverse relationship "${n}.${i}" must reference a named forward relation on "${a.table}".`);if(a.kind===`reverse`&&o.table!==n)throw Error(`Reverse relationship "${n}.${i}" references a forward relation targeting "${o.table}", not "${n}".`);let s=(a.kind===`forward`?r:e[a.table]).columns.find(e=>e.name===o.column);if(!s)throw Error(`Relationship "${n}.${i}" references unknown column "${o.column}".`);let c=s.column_type.type===`Array`&&s.column_type.element.type===`Uuid`;if(s.column_type.type!==`Uuid`&&!c)throw Error(`Relationship "${n}.${i}" requires UUID or UUID[] column "${o.column}".`);if(s.references&&s.references!==o.table)throw Error(`Relationship "${n}.${i}" conflicts with column reference target "${s.references}".`);t.get(n).push({name:i,type:a.kind,fromTable:n,toTable:a.table,fromColumn:a.kind===`forward`?o.column:`id`,toColumn:a.kind===`forward`?`id`:o.column,isArray:a.kind===`reverse`||c,nullable:a.kind===`forward`&&s.nullable})}return t}function xs(){return{type:`Row`,columns:[{name:`account`,column_type:{type:`Uuid`},nullable:!1},{name:`identity`,nullable:!1,column_type:{type:`Row`,columns:[{name:`issuer`,column_type:{type:`Text`},nullable:!1},{name:`subject`,column_type:{type:`Text`},nullable:!1}]}}]}}var Ss=[`$canRead`],Cs=[`$createdBy`,`$createdAt`,`$updatedBy`,`$updatedAt`,`$createdBy.account`,`$createdBy.identity`,`$createdBy.identity.issuer`,`$createdBy.identity.subject`,`$updatedBy.account`,`$updatedBy.identity`,`$updatedBy.identity.issuer`,`$updatedBy.identity.subject`];function ws(e){return Ss.includes(e)}function Ts(e){return Cs.includes(e)}function Es(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return xs();if(e===`$createdAt`||e===`$updatedAt`||e===`$deletedAt`)return{type:`Timestamp`};let[t,...n]=e.split(`.`);if((t===`$createdBy`||t===`$updatedBy`||t===`$deletedBy`)&&n.length){let e=xs();for(let t of n){if(e.type!==`Row`)return;let n=e.columns.find(e=>e.name===t);if(!n)return;e=n.column_type}return e}}var Ds=`__jazz_requireIncludes`;function Os(e){return Array.isArray(e)?e.filter(e=>F(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function ks(e){return Array.isArray(e)?e.filter(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&(e[1]===`asc`||e[1]===`desc`)):[]}function As(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function js(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ms(e){if(!F(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!F(r))throw Error(`Invalid large-value selection for column "${n}".`);let e=Object.keys(r);if(typeof r.at==`string`&&e.length===1)t[n]={at:r.at};else if(js(r.from)&&js(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(js(r.fromUtf8)&&js(r.toUtf8)&&e.length===2)t[n]={fromUtf8:r.fromUtf8,toUtf8:r.toUtf8};else throw Error(`Invalid large-value selection for column "${n}".`)}return t}function Ns(e){let t=F(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!F(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...F(e)&&e.seed?{seed:Ps(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:Os(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Ps(e){if(!F(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:Os(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ns(e.gather),...Array.isArray(e.orderBy)?{orderBy:ks(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return F(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!F(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ps(e.input)}])}),t}function Fs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function Is(e){let t={...e};return delete t[Ds],Bs(t)}function Ls(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Rs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function zs(e){if(e===!0)return Fs();if(!F(e))return null;if(Ls(e)){let t=Vs(e);return{table:t.table||void 0,conditions:t.conditions,includes:t.includes,requireIncludes:t.requireIncludes,select:t.select,partialSelect:t.partialSelect,orderBy:t.orderBy,limit:t.limit,offset:t.offset,hops:t.hops,gather:t.gather}}if(Rs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:Os(e.conditions),includes:Bs(e.includes),requireIncludes:e[Ds]===!0,select:As(e.select),partialSelect:Ms(e.partialSelect??e.select),orderBy:ks(e.orderBy),limit:typeof e.limit==`number`?e.limit:void 0,offset:typeof e.offset==`number`?e.offset:void 0,hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ns(e.gather)};let t=Fs();return t.requireIncludes=e[Ds]===!0,t.includes=Is(e),t}function Bs(e){if(!F(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=zs(r);e&&(t[n]=e)}return t}function Vs(e){let t=F(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Ms(t.partialSelect??t.select);return{table:t.table,conditions:Os(t.conditions),includes:Bs(t.includes),requireIncludes:t[Ds]===!0,select:Array.isArray(t.select)?As(t.select):Object.keys(n),partialSelect:n,orderBy:ks(t.orderBy),limit:typeof t.limit==`number`?t.limit:void 0,offset:typeof t.offset==`number`?t.offset:void 0,includeDeleted:t.includeDeleted===!0,hops:Array.isArray(t.hops)?t.hops.filter(e=>typeof e==`string`):[],gather:Ns(t.gather),...F(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!F(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ps(e.input)}])}}:{}}}var Hs=`__jazz_include_`;function Us(e){return`${Hs}${e}`}function Ws(e,t,n){let r=G(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);if(!n||n.length===0)return r.columns.map(e=>e.name);let i=new Set(r.columns.map(e=>e.name)),a={explicitColumnsInSchema:new Set,explicitColumnsNotInSchema:new Set,hasWildcard:!1};for(let e of n){if(e===`*`){a.hasWildcard=!0;continue}e!==`id`&&(i.has(e)?a.explicitColumnsInSchema.add(e):a.explicitColumnsNotInSchema.add(e))}if(!a.hasWildcard){let e=[...a.explicitColumnsInSchema,...a.explicitColumnsNotInSchema];return e.length===0&&n.includes(`id`)?[`id`]:e}return a.explicitColumnsNotInSchema.size===0?[...i]:[...i,...a.explicitColumnsNotInSchema]}function Gs(e,t){return t?{scope:t,column:e}:{column:e}}function Ks(e,t,n){let r=G(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:Gs(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:Gs(e.name,t)}}))]}function qs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=Es(n);if(r)return r;let i=G(e,t);if(i)return i.columns.find(e=>e.name===n)?.column_type}function Js(e){if(e instanceof Date){let t=e.getTime();if(!Number.isFinite(t))throw Error(`Invalid Date value for timestamp condition`);return t}if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid number value for timestamp condition`);return e}if(typeof e==`string`){let t=e.trim();if(/^-?\d+(\.\d+)?$/.test(t)){let e=Number(t);if(Number.isFinite(e))return e}let n=Date.parse(t);if(Number.isFinite(n))return n}throw Error(`Invalid timestamp condition. Expected Date, ISO string, or finite number.`)}function Ys(e){return Js(e)}function Xs(e,t){if(e==null)return{type:`Null`};if(t.type===`Json`)return{type:`Text`,value:gs(e)};if(t.type===`Timestamp`&&e instanceof Date)return{type:`Timestamp`,value:Ys(e)};if(t.type===`Bytea`){if(e instanceof Uint8Array)return{type:`Bytea`,value:[...e]};if(Array.isArray(e))return{type:`Bytea`,value:e.map(e=>{let t=Number(e);if(!Number.isInteger(t)||t<0||t>255)throw Error(`Bytea values must contain integers in range 0..255`);return t})};throw Error(`Bytea values must be Uint8Array or byte arrays`)}if(Array.isArray(e)){if(t.type!==`Array`)throw Error(`Unexpected array value for scalar column`);return{type:`Array`,value:e.map(e=>Xs(e,t.element))}}if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`){if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Ys(e)};if(t.type===`BigInt`){if(!Number.isSafeInteger(e))throw Error(`BIGINT query values must be bigint or safe integer numbers`);return{type:`BigInt`,value:BigInt(e)}}if(t.type===`Double`||t.type===`Integer`)return{type:t.type,value:e}}if(typeof e==`bigint`){if(t.type!==`BigInt`)throw Error(`Unexpected bigint value for non-BIGINT column`);return{type:`BigInt`,value:e}}if(typeof e==`string`){if(t?.type===`BigInt`)try{return{type:`BigInt`,value:BigInt(e)}}catch{throw Error(`BIGINT query values must be signed integer strings`)}if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Ys(e)};if(t?.type===`Uuid`)return{type:`Uuid`,value:e};if(t?.type===`Enum`&&!t.variants.includes(e))throw Error(`Invalid enum value "${e}". Expected one of: ${t.variants.join(`, `)}`);return{type:`Text`,value:e}}throw Error(`Unsupported value type: ${typeof e}`)}function Zs(e,t){if(!(!t||e.type!==`forward`||e.nullable))return e.isArray?`MatchCorrelationCardinality`:`AtLeastOne`}function Qs(e,t,n,r){let i=qs(n,r,e);if(!i)throw Error(`Unknown column "${e}" in partial select.`);if(`at`in t){if(i.type!==`Json`)throw Error(`JSON pointer selection requires a JSON column, got "${e}".`);return{kind:`json_pointer`,column:e,at:t.at}}if(`fromUtf8`in t){if(t.toUtf8<t.fromUtf8)throw Error(`Invalid UTF-8 range for column "${e}": toUtf8 must be >= fromUtf8.`);if(i.type!==`Text`)throw Error(`UTF-8 text selection requires a Text column, got "${e}".`);return{kind:`text_utf8`,column:e,from:t.fromUtf8,to:t.toUtf8}}if(t.to<t.from)throw Error(`Invalid range for column "${e}": to must be >= from.`);if(i.type===`Bytea`)return{kind:`bytes`,column:e,from:t.from,to:t.to};if(i.type===`Text`)return{kind:`text_utf16`,column:e,from:t.from,to:t.to};throw Error(`Range selection requires a bytes or Text column, got "${e}".`)}function $s(e,t={},n,r){let i=e.filter(e=>!Object.hasOwn(t,e)).map(e=>({kind:`full`,column:e})),a=n&&r?Object.entries(t).map(([e,t])=>Qs(e,t,n,r)):[];return i.length+a.length>0?[...i,...a]:null}function ec(e){return e.length>0?[...e]:null}function tc(e,t,n){if(t.table&&t.table!==e.toTable)throw Error(`Include builder for relation "${n}" must target table "${e.toTable}", got "${t.table}".`);if(typeof t.offset==`number`&&t.offset!==0)throw Error(`Include builder for relation "${n}" does not support offset().`);if(t.hops.length>0)throw Error(`Include builder for relation "${n}" does not support hopTo(...).`);if(t.gather)throw Error(`Include builder for relation "${n}" does not support gather(...).`);if(Object.keys(t.partialSelect).length>0)throw Error(`Include builder for relation "${n}" does not support partial large-value selections.`)}function nc(e,t,n,r,i){let a=n.get(t)||[],o=[],s=i?.requireIncludes===!0;for(let[i,c]of Object.entries(e)){let e=a.find(e=>e.name===i);if(!e)throw Error(`Unknown relation "${i}" on table "${t}"`);tc(e,c,i);let l=c.select.length>0?Ws(e.toTable,r,c.select):[],u=c.conditions.map(t=>rc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[hs(e),t===`desc`?`Descending`:`Ascending`]),f=nc(c.includes,e.toTable,n,r,{requireIncludes:c.requireIncludes}),p=ec(l),m=r[t]?.columns.some(e=>e.name===i)?Us(i):i;if(e.type===`forward`){let n=Zs(e,s);o.push({column_name:m,table:e.toTable,inner_column:`id`,outer_column:`${t}.${e.fromColumn}`,filters:u,joins:[],select_columns:p,order_by:d,limit:c.limit??null,...n?{requirement:n}:{},nested_arrays:f})}else o.push({column_name:m,table:e.toTable,inner_column:e.toColumn,outer_column:`${t}.id`,filters:u,joins:[],select_columns:p,order_by:d,limit:c.limit??null,nested_arrays:f})}return o}function rc(e,t,n,r){let i=Gs(hs(e.column),r),a=hs(e.column),o=qs(t,n,a);if(!o)throw Error(`Unknown column "${a}" in table "${n}"`);let s=e.value===void 0?!0:e.value;if(e.op===`isNull`){if(typeof s!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return s?{IsNull:{column:i}}:{IsNotNull:{column:i}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:i}};if(e.op===`ne`)return{IsNotNull:{column:i}}}if(o.type===`Row`&&Es(a)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${a}" only supports eq/ne operators.`);let i=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw Error(`Invalid structured author condition for "${a}".`);return e},o=a===`$createdBy`||a===`$updatedBy`||a===`$deletedBy`,s=o?i(e.value,[`account`,`identity`]):void 0,c=i(s?s.identity:e.value,[`issuer`,`subject`]);if(typeof c.issuer!=`string`||typeof c.subject!=`string`||s&&typeof s.account!=`string`)throw Error(`Invalid structured author condition for "${a}".`);ze(c.issuer,c.subject,s?.account);let l={And:[...s?[{column:`${a}.account`,op:`eq`,value:s.account}]:[],{column:`${a}${o?`.identity`:``}.issuer`,op:`eq`,value:c.issuer},{column:`${a}${o?`.identity`:``}.subject`,op:`eq`,value:c.subject}].map(e=>rc(e,t,n,r))};return e.op===`eq`?l:{Not:l}}if(e.op===`in`||e.op===`notIn`){if(!Array.isArray(e.value))throw Error(`"${e.op}" operator requires an array value.`);if(e.value.some(e=>e===null))throw Error(`"${e.op}" does not accept null membership values; use isNull or isNotNull separately.`);let t={In:{left:i,values:e.value.map(e=>({Literal:Xs(e,o)}))}};return e.op===`notIn`?{Not:t}:t}let c=e.op===`contains`&&o.type===`Array`?o.element:o,l=ic(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:Xs(e.value,c)};if(o.type===`Bytea`&&[`gt`,`gte`,`lt`,`lte`].includes(e.op))throw Error(`BYTEA column "${a}" only supports eq/ne operators.`);if(o.type===`Bytea`&&e.op===`contains`)throw Error(`BYTEA column "${a}" does not support contains filters.`);if(o.type===`Json`&&[`gt`,`gte`,`lt`,`lte`,`contains`].includes(e.op))throw Error(`JSON column "${a}" only supports eq/ne/in/isNull operators.`);switch(e.op){case`eq`:return{Cmp:{left:i,op:`Eq`,right:l}};case`ne`:return{Cmp:{left:i,op:`Ne`,right:l}};case`gt`:return{Cmp:{left:i,op:`Gt`,right:l}};case`gte`:return{Cmp:{left:i,op:`Ge`,right:l}};case`lt`:return{Cmp:{left:i,op:`Lt`,right:l}};case`lte`:return{Cmp:{left:i,op:`Le`,right:l}};case`contains`:return{Contains:{left:i,right:l}};default:throw Error(`Unknown operator: ${e.op}`)}}function ic(e){return typeof e!=`object`||!e?!1:e.__jazz_ir_frontier_row_id===!0}function ac(e,t,n,r){return e.length===0?`True`:e.length===1?rc(e[0],t,n,r):{And:e.map(e=>rc(e,t,n,r))}}function oc(e,t){return t===`True`?e:{Filter:{input:e,predicate:t}}}function sc(e,t,n,r,i){if(n.length===0)return e;let a=e,o=t,s=t;for(let e=0;e<n.length;e+=1){let t=n[e],i=(r.get(o)??[]).find(e=>e.name===t);if(!i)throw Error(`Unknown relation "${t}" on table "${o}"`);let c=`__hop_${e}`,l=i.type===`forward`?{left:Gs(i.fromColumn,s),right:Gs(`id`,c)}:{left:Gs(`id`,s),right:Gs(i.toColumn,c)};a={Join:{left:a,right:{TableScan:{table:i.toTable,alias:c}},on:[l],join_kind:`Inner`}},o=i.toTable,s=c}return{Project:{input:a,columns:Ks(o,s,i)}}}function cc(e,t,n,r,i){if(!i[e.step_table])throw Error(`Unknown gather step table "${e.step_table}"`);if(!Number.isInteger(e.max_depth)||e.max_depth<0)throw Error(`gather(...) max_depth must be a non-negative integer.`);let a=Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[];if(a.length!==1)throw Error(`gather(...) currently requires exactly one hopTo(...) step.`);let o=r.get(e.step_table)??[],s=a[0],c=o.find(e=>e.name===s);if(!c)throw Error(`Unknown relation "${s}" on table "${e.step_table}"`);if(c.type!==`forward`)throw Error(`gather(...) currently only supports forward hopTo(...) relations.`);if(c.toTable!==t)throw Error(`gather(...) step must hop back to "${t}" rows, got "${c.toTable}".`);let l={TableScan:{table:e.step_table}},u=Array.isArray(e.step_conditions)?e.step_conditions:[],d=e.step_table,f=oc(l,ac([...u,{column:hs(e.step_current_column),op:`eq`,value:{__jazz_ir_frontier_row_id:!0}}],i,e.step_table,d)),p=`__recursive_hop_0`;return{Gather:{seed:n,step:{Project:{input:{Join:{left:f,right:{TableScan:{table:c.toTable,alias:p}},on:[{left:Gs(c.fromColumn,e.step_table),right:Gs(`id`,p)}],join_kind:`Inner`}},columns:Ks(t,p,i)}},frontier_key:{RowId:`Current`},bound:{MaxDepth:e.max_depth},dedupe_key:[{RowId:`Current`}]}}}function lc(e,t,n){let r=e;for(let e of t){let t=(n.get(r)??[]).find(t=>t.name===e);if(!t)throw Error(`Unknown relation "${e}" on table "${r}"`);r=t.toTable}return r}function uc(e,t,n,r=!1){if(e.union){let r=e.union.inputs.map(e=>uc(e.input,t,n,!0)),i=r[0];if(!i)throw Error(`union(...) requires at least one seed relation.`);if(r.some(e=>e.outputTable!==i.outputTable))throw Error(`union(...) requires all seed relations to output the same table.`);return{expr:dc({Union:{inputs:e.union.inputs.map((e,t)=>({label:e.label,input:r[t].expr}))}},e,i.outputTable,i.outputTable,n),outputTable:i.outputTable}}if(!e.table)throw Error(`gather(...) seed relation is missing table metadata.`);let i={TableScan:{table:e.table}};i=oc(i,ac(e.conditions??[],n,e.table,e.table));let a=e.table;if(e.gather){let r=e.gather.seed?uc(e.gather.seed,t,n):{expr:i,outputTable:a};i=cc(e.gather,r.outputTable,r.expr,t,n),a=r.outputTable}let o=e.hops??[];i=sc(i,a,o,t,n),a=lc(a,o,t);let s=o.length?`__hop_${o.length-1}`:a;return r&&o.length===0&&!e.gather&&(i={Project:{input:i,columns:Ks(a,s,n)}}),i=dc(i,e,a,s,n),{expr:i,outputTable:a}}function dc(e,t,n,r,i){let a=e;return t.orderBy?.length&&(a={OrderBy:{input:a,terms:mc(t.orderBy,i,n).map(({column:e,direction:t})=>({column:Gs(e,r),direction:t}))}}),t.offset!==void 0&&t.offset>0&&(a={Offset:{input:a,offset:t.offset}}),t.limit!==void 0&&(a={Limit:{input:a,limit:t.limit}}),a}function fc(e,t){let n=Vs(JSON.parse(e)),r=bs(t),i=n.hops;if(n.gather&&Object.keys(n.includes).length>0)throw Error(`gather(...) does not yet support include(...).`);if(i.length>0&&Object.keys(n.includes).length>0)throw Error(`hopTo(...) does not yet support include(...).`);let a,o;if(n.gather?.seed){let e=uc(n.gather.seed,r,t);a=cc(n.gather,e.outputTable,e.expr,r,t),o=e.outputTable,a=oc(a,ac(n.conditions,t,o,o)),a=sc(a,o,i,r,t),o=lc(o,i,r)}else{let e=uc({table:n.table,conditions:n.conditions,hops:n.hops,gather:n.gather,union:n.union},r,t);a=e.expr,o=e.outputTable}if(Array.isArray(n.orderBy)&&n.orderBy.length>0){for(let[e]of n.orderBy){let n=qs(t,o,hs(e));if(n?.type===`Bytea`)throw Error(`BYTEA column "${e}" cannot be used in orderBy().`);if(n?.type===`Json`)throw Error(`JSON column "${e}" cannot be used in orderBy().`)}a={OrderBy:{input:a,terms:n.orderBy.map(([e,t])=>({column:Gs(hs(e),i.length>0?`__hop_${i.length-1}`:o),direction:t===`desc`?`Desc`:`Asc`}))}}}return typeof n.offset==`number`&&n.offset>0&&(a={Offset:{input:a,offset:n.offset}}),typeof n.limit==`number`&&(a={Limit:{input:a,limit:n.limit}}),{relation:a,outputTable:o}}function pc(e){return e.union!==void 0||e.hops.length>0||e.gather!==void 0}function mc(e,t,n){return e.map(([e,r])=>{let i=hs(e),a=qs(t,n,i);if(a?.type===`Bytea`)throw Error(`BYTEA column "${e}" cannot be used in orderBy().`);if(a?.type===`Json`)throw Error(`JSON column "${e}" cannot be used in orderBy().`);return{column:i,direction:r===`desc`?`Desc`:`Asc`}})}function hc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}function gc(e,t,n){return e.map(e=>rc(e,t,n))}function _c(e,t,n){let r=n??Vs(JSON.parse(e)),i=bs(t),a=pc(r)?fc(e,t):void 0,o=a?.outputTable??r.table,s=$s(r.select.length>0?Ws(o,t,r.select):[],r.partialSelect,t,o),c=nc(r.includes,r.table,i,t,{requireIncludes:r.requireIncludes});if(a)return hc({table:o,array_subqueries:c,relation_ir:a.relation,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{}});let l=mc(r.orderBy,t,r.table),u=typeof r.limit==`number`?r.limit:void 0,d=typeof r.offset==`number`?r.offset:void 0;return hc({table:r.table,conditions:gc(r.conditions,t,r.table),array_subqueries:c,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{},...l.length>0?{order_by:l}:{},...u===void 0?{}:{limit:u},...d===void 0?{}:{offset:d}})}function vc(e,t){if(t.union){let n=t.union.inputs[0];if(!n)throw Error(`union(...) requires at least one relation.`);let r=vc(e,n.input);for(let n of t.union.inputs.slice(1))if(vc(e,n.input)!==r)throw Error(`union(...) requires all relations to output the same table.`);return r}let n=t.gather?.seed?vc(e,t.gather.seed):t.table;if(!n)throw Error(`gather(...) seed relation is missing table metadata.`);let r=n;if(t.hops?.length)for(let n of t.hops){let t=e[r]?.relations?.[n];if(!t)throw Error(`Unknown relation "${n}" on table "${r}"`);r=t.table}return r}function yc(e,t){if(e)return e instanceof Map?e.get(t)??e.get(`user_${t}`):e[t]??e[`user_${t}`]}function bc(e,t){return e?e instanceof Map?e.has(t)||e.has(`user_${t}`):t in e||`user_${t}`in e:!1}function xc(e,t,n){let r=G(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return Ws(e,t,n).map(e=>{let t=Es(e);if(t)return{name:e,columnType:t};if(ws(e))return{name:e,columnType:{type:`Boolean`}};let n=r.columns.find(t=>t.name===e);return n?{name:n.name,columnType:n.column_type}:null}).filter(e=>e!==null)}function Sc(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e)){let t=e.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`Invalid Bytea array value. Expected integers in range 0..255.`);return e});return new Uint8Array(t)}throw Error(`Invalid Bytea value. Expected Uint8Array or byte array.`)}function Cc(e,t,n){let r=n.get(e)||[],i=[];for(let[a,o]of Object.entries(t)){let t=r.find(e=>e.name===a);if(!t)throw Error(`Unknown relation "${a}" on table "${e}"`);let s=Cc(t.toTable,o.includes,n);i.push({relation:t,nested:s,nestedRelationNames:s.map(e=>e.relation.name),projection:o.select.length>0?o.select:void 0})}return i}function wc(e,t,n=[],r,i){if(!t)return e;for(let a in t){if(!Object.hasOwn(t,a)||!(a in e)||n.includes(a))continue;let o=t[a];o.computed||(e[a]=r?.has(a)&&(!i||!Object.hasOwn(i,a))?r.get(a):o.from(e[a]))}return e}function Tc(e,t,n,r){if(e.type!==`Array`)return Oc(e);let i=e.value.map(e=>{if(e.type!==`Row`)return Oc(e);let i=e.value.id,a=e.value.values,o=e.value.valuesByColumn;return t.baseColumns??=xc(t.relation.toTable,n,t.projection),Ec(a,n,t.relation.toTable,t.nested,t.baseColumns,i,o,r,t.nestedRelationNames)});return t.relation.isArray?i:i[0]??null}function Ec(e,t,n,r,i,a,o,s,c=[],l=!0){if(!G(t,n))throw Error(`Unknown table "${n}" in schema`);let u={};a!==void 0&&(u.id=a);for(let t=0;t<i.length;t++){let n=i[t];if(!n)continue;let r=bc(o,n.name)?yc(o,n.name):o?void 0:e[t];r!==void 0&&(u[n.name]=Oc(r,n.columnType,n.name))}for(let n=0;n<r.length;n++){let a=r[n];if(!a)continue;let c=Us(a.relation.name),l=bc(o,c)?yc(o,c):bc(o,a.relation.name)?yc(o,a.relation.name):o?void 0:e[i.length+n];if(l===void 0){u[a.relation.name]=a.relation.isArray?[]:null;continue}u[a.relation.name]=Tc(l,a,t,s)}let d=l?s?.[n]:void 0;return d?wc(u,d,c):u}function Dc(e,t){return new Date(e)}function Oc(e,t,n){switch(e.type){case`Text`:if(t?.type===`Json`)try{return JSON.parse(e.value)}catch(e){throw Error(`Invalid stored JSON value: ${e instanceof Error?e.message:String(e)}`)}return e.value;case`Uuid`:return e.value;case`Boolean`:return e.value;case`Integer`:case`Double`:return e.value;case`BigInt`:return typeof e.value==`bigint`?e.value:BigInt(e.value);case`Timestamp`:return Dc(e.value,n);case`Bytea`:return Sc(e.value);case`Null`:return null;case`Array`:return t?.type===`Array`?e.value.map(e=>Oc(e,t.element)):e.value.map(e=>Oc(e));case`Row`:return t?.type===`Row`&&n&&(Ts(n)||n===`$deletedBy`||n.startsWith(`$deletedBy.`))?Object.fromEntries(t.columns.map((t,r)=>[t.name,Oc(e.value.values[r],t.column_type,`${n}.${t.name}`)])):t?.type===`Row`?e.value.values.map((e,n)=>Oc(e,t.columns[n]?.column_type)):e.value.values.map(e=>Oc(e))}}function kc(e,t,n,r){if(!G(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Cc(t,Bs(n),r??bs(e));return{includePlans:i,includedRelationNames:i.map(e=>e.relation.name)}}function Ac(e,t,n,r,i,a,o){return e.baseColumns??=xc(r,n,i),Ec(t.values,n,r,e.includePlans,e.baseColumns,t.id,t.valuesByColumn,a,e.includedRelationNames,o)}function jc(e,t,n,r={},i,a,o=!0){let s=kc(t,n,r);return e.map(e=>Ac(s,e,t,n,i,a,o))}function Mc(e,t,n={},r,i,a=!0,o){let s;return c=>(s??=kc(e,t,n,o),Ac(s,c,e,t,r,i,a))}function Nc(e,t,n,r={},i,a,o=!0){let s=jc([e],t,n,r,i,a,o)[0];if(s===void 0)throw Error(`Failed to transform row for table "${n}"`);return s}var Pc=class{failClosed;pending;error;failed=!1;get failure(){return this.error}set failure(e){this.failed=!0,this.error=e}cancelled=!1;constructor(e=!1){this.failClosed=e}run(e){let t=()=>{if(this.failed)throw this.failure;return e()},n=this.pending?this.pending.then(t):t();if(n instanceof Promise){let e=n.then(()=>{},e=>{this.failClosed&&(this.failure=e)});this.pending=e,e.then(()=>{this.pending===e&&(this.pending=void 0)})}return n}async drain(){if(await this.pending,this.failed)throw this.failure}},Fc=new WeakMap;function Ic(e){return Fc.get(e.preparationOwner?.()??e)}function Lc(e){let t=e.preparationOwner?.()??e,n=Fc.get(t);return n||Fc.set(t,n=new Pc),n}function q(e,t){let n=Ic(e);if(n?.pending)return n.run(t);let r=t();return r instanceof Promise?Lc(e).run(()=>r):r}function Rc(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`?t:void 0}var zc=new Set([`schema`,`query`,`write_rejected`,`transaction_conflict`,`storage`,`protocol`,`backpressure`,`not_observed`,`historical_read_requires_server`,`unsupported_storage_codecs`,`authority_changed`,`store_opened_without_migrations`]);function Bc(e){let t=Rc(e);return t!==void 0&&zc.has(t)?t:void 0}var Vc=new Set([`authorization_denied`,`client_clock_too_far_ahead`,`serialization_conflict`,`row_already_deleted`,`row_already_exists`,`row_not_deleted`,`missing_required`,`branch_move`,`missing_chunks`,`predecessor_rejected`,`schema_version_not_deployed`,`identity_mismatch`]);function Hc(e){if(!e||typeof e!=`object`)return;let t=e.reason;return typeof t==`string`&&Vc.has(t)?t:void 0}function Uc(e,t){let n=e.toUpperCase();return Object.assign(Error(`${e} failed: WriteError("authorization_denied: read policy denied ${n} on table ${t}: the row does not exist or the session may not read it")`),{code:`permission_denied`})}function Wc(e,t,n,r){let i=n.filter(e=>!e.name.startsWith(Hs)),a=new Map;for(let e of i)a.set(e.name,r[e.name]??e.default??{type:`Null`});return Object.defineProperty({table:e,id:t,values:i.filter(e=>!Ts(e.name)).map(e=>a.get(e.name))},`valuesByColumn`,{value:a,configurable:!0})}var Gc=new WeakMap;function Kc(e){let t=Gc.get(e);return t||(t=Object.keys(e).filter(t=>e[t].computed),Gc.set(e,t)),t}var qc=class extends Error{constructor(e){super(`Computed dependency "${e}" is unavailable.`)}},Jc=new WeakMap,Yc=class{dependencies=new Map;version=0;observedColumns(e){let t=this.dependencies.get(e);return t||(t=new Set(Jc.get(e)),this.dependencies.set(e,t)),t}observe(e,t){let n=this.observedColumns(e);if(!n.has(t)){n.add(t),this.version++;let r=Jc.get(e);r||Jc.set(e,r=new Set),r.add(t)}}storedColumns(e,t){let n=new Set,r=new Set,i=t=>{if(r.has(t))return;r.add(t);let a=Object.hasOwn(e,t)?e[t]:void 0;if(a?.computed)for(let e of this.observedColumns(a))i(e);else n.add(t)};return i(t),n}};function Xc(e,t,n){if(e===t)return!0;if(typeof e!=`object`||!e||ArrayBuffer.isView(e)||n?.has(e))return!1;if((n??=new Set).add(e),e instanceof Map){for(let[r,i]of e)if(Xc(r,t,n)||Xc(i,t,n))return!0}else if(e instanceof Set){for(let r of e)if(Xc(r,t,n))return!0}for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);if(i&&`value`in i&&Xc(i.value,t,n))return!0}return!1}function Zc(e,t,n,r,i){let a=new Map,o=new Set,s,c=e=>{if(!Object.hasOwn(n,e)||i&&Object.hasOwn(i,e))throw s=new qc(e),s;return n[e]},l=t=>{if(s)throw s;if(a.has(t))return a.get(t);if(o.has(t))throw Error(`Cyclic computed dependency at "${t}".`);o.add(t);try{let n=Object.hasOwn(e,t)?e[t]:void 0,i;if(n?.computed){let e=n.rowColumns??[],a,o=()=>{throw TypeError(`Computed callback rows are read-only.`)},c=i=>{if(a)return Reflect.get(a,i);if(!e.includes(i)){if(Object.hasOwn(Object.prototype,i))return Reflect.get(Object.prototype,i);if(i===`toJSON`)return;if(i===t)return l(i);throw Error(`Unknown computed dependency "${i}".`)}return r?.observe(n,i),l(i)},u=new Proxy(Object.create(null),{get:(e,t)=>typeof t==`string`?c(t):void 0,has:(t,n)=>typeof n==`string`&&e.includes(n),ownKeys:()=>[...e],getOwnPropertyDescriptor:(t,n)=>typeof n==`string`&&e.includes(n)?{configurable:!0,enumerable:!0,get:()=>c(n)}:void 0,set:o,deleteProperty:o,defineProperty:o,setPrototypeOf:o,preventExtensions:o});try{i=n.from(void 0,u)}catch(e){throw s??e}if(i&&(typeof i==`object`||typeof i==`function`)&&`then`in i&&typeof i.then==`function`)throw Promise.resolve(i).catch(()=>{}),TypeError(`Computed field "${t}" must return synchronously.`);if(s)throw s;Xc(i,u)&&(a={...u},i===u&&(i=a))}else{let e=c(t);i=n?n.from(e):e}return a.set(t,i),i}finally{o.delete(t)}};for(let e of t)l(e);return a}var Qc=-(1n<<63n),$c=(1n<<63n)-1n,el=-2147483648,tl=2147483647;function nl(e){let t=Number(e);if(!Number.isInteger(t)||t<el||t>tl)throw Error(`Integer values must be signed 32-bit integers between ${el} and ${tl}; received ${String(e)}`);return t}function rl(e){let t=typeof e==`bigint`?e:typeof e==`number`&&Number.isSafeInteger(e)?BigInt(e):null;if(t==null)throw Error(`Invalid BigInt value. Expected bigint or safe integer number.`);if(t<Qc||t>$c)throw Error(`Invalid BigInt value. Expected signed 64-bit integer range.`);return t}function il(e){let t=e instanceof Date?e.getTime():Number(e);if(!Number.isFinite(t))throw Error(`Invalid timestamp value. Expected Date or finite number.`);return t}function al(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e)){let t=e.map(e=>{let t=Number(e);if(!Number.isInteger(t)||t<0||t>255)throw Error(`Bytea arrays must contain integers in range 0..255`);return t});return new Uint8Array(t)}throw Error(`Expected Uint8Array or byte array for Bytea column type`)}function ol(e,t){if(e==null)return{type:`Null`};switch(t.type){case`Text`:return{type:`Text`,value:String(e)};case`Boolean`:return{type:`Boolean`,value:!!e};case`Integer`:return{type:`Integer`,value:nl(e)};case`BigInt`:return{type:`BigInt`,value:rl(e)};case`Double`:return{type:`Double`,value:Number(e)};case`Timestamp`:return{type:`Timestamp`,value:il(e)};case`Uuid`:return{type:`Uuid`,value:String(e)};case`Bytea`:return{type:`Bytea`,value:al(e)};case`Json`:return{type:`Text`,value:gs(e)};case`Enum`:{let n=String(e);if(!t.variants.includes(n))throw Error(`Invalid enum value "${n}". Expected one of: ${t.variants.join(`, `)}`);return{type:`Text`,value:n}}case`Array`:{if(!Array.isArray(e))throw Error(`Expected array for Array column type, got ${typeof e}`);let n=t.element;return{type:`Array`,value:e.map(e=>ol(e,n))}}case`Row`:{if(typeof e!=`object`||!e)throw Error(`Expected object for Row column type, got ${typeof e}`);let n=e;return{type:`Row`,value:{values:t.columns.map(e=>ol(n[e.name],e.column_type))}}}default:throw Error(`Unsupported column type: ${t.type}`)}}function sl(e,t,n){let r=t[n];if(!r)throw Error(`Unknown table "${n}"`);let i={};for(let[t,a]of Object.entries(e)){if(a===void 0)continue;let e=r.columns.find(e=>e.name===t);if(!e)throw Error(`Unknown column "${t}" on table "${n}"`);if(a===null&&!e.nullable)throw Error(`Cannot set required field '${t}' to null`);e.column_type.type===`Json`&&cl(t,a,e.column_type.schema),i[t]=ol(a,e.column_type)}return i}function cl(e,t,n){if(!n)return;let r=ll(t,n);if(r)throw Error(`encoding error: JSON schema validation failed for column \`${e}\`: ${r}`)}function ll(e,t){let n=t.type;if(n===`object`){if(typeof e!=`object`||!e||Array.isArray(e))return`${JSON.stringify(e)} is not an object`;let n=e,r=ul(t),i=new Set(dl(t.required));for(let e of i)if(!Object.hasOwn(n,e))return`missing required property ${JSON.stringify(e)}`;if(t.additionalProperties===!1){for(let e of Object.keys(n))if(!Object.hasOwn(r,e))return`unexpected property ${JSON.stringify(e)}`}for(let[e,t]of Object.entries(r))if(Object.hasOwn(n,e)){let r=ll(n[e],t);if(r)return r}return null}if(n===`string`){if(typeof e!=`string`)return`${JSON.stringify(e)} is not a string`;let n=fl(t.minLength);if(n!=null&&e.length<n)return`${JSON.stringify(e)} is shorter than ${n} character${n===1?``:`s`}`;let r=fl(t.maxLength);if(r!=null&&e.length>r)return`${JSON.stringify(e)} is longer than ${r} characters`;let i=pl(t.pattern);return i&&!new RegExp(i).test(e)?`${JSON.stringify(e)} does not match ${JSON.stringify(ml(i))}`:null}if(n===`integer`){if(typeof e!=`number`||!Number.isInteger(e))return`${JSON.stringify(e)} is not an integer`;let n=fl(t.minimum);if(n!=null&&e<n)return`${e} is less than the minimum of ${n}`;let r=fl(t.maximum);return r!=null&&e>r?`${e} is greater than the maximum of ${r}`:null}return null}function ul(e){return typeof e.properties!=`object`||e.properties===null||Array.isArray(e.properties)?{}:Object.fromEntries(Object.entries(e.properties).filter(e=>{let[,t]=e;return typeof t==`object`&&!!t&&!Array.isArray(t)}))}function dl(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function fl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function pl(e){return typeof e==`string`?e:null}function ml(e){return e.replaceAll(`\\d`,`[0-9]`)}var hl=1e3,gl=5*6e4;function _l(e){return Math.min(gl,hl*2**Math.min(e,20))}var vl=class{streak=0;next(){let e=this.streak++;return e===0?0:_l(e-1)}reset(){this.streak=0}},yl=new WeakMap;function bl(e){let t=yl.get(e);if(t?.size)for(let e of[...t])try{e()}catch(e){console.error(`Jazz local write observer failed`,e)}}var xl=Symbol.for(`jazz-tools.shippedMigrations`);function Sl(e){return e[xl]}function Cl(e){return!!e.adminSecret}function wl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,policies:void 0}]))}var Tl=new WeakMap;function El(e){let t=Tl.get(e);if(t)return t;let n=wl(e);return Tl.set(e,n),n}var Dl=class{host;client=null;clientSchema=null;disposeRuntimeTelemetry=null;remoteLinkHintBinding=null;clientCreatedListeners=new Set;syncStatusListeners=new Set;syncStatusBinding=null;foregroundNodeLease;constructor(e){this.host=e}getClient(e){let{config:t,runtimeSource:n}=this.host,r=n.supportsPolicyBypass&&Cl(t)?El(e):e,i=qe(r);if(this.client){if(!this.clientSchema||qe(this.clientSchema)!==i)throw Error(`Db is already initialized with a different schema. Create a separate Db for each schema/app.`);return this.client}this.installRuntimeTelemetry();let a={...t};es(t,a),l(a,A(t));let o=n.createClient({config:a,schema:r,migrations:Sl(e),onAuthFailure:e=>this.host.markUnauthenticated(e),foregroundNodeLease:this.foregroundNodeLease});o.onMutationError(e=>this.host.onMutationError(e)),pe(o,e=>this.host.renewsCredential?.(e)===!0),this.client=o,this.clientSchema=r,this.bindRemoteLinkHint(o),this.bindSyncStatus(),this.onClientCreated({schemaKey:i,schema:r,client:o});for(let e of[...this.clientCreatedListeners])e();return o}getCurrentClient(){return this.client}getRuntimeSchema(){return this.client?.getSchema()??null}get clientEntry(){return!this.client||!this.clientSchema?null:{schemaKey:qe(this.clientSchema),schema:this.clientSchema,client:this.client}}onClientCreated(e){}explicitOfflineListeners=new Set;onExplicitOfflineChange(e,t){t.aborted||(this.explicitOfflineListeners.add(e),t.addEventListener(`abort`,()=>this.explicitOfflineListeners.delete(e),{once:!0}))}publishExplicitOfflineState(){let e=this.isExplicitlyOffline();for(let t of[...this.explicitOfflineListeners])t(e)}remoteLinkState(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?`none`:this.isExplicitlyOffline()?`unavailable`:this.transportLinkState()}transportLinkState(){let e=this.getCurrentClient()?.getRuntime().remoteLinkState?.()??`connecting`;return e===`none`?`connecting`:e}onRemoteLinkStateChange(e,t){if(t.aborted)return;let n=this.remoteLinkState(),r=()=>{if(t.aborted)return;let r=this.remoteLinkState();r!==n&&(n=r,e(r))};this.onExplicitOfflineChange(r,t),this.onTransportLinkStateChange(r,t)}bindRemoteLinkHint(e){this.remoteLinkHintBinding?.abort();let t=e.getRuntime?.();if(!t?.setRemoteLinkHint)return;let n=new AbortController;this.remoteLinkHintBinding=n;let r=e=>{n.signal.aborted||t.setRemoteLinkHint?.(e)};this.onRemoteLinkStateChange(r,n.signal),r(this.remoteLinkState())}onTransportLinkStateChange(e,t){if(t.aborted)return;let n=()=>{this.getCurrentClient()?.getRuntime().onRemoteLinkStateChange?.(e,t),e()};if(this.getCurrentClient()){n();return}let r=()=>this.clientCreatedListeners.delete(i),i=()=>{r(),t.removeEventListener(`abort`,r),t.aborted||n()};this.clientCreatedListeners.add(i),t.addEventListener(`abort`,r,{once:!0})}syncStatus(){let e=this.linkStatus();if(e.state===`local-only`)return ds(e);let t=this.client?.getRuntime();return ds(e,t?.uploadStatus?.()??ns,t?.lastLinkFailure?.()??null)}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?os:this.isExplicitlyOffline()?K(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??ss;return e.state===`local-only`?ss:e}onSyncStatusChange(e,t){t.aborted||(this.syncStatusListeners.add(e),t.addEventListener(`abort`,()=>{this.syncStatusListeners.delete(e),this.syncStatusListeners.size===0&&this.unbindSyncStatus()},{once:!0}),this.onExplicitOfflineChange(e,t),this.bindSyncStatus())}notifySyncStatus(){for(let e of[...this.syncStatusListeners])e()}bindSyncStatus(){if(this.syncStatusBinding||!this.client||this.syncStatusListeners.size===0)return;let e=new AbortController;this.syncStatusBinding=e,this.client.getRuntime().onSyncStatusChange?.(()=>this.notifySyncStatus(),e.signal),this.notifySyncStatus()}unbindSyncStatus(){this.syncStatusBinding?.abort(),this.syncStatusBinding=null}async waitForSync(e){let t=this.getCurrentClient()?.getRuntime();if(!(!t||this.linkStatus().state===`local-only`)){if(!t.waitForPendingWrites)throw Error(`Runtime does not support waiting for sync`);await t.waitForPendingWrites(`global`,{throughOutage:!0,signal:e,sync:{}})}}initialExplicitOfflineState(){return null}openInspectorControlPort(e){return Promise.reject(Error(`This runtime has no shared browser worker`))}refreshAccountAuth(e,t){let n={mode:`bearer`,jwtToken:e,trustedReservedSession:t};this.host.runtimeSource.refreshAccountToken(e)?this.client?.acceptAuthUpdate(n):(this.host.runtimeSource.assertAuthUpdateAllowed(),this.updateAuth(n))}updateAuth(e){if(e.mode===`bearer`){e.jwtToken&&e.trustedReservedSession?this.client?.updateTrustedAuthToken(e.jwtToken,e.trustedReservedSession):this.client?.updateAuthToken(e.jwtToken);return}this.client?.updateCookieSession(e.cookieSession)}async storePendingUploads(){}isUsable(){return!0}async shutdownClient(){try{await this.client?.shutdown()}finally{this.clearClient()}}clearClient(){this.remoteLinkHintBinding?.abort(),this.remoteLinkHintBinding=null,this.unbindSyncStatus();let e=this.client!==null;this.client=null,this.clientSchema=null,e&&this.notifySyncStatus()}detachClient(){let e=this.client;return this.clearClient(),e}telemetryCollectorUrl(){return ti()??this.host.config.telemetryCollectorUrl}installRuntimeTelemetry(){let e=this.telemetryCollectorUrl();!e||this.disposeRuntimeTelemetry||(this.disposeRuntimeTelemetry=this.host.runtimeSource.installTelemetry?.({config:this.host.config,collectorUrl:e,runtimeThread:`main`})??null)}async waitForPendingWrites(e={}){let t=this.getCurrentClient()?.getRuntime();if(t){if(!t.waitForPendingWrites)throw Error(`Runtime does not support graceful sync shutdown`);await t.waitForPendingWrites(`global`,{inFlightStreams:e.inFlightStreams})}}async shutdown(){this.disposeRuntimeTelemetry?.(),this.disposeRuntimeTelemetry=null,await this.shutdownClient()}},Ol=class extends Dl{isDisconnected=!1;awaitingCredential=!1;reconnectWaiters=new Set;transportTransition=Promise.resolve();constructor(e){super(e)}async start(){this.foregroundNodeLease=await this.host.runtimeSource.acquireForegroundNodeLease(this.host.config)}async shutdown(){let e=this.foregroundNodeLease;this.foregroundNodeLease=void 0;let t=this.getCurrentClient();try{if(e){let n=t?.getRuntime();n?n.quiesceForegroundTxTimeHighWater?await e.returnWithHighWater(await n.quiesceForegroundTxTimeHighWater()):await e.retire():await e.returnWithHighWater(e.confirmedTxTime)}}catch{await e?.retire().catch(()=>void 0)}finally{await super.shutdown()}}onClientCreated({client:e}){if(this.isExplicitlyOffline()){if(this.host.runtimeSource?.nativeConnection)return;this.enqueueTransportTransition(()=>e.disconnectTransport()).catch(()=>void 0);return}this.connectClient(e)}connectClient(e,t=this.host.config){let{config:n}=this.host;if(this.host.runtimeSource?.nativeConnection||!n.serverUrl)return;let r={jwt_token:t.jwtToken,admin_secret:n.adminSecret,backend_session:t.cookieSession};this.awaitingCredential=!r.jwt_token&&!r.admin_secret&&!r.backend_session,!this.awaitingCredential&&e.connectTransport(n.serverUrl,r)}updateAuth(e){super.updateAuth(e);let t=this.clientEntry?.client;!this.awaitingCredential||!t||this.isExplicitlyOffline()||this.connectClient(t,e.mode===`bearer`?{jwtToken:e.jwtToken}:{cookieSession:e.cookieSession})}async ensureReady(e,t){if(e!==`runtime`)for(;;){for(await this.host.runtimeSource?.nativeConnection?.waitForTransportTransition?.();this.isExplicitlyOffline();)if(await this.waitForReconnect(t),t?.aborted)return;if(await this.transportTransition,!this.isExplicitlyOffline()||t?.aborted)return}}shouldDeferSubscriptionStart(e){return!1}isExplicitlyOffline(){return this.host.runtimeSource?.nativeConnection?.isExplicitlyOffline?.()??this.isDisconnected}onExplicitOfflineChange(e,t){let n=this.host.runtimeSource?.nativeConnection;if(n?.onExplicitOfflineChange){n.onExplicitOfflineChange(e,t);return}super.onExplicitOfflineChange(e,t)}async waitForReconnect(e){if(e?.aborted)return;let t=this.host.runtimeSource?.nativeConnection;if(t?.waitForReconnect){await t.waitForReconnect(e);return}!this.isDisconnected&&(await this.transportTransition,!this.isDisconnected)||await new Promise(t=>{let n=()=>{this.reconnectWaiters.delete(n),e?.removeEventListener(`abort`,r),t()},r=()=>n();e?.addEventListener(`abort`,r,{once:!0}),this.reconnectWaiters.add(n)})}async disconnect(){if(!this.host.config.serverUrl&&!this.host.runtimeSource?.nativeConnection?.configured())throw Error(`Db.disconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{this.host.runtimeSource?.nativeConnection?await this.host.runtimeSource?.nativeConnection.disconnect():await this.clientEntry?.client.disconnectTransport(),this.isDisconnected=!0,this.publishExplicitOfflineState()})}async reconnect(){if(!this.host.config.serverUrl&&!this.host.runtimeSource?.nativeConnection?.configured())throw Error(`Db.reconnect() requires a configured serverUrl.`);if(await this.enqueueTransportTransition(async()=>{let e=this.clientEntry?.client;this.host.runtimeSource?.nativeConnection?await this.host.runtimeSource?.nativeConnection.reconnect():e&&this.connectClient(e),this.isDisconnected=!1,this.publishExplicitOfflineState()}),!this.isDisconnected){let e=Array.from(this.reconnectWaiters);this.reconnectWaiters.clear();for(let t of e)t()}}enqueueTransportTransition(e){let t=this.transportTransition.then(e,e);return this.transportTransition=t.catch(()=>void 0),t}async deleteClientStorage(){if((this.host.config.driver??{type:`persistent`}).type!==`persistent`)throw Error(`deleteClientStorage() is only available when driver.type='persistent'.`);let e=this.getCurrentClient();if(typeof window>`u`&&!e?.supportsClientStorageReset()){console.error(`deleteClientStorage() is only available in browser runtimes.`);return}let t=e??this.getClient({});try{let e=await t.clearClientStorage();return await t.shutdown(),e}finally{this.clearClient()}}},kl=`jazz:indexeddb-invalidation-reload`,Al=1e4;function jl(e={}){let t=(e.now??Date.now)();try{let n=e.storage??globalThis.sessionStorage,r=Number(n.getItem(kl)??0);if(Number.isFinite(r)&&t-r<Al)return!1;n.setItem(kl,String(t))}catch{}return(e.reload??(()=>globalThis.location.reload()))(),!0}async function Ml(e){let t=!1,n;for(let r of e)try{await r()}catch(e){t||(t=!0,n=e)}if(t)throw n}var Nl=`store_held_by_another_tab`,Pl=class extends Error{name=`StoreHeldByAnotherTabError`;code=Nl;constructor(e=`Another tab holds this account's local store under another sign-in: close or reload that other tab. This tab joins once it lets go; reloading this tab first loses its unsynced writes`,t){super(e,t)}},Fl=Symbol.for(`jazz.browser-inspector-control-registry`);function Il(){let e=globalThis;return e[Fl]??={factories:new Map,nextFactoryId:1}}function Ll(e,t){e.getConfig=t;let n=Il(),r=n.nextFactoryId++;return n.factories.set(r,e),()=>n.factories.delete(r)}var Rl=[],zl=!1,Bl=Promise.resolve(),Vl=!1;function Hl(e){return typeof window>`u`||typeof window.addEventListener!=`function`?()=>{}:(Ul(),Rl.push(e),()=>{let t=Rl.indexOf(e);t!==-1&&Rl.splice(t,1)})}function Ul(){Vl||(Vl=!0,window.addEventListener(`pagehide`,e=>{e.persisted&&Wl()}),window.addEventListener(`pageshow`,e=>{e.persisted&&Gl()}))}function Wl(){if(!zl){zl=!0;for(let e of[...Rl])try{e.leave()}catch(e){console.warn(`Jazz could not let go of a page lock for the back/forward cache.`,e)}}}function Gl(){if(!zl)return;zl=!1;let e=[...Rl];Bl=Bl.then(async()=>{for(let t of e){if(zl)return;if(Rl.includes(t))try{if(await t.return()===`stop`)return}catch(e){console.warn(`Jazz could not take a page lock again after the back/forward cache.`,e)}}})}var Kl=class e extends Dl{earlyLease;connection=null;connectionReady=null;initialExplicitOfflineStateKnown=!1;connectionError=null;disconnected=!1;workerRemoteLink=`connecting`;workerLinkStatus=null;workerRemoteLinkListeners=new Set;reconnectWaiters=new Set;transportTransition=Promise.resolve();storageReset=null;storageResetError=null;connectionScope=null;unregisterInspectorControl=null;browserConnectionInput=null;recoverableConnectionFailure=!1;workerRecoveryTimer=null;workerRecoveryDelayMs=250;observedConfigurationAdmissionFailure=null;configurationAdmissionRetry=null;readinessByConnection=new WeakMap;replacementWaiters=new Set;heldPatienceTimer=null;heldTooLong=!1;pageAway=null;stopHoldingAcrossPageCache=null;shutdownStarted=!1;shutdownFailure=null;constructor(e,t){super(e),this.earlyLease=t}async start(){this.foregroundNodeLease=await(this.earlyLease??this.host.runtimeSource.acquireBrowserForegroundNodeLease(this.host.config))}getClient(e){if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);if(this.storageResetError)throw this.storageResetError;if(this.storageReset)throw Error(`Browser storage reset is still in progress`);return super.getClient(e)}onClientCreated(e){this.browserConnectionInput=e,this.openBrowserWorkerConnection(),this.stopHoldingAcrossPageCache??=Hl({leave:()=>this.leaveForPageCache(),return:()=>this.returnFromPageCache()})}leaveForPageCache(){let e=this.connection;if(!e||this.pageAway||this.shutdownStarted||this.host.isShuttingDown||this.storageReset||this.recoverableConnectionFailure||this.configurationAdmissionRetry||this.connectionScope?.inspectorAttachment||!e.leaveForPageCache?.())return;let t;this.pageAway={left:e,reopened:new Promise(e=>t=e),reopen:t},this.clearWorkerRecoveryTimer(),this.unregisterInspectorControl?.(),this.unregisterInspectorControl=null,this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.initialExplicitOfflineStateKnown=!1}returnFromPageCache(){let e=this.pageAway;if(e){if(this.pageAway=null,this.shutdownStarted||this.host.isShuttingDown||!this.browserConnectionInput){e.reopen(null);return}if(e.left.storeChangedSinceLeaving?.())return this.connectionError=Error(`This page's store was reset while the page was in the back/forward cache: reload the page`),jl(),e.reopen(null),`stop`;try{e.reopen(this.openBrowserWorkerConnection())}catch(t){throw e.reopen(null),t}}}openBrowserWorkerConnection(){if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);let e=this.browserConnectionInput;if(!e)throw Error(`Browser worker connection requires an initialized client`);this.host.clearAuthenticatedInspectorLocalReads();let t={...this.host.config};es(this.host.config,t),l(t,A(this.host.config));let n,r=this.host.runtimeSource.createBrowserWorkerConnection({config:t,schema:e.schema,client:e.client,onAuthFailure:t=>{lt(e.client,t),this.host.markUnauthenticated(t)},onAuthRestored:()=>this.host.clearAuthError(),onExplicitOfflineChange:e=>this.setExplicitOffline(r,e),onRemoteLinkChange:(e,t)=>this.setWorkerRemoteLink(r,e,t),onFailure:e=>this.observeConnectionFailure(r,s(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r)});n={connection:r,lease:this.foregroundNodeLease,inspectorAttachment:t.runtimeSources?.inspectorBinding!==void 0,resetReason:null,leaseWorkerReplaced:!1},this.connectionScope=n,this.connection=r,this.wakeReplacementWaiters(),this.setWorkerRemoteLink(r,`connecting`),this.observedConfigurationAdmissionFailure=null,this.unregisterInspectorControl?.(),this.unregisterInspectorControl=Ll(e=>r.openInspectorControlPort(e),()=>this.host.config),this.initialExplicitOfflineStateKnown=!1;let i=r.ready();if(this.readinessByConnection.set(r,i),this.connectionReady=i.then(()=>{let e=r.getWorkerRealmId?.();if(n.leaseWorkerReplaced=e!==void 0&&n.lease?.workerRealmId!==void 0&&e!==n.lease.workerRealmId,this.connection!==r)return;let t=r.getAuthenticatedInspectorAttachmentPhysicalDbName?.();t&&this.host.enableAuthenticatedInspectorLocalReads(t),this.initialExplicitOfflineStateKnown=!0,this.connectionError=null,this.recoverableConnectionFailure=!1,this.clearWorkerRecoveryTimer(),this.workerRecoveryDelayMs=250,this.clearHeldPatience()},e=>{this.observeConnectionFailure(r,s(e)),this.connection}),this.disconnected){let e=this.connectionReady;this.enqueueTransportTransition(async()=>{await e,await r.disconnect()}).catch(()=>void 0)}return r}observeConnectionFailure(e,t){if(this.shutdownFailure?.connection===e){t instanceof $e&&this.shutdownFailure.abandon(t);return}if(this.connection!==e)return;this.connectionError=t,this.recoverableConnectionFailure=!0,this.rejectReconnectWaiters(t),this.notifyWorkerRemoteLink();let n=this.admissionRefused(e);n?this.startHeldPatience():t instanceof $e||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof $e||n)&&this.scheduleWorkerRecovery(e)}static HELD_BY_ANOTHER_TAB_PATIENCE_MS=3e4;startHeldPatience(){this.heldPatienceTimer!==null||this.heldTooLong||(this.heldPatienceTimer=setTimeout(()=>{this.heldPatienceTimer=null,!(this.shutdownStarted||this.host.isShuttingDown)&&(this.heldTooLong=!0,this.wakeReplacementWaiters(),this.notifyWorkerRemoteLink())},e.HELD_BY_ANOTHER_TAB_PATIENCE_MS))}clearHeldPatience(){this.heldPatienceTimer!==null&&clearTimeout(this.heldPatienceTimer),this.heldPatienceTimer=null,this.heldTooLong&&(this.heldTooLong=!1,this.notifyWorkerRemoteLink())}admissionRefused(e){return!!e?.waitsForAnotherSignIn?.()}replacementOf(e,t){return new Promise(n=>{let r=()=>{this.connection===e&&!this.heldTooLong&&!this.shutdownStarted&&!this.host.isShuttingDown&&!t?.aborted||(this.replacementWaiters.delete(r),t?.removeEventListener(`abort`,r),n())};this.replacementWaiters.add(r),t?.addEventListener(`abort`,r,{once:!0}),r()})}wakeReplacementWaiters(){for(let e of[...this.replacementWaiters])e()}scheduleWorkerRecovery(e){if(this.workerRecoveryTimer!==null||this.shutdownStarted||this.host.isShuttingDown||this.storageReset||this.connectionScope?.inspectorAttachment&&!this.admissionRefused(e))return;let t=this.workerRecoveryDelayMs;this.workerRecoveryDelayMs=Math.min(t*2,3e4),this.workerRecoveryTimer=setTimeout(()=>{this.workerRecoveryTimer=null,this.enqueueTransportTransition(async()=>{if(!(this.connection!==e||this.shutdownStarted||this.host.isShuttingDown||this.storageReset)){if(this.admissionRefused(e)){await this.retryConfigurationAdmission(e),await this.connectionReady;return}this.connectionError instanceof $e&&(this.reopenFailedFollower(),await this.connectionReady)}}).catch(e=>{this.connectionError??=s(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.host.isShuttingDown||t?.aborted)return;let n=this.storageReset,r=n?null:this.connection,i=r!==null&&this.observedConfigurationAdmissionFailure===r;if(await n,this.storageResetError)throw this.storageResetError;if(!(this.host.isShuttingDown||t?.aborted)&&(r??=this.connection??await this.pageAway?.reopened??await this.configurationAdmissionRetry,i&&r&&(r=await this.retryConfigurationAdmission(r)),!(this.host.isShuttingDown||t?.aborted))){for(;;)try{await(r?this.readinessByConnection.get(r):this.connectionReady);break}catch(e){if(r&&this.admissionRefused(r)&&!t?.aborted){if(this.heldTooLong)throw new Pl(void 0,{cause:e});if(await this.replacementOf(r,t),this.host.isShuttingDown||this.shutdownStarted||t?.aborted)return;r=this.connection??await this.configurationAdmissionRetry;continue}throw r===this.connection&&r?.canRetryInitialConfigurationAdmission?.()&&(this.observedConfigurationAdmissionFailure=r),e}if(await this.connectionReady,!this.host.isShuttingDown){if(this.connectionError)throw this.connectionError;if(e!==`runtime`)for(;;){for(;this.disconnected;)if(await this.waitForReconnect(t),this.host.isShuttingDown||t?.aborted)return;if(await this.transportTransition,!this.disconnected||this.host.isShuttingDown||t?.aborted)break}this.host.config.serverUrl&&e===`server`&&await this.connection?.waitForServerConnection()}}}retryConfigurationAdmission(e){if(this.configurationAdmissionRetry)return this.configurationAdmissionRetry;if(e!==this.connection)return Promise.resolve(this.connection);let t=(async()=>(await e.shutdown(),this.host.isShuttingDown||e!==this.connection?null:(this.connection=null,this.connectionReady=null,this.connectionError=null,this.observedConfigurationAdmissionFailure=null,this.openBrowserWorkerConnection())))();return this.configurationAdmissionRetry=t,t.finally(()=>{this.configurationAdmissionRetry===t&&(this.configurationAdmissionRetry=null)}).catch(()=>void 0),t}shouldDeferSubscriptionStart(e){return e===`server`}isExplicitlyOffline(){return this.disconnected}initialExplicitOfflineState(){return this.initialExplicitOfflineStateKnown?null:this.connectionReady}async waitForReconnect(e){if(!e?.aborted){if(!this.disconnected){if(await this.transportTransition,this.connectionError)throw this.connectionError;if(!this.disconnected)return}await new Promise((t,n)=>{let r=!1,i=o=>{r||(r=!0,this.reconnectWaiters.delete(i),e?.removeEventListener(`abort`,a),o?n(o):t())},a=()=>i();e?.addEventListener(`abort`,a,{once:!0}),this.reconnectWaiters.add(i),e?.aborted?i():this.connectionError&&i(this.connectionError)})}}async disconnect(){if(!this.host.config.serverUrl)throw Error(`Db.disconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{await this.connectionReady,await this.connection?.disconnect(),this.disconnected=!0,this.publishExplicitOfflineState()})}async reconnect(){if(!this.host.config.serverUrl)throw Error(`Db.reconnect() requires a configured serverUrl.`);await this.enqueueTransportTransition(async()=>{if(this.shutdownStarted)throw Error(`Browser connection manager is shut down`);if(this.pageAway&&await this.pageAway.reopened,this.recoverableConnectionFailure&&this.reopenFailedFollower(),await this.connectionReady,this.connectionError)throw this.connectionError;let e=this.connection;if(!e)throw Error(`Browser worker connection is unavailable`);await e.reconnect(JSON.stringify(ql(this.host.config)),Jl(this.host.config)),this.disconnected=!1,this.publishExplicitOfflineState()}),this.disconnected||this.resolveReconnectWaiters()}updateAuth(e){let t={...this.host.config,...e.mode===`bearer`?{jwtToken:e.jwtToken,cookieSession:void 0}:{jwtToken:void 0,cookieSession:e.cookieSession}};l(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Bi(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(ql(t)),Jl(t)).catch(e=>{this.observeConnectionFailure(n,s(e))})}async deleteClientStorage(){if(this.storageReset)return this.storageReset;!this.connection&&!this.getCurrentClient()&&this.getClient({});let e=this.connection;if(e&&this.heldTooLong&&this.admissionRefused(e)&&await this.retryConfigurationAdmission(e),await this.ensureReady(`runtime`),this.storageReset)return this.storageReset;if(!this.connection)throw Error(`deleteClientStorage(): the browser worker is not connected`);let t=await this.connection.deleteStorage();return await this.storageReset,t}async storePendingUploads(){if(!(!this.connection||this.storageReset))return await this.connection.storePendingUploads?.().catch(()=>void 0)??void 0}isUsable(){return!this.shutdownStarted&&!this.storageReset&&!this.storageResetError}async openInspectorControlPort(e){if(await Ka(this.connectionReady??Promise.resolve(),e),!this.connection)throw Error(`Shared browser runtime is not connected`);return this.connection.openInspectorControlPort(e)}beginStorageReset(e,t){if(e.resetReason||this.connectionScope!==e&&this.shutdownFailure?.scope!==e)return;e.resetReason=Error(`Browser foreground lease released after storage reset ${t}`),this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.foregroundNodeLease=void 0,this.initialExplicitOfflineStateKnown=!1;let n=this.detachClient(),r=Ml([()=>n?.discard(),()=>e.lease?.releaseAfterStorageReset(e.resetReason),()=>{this.shutdownFailure?.scope===e&&this.shutdownFailure.reset()},()=>e.connection.shutdown(),async()=>{if(this.shutdownStarted||this.connectionScope!==e)return;if(e.inspectorAttachment){this.storageResetError=Error(`Inspector storage was reset; a new attachment is required`);return}let t=await this.host.runtimeSource.acquireBrowserForegroundNodeLease(this.host.config);this.shutdownStarted||this.connectionScope!==e?await t.retire():this.foregroundNodeLease=t}]).finally(()=>{this.storageReset===r&&(this.storageReset=null,this.connectionScope===e&&(this.connectionScope=null))});this.storageReset=r,r.catch(e=>{this.storageResetError??=s(e)})}reopenFailedFollower(){this.recoverableConnectionFailure&&(this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.connectionError=null,this.initialExplicitOfflineStateKnown=!1,this.recoverableConnectionFailure=!1,this.openBrowserWorkerConnection())}reloadAfterStorageInvalidation(e){this.connection===e&&(this.connectionError=Error(`IndexedDB storage was externally invalidated`),jl())}async waitForPendingWrites(){await(this.connection??await this.pageAway?.reopened)?.waitForPendingWrites()}async shutdown(){if(this.shutdownStarted)return;this.shutdownStarted=!0,this.clearWorkerRecoveryTimer(),this.stopHoldingAcrossPageCache?.(),this.stopHoldingAcrossPageCache=null,this.pageAway?.reopen(null),this.pageAway=null,this.heldPatienceTimer!==null&&clearTimeout(this.heldPatienceTimer),this.heldPatienceTimer=null,this.wakeReplacementWaiters();let e=this.connection,t=this.connectionScope,n=this.connectionError;this.connection=null,this.connectionReady=null,this.browserConnectionInput=null,this.initialExplicitOfflineStateKnown=!1,this.resolveReconnectWaiters();let r=this.unregisterInspectorControl;this.unregisterInspectorControl=null;let i=this.foregroundNodeLease;this.foregroundNodeLease=void 0;let a=this.getCurrentClient(),o=null,s=!1,c,l=new Promise(e=>{c=e}),u=e=>{if(!o){o=e;try{this.detachClient()?.discard()}catch{}finally{i?.abandonAfterWorkerFailure(e),c()}}};this.shutdownFailure={connection:e,scope:t,abandon:u,reset:c},n instanceof $e&&u(n);try{await Ml([()=>{if(o)throw o},()=>r?.(),()=>this.storageReset??void 0,async()=>{if(o)throw o;if(!t?.resetReason&&!n)try{await Promise.race([e?.flushLocal(),l.then(()=>{if(o)throw o})])}catch(e){throw s=!0,o||(e instanceof $e&&u(e),e)}},async()=>{if(o)throw o;if(t?.resetReason||!i)return;let e=!1,n;await Promise.race([(async()=>{try{let e=a?.getRuntime();if(!e)s?await i.retire():await i.returnWithHighWater(i.confirmedTxTime);else if(!e.quiesceForegroundTxTimeHighWater)await i.retire();else{let n=await e.quiesceForegroundTxTimeHighWater();if(t?.resetReason)return;t?.leaseWorkerReplaced&&i.releaseAfterWorkerReplacement?i.releaseAfterWorkerReplacement(Error(`Foreground lease owner was replaced`)):s?await i.retire():await i.returnWithHighWater(n)}}catch(r){if(r===t?.resetReason)return;throw e=!0,n=o??r,await i.retire().catch(()=>void 0),n}})(),l.then(()=>{if(e)throw n;if(o)throw o})])},()=>{this.detachClient()?.discard()},()=>super.shutdown(),()=>t?.resetReason?void 0:e?.shutdown(),()=>this.storageReset??void 0,()=>{if(o)throw o}])}finally{this.shutdownFailure=null,this.connectionScope===t&&(this.connectionScope=null)}}resolveReconnectWaiters(){let e=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let t of e)t()}rejectReconnectWaiters(e){let t=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let n of t)n(e)}setExplicitOffline(e,t){this.connection===e&&(this.disconnected=t,this.publishExplicitOfflineState(),t||this.resolveReconnectWaiters())}transportLinkState(){return this.heldTooLong?`unavailable`:this.connectionError&&this.admissionRefused(this.connection)?`connecting`:this.connectionError?`unavailable`:this.workerRemoteLink}onTransportLinkStateChange(e,t){t.aborted||(this.workerRemoteLinkListeners.add(e),t.addEventListener(`abort`,()=>this.workerRemoteLinkListeners.delete(e),{once:!0}))}transportLinkStatus(){if(this.heldTooLong)return K(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return ss;if(this.connectionError)return K(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?ss:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return cs;case`unavailable`:return K(`network`);default:return ss}}setWorkerRemoteLink(e,t,n=null){this.connection===e&&(this.workerRemoteLink=t,this.workerLinkStatus=n,this.notifyWorkerRemoteLink())}notifyWorkerRemoteLink(){for(let e of[...this.workerRemoteLinkListeners])e();this.notifySyncStatus()}enqueueTransportTransition(e){let t=this.transportTransition.then(e,e);return this.transportTransition=t.catch(()=>void 0),t}};function ql(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function Jl(e){return rt({...e,trustedReservedSession:A(e)})?.claims??{}}var Yl=new WeakMap,Xl=new WeakSet;function Zl(e){return Xl.has(typeof e?.current==`function`?e.current():e)}async function Ql(e,t){if(typeof e!=`object`||!e)throw TypeError(`upgradeToLocalFirst was called without its Db: call it as db.upgradeToLocalFirst(loader), not destructured from the Db`);let n=Yl.get(e);if(n)return await n(t);if(Zl(e))throw Error(`This thin Db was not opened by a Jazz provider. Use upgradeToLocalFirst from jazz-tools/thin, which returns the local-first Db.`)}var $l=class extends Error{reason;constructor(e){super(`This Db was replaced by its Jazz session (${e===`signed-out`?`its user signed out or switched accounts`:`it swapped in another client`}), so it no longer reads or writes. In React, read the current Db with useDb() in the component that uses it, instead of keeping an earlier one in a ref, a variable or a closure. Without a framework provider, read it from session.getSnapshot().client inside session.subscribe(...) and subscribe to your queries again there.`),this.name=`DbReplacedError`,this.reason=e}},eu=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}};function tu(e){return e??{type:`persistent`}}function nu(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function ru(e){let t=tu(e.driver);return nu((t.type===`persistent`?t.dbName:void 0)??e.dbName)??H(e)}function iu(e){return Vi(e,ru(e))}function au(e){if(!e)return;let t=e;oe(t.tier);let n={};v(t.tier)&&(n.tier=t.tier);let r=w(t.firstLoadRemoteWaitMs);r!==void 0&&(n.firstLoadRemoteWaitMs=r),t.branch!==void 0&&(n.branch=t.branch),t.base!==void 0&&(n.base=t.base);let i=t.splices;if(i!==void 0){if(!Array.isArray(i)||!i.every(e=>typeof e==`string`))throw Error(`splices must be an array of column names.`);i.length>0&&(n.splices=[...i])}return it(e)&&(n.tier=`local-only`),n}var ou=new WeakMap,su=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getLocalFirstIdentityProof.onAuthChanged.onMutationError.textAnchors.getSyncStatus.waitForSync.getConfig.setDevMode.disconnect.reconnect.getActiveQuerySubscriptions.onActiveQuerySubscriptionsChange.getRuntimeSchema.openInspectorControlPort.insert.insertStreaming.updateStreaming.upsertStreaming.restore.upsert.update.delete.canInsert.canRead.canUpdate.canDelete.createTransaction.captureSnapshot.beginTransaction.beginSerializableTransaction.transaction.serializableTransaction.upgradeToLocalFirst.deleteClientStorage.storePendingUploads.logout.all.allInternal.one.subscribe.subscribeDelta`.split(`.`);function cu(e){let t=ou.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function lu(e,t){let n=Object.values(e).flatMap(e=>e.columns).filter(e=>e.name===t)[0];if(!n)throw Error(`Unknown branch column "${t}".`);return n}function uu(e,t,n,r){let i=G(e,t);if(!i)throw Error(`Unknown table "${t}".`);let a=i.branchBy??[],o=r===`table`?new Set(a):new Set(Object.values(e).flatMap(e=>e.branchBy??[])),s=typeof n==`object`&&n&&!Array.isArray(n)?n:o.size===1?{[[...o][0]]:n}:(()=>{throw Error(`A scalar branch selector requires exactly one ${r===`table`?`table`:`schema`} branch column.`)})(),c=Object.keys(s);if(c.length!==o.size||c.some(e=>!o.has(e)))throw Error(`Branch selector must provide exactly: ${[...o].sort().join(`, `)||`no columns`}.`);return{values:Object.fromEntries(c.map(t=>[t,ol(s[t],lu(e,t).column_type)]))}}function du(e,t,n,r){let i=uu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:uu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:uu(e,t,r,`schema`)}}}function fu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:uu(e,t,r,`table`)}}function pu(e,t,n){if(!n)return;let{branch:r,base:i,...a}=n;if(r===void 0){if(i!==void 0)throw Error(`A branch base requires a branch head.`);return a}return{...a,branch:du(e,t,r,i)}}function mu(e){return{get _table(){return e._table},get _schema(){return e._schema},get _columnTransforms(){return e._columnTransforms},get _columnTransformsByTable(){return e._columnTransformsByTable},get _rowType(){return e._rowType},_build(){let t=JSON.parse(e._build());return t.limit=1,JSON.stringify(t)}}}function hu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function gu(e){if(!e)return e;let t=e.split(`
3
3
  `);if(t.length<=1)return e;let n=e=>e.includes(`Db.registerActiveQuerySubscriptionTrace`)||e.includes(`Db.subscribe`)||e.includes(`SubscriptionsOrchestrator.ensureEntryForKey`)||e.includes(`SubscriptionsOrchestrator.getCacheEntry`)||e.includes(`/node_modules/`)||e.includes(`react-dom`)||e.includes(`react_stack_bottom_frame`),r=t.findIndex((e,t)=>t>0&&!n(e));return r<=0?e:[t[0],...t.slice(r)].join(`
4
- `)}function _u(e){return{...e,branches:[...e.branches]}}function vu(e,t){if(G(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function yu(e,t,n){return pu(e,t,n)??{}}function bu(e,t,n,r){let i=G(e,t)?.columns??[];for(let e of r){let r=i.find(t=>t.name===e);if(!r)throw Error(`splices: "${e}" is not a column of "${t}".`);let a=r.column_type.type;if(a!==`Text`&&a!==`Bytea`)throw Error(`splices: column "${e}" is ${a}; splices are not supported yet for columns other than TEXT and BYTEA.`);if(n._columnTransforms?.[e])throw Error(`splices: column "${e}" has a column transform; splices are not supported yet for transformed columns.`)}}function xu(e,t,n){for(let r of n)if(Object.hasOwn(e.partialSelect,r)&&!Object.hasOwn(t.partialSelect,r))throw Error(`splices: column "${r}" is selected in part, but a computed or transformed column depends on it, so it is read whole; splices are not supported yet for such columns.`)}function J(e){if(zo(e._table))throw Error(`History table "${e._table}" is read-only`)}function Su(e,t,n){return Cu(e,Gu(t,n),t._schema,t._table)}function Cu(e,t,n,r){try{return sl(t,n,r)}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`${e} failed: WriteError("${Iu(n)}")`)}}function wu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Tu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Eu(e,t,n){let r=Number(e);if(!Number.isSafeInteger(r)||r<0)throw Error(`${t} for "${n}" must be a non-negative safe integer.`);return r}function Du(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Ou(e,t,n){let r=Au(e,t,n?.applyDiffs),i=n?.editedFrom;if(i===void 0)return{replacements:t,descriptors:r};if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`update option editedFrom must be an object keyed by column name.`);let a={...t},o=[];for(let[t,n]of Object.entries(i)){if(n===void 0)continue;let i=e._columnTransforms?.[t];if(i&&!i.computed)throw Error(`update option editedFrom is not supported yet on "${t}", which has a transform.`);let s=a[t];if(typeof s!=`string`||typeof n!=`string`)throw Error(`update option editedFrom.${t} needs a string, and a string replacement for "${t}".`);delete a[t],o.push(t),r.push({kind:`text_edit`,column:t,text:s,edited_from:n})}return{replacements:a,descriptors:r}}function ku(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function Au(e,t,n){if(n===void 0)return[];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`update option applyDiffs must be an object keyed by column name.`);if(Object.keys(t).some(e=>Object.hasOwn(n,e)))throw Error(`update replacements and applyDiffs must not both specify the same column.`);let{ordinary:r,descriptors:i}=ju(n,e._schema,e._table);if(Object.keys(r).length>0)throw Error(`update option applyDiffs accepts only field diff descriptors, not whole-column values.`);return i}function ju(e,t,n){let r={},i=[],a=t[n]?.columns;if(!a)throw Error(`Unknown table "${n}"`);for(let[t,o]of Object.entries(e)){if(!wu(o)){r[t]=o;continue}let e=a.find(e=>e.name===t)?.column_type;if(!e)throw Error(`Unknown column "${t}" in table "${n}"`);if(`splices`in o&&`within`in o){let n=Tu(o.within,`Large-value update "${t}" has an invalid page.`),r=o.splices;if(!Array.isArray(r))throw Error(`Large-value update "${t}" has invalid splices.`);let a;if(`fromUtf8`in n||`toUtf8`in n){if(e.type!==`Text`)throw Error(`UTF-8 splice requires a Text column, got "${t}".`);let r=Eu(n.fromUtf8,`fromUtf8`,t),i=Eu(n.toUtf8,`toUtf8`,t);Du(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Eu(n.from,`from`,t),r=Eu(n.to,`to`,t);Du(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Eu(n.from,`from`,t),r=Eu(n.to,`to`,t);Du(e,r,t),a={kind:`text_utf16`,from:e,to:r}}else throw Error(`Splice requires a Text or Bytea column, got "${t}".`);i.push({kind:`splice`,column:t,within:a,splices:r.map(e=>{let n=Tu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Eu(r?n.atUtf8:n.at,`at`,t),o=Eu(r?n.deleteUtf8:n.delete,`delete`,t),s=n.insert,c;if(a.kind===`bytes`){if(!(s instanceof Uint8Array))throw Error(`Byte splice insert for "${t}" must be a Uint8Array.`);c=[...s]}else{if(typeof s!=`string`)throw Error(`Text splice insert for "${t}" must be a string.`);c=[...new TextEncoder().encode(s)]}return{at:i,delete:o,insert:c}})});continue}if(`edits`in o){if(e.type!==`Json`)throw Error(`JSON set requires a JSON column, got "${t}".`);if(!Array.isArray(o.edits))throw Error(`JSON update "${t}" has invalid edits.`);i.push({kind:`json_set`,column:t,edits:o.edits.map(e=>{let n=Tu(e,`JSON update edit for "${t}" is invalid.`);if(n.op!==`set`||typeof n.at!=`string`)throw Error(`JSON update "${t}" supports only { op: "set", at, value } edits.`);return{at:n.at,value:n.value}})});continue}r[t]=o}return{ordinary:r,descriptors:i}}function Mu(e,t){if(t<0||t>e.length)return!1;if(t===0||t===e.length)return!0;let n=e.charCodeAt(t-1),r=e.charCodeAt(t);return!(n>=55296&&n<=56319&&r>=56320&&r<=57343)}function Nu(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`~`){t+=r;continue}let i=e[++n];if(i===`0`)t+=`~`;else if(i===`1`)t+=`/`;else throw Error(`JSON pointer has an invalid escape.`)}return t}function Pu(e,t){if(t===``)return e;if(!t.startsWith(`/`))throw Error(`JSON pointer must be empty or begin with '/'.`);let n=e;for(let e of t.slice(1).split(`/`)){let t=Nu(e);if(Array.isArray(n)){if(!/^(0|[1-9]\d*)$/.test(t))throw Error(`JSON array pointer token is not an index.`);let e=Number(t);if(!Number.isSafeInteger(e)||e>=n.length)throw Error(`JSON pointer path does not exist.`);n=n[e]}else if(typeof n==`object`&&n&&Object.hasOwn(n,t))n=n[t];else throw Error(`JSON pointer path does not exist.`)}return n}function Fu(e,t){if(Object.keys(t).length===0||typeof e!=`object`||!e)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(`at`in r){n[e]=Pu(t,r.at);continue}if(t instanceof Uint8Array){if(`fromUtf8`in r)throw Error(`Byte range for "${e}" takes from and to, not fromUtf8 and toUtf8.`);if(r.from>r.to)throw Error(`Byte range for "${e}" ends before it starts.`);n[e]=t.slice(r.from,r.to);continue}if(typeof t!=`string`)throw Error(`Large-value selection for "${e}" has an incompatible column type.`);if(`fromUtf8`in r){let i=new TextEncoder().encode(t),a=Math.min(r.toUtf8,i.length),o=Math.min(r.fromUtf8,a);if(r.fromUtf8>r.toUtf8)throw Error(`UTF-8 range for "${e}" ends before it starts.`);if(o<i.length&&(i[o]&192)==128||a<i.length&&(i[a]&192)==128)throw Error(`UTF-8 range for "${e}" splits a code point.`);n[e]=new T({fatal:!0}).decode(i.slice(o,a));continue}let i=Math.min(r.to,t.length),a=Math.min(r.from,i);if(r.from>r.to)throw Error(`UTF-16 range for "${e}" ends before it starts.`);if(!Mu(t,a)||!Mu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Iu(e){return e.replaceAll(`"`,`\\"`)}function Lu(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function Ru(e,t,n,r){let i=Lu(e,t.table,n),a=n===t.table||!Object.keys(t.includes).length?t.includes:{},o=Object.keys(a).length>0;if(!i&&(!e._columnTransformsByTable||!o)){let r=Mc(e._schema,n,a,t.select);return{computedState:void 0,version:0,physical:a===t.includes?t:{...t,includes:a},transform:r}}let s=o?bs(e._schema):void 0,c=(t,a,o,l)=>{let u=e._columnTransformsByTable?.[t]??(t===n?i:void 0),d=a,f=l,p=!a.length||a.includes(`*`),m,h,g,_=e=>{u?.[e]?.computed||(!p&&e!==`id`&&!d.includes(e)&&(d===a&&(d=[...a]),d.push(e),(h??=[]).push(e)),Object.hasOwn(f,e)&&(f===l&&(f={...l}),delete f[e]))};if(u&&a.some(e=>u[e]?.computed)&&(d=a.filter(e=>!u[e]?.computed)),u){for(let e of p?Object.keys(u):a)if(Object.hasOwn(u,e)&&((m??={})[e]=u[e],u[e].computed)){r??=new Yc,(g??=[]).push(e);for(let t of r.storedColumns(u,e))_(t)}}!p&&!d.length&&(d=[`id`]);let v=o,y=[];for(let[e,n]of Object.entries(o)){let r=s?.get(t)?.find(t=>t.name===e)?.toTable;if(!r)continue;let i=c(r,n.select,n.includes,n.partialSelect);(i.select!==n.select||i.includes!==n.includes||i.partialSelect!==n.partialSelect)&&(v===o&&(v={...o}),v[e]={...n,select:i.select,includes:i.includes,partialSelect:i.partialSelect}),i.finish&&y.push([e,i.finish])}let b=Object.keys(l).length>0,x=Object.fromEntries(Object.entries(l).filter(([e])=>!Object.hasOwn(f,e))),S=Object.keys(x).length>0,C=Object.keys(o);return{select:d,includes:v,partialSelect:f,finish:m||b||y.length?e=>{let t=g?Zc(u,g,{...e},r,f):void 0,n=S?Fu(e,x):e;if(m&&wc(n,m,C,t,b?l:void 0),g)for(let e of g)n[e]=t.get(e);for(let[e,t]of y){let r=n[e];if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=t(r[e]);else r&&typeof r==`object`&&(n[e]=t(r))}if(h)for(let e of h)delete n[e];return n}:void 0}},l=c(n,t.select,a,t.partialSelect),u=Mc(e._schema,n,l.includes,l.select,void 0,!1,s);return{computedState:r,version:r?.version??0,physical:l.select===t.select&&l.partialSelect===t.partialSelect&&l.includes===t.includes?t:{...t,select:l.select,partialSelect:l.partialSelect,includes:l.includes},transform:l.finish?e=>l.finish(u(e)):u}}async function zu(e,t,n,r,i,a){for(;;){let o=[],s;for(let e of i)try{o.push(r.transform(e))}catch(e){if(!(e instanceof qc))throw e;s=e}if(!s)return o;if(!r.computedState||r.computedState.version===r.version)throw s;r=Ru(e,t,n,r.computedState),i=await a(r.physical)}}var Bu=new WeakMap;function Vu(e,t){let n=Bu.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Hu(e,t){return Uu(e,t)}function Uu(e,t){if(!e._columnTransforms||typeof t!=`object`||!t)return t;let n=t,r=Kc(e._columnTransforms),i=r.length?Zc(e._columnTransforms,r,n):void 0;wc(n,e._columnTransforms,[],i);for(let e of r)n[e]=i.get(e);return n}function Wu(e,t){let n=e._columnTransforms;if(n){for(let e of Object.keys(t))if(n[e]?.computed)throw TypeError(`Computed field "${e}" is read-only.`)}}function Gu(e,t){let n=t,r=e._columnTransforms;if(!r)return n;let i;for(let e in n){if(!Object.hasOwn(n,e))continue;let t=r[e];if(t?.computed)throw TypeError(`Computed field "${e}" is read-only.`);!t||n[e]===void 0||((i??={...n})[e]=t.to(n[e]))}return i??n}var Ku=1e4;function qu(e,t,n,r,i){let a=JSON.stringify({table:t._table,conditions:[{column:`id`,op:`eq`,value:n}],limit:1}),o=e.queryInternal(_c(a,t._schema),i?{tier:`remote`,branch:i}:{tier:`remote`},r),s,c=new Promise(e=>{s=setTimeout(()=>e([]),Ku)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function Ju(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Yu(e,t,n){return Hu(e,Nc(Wc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function Xu(e,t){if(typeof t!=`object`||!t)throw Error(`Streaming insert data must be an object`);let n=t,r=(e._schema[e._table]?.columns.filter(e=>[`Text`,`Json`,`Bytea`].includes(e.column_type.type)))?.filter(e=>Object.hasOwn(n,e.name)&&Zu(n[e.name]));if(r?.length!==1)throw Error(`Streaming insert requires exactly one streamed Text, Json, or Bytea column`);let i=r[0].name;if(e._schema[e._table]?.branchBy?.includes(i))throw Error(`Streaming a branchBy column is not supported: ${e._table}.${i}`);let a=n[i],o={...n};return delete o[i],{column:i,source:a,values:o}}function Zu(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function Qu(e,t){let n=e._schema[e._table]?.branchBy??[];if(n.length===0)return;let r={};for(let i of n){let n=t[i];if(Zu(n))throw Error(`Streaming a branchBy column is not supported: ${e._table}.${i}`);if(typeof n!=`string`&&typeof n!=`number`&&typeof n!=`bigint`)throw Error(`Streaming insert requires branch column ${e._table}.${i}`);r[i]=n}return r}function $u(e){return new Proxy(e,{get(e,t){if(t===`commit`||t===`rollback`)return;let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n},has(e,t){return t===`commit`||t===`rollback`?!1:Reflect.has(e,t)},set(e,t,n){return Reflect.set(e,t,n,e)}})}function ed(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function td(e,t,n){let r;try{r=t($u(e))}catch(t){try{await e.rollback()}catch{}throw t}let i=typeof n==`function`?n:()=>n,a;try{a=await r}catch(t){try{await e.rollback()}catch{}throw t}let o;try{let t=await e.commitUnlessEmpty();if(t===`empty`)return new c(a,i());o=t}catch(t){try{await e.rollback()}catch{}throw t}let s=o.txId.catch(async t=>{try{await e.rollback()}catch{}throw t});return ed(e,a,s,i())}var nd=class e{kind;resolveClient;context;static createWithAdmission(t,n,r,i,a){let o=new e(t,n,r);return o.openingPrerequisite=a,i&&o.bindOwnerClient(i),o}openingPrerequisite;pendingReads=new Set;committing=!1;constructor(e,t,n=null,r){this.kind=e,this.resolveClient=t,this.context=n,r&&this.bindOwnerClient(r)}bindTable(e){let t=this.resolveClient(e._schema);if(Bu.has(this)||this.bindOwnerClient(t),this.requireBinding(`table operation`).committing)throw Error(`Transaction commit has already been requested.`);return this.requireBinding(`table operation`)}bindQuery(e){return this.bindTable(e)}requireBinding(e){if(this.committing)throw Error(`DbTransaction.${e}() cannot run after commit has been requested`);return Vu(this,e)}bindOwnerClient(e){let{writeSession:t,attribution:n}=this.context??{},r=new Pc(!0),i=Ic(e),a=i?.pending?f():this.openingPrerequisite?re(e,this.kind,t,n,void 0,this.openingPrerequisite):e.beginTransaction(this.kind,t,n),o={ownerClient:e,openTransactionId:a,session:t,attribution:n,preparation:r,begun:!i?.pending};Bu.set(this,o),o.begun||r.run(()=>i.run(()=>{r.cancelled||(this.openingPrerequisite?re(e,this.kind,t,n,a,this.openingPrerequisite):e.beginTransaction(this.kind,t,n,a),o.begun=!0)}))}openTransactionId(){return this.requireBinding(`openTransactionId`).openTransactionId}commit(){let e=this.requireBinding(`commit`),{ownerClient:t,openTransactionId:n,preparation:r}=e;if(e.committing)throw Error(`Transaction commit has already been requested.`);(r.pending||r.failed)&&(e.committing=!0);let i=r.pending||r.failed||this.pendingReads.size>0?Promise.all([r.drain(),...this.pendingReads]).then(()=>t.commitTransaction(n).txId):t.commitTransaction(n).txId;this.committing=!0;let a=()=>{this.committing=!1};return i.then(a,a),this.kind===`serializable`?new Re(i,t):new Le(i,t)}async commitUnlessEmpty(){if(this.kind!==`mergeable`)return this.commit();let{ownerClient:e,openTransactionId:t,preparation:n}=this.requireBinding(`commit`);if(e.hasStagedTransactionWrites(t)!==!1)return this.commit();if(n.pending||n.failed){this.committing=!0;let r=!0;try{await n.drain()}catch{r=!1}finally{this.committing=!1}if(!r||e.hasStagedTransactionWrites(t)!==!1)return this.commit()}return await this.rollback(),`empty`}rollback(){let{ownerClient:e,openTransactionId:t,preparation:n,begun:r}=this.requireBinding(`rollback`);if(!r)return n.cancelled=!0,Promise.resolve(!0);let i=e.rollbackTransaction(t);return n.cancelled=!0,i}insertStreaming(e,t,n){return this.streamingMutation(`insert`,e,n?.id,t,n)}updateStreaming(e,t,n,r){return this.streamingMutation(`update`,e,t,n,r)}upsertStreaming(e,t,n,r){return this.streamingMutation(`upsert`,e,t,n,r)}streamingMutation(e,t,n,r,i){J(t),this.bindTable(t);let a=this.resolveClient(t._schema),o=e===`insert`?`Insert`:e===`update`?`Update`:`Upsert`,{openTransactionId:s,session:c,attribution:l,preparation:u}=this.requireBinding(`${e}Streaming`),{column:d,source:f,values:p}=Xu(t,r);Wu(t,p);let m=async()=>{let r=Cu(o,Gu(t,p),t._schema,t._table),u=e===`insert`?Qu(t,p):void 0,m=e===`insert`?fu(t._schema,t._table,{...i,...n?{id:n}:{},...u?{branch:u}:{}}):pu(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,r,d,f,s,m,c,l,n)};return Promise.resolve(u.run(()=>q(a,()=>u.cancelled?void 0:m()))).then(e=>{if(!e)throw Error(`Transaction was rolled back before the stream was staged`);return e})}insert(e,t,n){J(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`insert`),c=n?.id,{values:l,value:u}=this.prepareCreation(e,t,c,`Insert`);!c&&(s.pending||Ic(r)?.pending)&&(c=Ju());let d,f=()=>{d=r.insertInternal(e._table,l,fu(e._schema,e._table,c?{...n,id:c}:n),a,o,i)};s.cancelled?f():s.run(()=>q(r,()=>{s.cancelled||f()}));try{return u??(d?Hu(e,Nc(d,e._schema,e._table)):Yu(e,c,l))}catch(e){throw s.failure=e,e}}restore(e,t,n,r){J(e),this.bindTable(e);let{values:i,value:a}=this.prepareCreation(e,n,t,`Restore`),o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l,preparation:u}=this.requireBinding(`restore`),d=()=>{o.restoreInternal(e._table,t,i,fu(e._schema,e._table,r),c,l,s)};return u.cancelled?d():u.run(()=>q(o,()=>{u.cancelled||d()})),a}prepareCreation(e,t,n,r){let i;try{i=e._columnTransforms?Gu(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=Cu(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:Yu(e,n,a)}}catch(e){throw this.requireBinding(r).preparation.failure=e,e}}upsert(e,t,n,r){J(e),this.bindTable(e);let i=this.resolveClient(e._schema),{openTransactionId:a,session:o,attribution:s}=this.requireBinding(`upsert`);this.prepareMutation(e,n,`Upsert`,n=>{i.upsertInternal(e._table,t,n,pu(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){J(e),this.bindTable(e);let{replacements:i,descriptors:a}=Ou(e,n,r);r=ku(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=pu(e._schema,e._table,r);this.prepareMutation(e,i,`Update`,n=>{if(a.length>0){o.updateLargeValuesInternal(e._table,t,n,a,u?.updatedAt,c,l,s,u?.branch);return}o.updateInternal(e._table,t,n,u?.updatedAt,c,l,s,u?.branch)})}prepareMutation(e,t,n,r){let{ownerClient:i,preparation:a}=this.requireBinding(n);if(Wu(e,t),(a.pending||Ic(i)?.pending)&&(t={...t}),a.cancelled){r({});return}a.run(()=>q(i,()=>{if(a.cancelled)return;let i;try{i=Gu(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(Cu(n,i,e._schema,e._table))}))}delete(e,t,n){J(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`delete`),c=pu(e._schema,e._table,n),l=()=>{r.deleteInternal(e._table,t,c?.updatedAt,a,o,i,c?.branch)};s.cancelled?l():s.run(()=>q(r,()=>{s.cancelled||l()}))}all(e,t){let n=this.readAll(e,t);this.pendingReads.add(n);let r=()=>this.pendingReads.delete(n);return n.then(r,r),n}async readAll(e,t){this.bindQuery(e);let{preparation:n,openTransactionId:r}=this.requireBinding(`query`);(n.pending||n.failed)&&await n.drain();let i=this.resolveClient(e._schema),a=e._build(),o=Vs(JSON.parse(a)),s=vu(e._schema,o.table),c=vc(s,o),l=Ru(e,o,c),u=pu(e._schema,o.table,au(t))??{},d=await i.queryInternal(_c(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?zu(e,o,c,l,d,e=>i.queryInternal(_c(a,s,e),{...u,openTransactionId:r},this.context?.readSession)):d.map(l.transform)}async one(e,t){return(await this.all(mu(e),t))[0]??null}},rd=class e{config;runtimeSource;authStateStore;connection;_localFirstSecret=null;localFirstRefreshOwned=!1;localFirstRenewals=new vl;localFirstRefreshTimer=null;shutdownPromise=null;replaced=null;liveSubscriptionEnders=new Set;successor=null;movable=new Set;shutdownAbort=new AbortController;syncStatusSnapshot=null;activeQuerySubscriptionTraces=new Map;activeQuerySubscriptionTraceListeners=new Set;mutationErrorListeners=new Set;pendingMutationErrorEvents=[];nextActiveQuerySubscriptionTraceId=1;#e=null;constructor(e,t,n){$o(e),this.config=e,this.runtimeSource=t;let r={...e,trustedReservedSession:A(e)};d(this,rt(r)),this.authStateStore=he(r,n),this.connection=new Ol(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=jo(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}ou.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,au(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,au(n))})}dbForConnection(){let e=this;return{get config(){return e.config},get runtimeSource(){return e.runtimeSource},get isShuttingDown(){return e.shutdownPromise!==null},markUnauthenticated:e=>this.markUnauthenticated(e),renewsCredential:e=>(gd.get(this)??0)>0||e===`expired`&&this.localFirstRefreshOwned,clearAuthError:()=>this.authStateStore.clearError(),onMutationError:e=>this.handleMutationError(e),enableAuthenticatedInspectorLocalReads:e=>this.#t(e),clearAuthenticatedInspectorLocalReads:()=>this.#n()}}#t(e){this.config.runtimeSources?.inspectorHostPhysicalDbName===e&&(this.#e=e)}#n(){this.#e=null}async inspectorAttachmentOptions(e,t){return this.getClient(e._schema),await this.connection.ensureReady(`runtime`),au(this.#e?o(t):t&&{...t})??{}}async allFromInspectorAttachment(e,t){return this.allInternal(e,await this.inspectorAttachmentOptions(e,t))}subscribeFromInspectorAttachment(e,t,n){let r=null,i=!1,a=this.inspectorAttachmentOptions(e,n).then(n=>{if(!i)return r=this.subscribeDelta(e,t,n),r.ready}),o=(()=>{i=!0,r?.()});return Object.defineProperty(o,`ready`,{value:a}),o}initLocalFirstAuth(e,t,n=!0){this._localFirstSecret=e,this.localFirstRefreshOwned=n,n&&this.scheduleLocalFirstRefresh(t)}scheduleLocalFirstRefresh(e){this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer);let t=e*800;this.localFirstRefreshTimer=setTimeout(()=>{this.localFirstRenewals.reset(),this.refreshLocalFirstToken()},t)}refreshLocalFirstToken(){if(!(!this._localFirstSecret||this.shutdownPromise))try{let e=3600,t=this.mintLocalFirstToken(this._localFirstSecret,H(this.config),e),n=Ae(Me(t)??{},`local-first`);if(!n)throw Error(`Minted local-first token is missing its reserved session identity`);this.applyAuthUpdate(t,n),this.scheduleLocalFirstRefresh(e)}catch(e){console.error(`Failed to refresh local-first token:`,e)}}mintLocalFirstToken(e,t,n){return this.runtimeSource.mintLocalFirstToken({secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))})}markUnauthenticated(e){try{this.authStateStore.markUnauthenticated(e)}finally{e===`expired`&&this.localFirstRefreshOwned&&this.renewExpiredLocalFirstToken()}}renewExpiredLocalFirstToken(){let e=this.localFirstRenewals.next();if(e===0){this.refreshLocalFirstToken();return}this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer),this.localFirstRefreshTimer=setTimeout(()=>this.refreshLocalFirstToken(),e)}publishAuthStateWithInternalSession(e,t){d(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=A(this.config);return!(r!==n||i!==void 0||JSON.stringify(a)!==JSON.stringify(t))&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateJwtToken(n,t)?!1:(this.connection.updateAuth({mode:`bearer`,jwtToken:n,trustedReservedSession:t}),this.publishAuthUpdate(n,t),!0)}publishAuthUpdate(e,t){let n={...this.config,jwtToken:e,cookieSession:void 0};l(n,t);let r=rt(n);this.config.jwtToken=e,this.config.cookieSession=void 0,l(this.config,t),this.publishAuthStateWithInternalSession(r,()=>{this.authStateStore.applyJwtToken(e,t)})}applyCookieSessionUpdate(e){this.runtimeSource.assertAuthUpdateAllowed();let t=e??void 0,n=this.config.cookieSession,r=this.config.jwtToken,i=A(this.config),a=JSON.stringify(n)!==JSON.stringify(t);if(!(r!==void 0||a||i!==void 0)&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateCookieSession(t))return!1;this.connection.updateAuth({mode:`cookie`,cookieSession:t});let o=rt({...this.config,jwtToken:void 0,cookieSession:t});return this.config.jwtToken=void 0,this.config.cookieSession=t,l(this.config,void 0),this.publishAuthStateWithInternalSession(o,()=>{this.authStateStore.applyCookieSession(t)}),!0}static create(t,n){return new e(t,n)}static async createWithDirectConnection(t,n){let r=new e(t,n);return await r.connection.start(),r}static async createWithBrowserWorker(t,n,r){let i=new e(t,n),a=new Kl(i.dbForConnection(),r);return i.connection=a,await a.start(),i}getClient(e){return this.assertOpen(),this.connection.getClient(e)}getCurrentClient(){return this.connection.getCurrentClient()}currentRuntime(){return this.getCurrentClient()?.getRuntime()??null}async prefetchRuntimeQueries(e,t){let n=this.getClient(e);await this.ensureReady(`server`),await Promise.all(t.map(e=>n.query(e,{tier:`remote`})))}async ensureReady(e,t){await this.connection.ensureReady(e,t??this.shutdownAbort.signal),this.assertOpen()}wrapWriteWait(e){return bl(this),g(e,async e=>{this.drain||await this.ensureReady(e===`global`?`upload`:`runtime`)})}getAccessContext(){return null}handleMutationError(e,t=!1){if(this.successor)return this.successor.handleMutationError(e,t);if(this.mutationErrorListeners.size===0){t||console.error(`Unhandled Jazz mutation error`,e),this.pendingMutationErrorEvents.push(e);return}for(let t of this.mutationErrorListeners)t(e)}async refreshAccountAuth(e){return this.refreshOwnAccountAuth(e)}async refreshOwnAccountAuth(e){$o(this.config);let t=at(this);if(e.id!==this.config.accountId||Xo(e)!==this.config.accountRegistryAuthority||e.identity.issuer!==t?.issuer||e.identity.subject!==t?.user_id)throw Error(`Account context mismatch`);try{let t=await Yo(e,Xo(e),{fresh:!0});if(this.shutdownAbort.signal.aborted)throw Error(`Account context closed`);let n=e.identity.issuer===`urn:jazz:local-first`?Ae(Me(t)??{},`local-first`):void 0;return this.authStateStore.validateJwtToken(t,n??void 0)?(this.connection.refreshAccountAuth(t,n??void 0),this.publishAuthUpdate(t,n??void 0),t):t}catch(e){throw this.markUnauthenticated(`invalid`),e}}updateAuthToken(e){this.applyAuthUpdate(e)}updateCookieSession(e){this.applyCookieSessionUpdate(e)}getAuthState(){return this.authStateStore.getState()}getLocalFirstIdentityProof(e){if(!this._localFirstSecret)return null;let t=e?.ttlSeconds??60,n=e?.audience??H(this.config);return this.mintLocalFirstToken(this._localFirstSecret,n,t)}onOwnAuthChanged(e){return this.authStateStore.onChange(t=>e(t))}onAuthChanged(e){return this.registerMovable(t=>t.authStateStore.onChange(t=>{e(t)}))}registerMovable(e,t=!1){let n=e(this),r=!1,i={move:i=>{r||(n(),n=t?e(this):i.registerMovable(e))}};return this.movable.add(i),()=>{r||(r=!0,this.movable.delete(i),n())}}onMutationError(e){if(this.replaced)throw this.replaced;return this.registerMovable(t=>{for(t.mutationErrorListeners.add(e);t.pendingMutationErrorEvents.length>0;)e(t.pendingMutationErrorEvents.shift());return()=>{t.mutationErrorListeners.delete(e)}})}textAnchors(){return this.runtimeSource.textAnchors()}getSyncStatus(){let e=this.connection.syncStatus();return this.syncStatusSnapshot&&fs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||fs(n,t)||(t=n,e(n))};return this.registerMovable(e=>{let t=e.syncStatusChangeRegistration(n);return e.successor&&n(e.getSyncStatus()),t},!0)}syncStatusChangeRegistration(e){return this.onSyncStatusChangeHere(e)}onSyncStatusChangeHere(e){let t=new AbortController,n=()=>t.abort();this.shutdownAbort.signal.addEventListener(`abort`,n,{once:!0}),t.signal.addEventListener(`abort`,()=>this.shutdownAbort.signal.removeEventListener(`abort`,n),{once:!0});let r=this.getSyncStatus();return this.connection.onSyncStatusChange(()=>{let t=this.getSyncStatus();t!==r&&(r=t,e(t))},t.signal),n}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;de(t),this.assertOpen(),n?.throwIfAborted();let r=new AbortController,i=()=>r.abort(n.reason);n?.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort(Error(`Db was shut down`));this.shutdownAbort.signal.addEventListener(`abort`,a,{once:!0});let o=t===void 0?void 0:setTimeout(()=>r.abort(new O(`global`,t)),t);try{await this.waitForUpstreamSync(r.signal)}finally{o!==void 0&&clearTimeout(o),n?.removeEventListener(`abort`,i),this.shutdownAbort.signal.removeEventListener(`abort`,a)}}waitForUpstreamSync(e){return this.connection.waitForSync(e)}getConfig(){let{browserWorkerPort:e,browserWorkerSession:t,...n}=this.config.runtimeSources??{};return structuredClone({...this.config,runtimeSources:Object.keys(n).length>0?n:void 0})}setDevMode(e){this.config.devMode=e}async disconnect(){if(this.shutdownPromise)throw Error(`Cannot disconnect a Db that is shutting down.`);this.offlineRequested=!0,await this.connection.disconnect()}async reconnect(){if(this.shutdownPromise&&!this.cancelSyncShutdown)throw Error(`Cannot reconnect a Db that is shutting down.`);this.offlineRequested=!1,await this.connection.reconnect()}getActiveQuerySubscriptions(){return Array.from(this.activeQuerySubscriptionTraces.values()).filter(e=>e.visibility===`public`).map(({visibility:e,...t})=>_u(t))}onActiveQuerySubscriptionsChange(e){return this.registerMovable(t=>(t.activeQuerySubscriptionTraceListeners.add(e),e(t.getActiveQuerySubscriptions()),()=>{t.activeQuerySubscriptionTraceListeners.delete(e)}))}getRuntimeSchema(){return this.connection.getRuntimeSchema()}openInspectorControlPort(e){return this.connection.openInspectorControlPort(e)}insert(e,t,n){J(e);let r=this.getClient(e._schema),i=n?.id,a=Cu(`Insert`,e._columnTransforms?Gu(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!Ic(r)?.pending;s&&!i&&(i=Ju());let c=s?Yu(e,i,a):void 0,l=q(r,()=>r.insert(e._table,a,fu(e._schema,e._table,i?{...n,id:i}:n),o?.writeSession,o?.attribution));return this.wrapWriteWait(l instanceof Promise?new E(c,l.then(e=>e.txId),r):l.mapValue(t=>c===void 0?Hu(e,Nc(t,e._schema,e._table)):c))}async insertStreaming(e,t,n){J(e);let r=this.getClient(e._schema),{column:i,source:a,values:o}=Xu(e,t);Wu(e,o),bl(this);let s=n?.id;return q(r,async()=>{let t=Cu(`Insert`,Gu(e,o),e._schema,e._table),c=this.getAccessContext(),l=Qu(e,o);return r.insertStreaming(e._table,t,i,a,fu(e._schema,e._table,l?{...n,...s?{id:s}:{},branch:l}:s?{...n,id:s}:n),c?.writeSession,c?.attribution)})}async updateStreaming(e,t,n,r){J(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=Xu(e,n);Wu(e,s),bl(this);let c=this.getAccessContext();return q(i,async()=>{let n=Cu(`Update`,Gu(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,pu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}async upsertStreaming(e,t,n,r){J(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=Xu(e,n);Wu(e,s),bl(this);let c=this.getAccessContext();return q(i,async()=>{let n=Cu(`Upsert`,Gu(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,pu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){J(e);let i=this.getClient(e._schema),a=Cu(`Restore`,e._columnTransforms?Gu(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=Ic(i)?.pending?Yu(e,t,a):void 0,c=q(i,()=>i.restore(e._table,t,a,fu(e._schema,e._table,r),o?.writeSession,o?.attribution));return this.wrapWriteWait(c instanceof Promise?new E(s,c.then(e=>e.txId),i):c.mapValue(t=>Hu(e,Nc(t,e._schema,e._table))))}upsert(e,t,n,r){return J(e),this.prepareMutation(e,t,n,`Upsert`,r)}prepareMutation(e,t,n,r,i,a){let o=this.getClient(e._schema);Wu(e,n),Ic(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=pu(e._schema,e._table,i),l=q(o,()=>{let i=n=>{let i=Cu(r,n,e._schema,e._table);return a?a(i):r===`Upsert`?o.upsert(e._table,t,i,c,s?.writeSession,s?.attribution):o.update(e._table,t,i,c,s?.writeSession,s?.attribution)},l=Gu(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Bc(n)!==`not_observed`)throw n;return qu(o,e,t,s?.readSession,c?.branch).then(()=>{try{return i(l)}catch(t){throw Bc(t)===`not_observed`?Uc(`Update`,e._table):t}})}});return this.wrapWriteWait(l instanceof Promise?new Le(l.then(e=>e.txId),o):l)}update(e,t,n,r){J(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Ou(e,n,r);r=ku(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,pu(e._schema,e._table,r),s?.writeSession,s?.attribution)):this.prepareMutation(e,t,n,`Update`,r)}delete(e,t,n){J(e);let r=this.getClient(e._schema),i=this.getAccessContext(),a=q(r,()=>r.delete(e._table,t,pu(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Le(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=Su(`Insert`,e,t),i=this.getAccessContext();return n.requestInsertPermissionAdvice(e._table,r,i?.writeSession)}explainReadClauses(e,t){let n=this.getAccessContext()?.readSession;if(!n)throw Error(`explain needs a Db acting as a user`);return this.getClient(e._schema).explainReadClauses(e._table,t,n)}async canRead(e,t){let n=this.getClient(e._schema),r=this.getAccessContext();return n.requestReadPermissionAdvice(e._table,t,r?.readSession)}async canUpdate(e,t,n){let r=this.getClient(e._schema),i=Su(`Update`,e,n),a=this.getAccessContext();return r.requestUpdatePermissionAdvice(e._table,t,i,a?.writeSession)}async canDelete(e,t){let n=this.getClient(e._schema),r=this.getAccessContext();return n.requestDeletePermissionAdvice(e._table,t,r?.writeSession)}createTransaction(e,t){this.assertOpen(),bl(this);let n=this.getAccessContext(),r=this.getCurrentClient();if(e===`serializable`&&!r)throw Error(`Cannot begin a serializable transaction before the JazzClient has been created. Run a query or mutation first.`);return nd.createWithAdmission(e,e=>this.getClient(e),n,r??void 0,t)}async captureSnapshot(){this.assertOpen();let e=this.getCurrentClient();if(!e)throw Error(`Cannot capture a snapshot before a schema is attached. Run a query or mutation first.`);return q(e,()=>e.captureSnapshot())}beginTransaction(){return this.createTransaction(`mergeable`)}beginSerializableTransaction(){return this.createTransaction(`serializable`)}transaction(e){let t=this.beginTransaction();return td(t,e,()=>Vu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return td(t,e,()=>Vu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await Ql(this,e)}isLocalFirst(){return!Zl(this)}async deleteClientStorage(){await this.connection.deleteClientStorage()}async storePendingUploads(){return await this.connection.storePendingUploads().catch(()=>void 0)??this.getSyncStatus().pendingUploads}isUsable(){return!this.shutdownPromise&&!this.replaced&&this.connection.isUsable()}async logout(e={}){e.wipeData&&await this.deleteClientStorage(),await this.shutdown()}async all(e,t){try{return await this.allInternal(e,au(t))}catch(n){if(this.successor&&_d(n))return this.current().all(e,t);throw n}}async allInternal(e,t){let n=this.getClient(e._schema),r=Ic(n);r?.pending&&await r.drain();let a=i(this.config,{tier:t?.tier,firstLoadRemoteWaitMs:t?.firstLoadRemoteWaitMs}).firstLoadRemoteWaitMs===void 0?null:this.connection.initialExplicitOfflineState();a&&await a;let o=e._build(),s=Vs(JSON.parse(o)),c=vu(e._schema,s.table),l=vc(c,s),u=Ru(e,s,l),d=yu(e._schema,s.table,t),f=_c(o,c,u.physical),p=hu(s),m=this.getAccessContext(),h=i(this.config,d).tier;await this.ensureReady(h===`remote`?`server`:`runtime`);let g=m||p?await n.queryInternal(f,d,m?.readSession):await n.queryInternal(f,d);return u.computedState?zu(e,s,l,u,g,e=>n.queryInternal(_c(o,c,e),d,m?.readSession)):g.map(u.transform)}async one(e,t){return(await this.all(mu(e),t))[0]??null}subscribe(e,t,n,r){let{onUpdate:i,onError:a}=typeof t==`function`?{onUpdate:t,onError:void 0}:t,o={onDelta:e=>{if(e.all===void 0)throw Error(`Jazz subscription update is missing its materialized result.`);let t=new Map;for(let n of e.delta)n.kind===ue.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,au(n),r)}subscribeDelta(e,t,n,r){if(this.replaced)throw this.replaced;let{onDelta:i,onError:a}=typeof t==`function`?{onDelta:t,onError:void 0}:t,o,s=!0,c=this.registerMovable(t=>{let c=!s;s=!1;let l=t.subscribeDeltaHere(e,{onDelta:e=>{if(c){c=!1,i({delta:e.delta,all:e.all??[],reset:!0});return}i(e)},...a===void 0?{}:{onError:a}},n,r);return o??=l.ready,l}),l=(()=>c());return o&&Object.defineProperty(l,`ready`,{value:o}),l}subscribeDeltaHere(e,t,n,r){let{onDelta:i,onError:a}=t,o=this.getClient(e._schema),c=this.connection.initialExplicitOfflineState(),l=new u,d=e._build(),f=Vs(JSON.parse(d)),p=vu(e._schema,f.table),m=vc(p,f),h=Ru(e,f,m),g=_c(d,p,h.physical),_=c===null,v=[],y=yu(e._schema,f.table,n);y.splices&&(bu(p,m,e,y.splices),xu(f,h.physical,y.splices));let b=this.getAccessContext()?.readSession??r,x=null,S=!1,C=!1,w=new AbortController,T=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},E=e=>{if(!a){console.error(`Unhandled Jazz subscription error`,e);return}try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},D=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||C||(e.terminalDelivered=!0,C=!0,_=!1,v.length=0,x===e&&(x=null),T(e),e.predecessor!==null&&(T(e.predecessor),e.predecessor=null),w.abort(),this.liveSubscriptionEnders.delete(se),this.unregisterActiveQuerySubscriptionTrace(ie),l.clear(),E(t))},O=(e,t)=>{S||C||x!==e||e.terminalDelivered||(e.terminalError??=s(t),D(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return x=t,t},te=e=>{if(!(S||C||x===null)){if(!_){v.push(e);return}try{i(e)}catch(e){let t=x;t!==null&&O(t,e)}}},ne=t=>{if(!(S||C||x===null))try{te(l.handleDelta(t,h.transform))}catch(t){if(!(t instanceof qc)||!h.computedState||h.computedState.version===h.version)throw t;h=Ru(e,f,m,h.computedState),y.splices&&xu(f,h.physical,y.splices),g=_c(d,p,h.physical),T(x);let n=ee();l.clear(),v.length=0,this.unregisterActiveQuerySubscriptionTrace(ie),ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),queueMicrotask(()=>{this.shutdownPromise||re(n)})}},re=(e,t=y)=>{if(S||x!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(g,{onUpdate:t=>{if(!(S||x!==e||e.terminalError!==null)){if(e.installing){n.push(t);return}try{ne(t)}catch(t){O(e,t)}}},onError:t=>{O(e,t)}},t,b)}catch(t){return e.installing=!1,O(e,t),null}if(e.installing=!1,S||x!==e||e.retired)return T(e),null;if(e.terminalError!==null)return D(e),null;try{for(let t of n){if(x!==e||e.terminalError!==null)break;ne(t)}}catch(t){return O(e,t),null}return S||x!==e||e.retired?null:e},ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),ae=()=>{S||(S=!0,this.liveSubscriptionEnders.delete(se),_=!1,v.length=0,w.abort(),this.unregisterActiveQuerySubscriptionTrace(ie),x!==null&&(T(x),x.predecessor!==null&&(T(x.predecessor),x.predecessor=null)),x=null,l.clear())},k=c?.then(()=>{if(!(S||C||x===null||this.shutdownPromise)){_=!0;for(let e of v.splice(0)){if(S||C||x===null)return;te(e)}}}).catch(e=>{if(!(S||C||x===null||this.shutdownPromise))throw O(x,e),e});k&&k.catch(()=>void 0);let oe=ee(),se=e=>{x!==null&&O(x,e)};this.liveSubscriptionEnders.add(se);let ce=y.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(ce)?this.ensureReady(ce,w.signal).then(()=>re(oe)).catch(e=>{S||w.signal.aborted||this.shutdownPromise||O(oe,e)}):re(oe);let le=ae;return k&&Object.defineProperty(le,`ready`,{value:k}),le}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new $l(e);this.replaced=t;for(let e of Array.from(this.liveSubscriptionEnders))e(t);this.liveSubscriptionEnders.clear()}adoptSuccessor(t){if(this.successor)throw Error(`This Db already has a successor`);let n=this.currentRuntime();this.successor=t,n?.endUnsentReads?.();let r=this.letStreamsFinish(),i=!0,a=new Set,o=this.shutdown({waitForSync:!0}).finally(()=>{i=!1;for(let e of Array.from(a))e()});o.catch(()=>{}),this.drain={done:o,endStreamWait:()=>r.abort(),abort:()=>{i&&this.abortGracefulShutdown()}};let s=null,c=()=>{let n=t.getSyncStatus();if(!i)return n;let r=e.prototype.getSyncStatus.call(this),a={link:n.link,pendingUploads:n.pendingUploads+r.pendingUploads,oldestPendingAt:n.oldestPendingAt===null||r.oldestPendingAt===null?n.oldestPendingAt??r.oldestPendingAt:Math.min(n.oldestPendingAt,r.oldestPendingAt),rejected:n.rejected+r.rejected,lastError:r.lastError&&(!n.lastError||r.lastError.at>n.lastError.at)?r.lastError:n.lastError,synced:n.synced&&r.pendingUploads===0};return s&&fs(a,s)?s:s=a},l={getSyncStatus:c,syncStatusChangeRegistration:e=>{let n=c(),r=()=>{let t=c();t!==n&&(n=t,e(t))},o=t.onSyncStatusChange(r),s=i?this.onSyncStatusChangeHere(r):()=>{};return a.add(r),()=>{o(),s(),a.delete(r)}},waitForSync:async(e={})=>{await Promise.all([t.waitForSync(e),i?this.waitForOwnSync(e,o):void 0])},disconnect:async()=>{await Promise.all([t.disconnect(),i?this.connection.disconnect():void 0])},reconnect:async()=>{await Promise.all([t.reconnect(),i?this.connection.reconnect():void 0])}};for(let e of su)Object.defineProperty(this,e,{configurable:!0,value:l[e]??((...n)=>t[e](...n))});Object.defineProperty(this,`syncStatusChangeRegistration`,{configurable:!0,value:l.syncStatusChangeRegistration}),(this.offlineRequested??this.connection.isExplicitlyOffline())&&t.disconnect().catch(()=>{});for(let e of this.pendingMutationErrorEvents.splice(0))t.handleMutationError(e,!0);for(let e of Array.from(this.movable))e.move(t);this.movable.clear()}async waitForOwnSync(e,t){let{timeoutMs:n,signal:r}=e;de(n),r?.throwIfAborted();let i=new AbortController,a=()=>i.abort(r.reason);r?.addEventListener(`abort`,a,{once:!0});let o=n===void 0?void 0:setTimeout(()=>i.abort(new O(`global`,n)),n);try{await Promise.race([this.connection.waitForSync(i.signal),t])}finally{o!==void 0&&clearTimeout(o),r?.removeEventListener(`abort`,a)}}offlineRequested;drain=null;streamsMayFinish=null;letStreamsFinish(){return this.streamsMayFinish?.abort(),this.streamsMayFinish=new AbortController,this.streamsMayFinish}async stopOwnRuntime(t={}){let n=this.drain;if(!n)return this.shutdown(t);n.endStreamWait(),t.waitForSync||n.abort(),await n.done.catch(()=>{}),await e.prototype.shutdown.call(this)}current(){return this.successor?.current()??this}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let t,n=new Promise(e=>{t=e});return this.shutdownPromise=n,t(this.runShutdown(e)),n}cancelSyncShutdown;abortGracefulShutdown(){this.cancelSyncShutdown?.()}assertOpen(){if(this.replaced)throw this.replaced;if(this.shutdownPromise)throw Error(`Cannot operate on a Db that is shutting down or closed.`)}shutdownListeners=new Set;onShutdown(e){return this.shutdownPromise?e():this.shutdownListeners.add(e),()=>this.shutdownListeners.delete(e)}async runShutdown(e){if(e.waitForSync){let e=new AbortController,t=new Promise((t,n)=>{this.cancelSyncShutdown=()=>{e.abort(),n(Error(`Graceful shutdown cancelled`))}});try{await Promise.race([this.runtimeSource.waitForPendingWrites?.(e.signal)??this.connection.waitForPendingWrites({inFlightStreams:this.streamsMayFinish?.signal}),t])}catch(t){throw e.abort(),this.shutdownPromise=null,new Uo(t)}finally{this.cancelSyncShutdown=void 0}}for(let e of this.shutdownListeners)try{e()}catch(e){console.error(`Context cleanup failed`,e)}this.shutdownListeners.clear(),this.shutdownAbort.abort(),this.localFirstRefreshTimer&&=(clearTimeout(this.localFirstRefreshTimer),null),this.clearActiveQuerySubscriptionTraces(),this.mutationErrorListeners.clear();try{await this.connection.shutdown()}finally{await this.runtimeSource.shutdown()}}notifyActiveQuerySubscriptionTraceListeners(){if(this.activeQuerySubscriptionTraceListeners.size===0)return;let e=this.getActiveQuerySubscriptions();for(let t of this.activeQuerySubscriptionTraceListeners)t(e)}registerActiveQuerySubscriptionTrace(e,t,n){if(!this.config.devMode)return null;let r=i(this.config,n);if(r.tier===`local-only`)return null;let a=this.parseRuntimeQueryTracePayload(e),o=`sub-${this.nextActiveQuerySubscriptionTraceId++}`;return this.activeQuerySubscriptionTraces.set(o,{id:o,query:e,table:a.table,branches:a.branches,tier:r.tier,createdAt:new Date().toISOString(),stack:gu(Error().stack),visibility:r.visibility??`public`}),this.notifyActiveQuerySubscriptionTraceListeners(),o}unregisterActiveQuerySubscriptionTrace(e){e&&this.activeQuerySubscriptionTraces.delete(e)&&this.notifyActiveQuerySubscriptionTraceListeners()}clearActiveQuerySubscriptionTraces(){this.activeQuerySubscriptionTraces.size!==0&&(this.activeQuerySubscriptionTraces.clear(),this.notifyActiveQuerySubscriptionTraceListeners())}parseRuntimeQueryTracePayload(e){try{let t=JSON.parse(e);return{table:typeof t.table==`string`?t.table:`unknown`,branches:Array.isArray(t.branches)?t.branches.filter(e=>typeof e==`string`):[]}}catch{return{table:`unknown`,branches:[]}}}};function id(){let e=y(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function ad(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function od(e,t){if(!t.supportsBrowserWorker||!hd()||tu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),sd.set(n,cd(e)),n}var sd=new WeakMap;function cd(e){try{let t=e.runtimeSources;return JSON.stringify([iu(e),zi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function ld(e,t){let n=sd.get(e);return n!==void 0&&n===cd(t)}async function ud(e){if(!(!e||fd.has(e))){fd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function dd(e,t,n){let r=n;try{return await pd(e,t,()=>(r??=od(e,t),r))}finally{ud(r)}}var fd=new WeakSet;async function pd(e,t,n){if($o(e),md(e),e.secret&&e.cookieSession)throw Error(`DbConfig error: secret and cookieSession are mutually exclusive`);if(e.secret&&e.jwtToken)throw Error(`DbConfig error: secret and jwtToken are mutually exclusive`);if(e.jwtToken&&e.cookieSession)throw Error(`DbConfig error: jwtToken and cookieSession are mutually exclusive`);let r=e.secret?se(e.secret):null,i={...e};l(i,A(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...u}=e,d=r;if(d){let n=d;if(!e.jwtToken){let r=t.mintLocalFirstToken(ad(n,H(e),3600)),a=Ae(Me(r)??{},`local-first`);i={...u,jwtToken:r},l(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=id(),r=t.mintAnonymousToken(ad(n,H(e),3600)),a=Ae(Me(r)??{},`anonymous`);i={...u,jwtToken:r},l(i,a)}es(e,i),t.admitConfig(i);let f=tu(i.driver),p=t.supportsBrowserWorker&&hd()&&f.type===`persistent`,m=a&&p&&ld(a,i)?a:void 0;m?fd.add(m):a&&await ud(a);let h=p?await rd.createWithBrowserWorker(i,t,m):await rd.createWithDirectConnection(i,t);return d&&h.initLocalFirstAuth(d,3600,!e.jwtToken),h}function md(e){if(Object.hasOwn(e,`backendSecret`))throw Error(`DbConfig does not accept backendSecret. Run Jazz in your backend with createJazz() from jazz-tools/backend instead.`)}function hd(){return typeof window<`u`&&typeof Worker<`u`}var gd=new WeakMap;function _d(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof eu)return!0;return!1}var vd={napi:`293b3c4ee11055c99bd31d3b6f532991c45407a3509436dec7ff3f45505d5e45`,wasm:`ea0408b6249e4383ff90c9554149de9dc9ddee467b464fb33b913b7e4214c5d0`};function yd(e,t,n=[]){let r=vd[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw Error(`Jazz ${t} artifact is stale or incompatible: missing nativeArtifactFingerprint (expected ${r}). In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`);let i=e.nativeArtifactFingerprint();if(i!==r)throw Error(`Jazz ${t} artifact ABI mismatch: expected ${r}, got ${String(i)}. In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`);for(let r of n)if(typeof e[r]!=`function`)throw Error(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${r}.`)}var bd=class extends Error{},xd=class extends Error{},Sd=new Set(`\\.+*?()|[]{}^$#&-~`),Cd=new Set(`imsUuRx`),wd=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Td(e){return Sd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Ed=class{pattern;chars;index=0;flags={multiLine:!1,dotAll:!1,swapGreed:!1};fancy=!1;caseInsensitive=!1;captures=0;names=new Set;unsupported=[];fancyInvalid=[];bellOutsideClass=!1;constructor(e){this.pattern=e,this.chars=[...e]}parse(){let e;try{e=this.parseAlternation(0),this.eof()||this.fail(`unopened group`)}catch(e){throw e instanceof bd&&this.fancy?new xd(e.message):e}return!this.fancy&&this.bellOutsideClass&&this.fail("`\\a` is not supported"),{node:e,fancy:this.fancy,caseInsensitive:this.caseInsensitive,captures:this.captures,unsupported:this.unsupported,fancyInvalid:this.fancyInvalid}}eof(){return this.index>=this.chars.length}char(){return this.chars[this.index]}peek(e=1){return this.chars[this.index+e]}startsWith(e){return this.chars.slice(this.index,this.index+e.length).join(``)===e}fail(e){throw new bd(e)}parseAlternation(e){let t=[this.parseConcat(e)];for(;!this.eof()&&this.char()===`|`;)this.index++,t.push(this.parseConcat(e));return t.length===1?t[0]:{kind:`alternation`,items:t}}parseConcat(e){let t=[],n=0;for(;!this.eof();){let r=this.char();if(r===`|`||r===`)`)break;if(r===`?`||r===`*`||r===`+`||r===`{`?(n++,n===2&&r===`+`?this.unsupported.push(`possessive quantifiers`):n===2&&r===`{`?this.unsupported.push(`a counted repetition right after another quantifier`):n>=2&&this.fancyInvalid.push(`a quantifier right after another quantifier`)):n=0,r===`(`)t.push(this.parseGroup(e));else if(r===`[`)t.push({kind:`class`,item:this.parseBracketed()});else if(r===`?`||r===`*`||r===`+`){this.index++;let[e,n]=r===`?`?[0,1]:r===`*`?[0,1/0]:[1,1/0],i=!0;!this.eof()&&this.char()===`?`&&(i=!1,this.index++),this.repeatLast(t,e,n,i)}else r===`{`?this.parseCountedRepetition(t):t.push(this.parsePrimitive())}return t.length===1?t[0]:{kind:`concat`,items:t}}repeatLast(e,t,n,r){let i=e.pop();(i===void 0||i.kind===`flags`)&&this.fail(`repetition operator missing expression`),i.kind===`look`&&this.fancyInvalid.push(`a quantifier on a lookaround`),e.push({kind:`repeat`,body:i,min:t,max:n,greedy:r!==this.flags.swapGreed})}skipWhitespaceInRepetition(){let e=!1;for(;!this.eof()&&/\p{White_Space}/u.test(this.char());)this.index++,e=!0;e&&this.unsupported.push(`spaces inside a counted repetition`)}parseDecimal(){this.skipWhitespaceInRepetition();let e=``;for(;!this.eof()&&/[0-9]/.test(this.char());)e+=this.chars[this.index++];if(this.skipWhitespaceInRepetition(),e===``)return;let t=Number(e);return t>4294967295&&this.fail(`repetition count is too large`),t}parseCountedRepetition(e){let t=e[e.length-1];(t===void 0||t.kind===`flags`)&&this.fail(`repetition operator missing expression`),this.index++,this.eof()&&this.fail(`unclosed counted repetition`);let n=this.parseDecimal();this.eof()&&this.fail(`unclosed counted repetition`);let r;if(this.char()===`,`)if(this.index++,this.eof()&&this.fail(`unclosed counted repetition`),this.char()!==`}`){let e=this.parseDecimal();(n===void 0||e===void 0)&&this.fail(`repetition count is empty`),r=e}else n===void 0&&this.fail(`repetition count is empty`),r=1/0;else n===void 0&&this.fail(`repetition count is empty`),r=n;(this.eof()||this.char()!==`}`)&&this.fail(`unclosed counted repetition`),this.index++;let i=!0;!this.eof()&&this.char()===`?`&&(i=!1,this.index++),n>r&&this.fail(`invalid repetition range`),this.repeatLast(e,n,r,i)}parseGroup(e){let t=this.index===0;this.index++;for(let t of[`=`,`!`,`<=`,`<!`])if(this.startsWith(`?${t}`))return this.fancy=!0,this.index+=t.length+1,{kind:`look`,op:t,body:this.parseGroupBody(e)};if(this.startsWith(`?P<`)||this.startsWith(`?<`))return this.index+=this.startsWith(`?P<`)?3:2,this.captures++,this.parseCaptureName(),{kind:`group`,capture:!0,body:this.parseGroupBody(e)};if(!this.eof()&&this.char()===`?`){this.index++,this.eof()&&this.fail(`unclosed group`);let n=this.flags,r=this.parseFlags(),i=this.char();if(this.index++,i===`)`)return r!==void 0&&(r&&t?this.caseInsensitive=!0:this.unsupported.push("`(?i)` anywhere but at the start of the pattern")),{kind:`flags`};r!==void 0&&this.unsupported.push("`(?i)` anywhere but at the start of the pattern");let a=this.parseGroupBody(e);return this.flags=n,{kind:`group`,capture:!1,body:a}}return this.captures++,{kind:`group`,capture:!0,body:this.parseGroupBody(e)}}parseGroupBody(e){let t=this.flags,n=this.parseAlternation(e+1);return this.eof()&&this.fail(`unclosed group`),this.index++,this.flags=t,n}parseCaptureName(){this.eof()&&this.fail(`unexpected end of group name`);let e=``;for(;!this.eof()&&this.char()!==`>`;){let t=this.char();(e===``?t===`_`||/\p{Alphabetic}/u.test(t):t===`_`||t===`.`||t===`[`||t===`]`||/[\p{Alphabetic}\p{N}]/u.test(t))||this.fail(`invalid group name`),e+=t,this.index++}this.eof()&&this.fail(`unexpected end of group name`),this.index++,e===``&&this.fail(`empty group name`),this.names.has(e)&&this.fail(`duplicate group name "${e}"`),this.names.add(e)}parseFlags(){let e=new Set,t=!1,n=!1,r,i={...this.flags};for(;this.char()!==`:`&&this.char()!==`)`;){let a=this.char();if(a===`-`)t&&this.fail(`repeated negation in flags`),t=!0,n=!0;else{n=!1,Cd.has(a)||this.fail(`unrecognized flag "${a}"`),e.has(a)&&this.fail(`duplicate flag "${a}"`),e.add(a);let o=!t;a===`i`?r=o:a===`m`?i.multiLine=o:a===`s`?i.dotAll=o:a===`U`?i.swapGreed=o:a===`x`?this.unsupported.push("the `x` flag"):a===`R`?this.unsupported.push("the `R` flag"):a===`u`&&!o&&this.unsupported.push("turning off the `u` flag")}this.index++,this.eof()&&this.fail(`unexpected end of flags`)}return n&&this.fail(`dangling flag negation`),e.size===0&&this.char()===`)`&&this.fail(`repetition operator missing expression`),this.flags=i,r}parsePrimitive(){let e=this.char();return e===`\\`?this.parseEscape(!1):(this.index++,e===`.`?{kind:`dot`,dotAll:this.flags.dotAll}:e===`^`?this.assertion(`start`):e===`$`?this.assertion(`end`):{kind:`literal`,char:e})}assertion(e){return{kind:`assertion`,assertion:e,multiLine:this.flags.multiLine}}parseEscape(e){this.index++,this.eof()&&this.fail(`incomplete escape`);let t=this.char();if(/[0-9]/.test(t)){this.fancy=!0;let t=``;for(;!this.eof()&&/[0-9]/.test(this.char());)t+=this.chars[this.index++];return(e||t.startsWith(`0`))&&this.unsupported.push(`\`\\${t}\``),{kind:`backref`,index:Number(t)}}if(t===`x`||t===`u`||t===`U`)return{kind:`literal`,char:this.parseHex(t)};if(t===`p`||t===`P`)return{kind:`class`,item:this.parseUnicodeClass(t===`P`)};if(`dswDSW`.includes(t)){this.index++;let e=t.toLowerCase();return{kind:`class`,item:{kind:`perl`,perl:e,negated:t!==e}}}if(this.index++,Td(t))return{kind:`literal`,char:t};let n={f:`\f`,t:` `,n:`
5
- `,r:`\r`,v:`\v`};if(n[t]!==void 0)return{kind:`literal`,char:n[t]};if(t===`a`)return e||(this.bellOutsideClass=!0),{kind:`literal`,char:`\x07`};if(t===`c`){let e=this.eof()?void 0:this.char();return(e===void 0||!/[A-Za-z]/.test(e))&&this.fail("invalid `\\c` escape"),this.index++,{kind:`literal`,char:String.fromCharCode(e.charCodeAt(0)%32)}}return e&&`AzbB<>`.includes(t)&&this.fail(`\`\\${t}\` is not allowed in a class`),t===`A`?this.assertion(`startText`):t===`z`?this.assertion(`endText`):t===`B`?this.assertion(`notWordBoundary`):t===`<`?this.assertion(`wordStart`):t===`>`?this.assertion(`wordEnd`):t===`b`?this.assertion(this.parseSpecialWordBoundary()):this.fail(`unrecognized escape \`\\${t}\``)}parseSpecialWordBoundary(){if(this.eof()||this.char()!==`{`)return`wordBoundary`;let e=this.index;if(this.index++,this.eof()&&this.fail(`unexpected end of special word boundary`),!/[A-Za-z-]/.test(this.char()))return this.index=e,`wordBoundary`;let t=``;for(;!this.eof()&&/[A-Za-z-]/.test(this.char());)t+=this.chars[this.index++];return(this.eof()||this.char()!==`}`)&&this.fail(`unclosed special word boundary`),this.index++,{start:`wordStart`,end:`wordEnd`,"start-half":`wordStartHalf`,"end-half":`wordEndHalf`}[t]??this.fail(`unrecognized special word boundary "${t}"`)}parseHex(e){this.index++,this.eof()&&this.fail(`incomplete hex escape`);let t=``;if(this.char()===`{`){for(this.index++;!this.eof()&&this.char()!==`}`;)/[0-9A-Fa-f]/.test(this.char())||this.fail(`invalid hex digit`),t+=this.chars[this.index++];this.eof()&&this.fail(`incomplete hex escape`),this.index++,t===``&&this.fail(`empty hex escape`)}else{let n=e===`x`?2:e===`u`?4:8;for(let e=0;e<n;e++)this.eof()&&this.fail(`incomplete hex escape`),/[0-9A-Fa-f]/.test(this.char())||this.fail(`invalid hex digit`),t+=this.chars[this.index++]}let n=parseInt(t,16);return(t.length>8||n>1114111||n>=55296&&n<=57343)&&this.fail(`invalid Unicode scalar value`),String.fromCodePoint(n)}parseUnicodeClass(e){if(this.index++,this.eof()&&this.fail(`incomplete Unicode class`),this.char()===`{`){this.index++;let t=``;for(;!this.eof()&&this.char()!==`}`;)t+=this.chars[this.index++];this.eof()&&this.fail(`incomplete Unicode class`),this.index++;let n=t.indexOf(`!=`);return n>=0?{kind:`unicode`,name:`${t.slice(0,n)}=${t.slice(n+2)}`,negated:!e}:{kind:`unicode`,name:t.replace(`:`,`=`),negated:e}}let t=this.char();return t===`\\`&&this.fail(`invalid Unicode class`),this.index++,{kind:`unicode`,name:t,negated:e}}parseBracketed(){this.index++,this.eof()&&this.fail(`unclosed class`);let e=!1;this.char()===`^`&&(e=!0,this.index++,this.eof()&&this.fail(`unclosed class`));let t=[];for(;this.char()===`-`;)t.push({kind:`literal`,char:`-`}),this.index++,this.eof()&&this.fail(`unclosed class`);t.length===0&&this.char()===`]`&&(t.push({kind:`literal`,char:`]`}),this.index++,this.eof()&&this.fail(`unclosed class`));let n,r,i=()=>{let e={kind:`union`,items:t};return n===void 0?e:{kind:`op`,op:r,lhs:n,rhs:e}};for(;;){this.eof()&&this.fail(`unclosed class`);let a=this.char();if(a===`[`){let e=this.maybeParseAsciiClass();t.push(e??this.parseBracketed())}else if(a===`]`)return this.index++,{kind:`bracket`,negated:e,set:i()};else (a===`&`||a===`-`||a===`~`)&&this.peek()===a?(n=i(),r=`${a}${a}`,t=[],this.index+=2):t.push(this.parseClassRange())}}maybeParseAsciiClass(){let e=/^\[:(\^?)([^:]*):\]/.exec(this.chars.slice(this.index).join(``));if(!(!e||!wd.has(e[2])))return this.index+=[...e[0]].length,{kind:`ascii`,ascii:e[2],negated:e[1]===`^`}}parseClassItem(){return this.char()===`\\`?this.parseEscape(!0):{kind:`literal`,char:this.chars[this.index++]}}parseClassRange(){let e=this.parseClassItem();if(this.eof()&&this.fail(`unclosed class`),this.char()!==`-`||this.peek()===`]`||this.peek()===`-`)return this.toClassItem(e);this.index++,this.eof()&&this.fail(`unclosed class`);let t=this.parseClassItem();return(e.kind!==`literal`||t.kind!==`literal`)&&this.fail(`class ranges need literal endpoints`),e.char.codePointAt(0)>t.char.codePointAt(0)&&this.fail(`invalid class range`),{kind:`range`,start:e.char,end:t.char}}toClassItem(e){return e.kind===`literal`?{kind:`literal`,char:e.char}:e.kind===`class`?e.item:{kind:`literal`,char:`\0`}}},Dd={alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]],d:[[48,57]],w:[[48,57],[65,90],[95,95],[97,122]],s:[[9,13],[32,32],[160,160],[8195,8195],[8233,8233],[65279,65279]]},Od=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,kd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:Od};function Ad(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function jd(e){return e.map(([e,t])=>{let n=Ad(String.fromCodePoint(e));return e===t?n:`${n}-${Ad(String.fromCodePoint(t))}`}).join(``)}var Md=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Ad(e.char);case`dot`:return e.dotAll?`[^]`:`[^\\n]`;case`assertion`:return this.assertion(e.assertion,e.multiLine);case`class`:return this.item(e.item).atom;case`group`:return`(${e.capture&&this.parsed.fancy?``:`?:`}${this.emit(e.body)})`;case`look`:return`(?${e.op}${this.emit(e.body)})`;case`backref`:if(e.index===0||e.index>this.parsed.captures)throw new xd(`backreference \`\\${e.index}\``);return`\\${e.index}(?:)`;case`repeat`:{let{min:t,max:n}=e,r=n===1/0?t===0?`*`:t===1?`+`:`{${t},}`:t===0&&n===1?`?`:t===n?`{${t}}`:`{${t},${n}}`;return`(?:${this.emit(e.body)})${r}${e.greedy?``:`?`}`}case`concat`:return e.items.map(e=>this.emit(e)).join(``);case`alternation`:return e.items.map(e=>this.emit(e)).join(`|`)}}assertion(e,t){let n=`[${Od}]`;switch(e){case`start`:return t?`(?<![^\\n])`:`^`;case`end`:return t?`(?![^\\n])`:`$`;case`startText`:return`^`;case`endText`:return`$`;case`wordBoundary`:return`(?:(?<=${n})(?!${n})|(?<!${n})(?=${n}))`;case`notWordBoundary`:return`(?:(?<=${n})(?=${n})|(?<!${n})(?!${n}))`;case`wordStart`:return`(?<!${n})(?=${n})`;case`wordEnd`:return`(?<=${n})(?!${n})`;case`wordStartHalf`:return`(?<!${n})`;case`wordEndHalf`:return`(?!${n})`}}item(e){switch(e.kind){case`literal`:{let t=Ad(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Ad(e.start)}-${Ad(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Nd(this.parsed.fancy?kd[e.perl]:jd(Dd[e.perl]),e.negated);case`ascii`:return Nd(jd(Dd[e.ascii]),e.negated);case`unicode`:return Nd(Pd(e.name),e.negated);case`bracket`:{let t=this.set(e.set);return e.negated?t.fragment===void 0?{atom:`(?:(?!${t.atom})[^])`}:{atom:`[^${t.fragment}]`}:t}}}set(e){if(e.kind===`union`){let t=e.items.map(e=>this.item(e));if(t.every(e=>e.fragment!==void 0)){let e=t.map(e=>e.fragment).join(``);return{fragment:e,atom:`[${e}]`}}return{atom:`(?:${t.map(e=>e.atom).join(`|`)})`}}let t=this.set(e.lhs).atom,n=this.set(e.rhs).atom;switch(e.op){case`&&`:return{atom:`(?:(?=${t})${n})`};case`--`:return{atom:`(?:(?!${n})${t})`};case`~~`:return{atom:`(?:(?!${n})${t}|(?!${t})${n})`}}}};function Nd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Pd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new xd(`the Unicode class \`${e}\``)}function Fd(e){try{return new Ed(e).parse(),!0}catch(e){return e instanceof xd}}var Id=new Map,Ld=1024;function Rd(e){let t=Id.get(e);if(t)return t;let n=new Ed(e).parse();if(n.fancyInvalid.length>0)throw new bd(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new xd(n.unsupported[0]);let r=new Md(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),Id.size>=Ld&&Id.clear(),Id.set(e,t),t}function zd(e,t){let n=e.charCodeAt(t)-48,r=e.charCodeAt(t+1)-48;if(!(n<0||n>9||r<0||r>9))return n*10+r}function Bd(e){return e%4==0&&e%100!=0||e%400==0}function Vd(e){if(e.length!==10||e[4]!==`-`||e[7]!==`-`||!/^[0-9]{4}$/.test(e.slice(0,4)))return!1;let t=Number(e.slice(0,4)),n=zd(e,5),r=zd(e,8);return n===void 0||n<1||n>12||r===void 0||r===0?!1:n===2?r<=(Bd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function Hd(e){if(e.length<9||e[2]!==`:`||e[5]!==`:`)return!1;let t=zd(e,0),n=zd(e,3),r=zd(e,6);if(t===void 0||n===void 0||r===void 0||t>23||n>59||r>60)return!1;let i=8;if(e[i]===`.`){i++;let t=i;for(;i<e.length&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i===t)return!1}if(i===e.length)return!1;let a=e[i];if(a===`Z`||a===`z`)return i===e.length-1&&(r!==60||t===23&&n===59);if(a!==`+`&&a!==`-`||e.length-i!==6||e[i+3]!==`:`)return!1;let o=zd(e,i+1),s=zd(e,i+4);if(o===void 0||s===void 0||o>23||s>59)return!1;if(r!==60)return!0;let c=a===`+`?-1:1,l=t+c*o,u=n+c*s;return l+=Math.trunc(u/60),u%=60,u<0&&(u+=60,--l),l=(l+24)%24,l===23&&u===59}function Ud(e){let t=e.search(/[Tt]/);return t<0?!1:Vd(e.slice(0,t))&&Hd(e.slice(t+1))}var Wd=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,Gd=`${Wd}(?:\\.${Wd}){3}`,Y=`[0-9A-Fa-f]{1,4}`,Kd=`(?:${Y}:${Y}|${Gd})`,qd=[`(?:${Y}:){6}${Kd}`,`::(?:${Y}:){5}${Kd}`,`(?:${Y})?::(?:${Y}:){4}${Kd}`,`(?:(?:${Y}:){0,1}${Y})?::(?:${Y}:){3}${Kd}`,`(?:(?:${Y}:){0,2}${Y})?::(?:${Y}:){2}${Kd}`,`(?:(?:${Y}:){0,3}${Y})?::${Y}:${Kd}`,`(?:(?:${Y}:){0,4}${Y})?::${Kd}`,`(?:(?:${Y}:){0,5}${Y})?::${Y}`,`(?:(?:${Y}:){0,6}${Y})?::`].map(e=>`(?:${e})`).join(`|`),Jd=RegExp(`^${Gd}$`),Yd=RegExp(`^(?:${qd})$`),Xd=e=>Jd.test(e),Zd=e=>Yd.test(e);function Qd(e){if(e.length===0||e.length>253||e.endsWith(`.`)||!/^[A-Za-z0-9.-]*$/.test(e))return!1;let t=e.split(`.`);for(let e of t){if(e.length===0||e.length>63||e.startsWith(`-`)||e.endsWith(`-`))return!1;let t=e.startsWith(`xn--`);if(e.slice(2,4)===`--`&&!t)return!1;if(t){let t=af(e.slice(4));if(t===void 0||!lf(t))return!1}}return!0}var $d=36,ef=1,tf=26,nf=4294967295;function rf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>($d-ef)*tf>>1;)r=Math.trunc(r/($d-ef)),i+=$d;return i+Math.trunc(($d-ef+1)*r/(r+38))}function af(e){let t=e.lastIndexOf(`-`),n=t>0?e.slice(0,t):``,r=t>0?e.slice(t+1):e,i=[...n].map(e=>e.charCodeAt(0)),a=128,o=72,s=0,c=0;for(;c<r.length;){let e=s,t=1;for(let e=$d;;e+=$d){if(c>=r.length)return;let n=of(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>nf||s>nf))return;let i=e<=o?ef:e>=o+tf?tf:e-o;if(n<i)break;if(t*=$d-i,t>nf)return}let n=i.length+1;if(o=rf(s-e,n,e===0),a+=Math.trunc(s/n),a>nf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function of(e){if(e>=48&&e<=57)return e-48+26;if(e>=65&&e<=90)return e-65;if(e>=97&&e<=122)return e-97}var sf=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3405,3530,3642,3972,4153,5908,5940,6098,6752,6980,7082,7154,7155,11647,43014,43204,43347,44013,68159,69702,69759,69817,69939,70080,70197,70378,70477,70722,70850,71103,71231,71350,71467,71737,72160,72244,72263,72345,72767,73028,73029,73111].map(e=>String.fromCodePoint(e))),cf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function lf(e){let t=[...e];if(t.length>0&&/^\p{M}/u.test(t[0]))return!1;let n=!1,r=!1,i=!1,a=!1;for(let e=0;e<t.length;e++){let o=t[e],s=t[e-1],c=t[e+1],l=o.codePointAt(0);if(o===`‍`){if(s===void 0||!sf.has(s))return!1}else if(o===`·`){if(s!==`l`||c!==`l`)return!1}else if(o===`͵`){let e=c?.codePointAt(0);if(e===void 0||e<880||e>1023)return!1}else if(o===`׳`||o===`״`){let e=s?.codePointAt(0);if(e===void 0||e<1424||e>1535)return!1}else if(o===`・`)n=!0;else if(l>=12352&&l<=12447||l>=12448&&l<=12543||l>=19968&&l<=40959)r=!0;else if(l>=1632&&l<=1641)i=!0;else if(l>=1776&&l<=1785)a=!0;else if(cf.has(o))return!1}return!(n&&!r||i&&a)}var uf=new TextEncoder;function df(e){return uf.encode(e).length}function ff(e){let t=e.codePointAt(0),n=t>>>24,r=t>>>16&255,i=t>>>8&255,a=t&255,o=e=>e>=128&&e<=191;return n===0&&r===0?i>=194&&i<=223&&o(a):n===0?r===224?i>=160&&i<=191&&o(a):r>=225&&r<=236?o(i)&&o(a):r===237?i>=128&&i<=159&&o(a):r===238||r===239?o(i)&&o(a):!1:n===240?r>=144&&r<=191&&o(i)&&o(a):n>=241&&n<=243?o(r)&&o(i)&&o(a):n===244?r>=128&&r<=143&&o(i)&&o(a):!1}var pf=/^[\p{Alphabetic}\p{N}]$/u,mf=new Set("!#$%&'*+-/=?^_`{|}~");function hf(e){return pf.test(e)||mf.has(e)||ff(e)}function gf(e){return e.length>0&&[...e].every(hf)}function _f(e){let t=[...e];for(let e=0;e<t.length;e++){let n=t[e],r=n.codePointAt(0);if(n===`\\`){let n=t[++e]?.codePointAt(0);if(n===void 0||n<33||n>126)return!1}else if(!(n===` `||n===` `||r===33||r>=35&&r<=91||r>=93&&r<=126||ff(n)))return!1}return!0}function vf(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||ff(e)}function yf(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function bf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=yf(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=yf(e.slice(0,r))}let i=t.lastIndexOf(`@`);if(i<0)return!1;let a=t.slice(0,i),o=t.slice(i+1);if(n===``&&a.startsWith(`<`)||a.length===0||df(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!_f(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(gf))return!1;if(o.length===0||df(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(vf)?e.startsWith(`IPv6:`)?Zd(e.slice(5)):Xd(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!pf.test(t[0])||!pf.test(t[t.length-1])||df(e)>63||!gf(e))return!1}return Qd(o)}var xf=`A-Za-z0-9\\-._~`,Sf=`!$&'()*+,;=`,Cf=`%[0-9A-Fa-f]{2}`,wf=`(?:[${xf}${Sf}:@]|${Cf})`,Tf=`${wf}*`,Ef=`${wf}+`,Df=`(?:[${xf}${Sf}@]|${Cf})+`,Of=`\\[(?:${qd}|[vV][0-9A-Fa-f]+\\.[${xf}${Sf}:]+)\\]`,kf=`(?:[${xf}${Sf}]|${Cf})*`,Af=`(?:${`(?:[${xf}${Sf}:]|${Cf})*`}@)?(?:${Of}|${kf})(?::[0-9]*)?`,jf=`(?:/${Tf})*`,Mf=`/(?:${Ef}(?:/${Tf})*)?`,Nf=`${Ef}(?:/${Tf})*`,Pf=`${Df}(?:/${Tf})*`,Ff=`(?:${wf}|[/?])*`,If=`[A-Za-z][A-Za-z0-9+\\-.]*`,Lf=`(?://${Af}${jf}|${Mf}|${Nf}|)`,Rf=`(?://${Af}${jf}|${Mf}|${Pf}|)`,zf=`(?:\\?${Ff})?(?:#${Ff})?`,Bf=RegExp(`^${If}:${Lf}${zf}$`),Vf=RegExp(`^(?:${If}:${Lf}|${Rf})${zf}$`);function Hf(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function Uf(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&Hf(n)}var Wf=new Set(`+#./;?&=,!@|`),Gf=new Set(`"'<>%\\^\`{|}`);function Kf(e){let t=0,n=t=>/^[0-9A-Fa-f]$/.test(e[t]??``),r=t=>/^[A-Za-z0-9_]$/.test(e[t]??``),i=()=>{let i=t;for(;t<e.length;)if(r(t))t++;else if(e[t]===`%`){if(t+2>=e.length||!n(t+1)||!n(t+2))return!1;t+=3}else break;return t>i},a=()=>{if(!i())return!1;for(;t<e.length;)if(e[t]===`.`){if(t++,!i())return!1}else if(r(t)||e[t]===`%`){if(!i())return!1}else break;return!0},o=()=>{if(!a())return!1;if(e[t]===`:`){if(t++,!/^[1-9]$/.test(e[t]??``))return!1;t++;for(let n=1;n<4&&/^[0-9]$/.test(e[t]??``);n++)t++}else e[t]===`*`&&t++;return!0};for(;t<e.length;){let r=e[t];if(r===`{`){if(t++,t>=e.length||Wf.has(e[t])&&(t++,t>=e.length)||!o())return!1;for(;e[t]===`,`;)if(t++,!o())return!1;if(e[t]!==`}`)return!1;t++}else if(r===`}`)return!1;else if(r===`%`){if(t+2>=e.length||!n(t+1)||!n(t+2))return!1;t+=3}else{let n=e.charCodeAt(t);if(n<=32||n===127||Gf.has(r))return!1;t++}}return!0}var qf={date:Vd,"date-time":Ud,email:bf,hostname:Qd,ipv4:Xd,ipv6:Zd,"json-pointer":Hf,regex:Fd,"relative-json-pointer":Uf,time:Hd,uri:e=>Bf.test(e),"uri-reference":e=>Vf.test(e),"uri-template":Kf},Jf=class{value;constructor(e){this.value=e}},Yf=2n**64n-1n,Xf=-(2n**63n),Zf=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,Qf=/[ \t\n\r]*/y;function $f(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{Qf.lastIndex=t,Qf.test(e),t=Qf.lastIndex},i=()=>{let r=t;t++;let i=!1;for(;t<e.length;){let a=e.charCodeAt(t);if(a===34){t++;let n=e.slice(r,t);return i?JSON.parse(n):n.slice(1,-1)}a===92?(i=!0,t++):a<32&&n(),t++}return n()},a=()=>{Zf.lastIndex=t;let r=Zf.exec(e);if(!r)return n();t=Zf.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new Jf(a):a;if(Object.is(a,-0))return new Jf(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<Xf||o>Yf?new Jf(a):BigInt(a)===o?a:o},o=()=>{r();let s=e[t];if(s===`{`){t++;let a=Object.create(null);if(r(),e[t]===`}`)return t++,a;for(;;){r(),e[t]!==`"`&&n();let s=i();if(r(),e[t]!==`:`&&n(),t++,a[s]=o(),r(),e[t]===`,`)t++;else if(e[t]===`}`)return t++,a;else n()}}if(s===`[`){t++;let i=[];if(r(),e[t]===`]`)return t++,i;for(;;)if(i.push(o()),r(),e[t]===`,`)t++;else if(e[t]===`]`)return t++,i;else n()}return s===`"`?i():e.startsWith(`true`,t)?(t+=4,!0):e.startsWith(`false`,t)?(t+=5,!1):e.startsWith(`null`,t)?(t+=4,null):a()},s=o();return r(),t!==e.length&&n(),s}function ep(e){return typeof e==`number`||typeof e==`bigint`||e instanceof Jf}function tp(e){return e instanceof Jf?e.value:e}function np(e,t){return typeof e==`bigint`?!0:e instanceof Jf?!t:Number.isInteger(e)}function rp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof Jf){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):ip(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?ip(e):Array.isArray(e)?`[${e.map(rp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${rp(t)}`).join(`,`)}}`:JSON.stringify(e)}function ip(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function ap(e){if(e instanceof Jf)return e.value;if(Array.isArray(e))return e.map(ap);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=ap(r);return t}function op(e,t){if(ep(e))return ep(t)?tp(e)==tp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>op(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||ep(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&op(e[n],t[n])):!1}return e===t}function sp(e,t){let n=Number(tp(e)),r=Number(tp(t));if(Number.isInteger(r))return Number.isInteger(n)&&n%r===0;if(n===0)return!0;if(n<r)return!1;let[i,a]=cp(n),[o,s]=cp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function cp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*lp(10,t),!Number.isFinite(n))return up(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(lp(10,t))]}function lp(e,t){let n=1,r=e;for(let e=t;e&1&&(n*=r),e=Math.trunc(e/2),e!==0;)r*=r;return n}function up(e){let[t,n]=Math.abs(e).toExponential().split(`e`),[r,i=``]=t.split(`.`),a=Number(n)-i.length,o=BigInt(r+i),s=1n;return a>=0?o*=10n**BigInt(a):s=10n**BigInt(-a),[e<0?-o:o,s]}var dp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},fp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},pp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mp=new URL(`json-schema:///`);function hp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function gp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _p(e,t=Object.create(null),n=[],r=mp,i=!0){let a=(e,n)=>{t[e]===void 0&&(t[e]=n)};if(typeof e==`boolean`)return i&&a(r.href,e),t;if(!gp(e))return t;let o=e.$id??e.id;if(typeof o==`string`){let t=new URL(o,r.href);t.hash.length>1?a(t.href,e):(t.hash=``,r=t,a(t.href,e))}if(i&&a(r.href,e),typeof e.$ref==`string`&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href}),n.push(t.href)}if(typeof e.$recursiveRef==`string`&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}typeof e.$anchor==`string`&&a(new URL(`#`+e.$anchor,r.href).href,e);for(let i in e){let a=e[i];if(fp[i]&&Array.isArray(a))for(let e of a)_p(e,t,n,r,!1);else if(dp[i])_p(a,t,n,r,!1);else if((pp[i]||i===`dependencies`)&&gp(a))for(let e in a)_p(a[e],t,n,r,!1)}return t}function vp(e,t){let n=e[t];if(n!==void 0)return n;let r=t.indexOf(`#`);if(r<0)return;let i=e[t.slice(0,r)],a=t.slice(r+1);if(!(i===void 0||!a.startsWith(`/`))){for(let e of a.slice(1).split(`/`)){let t;try{t=decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}catch{return}if(Array.isArray(i)){if(!/^(?:0|[1-9][0-9]*)$/.test(t))return;i=i[Number(t)]}else if(gp(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||gp(i)?i:void 0}}function yp(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r>=55296&&r<=56319&&n+1<e.length&&(e.charCodeAt(n+1)&64512)==56320&&n++,t++}return t}function bp(e){if(e===null)return`null`;if(ep(e))return`number`;if(Array.isArray(e))return`array`;switch(typeof e){case`boolean`:case`string`:return typeof e;case`object`:return`object`;default:throw Error(`Instances of "${typeof e}" type are not supported.`)}}function xp(e,t,n,r,i){return X(e,t,{draft:n,lookup:r,shortCircuit:i},null,`#`,`#`)}function X(e,t,n,r,i,a,o=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:`false`,keywordLocation:i,error:`False boolean schema.`}]};let{draft:s,lookup:c,shortCircuit:l}=n,u=bp(e),{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:E,patternProperties:D,additionalProperties:O,unevaluatedProperties:ee,minProperties:te,maxProperties:ne,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:k,prefixItems:oe,items:se,additionalItems:ce,unevaluatedItems:le,contains:ue,minContains:A,maxContains:de,minItems:fe,maxItems:pe,uniqueItems:me,minimum:he,maximum:j,exclusiveMinimum:ge,exclusiveMaximum:_e,multipleOf:ve,minLength:M,maxLength:ye,pattern:be,__absolute_ref__:xe,__absolute_recursive_ref__:Se}=t,N=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?vp(c,Se):r,l=`${a}/$recursiveRef`,u=X(e,r===null?t:r,n,s,i,l,o);u.valid||N.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=vp(c,xe??d);if(t===void 0)throw Error(`Unresolved $ref "${d}".`);let l=`${a}/$ref`,u=X(e,t,n,r,i,l,o);if(u.valid||N.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:N.length===0,errors:N}}let Ce=u===`number`&&np(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&Ce)||N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?Ce||N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!op(e,h)&&N.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${rp(h)}.`}),g!==void 0&&!g.some(t=>op(e,t))&&N.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${rp(g)}.`}),v!==void 0){let t=`${a}/not`;X(e,v,n,r,i,t).valid&&N.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let we=[];if(y!==void 0){let t=`${a}/anyOf`,s=N.length,c=!1;for(let a=0;a<y.length;a++){let s=Object.create(o),l=X(e,y[a],n,p===!0?r:null,i,`${t}/${a}`,s);N.push(...l.errors),c||=l.valid,l.valid&&we.push(s)}c?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${a}/allOf`,s=N.length,c=!0;for(let a=0;a<b.length;a++){let s=Object.create(o),l=X(e,b[a],n,p===!0?r:null,i,`${t}/${a}`,s);N.push(...l.errors),c&&=l.valid,l.valid&&we.push(s)}c?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${a}/oneOf`,s=N.length,c=x.filter((a,s)=>{let c=Object.create(o),l=X(e,a,n,p===!0?r:null,i,`${t}/${s}`,c);return N.push(...l.errors),l.valid&&we.push(c),l.valid}).length;c===1?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${c} matches).`})}if((u===`object`||u===`array`)&&Object.assign(o,...we),S!==void 0){let t=`${a}/if`,s=Object.create(o);if(X(e,S,n,r,i,t,s).valid){if(Object.assign(o,s),C!==void 0){let s=X(e,C,n,r,i,`${a}/then`,o);s.valid||N.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...s.errors)}}else if(w!==void 0){let s=X(e,w,n,r,i,`${a}/else`,o);s.valid||N.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...s.errors)}}if(u===`object`){let t=e;if(_!==void 0)for(let e of _)e in t||N.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(te!==void 0&&s.length<te&&N.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0&&s.length>ne&&N.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${ne} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${hp(a)}`,o=X(a,re,n,r,t,e);o.valid||N.push({instanceLocation:i,keyword:`propertyNames`,keywordLocation:e,error:`Property name "${a}" does not match schema.`},...o.errors)}}if(ie!==void 0){let e=`${a}/dependentRequired`;for(let n in ie)if(n in t)for(let r of ie[n])r in t||N.push({instanceLocation:i,keyword:`dependentRequired`,keywordLocation:e,error:`Instance has "${n}" but does not have "${r}".`})}if(ae!==void 0)for(let s in ae){let c=`${a}/dependentSchemas`;if(s in t){let t=X(e,ae[s],n,r,i,`${c}/${hp(s)}`,o);t.valid||N.push({instanceLocation:i,keyword:`dependentSchemas`,keywordLocation:c,error:`Instance has "${s}" but does not match dependant schema.`},...t.errors)}}if(k!==void 0){let o=`${a}/dependencies`;for(let a in k)if(a in t){let s=k[a];if(Array.isArray(s))for(let e of s)e in t||N.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not have "${e}".`});else{let t=X(e,s,n,r,i,`${o}/${hp(a)}`);t.valid||N.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not match dependant schema.`},...t.errors)}}}let c=Object.create(null),u=!1;if(E!==void 0){let e=`${a}/properties`;for(let a in E){if(!(a in t))continue;let s=`${i}/${hp(a)}`,d=X(t[a],E[a],n,r,s,`${e}/${hp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,N.push({instanceLocation:i,keyword:`properties`,keywordLocation:e,error:`Property "${a}" does not match schema.`},...d.errors),u)break}}if(!u&&D!==void 0){let e=`${a}/patternProperties`;for(let a in D){let s=Rd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${hp(f)}`,m=X(t[f],d,n,r,p,`${e}/${hp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,N.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&O!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${hp(a)}`,d=X(t[a],O,n,r,s,e);d.valid?o[a]=!0:(u=l,N.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&ee!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${hp(a)}`,c=X(t[a],ee,n,r,s,e);c.valid?o[a]=!0:N.push({instanceLocation:i,keyword:`unevaluatedProperties`,keywordLocation:e,error:`Property "${a}" does not match unevaluated properties schema.`},...c.errors)}}}else if(u===`array`){let t=e,s=t.length;pe!==void 0&&s>pe&&N.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${pe}).`}),fe!==void 0&&s<fe&&N.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${fe}).`});let c=0,u=!1;if(oe!==void 0){let e=`${a}/prefixItems`,d=Math.min(oe.length,s);for(;c<d;c++){let a=X(t[c],oe[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(se!==void 0){let e=`${a}/items`;if(Array.isArray(se)){let a=Math.min(se.length,s);for(;c<a;c++){let a=X(t[c],se[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}else for(;c<s;c++){let a=X(t[c],se,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}if(!u&&ce!==void 0){let e=`${a}/additionalItems`;for(;c<s;c++){let a=X(t[c],ce,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,N.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(ue!==void 0)if(s===0&&A===void 0)N.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(A!==void 0&&s<A)N.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${A}).`});else{let e=`${a}/contains`,c=N.length,l=0;for(let a=0;a<s;a++){let s=X(t[a],ue,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):N.push(...s.errors)}l>=(A||0)&&(N.length=c),A===void 0&&de===void 0&&l===0?N.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):A!==void 0&&l<A?N.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${A} items matching schema. Only ${l} items were found.`}):de!==void 0&&l>de&&N.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${de} items matching schema. ${l} items were found.`})}if(!u&&le!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=X(t[c],le,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||N.push({instanceLocation:i,keyword:`unevaluatedItems`,keywordLocation:e,error:`Items did not match unevaluated items schema.`},...a.errors)}}if(me){outer:for(let e=0;e<s;e++)for(let n=e+1;n<s;n++)if(op(t[e],t[n])){N.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=tp(e);s===`4`?(he!==void 0&&(ge===!0&&t<=he||t<he)&&N.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${ge?`or equal to `:``}${he}.`}),j!==void 0&&(_e===!0&&t>=j||t>j)&&N.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${_e?`or equal to `:``}${j}.`})):(he!==void 0&&t<he&&N.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${he}.`}),j!==void 0&&t>j&&N.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${j}.`}),ge!==void 0&&t<=ge&&N.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${ge}.`}),_e!==void 0&&t>=_e&&N.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${_e}.`})),ve!==void 0&&!sp(e,ve)&&N.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ve}.`})}else if(u===`string`){let t=e,n=M===void 0&&ye===void 0?0:yp(t);M!==void 0&&n<M&&N.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${M}).`}),ye!==void 0&&n>ye&&N.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${ye}).`}),be!==void 0&&!Rd(be).test(t)&&N.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:qf[T];r&&!r(t)&&N.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:N.length===0,errors:N}}var Sp={draft4:[{id:`http://json-schema.org/draft-04/schema#`,$schema:`http://json-schema.org/draft-04/schema#`,description:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},positiveInteger:{type:`integer`,minimum:0},positiveIntegerDefault0:{allOf:[{$ref:`#/definitions/positiveInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},minItems:1,uniqueItems:!0}},type:`object`,properties:{id:{type:`string`},$schema:{type:`string`},title:{type:`string`},description:{type:`string`},default:{},multipleOf:{type:`number`,minimum:0,exclusiveMinimum:!0},maximum:{type:`number`},exclusiveMaximum:{type:`boolean`,default:!1},minimum:{type:`number`},exclusiveMinimum:{type:`boolean`,default:!1},maxLength:{$ref:`#/definitions/positiveInteger`},minLength:{$ref:`#/definitions/positiveIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{anyOf:[{type:`boolean`},{$ref:`#`}],default:{}},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:{}},maxItems:{$ref:`#/definitions/positiveInteger`},minItems:{$ref:`#/definitions/positiveIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxProperties:{$ref:`#/definitions/positiveInteger`},minProperties:{$ref:`#/definitions/positiveIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{anyOf:[{type:`boolean`},{$ref:`#`}],default:{}},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},enum:{type:`array`},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},dependencies:{exclusiveMaximum:[`maximum`],exclusiveMinimum:[`minimum`]},default:{}}],draft6:[{$schema:`http://json-schema.org/draft-06/schema#`,$id:`http://json-schema.org/draft-06/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},title:{type:`string`},description:{type:`string`},default:{},examples:{type:`array`,items:{}},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:{}},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:{},enum:{type:`array`},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:{}}],draft7:[{$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}],draft201909:[{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/schema`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format`},{$ref:`meta/content`}],type:[`object`,`boolean`],properties:{definitions:{$comment:`While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.`,type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},dependencies:{$comment:`"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"`,type:`object`,additionalProperties:{anyOf:[{$recursiveRef:`#`},{$ref:`meta/validation#/$defs/stringArray`}]}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/core`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{type:`string`,format:`uri`},$anchor:{type:`string`,pattern:`^[A-Za-z][-A-Za-z0-9.:_]*$`},$ref:{type:`string`,format:`uri-reference`},$recursiveRef:{type:`string`,format:`uri-reference`},$recursiveAnchor:{type:`boolean`,default:!1},$vocabulary:{type:`object`,propertyNames:{type:`string`,format:`uri`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{additionalItems:{$recursiveRef:`#`},unevaluatedItems:{$recursiveRef:`#`},items:{anyOf:[{$recursiveRef:`#`},{$ref:`#/$defs/schemaArray`}]},contains:{$recursiveRef:`#`},additionalProperties:{$recursiveRef:`#`},unevaluatedProperties:{$recursiveRef:`#`},properties:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$recursiveRef:`#`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$recursiveRef:`#`}},propertyNames:{$recursiveRef:`#`},if:{$recursiveRef:`#`},then:{$recursiveRef:`#`},else:{$recursiveRef:`#`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$recursiveRef:`#`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$recursiveRef:`#`}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/format`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:`Format vocabulary meta-schema`,type:[`object`,`boolean`],properties:{format:{type:`string`}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/content`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentMediaType:{type:`string`},contentEncoding:{type:`string`},contentSchema:{$recursiveRef:`#`}}}],draft202012:[{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}]},Cp={"json-schema.org/draft/2020-12/schema":`2020-12`,"json-schema.org/draft/2019-09/schema":`2019-09`,"json-schema.org/draft-07/schema":`7`,"json-schema.org/draft-06/schema":`6`,"json-schema.org/draft-04/schema":`4`},wp=new Set(`$anchor.$id.$recursiveAnchor.$recursiveRef.$ref.additionalItems.additionalProperties.allOf.anyOf.const.contains.dependencies.dependentRequired.dependentSchemas.else.enum.exclusiveMaximum.exclusiveMinimum.format.id.if.items.maxContains.maxItems.maxLength.maxProperties.maximum.minContains.minItems.minLength.minProperties.minimum.multipleOf.not.oneOf.pattern.patternProperties.prefixItems.properties.propertyNames.required.then.type.unevaluatedItems.unevaluatedProperties.uniqueItems`.split(`.`)),Tp={single:[`additionalItems`,`additionalProperties`,`items`,`not`],array:[`allOf`,`anyOf`,`items`,`oneOf`],map:[`definitions`,`dependencies`,`patternProperties`,`properties`],plain:[`$ref`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`id`,`maxItems`,`maxLength`,`maxProperties`,`maximum`,`minItems`,`minLength`,`minProperties`,`minimum`,`multipleOf`,`pattern`,`required`,`type`,`uniqueItems`]},Ep={...Tp,single:[...Tp.single,`contains`,`propertyNames`],plain:[...Tp.plain.filter(e=>e!==`id`),`$id`,`const`]},Dp={...Ep,single:[...Ep.single,`if`,`then`,`else`]},Op={single:[...Dp.single,`unevaluatedItems`,`unevaluatedProperties`],array:Dp.array,map:[...Dp.map,`$defs`,`dependentSchemas`],plain:[...Dp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},kp={single:Op.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Op.map,plain:Op.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)},Ap={4:Tp,6:Ep,7:Dp,"2019-09":Op,"2020-12":kp},jp={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Mp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Np=[...Mp,`json-pointer`,`uri-reference`,`uri-template`],Pp={4:Mp,6:Np,7:[...Np,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},Fp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Ip={base64:Lp(`A-Za-z0-9+/`),base64url:Lp(`A-Za-z0-9\\-_`),base32:Rp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:Rp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Lp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function Rp(e,t,n,r,i){let a=`[${e}]`;return`^(?:${a}{8})*(?:${a}[${t}]={6}|${a}{3}[${n}]={4}|${a}{4}[${r}]={3}|${a}{6}[${i}]=)?$`}var zp=class extends Error{};function Bp(e){if(!F(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Cp[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new zp(`unknown JSON Schema dialect "${t}"`);return n}function Vp(e,t,n=[]){if(typeof e==`boolean`)return e;if(!F(e))return{};let r=Ap[t],i=new Set([...r.single,...r.array,...r.map,...r.plain,...n]),a=typeof e.$ref==`string`&&[`4`,`6`,`7`].includes(t),o=[];for(let[s,c]of Object.entries(e)){if(jp[t].includes(s)&&!n.includes(s))throw new zp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(wp.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&Up(c),s===`patternProperties`&&F(c))for(let e of Object.keys(c))Up(e);if(s===`format`&&typeof c==`string`){if(!Pp[t]?.includes(c))continue;if(Fp.includes(c))throw new zp(`the "${c}" format is not supported by the browser runtime yet`)}r.array.includes(s)&&Array.isArray(c)?o.push([s,c.map(e=>Vp(e,t,n))]):r.single.includes(s)?o.push([s,Vp(c,t,n)]):r.map.includes(s)&&F(c)?o.push([s,Hp(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Ip[s];if(e){let t=o.find(([e])=>e===`allOf`);t?t[1]=[...t[1],{pattern:e}]:o.push([`allOf`,[{pattern:e}]])}}return Object.fromEntries(o)}function Hp(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:Vp(r,t,n)]))}function Up(e){try{Rd(e)}catch(t){throw t instanceof bd?new zp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof xd?new zp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function Wp(e){for(let t of e.references)if(vp(e.lookup,t)===void 0)throw new zp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function Gp(e){if(Array.isArray(e))return e.map(Gp);if(!F(e))return e;let t=[];for(let[n,r]of Object.entries(e))n===`$dynamicAnchor`?t.push([`$recursiveAnchor`,!0]):n===`$dynamicRef`?t.push([`$recursiveRef`,`#`]):t.push([n,Gp(r)]);return Object.fromEntries(t)}var Kp={4:Sp.draft4,6:Sp.draft6,7:Sp.draft7,"2019-09":Sp.draft201909,"2020-12":Sp.draft202012};function qp(e){return Kp[e].map(t=>e===`2020-12`?Gp(Vp(t,e,[`$dynamicAnchor`,`$dynamicRef`])):Vp(t,e))}var Jp=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=_p(e,void 0,this.references);for(let e of r)_p(e,this.lookup)}validate(e){return xp(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},Yp=new Map;function Xp(e){let t=Yp.get(e);if(!t){let[n,...r]=qp(e);t=new Jp(n,e,!1,r),Yp.set(e,t)}return t}function Zp(e){let t=e[e.length-1];if(!t)return`value does not match the schema`;let n=t.instanceLocation.replace(/^#/,``);return n?`${t.error} (at ${n})`:t.error}function Qp(e){let t=Bp(e);if(typeof e==`boolean`){if(t===`4`)throw new zp(`boolean schemas need draft 6 or later`)}else{let n=Xp(t).validate(e);if(!n.valid)throw new zp(Zp(n.errors))}let n=new Jp(Vp(ap(e),t),t,!0,qp(t));return Wp(n),e=>{let t=n.validate($f(e));return t.valid?void 0:Zp(t.errors)}}function $p(e){return Qp($f(e))}function em(e){e.setJsonSchemaValidator($p)}async function tm(){let e=process.getBuiltinModule?.(`module`),t=process.getBuiltinModule?.(`fs`),n=process.getBuiltinModule?.(`path`);if(!e||!t||!n)return null;let{createRequire:r}=e,{existsSync:i,readFileSync:a}=t,{dirname:o,resolve:s}=n,c={}.JAZZ_CORRECTNESS_WASM_PACKAGE;if({}.JAZZ_CORRECTNESS_ARTIFACT_RUN===`1`&&!c)throw Error(`sealed correctness consumer is missing its admitted WASM package`);if(c){let e=s(c,`jazz_wasm_bg.wasm`);return i(e)?a(e):null}let l=s(o(r(import.meta.url).resolve(`jazz-wasm/package.json`)),`pkg/jazz_wasm_bg.wasm`);return i(l)?a(l):null}var nm=Promise.resolve(),rm;function im(e){let t=nm.then(()=>am(e));return nm=t.then(()=>void 0,()=>void 0),t}async function am(t){let n=await e(()=>import(`./jazz_wasm-C2VuKMqv.js`),[],import.meta.url),r=Qr(t);if(r)return n.initSync(r),om(n);let i=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await tm();e&&(n.initSync({module:e}),i=!0)}catch{}if(!i&&typeof n.default==`function`){let e=typeof location<`u`?$r(Vr,location.href,t)??Ur():null;if(e)await sm(n,e);else if(typeof location<`u`&&Gi())throw Error(Ui);else await n.default()}return om(n)}function om(e){return yd(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),em(e),e}async function sm(e,t){if(rm===t)return;let n=await fetch(t);if(!n.ok)throw Error(`WASM asset request failed (${n.status} ${n.statusText}) for ${t}`);let r=n.headers.get(`content-type`);if(cm(r)){let i;try{i=await WebAssembly.compileStreaming(n)}catch(e){throw e instanceof WebAssembly.CompileError?Error(`WASM asset response is not a WebAssembly binary for ${t} (${r}): ${e.message}`):e}await e.default({module_or_path:i}),rm=t;return}let i=new Uint8Array(await n.arrayBuffer());if(i.length<4||i[0]!==0||i[1]!==97||i[2]!==115||i[3]!==109)throw Error(`WASM asset response is not a WebAssembly binary for ${t} (${r??`unknown content type`})`);await e.default({module_or_path:i}),rm=t}function cm(e){return typeof WebAssembly.compileStreaming==`function`?e?.trim()===`application/wasm`:!1}function lm(e){return{captureAnchor:(t,n,r,i)=>e.captureTextAnchor(t,i,n,r),resolveAnchor:(t,n,r)=>e.resolveTextAnchor(t,n,r),captureRange:(t,n,r,i)=>e.captureTextRange(t,i,n,r),resolveRange:(t,n,r)=>e.resolveTextRange(t,n,r)}}function um(e,t,n,r){return Rr(`${ut}${e}`,{audience:t,ttlSeconds:n,now:r})}var dm=class{supportsBrowserWorker=!1;supportsPolicyBypass=!0;async load(e){await this.loadRuntime(e)}nativeConnection;assertAuthUpdateAllowed(){}refreshAccountToken(e){return!1}admitConfig(e){}async shutdown(){}async loadRuntime(e){}async acquireForegroundNodeLease(e){}acquireBrowserForegroundNodeLease(e){return Promise.reject(Error(`Db runtime source does not support browser foreground leases`))}createBrowserWorkerConnection(e){throw Error(`Db runtime source does not support browser worker connections`)}createBrowserFollowerConnection(e){throw Error(`Db runtime source does not support browser follower connections`)}installTelemetry(e){return null}mintLocalFirstToken(e){return um(e.secret,e.audience,e.ttlSeconds,Number(e.nowSeconds))}mintAnonymousToken(e){throw Error(`Db runtime source does not support anonymous auth`)}textAnchors(){throw Error(`Db runtime source does not support text anchors yet`)}};async function*fm(e){let t=e;if(typeof t.getReader!=`function`){let t=e[Symbol.asyncIterator](),n=!1;try{for(;;){let e=await t.next();if(e.done){n=!0;return}yield e.value}}finally{if(!n)try{Promise.resolve(t.return?.()).catch(()=>void 0)}catch{}}}let n=t.getReader(),r=!1;try{for(;;){let e=await n.read();if(e.done){r=!0;return}yield e.value}}finally{if(!r)try{Promise.resolve(n.cancel()).catch(()=>void 0)}catch{}n.releaseLock()}}var pm=`authority_changed`,mm=class extends Error{name=`AuthorityChangedError`;code=pm;constructor(e,t){super(e,t)}};function hm(e){return!e||typeof e!=`object`?!1:e.code===pm}function gm(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(hm(e))return new mm(t,{cause:e});if(e instanceof Error)return e;let n=Error(t),r=typeof e==`object`?e.code:void 0;return typeof r==`string`&&Object.assign(n,{code:r}),n}var _m=`core_tick_failed`,vm=class extends Error{name=`CoreTickFailedError`;code=_m;constructor(e){super(`core tick failed: ${bm(e)}`,{cause:e})}};function ym(e){return!e||typeof e!=`object`?!1:e.code===_m}function bm(e){if(e instanceof Error)return e.message;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`)return t}return String(e)}var xm=class extends ms{},Sm=class{text;constructor(e){this.text=e}};function Cm(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){if(++t>=e.length||e.charCodeAt(t)<56320||e.charCodeAt(t)>57343)throw Error(`invalid relation query: unpaired surrogate`)}else if(n>=56320&&n<=57343)throw Error(`invalid relation query: unpaired surrogate`)}}function wm(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Cm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Cm(e),e.includes(t)||n(r,t))):!1,r=`__jrq_raw_number_`;for(;e.includes(r)||n(t,r);)r=`_${r}`;let i=[],a=``,o=!1,s=!1;for(let t=0;t<e.length;t++){let n=e[t];if(o){a+=n,s?s=!1:n===`\\`?s=!0:n===`"`&&(o=!1);continue}if(n===`"`){o=!0,a+=n;continue}if(n===`-`||n>=`0`&&n<=`9`){let n=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(e.slice(t));if(n){i.push(n[0]),a+=JSON.stringify(`${r}${i.length-1}__`),t+=n[0].length-1;continue}}a+=n}let c=e=>{if(typeof e==`string`){let t=RegExp(`^${r}(\\d+)__$`).exec(e);return t?new Sm(i[Number(t[1])]):e}return Array.isArray(e)?e.map(c):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,c(t)])):e};return c(JSON.parse(a))}function Tm(e){let t=4096,n=[],r=0,i=0,a=new TextEncoder,o=e=>{throw Error(`invalid relation Postcard: ${e}`)},s=(...e)=>{e.some(e=>!Number.isInteger(e)||e<0||e>255)&&o(`byte`),n.length>1048576-e.length&&o(`byte limit`),n.push(...e)},c=e=>{(!Number.isSafeInteger(e)||e<0||e>t)&&o(`collection`),d(e)},l=()=>{++i>t&&o(`node limit`)},u=e=>{++r>128&&o(`depth limit`);try{e()}finally{r--}},d=e=>{let t=typeof e==`bigint`?e:BigInt(e);(t<0n||t>18446744073709551615n)&&o(`integer range`);do{let e=Number(t&127n);t>>=7n,t&&(e|=128),s(e)}while(t)},f=e=>d(e<0n?(-e<<1n)-1n:e<<1n),p=e=>{typeof e!=`string`&&o(`string`),Cm(e);let t=a.encode(e);t.length>65536&&o(`string limit`),d(t.length),s(...t)},m=(e,t)=>{e==null?s(0):(s(1),t())},h=(e,t,n)=>{let r=Object.keys(e);(r.length!==1||!t.includes(r[0]))&&o(n)},g=(e,t,n)=>{Object.keys(e).some(e=>!t.includes(e))&&o(n)},_=e=>{e instanceof Sm&&(/^(?:0|[1-9]\d*)$/.test(e.text)||o(`dimension`),e=Number(e.text));let t=typeof e==`number`?e:o(`dimension`);(!Number.isSafeInteger(t)||t<0||t>4294967295)&&o(`dimension`),d(t)},v=e=>{(!e||typeof e!=`object`)&&o(`column`),g(e,[`scope`,`column`],`column`),(typeof e.column!=`string`||e.scope!==void 0&&typeof e.scope!=`string`)&&o(`column`),m(e.scope,()=>p(e.scope)),p(e.column)},y=e=>d(e===`Current`?0:e===`Outer`?1:e===`Frontier`?2:o(`row id`)),b=e=>{if(l(),e instanceof Sm){if(/^(?:0|[1-9]\d*|-[1-9]\d*)$/.test(e.text)){let t=BigInt(e.text);if(t>=-9223372036854775808n&&t<=9223372036854775807n){d(2),f(t);return}if(t>=0n&&t<=18446744073709551615n){d(3),d(t);return}}let t=Number(e.text);Number.isFinite(t)||o(`number`),d(4);let n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t,!0),d(n.getBigUint64(0,!0));return}if(e===null){d(0);return}if(typeof e==`boolean`){d(1),s(e?1:0);return}if(typeof e==`number`){if(Number.isFinite(e)||o(`number`),Number.isInteger(e)&&!Object.is(e,-0)){let t=JSON.stringify(e);if(/^(?:0|[1-9]\d*|-[1-9]\d*)$/.test(t)){let e=BigInt(t);if(e>=-9223372036854775808n&&e<=9223372036854775807n){d(2),f(e);return}if(e>=0n&&e<=18446744073709551615n){d(3),d(e);return}}}d(4);let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!0),d(t.getBigUint64(0,!0));return}if(typeof e==`string`){d(5),p(e);return}if(Array.isArray(e)){d(6),c(e.length),e.forEach(e=>u(()=>b(e)));return}(!e||typeof e!=`object`)&&o(`literal`),d(7);let t=Object.entries(e).sort(([e],[t])=>{let n=a.encode(e),r=a.encode(t);for(let e=0;e<Math.min(n.length,r.length);e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length});c(t.length);for(let[e,n]of t)p(e),u(()=>b(n))},x=e=>{l(),h(e,[`Column`,`RowId`],`key`),`Column`in e?(d(0),v(e.Column)):(d(1),y(e.RowId))},S=e=>{l(),h(e,[`Column`,`RowId`],`project`),`Column`in e?(d(0),v(e.Column)):(d(1),y(e.RowId))},C=e=>{l(),h(e,[`Literal`,`Param`,`SessionRef`,`OuterColumn`,`FrontierColumn`,`RowId`],`value`),`Literal`in e?(d(0),b(e.Literal)):`Param`in e?(d(1),p(e.Param)):`SessionRef`in e?(d(2),c(e.SessionRef.length),e.SessionRef.forEach(p)):`OuterColumn`in e?(d(3),v(e.OuterColumn)):`FrontierColumn`in e?(d(4),v(e.FrontierColumn)):(d(5),y(e.RowId))},w=e=>{if(l(),e===`True`){d(9);return}if(e===`False`){d(10);return}if(h(e,[`Cmp`,`IsNull`,`IsNotNull`,`In`,`Contains`,`And`,`Or`,`Not`],`predicate`),`Cmp`in e){d(0),v(e.Cmp.left);let t=[`Eq`,`Ne`,`Lt`,`Le`,`Gt`,`Ge`].indexOf(e.Cmp.op);t<0&&o(`comparison operator`),d(t),u(()=>C(e.Cmp.right))}else `IsNull`in e?(d(1),v(e.IsNull.column)):`IsNotNull`in e?(d(2),v(e.IsNotNull.column)):`In`in e?(d(3),v(e.In.left),c(e.In.values.length),e.In.values.forEach(e=>u(()=>C(e)))):`Contains`in e?(d(4),v(e.Contains.left),u(()=>C(e.Contains.right))):`And`in e?(d(6),c(e.And.length),e.And.forEach(e=>u(()=>w(e)))):`Or`in e?(d(7),c(e.Or.length),e.Or.forEach(e=>u(()=>w(e)))):(d(8),u(()=>w(e.Not)))},T=e=>{l(),h(e,[`TableScan`,`Filter`,`Union`,`Join`,`Project`,`Gather`,`Distinct`,`OrderBy`,`Offset`,`Limit`],`expression`),`TableScan`in e?(g(e.TableScan,[`table`,`alias`],`table scan`),d(0),p(e.TableScan.table),m(e.TableScan.alias,()=>p(e.TableScan.alias))):`Filter`in e?(d(1),u(()=>T(e.Filter.input)),u(()=>w(e.Filter.predicate))):`Union`in e?(d(2),c(e.Union.inputs.length),e.Union.inputs.forEach(e=>{p(e.label),u(()=>T(e.input))})):`Join`in e?(g(e.Join,[`left`,`right`,`on`,`join_kind`],`join`),d(3),u(()=>T(e.Join.left)),u(()=>T(e.Join.right)),c(e.Join.on.length),e.Join.on.forEach(e=>{l(),v(e.left),v(e.right)}),e.Join.join_kind!==`Inner`&&e.Join.join_kind!==`Left`&&o(`join kind`),d(e.Join.join_kind===`Inner`?0:1)):`Project`in e?(d(4),u(()=>T(e.Project.input)),c(e.Project.columns.length),e.Project.columns.forEach(e=>{p(e.alias),S(e.expr)})):`Gather`in e?(d(5),u(()=>T(e.Gather.seed)),u(()=>T(e.Gather.step)),x(e.Gather.frontier_key),e.Gather.bound===`Fixpoint`?d(0):(d(1),_(e.Gather.bound.MaxDepth)),c(e.Gather.dedupe_key.length),e.Gather.dedupe_key.forEach(x)):`Distinct`in e?(d(6),u(()=>T(e.Distinct.input)),c(e.Distinct.key.length),e.Distinct.key.forEach(x)):`OrderBy`in e?(d(7),u(()=>T(e.OrderBy.input)),c(e.OrderBy.terms.length),e.OrderBy.terms.forEach(e=>{l(),g(e,[`column`,`direction`],`order term`),v(e.column),e.direction!==`Asc`&&e.direction!==`Desc`&&o(`order direction`),d(e.direction===`Asc`?0:1)})):`Offset`in e?(d(8),u(()=>T(e.Offset.input)),_(e.Offset.offset)):(d(9),u(()=>T(e.Limit.input)),_(e.Limit.limit))};return T(e),Uint8Array.from(n)}Pe({issuer:tt,user_id:`system`,claims:{},authMode:`external`});var Em=-(1n<<63n),Dm=(1n<<63n)-1n;function Om(e,t){if(typeof e==`number`&&!Number.isSafeInteger(e))throw Error(`${t} must be a safe integer when passed as a number, got ${e}`);let n=BigInt(e);if(n<Em||n>Dm)throw Error(`${t} must be a signed 64-bit integer`);return n}var km=new T({fatal:!0});function Am(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function jm(e){return{table:e.string(),descriptor:Nm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Mm(e,t){e.vec((e,n)=>{let r=t[n];e.u64(r.kind===`stored-column`?0:r.kind===`result-field`?1:2),r.kind===`stored-column`?(e.u64(r.id),e.string(r.outputName)):e.string(r.name),Um(e,r.valueType)},t.length)}function Nm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:Wm(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:Wm(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:Wm(e)}:Pm(t)})}function Pm(e){throw Error(`unknown native row descriptor field kind ${e}`)}function Fm(e){let t={added:e.readVec(jm),updated:e.readVec(jm),removed:e.readVec(Bm),addedOccurrenceKeys:e.readVec(e=>Im(e)),updatedOccurrenceKeys:e.readVec(e=>Im(e)),removedOccurrenceKeys:e.readVec(e=>Im(e)),addedIndices:e.readVec(e=>e.u64()),updatedPreviousIndices:e.readVec(e=>e.u64()),updatedIndices:e.readVec(e=>e.u64()),removedIndices:e.readVec(e=>e.u64()),updatedSplices:e.readVec(e=>e.readVec(e=>({column:e.string(),splices:e.readVec(e=>({at:e.u64(),delete:e.u64(),insert:e.bytes(),atUtf16:e.u64(),deleteUtf16:e.u64()}))})))},n=e=>e.reduce((e,t)=>e+t.rows.length,0);if(t.addedOccurrenceKeys.length!==n(t.added)||t.updatedOccurrenceKeys.length!==n(t.updated)||t.removedOccurrenceKeys.length!==t.removed.length||t.addedIndices.length!==n(t.added)||t.updatedPreviousIndices.length!==n(t.updated)||t.updatedIndices.length!==n(t.updated)||t.removedIndices.length!==t.removed.length||t.updatedSplices.length!==n(t.updated))throw Error(`subscription occurrence sidecar length mismatch`);return zm(e,`subscription delta`),t}function Im(e){let t=e.bytes();if(t[0]!==2||!Lm(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Lm(e){let t=t=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;if(e.length<25)return!1;let n=16,r=t(n);if(n+=4,r>256||n+r*16+4>e.length)return!1;n+=r*16;let i=t(n);if(n+=4,i>r+1)return!1;let a=-1;for(let o=0;o<i;o++){if(n+8>e.length)return!1;let i=t(n),o=t(n+4);if(n+=8,i>r||i<=a||o===0||o>4096||n+o>e.length||!le(e.subarray(n,n+o)))return!1;a=i,n+=o}for(let t=0;t<=r;t++){let t=e[n++];if(t===1)n+=24;else if(t!==0)return!1}return n===e.length}function Rm(e){let t=e.u64(),n=e.readVec(jm);return zm(e,`relation snapshot`),{rootCount:t,rows:n}}function zm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Bm(e){return{table:e.string(),rowId:e.bytes()}}function Vm(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),Um(e,t[n].valueType)},t.length)}function Hm(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:Wm(e)}))}function Um(e,t){if(e.enumUnit(t.tag),t.tag===10){if(!t.internal)throw Error(`missing physical type for ValueType::Internal`);if(e.enumUnit(t.internal.tag),t.internal.tag===2){if(t.internal.kind==null)throw Error(`missing stored-scalar kind`);e.enumUnit(t.internal.kind)}return}if(t.tag===12){let n=t.enumSchema,r=n?.variants;if(!n||!r)throw Error(`missing enum schema for ValueType::Enum`);e.u64(n.registryId??0),e.string(n.name),e.vec((e,t)=>e.string(r[t]),r.length);return}if(t.tag===13){let n=t.members??(t.inner?[t.inner]:[]);e.vec((e,t)=>Um(e,n[t]),n.length);return}if(t.tag===14||t.tag===15){if(!t.inner)throw Error(`missing inner value type for tag ${t.tag}`);Um(e,t.inner);return}if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);Vm(e,t.record);return}if(t.tag===17){let n=t.enumSchema,r=n?.cases;if(!n||!r)throw Error(`missing cases for ValueType::Enum`);e.u64(n.registryId??0),e.string(n.name),e.vec((e,t)=>{let n=r[t];e.string(n.name),Vm(e,n.payload)},r.length)}}function Wm(e){let t=e.u64();if(t===10){let n=e.u64();return{tag:t,internal:{tag:n,kind:n===2?e.u64():void 0}}}if(t===12)return{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),variants:e.readVec(e=>e.string())}};if(t===14||t===15)return{tag:t,inner:Wm(e)};if(t===13){let n=e.readVec(Wm);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:Hm(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:Hm(e)}))}}:{tag:t}}function Gm(e,t){let n=Dh(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=Te(r),o=new jh,s=a.length+Math.max(0,i.length-1)*4;for(let e of i.slice(0,-1))s+=e.length,o.u32Le(s);return Te([a,o.finish(),...i])}function Km(e,t){let n=th(sh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:yh(e.column_type,i)})}function qm(e,t){return Object.defineProperty(e,`valuesByColumn`,{value:t,enumerable:!1,configurable:!0}),e}function Jm(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r];i&&n.set(i.name,t[r])}return n}var Ym={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function Xm(e,t,n){let r=Zm([Ym,...t],n),i=r[0];if(i?.type!==`Uuid`||i.value!==e)throw Error(`terminal record key ${i?.type===`Uuid`?i.value:`<non-uuid>`} does not match addressed key ${e}`);let a=r.slice(1);return qm({id:e,values:a},Jm(t,a))}function Zm(e,t){let n=th(sh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:Qm(e.column_type,i,e.name)})}function Qm(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:wh(t,n)};case`Array`:return{type:`Array`,value:$m(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:Xm(Th(t.subarray(0,16)),e.columns,t)};default:return yh(e,t)}}function $m(e,t){return Ch(e,t,t=>Qm(e,t))}function eh(e,t){return Gm(sh(e),e.map((e,n)=>ch(e,t[n])))}function th(e){let t=Dh(e);return(n,r)=>nh(e,t,n,r)}function nh(e,t,n,r){let i=t.fields[r];if(!i)throw Error(`field is not present`);let a=e[r].valueType;if(i.kind===`fixed`){if(i.offset+i.size>n.length)throw Error(`unexpected end of record`);return rh(n.subarray(i.offset,i.offset+i.size),a)}let o=t.fixedSize,s=t.fixedSize+Math.max(0,t.variable.length-1)*4,c=i.variableIndex===0?s:Oh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Oh(n,o+i.variableIndex*4);if(c>l||l>n.length){let t=e[r],i=l-c,o=Math.max(0,n.length-c);throw Error(`invalid offset for ${t?.name??`<field ${r}>`}: declared type ${ih(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return rh(n.subarray(c,l),a)}function rh(e,t){if(t.tag!==15)return e;let n=oh(e);return n==null?null:t.inner?rh(n,t.inner):n}function ih(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?ih(e.inner):`?`}>`:ah(e.tag)}function ah(e){switch(e){case 0:return`U8`;case 1:return`U16`;case 2:return`U32`;case 3:return`U64`;case 4:return`I32`;case 5:return`I64`;case 6:return`F64`;case 7:return`Bool`;case 8:return`String`;case 9:return`Bytes`;case 10:return`Internal`;case 11:return`Uuid`;case 12:return`EnumTag`;case 13:return`Tuple`;case 14:return`Array`;case 15:return`Nullable`;case 16:return`Record`;case 17:return`Enum`;default:return`unknown(${e})`}}function oh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function sh(e){return e.map(e=>({name:e.name,valueType:gh(e)}))}function ch(e,t){let n=vh(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return uh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return uh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=uh(r);return e.sparse?lh(t,r):t}let i=dh(e.column_type,t);return e.nullable&&(i=lh(i,n)),e.sparse?lh(i,r):i}function lh(e,t){if(Eh(t)==null)return Te([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function uh(e){let t=Eh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function dh(e,t){switch(e.type){case`Boolean`:if(t.type!==`Boolean`)throw Error(`expected Boolean value`);return Uint8Array.of(t.value?1:0);case`Integer`:{let e=kh(t),n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),n}case`Timestamp`:{if(t.type!==`Timestamp`||!Number.isSafeInteger(t.value))throw Error(`expected ${e.type} value`);if(t.value<0)throw Error(`Timestamp value must be a non-negative safe integer (dates before 1970 are not supported), got ${t.value}`);let n=new Uint8Array(8);return new DataView(n.buffer).setBigUint64(0,BigInt(t.value),!0),n}case`BigInt`:{let e=Ah(t),n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,e,!0),n}case`Double`:{if(t.type!==`Double`)throw Error(`expected Double value`);let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.value,!0),e}case`Text`:case`Json`:case`Enum`:if(t.type!==`Text`)throw Error(`expected ${e.type} value`);return Te([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return hh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return Te([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return ph(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return fh(e.columns,t.value)}}function fh(e,t){let n=eh(e,t.valuesByColumn?e.map(e=>t.valuesByColumn?.get(e.name)??(e.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`})):t.values),r=t.id?hh(t.id):new Uint8Array;return Te([Uint8Array.of(t.id?1:0),r,mh(n.byteLength),n])}function ph(e,t){let n=t.map(t=>dh(e,t));if(Eh(vh(e))!=null)return Te(n);let r=new Uint8Array(Math.max(0,t.length-1)*4),i=new DataView(r.buffer),a=4+r.byteLength;return n.slice(0,-1).forEach((e,t)=>{a+=e.length,i.setUint32(t*4,a,!0)}),Te([mh(t.length),r,...n])}function mh(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function hh(e){let t=Ze(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function gh(e){let t=vh(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function _h(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[..._h(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[..._h(e.column_type.element.columns)]}}:e.column_type}))}function vh(e){switch(e.type){case`Boolean`:return{tag:7};case`Integer`:return{tag:4};case`BigInt`:return{tag:5};case`Timestamp`:return{tag:3};case`Double`:return{tag:6};case`Text`:case`Json`:case`Enum`:return{tag:8};case`Bytea`:return{tag:9};case`Uuid`:return{tag:11};case`Array`:return{tag:14,inner:vh(e.element)};case`Row`:return{tag:9}}}function yh(e,t){let n=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e.type){case`Boolean`:return{type:`Boolean`,value:t[0]!==0};case`Integer`:return{type:`Integer`,value:n.getInt32(0,!0)};case`BigInt`:return{type:`BigInt`,value:n.getBigInt64(0,!0)};case`Double`:return{type:`Double`,value:n.getFloat64(0,!0)};case`Timestamp`:return{type:`Timestamp`,value:Number(n.getBigUint64(0,!0))};case`Text`:case`Json`:case`Enum`:return{type:`Text`,value:km.decode(bh(t))};case`Uuid`:return{type:`Uuid`,value:Th(t)};case`Bytea`:return{type:`Bytea`,value:bh(t).slice()};case`Array`:return{type:`Array`,value:Sh(e.element,t)};case`Row`:return{type:`Row`,value:xh(e.columns,t)}}}function bh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function xh(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Th(t.subarray(r,r+16)),r+=16);let a=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(r,!0);r+=4;let o=t.subarray(r,r+a);if(o.byteLength!==a)throw Error(`invalid nested row value length`);let s=Km(e,o);return qm({id:i,values:s},Jm(e,s))}function Sh(e,t){return Ch(e,t,t=>yh(e,t))}function Ch(e,t,n){let r=Eh(vh(e));if(r!=null){if(r===0)return[];if(t.length%r!==0)throw Error(`invalid fixed-width array byte length ${t.length}`);let e=[];for(let i=0;i<t.length;i+=r)e.push(n(t.subarray(i,i+r)));return e}if(t.length<4)throw Error(`invalid variable-width array byte length`);let i=Oh(t,0),a=4+Math.max(0,i-1)*4;if(a>t.length)throw Error(`invalid variable-width array offset table`);let o=[];for(let e=0;e<i;e+=1){let r=e===0?a:Oh(t,4+(e-1)*4),s=e===i-1?t.length:Oh(t,4+e*4);if(r>s||s>t.length)throw Error(`invalid variable-width array element offset`);o.push(n(t.subarray(r,s)))}return o}function wh(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Th(e){if(e.length>=16)return Ge(e,0);let t=Ie(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Eh(e){switch(e.tag){case 0:case 7:case 12:return 1;case 1:return 2;case 2:case 4:return 4;case 3:case 5:case 6:return 8;case 11:return 16;case 13:return(e.members??(e.inner?[e.inner]:[])).reduce((e,t)=>{if(e==null)return;let n=Eh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Eh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function Dh(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Eh(e[r].valueType);if(a==null)continue;let o={kind:`fixed`,logicalIndex:r,offset:i,size:a};t[r]=o,n.push(o),i+=a}for(let n=0;n<e.length;n+=1){if(Eh(e[n].valueType)!=null)continue;let i={kind:`variable`,logicalIndex:n,variableIndex:r.length};t[n]=i,r.push(i)}return{fields:t,fixed:n,variable:r,fixedSize:i}}function Oh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function kh(e){if(e.type!==`Integer`||!Number.isSafeInteger(e.value)||e.value<-2147483648||e.value>2147483647)throw Error(`Integer value must be a signed 32-bit integer`);return e.value}function Ah(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Om(e.value,`BigInt value`)}var jh=class{#e=[];u32Le(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`offset must be an unsigned 32-bit integer, got ${e}`);this.#e.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}finish(){return new Uint8Array(this.#e)}},Mh=new T({fatal:!0}),Nh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Ph(e,t){return t?Nh:e}function Fh(e,t,n,r=!1,i,a,o,s){let c=new Xh;return c.bytes(e),c.string(Ih(Ph(t,a))),n==null?c.none():c.some(e=>e.u64(n)),c.bool(r),i==null?c.none():c.some(e=>e.u64(i)),o==null?c.none():c.some(e=>e.bytes(Qh(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Ih(e){try{let t=Mh.decode(e);if(D(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Lh(e,t,n={}){let{limit:r,offset:i=0,orderBy:a=[],select:o,arraySubqueries:s=[],relation:c,partial:l=[]}=typeof n==`number`?{limit:n}:n;r!=null&&Bh(`query limit`,r),Bh(`query offset`,i);let u=new Xh;return u.string(e),u.vec((e,n)=>{let r=t[n];Hh(e,r)},t.length),u.vec(()=>void 0,0),u.none(),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec((e,t)=>{zh(e,s[t])},s.length),o==null?u.none():u.some(e=>{e.vec((e,t)=>{e.string(o[t])},o.length)}),u.vec((e,t)=>{let n=a[t];e.string(n.column),e.u64(n.direction===`Asc`?0:1)},a.length),u.none(),r==null?u.none():u.some(e=>e.u64(r)),u.u64(i),c==null?u.none():u.some(e=>e.bytes(Tm(c),!1)),Rh(u,l),u.finish()}function Rh(e,t){e.vec((e,n)=>{let r=t[n];if(e.string(r.column),r.kind===`json_pointer`){e.u64(3),e.string(r.at);return}Bh(`partial selection ${r.column} start`,r.from),Bh(`partial selection ${r.column} end`,r.to),e.u64(r.kind===`bytes`?0:r.kind===`text_utf16`?1:2),e.u64(r.from),e.u64(r.to)},t.length)}function zh(e,t){let{filters:n=[],select:r,orderBy:i=[],limit:a=null,offset:o=0,requirement:s=`Optional`,nestedArrays:c=[]}=t;a!=null&&Bh(`array subquery ${t.columnName} limit`,a),Bh(`array subquery ${t.columnName} offset`,o),e.string(t.columnName),e.string(t.table),e.string(t.innerColumn),e.string(t.outerColumn),e.vec((e,t)=>{Hh(e,n[t])},n.length),r==null?e.none():e.some(e=>{e.vec((e,t)=>{e.string(r[t])},r.length)}),e.vec((e,t)=>{let n=i[t];e.string(n.column),e.u64(n.direction===`Asc`?0:1)},i.length),a==null?e.none():e.some(e=>e.u64(a)),e.u64(o),e.u64(Vh(s)),e.vec((e,t)=>{zh(e,c[t])},c.length),Rh(e,[])}function Bh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function Vh(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function Hh(e,t){if(t.op===`All`||t.op===`Any`){e.u64(t.op===`All`?0:1),e.vec((e,n)=>Hh(e,t.predicates[n]),t.predicates.length);return}if(t.op===`Not`){e.u64(2),Hh(e,t.predicate);return}if(t.op===`In`){e.u64(5),Gh(e,t.column),e.vec((e,n)=>{e.u64(3),Jh(e,t.values[n])},t.values.length);return}if(t.op===`Contains`){e.u64(10),Gh(e,t.column),Kh(e,t.value);return}if(t.op===`IsNull`||t.op===`IsNotNull`){t.op===`IsNotNull`&&e.u64(2),e.u64(12),Gh(e,t.column);return}if(Uh(t)){Wh(e,t.column,t.op,t.value);return}throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Uh(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Wh(e,t,n,r){e.u64(qh(n)),Gh(e,t),Kh(e,r)}function Gh(e,t){e.u64(0),e.string(t)}function Kh(e,t){e.u64(3),Jh(e,t)}function qh(e){switch(e){case`Eq`:return 3;case`Ne`:return 4;case`Gt`:return 6;case`Gte`:return 7;case`Lt`:return 8;case`Lte`:return 9}}function Jh(e,t){if(t.type===`U64`){if(t.value<0n||t.value>(1n<<64n)-1n)throw Error(`U64 value must be an unsigned 64-bit integer`);e.u64(3),e.u64(t.value);return}if(t.type===`Nullable`){e.u64(13),t.value==null?e.none():e.some(e=>Jh(e,t.value));return}if(t.type===`Boolean`){e.u64(5),e.bool(t.value);return}if(t.type===`Integer`){if(!Number.isSafeInteger(t.value)||t.value<-2147483648||t.value>2147483647)throw Error(`Integer value must be a signed 32-bit integer`);e.u64(15),e.i64(t.value);return}if(t.type===`BigInt`){if(t.value<-(1n<<63n)||t.value>(1n<<63n)-1n)throw Error(`BigInt value must be a signed 64-bit integer`);e.u64(14),e.i64(t.value);return}if(t.type===`Timestamp`){if(!Number.isSafeInteger(t.value)||t.value<0)throw Error(`${t.type} value must be a non-negative safe integer`);e.u64(3),e.u64(t.value);return}if(t.type===`Double`){if(!Number.isFinite(t.value))throw Error(`Double value must be finite`);e.u64(4),e.f64Le(t.value);return}if(t.type===`Uuid`){e.u64(9);let n=Ze(t.value);if(!n)throw Error(`invalid uuid ${t.value}`);e.bytes(n);return}if(t.type===`Bytea`){e.u64(7),e.bytes(t.value);return}if(t.type===`Array`){e.u64(12),e.vec((e,n)=>Jh(e,t.value[n]),t.value.length);return}e.u64(6),e.string(t.value)}var Yh=64,Xh=class{chunks=[];parts=[];partsBytes=0;finish(){if(this.parts.length===0)return Uint8Array.from(this.chunks);this.flushChunks();let e=new Uint8Array(this.partsBytes),t=0;for(let n of this.parts)e.set(n,t),t+=n.byteLength;return e}flushChunks(){this.chunks.length!==0&&(this.pushPart(Uint8Array.from(this.chunks)),this.chunks=[])}pushPart(e){this.parts.push(e),this.partsBytes+=e.byteLength}u64(e){if(typeof e==`bigint`){if(e<0n||e>18446744073709551615n)throw Error(`u64 out of range: ${e}`);this.u64Big(e);return}if(!Number.isSafeInteger(e)||e<0)throw Error(`u64 must be a non-negative safe integer, got ${e}`);let t=e;do{let e=t&127;t=Math.floor(t/128),t!==0&&(e|=128),this.chunks.push(e)}while(t!==0)}i64(e){let t=Om(e,`i64`),n=t<0n?(-t<<1n)-1n:t<<1n;this.u64Big(n)}u64Big(e){let t=e;do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),this.chunks.push(e)}while(t!==0n)}u32Le(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`u32Le must be an unsigned 32-bit integer, got ${e}`);this.chunks.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}f64Le(e){let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e,!0),this.bytes(t,!1)}bool(e){this.chunks.push(e?1:0)}string(e){this.bytes($h(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<Yh){for(let t of e)this.chunks.push(t);return}this.flushChunks(),this.pushPart(new Uint8Array(e))}vec(e,t){this.u64(t);for(let n=0;n<t;n+=1)e(this,n)}map(e){this.u64(e)}set(e){this.u64(e)}none(){this.chunks.push(0)}some(e){this.chunks.push(1),e(this)}enumUnit(e){this.u64(e)}},Zh=class{bytesValue;offset=0;constructor(e){this.bytesValue=e}u64(){let e=this.readCanonicalU64();if(e>BigInt(2**53-1))throw Error(`postcard u64 exceeds Number.MAX_SAFE_INTEGER: ${e}`);return Number(e)}u64BigInt(){return this.readCanonicalU64()}i64(){let e=this.readCanonicalU64();return(e&1n)==0n?e>>1n:-(e+1n>>1n)}readCanonicalU64(){let e=0n;for(let t=0;t<10;t+=1){let n=this.readByte(),r=BigInt(n&127);if(t===9&&r>1n)throw Error(`postcard u64 overflow`);if(e|=r<<BigInt(t*7),!(n&128)){if(t!==0&&e<1n<<BigInt(t*7))throw Error(`postcard u64 is not minimally encoded`);return e}}throw Error(`postcard u64 overflow`)}string(){return Mh.decode(this.bytes())}bool(){let e=this.readByte();if(e===0)return!1;if(e===1)return!0;throw Error(`invalid bool tag ${e}`)}f64Le(){let e=this.bytesOfLength(8);return new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(0,!0)}bytes(e=!0){let t=e?this.u64():16;return this.bytesOfLength(t)}bytesAtMost(e,t){let n=this.u64();if(n>e)throw Error(`${t} exceeds maximum length of ${e} bytes`);return this.bytesOfLength(n)}bytesOfLength(e){let t=this.offset+e;if(t>this.bytesValue.length)throw Error(`postcard bytes overflow`);let n=this.bytesValue.subarray(this.offset,t);return this.offset=t,n}option(e){let t=this.readByte();if(t!==0){if(t!==1)throw Error(`invalid option tag ${t}`);return e(this)}}readVec(e){let t=this.u64();return Array.from({length:t},()=>e(this))}done(){return this.offset===this.bytesValue.length}readByte(){if(this.offset>=this.bytesValue.length)throw Error(`postcard eof`);return this.bytesValue[this.offset++]}};function Qh(e){return $h(JSON.stringify(e,b))}function $h(e){return new TextEncoder().encode(e)}var eg=new TextEncoder;function tg(e){return eg.encode(ge(e))}function ng(e){let t=new Xh;return t.string(e.table),Mm(t,[...e.descriptor]),Ie(t.finish())}var rg=3600*1e3,ig=500,ag=`jazz-http-stream-endpoints`,og=`endpoints`;function sg(){return globalThis.indexedDB!==void 0}function cg(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(ag,1);r.onupgradeneeded=()=>r.result.createObjectStore(og),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function lg(e,t){let n=cg();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(og,e).objectStore(og));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var ug=`jazz-stream-endpoint:`,dg=600*1e3;function fg(){if(!(typeof document>`u`))try{return globalThis.localStorage??void 0}catch{return}}function pg(e,t=Date.now()){let n=fg();if(n)try{let r=n.getItem(ug+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(ug+e);return}return i===`stream`}catch{return}}function mg(e,t,n){let r=fg();if(r)try{r.setItem(ug+e,`${t}:${n}`)}catch{try{r.removeItem(ug+e)}catch{}}}async function hg(e,t=Date.now()){let n,r=await Promise.race([lg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),ig)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?mg(e,`stream`,r.until):mg(e,`none`,t+dg),i}function gg(e,t=Date.now()){return mg(e,`stream`,t+rg),lg(`readwrite`,n=>n.put(t+rg,e)).then(()=>void 0,()=>void 0)}function _g(e){return mg(e,`none`,Date.now()+dg),lg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var vg=`x-jazz-stream-key`;function yg(e,t){let n=new Uint8Array(5+t.byteLength);return n[0]=e,new DataView(n.buffer).setUint32(1,t.byteLength,!1),n.set(t,5),n}function bg(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}var xg=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?bg([this.buffered,e]):e;let t=[],n=0;for(;this.buffered.byteLength-n>=5;){let e=new DataView(this.buffered.buffer,this.buffered.byteOffset+n).getUint32(1,!1);if(this.buffered.byteLength-n<5+e)break;t.push({kind:this.buffered[n],payload:this.buffered.slice(n+5,n+5+e)}),n+=5+e}return this.buffered=this.buffered.slice(n),t}get pending(){return this.buffered.byteLength}},Sg=new TextEncoder,Cg=new TextDecoder;function wg(e){let t=new URL(e);return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=t.pathname.replace(/\/ws\/?$/,`/stream`),t.toString()}var Tg=class{listeners=new Map;addEventListener(e,t){let n=this.listeners.get(e)??[];n.push(t),this.listeners.set(e,n)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}},Eg=4*1024*1024,Dg=(e,t)=>fetch(e,t),Og=class extends Tg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=Dg){super(),this.request=t,this.streamUrl=wg(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?Sg.encode(e):e;this.queued.push(yg(1,t)),this.flush()}close(){if(this.readyState>=2)return;let e=this.session;if(!e)return this.finish(1e3,`client closed`);this.finish(1e3,`client closed`,!1),this.request(`${this.streamUrl}/${encodeURIComponent(e.id)}`,{method:`DELETE`,credentials:`same-origin`,headers:{[vg]:e.key},signal:AbortSignal.timeout?.(jg)}).catch(()=>void 0).finally(()=>this.abort.abort())}async run(){try{let e=await this.request(this.streamUrl,{method:`POST`,credentials:`same-origin`,signal:this.abort.signal});if(!e.ok||!e.body)throw Error(`HTTP stream refused (${e.status})`);let t=e.body.getReader(),n=new xg;for(;;){let{done:e,value:r}=await t.read();if(e)break;for(let e of n.push(r)){if(this.readyState>=2)return;this.receive(e.kind,e.payload)}}this.fail(1006,`HTTP stream ended`)}catch(e){if(this.readyState>=2)return;this.emit(`error`,e),this.fail(1006,e instanceof Error?e.message:String(e))}}receive(e,t){if(e===0)this.session=JSON.parse(Cg.decode(t)),this.readyState=1,this.emit(`open`);else if(e===1){let e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.emit(`message`,{data:e})}else if(e===2){let{code:e,reason:n}=JSON.parse(Cg.decode(t));this.finish(e,n)}}async flush(){if(!(this.sending||!this.session)){this.sending=!0;try{for(;this.queued.length>0&&this.readyState===1;){let e=0,t=0;for(;e<this.queued.length&&(e===0||t+this.queued[e].byteLength<=Eg);)t+=this.queued[e].byteLength,e+=1;let n=bg(this.queued.splice(0,e)),r=await this.request(`${this.streamUrl}/${encodeURIComponent(this.session.id)}`,{method:`POST`,credentials:`same-origin`,headers:{"Content-Type":`application/octet-stream`,[vg]:this.session.key},body:n});if(!r.ok)throw Error(`HTTP stream send refused (${r.status})`)}}catch(e){this.emit(`error`,e),this.close()}finally{this.sending=!1}}}fail(e,t){this.finish(e,t)}finish(e,t,n=!0){this.readyState>=2||(this.readyState=3,n&&this.abort.abort(),this.emit(`close`,{code:e,reason:t}))}},kg=new Set,Ag=new Map,jg=1e4,Mg=new Map,Ng=`x-jazz-stream`,Pg=new Set,Fg=`x-jazz-store-error`,Ig=new Set;async function Lg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(jg)});if(n.status===503&&n.headers.get(Fg)===`1`){let t=await n.text().catch(()=>``);return t&&!Ig.has(`${e}\n${t}`)&&(Ig.add(`${e}\n${t}`),console.error(`jazz: the backend at ${e} can't serve: ${t}`)),`other`}return n.body?.cancel().catch(()=>void 0),n.status===403?`refused`:n.status===426?n.headers.get(Ng)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function Rg(e,t,n){let r=await Lg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return Ag.delete(e),Mg.delete(e),r===`refused`&&!Pg.has(e)&&(Pg.add(e),console.warn(`jazz: the backend at ${e} refuses this page's origin (403). If a proxy rewrites the Host header, set the backend's publicUrl or allowedOrigins.`)),r;let i=(Ag.get(e)??0)+1;Ag.set(e,i);let a=t?(Mg.get(e)??0)+1:0;t?Mg.set(e,a):Mg.delete(e);let o=a>=2;return i<3&&!o?r:(Ag.delete(e),Mg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${jg/1e3} s, although the backend answers and upgrades them: something in between (a proxy or dev server) doesn't pass WebSocket upgrades on. Syncing over the HTTP stream instead, for as long as this client runs.`),`stream-in-between`):(console.warn(`jazz: ${i} WebSockets in a row to ${e} failed, although the backend answers and upgrades them: something in between (a proxy or dev server) doesn't pass WebSocket upgrades on. Syncing over the HTTP stream instead, for as long as this client runs.`),`stream-in-between`))}function zg(e,t={}){let n=t.fetch??Dg,r=t.describeFailedUpgrade;return class extends Tg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,kg.has(e)){this.openStream();return}if(!sg()){this.inner=this.openNative();return}let t=pg(e);if(t===!0){kg.add(e),this.openStream();return}if(t===!1){this.inner=this.openNative();return}hg(e).then(t=>{this.closedEarly||(t?(kg.add(e),this.openStream()):this.inner=this.openNative())})}get readyState(){return this.inner?this.probing?0:this.inner.readyState:this.closedEarly?3:0}send(e){if(!this.inner)throw Error(`WebSocket is not open`);this.inner.send(e)}close(){if(this.closedByClient=!0,this.settled=!0,this.probing=!1,clearTimeout(this.openDeadline),this.abort.abort(),this.inner)return this.inner.close();this.closedEarly||(this.closedEarly=!0,queueMicrotask(()=>this.emit(`close`,{code:1e3,reason:``})))}openStream(){let e=new Og(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(kg.delete(this.url),_g(this.url))}),this.inner=e,this.forward(e)}openNative(){let t=new e(this.url);t.binaryType=`arraybuffer`;let i=!1,a,o=(e,t,i=!1)=>{if(clearTimeout(this.openDeadline),!this.settled){if(a){a[e]??=t;return}a={[e]:t},this.probing=!0,Rg(this.url,i,n).then(async e=>{let t=e===`stream`||e===`stream-in-between`,n=!(!i&&(e===`upgrades`||e===`other`))||this.settled?void 0:await r?.(this.url,this.abort.signal).catch(()=>void 0);if(this.probing=!1,!this.settled){if(this.settled=!0,t){kg.add(this.url),e===`stream`&&gg(this.url),this.openStream();return}if(n){this.emit(`error`,Error(n)),this.emit(`close`,{code:1006,reason:n});return}a?.error!==void 0&&this.emit(`error`,a.error),this.emit(`close`,a?.close??{code:1006,reason:``})}})}};return this.openDeadline=setTimeout(()=>{o(`close`,{code:1006,reason:`the WebSocket upgrade got no answer`},!0),t.close()},jg),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,Ag.delete(this.url),Mg.delete(this.url),this.settled=!0,this.emit(`open`))}),t.addEventListener(`message`,e=>{a||this.emit(`message`,e)}),t.addEventListener(`error`,e=>{i?this.emit(`error`,e):o(`error`,e)}),t.addEventListener(`close`,e=>{i?this.emit(`close`,e):o(`close`,e)}),t}forward(e){e.addEventListener(`open`,()=>this.emit(`open`)),e.addEventListener(`message`,e=>this.emit(`message`,e)),e.addEventListener(`error`,e=>this.emit(`error`,e)),e.addEventListener(`close`,e=>this.emit(`close`,e))}}}var Bg=`jazz_renewal`,Vg=`X-Jazz-Renew`,Hg=2048;function Ug(e){let t=new Zh(e);if(t.u64()!==64)throw Error(`not a renew-soon frame`);let n=t.string(),r=t.u64();if(!t.done()||!n||n.length>Hg)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function Wg(e){let t=new Xh;return t.u64(65),t.string(e),t.finish()}function Gg(e){return e[0]===64}function Kg(e){try{let t=new URL(e);return/\/ws\/?$/.test(t.pathname)?(t.protocol=t.protocol===`wss:`?`https:`:t.protocol===`ws:`?`http:`:t.protocol,t.pathname=t.pathname.replace(/\/ws\/?$/,`/accounts/backend-user`),t.search=``,t.hash=``,t.toString()):null}catch{return null}}function qg(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var Jg=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function Yg(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function Xg(e){return e.code===`auth_failed`&&e.retry===`after_resume`&&e.message.startsWith(`reauthenticate:`)}function Zg(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}var Qg=2048,$g=12e4,e_=1e3,t_=7,n_=4496,r_=1<<20,i_=5,a_=5,o_=2*1024*1024,s_=4096;function c_(e){u_(e);let t=new Xh;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>o_)throw Error(`websocket frame batch exceeds maximum length of ${o_} bytes`);return n}function l_(e){if(e.byteLength>o_)throw Error(`websocket frame batch exceeds maximum length of ${o_} bytes`);let t=new Zh(e),n=t.u64();if(n===0||n>s_)throw Error(`websocket frame batch exceeds frame-count limit of ${s_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(o_,`websocket frame`));return w_(t,`websocket frame batch`),r}function u_(e){if(e.length===0||e.length>s_)throw Error(`websocket frame batch exceeds frame-count limit of ${s_}`);for(let t of e)if(t.byteLength>o_)throw Error(`websocket frame exceeds maximum length of ${o_} bytes`)}function d_(e=n_){x_(e,`client wire features`);let t=new Xh;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var f_=0,p_=1;function m_(e){if(e[0]!==f_)return!1;let t=new Zh(e);t.u64();let{min:n,max:r}=S_(t);return n===6&&r===6&&C_(t),!0}function h_(e){if(e[0]!==p_)return!1;let t=new Zh(e);return t.u64(),__(t),!0}function g_(e){let t=new Zh(e),n=t.u64();if(n!==1)throw Error(`expected WireFrame::Error, got tag ${n}`);return __(t)}function __(e){let t={code:U_(e.u64()),retry:W_(e.u64()),message:e.string()};return w_(e,`WireFrame::Error`),t}function v_(e){return e.code===`auth_failed`?S(e.message):null}var y_=class{url;socket;onFrame;onError;onTerminal;localFeatures;opened;resolveNegotiation;rejectNegotiation;negotiated=!1;closing=!1;terminated=!1;lastInbound=performance.now();silenceTimer;handshakeTimer;renewalUrl;renewalTimer;constructor(e){this.url=e.endpointUrl;let t=e.WebSocket??Xe(this.url)??B_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??4496)|Qg,this.renewalUrl=D_(e.authJson)?Kg(this.url):null,x_(this.localFeatures,`client wire features`),this.socket=new t(this.url),this.socket.binaryType=`arraybuffer`,this.watchHandshake(e.handshakeTimeoutMs??1e4),this.opened=new Promise((e,t)=>{this.resolveNegotiation=e,this.rejectNegotiation=t}),G_(this.socket).then(()=>{this.closing||(this.socket.send(E_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(c_([d_(this.localFeatures)])))},e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:String(e)}),this.close()}),this.socket.addEventListener(`message`,e=>{this.lastInbound=performance.now(),this.handleMessage(e.data).catch(e=>{this.reportTerminal({code:`protocol_error`,retry:`never`,message:e instanceof Error?e.message:String(e)},void 0,!1),this.close()})}),this.socket.addEventListener(`error`,e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:`websocket transport error`})}),this.socket.addEventListener(`close`,e=>{let t=T_(e);this.reportTerminal({code:`websocket_closed`,retry:`later`,message:`websocket closed (code=${t.code??`unknown`}, reason=${t.reason??`none`})`})})}async send(e){await this.sendBatch([e])}async sendBatch(e){await this.ready();let t=[],n=a_;for(let r of e){let e=r.byteLength+i_;t.length>0&&(t.length>=s_||n+e>r_)&&(this.socket.send(c_(t)),t=[],n=a_),t.push(r),n+=e}t.length>0&&this.socket.send(c_(t))}ready(){return this.opened}get hasNegotiated(){return this.negotiated}close(){if(!this.closing){this.closing=!0,clearTimeout(this.silenceTimer),clearTimeout(this.handshakeTimer),clearTimeout(this.renewalTimer),this.reportTerminal({code:`websocket_closed`,retry:`never`,message:`websocket closed before server hello`},Error(`websocket closed before server hello`),!1,!1);try{this.socket.close()}catch{}}}reportTerminal(e,t=Error(e.message),n=!0,r=!0){this.terminated||(this.terminated=!0,clearTimeout(this.silenceTimer),clearTimeout(this.handshakeTimer),clearTimeout(this.renewalTimer),this.rejectNegotiation(t),n&&this.onError?.(e),r&&this.onTerminal?.(e))}watchHandshake(e){this.handshakeTimer=setTimeout(()=>{this.handshakeTimer=setTimeout(()=>{this.negotiated||this.terminated||(this.reportTerminal({code:`websocket_silent`,retry:`later`,message:`the server did not answer the connection within ${Math.round(e/1e3)} s`}),this.close())},e_)},e)}scheduleRenewal({session:e,renewInMs:t}){clearTimeout(this.renewalTimer);let n=this.renewalUrl;n&&(this.renewalTimer=setTimeout(()=>{this.renewalTimer=void 0,!(this.closing||this.terminated)&&k_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send(Wg(e))}).catch(()=>{})},Math.min(t,2**31-1)))}watchSilence(e=!1){if(clearTimeout(this.silenceTimer),this.closing||this.terminated)return;let t=performance.now()-this.lastInbound;if(t>=12e4&&!e){this.silenceTimer=setTimeout(()=>this.watchSilence(!0),e_);return}if(t>=12e4){this.reportTerminal({code:`websocket_silent`,retry:`later`,message:`the server sent nothing for ${Math.round(t/1e3)} s, not even a heartbeat`}),this.close();return}this.silenceTimer=setTimeout(()=>this.watchSilence(),$g-t)}async handleMessage(e){for(let t of l_(await z_(e))){if(this.closing)return;if(m_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=b_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&~Qg});continue}if(!(this.negotiated&&t.byteLength===1&&t[0]===t_)){if(this.negotiated&&this.renewalUrl&&Gg(t)){this.scheduleRenewal(Ug(t));continue}if(!this.negotiated){if(h_(t)){let e=g_(t);if(v_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new Jg(e)),this.close();return}this.reportTerminal({code:`protocol_error`,retry:`never`,message:`websocket received semantic frame before server hello`},void 0,!1),this.close();return}if(h_(t)){let e=g_(t);if(Yg(e)){this.reportTerminal(e),this.close();return}this.onError?.(e);continue}this.onFrame(t)}}}};function b_(e,t=n_){let n=new Zh(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=S_(n);if(r!==6||i!==6)throw Error(`server must advertise exactly wire protocol 6, got ${r}..=${i}`);let{features:a,role:o,authority:s}=C_(n),c=a&~BigInt(t);if(c!==0n)throw Error(`server accepted unsupported wire features 0x${c.toString(16)}`);if(o!==1)throw Error(`expected WirePeerRole::Core server hello`);return{protocolVersion:6,features:Number(a),authority:s}}function x_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function S_(e){return{min:e.u64(),max:e.u64()}}function C_(e){let t=e.u64BigInt(),n=e.u64(),r=e.option(e=>{let t=e.bytes();if(t.byteLength!==16)throw Error(`WireHello.authority.node must be exactly 16 bytes, got ${t.byteLength}`);return{node:t,epoch:e.u64BigInt()}});return w_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function w_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function T_(e){if(!e||typeof e!=`object`)return{};let t=e;return{code:typeof t.code==`number`?t.code:void 0,reason:typeof t.reason==`string`?t.reason:void 0}}function E_(e,t,n,r=!1){let i=JSON.parse(e),a=new T().decode(t),o=K_(i)??R_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Bg]:1}:{}})}function D_(e){if(!e)return!1;try{let t=JSON.parse(e);return t.backend_session!=null&&t.jwt_token==null&&t.admin_secret==null&&t.backend_secret==null}catch{return!1}}var O_=3e4;async function k_(e,t){return A_(qg(e),()=>j_(e,t))}async function A_(e,t){let n=globalThis.navigator?.locks;if(!n)return t();let r,i=()=>r??=t();try{await n.request(e,()=>{let e;return Promise.race([i().catch(()=>void 0),new Promise(t=>{e=setTimeout(t,O_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function j_(e,t){try{let n=await Ue(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[Vg]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function M_(e){let t=JSON.parse(e);if(t.admin_secret)return{};if(typeof t.backend_secret==`string`){let e=t.backend_session,n=e&&typeof e==`object`?e.claims:void 0;return n&&typeof n==`object`&&!Array.isArray(n)?n:{}}if(typeof t.jwt_token!=`string`)return{};let n=Me(t.jwt_token);if(!n)return{};if(n.iss===`urn:jazz:local-first`||n.iss===`urn:jazz:anonymous`){let{jazz_pub_key:e,...t}=n;return Se(t)}return Se(n)}function N_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!F_(n))return new TextEncoder().encode(ze(`urn:jazz:system`,`system`));let r=L_(n),i=null;try{i=D(new T({fatal:!0}).decode(t))}catch{}if(i?.account_id&&r){let e=D(r);if(e.issuer!==i.issuer||e.user_id!==i.user_id||e.account_id!==void 0&&e.account_id!==i.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return r?new TextEncoder().encode(r):t}function P_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!F_(t)&&delete t.jwt_token,JSON.stringify(t)}function F_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&P(t.issuer)&&P(t.user_id)}function I_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||L_(t)!==null}function L_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&F_(e)){let t=e.backend_session;return ze(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=Me(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,r=t?.sub;if(typeof n==`string`&&typeof r==`string`&&P(n)&&P(r))return ze(n,r)}return null}function R_(e){return D(e)?.user_id??null}async function z_(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw Error(`expected binary websocket message, got ${typeof e}`)}function B_(e){let t=H_();return V_(e)?zg(t):t}function V_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function H_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function U_(e){switch(e){case 0:return`unsupported_protocol_version`;case 1:return`unsupported_feature`;case 2:return`malformed_frame`;case 3:return`auth_failed`;case 4:return`backpressure`;case 5:return`internal`;case 6:return`not_ready`;default:throw Error(`unknown WireErrorCode discriminant ${e}`)}}function W_(e){switch(e){case 0:return`never`;case 1:return`after_auth`;case 2:return`after_resume`;case 3:return`later`;default:throw Error(`unknown WireRetry discriminant ${e}`)}}function G_(e){return e.readyState===1?Promise.resolve():new Promise((t,n)=>{let r=!1,i=e=>{r||(r=!0,e())};e.addEventListener(`open`,()=>i(t)),e.addEventListener(`error`,e=>i(()=>n(e))),e.addEventListener(`close`,()=>i(()=>n(Error(`websocket closed before open`))))})}function K_(e){let t=e.sub;if(typeof t==`string`&&P(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=q_(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&P(e))return e}return null}function q_(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(J_(t[1]));return typeof e.sub==`string`&&P(e.sub)?e.sub:null}catch{return null}}function J_(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=t.padEnd(Math.ceil(t.length/4)*4,`=`);return typeof atob==`function`?atob(n):Buffer.from(n,`base64`).toString(`binary`)}var Y_=20,X_=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,Z_=16,Q_={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},$_=250,ev=4;function tv(e){return typeof e?.poll==`function`}function nv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function rv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function iv(e,t){let n=e.message;return Xg(e)?{kind:`reauthenticate`,message:n}:v_(e)?{kind:`authRejected`,message:n}:Yg(e)||e.code===`internal`&&e.retry===`later`?t?{kind:`network`,message:n}:{kind:e.code===`not_ready`?`serverNotReady`:`refused`,message:n}:Zg(e)?{kind:`network`,message:n}:{kind:`fatal`,message:n}}function av(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function ov(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var sv=new T({fatal:!0}),cv=new WeakMap;function lv(e,t,n,r,i,a=!1){try{return uv(e,t,n,r,i,a)}catch(e){throw Fe(e)}}function uv(e,t,n,r,i,a){if(i&&a)throw Error(`A native runtime cannot be both self-signed and backend-scoped`);if(a){if(!e.openPersistentAsBackend)throw Error(`Native runtime does not support explicit backend opens; rebuild the matching Jazz native artifact`);return e.openPersistentAsBackend(t,n,r)}if(i){if(!e.openPersistentWithSelfSignedProof)throw Error(`Native runtime does not support self-signed client opens; rebuild the matching Jazz native artifact`);return e.openPersistentWithSelfSignedProof(t,n,r,i.token,i.appId,i.claimedAuthor)}if(!e.openPersistent)throw Error(`Native runtime does not expose persistent storage`);return e.openPersistent(t,n,r)}function dv(e,t,n,r,i=!1){if(r&&i)throw Error(`A native runtime cannot be both self-signed and backend-scoped`);if(i){if(!e.openMemoryAsBackend)throw Error(`Native runtime does not support explicit backend opens; rebuild the matching Jazz native artifact`);return e.openMemoryAsBackend(t,n)}if(!r)return e.openMemory(t,n);if(!e.openMemoryWithSelfSignedProof)throw Error(`Native runtime does not support self-signed client opens; rebuild the matching Jazz native artifact`);return e.openMemoryWithSelfSignedProof(t,n,r.token,r.appId,r.claimedAuthor)}function fv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var pv=class e{schema;node;auxiliaryReceiveDeadlines=new Map;pendingNativeAdmissionCancels=new Set;pendingNativeReadCancels=new Set;db;schemaBytes;configBytes;peerIdentity;upstreamPrincipal=null;selfSignedClientProof;scopeIsolatedRelay;schemaHash;trustedBackend;transactionOwner;pendingTxs;completedTxs;writes;pendingLocalSettlements=new Set;localSettlementListeners=new Set;pendingStreamingMutations=new Set;streamingFinalization=Promise.resolve();ownerRuntime;slowQueryApp;slowQueryConsoleDetail;get preparationOwner(){return this.ownerRuntime}readAuthorizationHost;subscriptions=new Map;subscriptionPool;pooledSubscriptions=new Map;drainingSubscriptionPool=!1;subscriptionPoolDirty=!1;authFailureCallback=null;mutationErrorCallback=null;serverTransportErrorCallback=null;deliveredMutationErrors=new Set;serverTransport=null;peerUpstreamAttached=!1;nonDurableClient=!1;serverCarrier=null;webSocket;serverCarrierPromise=null;serverConnectionAttempt=null;serverReplacementRetirement=null;serverTransportError=null;serverTransportErrorWaiters=[];localStorageFailure=null;localStorageFailureWaiters=new Set;serverTransportWorkEpoch=0;serverTransportWorkWaiters=[];serverEndpointUrl=null;serverAuthJson=null;link=null;linkStatus=null;linkInputs=[];linkStepping=!1;linkAttemptId=null;linkTimer=null;linkConnection=null;linkFailure=null;upstreamRefusal=null;linkCloseReason=`server transport replaced`;serverTransportErrorRetrying=!1;serverTransportErrorAwaitsAuth=!1;nativeAuthRefusalRenewable=!1;nativeLinkEverConnected=!1;nativeLinkPoll=null;firstLoadWaitSeen=!1;remoteLink=new xm(()=>this.readRemoteLinkState());linkStatusPublisher=new ms(()=>this.upstreamLinkStatus(),us);syncStatusPublisher=new ms(()=>this.readSyncStatus(),(e,t)=>ps(e.uploads,t.uploads)&&us(e.link,t.link));lastFailure=null;failingAs=null;pendingInboundServerFrames=[];serverInboundRouting=Promise.resolve();serverInboundProcessed=!1;peerTransportWorkListeners=new Set;auxiliaryTraceListeners=new Set;queryCoverageTraceListeners=new Set;peerTransportActivityEpoch=0;peerTransportProcessedActivityEpoch=0;coreTickScheduled=!1;coreDeadlineTimer;coreDeadlineAt;coreTickAgain=!1;coreOperation=null;pendingTransportRetirements=new Map;serverPumpScheduled=!1;serverPumpRunning=!1;serverPumpAgain=!1;serverConnectionGeneration=0;closed=!1;foregroundLeaseQuiesced=!1;foregroundLeaseCapture=null;foregroundLeaseDraining=!1;physicalCloseStarted=!1;nextSubscriptionId=1;static fromDb(t,n,r,i,a,o,s){return new e(null,n,r,i,a,o,{db:t,selfSignedClientProof:s?.selfSignedClientProof,scopeIsolatedRelay:s?.scopeIsolatedRelay,slowQueryLog:s?.slowQueryLog})}migrations;registerSchemaView(t,n){return new e(null,t,this.node,this.peerIdentity,1,!0,{db:this.db.registerSchema(tg(t),n?Qh(n):void 0),backendMode:this.trustedBackend,owner:this})}constructor(e,t,n,r,i,a,o){if(this.schema=t,this.node=n,this.ownerRuntime=o?.owner?.ownerRuntime??this,this.readAuthorizationHost=o?.owner?.readAuthorizationHost??o?.readAuthorizationHost??`client-local`,this.transactionOwner=o?.owner?.transactionOwner??{pendingTxs:new Map,completedTxs:new Map,writes:new Map},this.pendingTxs=this.transactionOwner.pendingTxs,this.completedTxs=this.transactionOwner.completedTxs,this.writes=this.transactionOwner.writes,this.schemaBytes=tg(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=Fh(n,r,void 0,a,o?.initialSyncFlushEvery,o?.selfSignedClientProof,o?.migrations,o?.systemNode),this.peerIdentity=r,this.migrations=o?.owner?.migrations??o?.migrations,this.schemaHash=ve(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=lv(e,o.persistentPath,this.schemaBytes,this.configBytes,o?.selfSignedClientProof,o?.backendMode)}else{if(!e)throw Error(`Native runtime constructor required for memory storage`);this.db=dv(e,this.schemaBytes,this.configBytes,o?.selfSignedClientProof,o?.backendMode)}if(o?.owner)return;this.slowQueryApp=o?.slowQueryLog?.appId,this.slowQueryConsoleDetail=o?.slowQueryLog?.consoleDetail;let s=o?.slowQueryLog?.thresholdMs;if(s!==void 0){if(!Number.isFinite(s)||s<0)throw Error(`slowQueryThresholdMs must be a non-negative number of milliseconds`);this.db.setSlowQueryThresholdMs?.(s)}if(typeof this.db.setTickScheduler!=`function`)throw Error(`Native runtime requires db.setTickScheduler`);this.db.setTickScheduler(((e,t)=>{let n=typeof e==`string`?e:t;(n===`immediate`||n===`deferred`||n===`after-current-turn`||typeof n==`string`&&n.startsWith(`after:`))&&this.scheduleCoreWake(n)})),this.db.onUpstreamFailure?.(e=>{if(!e)return this.nativeAuthRefusalRenewable=!1,this.clearRemoteServerTransportError();let t=e.code?gm({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:p(),features:this.nativeWireFeatures()}}async connectUpstreamPeer(e){return this===this.ownerRuntime?(this.peerUpstreamAttached=!0,e?this.connectNegotiatedUpstream({protocolVersion:6,features:e.features,authority:e}):await this.db.connectUpstream()):await this.ownerRuntime.connectUpstreamPeer(e)}onPeerTransportWork(e){return this===this.ownerRuntime?(this.peerTransportWorkListeners.add(e),()=>{this.peerTransportWorkListeners.delete(e)}):this.ownerRuntime.onPeerTransportWork(e)}onAuxiliaryTrace(e){return this===this.ownerRuntime?(this.auxiliaryTraceListeners.add(e),this.serverTransport?.setAuxiliaryTraceEnabled?.(!0),()=>{this.auxiliaryTraceListeners.delete(e),this.auxiliaryTraceListeners.size===0&&this.serverTransport?.setAuxiliaryTraceEnabled?.(!1)}):this.ownerRuntime.onAuxiliaryTrace(e)}onQueryCoverageTrace(e){return this===this.ownerRuntime?(this.queryCoverageTraceListeners.add(e),()=>this.queryCoverageTraceListeners.delete(e)):this.ownerRuntime.onQueryCoverageTrace(e)}emitQueryCoverageTrace(e){if(this!==this.ownerRuntime){this.ownerRuntime.emitQueryCoverageTrace(e);return}let t={stage:e,peerActivityEpoch:this.peerTransportActivityEpoch,peerProcessedActivityEpoch:this.peerTransportProcessedActivityEpoch};for(let e of this.queryCoverageTraceListeners)e(t)}notifyPeerTransportActivity(){if(this!==this.ownerRuntime)return this.ownerRuntime.notifyPeerTransportActivity();this.peerTransportActivityEpoch+=1,this.notifyPeerTransportWork(!0)}async progressPeerTransport(){if(this!==this.ownerRuntime)return this.ownerRuntime.progressPeerTransport();let e=this.peerTransportActivityEpoch;await this.runCoreTick(),!this.closed&&(this.peerTransportProcessedActivityEpoch=Math.max(this.peerTransportProcessedActivityEpoch,e))}retirePeerTransport(e){return this===this.ownerRuntime?(this.auxiliaryReceiveDeadlines.get(e)?.close(),this.auxiliaryReceiveDeadlines.delete(e),this.coreOperation?new Promise((t,n)=>{let r=this.pendingTransportRetirements.get(e)??[];r.push({resolve:t,reject:n}),this.pendingTransportRetirements.set(e,r)}):(e.close(),Promise.resolve())):this.ownerRuntime.retirePeerTransport(e)}setNonDurableClient(){if(this!==this.ownerRuntime)return this.ownerRuntime.setNonDurableClient();if(!this.db.setNonDurableClient)throw Error(`Native runtime does not expose non-durable client mode`);this.db.setNonDurableClient(),this.nonDurableClient=!0}foregroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.foregroundTxTimeHighWater();if(!this.db.foregroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water`);return this.db.foregroundTxTimeHighWater()}quiesceForegroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.quiesceForegroundTxTimeHighWater();if(this.foregroundLeaseCapture)return this.foregroundLeaseCapture;if(this.closed)throw Error(`Native runtime is already closed`);this.closed=!0,this.clearCoreDeadline(),this.foregroundLeaseQuiesced=!0,this.foregroundLeaseDraining=!0;let e=this.captureForegroundTxTimeHighWater().finally(()=>{this.foregroundLeaseDraining=!1,this.clearCoreDeadline()});return this.foregroundLeaseCapture=e,e}coreProgressAllowed(){return!this.closed||this.foregroundLeaseDraining}async captureForegroundTxTimeHighWater(){return await Promise.all(this.pendingStreamingMutations),await Promise.all(this.pendingLocalSettlements),await this.coreOperation?.completion.catch(()=>void 0),await this.foregroundTxTimeHighWater()}seedForegroundTxTimeHighWater(e){if(this!==this.ownerRuntime)return this.ownerRuntime.seedForegroundTxTimeHighWater(e);if(!this.db.seedForegroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water seeding`);this.db.seedForegroundTxTimeHighWater(e)}setLargeValueStagingPolicy(e,t,n){if(this!==this.ownerRuntime)return this.ownerRuntime.setLargeValueStagingPolicy(e,t,n);if(!this.db.setLargeValueStagingPolicy)throw Error(`Native runtime does not expose large-value staging policy`);this.db.setLargeValueStagingPolicy(e,t,n)}async evictExpiredStagedLargeValues(){if(this!==this.ownerRuntime)return await this.ownerRuntime.evictExpiredStagedLargeValues();if(!this.db.evictExpiredStagedLargeValues)throw Error(`Native runtime does not expose large-value staging maintenance`);return await this.db.evictExpiredStagedLargeValues()}async acceptPeer(e={},t,n=this.peerIdentity){if(this!==this.ownerRuntime)return this.ownerRuntime.acceptPeer(e,t,n);if(this.closed)throw Error(`Native runtime is closed`);return this.runWhenCoreIdle(async()=>{if(this.closed)throw Error(`Native runtime is closed`);let r;this.coreOperation={kind:`admission`,completion:new Promise(e=>{r=e})};try{let r=this.selfSignedClientProof,i;if(r){if(!Nb(n,this.peerIdentity))throw _y();if(!this.db.acceptSubscriberWithSelfSignedProof)throw Error(`Native runtime does not support self-signed subscriber admission; rebuild the matching Jazz WASM artifact`);i=await this.db.acceptSubscriberWithSelfSignedProof(e,r.token,r.appId,r.claimedAuthor,t)}else{if(!this.db.acceptSubscriber)throw Error(`Native runtime does not expose subscriber links`);i=await this.db.acceptSubscriber(n,e,t)}if(this.closed)throw i.close(),Error(`Native runtime closed during subscriber admission`);return i}finally{this.drainTransportRetirements(),this.coreOperation=null,r(),this.coreTickAgain&&!this.closed&&this.scheduleCoreTick()}})}async runWhenCoreIdle(e){let t=this.ownerRuntime;for(;t.coreOperation;)await t.coreOperation.completion;return e()}setRemoteLinkHint(e){if(this!==this.ownerRuntime)return this.ownerRuntime.setRemoteLinkHint(e);this.closed||this.db.setRemoteLinkHint?.(Q_[e])}remoteLinkState(){return this===this.ownerRuntime?this.readRemoteLinkState():this.ownerRuntime.remoteLinkState()}onRemoteLinkStateChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onRemoteLinkStateChange(e,t);return}this.remoteLink.subscribe(e,t),this.startNativeLinkPoll()}startNativeLinkPoll(){!this.db?.nativeConnectionStatus||this.nativeLinkPoll||this.closed||!this.linkHasListeners()||(this.nativeLinkPoll=setInterval(()=>{this.linkHasListeners()?this.linkChanged():this.stopNativeLinkPoll()},$_))}noteFirstLoadWait(e){if(!Mv(e))return;let t=this.ownerRuntime;t.firstLoadWaitSeen||(t.firstLoadWaitSeen=!0,t.startNativeLinkPoll())}stopNativeLinkPoll(){this.nativeLinkPoll&&clearInterval(this.nativeLinkPoll),this.nativeLinkPoll=null}linkHasListeners(){return this.syncStatusPublisher.hasListeners||this.linkStatusPublisher.hasListeners||this.firstLoadWaitSeen&&this.remoteLink.hasListeners}linkChanged(){this===this.ownerRuntime&&this.noteLinkFailure(),this.remoteLink.changed(),this.linkStatusPublisher.changed(),this.syncStatusPublisher.changed()}upstreamLinkStatus(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamLinkStatus();if(this.closed)return K(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?K(`disconnected`):e.authRejected?K(`auth`):e.connected?cs:this.serverTransportError?this.serverTransportErrorRetrying?K(`network`):hm(this.serverTransportError)?K(`authority-changed`,!1):K(`stopped`):ss:os:this.linkStatus?.phase===`stopped`&&hm(this.upstreamRefusal)?K(`authority-changed`,!1):ls(this.linkStatus)}canClearClientStorage(){return this===this.ownerRuntime?typeof this.db?.deleteNativeStore==`function`:this.ownerRuntime.canClearClientStorage()}async clearClientStorage(){if(this!==this.ownerRuntime)return this.ownerRuntime.clearClientStorage();if(!this.db?.deleteNativeStore)throw Error(`Runtime does not support client storage reset.`);let e=this.db.deleteNativeStore();return this.closed=!0,e}uploadStatus(){return this===this.ownerRuntime?this.closed?ns:this.db?.uploadStatus?.()??ns:this.ownerRuntime.uploadStatus()}lastLinkFailure(){return this===this.ownerRuntime?(this.noteLinkFailure(),this.lastFailure):this.ownerRuntime.lastLinkFailure()}noteLinkFailure(){let e=this.upstreamLinkStatus(),t=e.state===`offline`?e.reason:null;if(t===this.failingAs)return;this.failingAs=t;let n=is(e,(this.linkFailure??this.serverTransportError)?.message);n&&(this.lastFailure=n)}onUpstreamLinkStatusChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onUpstreamLinkStatusChange(e,t);return}this.linkStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()}onSyncStatusChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onSyncStatusChange(e,t);return}this.syncStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()}readSyncStatus(){return{link:this.upstreamLinkStatus(),uploads:this.uploadStatus()}}readRemoteLinkState(){if(this.closed)return`unavailable`;let e=this.db?.nativeConnectionStatus?.();if(e)return e.configured?e.explicitlyOffline||e.authRejected?`unavailable`:e.connected?(this.nativeLinkEverConnected=!0,`connected`):this.serverTransportError||this.nativeLinkEverConnected?`unavailable`:`connecting`:`none`;switch(this.linkStatus?.phase??`noServer`){case`noServer`:return`none`;case`live`:return`connected`;case`connecting`:return this.serverTransportError?`unavailable`:`connecting`;default:return`unavailable`}}async waitForUpstreamServerConnection(){if(this!==this.ownerRuntime)return await this.ownerRuntime.waitForUpstreamServerConnection();if(!this.serverCarrierPromise){if(this.serverTransportError)throw this.serverTransportError;return}if(this.linkStatus?.outagePublished&&this.serverTransportError)throw this.serverTransportError;let e=this.linkStatus?.consecutiveFailures?this.waitForServerTransportError(`global`):null;try{await(e?Promise.race([this.serverCarrierPromise,e.promise]):this.serverCarrierPromise)}finally{e?.cancel()}}isClosed(){return this.ownerRuntime.closed}async close(){if(this!==this.ownerRuntime){this.closeRuntimeState();return}if(!this.physicalCloseStarted&&!(this.closed&&!this.foregroundLeaseQuiesced)){this.physicalCloseStarted=!0,this.closed=!0,this.clearCoreDeadline();for(let e of this.pendingNativeAdmissionCancels)e();for(let e of this.pendingNativeReadCancels)e();await this.foregroundLeaseCapture?.catch(()=>void 0),this.pendingStreamingMutations.size>0&&await Promise.all(this.pendingStreamingMutations),this.pendingLocalSettlements.size>0&&await Promise.all(this.pendingLocalSettlements),await this.coreOperation?.completion.catch(()=>void 0),this.closeRuntimeState(!0),await this.db.close?.()}}discard(){this.closeRuntimeState()}closeRuntimeState(e=!1){if(this.closed&&!e)return!1;this.closed=!0,this.clearCoreDeadline();for(let e of this.pendingNativeAdmissionCancels)e();for(let e of this.pendingNativeReadCancels)e();for(let[e,t]of this.subscriptions)this.terminateSubscription(e,t);if(this!==this.ownerRuntime)return this.subscriptions.clear(),!1;for(let e of this.writes.values())e.close?.();this.subscriptions.clear(),this.pendingTxs.clear(),this.completedTxs.clear(),this.writes.clear(),this.serverConnectionGeneration+=1,this.clearLinkTimer(),this.linkAttemptId=null,this.settleLinkConnection(Error(`server transport disconnected`)),this.stopNativeLinkPoll(),this.linkChanged();let t=this.serverConnectionAttempt;this.serverConnectionAttempt=null,t&&this.finishServerConnectionAttempt(t,Error(`runtime closed`)),this.serverCarrierPromise=null,this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.peerTransportWorkListeners.clear(),this.localSettlementListeners.clear(),this.pendingInboundServerFrames.length=0;let n=this.serverTransport;return this.serverTransport=null,n&&this.retirePeerTransport(n).catch(Ib),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null,!0}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Q(n):y(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Q(r):void 0,a=xv(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=wv(n),l=vv(n);bv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=$y(this.table(e),t);if(u){this.assertTransactionWriteIdentity(u,s?void 0:o);let r=this.db.insertInTransaction(u.id,e,d,{rowId:i,branch:l?.head,updatedAtMs:c??void 0});if(!(r instanceof Uint8Array))throw Error(`Native runtime transaction insert did not return a row id`);let a=this.rowStateFromValues(e,r,t);return u.hasStagedMutations=!0,{id:a.id,values:a.values,kind:`staged`,openTransactionId:_v(n)}}let f=py(`Insert`,()=>nv(this.db.insert(e,d,{rowId:i,author:s?void 0:o,attribution:s,branch:l?.head,updatedAtMs:c??void 0})));return this.finishInsert(e,i??f.rowId,t,f)}async streamingMutation(e,t,n,r,i,a,o){let s=this.db.beginStreamingMutation,c=e===`insert`?`Insert`:e===`update`?`Update`:`Upsert`;this.assertMutationAdmission(c);let l=this.currentTx(a,c),u=xv(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=vv(a),m=wv(a);if(bv(f,p),l&&(this.assertTransactionAttribution(l,f),this.assertTransactionWriteIdentity(l,f?void 0:d)),!s)throw Error(`Native runtime does not expose streaming mutations`);let h=this.table(t),g=h.columns.find(e=>e.name===r)?.column_type.type;if(g!==`Text`&&g!==`Json`&&g!==`Bytea`)throw Error(`Streaming insert requires a Text, Json, or Bytea column: ${t}.${r}`);let _=o?Q(o):y(16),v=e===`insert`?eb(h,n,r,t):tb(h,n,r),b=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!b.finishInTransaction)throw await b.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let x=this.ownerRuntime,S,C=new Promise(e=>{S=e});x.pendingStreamingMutations.add(C);let w=new TextEncoder,T=async e=>{let t=64*1024;for(let n=0;n<e.byteLength;n+=t)await b.push(e.subarray(n,n+t))},E=``;try{for await(let e of fm(i))if(typeof e==`string`){if(g===`Bytea`)throw Error(`Bytea streams require Uint8Array chunks`);let t=E+e;E=``;let n=t.charCodeAt(t.length-1);n>=55296&&n<=56319&&(E=t.slice(-1),t=t.slice(0,-1)),t.length>0&&await T(w.encode(t))}else if(e instanceof Uint8Array)E&&=(await T(w.encode(E)),``),await T(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await T(w.encode(E));let e=x.streamingFinalization,t,n=new Promise(e=>{t=e});x.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await b.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await b.finish())}finally{t()}return{id:Ce(_),...r}}catch(e){throw await b.abort(),e}finally{S(),x.pendingStreamingMutations.delete(C)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Q(t),a=xv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=wv(r),l=vv(r);bv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=$y(this.table(e),n);if(u){this.assertTransactionWriteIdentity(u,s?void 0:o),this.db.restoreInTransaction(u.id,e,i,d,{branch:l?.head,updatedAtMs:c??void 0});let t=this.rowStateFromValues(e,i,n);return u.hasStagedMutations=!0,{id:t.id,values:t.values,kind:`staged`,openTransactionId:_v(r)}}let f=py(`Restore`,()=>nv(this.db.restore(e,i,d,{author:s?void 0:o,attribution:s,branch:l?.head,updatedAtMs:c??void 0})));return this.finishInsert(e,i,n,f)}update(e,t,n,r){this.assertMutationAdmission(`Update`);let i=Q(t),a=xv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=wv(r),l=vv(r);bv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=nb(this.table(e),n);if(u)return this.assertTransactionWriteIdentity(u,s?void 0:o),this.db.updateInTransaction(u.id,e,i,d,{head:l?.head,base:l?.base,updatedAtMs:c??void 0}),u.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(r)};let f=py(`Update`,()=>nv(this.db.update(e,i,d,{author:s?void 0:o,attribution:s,head:l?.head,base:l?.base,updatedAtMs:c??void 0})));return this.finishMutation(f)}updateLargeValues(e,t,n,r,i){this.assertMutationAdmission(`Update`);let a=Q(t),o=wv(i),s=vv(i),c=this.currentTx(i,`Update`);if(s)throw Error(`Partial-value updates (applyDiffs, editedFrom) are not yet supported in branch views.`);if(c){let t=xv(i);this.applySessionClaims(t);let s=this.trustedWriteIdentity(t),l=this.backendAttribution(i);this.assertTransactionAttribution(c,l),this.assertTransactionWriteIdentity(c,l?void 0:s);let u=this.db.updateLargeValuesInTransaction;if(!u)throw my(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=nb(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(i)}}if(yv(i,this.peerIdentity))throw Error(`Partial-value updates (applyDiffs, editedFrom) do not yet support a session or attributed identity outside a transaction.`);let l=this.db.updateLargeValues;if(!l)throw Error(`Native runtime does not support typed partial-value updates.`);let u=nb(this.table(e),n),d=py(`Update`,()=>l.call(this.db,e,a,u,r,o??void 0));return this.finishMutation(d)}upsert(e,t,n,r){this.assertMutationAdmission(`Upsert`);let i=Q(t),a=this.table(e),o=xv(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=wv(r),u=vv(r);bv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=nb(a,n)}catch(e){throw my(`Upsert`,hy(gy(e)))}if(d)return this.assertTransactionWriteIdentity(d,c?void 0:s),this.db.upsertInTransaction(d.id,e,i,f,{head:u?.head,base:u?.base,updatedAtMs:l??void 0}),d.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(r)};let p=py(`Upsert`,()=>nv(this.db.upsert(e,i,f,{author:c?void 0:s,attribution:c,head:u?.head,base:u?.base,updatedAtMs:l??void 0})));return this.finishMutation(p)}delete(e,t,n){this.assertMutationAdmission(`Delete`),this.table(e);let r=Q(t),i=xv(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=wv(n),c=vv(n);bv(o,c);let l=this.currentTx(n,`Delete`);if(l&&this.assertTransactionAttribution(l,o),l)return this.assertTransactionWriteIdentity(l,o?void 0:a),this.db.deleteInTransaction(l.id,e,r,{head:c?.head,base:c?.base,updatedAtMs:s??void 0}),l.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(n)};let u=py(`Delete`,()=>nv(this.db.delete(e,r,{author:o?void 0:a,attribution:o,head:c?.head,base:c?.base,updatedAtMs:s??void 0})));return this.finishMutation(u)}canInsertLocally(e,t,n){return`unknown`}canReadLocally(e,t,n){return`unknown`}canUpdateLocally(e,t,n,r){return`unknown`}canDeleteLocally(e,t,n){return`unknown`}isScopedPermissionAdvice(e){return this.readAuthorizationHost!==`trusted-serving`||!e?!1:!(this.trustedBackend&&e.issuer===`urn:jazz:system`&&e.user_id===`system`&&Ve(e,ct(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return Fv(JSON.stringify(e))}catch{return null}}explainReadClauses(e,t,n){if(!this.trustedBackend)throw Error(`explain runs only on a trusted backend`);let r=this.db.explainReadClauses;if(!r)throw Error(`explain is not supported yet by this runtime`);let i=Fv(JSON.stringify(n));if(!i?.identity)throw Error(`explain needs a user to explain for`);return r.call(this.db,e,t,i.identity,i.claims)}requestInsertPermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestInsertPermissionAdvice;if(!i)return Promise.resolve(`unknown`);let a=$y(this.table(e),t,e);return this.withPermissionAdviceTimeout(()=>i.call(this.db,e,a,r?.identity,r?.claims))}requestReadPermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestReadPermissionAdvice;return i?this.withPermissionAdviceTimeout(()=>i.call(this.db,e,Q(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}requestUpdatePermissionAdvice(e,t,n,r){if(this.isScopedPermissionAdvice(r)&&!this.trustedBackend)return Promise.resolve(`unknown`);let i=this.delegatedPermissionAdviceSession(r);if(this.isScopedPermissionAdvice(r)&&!i)return Promise.resolve(`unknown`);let a=this.db.requestUpdatePermissionAdvice;if(!a)return Promise.resolve(`unknown`);let o=nb(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Q(t),o,i?.identity,i?.claims))}requestDeletePermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestDeletePermissionAdvice;return i?this.withPermissionAdviceTimeout(()=>i.call(this.db,e,Q(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}captureSnapshot(){if(this!==this.ownerRuntime)return this.ownerRuntime.captureSnapshot();if(this.closed)return Promise.reject(Error(`Cannot capture a snapshot: native runtime is closed`));if(!this.db.captureSnapshot)return Promise.reject(new ye);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(sv.decode(e)))}beginTransaction(e,t,n){if(this!==this.ownerRuntime)return this.ownerRuntime.beginTransaction(e,t,n);if(this.closed)throw Error(`Begin transaction failed: native runtime is closed`);if(this.pendingTxs.has(t)||this.completedTxs.has(t))throw Error(`Begin transaction failed: transaction ${t} has already been opened`);let r=xv(n);this.applySessionClaims(r);let i=this.trustedWriteIdentity(r),a=this.backendAttribution(n),o=a?void 0:i;return this.db.beginTransaction(t,e,o,a),this.pendingTxs.set(t,{id:t,kind:e,identity:o,requestSession:o?r??void 0:void 0,attribution:a,hasStagedMutations:!1}),t}hasStagedTransactionWrites(e){return this===this.ownerRuntime?this.pendingTxs.get(e)?.hasStagedMutations:this.ownerRuntime.hasStagedTransactionWrites(e)}commitTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.commitTransaction(e);if(this.closed)throw Error(`Commit transaction failed: native runtime is closed`);let t=this.pendingTxs.get(e);if(!t)throw Error(Ev(e,this.completedTxs));if(!t.hasStagedMutations&&t.kind===`mergeable`)throw Error(`Commit transaction failed: empty mergeable transaction has no committed unit; roll it back instead`);let n=this.db.commitTransaction(e,t.kind);this.pendingTxs.delete(e),this.completedTxs.set(e,{kind:t.kind,state:`committed`}),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork();let r=gv(n,this.writes);return this.nonDurableClient&&this.trackLocalSettlement(r),r}async waitForTransaction(e,t,n={}){if(this!==this.ownerRuntime)return this.ownerRuntime.waitForTransaction(e,t,n);typeof e!=`string`&&(e=await e);let r=this.writes.get(e);if(!r)throw Error(`Wait for transaction failed: unknown transaction ${e}`);let{signal:i}=n,a=n.observeOnly?r.wait(t,!0):r.wait(t);if(a.catch(()=>void 0),n.ready)if(i){let e,t=new Promise(t=>{e=()=>t(),i.addEventListener(`abort`,e,{once:!0})});try{await Promise.race([n.ready,t])}finally{i.removeEventListener(`abort`,e)}}else await n.ready;let o=a.then(()=>`settled`);for(o.catch(()=>void 0);;){if(this.closed)throw Error(`Wait for transaction failed: native runtime is closed`);i?.throwIfAborted(),this.throwServerTransportErrorForTier(t,!0);let n=this.serverTransportWorkEpoch;this.startServerPump(),this.throwServerTransportErrorForTier(t,!0);let r=this.waitForServerTransportError(t,!0),a=this.waitForServerTransportWork(t,n),s=this.waitForLocalStorageFailure(t),c;try{let e=[o];if(r&&e.push(r.promise),s&&e.push(s.promise),a&&e.push(a.promise.then(()=>`work`)),i&&e.push(new Promise(e=>{let t=()=>e(`work`);i.addEventListener(`abort`,t,{once:!0}),c=()=>i.removeEventListener(`abort`,t)})),await Promise.race(e)===`settled`){this.pumpSubscriptions();return}}catch(t){throw uy(e,t)||t}finally{c?.(),r?.cancel(),a?.cancel(),s?.cancel()}}}rollbackTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.rollbackTransaction(e);let t=this.pendingTxs.get(e);if(!t)throw Error(Dv(e,this.completedTxs));try{this.db.rollbackTransaction(e)}finally{this.pendingTxs.delete(e)}return this.completedTxs.set(e,{kind:t.kind,state:`rolled_back`}),Promise.resolve(!0)}async query(e,t,n,r){if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);Nv(n,r),this.noteFirstLoadWait(r),Ov(r,this.pendingTxs,this.completedTxs);let i=Fv(t);Uv(e);let a=sy(e),o=kv(r,this.pendingTxs),s=jv(n,Bv(a),r),c=this.nativeReadContext(i,o),l=Hv(a,this.schema);if(await this.ensureClientSessionClaims(i),await this.waitForStrictRemoteQueryTransport(n),await this.processPendingPeerActivityBeforeRead(),this.closed||this.ownerRuntime.closed)return[];if(o||this.attachLocalReadCoverageInBackground(n,l,i),this.emitQueryCoverageTrace(`attach`),Vv(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),ub(sb(e),this.schema,ty(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),ub(sb(e),this.schema,ty(a,this.schema).rootColumns)}let u=ty(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),cb(ob(d),this.schema,u)}createSubscription(e,t,n,r){Nv(n,r),this.noteFirstLoadWait(r);let i=Fv(t),a=this.nativeReadContext(i);Uv(e);let o=this.nextSubscriptionId++,s=jv(n,Bv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:ty(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=Hv(e,this.schema),u=e=>{let t=Eb(e);if(c.cancelled||this.closed||this.ownerRuntime.closed){zv(t);return}c.source=t,c.callback&&this.startSubscriptionReader(o,c)},d=e=>{c.cancelled||this.failSubscription(c,e instanceof Error?e:Error(String(e)))},f=()=>{if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);if(c.cancelled)throw Error(`native operation was cancelled`);let e=this.subscribeForContext(l,s,a);return ov(e)?this.awaitNativeOperation(e,c.openingAbort.signal):e};try{let e=this.ensureClientSessionClaims(i),t=e instanceof Promise?e.then(f):f();t instanceof Promise?t.then(u).catch(d):u(t)}catch(e){d(e)}return o}executeSubscription(e,t){let n=this.subscriptions.get(e);if(n){if(n.callback)throw Error(`Subscription has already been activated`);if(n.callback=t,n.terminalError){this.deliverSubscriptionFailure(n);return}this.startSubscriptionReader(e,n)}}unsubscribe(e){let t=this.subscriptions.get(e);t&&this.terminateSubscription(e,t)}connect(e,t){if(this!==this.ownerRuntime)return this.ownerRuntime.connect(e,t);if(this.db?.reconnectNativeUpstream){this.db.reconnectNativeUpstream(),this.nativeLinkEverConnected=!1,this.linkChanged();return}let n=P_(t);this.assertCredentialKeepsPrincipal(n),this.nativeWireFeatures(),this.link??=this.createUpstreamLink(),this.serverEndpointUrl=e,this.serverAuthJson=n,this.linkCloseReason=`server transport replaced`,this.stepLink(this.linkStatus&&this.linkStatus.phase!==`noServer`?{type:`setOffline`,offline:!1}:{type:`serverConfigured`,configured:!0})}createUpstreamLink(){if(!this.db.createUpstreamLink)throw Error(`native runtime binding does not expose the upstream link machine; install the matching Jazz native runtime package`);return this.db.createUpstreamLink(Math.floor(Math.random()*(2**53-1)))}stepLink(e){if(this.linkInputs.push(e),!this.linkStepping){this.linkStepping=!0;try{for(let e=this.linkInputs.shift();e;e=this.linkInputs.shift()){if(this.closed||!this.link)continue;let t=JSON.parse(this.link.handle(Date.now(),JSON.stringify(e))),n=this.linkStatus;this.linkStatus=t.status;for(let e of t.actions)this.runLinkAction(e);this.applyLinkStatus(n,t.status);for(let e of t.events)e.type===`authFailed`&&this.authFailureCallback?.(e.reason);this.linkChanged()}}catch(e){throw this.linkInputs.length=0,e}finally{this.linkStepping=!1}}}runLinkAction(e){switch(e.type){case`connect`:this.runLinkAttempt(e.attempt);return;case`close`:{this.linkAttemptId===e.attempt&&(this.linkAttemptId=null);let t=this.serverConnectionAttempt;t?.id===e.attempt&&this.finishServerConnectionAttempt(t,Error(this.linkCloseReason),!1),this.pendingInboundServerFrames.length=0,this.serverPumpScheduled=!1,this.serverPumpAgain=!1;return}case`armTimer`:{this.clearLinkTimer();let t=e.token;this.linkTimer={token:t,handle:setTimeout(()=>{this.linkTimer?.token===t&&(this.linkTimer=null,this.stepLink({type:`timerFired`,token:t}))},e.afterMs)};return}case`cancelTimer`:this.linkTimer?.token===e.token&&this.clearLinkTimer();return}}applyLinkStatus(e,t){let n=this.linkFailure??Error(t.reason??`server transport failed`);switch(t.phase){case`live`:e?.outagePublished&&this.forgetServerTransportError();return;case`connecting`:case`backoff`:this.linkConnection||this.awaitLinkConnection(),t.outagePublished&&!e?.outagePublished&&this.handleServerTransportError(Error(n.message),void 0,!0);return;case`awaitingCredential`:case`stopped`:if(e?.phase!==t.phase){let e=t.phase===`awaitingCredential`&&!t.terminal;this.handleServerTransportError(n,void 0,e),this.serverTransportErrorAwaitsAuth=e,this.settleLinkConnection(n)}return;case`offline`:case`noServer`:this.settleLinkConnection(Error(`server transport disconnected`));return}}awaitLinkConnection(){let e=new Promise((e,t)=>{this.linkConnection={resolve:e,reject:t}});e.catch(()=>void 0),this.serverCarrierPromise=e}settleLinkConnection(e){let t=this.linkConnection;this.linkConnection=null,e instanceof Error?(this.serverCarrierPromise=null,t?.reject(e)):(this.serverCarrierPromise=Promise.resolve(e),t?.resolve(e))}clearLinkTimer(){this.linkTimer&&clearTimeout(this.linkTimer.handle),this.linkTimer=null}endLinkAttempt(e,t,n){if(e.finished)return;let r=e.id===this.linkAttemptId;if(this.finishServerConnectionAttempt(e,t,!1),!(!r||this.closed)){this.linkAttemptId=null,this.pendingInboundServerFrames.length=0,this.linkFailure=t;try{this.stepLink({type:`ended`,attempt:e.id,failure:n})}finally{this.linkFailure=null}}}runLinkAttempt(e){this.linkAttemptId=e,this.linkConnection||this.awaitLinkConnection();let t=this.serverEndpointUrl,n=this.serverAuthJson;(async()=>{for(let e=this.serverReplacementRetirement;e;e=this.serverReplacementRetirement)await e,this.serverReplacementRetirement===e&&(this.serverReplacementRetirement=null);this.closed||this.linkAttemptId!==e||t===null||n===null||this.startServerConnection(e,t,n)})().catch(t=>{if(this.closed||this.linkAttemptId!==e)return;this.linkAttemptId=null;let n=t instanceof Error?t:Error(gy(t));this.linkFailure=n;try{this.stepLink({type:`ended`,attempt:e,failure:{kind:`fatal`,message:n.message}})}finally{this.linkFailure=null}})}startServerConnection(e,t,n){this.serverConnectionGeneration+=1;let r=this.serverConnectionGeneration,i=this.nativeWireFeatures(),a=N_(n,this.peerIdentity);this.linkStatus?.outagePublished||this.forgetServerTransportError(),this.upstreamRefusal=null,this.linkChanged();let o,s=new Promise(e=>{o=e}),c=null,l=e=>{if(!c)return;let t=this.serverTransportError&&!this.linkStatus?.outagePublished?{kind:`fatal`,message:e.message}:iv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new y_({WebSocket:this.webSocket,endpointUrl:t,peerIdentity:a,features:i,authJson:n,requestedLink:this.scopeIsolatedRelay?`scope_isolated_client_relay`:void 0,onFrame:e=>{r===this.serverConnectionGeneration&&(this.pendingInboundServerFrames.push(e),this.notifyServerTransportWork(),this.scheduleServerPump(),this.serverPumpRunning&&queueMicrotask(()=>{!this.serverPumpRunning||this.pendingInboundServerFrames.length===0||this.routePendingInboundServerFrames().catch(e=>this.handleServerTransportError(e,r))}))},onError:e=>{Yg(e)||e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`||l(e)},onTerminal:l});c={id:e,generation:r,carrier:u,terminal:s,resolveTerminal:o,finished:!1,outcome:null,transport:null,retirement:null,admission:null},this.serverConnectionAttempt=c,this.serverCarrier=u;let d=()=>!this.closed&&r===this.serverConnectionGeneration&&u===this.serverCarrier&&c===this.serverConnectionAttempt;Promise.race([u.ready(),s.then(e=>{throw e})]).then(async t=>{if(!d()){u.close();return}if(!this.trustedBackend&&(await this.runWhenCoreIdle(()=>{if(d())return this.installClientSessionClaims(M_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw vy(`connecting the negotiated upstream transport`,e)});c.admission=i;let a=await Promise.race([i.then(e=>({type:`admitted`,transport:e})),s.then(e=>({type:`terminal`,error:e}))]);if(a.type===`terminal`)return;c.admission=null;let o=a.transport;if(!d()){u.close(),c.finished?await c.retirement:await this.retirePeerTransport(o);return}c.transport=o,this.serverTransport=o,o.setAuxiliaryTraceEnabled?.(this.auxiliaryTraceListeners.size>0),this.watchAuxiliaryOutbound(o,u,r).catch(e=>this.handleServerTransportError(e,r));let l=this.pumpServerTransport();l.catch(e=>this.handleServerTransportError(e,r)),this.pumpSubscriptions(),this.pinUpstreamPrincipal(n),this.stepLink({type:`admitted`,attempt:e}),await Promise.race([l.catch(()=>void 0),new Promise(e=>setTimeout(e,0))]),d()&&this.settleLinkConnection(u)}).catch(e=>{let t=e instanceof Error?e:Error(gy(e));this.endLinkAttempt(c,t,{kind:`fatal`,message:t.message})})}async connectNegotiatedUpstream(e){let t=e.authority,n=this.db.connectUpstreamWithSession;if(!t||!n)return await this.db.connectUpstream();let r=p();return await n.call(this.db,e.protocolVersion,e.features,t.node,t.epoch,this.node,r)}nativeWireFeatures(){if(!this.db.wireFeatures)throw Error(`native runtime binding does not expose its wire feature mask; install the matching Jazz native runtime package`);let e=this.db.wireFeatures();if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`native binding returned invalid wire feature mask ${e}`);return e}nativeUpstreamConfigured(){return this===this.ownerRuntime?this.db.nativeConnectionStatus?.().configured===!0:this.ownerRuntime.nativeUpstreamConfigured()}async disconnect(e={}){if(this!==this.ownerRuntime)return this.ownerRuntime.disconnect(e);if(this.db?.disconnectNativeUpstream){this.db.disconnectNativeUpstream(),this.linkChanged();return}let t=this.serverTransport,n=this.serverConnectionAttempt,r=n?.transport;this.linkCloseReason=`server transport disconnected`,this.stepLink({type:`setOffline`,offline:!0}),this.linkCloseReason=`server transport replaced`,this.serverEndpointUrl=null,this.serverAuthJson=null,this.serverReplacementRetirement||this.forgetServerTransportError(),e.rejectWaiters??!0?this.resolveServerTransportErrorWaiters(Error(`server transport disconnected`)):this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.serverTransport=null;let i=[];n?.retirement&&i.push(n.retirement),t&&t!==r&&i.push(Promise.resolve().then(()=>this.retirePeerTransport(t))),this.linkChanged(),await Promise.all(i)}updateAuth(e){if(this!==this.ownerRuntime)return this.ownerRuntime.updateAuth(e);if(this.nativeAuthRefusalRenewable=!1,this.db?.rejectAuthUpdate)return this.db.rejectAuthUpdate();let t=P_(e);this.assertCredentialKeepsPrincipal(t),this.serverEndpointUrl&&(this.serverAuthJson=t,this.stepLink({type:`credentialUpdated`}))}assertCredentialKeepsPrincipal(e){if(this!==this.ownerRuntime)return this.ownerRuntime.assertCredentialKeepsPrincipal(e);if(!this.upstreamPrincipal)return;let t=P_(e);if(!I_(t))return;let n;try{n=N_(t,this.peerIdentity)}catch{n=null}if(!n||!Nb(n,this.upstreamPrincipal))throw _y(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){this.upstreamPrincipal||!I_(e)||(this.upstreamPrincipal=N_(e,this.peerIdentity))}onAuthFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onAuthFailure(e);this.authFailureCallback=e,this.db.onAuthRejected?.(e=>{this.nativeAuthRefusalRenewable=m(S(e)),this.authFailureCallback?.(e)})}onMutationError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onMutationError(e);this.mutationErrorCallback=e,this.db.onMutationError(e=>this.deliverMutationError(e))}onStorageFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onStorageFailure(e);this.db.onStorageFailure?.(e)}onServerTransportError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onServerTransportError(e);this.serverTransportErrorCallback=e}endCredentialWait(){if(this!==this.ownerRuntime)return this.ownerRuntime.endCredentialWait();this.nativeAuthRefusalRenewable=!1;let e=this.serverTransportError;!e||!this.serverTransportErrorRetrying||(this.serverTransportErrorAwaitsAuth=!1,this.handleServerTransportError(e,this.serverConnectionGeneration,!1))}reportRemoteServerTransportError(e,t=!1){if(this!==this.ownerRuntime)return this.ownerRuntime.reportRemoteServerTransportError(e,t);this.handleServerTransportError(e,this.serverConnectionGeneration,t)}clearRemoteServerTransportError(){if(this!==this.ownerRuntime)return this.ownerRuntime.clearRemoteServerTransportError();this.serverTransportError&&(this.forgetServerTransportError(),this.linkChanged())}reportLocalStorageFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.reportLocalStorageFailure(e);if(e===null){this.localStorageFailure=null;return}let t=Object.assign(Error(e),{code:`storage`});this.localStorageFailure=t;for(let e of this.localStorageFailureWaiters)e(t);this.localStorageFailureWaiters.clear()}waitForLocalStorageFailure(e){if(e!==`local`||!this.nonDurableClient)return null;if(this.localStorageFailure)return{promise:Promise.reject(this.localStorageFailure),cancel:()=>{}};let t,n=new Promise((e,n)=>{t=n});return this.localStorageFailureWaiters.add(t),{promise:n,cancel:()=>this.localStorageFailureWaiters.delete(t)}}reportRemoteMutationError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.reportRemoteMutationError(e);this.deliverMutationError(e)}async waitForPendingWrites(e=`global`,t={}){if(this!==this.ownerRuntime)return this.ownerRuntime.waitForPendingWrites(e,t);if(!this.db.waitForPendingWrites)throw Error(`Native runtime lacks graceful sync shutdown; rebuild its bindings`);let{throughOutage:n=!1,signal:r}=t;r?.throwIfAborted(),await this.flushLocalSettlements(),this.throwServerTransportErrorForTier(e,n),this.startServerPump();let i=this.waitForServerTransportError(e,n),a=new AbortController,o=new Promise((e,t)=>{a.signal.addEventListener(`abort`,()=>t(a.signal.reason),{once:!0})});o.catch(()=>void 0);let s=new Promise(e=>{a.signal.addEventListener(`abort`,()=>e(),{once:!0})}),c=()=>a.abort(r?.reason);r?.addEventListener(`abort`,c,{once:!0});try{let{sync:n}=t,r=n?this.db.waitForSync?this.db.waitForSync(e,this.trustedWriteIdentity(xv(n.writeContext))??null):this.db.waitForPendingWrites(e,s,!0):this.db.waitForPendingWrites(e,s),c=this.awaitNativeRead(Promise.resolve(r).then(e=>e??new Uint8Array),void 0,a.signal);c.catch(()=>void 0);let l=[c,o];i&&l.push(i.promise),await Promise.race(l)}finally{i?.cancel(),r?.removeEventListener(`abort`,c),a.abort(Error(`waitForPendingWrites ended`))}}async flushLocalSettlements(){if(this!==this.ownerRuntime)return this.ownerRuntime.flushLocalSettlements();this.pendingLocalSettlements.size>0&&await Promise.all(this.pendingLocalSettlements)}onLocalSettlementChange(e){return this===this.ownerRuntime?(this.localSettlementListeners.add(e),e(this.pendingLocalSettlements.size>0),()=>this.localSettlementListeners.delete(e)):this.ownerRuntime.onLocalSettlementChange(e)}deliverMutationError(e){let t=e.transaction.transactionId;this.deliveredMutationErrors.has(t)||(this.deliveredMutationErrors.add(t),this.mutationErrorCallback?.(e))}trackLocalSettlement(e){if(this!==this.ownerRuntime)return this.ownerRuntime.trackLocalSettlement(e);let t;t=this.waitForTransaction(e,`local`,{observeOnly:!0}).catch(()=>void 0).finally(()=>{if(this.pendingLocalSettlements.delete(t),this.pendingLocalSettlements.size===0)for(let e of this.localSettlementListeners)e(!1)});let n=this.pendingLocalSettlements.size===0;if(this.pendingLocalSettlements.add(t),n)for(let e of this.localSettlementListeners)e(!0)}finishInsert(e,t,n,r){let i=gv(r,this.writes);this.nonDurableClient&&this.trackLocalSettlement(i),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork();let a=this.rowStateFromValues(e,t,n);return{id:a.id,values:a.values,kind:`committed`,txId:i}}finishMutation(e){let t=gv(e,this.writes);return this.nonDurableClient&&this.trackLocalSettlement(t),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),{kind:`committed`,txId:t}}assertMutationAdmission(e){if(this.ownerRuntime.closed)throw Error(`${e} failed: native runtime is closed`)}rowStateFromValues(e,t,n){return Wc(e,Ce(t),this.table(e).columns,n)}async readPlainRows(e,t,n,r){let i=this.nativeReadContext(n,r);return this.readRowsForContextAsync(e,t,i,r?.id)}readRowsForContext(e,t,n){let r=this.db.all(e,{...t,sync:!0},void 0,this.nativeReadAuthor(n),this.nativeReadClaims(n));if(typeof r.then==`function`)throw Error(`native read is asynchronous; use the asynchronous read boundary`);if(tv(r))throw Error(`native read is pending; use the asynchronous read boundary`);return r}async readRowsForContextAsync(e,t,n,r){return this.awaitNativeRead(this.startRowsForContext(e,t,n,r),t.tier)}startRowsForContext(e,t,n,r){let i=this.nativeReadAuthor(n);return this.db.all(e,t,r,i,this.nativeReadClaims(n))}nativeReadAuthor(e){return e.kind===`session-authority`?e.identity:void 0}nativeReadClaims(e){return e.kind===`session-authority`?e.claims:void 0}nativeReadContext(e,t){return this.trustedBackend&&(e?.backendAuthority||!e&&!t?.identity)?{kind:`backend-authority`}:this.readAuthorizationHost===`trusted-serving`?{kind:`session-authority`,identity:t?.identity??e?.identity??this.peerIdentity,claims:t?.requestSession?.claims??e?.claims}:{kind:`client-local`}}subscribeForContext(e,t,n){if(!this.db.subscribe)throw Error(`Native runtime does not support subscriptions`);let r=n.kind===`session-authority`?n.identity:void 0;return this.db.subscribe(e,t,r,this.nativeReadClaims(n))}async awaitNativeRead(e,t,n){let r=await e;if(!tv(r))return r;let i=()=>r.cancel();this.ownerRuntime.pendingNativeReadCancels.add(i);try{for(;;){if(this.closed||this.ownerRuntime.closed)throw Error(`native read was cancelled by runtime shutdown`);n?.throwIfAborted(),t&&this.throwServerTransportErrorForTier(t);let e=r.poll();if(e!==null)return e;this.startServerPump(),t&&this.throwServerTransportErrorForTier(t),await ly(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Nb(e.identity,this.peerIdentity)?void 0:e.identity:t&&!this.trustedBackend?this.peerIdentity:void 0}backendAttribution(e){if(!this.trustedBackend||!e)return;let t;try{t=JSON.parse(e).attribution}catch{return}if(t===void 0)return;if(typeof t!=`string`||!D(t))throw Error(`backend attribution must be a canonical author subject string`);let n=xv(e);if(!n)throw Error(`backend attribution requires a valid author`);return n.identity}awaitNativeOperation(e,t){let n=0,r,i=!1,a,o=()=>{n+=1,r?.()},s=()=>{i=!0,e.cancel(),o()};this.pendingNativeAdmissionCancels.add(s),t?.addEventListener(`abort`,s,{once:!0});let c=()=>{this.pendingNativeAdmissionCancels.delete(s),t?.removeEventListener(`abort`,s),e.cancel()},l=()=>{for(;;){if(this.closed||i||t?.aborted)throw Error(`native operation was cancelled`);if(a)throw a;let s=n,c=e.poll();if(c!=null)return c;if(this.pumpServerTransport().catch(e=>{a=e,o()}),n===s)return new Promise(e=>{r=e,n!==s&&e()}).then(()=>(r=void 0,l()))}};try{e.setWake(o);let t=l();return t instanceof Promise?t.finally(c):(c(),t)}catch(e){throw c(),e}}clientSessionClaimsKey;installClientSessionClaims(e){let t=Lv(e);if(t===this.clientSessionClaimsKey)return;let n=this.db.setSessionClaims?.(e);if(n instanceof Promise)return n.then(()=>{this.clientSessionClaimsKey=t});this.clientSessionClaimsKey=t}ensureClientSessionClaims(e){if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);if(!e||e.backendAuthority||this.readAuthorizationHost===`trusted-serving`||Lv(e.claims)===this.clientSessionClaimsKey)return;let t=()=>{if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);return this.installClientSessionClaims(e.claims)};return this.ownerRuntime.coreOperation?this.runWhenCoreIdle(t):t()}async waitForStrictRemoteQueryTransport(e){if(e!==`remote`)return;let t=this.serverEndpointUrl,n=N_(this.serverAuthJson??`{}`,this.peerIdentity);for(;!this.hasUpstream();){this.throwServerTransportErrorForTier(`global`);let e=this.serverCarrierPromise;if(!e)return;let r=this.serverConnectionAttempt,i=e.then(()=>null,e=>e instanceof Error?e:Error(gy(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(gy(e))),s;try{s=await Promise.race([i,...r?.carrier===this.serverCarrier?[r.terminal]:[],...o?[o]:[]])}finally{a?.cancel()}if(this.closed)return;let c=this.serverEndpointUrl,l=this.serverAuthJson??`{}`;if(this.serverCarrierPromise&&(c!==t||!jb(n,N_(l,this.peerIdentity))))throw Error(`server transport scope changed while waiting for remote query`);if(s){if((s.message===`server transport replaced`||s.message===`server transport disconnected`)&&this.serverCarrierPromise!==null||this.linkStatus?.phase===`connecting`&&this.serverCarrierPromise!==null)continue;throw s}}}async processPendingPeerActivityBeforeRead(){if(this.nonDurableClient)for(;!this.closed&&this.peerTransportProcessedActivityEpoch<this.peerTransportActivityEpoch;)await this.progressPeerTransport()}attachLocalReadCoverageInBackground(e,t,n){e!=null&&e!==`local-first`||this.nonDurableClient||!this.serverTransport||(async()=>{await this.serverCarrierPromise,!(this.closed||this.ownerRuntime.closed)&&(await this.waitForStrictRemoteQueryTransport(`remote`),!(this.closed||this.ownerRuntime.closed)&&await this.readRowsForContextAsync(t,jv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Ve(e,ct(e)))throw Error(`Local-first native admission requires a verified account session`);if(!this.db.admitLocalFirstSession)throw Error(`Native runtime lacks local-first session admission`);this.db.admitLocalFirstSession(t,n,new T().decode(ne(e)))}applySessionClaims(e){!e||e.backendAuthority||this.readAuthorizationHost!==`trusted-serving`||!this.db.setIdentityClaims||this.db.setIdentityClaims(e.identity,e.claims)}table(e){let t=this.schema[e];if(!t)throw Error(`unknown table ${e}`);return t}currentTx(e,t){let n=_v(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Tv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Nb(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`);return}if(e.identity&&(!t||!Nb(e.identity,t))||t&&!e.identity)throw Error(`Native runtime mergeable transaction cannot mix write identities`)}assertTransactionAttribution(e,t){if(!(!e.attribution&&!t)){if(!e.attribution)throw Error(`Native runtime transaction was opened without backend attribution`);if(!t||!Nb(e.attribution,t))throw Error(`Native runtime backend-attributed transaction requires its original provenance subject`)}}pumpSubscriptions(){this.drainSubscriptionPool();for(let[e,t]of this.subscriptions)t.poolId===void 0&&this.startSubscriptionReader(e,t)}nativeSubscriptionPool(){return this.subscriptionPool===void 0&&(this.subscriptionPool=this.db.createSubscriptionPool?.()??null),this.subscriptionPool}drainSubscriptionPool(){let e=this.subscriptionPool;if(!(!e||this.pooledSubscriptions.size===0)){if(this.drainingSubscriptionPool){this.subscriptionPoolDirty=!0;return}this.drainingSubscriptionPool=!0;try{do{this.subscriptionPoolDirty=!1;for(let t of e.drain())this.applyPooledBatch(t)}while(this.subscriptionPoolDirty&&!this.closed)}finally{this.drainingSubscriptionPool=!1}}}applyPooledBatch(e){let t=this.pooledSubscriptions.get(e.id);if(t===void 0)return;let n=this.subscriptions.get(t),r=()=>n!==void 0&&!n.cancelled&&this.subscriptions.get(t)===n;if(!n||!r()){this.pooledSubscriptions.delete(e.id);return}for(let i of e.events){if(!r())break;try{this.applySubscriptionChunk(t,n,i)}catch(e){this.failSubscription(n,e instanceof Error?e:Error(String(e)))}}if(e.error&&(this.pooledSubscriptions.delete(e.id),!this.closed&&r())){let t=Error(e.error.message);t.code=e.error.code,this.failSubscription(n,t)}r()||this.pooledSubscriptions.delete(e.id)}withPermissionAdviceTimeout(e){if(this!==this.ownerRuntime)return this.ownerRuntime.withPermissionAdviceTimeout(e);if(this.closed||(!this.serverTransport||!this.serverCarrier)&&!this.nativeUpstreamConfigured())return Promise.resolve(`unknown`);let t=e(),n=rv(t)?{promise:this.awaitNativePermissionAdvice(t),cancel:()=>t.cancel()}:typeof t==`string`?{promise:Promise.resolve(t===`allowed`||t===`denied`||t===`unknown`?t:`unknown`),cancel:()=>{}}:t;return new Promise(e=>{let t=!1,r=n=>{t||(t=!0,clearTimeout(i),e(n))},i=setTimeout(()=>{n.cancel(),r(`unknown`)},2e3);n.promise.then(r,()=>r(`unknown`))})}async awaitNativePermissionAdvice(e){for(;;){if(this.closed)return e.cancel(),`unknown`;let t=e.poll();if(t!==null)return t===`allowed`||t===`denied`||t===`unknown`?t:`unknown`;await this.pumpServerTransport(),await ly(0)}}clearCoreDeadline(){this.coreDeadlineTimer!==void 0&&clearTimeout(this.coreDeadlineTimer),this.coreDeadlineTimer=void 0,this.coreDeadlineAt=void 0}scheduleCoreWake(e){if(this.coreProgressAllowed()){if(e===`after-current-turn`){setTimeout(()=>this.scheduleCoreWake(`immediate`),0);return}if(e.startsWith(`after:`)){let t=Number(e.slice(6));if(!Number.isSafeInteger(t)||t<0)return;let n=performance.now()+t;if(this.coreDeadlineAt!==void 0&&this.coreDeadlineAt<=n)return;this.clearCoreDeadline(),this.coreDeadlineAt=n,this.coreDeadlineTimer=setTimeout(()=>{this.coreDeadlineTimer=void 0,this.coreDeadlineAt=void 0,this.scheduleCoreWake(`immediate`)},t);return}if(this.notifyPeerTransportWork(),e===`immediate`){this.scheduleCoreTick();return}queueMicrotask(()=>{this.scheduleCoreTick()})}}scheduleCoreTick(){if(this.coreProgressAllowed()){if(this.coreOperation){this.coreTickAgain=!0;return}this.coreTickScheduled||(this.coreTickScheduled=!0,queueMicrotask(()=>{if(this.coreTickScheduled=!1,this.coreProgressAllowed()){if(this.coreOperation){this.coreTickAgain=!0;return}this.runCoreTick().catch(e=>{try{if(this.db.isNativeForegroundClosed?.())return}catch(e){Ib(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Ib(e)})}}))}}runCoreTick(){if(!this.coreProgressAllowed())return Promise.resolve();let e=this.coreOperation;if(e)return this.coreTickAgain=!0,e.kind===`tick`?e.completion:e.completion.then(()=>this.runCoreTick());let t,n,r=new Promise((e,r)=>{t=e,n=r});return this.coreOperation={kind:`tick`,completion:r},this.driveCoreTicks().then(t,n),r}reportSlowQueries(){let e=this.ownerRuntime;for(let t of this.db.takeSlowQueryReport?.(e.slowQueryApp)??[]){if(e.slowQueryConsoleDetail!==`summary`){console.warn(`[jazz] ${t}`);continue}let n=fv(t);if(n===t){console.warn(`[jazz] ${t}`);continue}console.warn(`[jazz] ${n}. Plan and SQL are logged at the debug ("Verbose") level.`),console.debug(`[jazz] ${t}`)}}async driveCoreTicks(){let e=!1;try{for(let t=0;;t+=1){this.coreTickAgain=!1;try{await this.db.tick()}catch(e){throw new vm(e)}if(this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=ev){e=!0;break}}}finally{this.drainTransportRetirements(),this.coreOperation=null}e&&this.coreProgressAllowed()&&setTimeout(()=>this.scheduleCoreTick(),0)}drainTransportRetirements(){let e=[...this.pendingTransportRetirements];this.pendingTransportRetirements.clear();for(let[t,n]of e)try{t.close();for(let e of n)e.resolve()}catch(e){for(let t of n)t.reject(e)}}startSubscriptionReader(e,t){let n=t.source;if(t.cancelled||t.reading||!t.callback||!n)return;if(t.poolId!==void 0){this.drainSubscriptionPool();return}let r=n.joinPool?this.nativeSubscriptionPool():null;if(r&&n.joinPool){let i=n.joinPool(r);t.poolId=i,this.pooledSubscriptions.set(i,e),this.drainSubscriptionPool();return}t.reading=!0,this.readSubscription(e,t,n)}readSubscription(e,t,n){let r=()=>!t.cancelled&&this.subscriptions.get(e)===t,i=()=>{t.reading=!1},a=e=>{!this.closed&&r()&&this.failSubscription(t,e instanceof Error?e:Error(String(e))),i()},o=n=>{if(n.type===`closed`||!r())return n.type===`closed`&&this.terminateSubscription(e,t),i(),!1;if(n.type===`pending`)return this.pumpServerTransport().then(()=>ly(Math.max(0,n.retryAfterMs))).then(s).catch(a),!1;for(let a of n.events){if(!r())return i(),!1;try{this.applySubscriptionChunk(e,t,a)}catch(e){this.failSubscription(t,e instanceof Error?e:Error(String(e)))}}return n.events.length===0||!r()?(i(),!1):!0},s=()=>{for(;r();){let e;try{e=n.pull(e=>{o(e)&&s()},a)}catch(e){a(e);return}if(e===void 0||!o(e))return}i()};s()}applySubscriptionChunk(e,t,n){let r=Cb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Tb(r.reason));return}let i=pb(r.delta,this.schema,r.reset===!0,t.outputColumns);i.terminalOperations=ny(r.terminalOperations,t.outputColumns?.rootColumns),t.callback?.(i)}scheduleServerPump(){if(!(this.closed||!this.serverTransport)){if(this.serverPumpRunning){this.serverPumpAgain=!0;return}this.serverPumpScheduled||(this.serverPumpScheduled=!0,setTimeout(()=>{this.serverPumpScheduled=!1,!this.closed&&this.startServerPump()},Z_))}}startServerPump(){let e=this.serverConnectionGeneration;this.pumpServerTransport().catch(t=>this.handleServerTransportError(t,e))}notifyPeerTransportWork(e=!1){for(let t of this.peerTransportWorkListeners)t(e)}hasUpstream(){return this.serverTransport!=null||this.peerUpstreamAttached}async pumpServerTransport(){let e=this.serverTransport,t=this.serverCarrier,n=this.serverConnectionGeneration;if(!(this.closed||!e||!t)){if(this.serverPumpRunning){this.serverPumpAgain=!0;return}this.serverPumpRunning=!0;try{let r=this.pendingInboundServerFrames.length>0?await this.routePendingInboundServerFrames():!1;r||=this.serverInboundProcessed,this.serverInboundProcessed=!1;for(let i=0;i<32;i+=1){if(await this.runCoreTick(),this.flushAuxiliaryOutbound(e,t,n),(r||this.serverInboundProcessed)&&(r=!1,this.serverInboundProcessed=!1,this.notifyServerTransportWork(),queueMicrotask(()=>this.notifyServerTransportWork())),this.closed||n!==this.serverConnectionGeneration||e!==this.serverTransport||t!==this.serverCarrier||this.stopRefusedUpstream(e))return;let i=mv(e.recvWireFrames());if(i.length>0&&this.sendServerFrames(i,t,n),this.pumpSubscriptions(),i.length===0)return}this.serverPumpAgain=!0}finally{this.serverPumpRunning=!1,this.serverPumpAgain&&(this.serverPumpAgain=!1,this.scheduleServerPump())}}}stopRefusedUpstream(e){let t=gm(e.upstreamRefusal?.());if(!t)return!1;let n=this.serverConnectionAttempt;return!n||n.transport!==e?!1:(this.upstreamRefusal=t,this.endLinkAttempt(n,t,{kind:`fatal`,message:t.message}),!0)}async routePendingInboundServerFrames(){let e=!1,t=this.serverInboundRouting.then(async()=>{let t=this.serverTransport,n=this.serverCarrier,r=this.serverConnectionGeneration;if(!t||this.pendingInboundServerFrames.length===0)return;let i=this.pendingInboundServerFrames.splice(0);e=!0,this.serverInboundProcessed=!0;let a=[];for(let e of i){let i=t.routeAuxiliaryWireFrame?await t.routeAuxiliaryWireFrame(e):e;if(n&&this.refreshAuxiliaryReceiveDeadline(t,n,r),t!==this.serverTransport||r!==this.serverConnectionGeneration)return;i!=null&&a.push(hv(i))}if(this.publishAuxiliaryTrace(t),a.length>0)if(t.sendWireFrames)t.sendWireFrames(a);else for(let e of a)t.sendWireFrame(e);this.notifyPeerTransportWork(!0),n&&this.flushAuxiliaryOutbound(t,n,this.serverConnectionGeneration)});return this.serverInboundRouting=t.then(()=>void 0,()=>void 0),await t,e}refreshAuxiliaryReceiveDeadline(e,t,n){if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let r=this.auxiliaryReceiveDeadlines.get(e);r||(r=new Ki(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(gy(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Ib))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=mv(r.call(e));i.length>0&&this.sendServerFrames(i,t,n),this.publishAuxiliaryTrace(e)}publishAuxiliaryTrace(e){let t=e.takeAuxiliaryTrace?.();if(!(!t||t.length===0))for(let e of this.auxiliaryTraceListeners)e(t)}async watchAuxiliaryOutbound(e,t,n){for(;!this.closed&&e===this.serverTransport&&t===this.serverCarrier&&n===this.serverConnectionGeneration;){let r=e.auxiliaryOutboundReady?.();if(!r||typeof r==`boolean`||(await r,e!==this.serverTransport||t!==this.serverCarrier))return;this.flushAuxiliaryOutbound(e,t,n)}}sendServerFrames(e,t,n){n!==this.serverConnectionGeneration||t!==this.serverCarrier||t.sendBatch(e).catch(e=>{this.handleServerTransportError(e,n)})}forgetServerTransportError(){this.serverTransportError=null,this.serverTransportErrorRetrying=!1,this.serverTransportErrorAwaitsAuth=!1}handleServerTransportError(e,t=this.serverConnectionGeneration,n=!1){if(t!==this.serverConnectionGeneration&&(this.closed||!ym(e)))return;let r=gy(e);if(this.serverTransportError&&r===`websocket closed`){if(n||!this.serverTransportErrorRetrying)return;e=this.serverTransportError}e===this.serverTransportError&&this.serverTransportErrorAwaitsAuth&&(n=!0),this.serverTransportErrorAwaitsAuth=!1;let i=this.serverTransportError===null||this.serverTransportErrorRetrying&&!n;this.serverTransportError=e instanceof Error?e:Error(r),this.serverTransportErrorRetrying=n,this.linkChanged(),n||this.failRemoteSubscriptions(this.serverTransportError),this.resolveServerTransportErrorWaiters(this.serverTransportError,n),i&&this.serverTransportErrorCallback?.(this.serverTransportError,{retrying:n})}finishServerConnectionAttempt(e,t,n=!0){if(e.finished)return;e.finished=!0,this.linkChanged(),e.outcome=t,e.resolveTerminal(t);let r=e===this.serverConnectionAttempt&&e.generation===this.serverConnectionGeneration&&e.carrier===this.serverCarrier;r&&(this.serverConnectionGeneration+=1,this.serverConnectionAttempt=null,this.serverCarrier=null),e.carrier.close();let i=e.transport;if(e.transport=null,i){i===this.serverTransport&&(this.serverTransport=null);try{if(this.coreOperation){let t=Promise.resolve(this.retirePeerTransport(i));e.retirement=t,t.catch(e=>{this.closed||this.handleServerTransportError(e)})}else this.retirePeerTransport(i),e.retirement=null}catch(t){let n=Promise.reject(t);e.retirement=n,n.catch(e=>{this.closed||this.handleServerTransportError(e)})}}if(e.admission){let t=e.admission;e.admission=null,e.retirement=t.then(e=>this.retirePeerTransport(e),()=>void 0),e.retirement.catch(e=>{this.closed||this.handleServerTransportError(e)})}e.retirement&&(this.serverReplacementRetirement=av(this.serverReplacementRetirement,e.retirement),this.serverReplacementRetirement.catch(()=>void 0)),r&&(n&&this.handleServerTransportError(t),this.resolveServerTransportWorkWaiters())}failRemoteSubscriptions(e){for(let t of this.subscriptions.values())t.cancelled||t.tier===`remote`&&this.failSubscription(t,e)}terminateSubscription(e,t){this.subscriptions.get(e)===t&&this.subscriptions.delete(e),this.retireSubscriptionResources(t)}failSubscription(e,t){e.cancelled||(e.terminalError=t,this.retireSubscriptionResources(e),this.deliverSubscriptionFailure(e))}retireSubscriptionResources(e){if(e.cancelled)return;e.cancelled=!0,e.poolId!==void 0&&this.pooledSubscriptions.delete(e.poolId),e.openingAbort?.abort();let t=e.source;if(e.source=void 0,t)try{zv(t)}catch(e){console.error(`Jazz subscription source cleanup failed`,e)}}deliverSubscriptionFailure(e){if(!(!e.callback||!e.terminalError||e.terminalErrorDelivered)){e.terminalErrorDelivered=!0;try{e.callback(e.terminalError)}catch(e){setTimeout(()=>{throw e},0)}}}serverTransportErrorFor(e){return e&&this.serverTransportErrorRetrying?null:this.serverTransportError}throwServerTransportErrorForTier(e,t=!1){if(e!==`global`&&e!==`remote`)return;let n=this.serverTransportErrorFor(t);if(n)throw n}waitForServerTransportError(e,t=!1){if(e!==`global`&&e!==`remote`)return null;let n=this.serverTransportErrorFor(t);if(n)return{promise:Promise.reject(n),cancel:()=>{}};let r={active:!0,throughOutage:t,reject:()=>{}},i=new Promise((e,t)=>{r.reject=t});return this.serverTransportErrorWaiters.push(r),{promise:i,cancel:()=>{if(!r.active)return;r.active=!1;let e=this.serverTransportErrorWaiters.indexOf(r);e>=0&&this.serverTransportErrorWaiters.splice(e,1)}}}resolveServerTransportErrorWaiters(e,t=!1){let n=this.serverTransportErrorWaiters.splice(0);for(let r of n)r.active&&(t&&r.throughOutage?this.serverTransportErrorWaiters.push(r):r.reject(e))}clearServerTransportErrorWaiters(){for(let e of this.serverTransportErrorWaiters)e.active=!1;this.serverTransportErrorWaiters.length=0}waitForServerTransportWork(e,t){if(e!==`global`&&e!==`remote`)return null;if(this.serverTransportWorkEpoch!==t)return{promise:Promise.resolve(),cancel:()=>{}};let n={active:!0,resolve:()=>{}},r=new Promise(e=>{n.resolve=e});return this.serverTransportWorkWaiters.push(n),{promise:r,cancel:()=>{if(!n.active)return;n.active=!1;let e=this.serverTransportWorkWaiters.indexOf(n);e>=0&&this.serverTransportWorkWaiters.splice(e,1)}}}notifyServerTransportWork(){this.serverTransportWorkEpoch+=1,this.resolveServerTransportWorkWaiters()}resolveServerTransportWorkWaiters(){let e=this.serverTransportWorkWaiters.splice(0);for(let t of e)t.active&&t.resolve()}};function mv(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function hv(e){let t=mv([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function gv(e,t){let n=e.txId;return t.set(n,e),n}function _v(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function vv(e){if(e)try{let t=JSON.parse(e);if(!t.branch_view||typeof t.branch_view!=`object`)return;let n=t.branch_view;return n.head==null?void 0:{head:n.head,base:n.base}}catch{return}}function yv(e,t){if(!e)return!1;let n;try{if(n=JSON.parse(e),n.attribution!==void 0)return!0;if(!(n.issuer!==void 0||n.user_id!==void 0||n.session!==void 0))return!1}catch{return!1}try{let n=xv(e);return n===null||!Nb(n.identity,t)}catch{return!0}}function bv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function xv(e){if(!e)return null;try{let t=JSON.parse(e);if(t.attribution===`system`)throw Error(`Native runtime public session uses reserved issuer`);let n=typeof t.attribution==`string`?D(t.attribution):null;if(n?.issuer===`urn:jazz:system`)throw Error(`Native runtime public session uses reserved issuer`);let r=n?.user_id??(typeof t.user_id==`string`?t.user_id:typeof t.session?.user_id==`string`?t.session.user_id:void 0);if(!r||!P(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!P(i))throw Error(`session is missing issuer`);let a={account_id:Pv(n?n.account_id:(t.session??t).account_id),issuer:i,user_id:r,authMode:typeof t.session?.authMode==`string`?t.session.authMode:typeof t.authMode==`string`?t.authMode:`external`};Sv(a.issuer,a.user_id,a.authMode,t.session?.__jazz_trusted_reserved_session??t.__jazz_trusted_reserved_session,a.account_id);let o=t.session?.__jazz_trusted_reserved_session??t.__jazz_trusted_reserved_session,s=Rv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:ne(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Ve(a,o)}}catch(e){if(e instanceof Error&&(e.message===`session is missing issuer`||e.message===`session has invalid account_id`||e.message===`Native runtime public session uses reserved issuer`))throw e;return null}}function Sv(e,t,n,r,i){if(Ke(e)&&!((n===`local-first`||n===`anonymous`||n===`external`)&&Ve({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Cv(e){if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t.updated_at==`number`){if(!Number.isSafeInteger(t.updated_at)||t.updated_at<0)throw Error(`updatedAt must be a nonnegative safe integer`);return t.updated_at}}function wv(e){return Cv(e)??null}function Tv(e,t){return t.get(e)?.state===`committed`?`open transaction ${e} is already committed`:`open transaction ${e} has already been completed or was never opened`}function Ev(e,t){let n=Tv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function Dv(e,t){let n=Tv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Ov(e,t,n){let r=Av(e);if(!(!r||t.has(r)))throw Error(`Query setup failed: Write error: ${Tv(r,n)}`)}function kv(e,t){let n=Av(e);return n?t.get(n):void 0}function Av(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function jv(e,t=!1,n){let r=n==null?{}:JSON.parse(n),i={};e!=null&&(i.tier=e),t&&(i.include_deleted=!0),typeof r.first_load_remote_wait_ms==`number`&&r.first_load_remote_wait_ms>0&&(i.first_load_remote_wait_ms=r.first_load_remote_wait_ms);let a=r.read_view??r.readView;return a!=null&&(i.read_view=a),Array.isArray(r.splices)&&r.splices.length>0&&(i.splices=r.splices),i}function Mv(e){if(e==null)return!1;try{let t=JSON.parse(e);return typeof t.first_load_remote_wait_ms==`number`&&t.first_load_remote_wait_ms>0}catch{return!1}}function Nv(e,t){if(e!=null&&![`local-first`,`remote`,`local-only`].includes(e))throw Error(`Native runtime received unsupported read tier '${e}'`);t!=null&&JSON.parse(t)}function Pv(e){if(e!==void 0){if(typeof e!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e))throw Error(`session has invalid account_id`);return e}}function Fv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!P(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!P(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Pv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};Sv(n.issuer,n.user_id,n.authMode,t[De],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Ve(n,t.__jazz_trusted_reserved_session);return{...n,claims:Rv(t.claims,n),identity:ne(n),backendAuthority:r}}function Iv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lv(e){return e===null||typeof e==`boolean`||typeof e==`string`?JSON.stringify(e):typeof e==`number`?Number.isFinite(e)?JSON.stringify(e):`null`:Array.isArray(e)?`[${e.map(Lv).join(`,`)}]`:Iv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Lv(e[t])}`).join(`,`)}}`:`null`}function Rv(e,t){return{...Iv(e)?e:{},iss:t.issuer,sub:t.user_id}}function zv(e){e.close()}function Bv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function Vv(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function Hv(e,t){return Ey(e,t)}function Uv(e){if(Wv(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function Wv(e){let t=JSON.parse(e);return Yv(t.select_columns??t.select)||Xv(t.conditions)||Gv(t.relation_ir)||Kv(t.relation_ir)||Zv(t.array_subqueries)}function Gv(e){return $v(e)}function Kv(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(Kv);let t=e,n=t.Project;if(n&&typeof n==`object`){let e=n.columns;if(Array.isArray(e))for(let t of e){if(!t||typeof t!=`object`)continue;let e=t,n=Jv(e.expr??e.source);if(n&&ws(n))return!0}}return Object.values(t).some(Kv)}function qv(e){if(!e||typeof e!=`object`)return null;let t=e;return qy(t.left??t.column)}function Jv(e){return!e||typeof e!=`object`?null:`Column`in e?qy(e.Column):qy(e)}function Yv(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&ws(ey(e))):!1}function Xv(e){return Array.isArray(e)?e.some($v):!1}function Zv(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return Yv(t.select_columns??t.select)||Qv(t.filters)||Zv(t.nested_arrays)}):!1}function Qv(e){return Array.isArray(e)?e.some($v):!1}function $v(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some($v);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&ws(ey(t.column)))return!0;for(let e of[`Eq`,`Ne`,`Gt`,`Ge`,`Lt`,`Le`,`IsNull`,`IsNotNull`,`Contains`]){let n=t[e];if(!n||typeof n!=`object`)continue;let r=n.column;if(typeof r==`string`&&ws(ey(r)))return!0}let n=qv(t.Cmp)??qv(t.In)??qv(t.IsNull)??qv(t.IsNotNull)??qv(t.Contains);return n&&ws(ey(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&$v(t))}function ey(e){return hs(e)}function ty(e,t){let n=JSON.parse(e);if(typeof n.table!=`string`)throw Error(`Native runtime only supports table queries in this slice`);return{rootTable:n.table,rootColumns:oy(n.table,t,Ay(n.select_columns??n.select),My(n.array_subqueries,n.table,t)??[])}}function ny(e,t){if(!(!e||e.length===0))return e.map(e=>{let n=t,r,i=e.path.map(e=>{if(`Key`in e)return{Key:ry(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Hs.length):e.Collection,i=n.findIndex(e=>e.name===t),a=n[i]?.column_type;if(a?.type!==`Array`||a.element.type!==`Row`)throw Error(`native terminal operation addressed unknown collection ${t}`);return n=a.element.columns,r=n,{Collection:i}}),a=e.edit;if(`Insert`in a){if(!r)throw Error(`native terminal insert has no collection target`);let t=ay(a.Insert.key);return{root_key:ry(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:ry(a.Insert.key),row:Xm(t,r,iy(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=ay(a.Update.key);return{root_key:ry(e.root_key),path:i,edit:{Update:{key:ry(a.Update.key),row:Xm(t,r,iy(a.Update.value))}}}}return`Remove`in a?{root_key:ry(e.root_key),path:i,edit:{Remove:{key:ry(a.Remove.key)}}}:{root_key:ry(e.root_key),path:i,edit:{Move:{key:ry(a.Move.key),index:a.Move.index}}}})}function ry(e){return Array.isArray(e)?e:Array.from(e)}function iy(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function ay(e){let t=iy(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return Ce(t.subarray(1,17))}function oy(e,t,n,r,i=!0){let a=G(t,e);if(!a)throw Error(`missing schema for subscription table ${e}`);let o=n===void 0,s=(n??a.columns.map(e=>e.name)).map(e=>{let t=a.columns.find(t=>t.name===e);if(t)return o&&i?{...t,sparse:!0}:t;let n=Es(e);return n?{name:e,column_type:n,nullable:e===`$deletedAt`||e.startsWith(`$deletedBy`)}:void 0}).filter(e=>e!==void 0);for(let e of r){let n=oy(e.table,t,e.select,e.nestedArrays??[],!1);s.push({name:e.columnName,column_type:{type:`Array`,element:{type:`Row`,columns:n}},nullable:!1})}return s}function sy(e){let t=JSON.parse(e);return cy(t.array_subqueries),JSON.stringify(t)}function cy(e){if(Array.isArray(e))for(let t of e){if(!t||typeof t!=`object`)continue;let e=t;if(Array.isArray(e.select_columns)&&Array.isArray(e.nested_arrays))for(let t of e.nested_arrays){if(!t||typeof t!=`object`)continue;let n=t.outer_column;if(typeof n!=`string`)continue;let r=hs(n);(Ay(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}cy(e.nested_arrays)}}function ly(e){return new Promise(t=>setTimeout(t,e))}function uy(e,t){return Cy(t)?dy(e,t):wy(t)?fy(e,t):null}function dy(e,t){let n=gy(t),r={kind:`rejected`,transactionId:e,code:`transaction_conflict`,reason:/^\(transaction_conflict\):\s*(.*)$/s.exec(n)?.[1]||n,message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function fy(e,t){let n=gy(t),r={kind:`rejected`,transactionId:e,code:by(Hc(t)),reason:Sy(n,Hc(t)),message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function py(e,t){try{return t()}catch(t){if(wy(t)){let n=gy(t),r=Ty(n)??n,i=Hc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:by(i)})}throw t}}function my(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function hy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function gy(e){if(e instanceof Error)return e.message;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`&&t.trim())return t;try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)}function _y(e=`a store configured as one user serves only its own identity's peers`){return Object.assign(Error(e),{code:`protocol`,reason:`identity_mismatch`})}function vy(e,t){let n=t instanceof Error?t:Error(gy(t));return Error(`${e}: ${n.message}`,{cause:n})}var yy={authorization_denied:`permission_denied`,client_clock_too_far_ahead:`client_clock_too_far_ahead`,serialization_conflict:`serialization_conflict`,row_already_deleted:`write_rejected`,row_already_exists:`write_rejected`,row_not_deleted:`write_rejected`,missing_required:`write_rejected`,branch_move:`write_rejected`,missing_chunks:`write_rejected`,predecessor_rejected:`write_rejected`,schema_version_not_deployed:`write_rejected`,identity_mismatch:`write_rejected`};function by(e){return e===void 0?`write_rejected`:yy[e]}var xy={permission_denied:`Write rejected by server authorization`,serialization_conflict:`Serializable transaction conflicted with another write`,client_clock_too_far_ahead:`Client clock is too far ahead`};function Sy(e,t){let n=Ty(e);return n===null?e:xy[by(t)]??(n||`Write rejected`)}function Cy(e){return Bc(e)===`transaction_conflict`}function wy(e){return Bc(e)===`write_rejected`}function Ty(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Ey(e,t){let n=JSON.parse(e);if(typeof n.table!=`string`)throw Error(`Native runtime only supports table queries in this slice`);let r=n.table;if(n.relation_ir!=null){let i=wm(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Lh(r,[],{relation:i.relation_ir,select:Ay(n.select_columns??n.select),partial:ky(n.select_columns),arraySubqueries:My(n.array_subqueries,r,t)})}let i=Hy(n.conditions);if(!i)throw Z();return Lh(r,i.map(e=>Dy(r,e,t)),{limit:Xy(n.limit),offset:Zy(n.offset),orderBy:jy(n.order_by??n.orderBy),select:Ay(n.select_columns??n.select),partial:ky(n.select_columns),arraySubqueries:My(n.array_subqueries,r,t)})}function Z(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function Dy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>Dy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:Dy(e,t.predicate,n)};if(zo(e)&&`column`in t){if(t.column===`$transactionId`)throw Error(`History $transactionId predicates do not accept user-provided values`);if(t.column===`$acceptedAt`){if(t.op===`In`)return{op:`Any`,predicates:t.values.map(r=>Dy(e,{column:t.column,op:`Eq`,value:r},n))};if(Oy(t)){let r=zy(e,t.column,t.value,n);if(r.type!==`Timestamp`||!Number.isSafeInteger(r.value))throw Error(`History $acceptedAt predicates require a valid Date or integer milliseconds`);let i=BigInt(r.value)<<18n,a=i+(1n<<18n)-1n,o=(e,n)=>n<0n||n>(1n<<64n)-1n?{op:(n<0n?e===`Gt`||e===`Gte`:e===`Lt`||e===`Lte`)?`All`:`Any`,predicates:[]}:{column:t.column,op:e,value:{type:`U64`,value:n}};switch(t.op){case`Eq`:return{op:`All`,predicates:[o(`Gte`,i),o(`Lte`,a)]};case`Ne`:return{op:`Not`,predicate:{op:`All`,predicates:[o(`Gte`,i),o(`Lte`,a)]}};case`Gt`:return o(`Gt`,a);case`Gte`:return o(`Gte`,i);case`Lt`:return o(`Lt`,i);case`Lte`:return o(`Lte`,a)}}}}if(t.op===`In`){let r=t.column===`id`?{type:`Uuid`}:G(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return r?.type===`Array`?{op:`Any`,predicates:t.values.map(i=>i.type===`Array`?{column:t.column,op:`Eq`,value:zy(e,t.column,i,n)}:{column:t.column,op:`Contains`,value:By(i,r.element,!1)})}:{...t,values:t.values.map(r=>zy(e,t.column,r,n))}}if(t.op===`Contains`){let r=t.column===`id`?{type:`Uuid`}:G(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?By(t.value,r.element,!1):zy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(Oy(t))return{...t,value:zy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Oy(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function ky(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;if(e.kind===`json_pointer`){if(typeof e.at!=`string`)throw Z(`select_columns`);t.push({column:e.column,kind:`json_pointer`,at:e.at})}else if(e.kind===`bytes`||e.kind===`text_utf16`||e.kind===`text_utf8`){if(typeof e.from!=`number`||typeof e.to!=`number`)throw Z(`select_columns`);t.push({column:e.column,kind:e.kind,from:e.from,to:e.to})}}return t}function Ay(e){if(e==null)return;if(!Array.isArray(e))throw Z();let t=[];for(let n of e){if(typeof n==`string`){t.push(n);continue}if(!n||typeof n!=`object`||typeof n.column!=`string`)throw Z();let e=n;if(e.kind!==`full`&&e.kind!==`bytes`&&e.kind!==`text_utf16`&&e.kind!==`text_utf8`&&e.kind!==`json_pointer`)throw Z();t.push(e.column)}return t}function jy(e){if(e==null)return[];if(!Array.isArray(e))throw Z(`order_by`);return e.map(e=>{if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`){if(e[1]!==`asc`&&e[1]!==`desc`)throw Z(`order_by`);return{column:e[0],direction:e[1]===`asc`?`Asc`:`Desc`}}if(!e||typeof e!=`object`)throw Z(`order_by`);let t=e;if(typeof t.column!=`string`||t.direction!==`Asc`&&t.direction!==`Desc`)throw Z(`order_by`);return{column:t.column,direction:t.direction}})}function My(e,t,n){if(e!=null){if(!Array.isArray(e))throw Z(`array_subqueries`);return e.map(e=>Ny(e,t,n))}}function Ny(e,t,n){if(!e||typeof e!=`object`)throw Z(`array_subqueries`);let r=e;if(typeof r.column_name!=`string`||typeof r.table!=`string`||typeof r.inner_column!=`string`||typeof r.outer_column!=`string`)throw Z(`array_subqueries`);if(Array.isArray(r.joins)&&r.joins.length>0)throw Z(`array_subqueries.joins`);let i=Py(r.filters,r.table,n),a=Ay(r.select_columns),o=Iy(r.order_by),s=My(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:Ry(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:Yy(r.limit),offset:Zy(r.offset),requirement:Ly(r.requirement),nestedArrays:s}}function Py(e,t,n){if(e==null)return[];if(!Array.isArray(e))throw Z(`array_subqueries.filters`);let r=[];for(let i of e){let e=Fy(i);if(!e)throw Z(`array_subqueries.filters`);r.push(...e.map(e=>Dy(t,e,n)))}return r}function Fy(e){let t=Wy(e);if(t)return[t];if(!e||typeof e!=`object`)return null;let n=e;for(let[e,t]of[[`Eq`,`Eq`],[`Ne`,`Ne`],[`Gt`,`Gt`],[`Ge`,`Gte`],[`Lt`,`Lt`],[`Le`,`Lte`]]){let r=n[e];if(r&&typeof r==`object`){let{column:e,value:n}=r;return typeof e==`string`?[{column:e,op:t,value:Gy(n)}]:null}}let r=n.IsNull;if(r&&typeof r==`object`){let e=r.column;return typeof e==`string`?[{column:e,op:`IsNull`}]:null}let i=n.IsNotNull;if(i&&typeof i==`object`){let e=i.column;return typeof e==`string`?[{column:e,op:`IsNotNull`}]:null}let a=n.Contains;if(a&&typeof a==`object`){let{column:e,value:t}=a;return typeof e==`string`?[{column:e,op:`Contains`,value:Gy(t)}]:null}return null}function Iy(e){if(e==null)return[];if(!Array.isArray(e))throw Z(`array_subqueries.order_by`);return e.map(e=>{if(!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`||e[1]!==`Ascending`&&e[1]!==`Descending`)throw Z(`array_subqueries.order_by`);return{column:e[0],direction:e[1]===`Ascending`?`Asc`:`Desc`}})}function Ly(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Z(`array_subqueries.requirement`)}function Ry(e,t){let n=`${t}.`;return e.startsWith(n)?e.slice(n.length):e}function zy(e,t,n,r){let i=t===`id`?{type:`Uuid`}:Es(t)??G(r,e)?.columns.find(e=>e.name===t)?.column_type;if(i?.type===`Bytea`&&n.type===`Array`)return{type:`Bytea`,value:Uint8Array.from(n.value.map(Vy))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:G(r,e)?.columns.find(e=>e.name===t)?.column_type,a=i?.type===`Array`?i.element:i;return{type:`Array`,value:n.value.map(e=>By(e,a,!1))}}return By(n,i,!0)}function By(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:By(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&Qy(e.value))return{type:`Uuid`,value:e.value};if(t?.type===`Text`&&e.type===`Uuid`)return{type:`Text`,value:e.value};if(t?.type===`Double`&&e.type===`Integer`)return{type:`Double`,value:e.value};if(t?.type===`BigInt`&&e.type===`Integer`)return{type:`BigInt`,value:Om(e.value,`BigInt value`)};if(t?.type===`Timestamp`&&e.type===`Integer`)return{type:`Timestamp`,value:e.value};if(t?.type===`Timestamp`&&e.type===`Text`){let t=Date.parse(e.value);if(Number.isFinite(t))return{type:`Timestamp`,value:t}}return t?.type===`Bytea`&&e.type===`Array`?{type:`Bytea`,value:Uint8Array.from(e.value.map(Vy))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>By(e,t.element,!1))}:e}function Vy(e){if(e.type!==`Integer`||e.value<0||e.value>255)throw Error(`Bytea values must contain integers in range 0..255`);return e.value}function Hy(e){if(e==null)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!=`object`)return null;let e=Wy(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=hs(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:Gy(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:Gy(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:Gy(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:Gy(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:Gy(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:Gy(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:Gy(r.value)});break;case`isNull`:if(typeof r.value!=`boolean`)return null;t.push({column:i,op:r.value?`IsNull`:`IsNotNull`});break;case`in`:if(!Array.isArray(r.value))return null;t.push({column:i,op:`In`,values:r.value.map(Gy)});break;default:return null}}return t}function Uy(e){if(e===`True`)return[];if(e===`False`)return[{column:`id`,op:`In`,values:[]}];if(!e||typeof e!=`object`)return null;let t=e;if(Array.isArray(t.And)){let e=[];for(let n of t.And){let t=Uy(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=Wy(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=qy(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=qy(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=qy(e.left),n=Jy(e.right);return t&&n?[{column:t,op:`Contains`,value:n}]:null}let a=t.In;if(a&&typeof a==`object`){let e=a,t=qy(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(Jy);return n.every(e=>e!=null)?[{column:t,op:`In`,values:n}]:null}let o=t.Cmp;if(!o||typeof o!=`object`)return null;let s=o,c=Ky(s.op);if(!c)return null;let l=qy(s.left),u=Jy(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function Wy(e){if(e===`True`)return{op:`All`,predicates:[]};if(e===`False`)return{op:`Any`,predicates:[]};if(!e||typeof e!=`object`)return null;let t=e;if(Array.isArray(t.And)||Array.isArray(t.Or)){let e=Array.isArray(t.And)?`All`:`Any`,n=(t.And??t.Or).map(Wy);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=Wy(t.Not);return e?{op:`Not`,predicate:e}:null}let n=Uy(e);return n?.length===1?n[0]:null}function Gy(e){if(e==null)return{type:`Nullable`,value:null};if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`&&Number.isSafeInteger(e))return{type:`Integer`,value:e};if(typeof e==`number`&&Number.isFinite(e))return{type:`Double`,value:e};if(typeof e==`bigint`)return{type:`BigInt`,value:e};if(typeof e==`string`)return Qy(e)?{type:`Uuid`,value:e}:{type:`Text`,value:e};if(e instanceof Uint8Array)return{type:`Bytea`,value:e};if(Array.isArray(e))return{type:`Array`,value:e.map(Gy)};throw Z()}function Ky(e){switch(e){case`Eq`:case`Ne`:case`Gt`:case`Gte`:case`Lt`:case`Lte`:return e;case`Ge`:return`Gte`;case`Le`:return`Lte`;default:return null}}function qy(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?hs(t):null}function Jy(e){if(!e||typeof e!=`object`||!(`Literal`in e))return null;let t=e.Literal;if(!t||typeof t!=`object`)return null;let n=t;if(n.type===`Boolean`&&typeof n.value==`boolean`)return{type:`Boolean`,value:n.value};if(n.type===`Integer`&&typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`Integer`,value:n.value};if(n.type===`BigInt`){if(typeof n.value==`string`&&n.value.length<=Y_&&X_.test(n.value))try{return{type:`BigInt`,value:Om(BigInt(n.value),`BigInt value`)}}catch{return null}if(typeof n.value==`bigint`||typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`BigInt`,value:BigInt(n.value)}}if(n.type===`Timestamp`&&typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`Timestamp`,value:n.value};if(n.type===`Double`&&typeof n.value==`number`&&Number.isFinite(n.value))return{type:`Double`,value:n.value};if(n.type===`Bytea`&&Array.isArray(n.value))return{type:`Bytea`,value:Uint8Array.from(n.value.map(Number))};if(n.type===`Null`)return{type:`Nullable`,value:null};if(n.type===`Array`&&Array.isArray(n.value)){let e=n.value.map(e=>Jy({Literal:e}));if(e.every(e=>e!=null))return{type:`Array`,value:e}}return n.type===`Uuid`&&typeof n.value==`string`?{type:`Uuid`,value:n.value}:(n.type===`Text`||n.type===`Enum`)&&typeof n.value==`string`?{type:`Text`,value:n.value}:null}function Yy(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function Xy(e){return e==null?void 0:Yy(e)}function Zy(e){if(e==null)return 0;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query offset must be a non-negative safe integer`);return e}function Qy(e){return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e)}function $y(e,t,n){return ib(e.columns,t,n),rb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function eb(e,t,n,r){return ib(e.columns.filter(e=>e.name!==n),t,r),rb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function tb(e,t,n){return rb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function nb(e,t){return rb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function rb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:gh(e),column:e})),i=r.map(({column:e})=>ab(e,t(e),n)),a=new Xh;return Vm(a,r),a.bytes(Gm(r,i)),a.finish()}function ib(e,t,n){for(let r of e){let e=t[r.name]??r.default;if(!(e&&e.type!==`Null`)&&!r.nullable)throw Error(n?`encoding error: missing required field \`${r.name}\` on table \`${n}\``:`missing required column ${r.name}`)}}function ab(e,t,n){let r=t;if(!r){if(e.nullable)return uh(gh(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return ch(e,r)}function ob(e){return new Zh(e).readVec(jm)}function sb(e){return Rm(new Zh(e))}function cb(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=lb(a,t,n),o=th(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=gb(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(qm({table:a.table,id:Ce(t.rowId),values:n},s))}}return i}function lb(e,t,n){let r=cv.get(t);r||(r=new Map,cv.set(t,r));let i=ng(e),a=n?void 0:r.get(i);if(a)return a;let o=n??G(t,e.table)?.columns??[],s=new Map(o.map(e=>[e.name,e])),c=n?new Set(n.map(e=>e.name)):null,l=[];for(let t=0;t<e.descriptor.length;t+=1){let n=e.descriptor[t],r=n&&Am(n);if(!r)continue;let i=Es(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!Pb(r)&&(!Ts(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function ub(e,t,n,r=`full-record`){return fb(cb(e.rows,t,n,r),t).slice(0,e.rootCount)}var db=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function fb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((G(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of db){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:qm({...e,values:e.values.filter(e=>!i.has(e))},r)})}function pb(e,t,n=!1,r=null){let i=(e,n,i,a)=>{let o=hb(e,t,r,`full-record`);if(o.length!==n.length)throw Error(`subscription occurrence sidecar length mismatch`);return o.flatMap((e,o)=>{if(r&&e.table!==r.rootTable)return[];let s=a?.[o];return[{sourceId:e.id,occurrenceKey:n[o],index:i[o],row:Db(e,t,r),...s&&s.length>0?{splices:mb(s,t,e.table)}:{}}]})};return{added:i(e.added,e.addedOccurrenceKeys,e.addedIndices),updated:i(e.updated,e.updatedOccurrenceKeys,e.updatedIndices,e.updatedSplices),removed:e.removed.flatMap((t,n)=>r&&t.table!==r.rootTable?[]:[{sourceId:Ce(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{}}}function mb(e,t,n){let r=G(t,n)?.columns??[],i={};for(let{column:t,splices:n}of e){let e=r.find(e=>e.name===t)?.column_type.type;if(e===`Text`)i[t]=n.map(e=>({at:e.atUtf16,delete:e.deleteUtf16,insert:sv.decode(e.insert)}));else if(e===`Bytea`)i[t]=n.map(e=>({at:e.at,delete:e.delete,insert:e.insert}));else throw Error(`subscription splices for column "${t}" of type ${e} are not supported yet`)}return i}function hb(e,t,n,r){return e.flatMap(e=>cb([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function gb(e,t,n,r){let i=t(n,e.index);if(i==null)return{type:`Null`};if(!e.type)return{type:`Bytea`,value:i};try{return _b(e.type,i,e.name,e.storageType,r)}catch(t){throw Error(`${String(t)} while decoding ${e.name} as ${e.type.type} from storage tag ${e.storageType.tag} (${i.byteLength} bytes)`)}}function _b(e,t,n,r,i=`full-record`){let a=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e.type){case`Boolean`:return{type:`Boolean`,value:t[0]!==0};case`Integer`:return{type:`Integer`,value:a.getInt32(0,!0)};case`BigInt`:return{type:`BigInt`,value:vb(r)?.tag===3?a.getBigUint64(0,!0):a.getBigInt64(0,!0)};case`Double`:return{type:`Double`,value:a.getFloat64(0,!0)};case`Timestamp`:return{type:`Timestamp`,value:Number(a.getBigUint64(0,!0))};case`Text`:case`Json`:case`Enum`:if(t[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return{type:`Text`,value:sv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:Ce(t)};case`Bytea`:if(t[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return{type:`Bytea`,value:t.subarray(1).slice()};case`Array`:return{type:`Array`,value:Sb(e.element,t,yb(r),i)};case`Row`:{let a={type:`Row`,value:xb(e.columns,t,bb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ee(a),a}}}function vb(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function yb(e){let t=vb(e);return t?.tag===14?t.inner:void 0}function bb(e){let t=vb(e);return t?.tag===16?t.record:void 0}function xb(e,t,n,r=`full-record`){if(n){let i=r===`keyed-terminal`;if(i&&n[0]?.name!==`row_uuid`)throw Error(`keyed terminal nested row descriptor must start with row_uuid`);if(i&&t.byteLength<16)throw Error(`terminal nested row is missing its key`);let a=i?n.slice(1):n,o=i?t.subarray(16):t,s=th(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?Ce(t.subarray(0,16)):void 0;for(let e=0;e<a.length;e+=1){let t=a[e]?.name;if(!t)continue;let n=s(o,e);if(!i&&t===`row_uuid`&&n){u=Ce(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:_b(d.column_type,n,t,a[e]?.valueType,r))}let d=e.map(e=>l.get(e.name)??(e.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}));return qm({id:u,values:d},l)}if(t.byteLength<5)throw Error(`invalid nested row value`);let i=t[0]===1,a=1,o;if(i){if(t.byteLength<21)throw Error(`invalid nested row id`);o=Ce(t.subarray(a,a+16)),a+=16}let s=Mb(t,a);a+=4;let c=t.subarray(a,a+s);if(c.byteLength!==s)throw Error(`invalid nested row value length`);return{id:o,values:Km(e,c)}}function Sb(e,t,n,r=`full-record`){let i=Eh(n??vh(e));if(i!=null){if(i===0)return[];if(t.length%i!==0)throw Error(`invalid fixed-width array byte length ${t.length}`);let a=[];for(let o=0;o<t.length;o+=i)a.push(_b(e,t.subarray(o,o+i),void 0,n,r));return a}if(t.length<4)throw Error(`invalid variable-width array byte length`);let a=Mb(t,0),o=4+Math.max(0,a-1)*4;if(o>t.length)throw Error(`invalid variable-width array offset table`);let s=[];for(let i=0;i<a;i+=1){let c=i===0?o:Mb(t,4+(i-1)*4),l=i===a-1?t.length:Mb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(_b(e,t.subarray(c,l),void 0,n,r))}return s}function Cb(e){if(!e||typeof e!=`object`)throw Error(`expected subscription chunk`);let t=e;if(t.type===`closed`||t.type===`Closed`)return{type:`closed`};if(t.type===`delta`||t.type===`Delta`)return{type:`delta`,reset:t.reset===!0,delta:Fm(new Zh(Fb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:wb(t.reason)};throw Error(`unknown subscription chunk`)}function wb(e){if(!e||typeof e!=`object`)throw Error(`expected subscription rejection reason`);let t=e;if(t.type===`UnsupportedShapeCapability`&&typeof t.detail==`string`)return{type:`UnsupportedShapeCapability`,detail:t.detail};if(t.type===`ShapeRegistrationPendingCatalogueAdmission`)return{type:`ShapeRegistrationPendingCatalogueAdmission`};let n=t.code??t.detail;if(t.type===`ServerFailure`&&typeof n==`string`)return typeof t.errorCode==`string`?{type:`ServerFailure`,code:n,errorCode:t.errorCode}:{type:`ServerFailure`,code:n};if(t.type===`InvalidAuthoritySourceClosure`&&typeof t.transition==`string`)return{type:`InvalidAuthoritySourceClosure`,transition:t.transition};throw Error(`unknown subscription rejection reason`)}function Tb(e){let t=e.type===`UnsupportedShapeCapability`?e.detail:e.type===`ServerFailure`?e.code:e.type===`InvalidAuthoritySourceClosure`?e.transition:`catalogue admission pending`,n=`Subscription rejected: ${e.type}: ${t}`,r=e.type===`ServerFailure`?e.errorCode:void 0;return r===void 0?Error(n):gm({code:r,message:n})??Error(n)}function Eb(e){let t=e;if(typeof t.getReader==`function`){let e=t.getReader();return{pull(t,n){e.read().then(e=>t(e.done?{type:`closed`}:{type:`batch`,events:[e.value]}),n)},close(){e.cancel().catch(()=>{})}}}let n=e;return{joinPool:n.joinPool?e=>n.joinPool(e):void 0,pull(){let e=n.readAll();return Array.isArray(e)?{type:`batch`,events:e}:{type:`pending`,retryAfterMs:e.retryAfterMs?.()??0}},close(){n.close?.()}}}function Db(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?_h(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=Ab(e,i).map((e,t)=>Ob(e,i[t].column_type));return qm({id:e.id,values:a},Jm(i,a))}function Ob(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Ob(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:kb(e.value,t.columns)}:e}function kb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Ob(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return qm({id:e.id,values:r},Jm(t,r))}function Ab(e,t){if(!e.valuesByColumn)return e.values.slice(0,t.length);let n=[];n.length=t.length;for(let r=0;r<t.length;r+=1){let i=t[r];n[r]=e.valuesByColumn.get(i.name)??(i.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`})}return n}function jb(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function Q(e){let t=Ze(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Mb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Nb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pb(e){return e.startsWith(Hs)}function Fb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Ib(e){queueMicrotask(()=>{throw e})}var Lb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Ya(e,t,n,r,i,!1,a)}ready(){return this.connection.ready()}waitForServerConnection(){return this.connection.waitForServerConnection()}async updateAuth(e,t){this.connection.updateAuth(e,t)}disconnect(){return this.connection.disconnect()}reconnect(e,t){return this.connection.reconnect(e,t)}deleteStorage(){return this.connection.deleteStorage()}storePendingUploads(){return this.connection.storePendingUploads()}waitForPendingWrites(){return this.connection.waitForPendingWrites()}flushLocal(){return this.connection.flushLocal()}shutdown(){return this.connection.shutdown()}async openInspectorControlPort(){throw Error(`Inspector peers cannot open nested inspector sessions`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.connection.getAuthenticatedInspectorAttachmentPhysicalDbName()}};function Rb(e,t,n=globalThis.WebSocket){let r=new URL(e.replace(/^ws/,`http`)).origin;if(typeof n!=`function`)throw Error(`Jazz: this platform has no WebSocket`);return Vb(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return Bb(t)},`the app's bearer`)}var zb=3e4;function Bb(e){let t;return Promise.race([Promise.resolve().then(()=>e()),new Promise((e,n)=>{t=setTimeout(()=>n(Error(`the app's bearer did not answer`)),zb)})]).finally(()=>clearTimeout(t))}function Vb(e,t,n){return class{type=`arraybuffer`;inner;closed=!1;listeners=[];constructor(r){let i=t(r);if(!i){this.attach(new e(r));return}i.then(t=>{this.closed||this.attach(t?new e(r,{headers:{authorization:`Bearer ${t}`}}):new e(r))},e=>{this.closed||(this.closed=!0,console.error(`Jazz: ${n} failed`,e),this.emit(`error`,e),this.emit(`close`,{code:1006,reason:`credential unavailable`}))})}get binaryType(){return this.inner?.binaryType??this.type}set binaryType(e){this.type=e,this.inner&&(this.inner.binaryType=e)}attach(e){e.binaryType=this.type,this.inner=e;for(let[t,n]of this.listeners)e.addEventListener(t,n)}emit(e,t){for(let[n,r]of this.listeners)n===e&&r(t)}get readyState(){return this.inner?this.inner.readyState:this.closed?3:0}send(e){if(!this.inner)throw Error(`WebSocket is not open`);this.inner.send(e)}close(){if(this.inner)return this.inner.close();this.closed||(this.closed=!0,queueMicrotask(()=>this.emit(`close`,{code:1e3,reason:``})))}addEventListener(e,t){this.listeners.push([e,t]),this.inner?.addEventListener(e,t)}}}var Hb=`warn`;function Ub(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??Hb}function Wb(e){return rt({...e,trustedReservedSession:A(e)})}function Gb(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=Me(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`local-first`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Ae(n??{},r);if(!i||i.issuer!==t.issuer||i.user_id!==t.user_id||i.authMode!==t.authMode)throw Error(`Attached browser worker session does not match its identity token`);l(e,i)}function Kb(e){let t=Wb(e);if(t)return t;if(e.adminSecret)return{issuer:`https://jazz.invalid`,user_id:`backend-open`};throw Error(`Default runtime requires a verified session or admin credential`)}function qb(e){return!Wb(e)&&!!e.adminSecret}function Jb(e,t){if(!(!t||!e.jwtToken||t.issuer!==`urn:jazz:local-first`&&t.issuer!==`urn:jazz:anonymous`))return{token:e.jwtToken,appId:H(e),claimedAuthor:ze(t.issuer,t.user_id,t.account_id)}}function Yb(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function Xb(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var Zb=class extends dm{supportsBrowserWorker=!0;module=null;ownerRuntime=null;get wasmModule(){if(!this.module)throw Error(`Default runtime source is not loaded`);return this.module}async load(e){this.module??=await im(e.runtimeSources)}admitConfig(e){Gb(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,foregroundNodeLease:i}){Ub(e.logLevel);let a={onAuthFailure:r},o=Jb(e,Wb(e)),s=qb(e),c=i?.node.slice()??ie(),u=ne(Kb(e)),d=Yb(e),f=ex(e),p=e.cookieSession&&e.accountId?Qo(e):void 0,m=this.nativeSchemaView(t,c,u,d,!f,o,s,{appId:H(e),thresholdMs:e.slowQueryThresholdMs,...Qb()?{consoleDetail:`summary`}:{}},n,p&&e.serverUrl?Rb(e.serverUrl,p):void 0);if(i&&m.seedForegroundTxTimeHighWater(i.confirmedTxTime),f&&(m.setNonDurableClient(),!i))throw Error(`Persistent browser runtime requires a foreground node lease`);let h={appId:H(e),accountId:e.accountId,schema:t,driver:e.driver,serverUrl:e.serverUrl,env:e.env,jwtToken:e.jwtToken,cookieSession:e.cookieSession,adminSecret:e.adminSecret};return l(h,A(e)),te.connectWithRuntime(this.wrapClientRuntime(m,e,t),h,a)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!ex(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=iu(e);return await yo.acquire({runtimeSources:Xb(e),dbName:t,storageOwner:zi(e)})}async acquireForegroundNodeLease(t){if(!$b()||(t.driver?.type??`persistent`)!==`persistent`)return;let{acquireNodeForegroundNodeLease:n}=await e(async()=>{let{acquireNodeForegroundNodeLease:e}=await import(`./node-foreground-node-lease.browser-CH8w-D6S.js`);return{acquireNodeForegroundNodeLease:e}},[],import.meta.url);return await n({appId:H(t),env:t.env??`dev`,authScope:Ri(t)})}createBrowserWorkerConnection({config:e,schema:t,client:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l}){let u=n.getRuntime();if(!(u instanceof pv))throw Error(`Browser worker connections require the native runtime adapter`);let d=Jb(e,Wb(e));if(qb(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let f=iu(e),p=ne(Kb(e));return e.runtimeSources?.browserWorkerPort?new Lb(u,e.runtimeSources.browserWorkerPort,Wb(e)?.claims??{},f,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l},e.runtimeSources.inspectorBinding):new bo(u,{runtimeSources:Xb(e),schema:t,dbName:f,author:p,selfSignedClientProof:d,initialSyncFlushEvery:Yb(e),migrations:u.migrations,appId:H(e),slowQueryThresholdMs:e.slowQueryThresholdMs,storageOwner:zi(e),authSessionKey:Ri(e),serverUrl:e.serverUrl?ke(e.serverUrl,H(e)):void 0,authJson:JSON.stringify(tx(e)),sessionClaims:Wb(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Pi(e,f,qe(t)),{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof pv))throw Error(`Browser follower connections require the native runtime adapter`);let l=Wb(e)?.claims??{},u=new Ya(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(tx(e)),l),u}nativeSchemaView(e,t,n,r,i,a,o=!1,s,c,l){return!this.ownerRuntime||this.ownerRuntime.isClosed()?(this.ownerRuntime=new pv(this.wasmModule.WasmDb,e,t,n,1,i,{initialSyncFlushEvery:r,selfSignedClientProof:a,backendMode:o,slowQueryLog:s,migrations:c,webSocket:l}),this.ownerRuntime):Object.keys(e).length===0?this.ownerRuntime:this.ownerRuntime.registerSchemaView(e,c)}installTelemetry({config:e,collectorUrl:t,runtimeThread:n}){return li({wasmModule:this.wasmModule,collectorUrl:t,runtimeThread:n})}textAnchors(){return lm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function Qb(){return typeof window<`u`&&typeof Worker<`u`}function $b(){return typeof process<`u`&&!!process.versions?.node}function ex(e){return Qb()&&(e.driver?.type??`persistent`)===`persistent`}function tx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function nx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},cu(e),at(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(at(e))}),o=e.getSyncStatus().link.state===`connected`,s=e.onSyncStatusChange(({link:e})=>{let t=e.state===`connected`;t&&!o&&i.retryRejected(),o=t}),c=n?.(e);return ot({db:e,get session(){return r},async shutdown(t){t?.waitForSync&&await e.shutdown(t),await Ml([()=>a?.(),()=>s(),...c?[c]:[],()=>i.shutdown(),()=>e.shutdown()])}},i)}function rx(e){return(e.driver??{type:`persistent`}).type===`persistent`?iu(e):null}function ix(e){if(typeof window>`u`)return()=>{};let t=rx(e.getConfig());if(!t)return()=>{};let n=window;Lo(n);let r=To(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function ax(e){return nx(e,H(e.getConfig()),ix)}async function ox(e,t,n){await new Promise((r,i)=>{let a=t=>{clearTimeout(c),e.removeEventListener(`message`,s),e.removeEventListener(`messageerror`,o),t?i(t):r()},o=()=>a(Error(`Inspector attachment channel failed`)),s=({data:e})=>{if(!(!(`id`in e)||e.id!==-1)){if(e.type===`result`&&e.error)return a(He(e.error));if(e.type!==`inspector-binding`||e.binding.appId!==t.appId||e.binding.physicalDbName!==t.physicalDbName||e.binding.authSessionKey!==t.authSessionKey||e.binding.storageOwner!==t.storageOwner)return a(Error(`Inspector attachment receipt does not match its requested scope`));a()}},c=setTimeout(()=>a(Error(`Inspector attachment timed out`)),1e4);e.addEventListener(`message`,s),e.addEventListener(`messageerror`,o),e.start(),e.postMessage({type:`inspect-binding`,id:-1,binding:t,leasePort:n},[n])})}var sx=class extends Zb{leasePort;inspectorPort;leaseRequested=!1;constructor(e,t){super(),this.leasePort=e,this.inspectorPort=t}wrapClientRuntime(e,t,n){return mt(e,this.inspectorPort,t.runtimeSources.inspectorBinding,n)}async acquireBrowserForegroundNodeLease(e){return this.leaseRequested=!0,yo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:zi(e)})}};async function cx(e,t,n,r){let i=new MessageChannel,a=new sx(i.port1,r);try{if(!e.jwtToken)throw Error(`Inspector attachment requires the host's resolved client token`);let o={appId:t,jwtToken:e.jwtToken,accountId:e.accountId,accountRegistryAuthority:e.accountRegistryAuthority,serverUrl:e.serverUrl,env:e.env,runtimeSources:{...e.runtimeSources,browserWorkerPort:r,inspectorHostPhysicalDbName:n}};Gb(o);let s=Vi(o,``);if(!n.endsWith(s))throw Error(`Inspector storage scope mismatch`);o.driver={type:`persistent`,dbName:n.slice(0,-s.length)};let c={appId:t,physicalDbName:n,authSessionKey:Ri(o),storageOwner:zi(o)};return await ox(r,c,i.port2),o.runtimeSources.inspectorBinding=c,ts(o),await ax(await dd(o,a))}catch(e){try{r.postMessage({type:`close`})}catch{}throw r.close(),a.leaseRequested||(i.port1.postMessage({type:`cancel-foreground-node-lease`}),i.port1.close(),i.port2.close()),e}}function lx(e,t){let n=t?.runtimeSources?.inspectorHostPhysicalDbName??null;return e.find(e=>e.appId===t?.appId&&e.dbName===n)?.key??e[0]?.key??null}var $=st(),ux=200,dx=15e3,fx=1e3;function px(e,t){return t.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n()};t.addEventListener(`abort`,i,{once:!0})})}function mx(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>mx(e,t[n]));let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length?n.every((n,i)=>n===r[i]&&mx(e[n],t[n])):!1}function hx(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.key===e.key&&r.appId===e.appId&&r.dbName===e.dbName&&mx(r.schema,e.schema)})}var gx=class extends I.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}render(){return this.state.error?(0,$.jsxs)(`p`,{style:{padding:16},children:[`Inspector connection failed: `,this.state.error.message]}):this.props.children}};function _x(){let[e,t]=(0,I.useState)(null),[n,r]=(0,I.useState)([]),[i,a]=(0,I.useState)(null),o=(0,I.useRef)(Promise.resolve()),[s,c]=(0,I.useState)(null),[l,u]=(0,I.useState)(!1),[d,f]=(0,I.useState)(null);return(0,I.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+dx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await Ne({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(lx(s.contexts,je()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await px(Math.min(ux,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,I.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await px(fx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>hx(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:lx(n,je()))}catch{}}})(),()=>t.abort()},[e]),(0,I.useEffect)(()=>{if(!e||!i)return;let t=n.find(e=>e.key===i);if(!t)return;let r,a=!0,s;c(null),f(null);let l=o.current.then(()=>{if(a){if(r=je(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){Be(e);return}let n=await cx(r,t.appId,t.dbName,e);if(!a){await n.shutdown();return}s=n,c({client:n,schema:t.schema})}).catch(e=>{a&&f(e instanceof Error?e:Error(String(e)))});return o.current=l,()=>{a=!1,o.current=l.then(()=>s?.shutdown()).catch(e=>{f(e instanceof Error?e:Error(String(e)))})}},[n,i,e]),d?(0,$.jsxs)(`p`,{style:{padding:16},children:[`Inspector connection failed: `,d.message]}):s?(0,$.jsxs)($.Fragment,{children:[n.length>1?(0,$.jsxs)(`label`,{style:{display:`block`,padding:`8px 12px`},children:[`Runtime context`,` `,(0,$.jsx)(`select`,{value:i??``,onChange:e=>a(e.target.value),children:n.map(e=>(0,$.jsxs)(`option`,{value:e.key,children:[e.appId,` / `,e.dbName]},e.key))})]}):null,(0,$.jsx)(vx,{client:s.client,wasmSchema:s.schema},i)]}):l?(0,$.jsx)(`p`,{style:{padding:16},children:`Inspector: no host connection found. Is this page running under the Jazz dev plugin?`}):(0,$.jsx)(`p`,{style:{padding:16},children:`Connecting…`})}function vx({client:e,wasmSchema:t}){return(0,$.jsx)(gx,{children:(0,$.jsx)(nt,{client:e,children:(0,$.jsx)(xe,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(we,{initialEntries:[new URLSearchParams(window.location.search).get(`route`)??`/`],children:(0,$.jsx)(Qe,{})})})})})}(0,dt.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(I.StrictMode,{children:(0,$.jsx)(_x,{})}));
4
+ `)}function _u(e){return{...e,branches:[...e.branches]}}function vu(e,t){if(G(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function yu(e,t,n){return pu(e,t,n)??{}}function bu(e,t,n,r){let i=G(e,t)?.columns??[];for(let e of r){let r=i.find(t=>t.name===e);if(!r)throw Error(`splices: "${e}" is not a column of "${t}".`);let a=r.column_type.type;if(a!==`Text`&&a!==`Bytea`)throw Error(`splices: column "${e}" is ${a}; splices are not supported yet for columns other than TEXT and BYTEA.`);if(n._columnTransforms?.[e])throw Error(`splices: column "${e}" has a column transform; splices are not supported yet for transformed columns.`)}}function xu(e,t,n){for(let r of n)if(Object.hasOwn(e.partialSelect,r)&&!Object.hasOwn(t.partialSelect,r))throw Error(`splices: column "${r}" is selected in part, but a computed or transformed column depends on it, so it is read whole; splices are not supported yet for such columns.`)}function J(e){if(zo(e._table))throw Error(`History table "${e._table}" is read-only`)}function Su(e,t,n){return Cu(e,Gu(t,n),t._schema,t._table)}function Cu(e,t,n,r){try{return sl(t,n,r)}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`${e} failed: WriteError("${Iu(n)}")`)}}function wu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Tu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Eu(e,t,n){let r=Number(e);if(!Number.isSafeInteger(r)||r<0)throw Error(`${t} for "${n}" must be a non-negative safe integer.`);return r}function Du(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Ou(e,t,n){let r=Au(e,t,n?.applyDiffs),i=n?.editedFrom;if(i===void 0)return{replacements:t,descriptors:r};if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`update option editedFrom must be an object keyed by column name.`);let a={...t},o=[];for(let[t,n]of Object.entries(i)){if(n===void 0)continue;let i=e._columnTransforms?.[t];if(i&&!i.computed)throw Error(`update option editedFrom is not supported yet on "${t}", which has a transform.`);let s=a[t];if(typeof s!=`string`||typeof n!=`string`)throw Error(`update option editedFrom.${t} needs a string, and a string replacement for "${t}".`);delete a[t],o.push(t),r.push({kind:`text_edit`,column:t,text:s,edited_from:n})}return{replacements:a,descriptors:r}}function ku(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function Au(e,t,n){if(n===void 0)return[];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`update option applyDiffs must be an object keyed by column name.`);if(Object.keys(t).some(e=>Object.hasOwn(n,e)))throw Error(`update replacements and applyDiffs must not both specify the same column.`);let{ordinary:r,descriptors:i}=ju(n,e._schema,e._table);if(Object.keys(r).length>0)throw Error(`update option applyDiffs accepts only field diff descriptors, not whole-column values.`);return i}function ju(e,t,n){let r={},i=[],a=t[n]?.columns;if(!a)throw Error(`Unknown table "${n}"`);for(let[t,o]of Object.entries(e)){if(!wu(o)){r[t]=o;continue}let e=a.find(e=>e.name===t)?.column_type;if(!e)throw Error(`Unknown column "${t}" in table "${n}"`);if(`splices`in o&&`within`in o){let n=Tu(o.within,`Large-value update "${t}" has an invalid page.`),r=o.splices;if(!Array.isArray(r))throw Error(`Large-value update "${t}" has invalid splices.`);let a;if(`fromUtf8`in n||`toUtf8`in n){if(e.type!==`Text`)throw Error(`UTF-8 splice requires a Text column, got "${t}".`);let r=Eu(n.fromUtf8,`fromUtf8`,t),i=Eu(n.toUtf8,`toUtf8`,t);Du(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Eu(n.from,`from`,t),r=Eu(n.to,`to`,t);Du(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Eu(n.from,`from`,t),r=Eu(n.to,`to`,t);Du(e,r,t),a={kind:`text_utf16`,from:e,to:r}}else throw Error(`Splice requires a Text or Bytea column, got "${t}".`);i.push({kind:`splice`,column:t,within:a,splices:r.map(e=>{let n=Tu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Eu(r?n.atUtf8:n.at,`at`,t),o=Eu(r?n.deleteUtf8:n.delete,`delete`,t),s=n.insert,c;if(a.kind===`bytes`){if(!(s instanceof Uint8Array))throw Error(`Byte splice insert for "${t}" must be a Uint8Array.`);c=[...s]}else{if(typeof s!=`string`)throw Error(`Text splice insert for "${t}" must be a string.`);c=[...new TextEncoder().encode(s)]}return{at:i,delete:o,insert:c}})});continue}if(`edits`in o){if(e.type!==`Json`)throw Error(`JSON set requires a JSON column, got "${t}".`);if(!Array.isArray(o.edits))throw Error(`JSON update "${t}" has invalid edits.`);i.push({kind:`json_set`,column:t,edits:o.edits.map(e=>{let n=Tu(e,`JSON update edit for "${t}" is invalid.`);if(n.op!==`set`||typeof n.at!=`string`)throw Error(`JSON update "${t}" supports only { op: "set", at, value } edits.`);return{at:n.at,value:n.value}})});continue}r[t]=o}return{ordinary:r,descriptors:i}}function Mu(e,t){if(t<0||t>e.length)return!1;if(t===0||t===e.length)return!0;let n=e.charCodeAt(t-1),r=e.charCodeAt(t);return!(n>=55296&&n<=56319&&r>=56320&&r<=57343)}function Nu(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`~`){t+=r;continue}let i=e[++n];if(i===`0`)t+=`~`;else if(i===`1`)t+=`/`;else throw Error(`JSON pointer has an invalid escape.`)}return t}function Pu(e,t){if(t===``)return e;if(!t.startsWith(`/`))throw Error(`JSON pointer must be empty or begin with '/'.`);let n=e;for(let e of t.slice(1).split(`/`)){let t=Nu(e);if(Array.isArray(n)){if(!/^(0|[1-9]\d*)$/.test(t))throw Error(`JSON array pointer token is not an index.`);let e=Number(t);if(!Number.isSafeInteger(e)||e>=n.length)throw Error(`JSON pointer path does not exist.`);n=n[e]}else if(typeof n==`object`&&n&&Object.hasOwn(n,t))n=n[t];else throw Error(`JSON pointer path does not exist.`)}return n}function Fu(e,t){if(Object.keys(t).length===0||typeof e!=`object`||!e)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(`at`in r){n[e]=Pu(t,r.at);continue}if(t instanceof Uint8Array){if(`fromUtf8`in r)throw Error(`Byte range for "${e}" takes from and to, not fromUtf8 and toUtf8.`);if(r.from>r.to)throw Error(`Byte range for "${e}" ends before it starts.`);n[e]=t.slice(r.from,r.to);continue}if(typeof t!=`string`)throw Error(`Large-value selection for "${e}" has an incompatible column type.`);if(`fromUtf8`in r){let i=new TextEncoder().encode(t),a=Math.min(r.toUtf8,i.length),o=Math.min(r.fromUtf8,a);if(r.fromUtf8>r.toUtf8)throw Error(`UTF-8 range for "${e}" ends before it starts.`);if(o<i.length&&(i[o]&192)==128||a<i.length&&(i[a]&192)==128)throw Error(`UTF-8 range for "${e}" splits a code point.`);n[e]=new T({fatal:!0}).decode(i.slice(o,a));continue}let i=Math.min(r.to,t.length),a=Math.min(r.from,i);if(r.from>r.to)throw Error(`UTF-16 range for "${e}" ends before it starts.`);if(!Mu(t,a)||!Mu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Iu(e){return e.replaceAll(`"`,`\\"`)}function Lu(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function Ru(e,t,n,r){let i=Lu(e,t.table,n),a=n===t.table||!Object.keys(t.includes).length?t.includes:{},o=Object.keys(a).length>0;if(!i&&(!e._columnTransformsByTable||!o)){let r=Mc(e._schema,n,a,t.select);return{computedState:void 0,version:0,physical:a===t.includes?t:{...t,includes:a},transform:r}}let s=o?bs(e._schema):void 0,c=(t,a,o,l)=>{let u=e._columnTransformsByTable?.[t]??(t===n?i:void 0),d=a,f=l,p=!a.length||a.includes(`*`),m,h,g,_=e=>{u?.[e]?.computed||(!p&&e!==`id`&&!d.includes(e)&&(d===a&&(d=[...a]),d.push(e),(h??=[]).push(e)),Object.hasOwn(f,e)&&(f===l&&(f={...l}),delete f[e]))};if(u&&a.some(e=>u[e]?.computed)&&(d=a.filter(e=>!u[e]?.computed)),u){for(let e of p?Object.keys(u):a)if(Object.hasOwn(u,e)&&((m??={})[e]=u[e],u[e].computed)){r??=new Yc,(g??=[]).push(e);for(let t of r.storedColumns(u,e))_(t)}}!p&&!d.length&&(d=[`id`]);let v=o,y=[];for(let[e,n]of Object.entries(o)){let r=s?.get(t)?.find(t=>t.name===e)?.toTable;if(!r)continue;let i=c(r,n.select,n.includes,n.partialSelect);(i.select!==n.select||i.includes!==n.includes||i.partialSelect!==n.partialSelect)&&(v===o&&(v={...o}),v[e]={...n,select:i.select,includes:i.includes,partialSelect:i.partialSelect}),i.finish&&y.push([e,i.finish])}let b=Object.keys(l).length>0,x=Object.fromEntries(Object.entries(l).filter(([e])=>!Object.hasOwn(f,e))),S=Object.keys(x).length>0,C=Object.keys(o);return{select:d,includes:v,partialSelect:f,finish:m||b||y.length?e=>{let t=g?Zc(u,g,{...e},r,f):void 0,n=S?Fu(e,x):e;if(m&&wc(n,m,C,t,b?l:void 0),g)for(let e of g)n[e]=t.get(e);for(let[e,t]of y){let r=n[e];if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=t(r[e]);else r&&typeof r==`object`&&(n[e]=t(r))}if(h)for(let e of h)delete n[e];return n}:void 0}},l=c(n,t.select,a,t.partialSelect),u=Mc(e._schema,n,l.includes,l.select,void 0,!1,s);return{computedState:r,version:r?.version??0,physical:l.select===t.select&&l.partialSelect===t.partialSelect&&l.includes===t.includes?t:{...t,select:l.select,partialSelect:l.partialSelect,includes:l.includes},transform:l.finish?e=>l.finish(u(e)):u}}async function zu(e,t,n,r,i,a){for(;;){let o=[],s;for(let e of i)try{o.push(r.transform(e))}catch(e){if(!(e instanceof qc))throw e;s=e}if(!s)return o;if(!r.computedState||r.computedState.version===r.version)throw s;r=Ru(e,t,n,r.computedState),i=await a(r.physical)}}var Bu=new WeakMap;function Vu(e,t){let n=Bu.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Hu(e,t){return Uu(e,t)}function Uu(e,t){if(!e._columnTransforms||typeof t!=`object`||!t)return t;let n=t,r=Kc(e._columnTransforms),i=r.length?Zc(e._columnTransforms,r,n):void 0;wc(n,e._columnTransforms,[],i);for(let e of r)n[e]=i.get(e);return n}function Wu(e,t){let n=e._columnTransforms;if(n){for(let e of Object.keys(t))if(n[e]?.computed)throw TypeError(`Computed field "${e}" is read-only.`)}}function Gu(e,t){let n=t,r=e._columnTransforms;if(!r)return n;let i;for(let e in n){if(!Object.hasOwn(n,e))continue;let t=r[e];if(t?.computed)throw TypeError(`Computed field "${e}" is read-only.`);!t||n[e]===void 0||((i??={...n})[e]=t.to(n[e]))}return i??n}var Ku=1e4;function qu(e,t,n,r,i){let a=JSON.stringify({table:t._table,conditions:[{column:`id`,op:`eq`,value:n}],limit:1}),o=e.queryInternal(_c(a,t._schema),i?{tier:`remote`,branch:i}:{tier:`remote`},r),s,c=new Promise(e=>{s=setTimeout(()=>e([]),Ku)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function Ju(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Yu(e,t,n){return Hu(e,Nc(Wc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function Xu(e,t){if(typeof t!=`object`||!t)throw Error(`Streaming insert data must be an object`);let n=t,r=(e._schema[e._table]?.columns.filter(e=>[`Text`,`Json`,`Bytea`].includes(e.column_type.type)))?.filter(e=>Object.hasOwn(n,e.name)&&Zu(n[e.name]));if(r?.length!==1)throw Error(`Streaming insert requires exactly one streamed Text, Json, or Bytea column`);let i=r[0].name;if(e._schema[e._table]?.branchBy?.includes(i))throw Error(`Streaming a branchBy column is not supported: ${e._table}.${i}`);let a=n[i],o={...n};return delete o[i],{column:i,source:a,values:o}}function Zu(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function Qu(e,t){let n=e._schema[e._table]?.branchBy??[];if(n.length===0)return;let r={};for(let i of n){let n=t[i];if(Zu(n))throw Error(`Streaming a branchBy column is not supported: ${e._table}.${i}`);if(typeof n!=`string`&&typeof n!=`number`&&typeof n!=`bigint`)throw Error(`Streaming insert requires branch column ${e._table}.${i}`);r[i]=n}return r}function $u(e){return new Proxy(e,{get(e,t){if(t===`commit`||t===`rollback`)return;let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n},has(e,t){return t===`commit`||t===`rollback`?!1:Reflect.has(e,t)},set(e,t,n){return Reflect.set(e,t,n,e)}})}function ed(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function td(e,t,n){let r;try{r=t($u(e))}catch(t){try{await e.rollback()}catch{}throw t}let i=typeof n==`function`?n:()=>n,a;try{a=await r}catch(t){try{await e.rollback()}catch{}throw t}let o;try{let t=await e.commitUnlessEmpty();if(t===`empty`)return new c(a,i());o=t}catch(t){try{await e.rollback()}catch{}throw t}let s=o.txId.catch(async t=>{try{await e.rollback()}catch{}throw t});return ed(e,a,s,i())}var nd=class e{kind;resolveClient;context;static createWithAdmission(t,n,r,i,a){let o=new e(t,n,r);return o.openingPrerequisite=a,i&&o.bindOwnerClient(i),o}openingPrerequisite;pendingReads=new Set;committing=!1;constructor(e,t,n=null,r){this.kind=e,this.resolveClient=t,this.context=n,r&&this.bindOwnerClient(r)}bindTable(e){let t=this.resolveClient(e._schema);if(Bu.has(this)||this.bindOwnerClient(t),this.requireBinding(`table operation`).committing)throw Error(`Transaction commit has already been requested.`);return this.requireBinding(`table operation`)}bindQuery(e){return this.bindTable(e)}requireBinding(e){if(this.committing)throw Error(`DbTransaction.${e}() cannot run after commit has been requested`);return Vu(this,e)}bindOwnerClient(e){let{writeSession:t,attribution:n}=this.context??{},r=new Pc(!0),i=Ic(e),a=i?.pending?f():this.openingPrerequisite?re(e,this.kind,t,n,void 0,this.openingPrerequisite):e.beginTransaction(this.kind,t,n),o={ownerClient:e,openTransactionId:a,session:t,attribution:n,preparation:r,begun:!i?.pending};Bu.set(this,o),o.begun||r.run(()=>i.run(()=>{r.cancelled||(this.openingPrerequisite?re(e,this.kind,t,n,a,this.openingPrerequisite):e.beginTransaction(this.kind,t,n,a),o.begun=!0)}))}openTransactionId(){return this.requireBinding(`openTransactionId`).openTransactionId}commit(){let e=this.requireBinding(`commit`),{ownerClient:t,openTransactionId:n,preparation:r}=e;if(e.committing)throw Error(`Transaction commit has already been requested.`);(r.pending||r.failed)&&(e.committing=!0);let i=r.pending||r.failed||this.pendingReads.size>0?Promise.all([r.drain(),...this.pendingReads]).then(()=>t.commitTransaction(n).txId):t.commitTransaction(n).txId;this.committing=!0;let a=()=>{this.committing=!1};return i.then(a,a),this.kind===`serializable`?new Re(i,t):new Le(i,t)}async commitUnlessEmpty(){if(this.kind!==`mergeable`)return this.commit();let{ownerClient:e,openTransactionId:t,preparation:n}=this.requireBinding(`commit`);if(e.hasStagedTransactionWrites(t)!==!1)return this.commit();if(n.pending||n.failed){this.committing=!0;let r=!0;try{await n.drain()}catch{r=!1}finally{this.committing=!1}if(!r||e.hasStagedTransactionWrites(t)!==!1)return this.commit()}return await this.rollback(),`empty`}rollback(){let{ownerClient:e,openTransactionId:t,preparation:n,begun:r}=this.requireBinding(`rollback`);if(!r)return n.cancelled=!0,Promise.resolve(!0);let i=e.rollbackTransaction(t);return n.cancelled=!0,i}insertStreaming(e,t,n){return this.streamingMutation(`insert`,e,n?.id,t,n)}updateStreaming(e,t,n,r){return this.streamingMutation(`update`,e,t,n,r)}upsertStreaming(e,t,n,r){return this.streamingMutation(`upsert`,e,t,n,r)}streamingMutation(e,t,n,r,i){J(t),this.bindTable(t);let a=this.resolveClient(t._schema),o=e===`insert`?`Insert`:e===`update`?`Update`:`Upsert`,{openTransactionId:s,session:c,attribution:l,preparation:u}=this.requireBinding(`${e}Streaming`),{column:d,source:f,values:p}=Xu(t,r);Wu(t,p);let m=async()=>{let r=Cu(o,Gu(t,p),t._schema,t._table),u=e===`insert`?Qu(t,p):void 0,m=e===`insert`?fu(t._schema,t._table,{...i,...n?{id:n}:{},...u?{branch:u}:{}}):pu(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,r,d,f,s,m,c,l,n)};return Promise.resolve(u.run(()=>q(a,()=>u.cancelled?void 0:m()))).then(e=>{if(!e)throw Error(`Transaction was rolled back before the stream was staged`);return e})}insert(e,t,n){J(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`insert`),c=n?.id,{values:l,value:u}=this.prepareCreation(e,t,c,`Insert`);!c&&(s.pending||Ic(r)?.pending)&&(c=Ju());let d,f=()=>{d=r.insertInternal(e._table,l,fu(e._schema,e._table,c?{...n,id:c}:n),a,o,i)};s.cancelled?f():s.run(()=>q(r,()=>{s.cancelled||f()}));try{return u??(d?Hu(e,Nc(d,e._schema,e._table)):Yu(e,c,l))}catch(e){throw s.failure=e,e}}restore(e,t,n,r){J(e),this.bindTable(e);let{values:i,value:a}=this.prepareCreation(e,n,t,`Restore`),o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l,preparation:u}=this.requireBinding(`restore`),d=()=>{o.restoreInternal(e._table,t,i,fu(e._schema,e._table,r),c,l,s)};return u.cancelled?d():u.run(()=>q(o,()=>{u.cancelled||d()})),a}prepareCreation(e,t,n,r){let i;try{i=e._columnTransforms?Gu(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=Cu(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:Yu(e,n,a)}}catch(e){throw this.requireBinding(r).preparation.failure=e,e}}upsert(e,t,n,r){J(e),this.bindTable(e);let i=this.resolveClient(e._schema),{openTransactionId:a,session:o,attribution:s}=this.requireBinding(`upsert`);this.prepareMutation(e,n,`Upsert`,n=>{i.upsertInternal(e._table,t,n,pu(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){J(e),this.bindTable(e);let{replacements:i,descriptors:a}=Ou(e,n,r);r=ku(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=pu(e._schema,e._table,r);this.prepareMutation(e,i,`Update`,n=>{if(a.length>0){o.updateLargeValuesInternal(e._table,t,n,a,u?.updatedAt,c,l,s,u?.branch);return}o.updateInternal(e._table,t,n,u?.updatedAt,c,l,s,u?.branch)})}prepareMutation(e,t,n,r){let{ownerClient:i,preparation:a}=this.requireBinding(n);if(Wu(e,t),(a.pending||Ic(i)?.pending)&&(t={...t}),a.cancelled){r({});return}a.run(()=>q(i,()=>{if(a.cancelled)return;let i;try{i=Gu(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(Cu(n,i,e._schema,e._table))}))}delete(e,t,n){J(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`delete`),c=pu(e._schema,e._table,n),l=()=>{r.deleteInternal(e._table,t,c?.updatedAt,a,o,i,c?.branch)};s.cancelled?l():s.run(()=>q(r,()=>{s.cancelled||l()}))}all(e,t){let n=this.readAll(e,t);this.pendingReads.add(n);let r=()=>this.pendingReads.delete(n);return n.then(r,r),n}async readAll(e,t){this.bindQuery(e);let{preparation:n,openTransactionId:r}=this.requireBinding(`query`);(n.pending||n.failed)&&await n.drain();let i=this.resolveClient(e._schema),a=e._build(),o=Vs(JSON.parse(a)),s=vu(e._schema,o.table),c=vc(s,o),l=Ru(e,o,c),u=pu(e._schema,o.table,au(t))??{},d=await i.queryInternal(_c(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?zu(e,o,c,l,d,e=>i.queryInternal(_c(a,s,e),{...u,openTransactionId:r},this.context?.readSession)):d.map(l.transform)}async one(e,t){return(await this.all(mu(e),t))[0]??null}},rd=class e{config;runtimeSource;authStateStore;connection;_localFirstSecret=null;localFirstRefreshOwned=!1;localFirstRenewals=new vl;localFirstRefreshTimer=null;shutdownPromise=null;replaced=null;liveSubscriptionEnders=new Set;successor=null;movable=new Set;shutdownAbort=new AbortController;syncStatusSnapshot=null;activeQuerySubscriptionTraces=new Map;activeQuerySubscriptionTraceListeners=new Set;mutationErrorListeners=new Set;pendingMutationErrorEvents=[];nextActiveQuerySubscriptionTraceId=1;#e=null;constructor(e,t,n){$o(e),this.config=e,this.runtimeSource=t;let r={...e,trustedReservedSession:A(e)};d(this,rt(r)),this.authStateStore=he(r,n),this.connection=new Ol(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=jo(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}ou.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,au(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,au(n))})}dbForConnection(){let e=this;return{get config(){return e.config},get runtimeSource(){return e.runtimeSource},get isShuttingDown(){return e.shutdownPromise!==null},markUnauthenticated:e=>this.markUnauthenticated(e),renewsCredential:e=>(gd.get(this)??0)>0||e===`expired`&&this.localFirstRefreshOwned,clearAuthError:()=>this.authStateStore.clearError(),onMutationError:e=>this.handleMutationError(e),enableAuthenticatedInspectorLocalReads:e=>this.#t(e),clearAuthenticatedInspectorLocalReads:()=>this.#n()}}#t(e){this.config.runtimeSources?.inspectorHostPhysicalDbName===e&&(this.#e=e)}#n(){this.#e=null}async inspectorAttachmentOptions(e,t){return this.getClient(e._schema),await this.connection.ensureReady(`runtime`),au(this.#e?o(t):t&&{...t})??{}}async allFromInspectorAttachment(e,t){return this.allInternal(e,await this.inspectorAttachmentOptions(e,t))}subscribeFromInspectorAttachment(e,t,n){let r=null,i=!1,a=this.inspectorAttachmentOptions(e,n).then(n=>{if(!i)return r=this.subscribeDelta(e,t,n),r.ready}),o=(()=>{i=!0,r?.()});return Object.defineProperty(o,`ready`,{value:a}),o}initLocalFirstAuth(e,t,n=!0){this._localFirstSecret=e,this.localFirstRefreshOwned=n,n&&this.scheduleLocalFirstRefresh(t)}scheduleLocalFirstRefresh(e){this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer);let t=e*800;this.localFirstRefreshTimer=setTimeout(()=>{this.localFirstRenewals.reset(),this.refreshLocalFirstToken()},t)}refreshLocalFirstToken(){if(!(!this._localFirstSecret||this.shutdownPromise))try{let e=3600,t=this.mintLocalFirstToken(this._localFirstSecret,H(this.config),e),n=Ae(Me(t)??{},`local-first`);if(!n)throw Error(`Minted local-first token is missing its reserved session identity`);this.applyAuthUpdate(t,n),this.scheduleLocalFirstRefresh(e)}catch(e){console.error(`Failed to refresh local-first token:`,e)}}mintLocalFirstToken(e,t,n){return this.runtimeSource.mintLocalFirstToken({secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))})}markUnauthenticated(e){try{this.authStateStore.markUnauthenticated(e)}finally{e===`expired`&&this.localFirstRefreshOwned&&this.renewExpiredLocalFirstToken()}}renewExpiredLocalFirstToken(){let e=this.localFirstRenewals.next();if(e===0){this.refreshLocalFirstToken();return}this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer),this.localFirstRefreshTimer=setTimeout(()=>this.refreshLocalFirstToken(),e)}publishAuthStateWithInternalSession(e,t){d(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=A(this.config);return!(r!==n||i!==void 0||JSON.stringify(a)!==JSON.stringify(t))&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateJwtToken(n,t)?!1:(this.connection.updateAuth({mode:`bearer`,jwtToken:n,trustedReservedSession:t}),this.publishAuthUpdate(n,t),!0)}publishAuthUpdate(e,t){let n={...this.config,jwtToken:e,cookieSession:void 0};l(n,t);let r=rt(n);this.config.jwtToken=e,this.config.cookieSession=void 0,l(this.config,t),this.publishAuthStateWithInternalSession(r,()=>{this.authStateStore.applyJwtToken(e,t)})}applyCookieSessionUpdate(e){this.runtimeSource.assertAuthUpdateAllowed();let t=e??void 0,n=this.config.cookieSession,r=this.config.jwtToken,i=A(this.config),a=JSON.stringify(n)!==JSON.stringify(t);if(!(r!==void 0||a||i!==void 0)&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateCookieSession(t))return!1;this.connection.updateAuth({mode:`cookie`,cookieSession:t});let o=rt({...this.config,jwtToken:void 0,cookieSession:t});return this.config.jwtToken=void 0,this.config.cookieSession=t,l(this.config,void 0),this.publishAuthStateWithInternalSession(o,()=>{this.authStateStore.applyCookieSession(t)}),!0}static create(t,n){return new e(t,n)}static async createWithDirectConnection(t,n){let r=new e(t,n);return await r.connection.start(),r}static async createWithBrowserWorker(t,n,r){let i=new e(t,n),a=new Kl(i.dbForConnection(),r);return i.connection=a,await a.start(),i}getClient(e){return this.assertOpen(),this.connection.getClient(e)}getCurrentClient(){return this.connection.getCurrentClient()}currentRuntime(){return this.getCurrentClient()?.getRuntime()??null}async prefetchRuntimeQueries(e,t){let n=this.getClient(e);await this.ensureReady(`server`),await Promise.all(t.map(e=>n.query(e,{tier:`remote`})))}async ensureReady(e,t){await this.connection.ensureReady(e,t??this.shutdownAbort.signal),this.assertOpen()}wrapWriteWait(e){return bl(this),g(e,async e=>{this.drain||await this.ensureReady(e===`global`?`upload`:`runtime`)})}getAccessContext(){return null}handleMutationError(e,t=!1){if(this.successor)return this.successor.handleMutationError(e,t);if(this.mutationErrorListeners.size===0){t||console.error(`Unhandled Jazz mutation error`,e),this.pendingMutationErrorEvents.push(e);return}for(let t of this.mutationErrorListeners)t(e)}async refreshAccountAuth(e){return this.refreshOwnAccountAuth(e)}async refreshOwnAccountAuth(e){$o(this.config);let t=at(this);if(e.id!==this.config.accountId||Xo(e)!==this.config.accountRegistryAuthority||e.identity.issuer!==t?.issuer||e.identity.subject!==t?.user_id)throw Error(`Account context mismatch`);try{let t=await Yo(e,Xo(e),{fresh:!0});if(this.shutdownAbort.signal.aborted)throw Error(`Account context closed`);let n=e.identity.issuer===`urn:jazz:local-first`?Ae(Me(t)??{},`local-first`):void 0;return this.authStateStore.validateJwtToken(t,n??void 0)?(this.connection.refreshAccountAuth(t,n??void 0),this.publishAuthUpdate(t,n??void 0),t):t}catch(e){throw this.markUnauthenticated(`invalid`),e}}updateAuthToken(e){this.applyAuthUpdate(e)}updateCookieSession(e){this.applyCookieSessionUpdate(e)}getAuthState(){return this.authStateStore.getState()}getLocalFirstIdentityProof(e){if(!this._localFirstSecret)return null;let t=e?.ttlSeconds??60,n=e?.audience??H(this.config);return this.mintLocalFirstToken(this._localFirstSecret,n,t)}onOwnAuthChanged(e){return this.authStateStore.onChange(t=>e(t))}onAuthChanged(e){return this.registerMovable(t=>t.authStateStore.onChange(t=>{e(t)}))}registerMovable(e,t=!1){let n=e(this),r=!1,i={move:i=>{r||(n(),n=t?e(this):i.registerMovable(e))}};return this.movable.add(i),()=>{r||(r=!0,this.movable.delete(i),n())}}onMutationError(e){if(this.replaced)throw this.replaced;return this.registerMovable(t=>{for(t.mutationErrorListeners.add(e);t.pendingMutationErrorEvents.length>0;)e(t.pendingMutationErrorEvents.shift());return()=>{t.mutationErrorListeners.delete(e)}})}textAnchors(){return this.runtimeSource.textAnchors()}getSyncStatus(){let e=this.connection.syncStatus();return this.syncStatusSnapshot&&fs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||fs(n,t)||(t=n,e(n))};return this.registerMovable(e=>{let t=e.syncStatusChangeRegistration(n);return e.successor&&n(e.getSyncStatus()),t},!0)}syncStatusChangeRegistration(e){return this.onSyncStatusChangeHere(e)}onSyncStatusChangeHere(e){let t=new AbortController,n=()=>t.abort();this.shutdownAbort.signal.addEventListener(`abort`,n,{once:!0}),t.signal.addEventListener(`abort`,()=>this.shutdownAbort.signal.removeEventListener(`abort`,n),{once:!0});let r=this.getSyncStatus();return this.connection.onSyncStatusChange(()=>{let t=this.getSyncStatus();t!==r&&(r=t,e(t))},t.signal),n}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;de(t),this.assertOpen(),n?.throwIfAborted();let r=new AbortController,i=()=>r.abort(n.reason);n?.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort(Error(`Db was shut down`));this.shutdownAbort.signal.addEventListener(`abort`,a,{once:!0});let o=t===void 0?void 0:setTimeout(()=>r.abort(new O(`global`,t)),t);try{await this.waitForUpstreamSync(r.signal)}finally{o!==void 0&&clearTimeout(o),n?.removeEventListener(`abort`,i),this.shutdownAbort.signal.removeEventListener(`abort`,a)}}waitForUpstreamSync(e){return this.connection.waitForSync(e)}getConfig(){let{browserWorkerPort:e,browserWorkerSession:t,...n}=this.config.runtimeSources??{};return structuredClone({...this.config,runtimeSources:Object.keys(n).length>0?n:void 0})}setDevMode(e){this.config.devMode=e}async disconnect(){if(this.shutdownPromise)throw Error(`Cannot disconnect a Db that is shutting down.`);this.offlineRequested=!0,await this.connection.disconnect()}async reconnect(){if(this.shutdownPromise&&!this.cancelSyncShutdown)throw Error(`Cannot reconnect a Db that is shutting down.`);this.offlineRequested=!1,await this.connection.reconnect()}getActiveQuerySubscriptions(){return Array.from(this.activeQuerySubscriptionTraces.values()).filter(e=>e.visibility===`public`).map(({visibility:e,...t})=>_u(t))}onActiveQuerySubscriptionsChange(e){return this.registerMovable(t=>(t.activeQuerySubscriptionTraceListeners.add(e),e(t.getActiveQuerySubscriptions()),()=>{t.activeQuerySubscriptionTraceListeners.delete(e)}))}getRuntimeSchema(){return this.connection.getRuntimeSchema()}openInspectorControlPort(e){return this.connection.openInspectorControlPort(e)}insert(e,t,n){J(e);let r=this.getClient(e._schema),i=n?.id,a=Cu(`Insert`,e._columnTransforms?Gu(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!Ic(r)?.pending;s&&!i&&(i=Ju());let c=s?Yu(e,i,a):void 0,l=q(r,()=>r.insert(e._table,a,fu(e._schema,e._table,i?{...n,id:i}:n),o?.writeSession,o?.attribution));return this.wrapWriteWait(l instanceof Promise?new E(c,l.then(e=>e.txId),r):l.mapValue(t=>c===void 0?Hu(e,Nc(t,e._schema,e._table)):c))}async insertStreaming(e,t,n){J(e);let r=this.getClient(e._schema),{column:i,source:a,values:o}=Xu(e,t);Wu(e,o),bl(this);let s=n?.id;return q(r,async()=>{let t=Cu(`Insert`,Gu(e,o),e._schema,e._table),c=this.getAccessContext(),l=Qu(e,o);return r.insertStreaming(e._table,t,i,a,fu(e._schema,e._table,l?{...n,...s?{id:s}:{},branch:l}:s?{...n,id:s}:n),c?.writeSession,c?.attribution)})}async updateStreaming(e,t,n,r){J(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=Xu(e,n);Wu(e,s),bl(this);let c=this.getAccessContext();return q(i,async()=>{let n=Cu(`Update`,Gu(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,pu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}async upsertStreaming(e,t,n,r){J(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=Xu(e,n);Wu(e,s),bl(this);let c=this.getAccessContext();return q(i,async()=>{let n=Cu(`Upsert`,Gu(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,pu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){J(e);let i=this.getClient(e._schema),a=Cu(`Restore`,e._columnTransforms?Gu(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=Ic(i)?.pending?Yu(e,t,a):void 0,c=q(i,()=>i.restore(e._table,t,a,fu(e._schema,e._table,r),o?.writeSession,o?.attribution));return this.wrapWriteWait(c instanceof Promise?new E(s,c.then(e=>e.txId),i):c.mapValue(t=>Hu(e,Nc(t,e._schema,e._table))))}upsert(e,t,n,r){return J(e),this.prepareMutation(e,t,n,`Upsert`,r)}prepareMutation(e,t,n,r,i,a){let o=this.getClient(e._schema);Wu(e,n),Ic(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=pu(e._schema,e._table,i),l=q(o,()=>{let i=n=>{let i=Cu(r,n,e._schema,e._table);return a?a(i):r===`Upsert`?o.upsert(e._table,t,i,c,s?.writeSession,s?.attribution):o.update(e._table,t,i,c,s?.writeSession,s?.attribution)},l=Gu(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Bc(n)!==`not_observed`)throw n;return qu(o,e,t,s?.readSession,c?.branch).then(()=>{try{return i(l)}catch(t){throw Bc(t)===`not_observed`?Uc(`Update`,e._table):t}})}});return this.wrapWriteWait(l instanceof Promise?new Le(l.then(e=>e.txId),o):l)}update(e,t,n,r){J(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Ou(e,n,r);r=ku(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,pu(e._schema,e._table,r),s?.writeSession,s?.attribution)):this.prepareMutation(e,t,n,`Update`,r)}delete(e,t,n){J(e);let r=this.getClient(e._schema),i=this.getAccessContext(),a=q(r,()=>r.delete(e._table,t,pu(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Le(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=Su(`Insert`,e,t),i=this.getAccessContext();return n.requestInsertPermissionAdvice(e._table,r,i?.writeSession)}explainReadClauses(e,t){let n=this.getAccessContext()?.readSession;if(!n)throw Error(`explain needs a Db acting as a user`);return this.getClient(e._schema).explainReadClauses(e._table,t,n)}async canRead(e,t){let n=this.getClient(e._schema),r=this.getAccessContext();return n.requestReadPermissionAdvice(e._table,t,r?.readSession)}async canUpdate(e,t,n){let r=this.getClient(e._schema),i=Su(`Update`,e,n),a=this.getAccessContext();return r.requestUpdatePermissionAdvice(e._table,t,i,a?.writeSession)}async canDelete(e,t){let n=this.getClient(e._schema),r=this.getAccessContext();return n.requestDeletePermissionAdvice(e._table,t,r?.writeSession)}createTransaction(e,t){this.assertOpen(),bl(this);let n=this.getAccessContext(),r=this.getCurrentClient();if(e===`serializable`&&!r)throw Error(`Cannot begin a serializable transaction before the JazzClient has been created. Run a query or mutation first.`);return nd.createWithAdmission(e,e=>this.getClient(e),n,r??void 0,t)}async captureSnapshot(){this.assertOpen();let e=this.getCurrentClient();if(!e)throw Error(`Cannot capture a snapshot before a schema is attached. Run a query or mutation first.`);return q(e,()=>e.captureSnapshot())}beginTransaction(){return this.createTransaction(`mergeable`)}beginSerializableTransaction(){return this.createTransaction(`serializable`)}transaction(e){let t=this.beginTransaction();return td(t,e,()=>Vu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return td(t,e,()=>Vu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await Ql(this,e)}isLocalFirst(){return!Zl(this)}async deleteClientStorage(){await this.connection.deleteClientStorage()}async storePendingUploads(){return await this.connection.storePendingUploads().catch(()=>void 0)??this.getSyncStatus().pendingUploads}isUsable(){return!this.shutdownPromise&&!this.replaced&&this.connection.isUsable()}async logout(e={}){e.wipeData&&await this.deleteClientStorage(),await this.shutdown()}async all(e,t){try{return await this.allInternal(e,au(t))}catch(n){if(this.successor&&_d(n))return this.current().all(e,t);throw n}}async allInternal(e,t){let n=this.getClient(e._schema),r=Ic(n);r?.pending&&await r.drain();let a=i(this.config,{tier:t?.tier,firstLoadRemoteWaitMs:t?.firstLoadRemoteWaitMs}).firstLoadRemoteWaitMs===void 0?null:this.connection.initialExplicitOfflineState();a&&await a;let o=e._build(),s=Vs(JSON.parse(o)),c=vu(e._schema,s.table),l=vc(c,s),u=Ru(e,s,l),d=yu(e._schema,s.table,t),f=_c(o,c,u.physical),p=hu(s),m=this.getAccessContext(),h=i(this.config,d).tier;await this.ensureReady(h===`remote`?`server`:`runtime`);let g=m||p?await n.queryInternal(f,d,m?.readSession):await n.queryInternal(f,d);return u.computedState?zu(e,s,l,u,g,e=>n.queryInternal(_c(o,c,e),d,m?.readSession)):g.map(u.transform)}async one(e,t){return(await this.all(mu(e),t))[0]??null}subscribe(e,t,n,r){let{onUpdate:i,onError:a}=typeof t==`function`?{onUpdate:t,onError:void 0}:t,o={onDelta:e=>{if(e.all===void 0)throw Error(`Jazz subscription update is missing its materialized result.`);let t=new Map;for(let n of e.delta)n.kind===ue.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,au(n),r)}subscribeDelta(e,t,n,r){if(this.replaced)throw this.replaced;let{onDelta:i,onError:a}=typeof t==`function`?{onDelta:t,onError:void 0}:t,o,s=!0,c=this.registerMovable(t=>{let c=!s;s=!1;let l=t.subscribeDeltaHere(e,{onDelta:e=>{if(c){c=!1,i({delta:e.delta,all:e.all??[],reset:!0});return}i(e)},...a===void 0?{}:{onError:a}},n,r);return o??=l.ready,l}),l=(()=>c());return o&&Object.defineProperty(l,`ready`,{value:o}),l}subscribeDeltaHere(e,t,n,r){let{onDelta:i,onError:a}=t,o=this.getClient(e._schema),c=this.connection.initialExplicitOfflineState(),l=new u,d=e._build(),f=Vs(JSON.parse(d)),p=vu(e._schema,f.table),m=vc(p,f),h=Ru(e,f,m),g=_c(d,p,h.physical),_=c===null,v=[],y=yu(e._schema,f.table,n);y.splices&&(bu(p,m,e,y.splices),xu(f,h.physical,y.splices));let b=this.getAccessContext()?.readSession??r,x=null,S=!1,C=!1,w=new AbortController,T=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},E=e=>{if(!a){console.error(`Unhandled Jazz subscription error`,e);return}try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},D=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||C||(e.terminalDelivered=!0,C=!0,_=!1,v.length=0,x===e&&(x=null),T(e),e.predecessor!==null&&(T(e.predecessor),e.predecessor=null),w.abort(),this.liveSubscriptionEnders.delete(se),this.unregisterActiveQuerySubscriptionTrace(ie),l.clear(),E(t))},O=(e,t)=>{S||C||x!==e||e.terminalDelivered||(e.terminalError??=s(t),D(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return x=t,t},te=e=>{if(!(S||C||x===null)){if(!_){v.push(e);return}try{i(e)}catch(e){let t=x;t!==null&&O(t,e)}}},ne=t=>{if(!(S||C||x===null))try{te(l.handleDelta(t,h.transform))}catch(t){if(!(t instanceof qc)||!h.computedState||h.computedState.version===h.version)throw t;h=Ru(e,f,m,h.computedState),y.splices&&xu(f,h.physical,y.splices),g=_c(d,p,h.physical),T(x);let n=ee();l.clear(),v.length=0,this.unregisterActiveQuerySubscriptionTrace(ie),ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),queueMicrotask(()=>{this.shutdownPromise||re(n)})}},re=(e,t=y)=>{if(S||x!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(g,{onUpdate:t=>{if(!(S||x!==e||e.terminalError!==null)){if(e.installing){n.push(t);return}try{ne(t)}catch(t){O(e,t)}}},onError:t=>{O(e,t)}},t,b)}catch(t){return e.installing=!1,O(e,t),null}if(e.installing=!1,S||x!==e||e.retired)return T(e),null;if(e.terminalError!==null)return D(e),null;try{for(let t of n){if(x!==e||e.terminalError!==null)break;ne(t)}}catch(t){return O(e,t),null}return S||x!==e||e.retired?null:e},ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),ae=()=>{S||(S=!0,this.liveSubscriptionEnders.delete(se),_=!1,v.length=0,w.abort(),this.unregisterActiveQuerySubscriptionTrace(ie),x!==null&&(T(x),x.predecessor!==null&&(T(x.predecessor),x.predecessor=null)),x=null,l.clear())},k=c?.then(()=>{if(!(S||C||x===null||this.shutdownPromise)){_=!0;for(let e of v.splice(0)){if(S||C||x===null)return;te(e)}}}).catch(e=>{if(!(S||C||x===null||this.shutdownPromise))throw O(x,e),e});k&&k.catch(()=>void 0);let oe=ee(),se=e=>{x!==null&&O(x,e)};this.liveSubscriptionEnders.add(se);let ce=y.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(ce)?this.ensureReady(ce,w.signal).then(()=>re(oe)).catch(e=>{S||w.signal.aborted||this.shutdownPromise||O(oe,e)}):re(oe);let le=ae;return k&&Object.defineProperty(le,`ready`,{value:k}),le}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new $l(e);this.replaced=t;for(let e of Array.from(this.liveSubscriptionEnders))e(t);this.liveSubscriptionEnders.clear()}adoptSuccessor(t){if(this.successor)throw Error(`This Db already has a successor`);let n=this.currentRuntime();this.successor=t,n?.endUnsentReads?.();let r=this.letStreamsFinish(),i=!0,a=new Set,o=this.shutdown({waitForSync:!0}).finally(()=>{i=!1;for(let e of Array.from(a))e()});o.catch(()=>{}),this.drain={done:o,endStreamWait:()=>r.abort(),abort:()=>{i&&this.abortGracefulShutdown()}};let s=null,c=()=>{let n=t.getSyncStatus();if(!i)return n;let r=e.prototype.getSyncStatus.call(this),a={link:n.link,pendingUploads:n.pendingUploads+r.pendingUploads,oldestPendingAt:n.oldestPendingAt===null||r.oldestPendingAt===null?n.oldestPendingAt??r.oldestPendingAt:Math.min(n.oldestPendingAt,r.oldestPendingAt),rejected:n.rejected+r.rejected,lastError:r.lastError&&(!n.lastError||r.lastError.at>n.lastError.at)?r.lastError:n.lastError,synced:n.synced&&r.pendingUploads===0};return s&&fs(a,s)?s:s=a},l={getSyncStatus:c,syncStatusChangeRegistration:e=>{let n=c(),r=()=>{let t=c();t!==n&&(n=t,e(t))},o=t.onSyncStatusChange(r),s=i?this.onSyncStatusChangeHere(r):()=>{};return a.add(r),()=>{o(),s(),a.delete(r)}},waitForSync:async(e={})=>{await Promise.all([t.waitForSync(e),i?this.waitForOwnSync(e,o):void 0])},disconnect:async()=>{await Promise.all([t.disconnect(),i?this.connection.disconnect():void 0])},reconnect:async()=>{await Promise.all([t.reconnect(),i?this.connection.reconnect():void 0])}};for(let e of su)Object.defineProperty(this,e,{configurable:!0,value:l[e]??((...n)=>t[e](...n))});Object.defineProperty(this,`syncStatusChangeRegistration`,{configurable:!0,value:l.syncStatusChangeRegistration}),(this.offlineRequested??this.connection.isExplicitlyOffline())&&t.disconnect().catch(()=>{});for(let e of this.pendingMutationErrorEvents.splice(0))t.handleMutationError(e,!0);for(let e of Array.from(this.movable))e.move(t);this.movable.clear()}async waitForOwnSync(e,t){let{timeoutMs:n,signal:r}=e;de(n),r?.throwIfAborted();let i=new AbortController,a=()=>i.abort(r.reason);r?.addEventListener(`abort`,a,{once:!0});let o=n===void 0?void 0:setTimeout(()=>i.abort(new O(`global`,n)),n);try{await Promise.race([this.connection.waitForSync(i.signal),t])}finally{o!==void 0&&clearTimeout(o),r?.removeEventListener(`abort`,a)}}offlineRequested;drain=null;streamsMayFinish=null;letStreamsFinish(){return this.streamsMayFinish?.abort(),this.streamsMayFinish=new AbortController,this.streamsMayFinish}async stopOwnRuntime(t={}){let n=this.drain;if(!n)return this.shutdown(t);n.endStreamWait(),t.waitForSync||n.abort(),await n.done.catch(()=>{}),await e.prototype.shutdown.call(this)}current(){return this.successor?.current()??this}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let t,n=new Promise(e=>{t=e});return this.shutdownPromise=n,t(this.runShutdown(e)),n}cancelSyncShutdown;abortGracefulShutdown(){this.cancelSyncShutdown?.()}assertOpen(){if(this.replaced)throw this.replaced;if(this.shutdownPromise)throw Error(`Cannot operate on a Db that is shutting down or closed.`)}shutdownListeners=new Set;onShutdown(e){return this.shutdownPromise?e():this.shutdownListeners.add(e),()=>this.shutdownListeners.delete(e)}async runShutdown(e){if(e.waitForSync){let e=new AbortController,t=new Promise((t,n)=>{this.cancelSyncShutdown=()=>{e.abort(),n(Error(`Graceful shutdown cancelled`))}});try{await Promise.race([this.runtimeSource.waitForPendingWrites?.(e.signal)??this.connection.waitForPendingWrites({inFlightStreams:this.streamsMayFinish?.signal}),t])}catch(t){throw e.abort(),this.shutdownPromise=null,new Uo(t)}finally{this.cancelSyncShutdown=void 0}}for(let e of this.shutdownListeners)try{e()}catch(e){console.error(`Context cleanup failed`,e)}this.shutdownListeners.clear(),this.shutdownAbort.abort(),this.localFirstRefreshTimer&&=(clearTimeout(this.localFirstRefreshTimer),null),this.clearActiveQuerySubscriptionTraces(),this.mutationErrorListeners.clear();try{await this.connection.shutdown()}finally{await this.runtimeSource.shutdown()}}notifyActiveQuerySubscriptionTraceListeners(){if(this.activeQuerySubscriptionTraceListeners.size===0)return;let e=this.getActiveQuerySubscriptions();for(let t of this.activeQuerySubscriptionTraceListeners)t(e)}registerActiveQuerySubscriptionTrace(e,t,n){if(!this.config.devMode)return null;let r=i(this.config,n);if(r.tier===`local-only`)return null;let a=this.parseRuntimeQueryTracePayload(e),o=`sub-${this.nextActiveQuerySubscriptionTraceId++}`;return this.activeQuerySubscriptionTraces.set(o,{id:o,query:e,table:a.table,branches:a.branches,tier:r.tier,createdAt:new Date().toISOString(),stack:gu(Error().stack),visibility:r.visibility??`public`}),this.notifyActiveQuerySubscriptionTraceListeners(),o}unregisterActiveQuerySubscriptionTrace(e){e&&this.activeQuerySubscriptionTraces.delete(e)&&this.notifyActiveQuerySubscriptionTraceListeners()}clearActiveQuerySubscriptionTraces(){this.activeQuerySubscriptionTraces.size!==0&&(this.activeQuerySubscriptionTraces.clear(),this.notifyActiveQuerySubscriptionTraceListeners())}parseRuntimeQueryTracePayload(e){try{let t=JSON.parse(e);return{table:typeof t.table==`string`?t.table:`unknown`,branches:Array.isArray(t.branches)?t.branches.filter(e=>typeof e==`string`):[]}}catch{return{table:`unknown`,branches:[]}}}};function id(){let e=y(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function ad(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function od(e,t){if(!t.supportsBrowserWorker||!hd()||tu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),sd.set(n,cd(e)),n}var sd=new WeakMap;function cd(e){try{let t=e.runtimeSources;return JSON.stringify([iu(e),zi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function ld(e,t){let n=sd.get(e);return n!==void 0&&n===cd(t)}async function ud(e){if(!(!e||fd.has(e))){fd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function dd(e,t,n){let r=n;try{return await pd(e,t,()=>(r??=od(e,t),r))}finally{ud(r)}}var fd=new WeakSet;async function pd(e,t,n){if($o(e),md(e),e.secret&&e.cookieSession)throw Error(`DbConfig error: secret and cookieSession are mutually exclusive`);if(e.secret&&e.jwtToken)throw Error(`DbConfig error: secret and jwtToken are mutually exclusive`);if(e.jwtToken&&e.cookieSession)throw Error(`DbConfig error: jwtToken and cookieSession are mutually exclusive`);let r=e.secret?se(e.secret):null,i={...e};l(i,A(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...u}=e,d=r;if(d){let n=d;if(!e.jwtToken){let r=t.mintLocalFirstToken(ad(n,H(e),3600)),a=Ae(Me(r)??{},`local-first`);i={...u,jwtToken:r},l(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=id(),r=t.mintAnonymousToken(ad(n,H(e),3600)),a=Ae(Me(r)??{},`anonymous`);i={...u,jwtToken:r},l(i,a)}es(e,i),t.admitConfig(i);let f=tu(i.driver),p=t.supportsBrowserWorker&&hd()&&f.type===`persistent`,m=a&&p&&ld(a,i)?a:void 0;m?fd.add(m):a&&await ud(a);let h=p?await rd.createWithBrowserWorker(i,t,m):await rd.createWithDirectConnection(i,t);return d&&h.initLocalFirstAuth(d,3600,!e.jwtToken),h}function md(e){if(Object.hasOwn(e,`backendSecret`))throw Error(`DbConfig does not accept backendSecret. Run Jazz in your backend with createJazz() from jazz-tools/backend instead.`)}function hd(){return typeof window<`u`&&typeof Worker<`u`}var gd=new WeakMap;function _d(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof eu)return!0;return!1}var vd={napi:`b84e0904a2a57ac95066df0640d867441da3c2c06464eb57123a3b9824623f57`,wasm:`d7ba77fde7fc70f887022c32e739c08358627d9b32911fddde3ebbabf1767191`};function yd(e,t,n=[]){let r=vd[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw Error(`Jazz ${t} artifact is stale or incompatible: missing nativeArtifactFingerprint (expected ${r}). In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`);let i=e.nativeArtifactFingerprint();if(i!==r)throw Error(`Jazz ${t} artifact ABI mismatch: expected ${r}, got ${String(i)}. In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`);for(let r of n)if(typeof e[r]!=`function`)throw Error(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${r}.`)}var bd=class extends Error{},xd=class extends Error{},Sd=new Set(`\\.+*?()|[]{}^$#&-~`),Cd=new Set(`imsUuRx`),wd=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Td(e){return Sd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Ed=class{pattern;chars;index=0;flags={multiLine:!1,dotAll:!1,swapGreed:!1};fancy=!1;caseInsensitive=!1;captures=0;names=new Set;unsupported=[];fancyInvalid=[];bellOutsideClass=!1;constructor(e){this.pattern=e,this.chars=[...e]}parse(){let e;try{e=this.parseAlternation(0),this.eof()||this.fail(`unopened group`)}catch(e){throw e instanceof bd&&this.fancy?new xd(e.message):e}return!this.fancy&&this.bellOutsideClass&&this.fail("`\\a` is not supported"),{node:e,fancy:this.fancy,caseInsensitive:this.caseInsensitive,captures:this.captures,unsupported:this.unsupported,fancyInvalid:this.fancyInvalid}}eof(){return this.index>=this.chars.length}char(){return this.chars[this.index]}peek(e=1){return this.chars[this.index+e]}startsWith(e){return this.chars.slice(this.index,this.index+e.length).join(``)===e}fail(e){throw new bd(e)}parseAlternation(e){let t=[this.parseConcat(e)];for(;!this.eof()&&this.char()===`|`;)this.index++,t.push(this.parseConcat(e));return t.length===1?t[0]:{kind:`alternation`,items:t}}parseConcat(e){let t=[],n=0;for(;!this.eof();){let r=this.char();if(r===`|`||r===`)`)break;if(r===`?`||r===`*`||r===`+`||r===`{`?(n++,n===2&&r===`+`?this.unsupported.push(`possessive quantifiers`):n===2&&r===`{`?this.unsupported.push(`a counted repetition right after another quantifier`):n>=2&&this.fancyInvalid.push(`a quantifier right after another quantifier`)):n=0,r===`(`)t.push(this.parseGroup(e));else if(r===`[`)t.push({kind:`class`,item:this.parseBracketed()});else if(r===`?`||r===`*`||r===`+`){this.index++;let[e,n]=r===`?`?[0,1]:r===`*`?[0,1/0]:[1,1/0],i=!0;!this.eof()&&this.char()===`?`&&(i=!1,this.index++),this.repeatLast(t,e,n,i)}else r===`{`?this.parseCountedRepetition(t):t.push(this.parsePrimitive())}return t.length===1?t[0]:{kind:`concat`,items:t}}repeatLast(e,t,n,r){let i=e.pop();(i===void 0||i.kind===`flags`)&&this.fail(`repetition operator missing expression`),i.kind===`look`&&this.fancyInvalid.push(`a quantifier on a lookaround`),e.push({kind:`repeat`,body:i,min:t,max:n,greedy:r!==this.flags.swapGreed})}skipWhitespaceInRepetition(){let e=!1;for(;!this.eof()&&/\p{White_Space}/u.test(this.char());)this.index++,e=!0;e&&this.unsupported.push(`spaces inside a counted repetition`)}parseDecimal(){this.skipWhitespaceInRepetition();let e=``;for(;!this.eof()&&/[0-9]/.test(this.char());)e+=this.chars[this.index++];if(this.skipWhitespaceInRepetition(),e===``)return;let t=Number(e);return t>4294967295&&this.fail(`repetition count is too large`),t}parseCountedRepetition(e){let t=e[e.length-1];(t===void 0||t.kind===`flags`)&&this.fail(`repetition operator missing expression`),this.index++,this.eof()&&this.fail(`unclosed counted repetition`);let n=this.parseDecimal();this.eof()&&this.fail(`unclosed counted repetition`);let r;if(this.char()===`,`)if(this.index++,this.eof()&&this.fail(`unclosed counted repetition`),this.char()!==`}`){let e=this.parseDecimal();(n===void 0||e===void 0)&&this.fail(`repetition count is empty`),r=e}else n===void 0&&this.fail(`repetition count is empty`),r=1/0;else n===void 0&&this.fail(`repetition count is empty`),r=n;(this.eof()||this.char()!==`}`)&&this.fail(`unclosed counted repetition`),this.index++;let i=!0;!this.eof()&&this.char()===`?`&&(i=!1,this.index++),n>r&&this.fail(`invalid repetition range`),this.repeatLast(e,n,r,i)}parseGroup(e){let t=this.index===0;this.index++;for(let t of[`=`,`!`,`<=`,`<!`])if(this.startsWith(`?${t}`))return this.fancy=!0,this.index+=t.length+1,{kind:`look`,op:t,body:this.parseGroupBody(e)};if(this.startsWith(`?P<`)||this.startsWith(`?<`))return this.index+=this.startsWith(`?P<`)?3:2,this.captures++,this.parseCaptureName(),{kind:`group`,capture:!0,body:this.parseGroupBody(e)};if(!this.eof()&&this.char()===`?`){this.index++,this.eof()&&this.fail(`unclosed group`);let n=this.flags,r=this.parseFlags(),i=this.char();if(this.index++,i===`)`)return r!==void 0&&(r&&t?this.caseInsensitive=!0:this.unsupported.push("`(?i)` anywhere but at the start of the pattern")),{kind:`flags`};r!==void 0&&this.unsupported.push("`(?i)` anywhere but at the start of the pattern");let a=this.parseGroupBody(e);return this.flags=n,{kind:`group`,capture:!1,body:a}}return this.captures++,{kind:`group`,capture:!0,body:this.parseGroupBody(e)}}parseGroupBody(e){let t=this.flags,n=this.parseAlternation(e+1);return this.eof()&&this.fail(`unclosed group`),this.index++,this.flags=t,n}parseCaptureName(){this.eof()&&this.fail(`unexpected end of group name`);let e=``;for(;!this.eof()&&this.char()!==`>`;){let t=this.char();(e===``?t===`_`||/\p{Alphabetic}/u.test(t):t===`_`||t===`.`||t===`[`||t===`]`||/[\p{Alphabetic}\p{N}]/u.test(t))||this.fail(`invalid group name`),e+=t,this.index++}this.eof()&&this.fail(`unexpected end of group name`),this.index++,e===``&&this.fail(`empty group name`),this.names.has(e)&&this.fail(`duplicate group name "${e}"`),this.names.add(e)}parseFlags(){let e=new Set,t=!1,n=!1,r,i={...this.flags};for(;this.char()!==`:`&&this.char()!==`)`;){let a=this.char();if(a===`-`)t&&this.fail(`repeated negation in flags`),t=!0,n=!0;else{n=!1,Cd.has(a)||this.fail(`unrecognized flag "${a}"`),e.has(a)&&this.fail(`duplicate flag "${a}"`),e.add(a);let o=!t;a===`i`?r=o:a===`m`?i.multiLine=o:a===`s`?i.dotAll=o:a===`U`?i.swapGreed=o:a===`x`?this.unsupported.push("the `x` flag"):a===`R`?this.unsupported.push("the `R` flag"):a===`u`&&!o&&this.unsupported.push("turning off the `u` flag")}this.index++,this.eof()&&this.fail(`unexpected end of flags`)}return n&&this.fail(`dangling flag negation`),e.size===0&&this.char()===`)`&&this.fail(`repetition operator missing expression`),this.flags=i,r}parsePrimitive(){let e=this.char();return e===`\\`?this.parseEscape(!1):(this.index++,e===`.`?{kind:`dot`,dotAll:this.flags.dotAll}:e===`^`?this.assertion(`start`):e===`$`?this.assertion(`end`):{kind:`literal`,char:e})}assertion(e){return{kind:`assertion`,assertion:e,multiLine:this.flags.multiLine}}parseEscape(e){this.index++,this.eof()&&this.fail(`incomplete escape`);let t=this.char();if(/[0-9]/.test(t)){this.fancy=!0;let t=``;for(;!this.eof()&&/[0-9]/.test(this.char());)t+=this.chars[this.index++];return(e||t.startsWith(`0`))&&this.unsupported.push(`\`\\${t}\``),{kind:`backref`,index:Number(t)}}if(t===`x`||t===`u`||t===`U`)return{kind:`literal`,char:this.parseHex(t)};if(t===`p`||t===`P`)return{kind:`class`,item:this.parseUnicodeClass(t===`P`)};if(`dswDSW`.includes(t)){this.index++;let e=t.toLowerCase();return{kind:`class`,item:{kind:`perl`,perl:e,negated:t!==e}}}if(this.index++,Td(t))return{kind:`literal`,char:t};let n={f:`\f`,t:` `,n:`
5
+ `,r:`\r`,v:`\v`};if(n[t]!==void 0)return{kind:`literal`,char:n[t]};if(t===`a`)return e||(this.bellOutsideClass=!0),{kind:`literal`,char:`\x07`};if(t===`c`){let e=this.eof()?void 0:this.char();return(e===void 0||!/[A-Za-z]/.test(e))&&this.fail("invalid `\\c` escape"),this.index++,{kind:`literal`,char:String.fromCharCode(e.charCodeAt(0)%32)}}return e&&`AzbB<>`.includes(t)&&this.fail(`\`\\${t}\` is not allowed in a class`),t===`A`?this.assertion(`startText`):t===`z`?this.assertion(`endText`):t===`B`?this.assertion(`notWordBoundary`):t===`<`?this.assertion(`wordStart`):t===`>`?this.assertion(`wordEnd`):t===`b`?this.assertion(this.parseSpecialWordBoundary()):this.fail(`unrecognized escape \`\\${t}\``)}parseSpecialWordBoundary(){if(this.eof()||this.char()!==`{`)return`wordBoundary`;let e=this.index;if(this.index++,this.eof()&&this.fail(`unexpected end of special word boundary`),!/[A-Za-z-]/.test(this.char()))return this.index=e,`wordBoundary`;let t=``;for(;!this.eof()&&/[A-Za-z-]/.test(this.char());)t+=this.chars[this.index++];return(this.eof()||this.char()!==`}`)&&this.fail(`unclosed special word boundary`),this.index++,{start:`wordStart`,end:`wordEnd`,"start-half":`wordStartHalf`,"end-half":`wordEndHalf`}[t]??this.fail(`unrecognized special word boundary "${t}"`)}parseHex(e){this.index++,this.eof()&&this.fail(`incomplete hex escape`);let t=``;if(this.char()===`{`){for(this.index++;!this.eof()&&this.char()!==`}`;)/[0-9A-Fa-f]/.test(this.char())||this.fail(`invalid hex digit`),t+=this.chars[this.index++];this.eof()&&this.fail(`incomplete hex escape`),this.index++,t===``&&this.fail(`empty hex escape`)}else{let n=e===`x`?2:e===`u`?4:8;for(let e=0;e<n;e++)this.eof()&&this.fail(`incomplete hex escape`),/[0-9A-Fa-f]/.test(this.char())||this.fail(`invalid hex digit`),t+=this.chars[this.index++]}let n=parseInt(t,16);return(t.length>8||n>1114111||n>=55296&&n<=57343)&&this.fail(`invalid Unicode scalar value`),String.fromCodePoint(n)}parseUnicodeClass(e){if(this.index++,this.eof()&&this.fail(`incomplete Unicode class`),this.char()===`{`){this.index++;let t=``;for(;!this.eof()&&this.char()!==`}`;)t+=this.chars[this.index++];this.eof()&&this.fail(`incomplete Unicode class`),this.index++;let n=t.indexOf(`!=`);return n>=0?{kind:`unicode`,name:`${t.slice(0,n)}=${t.slice(n+2)}`,negated:!e}:{kind:`unicode`,name:t.replace(`:`,`=`),negated:e}}let t=this.char();return t===`\\`&&this.fail(`invalid Unicode class`),this.index++,{kind:`unicode`,name:t,negated:e}}parseBracketed(){this.index++,this.eof()&&this.fail(`unclosed class`);let e=!1;this.char()===`^`&&(e=!0,this.index++,this.eof()&&this.fail(`unclosed class`));let t=[];for(;this.char()===`-`;)t.push({kind:`literal`,char:`-`}),this.index++,this.eof()&&this.fail(`unclosed class`);t.length===0&&this.char()===`]`&&(t.push({kind:`literal`,char:`]`}),this.index++,this.eof()&&this.fail(`unclosed class`));let n,r,i=()=>{let e={kind:`union`,items:t};return n===void 0?e:{kind:`op`,op:r,lhs:n,rhs:e}};for(;;){this.eof()&&this.fail(`unclosed class`);let a=this.char();if(a===`[`){let e=this.maybeParseAsciiClass();t.push(e??this.parseBracketed())}else if(a===`]`)return this.index++,{kind:`bracket`,negated:e,set:i()};else (a===`&`||a===`-`||a===`~`)&&this.peek()===a?(n=i(),r=`${a}${a}`,t=[],this.index+=2):t.push(this.parseClassRange())}}maybeParseAsciiClass(){let e=/^\[:(\^?)([^:]*):\]/.exec(this.chars.slice(this.index).join(``));if(!(!e||!wd.has(e[2])))return this.index+=[...e[0]].length,{kind:`ascii`,ascii:e[2],negated:e[1]===`^`}}parseClassItem(){return this.char()===`\\`?this.parseEscape(!0):{kind:`literal`,char:this.chars[this.index++]}}parseClassRange(){let e=this.parseClassItem();if(this.eof()&&this.fail(`unclosed class`),this.char()!==`-`||this.peek()===`]`||this.peek()===`-`)return this.toClassItem(e);this.index++,this.eof()&&this.fail(`unclosed class`);let t=this.parseClassItem();return(e.kind!==`literal`||t.kind!==`literal`)&&this.fail(`class ranges need literal endpoints`),e.char.codePointAt(0)>t.char.codePointAt(0)&&this.fail(`invalid class range`),{kind:`range`,start:e.char,end:t.char}}toClassItem(e){return e.kind===`literal`?{kind:`literal`,char:e.char}:e.kind===`class`?e.item:{kind:`literal`,char:`\0`}}},Dd={alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]],d:[[48,57]],w:[[48,57],[65,90],[95,95],[97,122]],s:[[9,13],[32,32],[160,160],[8195,8195],[8233,8233],[65279,65279]]},Od=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,kd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:Od};function Ad(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function jd(e){return e.map(([e,t])=>{let n=Ad(String.fromCodePoint(e));return e===t?n:`${n}-${Ad(String.fromCodePoint(t))}`}).join(``)}var Md=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Ad(e.char);case`dot`:return e.dotAll?`[^]`:`[^\\n]`;case`assertion`:return this.assertion(e.assertion,e.multiLine);case`class`:return this.item(e.item).atom;case`group`:return`(${e.capture&&this.parsed.fancy?``:`?:`}${this.emit(e.body)})`;case`look`:return`(?${e.op}${this.emit(e.body)})`;case`backref`:if(e.index===0||e.index>this.parsed.captures)throw new xd(`backreference \`\\${e.index}\``);return`\\${e.index}(?:)`;case`repeat`:{let{min:t,max:n}=e,r=n===1/0?t===0?`*`:t===1?`+`:`{${t},}`:t===0&&n===1?`?`:t===n?`{${t}}`:`{${t},${n}}`;return`(?:${this.emit(e.body)})${r}${e.greedy?``:`?`}`}case`concat`:return e.items.map(e=>this.emit(e)).join(``);case`alternation`:return e.items.map(e=>this.emit(e)).join(`|`)}}assertion(e,t){let n=`[${Od}]`;switch(e){case`start`:return t?`(?<![^\\n])`:`^`;case`end`:return t?`(?![^\\n])`:`$`;case`startText`:return`^`;case`endText`:return`$`;case`wordBoundary`:return`(?:(?<=${n})(?!${n})|(?<!${n})(?=${n}))`;case`notWordBoundary`:return`(?:(?<=${n})(?=${n})|(?<!${n})(?!${n}))`;case`wordStart`:return`(?<!${n})(?=${n})`;case`wordEnd`:return`(?<=${n})(?!${n})`;case`wordStartHalf`:return`(?<!${n})`;case`wordEndHalf`:return`(?!${n})`}}item(e){switch(e.kind){case`literal`:{let t=Ad(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Ad(e.start)}-${Ad(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Nd(this.parsed.fancy?kd[e.perl]:jd(Dd[e.perl]),e.negated);case`ascii`:return Nd(jd(Dd[e.ascii]),e.negated);case`unicode`:return Nd(Pd(e.name),e.negated);case`bracket`:{let t=this.set(e.set);return e.negated?t.fragment===void 0?{atom:`(?:(?!${t.atom})[^])`}:{atom:`[^${t.fragment}]`}:t}}}set(e){if(e.kind===`union`){let t=e.items.map(e=>this.item(e));if(t.every(e=>e.fragment!==void 0)){let e=t.map(e=>e.fragment).join(``);return{fragment:e,atom:`[${e}]`}}return{atom:`(?:${t.map(e=>e.atom).join(`|`)})`}}let t=this.set(e.lhs).atom,n=this.set(e.rhs).atom;switch(e.op){case`&&`:return{atom:`(?:(?=${t})${n})`};case`--`:return{atom:`(?:(?!${n})${t})`};case`~~`:return{atom:`(?:(?!${n})${t}|(?!${t})${n})`}}}};function Nd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Pd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new xd(`the Unicode class \`${e}\``)}function Fd(e){try{return new Ed(e).parse(),!0}catch(e){return e instanceof xd}}var Id=new Map,Ld=1024;function Rd(e){let t=Id.get(e);if(t)return t;let n=new Ed(e).parse();if(n.fancyInvalid.length>0)throw new bd(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new xd(n.unsupported[0]);let r=new Md(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),Id.size>=Ld&&Id.clear(),Id.set(e,t),t}function zd(e,t){let n=e.charCodeAt(t)-48,r=e.charCodeAt(t+1)-48;if(!(n<0||n>9||r<0||r>9))return n*10+r}function Bd(e){return e%4==0&&e%100!=0||e%400==0}function Vd(e){if(e.length!==10||e[4]!==`-`||e[7]!==`-`||!/^[0-9]{4}$/.test(e.slice(0,4)))return!1;let t=Number(e.slice(0,4)),n=zd(e,5),r=zd(e,8);return n===void 0||n<1||n>12||r===void 0||r===0?!1:n===2?r<=(Bd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function Hd(e){if(e.length<9||e[2]!==`:`||e[5]!==`:`)return!1;let t=zd(e,0),n=zd(e,3),r=zd(e,6);if(t===void 0||n===void 0||r===void 0||t>23||n>59||r>60)return!1;let i=8;if(e[i]===`.`){i++;let t=i;for(;i<e.length&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i===t)return!1}if(i===e.length)return!1;let a=e[i];if(a===`Z`||a===`z`)return i===e.length-1&&(r!==60||t===23&&n===59);if(a!==`+`&&a!==`-`||e.length-i!==6||e[i+3]!==`:`)return!1;let o=zd(e,i+1),s=zd(e,i+4);if(o===void 0||s===void 0||o>23||s>59)return!1;if(r!==60)return!0;let c=a===`+`?-1:1,l=t+c*o,u=n+c*s;return l+=Math.trunc(u/60),u%=60,u<0&&(u+=60,--l),l=(l+24)%24,l===23&&u===59}function Ud(e){let t=e.search(/[Tt]/);return t<0?!1:Vd(e.slice(0,t))&&Hd(e.slice(t+1))}var Wd=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,Gd=`${Wd}(?:\\.${Wd}){3}`,Y=`[0-9A-Fa-f]{1,4}`,Kd=`(?:${Y}:${Y}|${Gd})`,qd=[`(?:${Y}:){6}${Kd}`,`::(?:${Y}:){5}${Kd}`,`(?:${Y})?::(?:${Y}:){4}${Kd}`,`(?:(?:${Y}:){0,1}${Y})?::(?:${Y}:){3}${Kd}`,`(?:(?:${Y}:){0,2}${Y})?::(?:${Y}:){2}${Kd}`,`(?:(?:${Y}:){0,3}${Y})?::${Y}:${Kd}`,`(?:(?:${Y}:){0,4}${Y})?::${Kd}`,`(?:(?:${Y}:){0,5}${Y})?::${Y}`,`(?:(?:${Y}:){0,6}${Y})?::`].map(e=>`(?:${e})`).join(`|`),Jd=RegExp(`^${Gd}$`),Yd=RegExp(`^(?:${qd})$`),Xd=e=>Jd.test(e),Zd=e=>Yd.test(e);function Qd(e){if(e.length===0||e.length>253||e.endsWith(`.`)||!/^[A-Za-z0-9.-]*$/.test(e))return!1;let t=e.split(`.`);for(let e of t){if(e.length===0||e.length>63||e.startsWith(`-`)||e.endsWith(`-`))return!1;let t=e.startsWith(`xn--`);if(e.slice(2,4)===`--`&&!t)return!1;if(t){let t=af(e.slice(4));if(t===void 0||!lf(t))return!1}}return!0}var $d=36,ef=1,tf=26,nf=4294967295;function rf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>($d-ef)*tf>>1;)r=Math.trunc(r/($d-ef)),i+=$d;return i+Math.trunc(($d-ef+1)*r/(r+38))}function af(e){let t=e.lastIndexOf(`-`),n=t>0?e.slice(0,t):``,r=t>0?e.slice(t+1):e,i=[...n].map(e=>e.charCodeAt(0)),a=128,o=72,s=0,c=0;for(;c<r.length;){let e=s,t=1;for(let e=$d;;e+=$d){if(c>=r.length)return;let n=of(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>nf||s>nf))return;let i=e<=o?ef:e>=o+tf?tf:e-o;if(n<i)break;if(t*=$d-i,t>nf)return}let n=i.length+1;if(o=rf(s-e,n,e===0),a+=Math.trunc(s/n),a>nf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function of(e){if(e>=48&&e<=57)return e-48+26;if(e>=65&&e<=90)return e-65;if(e>=97&&e<=122)return e-97}var sf=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3405,3530,3642,3972,4153,5908,5940,6098,6752,6980,7082,7154,7155,11647,43014,43204,43347,44013,68159,69702,69759,69817,69939,70080,70197,70378,70477,70722,70850,71103,71231,71350,71467,71737,72160,72244,72263,72345,72767,73028,73029,73111].map(e=>String.fromCodePoint(e))),cf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function lf(e){let t=[...e];if(t.length>0&&/^\p{M}/u.test(t[0]))return!1;let n=!1,r=!1,i=!1,a=!1;for(let e=0;e<t.length;e++){let o=t[e],s=t[e-1],c=t[e+1],l=o.codePointAt(0);if(o===`‍`){if(s===void 0||!sf.has(s))return!1}else if(o===`·`){if(s!==`l`||c!==`l`)return!1}else if(o===`͵`){let e=c?.codePointAt(0);if(e===void 0||e<880||e>1023)return!1}else if(o===`׳`||o===`״`){let e=s?.codePointAt(0);if(e===void 0||e<1424||e>1535)return!1}else if(o===`・`)n=!0;else if(l>=12352&&l<=12447||l>=12448&&l<=12543||l>=19968&&l<=40959)r=!0;else if(l>=1632&&l<=1641)i=!0;else if(l>=1776&&l<=1785)a=!0;else if(cf.has(o))return!1}return!(n&&!r||i&&a)}var uf=new TextEncoder;function df(e){return uf.encode(e).length}function ff(e){let t=e.codePointAt(0),n=t>>>24,r=t>>>16&255,i=t>>>8&255,a=t&255,o=e=>e>=128&&e<=191;return n===0&&r===0?i>=194&&i<=223&&o(a):n===0?r===224?i>=160&&i<=191&&o(a):r>=225&&r<=236?o(i)&&o(a):r===237?i>=128&&i<=159&&o(a):r===238||r===239?o(i)&&o(a):!1:n===240?r>=144&&r<=191&&o(i)&&o(a):n>=241&&n<=243?o(r)&&o(i)&&o(a):n===244?r>=128&&r<=143&&o(i)&&o(a):!1}var pf=/^[\p{Alphabetic}\p{N}]$/u,mf=new Set("!#$%&'*+-/=?^_`{|}~");function hf(e){return pf.test(e)||mf.has(e)||ff(e)}function gf(e){return e.length>0&&[...e].every(hf)}function _f(e){let t=[...e];for(let e=0;e<t.length;e++){let n=t[e],r=n.codePointAt(0);if(n===`\\`){let n=t[++e]?.codePointAt(0);if(n===void 0||n<33||n>126)return!1}else if(!(n===` `||n===` `||r===33||r>=35&&r<=91||r>=93&&r<=126||ff(n)))return!1}return!0}function vf(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||ff(e)}function yf(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function bf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=yf(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=yf(e.slice(0,r))}let i=t.lastIndexOf(`@`);if(i<0)return!1;let a=t.slice(0,i),o=t.slice(i+1);if(n===``&&a.startsWith(`<`)||a.length===0||df(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!_f(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(gf))return!1;if(o.length===0||df(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(vf)?e.startsWith(`IPv6:`)?Zd(e.slice(5)):Xd(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!pf.test(t[0])||!pf.test(t[t.length-1])||df(e)>63||!gf(e))return!1}return Qd(o)}var xf=`A-Za-z0-9\\-._~`,Sf=`!$&'()*+,;=`,Cf=`%[0-9A-Fa-f]{2}`,wf=`(?:[${xf}${Sf}:@]|${Cf})`,Tf=`${wf}*`,Ef=`${wf}+`,Df=`(?:[${xf}${Sf}@]|${Cf})+`,Of=`\\[(?:${qd}|[vV][0-9A-Fa-f]+\\.[${xf}${Sf}:]+)\\]`,kf=`(?:[${xf}${Sf}]|${Cf})*`,Af=`(?:${`(?:[${xf}${Sf}:]|${Cf})*`}@)?(?:${Of}|${kf})(?::[0-9]*)?`,jf=`(?:/${Tf})*`,Mf=`/(?:${Ef}(?:/${Tf})*)?`,Nf=`${Ef}(?:/${Tf})*`,Pf=`${Df}(?:/${Tf})*`,Ff=`(?:${wf}|[/?])*`,If=`[A-Za-z][A-Za-z0-9+\\-.]*`,Lf=`(?://${Af}${jf}|${Mf}|${Nf}|)`,Rf=`(?://${Af}${jf}|${Mf}|${Pf}|)`,zf=`(?:\\?${Ff})?(?:#${Ff})?`,Bf=RegExp(`^${If}:${Lf}${zf}$`),Vf=RegExp(`^(?:${If}:${Lf}|${Rf})${zf}$`);function Hf(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function Uf(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&Hf(n)}var Wf=new Set(`+#./;?&=,!@|`),Gf=new Set(`"'<>%\\^\`{|}`);function Kf(e){let t=0,n=t=>/^[0-9A-Fa-f]$/.test(e[t]??``),r=t=>/^[A-Za-z0-9_]$/.test(e[t]??``),i=()=>{let i=t;for(;t<e.length;)if(r(t))t++;else if(e[t]===`%`){if(t+2>=e.length||!n(t+1)||!n(t+2))return!1;t+=3}else break;return t>i},a=()=>{if(!i())return!1;for(;t<e.length;)if(e[t]===`.`){if(t++,!i())return!1}else if(r(t)||e[t]===`%`){if(!i())return!1}else break;return!0},o=()=>{if(!a())return!1;if(e[t]===`:`){if(t++,!/^[1-9]$/.test(e[t]??``))return!1;t++;for(let n=1;n<4&&/^[0-9]$/.test(e[t]??``);n++)t++}else e[t]===`*`&&t++;return!0};for(;t<e.length;){let r=e[t];if(r===`{`){if(t++,t>=e.length||Wf.has(e[t])&&(t++,t>=e.length)||!o())return!1;for(;e[t]===`,`;)if(t++,!o())return!1;if(e[t]!==`}`)return!1;t++}else if(r===`}`)return!1;else if(r===`%`){if(t+2>=e.length||!n(t+1)||!n(t+2))return!1;t+=3}else{let n=e.charCodeAt(t);if(n<=32||n===127||Gf.has(r))return!1;t++}}return!0}var qf={date:Vd,"date-time":Ud,email:bf,hostname:Qd,ipv4:Xd,ipv6:Zd,"json-pointer":Hf,regex:Fd,"relative-json-pointer":Uf,time:Hd,uri:e=>Bf.test(e),"uri-reference":e=>Vf.test(e),"uri-template":Kf},Jf=class{value;constructor(e){this.value=e}},Yf=2n**64n-1n,Xf=-(2n**63n),Zf=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,Qf=/[ \t\n\r]*/y;function $f(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{Qf.lastIndex=t,Qf.test(e),t=Qf.lastIndex},i=()=>{let r=t;t++;let i=!1;for(;t<e.length;){let a=e.charCodeAt(t);if(a===34){t++;let n=e.slice(r,t);return i?JSON.parse(n):n.slice(1,-1)}a===92?(i=!0,t++):a<32&&n(),t++}return n()},a=()=>{Zf.lastIndex=t;let r=Zf.exec(e);if(!r)return n();t=Zf.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new Jf(a):a;if(Object.is(a,-0))return new Jf(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<Xf||o>Yf?new Jf(a):BigInt(a)===o?a:o},o=()=>{r();let s=e[t];if(s===`{`){t++;let a=Object.create(null);if(r(),e[t]===`}`)return t++,a;for(;;){r(),e[t]!==`"`&&n();let s=i();if(r(),e[t]!==`:`&&n(),t++,a[s]=o(),r(),e[t]===`,`)t++;else if(e[t]===`}`)return t++,a;else n()}}if(s===`[`){t++;let i=[];if(r(),e[t]===`]`)return t++,i;for(;;)if(i.push(o()),r(),e[t]===`,`)t++;else if(e[t]===`]`)return t++,i;else n()}return s===`"`?i():e.startsWith(`true`,t)?(t+=4,!0):e.startsWith(`false`,t)?(t+=5,!1):e.startsWith(`null`,t)?(t+=4,null):a()},s=o();return r(),t!==e.length&&n(),s}function ep(e){return typeof e==`number`||typeof e==`bigint`||e instanceof Jf}function tp(e){return e instanceof Jf?e.value:e}function np(e,t){return typeof e==`bigint`?!0:e instanceof Jf?!t:Number.isInteger(e)}function rp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof Jf){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):ip(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?ip(e):Array.isArray(e)?`[${e.map(rp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${rp(t)}`).join(`,`)}}`:JSON.stringify(e)}function ip(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function ap(e){if(e instanceof Jf)return e.value;if(Array.isArray(e))return e.map(ap);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=ap(r);return t}function op(e,t){if(ep(e))return ep(t)?tp(e)==tp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>op(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||ep(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&op(e[n],t[n])):!1}return e===t}function sp(e,t){let n=Number(tp(e)),r=Number(tp(t));if(Number.isInteger(r))return Number.isInteger(n)&&n%r===0;if(n===0)return!0;if(n<r)return!1;let[i,a]=cp(n),[o,s]=cp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function cp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*lp(10,t),!Number.isFinite(n))return up(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(lp(10,t))]}function lp(e,t){let n=1,r=e;for(let e=t;e&1&&(n*=r),e=Math.trunc(e/2),e!==0;)r*=r;return n}function up(e){let[t,n]=Math.abs(e).toExponential().split(`e`),[r,i=``]=t.split(`.`),a=Number(n)-i.length,o=BigInt(r+i),s=1n;return a>=0?o*=10n**BigInt(a):s=10n**BigInt(-a),[e<0?-o:o,s]}var dp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},fp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},pp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mp=new URL(`json-schema:///`);function hp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function gp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _p(e,t=Object.create(null),n=[],r=mp,i=!0){let a=(e,n)=>{t[e]===void 0&&(t[e]=n)};if(typeof e==`boolean`)return i&&a(r.href,e),t;if(!gp(e))return t;let o=e.$id??e.id;if(typeof o==`string`){let t=new URL(o,r.href);t.hash.length>1?a(t.href,e):(t.hash=``,r=t,a(t.href,e))}if(i&&a(r.href,e),typeof e.$ref==`string`&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href}),n.push(t.href)}if(typeof e.$recursiveRef==`string`&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}typeof e.$anchor==`string`&&a(new URL(`#`+e.$anchor,r.href).href,e);for(let i in e){let a=e[i];if(fp[i]&&Array.isArray(a))for(let e of a)_p(e,t,n,r,!1);else if(dp[i])_p(a,t,n,r,!1);else if((pp[i]||i===`dependencies`)&&gp(a))for(let e in a)_p(a[e],t,n,r,!1)}return t}function vp(e,t){let n=e[t];if(n!==void 0)return n;let r=t.indexOf(`#`);if(r<0)return;let i=e[t.slice(0,r)],a=t.slice(r+1);if(!(i===void 0||!a.startsWith(`/`))){for(let e of a.slice(1).split(`/`)){let t;try{t=decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}catch{return}if(Array.isArray(i)){if(!/^(?:0|[1-9][0-9]*)$/.test(t))return;i=i[Number(t)]}else if(gp(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||gp(i)?i:void 0}}function yp(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r>=55296&&r<=56319&&n+1<e.length&&(e.charCodeAt(n+1)&64512)==56320&&n++,t++}return t}function bp(e){if(e===null)return`null`;if(ep(e))return`number`;if(Array.isArray(e))return`array`;switch(typeof e){case`boolean`:case`string`:return typeof e;case`object`:return`object`;default:throw Error(`Instances of "${typeof e}" type are not supported.`)}}function xp(e,t,n,r,i){return X(e,t,{draft:n,lookup:r,shortCircuit:i},null,`#`,`#`)}function X(e,t,n,r,i,a,o=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:`false`,keywordLocation:i,error:`False boolean schema.`}]};let{draft:s,lookup:c,shortCircuit:l}=n,u=bp(e),{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:E,patternProperties:D,additionalProperties:O,unevaluatedProperties:ee,minProperties:te,maxProperties:ne,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:k,prefixItems:oe,items:se,additionalItems:ce,unevaluatedItems:le,contains:ue,minContains:A,maxContains:de,minItems:fe,maxItems:pe,uniqueItems:me,minimum:he,maximum:j,exclusiveMinimum:ge,exclusiveMaximum:_e,multipleOf:ve,minLength:M,maxLength:ye,pattern:be,__absolute_ref__:xe,__absolute_recursive_ref__:Se}=t,N=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?vp(c,Se):r,l=`${a}/$recursiveRef`,u=X(e,r===null?t:r,n,s,i,l,o);u.valid||N.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=vp(c,xe??d);if(t===void 0)throw Error(`Unresolved $ref "${d}".`);let l=`${a}/$ref`,u=X(e,t,n,r,i,l,o);if(u.valid||N.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:N.length===0,errors:N}}let Ce=u===`number`&&np(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&Ce)||N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?Ce||N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&N.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!op(e,h)&&N.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${rp(h)}.`}),g!==void 0&&!g.some(t=>op(e,t))&&N.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${rp(g)}.`}),v!==void 0){let t=`${a}/not`;X(e,v,n,r,i,t).valid&&N.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let we=[];if(y!==void 0){let t=`${a}/anyOf`,s=N.length,c=!1;for(let a=0;a<y.length;a++){let s=Object.create(o),l=X(e,y[a],n,p===!0?r:null,i,`${t}/${a}`,s);N.push(...l.errors),c||=l.valid,l.valid&&we.push(s)}c?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${a}/allOf`,s=N.length,c=!0;for(let a=0;a<b.length;a++){let s=Object.create(o),l=X(e,b[a],n,p===!0?r:null,i,`${t}/${a}`,s);N.push(...l.errors),c&&=l.valid,l.valid&&we.push(s)}c?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${a}/oneOf`,s=N.length,c=x.filter((a,s)=>{let c=Object.create(o),l=X(e,a,n,p===!0?r:null,i,`${t}/${s}`,c);return N.push(...l.errors),l.valid&&we.push(c),l.valid}).length;c===1?N.length=s:N.splice(s,0,{instanceLocation:i,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${c} matches).`})}if((u===`object`||u===`array`)&&Object.assign(o,...we),S!==void 0){let t=`${a}/if`,s=Object.create(o);if(X(e,S,n,r,i,t,s).valid){if(Object.assign(o,s),C!==void 0){let s=X(e,C,n,r,i,`${a}/then`,o);s.valid||N.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...s.errors)}}else if(w!==void 0){let s=X(e,w,n,r,i,`${a}/else`,o);s.valid||N.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...s.errors)}}if(u===`object`){let t=e;if(_!==void 0)for(let e of _)e in t||N.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(te!==void 0&&s.length<te&&N.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0&&s.length>ne&&N.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${ne} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${hp(a)}`,o=X(a,re,n,r,t,e);o.valid||N.push({instanceLocation:i,keyword:`propertyNames`,keywordLocation:e,error:`Property name "${a}" does not match schema.`},...o.errors)}}if(ie!==void 0){let e=`${a}/dependentRequired`;for(let n in ie)if(n in t)for(let r of ie[n])r in t||N.push({instanceLocation:i,keyword:`dependentRequired`,keywordLocation:e,error:`Instance has "${n}" but does not have "${r}".`})}if(ae!==void 0)for(let s in ae){let c=`${a}/dependentSchemas`;if(s in t){let t=X(e,ae[s],n,r,i,`${c}/${hp(s)}`,o);t.valid||N.push({instanceLocation:i,keyword:`dependentSchemas`,keywordLocation:c,error:`Instance has "${s}" but does not match dependant schema.`},...t.errors)}}if(k!==void 0){let o=`${a}/dependencies`;for(let a in k)if(a in t){let s=k[a];if(Array.isArray(s))for(let e of s)e in t||N.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not have "${e}".`});else{let t=X(e,s,n,r,i,`${o}/${hp(a)}`);t.valid||N.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not match dependant schema.`},...t.errors)}}}let c=Object.create(null),u=!1;if(E!==void 0){let e=`${a}/properties`;for(let a in E){if(!(a in t))continue;let s=`${i}/${hp(a)}`,d=X(t[a],E[a],n,r,s,`${e}/${hp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,N.push({instanceLocation:i,keyword:`properties`,keywordLocation:e,error:`Property "${a}" does not match schema.`},...d.errors),u)break}}if(!u&&D!==void 0){let e=`${a}/patternProperties`;for(let a in D){let s=Rd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${hp(f)}`,m=X(t[f],d,n,r,p,`${e}/${hp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,N.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&O!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${hp(a)}`,d=X(t[a],O,n,r,s,e);d.valid?o[a]=!0:(u=l,N.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&ee!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${hp(a)}`,c=X(t[a],ee,n,r,s,e);c.valid?o[a]=!0:N.push({instanceLocation:i,keyword:`unevaluatedProperties`,keywordLocation:e,error:`Property "${a}" does not match unevaluated properties schema.`},...c.errors)}}}else if(u===`array`){let t=e,s=t.length;pe!==void 0&&s>pe&&N.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${pe}).`}),fe!==void 0&&s<fe&&N.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${fe}).`});let c=0,u=!1;if(oe!==void 0){let e=`${a}/prefixItems`,d=Math.min(oe.length,s);for(;c<d;c++){let a=X(t[c],oe[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(se!==void 0){let e=`${a}/items`;if(Array.isArray(se)){let a=Math.min(se.length,s);for(;c<a;c++){let a=X(t[c],se[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}else for(;c<s;c++){let a=X(t[c],se,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,N.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}if(!u&&ce!==void 0){let e=`${a}/additionalItems`;for(;c<s;c++){let a=X(t[c],ce,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,N.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(ue!==void 0)if(s===0&&A===void 0)N.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(A!==void 0&&s<A)N.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${A}).`});else{let e=`${a}/contains`,c=N.length,l=0;for(let a=0;a<s;a++){let s=X(t[a],ue,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):N.push(...s.errors)}l>=(A||0)&&(N.length=c),A===void 0&&de===void 0&&l===0?N.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):A!==void 0&&l<A?N.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${A} items matching schema. Only ${l} items were found.`}):de!==void 0&&l>de&&N.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${de} items matching schema. ${l} items were found.`})}if(!u&&le!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=X(t[c],le,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||N.push({instanceLocation:i,keyword:`unevaluatedItems`,keywordLocation:e,error:`Items did not match unevaluated items schema.`},...a.errors)}}if(me){outer:for(let e=0;e<s;e++)for(let n=e+1;n<s;n++)if(op(t[e],t[n])){N.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=tp(e);s===`4`?(he!==void 0&&(ge===!0&&t<=he||t<he)&&N.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${ge?`or equal to `:``}${he}.`}),j!==void 0&&(_e===!0&&t>=j||t>j)&&N.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${_e?`or equal to `:``}${j}.`})):(he!==void 0&&t<he&&N.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${he}.`}),j!==void 0&&t>j&&N.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${j}.`}),ge!==void 0&&t<=ge&&N.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${ge}.`}),_e!==void 0&&t>=_e&&N.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${_e}.`})),ve!==void 0&&!sp(e,ve)&&N.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ve}.`})}else if(u===`string`){let t=e,n=M===void 0&&ye===void 0?0:yp(t);M!==void 0&&n<M&&N.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${M}).`}),ye!==void 0&&n>ye&&N.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${ye}).`}),be!==void 0&&!Rd(be).test(t)&&N.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:qf[T];r&&!r(t)&&N.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:N.length===0,errors:N}}var Sp={draft4:[{id:`http://json-schema.org/draft-04/schema#`,$schema:`http://json-schema.org/draft-04/schema#`,description:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},positiveInteger:{type:`integer`,minimum:0},positiveIntegerDefault0:{allOf:[{$ref:`#/definitions/positiveInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},minItems:1,uniqueItems:!0}},type:`object`,properties:{id:{type:`string`},$schema:{type:`string`},title:{type:`string`},description:{type:`string`},default:{},multipleOf:{type:`number`,minimum:0,exclusiveMinimum:!0},maximum:{type:`number`},exclusiveMaximum:{type:`boolean`,default:!1},minimum:{type:`number`},exclusiveMinimum:{type:`boolean`,default:!1},maxLength:{$ref:`#/definitions/positiveInteger`},minLength:{$ref:`#/definitions/positiveIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{anyOf:[{type:`boolean`},{$ref:`#`}],default:{}},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:{}},maxItems:{$ref:`#/definitions/positiveInteger`},minItems:{$ref:`#/definitions/positiveIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxProperties:{$ref:`#/definitions/positiveInteger`},minProperties:{$ref:`#/definitions/positiveIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{anyOf:[{type:`boolean`},{$ref:`#`}],default:{}},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},enum:{type:`array`},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},dependencies:{exclusiveMaximum:[`maximum`],exclusiveMinimum:[`minimum`]},default:{}}],draft6:[{$schema:`http://json-schema.org/draft-06/schema#`,$id:`http://json-schema.org/draft-06/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},title:{type:`string`},description:{type:`string`},default:{},examples:{type:`array`,items:{}},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:{}},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:{},enum:{type:`array`},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:{}}],draft7:[{$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}],draft201909:[{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/schema`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format`},{$ref:`meta/content`}],type:[`object`,`boolean`],properties:{definitions:{$comment:`While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.`,type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},dependencies:{$comment:`"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"`,type:`object`,additionalProperties:{anyOf:[{$recursiveRef:`#`},{$ref:`meta/validation#/$defs/stringArray`}]}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/core`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{type:`string`,format:`uri`},$anchor:{type:`string`,pattern:`^[A-Za-z][-A-Za-z0-9.:_]*$`},$ref:{type:`string`,format:`uri-reference`},$recursiveRef:{type:`string`,format:`uri-reference`},$recursiveAnchor:{type:`boolean`,default:!1},$vocabulary:{type:`object`,propertyNames:{type:`string`,format:`uri`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{additionalItems:{$recursiveRef:`#`},unevaluatedItems:{$recursiveRef:`#`},items:{anyOf:[{$recursiveRef:`#`},{$ref:`#/$defs/schemaArray`}]},contains:{$recursiveRef:`#`},additionalProperties:{$recursiveRef:`#`},unevaluatedProperties:{$recursiveRef:`#`},properties:{type:`object`,additionalProperties:{$recursiveRef:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$recursiveRef:`#`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$recursiveRef:`#`}},propertyNames:{$recursiveRef:`#`},if:{$recursiveRef:`#`},then:{$recursiveRef:`#`},else:{$recursiveRef:`#`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$recursiveRef:`#`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$recursiveRef:`#`}}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}},const:!0,enum:{type:`array`,items:!0},type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/format`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:`Format vocabulary meta-schema`,type:[`object`,`boolean`],properties:{format:{type:`string`}}},{$schema:`https://json-schema.org/draft/2019-09/schema`,$id:`https://json-schema.org/draft/2019-09/meta/content`,$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentMediaType:{type:`string`},contentEncoding:{type:`string`},contentSchema:{$recursiveRef:`#`}}}],draft202012:[{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}},{$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}]},Cp={"json-schema.org/draft/2020-12/schema":`2020-12`,"json-schema.org/draft/2019-09/schema":`2019-09`,"json-schema.org/draft-07/schema":`7`,"json-schema.org/draft-06/schema":`6`,"json-schema.org/draft-04/schema":`4`},wp=new Set(`$anchor.$id.$recursiveAnchor.$recursiveRef.$ref.additionalItems.additionalProperties.allOf.anyOf.const.contains.dependencies.dependentRequired.dependentSchemas.else.enum.exclusiveMaximum.exclusiveMinimum.format.id.if.items.maxContains.maxItems.maxLength.maxProperties.maximum.minContains.minItems.minLength.minProperties.minimum.multipleOf.not.oneOf.pattern.patternProperties.prefixItems.properties.propertyNames.required.then.type.unevaluatedItems.unevaluatedProperties.uniqueItems`.split(`.`)),Tp={single:[`additionalItems`,`additionalProperties`,`items`,`not`],array:[`allOf`,`anyOf`,`items`,`oneOf`],map:[`definitions`,`dependencies`,`patternProperties`,`properties`],plain:[`$ref`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`id`,`maxItems`,`maxLength`,`maxProperties`,`maximum`,`minItems`,`minLength`,`minProperties`,`minimum`,`multipleOf`,`pattern`,`required`,`type`,`uniqueItems`]},Ep={...Tp,single:[...Tp.single,`contains`,`propertyNames`],plain:[...Tp.plain.filter(e=>e!==`id`),`$id`,`const`]},Dp={...Ep,single:[...Ep.single,`if`,`then`,`else`]},Op={single:[...Dp.single,`unevaluatedItems`,`unevaluatedProperties`],array:Dp.array,map:[...Dp.map,`$defs`,`dependentSchemas`],plain:[...Dp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},kp={single:Op.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Op.map,plain:Op.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)},Ap={4:Tp,6:Ep,7:Dp,"2019-09":Op,"2020-12":kp},jp={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Mp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Np=[...Mp,`json-pointer`,`uri-reference`,`uri-template`],Pp={4:Mp,6:Np,7:[...Np,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},Fp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Ip={base64:Lp(`A-Za-z0-9+/`),base64url:Lp(`A-Za-z0-9\\-_`),base32:Rp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:Rp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Lp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function Rp(e,t,n,r,i){let a=`[${e}]`;return`^(?:${a}{8})*(?:${a}[${t}]={6}|${a}{3}[${n}]={4}|${a}{4}[${r}]={3}|${a}{6}[${i}]=)?$`}var zp=class extends Error{};function Bp(e){if(!F(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Cp[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new zp(`unknown JSON Schema dialect "${t}"`);return n}function Vp(e,t,n=[]){if(typeof e==`boolean`)return e;if(!F(e))return{};let r=Ap[t],i=new Set([...r.single,...r.array,...r.map,...r.plain,...n]),a=typeof e.$ref==`string`&&[`4`,`6`,`7`].includes(t),o=[];for(let[s,c]of Object.entries(e)){if(jp[t].includes(s)&&!n.includes(s))throw new zp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(wp.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&Up(c),s===`patternProperties`&&F(c))for(let e of Object.keys(c))Up(e);if(s===`format`&&typeof c==`string`){if(!Pp[t]?.includes(c))continue;if(Fp.includes(c))throw new zp(`the "${c}" format is not supported by the browser runtime yet`)}r.array.includes(s)&&Array.isArray(c)?o.push([s,c.map(e=>Vp(e,t,n))]):r.single.includes(s)?o.push([s,Vp(c,t,n)]):r.map.includes(s)&&F(c)?o.push([s,Hp(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Ip[s];if(e){let t=o.find(([e])=>e===`allOf`);t?t[1]=[...t[1],{pattern:e}]:o.push([`allOf`,[{pattern:e}]])}}return Object.fromEntries(o)}function Hp(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:Vp(r,t,n)]))}function Up(e){try{Rd(e)}catch(t){throw t instanceof bd?new zp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof xd?new zp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function Wp(e){for(let t of e.references)if(vp(e.lookup,t)===void 0)throw new zp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function Gp(e){if(Array.isArray(e))return e.map(Gp);if(!F(e))return e;let t=[];for(let[n,r]of Object.entries(e))n===`$dynamicAnchor`?t.push([`$recursiveAnchor`,!0]):n===`$dynamicRef`?t.push([`$recursiveRef`,`#`]):t.push([n,Gp(r)]);return Object.fromEntries(t)}var Kp={4:Sp.draft4,6:Sp.draft6,7:Sp.draft7,"2019-09":Sp.draft201909,"2020-12":Sp.draft202012};function qp(e){return Kp[e].map(t=>e===`2020-12`?Gp(Vp(t,e,[`$dynamicAnchor`,`$dynamicRef`])):Vp(t,e))}var Jp=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=_p(e,void 0,this.references);for(let e of r)_p(e,this.lookup)}validate(e){return xp(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},Yp=new Map;function Xp(e){let t=Yp.get(e);if(!t){let[n,...r]=qp(e);t=new Jp(n,e,!1,r),Yp.set(e,t)}return t}function Zp(e){let t=e[e.length-1];if(!t)return`value does not match the schema`;let n=t.instanceLocation.replace(/^#/,``);return n?`${t.error} (at ${n})`:t.error}function Qp(e){let t=Bp(e);if(typeof e==`boolean`){if(t===`4`)throw new zp(`boolean schemas need draft 6 or later`)}else{let n=Xp(t).validate(e);if(!n.valid)throw new zp(Zp(n.errors))}let n=new Jp(Vp(ap(e),t),t,!0,qp(t));return Wp(n),e=>{let t=n.validate($f(e));return t.valid?void 0:Zp(t.errors)}}function $p(e){return Qp($f(e))}function em(e){e.setJsonSchemaValidator($p)}async function tm(){let e=process.getBuiltinModule?.(`module`),t=process.getBuiltinModule?.(`fs`),n=process.getBuiltinModule?.(`path`);if(!e||!t||!n)return null;let{createRequire:r}=e,{existsSync:i,readFileSync:a}=t,{dirname:o,resolve:s}=n,c={}.JAZZ_CORRECTNESS_WASM_PACKAGE;if({}.JAZZ_CORRECTNESS_ARTIFACT_RUN===`1`&&!c)throw Error(`sealed correctness consumer is missing its admitted WASM package`);if(c){let e=s(c,`jazz_wasm_bg.wasm`);return i(e)?a(e):null}let l=s(o(r(import.meta.url).resolve(`jazz-wasm/package.json`)),`pkg/jazz_wasm_bg.wasm`);return i(l)?a(l):null}var nm=Promise.resolve(),rm;function im(e){let t=nm.then(()=>am(e));return nm=t.then(()=>void 0,()=>void 0),t}async function am(t){let n=await e(()=>import(`./jazz_wasm-mBuVt23h.js`),[],import.meta.url),r=Qr(t);if(r)return n.initSync(r),om(n);let i=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await tm();e&&(n.initSync({module:e}),i=!0)}catch{}if(!i&&typeof n.default==`function`){let e=typeof location<`u`?$r(Vr,location.href,t)??Ur():null;if(e)await sm(n,e);else if(typeof location<`u`&&Gi())throw Error(Ui);else await n.default()}return om(n)}function om(e){return yd(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),em(e),e}async function sm(e,t){if(rm===t)return;let n=await fetch(t);if(!n.ok)throw Error(`WASM asset request failed (${n.status} ${n.statusText}) for ${t}`);let r=n.headers.get(`content-type`);if(cm(r)){let i;try{i=await WebAssembly.compileStreaming(n)}catch(e){throw e instanceof WebAssembly.CompileError?Error(`WASM asset response is not a WebAssembly binary for ${t} (${r}): ${e.message}`):e}await e.default({module_or_path:i}),rm=t;return}let i=new Uint8Array(await n.arrayBuffer());if(i.length<4||i[0]!==0||i[1]!==97||i[2]!==115||i[3]!==109)throw Error(`WASM asset response is not a WebAssembly binary for ${t} (${r??`unknown content type`})`);await e.default({module_or_path:i}),rm=t}function cm(e){return typeof WebAssembly.compileStreaming==`function`?e?.trim()===`application/wasm`:!1}function lm(e){return{captureAnchor:(t,n,r,i)=>e.captureTextAnchor(t,i,n,r),resolveAnchor:(t,n,r)=>e.resolveTextAnchor(t,n,r),captureRange:(t,n,r,i)=>e.captureTextRange(t,i,n,r),resolveRange:(t,n,r)=>e.resolveTextRange(t,n,r)}}function um(e,t,n,r){return Rr(`${ut}${e}`,{audience:t,ttlSeconds:n,now:r})}var dm=class{supportsBrowserWorker=!1;supportsPolicyBypass=!0;async load(e){await this.loadRuntime(e)}nativeConnection;assertAuthUpdateAllowed(){}refreshAccountToken(e){return!1}admitConfig(e){}async shutdown(){}async loadRuntime(e){}async acquireForegroundNodeLease(e){}acquireBrowserForegroundNodeLease(e){return Promise.reject(Error(`Db runtime source does not support browser foreground leases`))}createBrowserWorkerConnection(e){throw Error(`Db runtime source does not support browser worker connections`)}createBrowserFollowerConnection(e){throw Error(`Db runtime source does not support browser follower connections`)}installTelemetry(e){return null}mintLocalFirstToken(e){return um(e.secret,e.audience,e.ttlSeconds,Number(e.nowSeconds))}mintAnonymousToken(e){throw Error(`Db runtime source does not support anonymous auth`)}textAnchors(){throw Error(`Db runtime source does not support text anchors yet`)}};async function*fm(e){let t=e;if(typeof t.getReader!=`function`){let t=e[Symbol.asyncIterator](),n=!1;try{for(;;){let e=await t.next();if(e.done){n=!0;return}yield e.value}}finally{if(!n)try{Promise.resolve(t.return?.()).catch(()=>void 0)}catch{}}}let n=t.getReader(),r=!1;try{for(;;){let e=await n.read();if(e.done){r=!0;return}yield e.value}}finally{if(!r)try{Promise.resolve(n.cancel()).catch(()=>void 0)}catch{}n.releaseLock()}}var pm=`authority_changed`,mm=class extends Error{name=`AuthorityChangedError`;code=pm;constructor(e,t){super(e,t)}};function hm(e){return!e||typeof e!=`object`?!1:e.code===pm}function gm(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(hm(e))return new mm(t,{cause:e});if(e instanceof Error)return e;let n=Error(t),r=typeof e==`object`?e.code:void 0;return typeof r==`string`&&Object.assign(n,{code:r}),n}var _m=`core_tick_failed`,vm=class extends Error{name=`CoreTickFailedError`;code=_m;constructor(e){super(`core tick failed: ${bm(e)}`,{cause:e})}};function ym(e){return!e||typeof e!=`object`?!1:e.code===_m}function bm(e){if(e instanceof Error)return e.message;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`)return t}return String(e)}var xm=class extends ms{},Sm=class{text;constructor(e){this.text=e}};function Cm(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){if(++t>=e.length||e.charCodeAt(t)<56320||e.charCodeAt(t)>57343)throw Error(`invalid relation query: unpaired surrogate`)}else if(n>=56320&&n<=57343)throw Error(`invalid relation query: unpaired surrogate`)}}function wm(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Cm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Cm(e),e.includes(t)||n(r,t))):!1,r=`__jrq_raw_number_`;for(;e.includes(r)||n(t,r);)r=`_${r}`;let i=[],a=``,o=!1,s=!1;for(let t=0;t<e.length;t++){let n=e[t];if(o){a+=n,s?s=!1:n===`\\`?s=!0:n===`"`&&(o=!1);continue}if(n===`"`){o=!0,a+=n;continue}if(n===`-`||n>=`0`&&n<=`9`){let n=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(e.slice(t));if(n){i.push(n[0]),a+=JSON.stringify(`${r}${i.length-1}__`),t+=n[0].length-1;continue}}a+=n}let c=e=>{if(typeof e==`string`){let t=RegExp(`^${r}(\\d+)__$`).exec(e);return t?new Sm(i[Number(t[1])]):e}return Array.isArray(e)?e.map(c):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,c(t)])):e};return c(JSON.parse(a))}function Tm(e){let t=4096,n=[],r=0,i=0,a=new TextEncoder,o=e=>{throw Error(`invalid relation Postcard: ${e}`)},s=(...e)=>{e.some(e=>!Number.isInteger(e)||e<0||e>255)&&o(`byte`),n.length>1048576-e.length&&o(`byte limit`),n.push(...e)},c=e=>{(!Number.isSafeInteger(e)||e<0||e>t)&&o(`collection`),d(e)},l=()=>{++i>t&&o(`node limit`)},u=e=>{++r>128&&o(`depth limit`);try{e()}finally{r--}},d=e=>{let t=typeof e==`bigint`?e:BigInt(e);(t<0n||t>18446744073709551615n)&&o(`integer range`);do{let e=Number(t&127n);t>>=7n,t&&(e|=128),s(e)}while(t)},f=e=>d(e<0n?(-e<<1n)-1n:e<<1n),p=e=>{typeof e!=`string`&&o(`string`),Cm(e);let t=a.encode(e);t.length>65536&&o(`string limit`),d(t.length),s(...t)},m=(e,t)=>{e==null?s(0):(s(1),t())},h=(e,t,n)=>{let r=Object.keys(e);(r.length!==1||!t.includes(r[0]))&&o(n)},g=(e,t,n)=>{Object.keys(e).some(e=>!t.includes(e))&&o(n)},_=e=>{e instanceof Sm&&(/^(?:0|[1-9]\d*)$/.test(e.text)||o(`dimension`),e=Number(e.text));let t=typeof e==`number`?e:o(`dimension`);(!Number.isSafeInteger(t)||t<0||t>4294967295)&&o(`dimension`),d(t)},v=e=>{(!e||typeof e!=`object`)&&o(`column`),g(e,[`scope`,`column`],`column`),(typeof e.column!=`string`||e.scope!==void 0&&typeof e.scope!=`string`)&&o(`column`),m(e.scope,()=>p(e.scope)),p(e.column)},y=e=>d(e===`Current`?0:e===`Outer`?1:e===`Frontier`?2:o(`row id`)),b=e=>{if(l(),e instanceof Sm){if(/^(?:0|[1-9]\d*|-[1-9]\d*)$/.test(e.text)){let t=BigInt(e.text);if(t>=-9223372036854775808n&&t<=9223372036854775807n){d(2),f(t);return}if(t>=0n&&t<=18446744073709551615n){d(3),d(t);return}}let t=Number(e.text);Number.isFinite(t)||o(`number`),d(4);let n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t,!0),d(n.getBigUint64(0,!0));return}if(e===null){d(0);return}if(typeof e==`boolean`){d(1),s(e?1:0);return}if(typeof e==`number`){if(Number.isFinite(e)||o(`number`),Number.isInteger(e)&&!Object.is(e,-0)){let t=JSON.stringify(e);if(/^(?:0|[1-9]\d*|-[1-9]\d*)$/.test(t)){let e=BigInt(t);if(e>=-9223372036854775808n&&e<=9223372036854775807n){d(2),f(e);return}if(e>=0n&&e<=18446744073709551615n){d(3),d(e);return}}}d(4);let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e,!0),d(t.getBigUint64(0,!0));return}if(typeof e==`string`){d(5),p(e);return}if(Array.isArray(e)){d(6),c(e.length),e.forEach(e=>u(()=>b(e)));return}(!e||typeof e!=`object`)&&o(`literal`),d(7);let t=Object.entries(e).sort(([e],[t])=>{let n=a.encode(e),r=a.encode(t);for(let e=0;e<Math.min(n.length,r.length);e++)if(n[e]!==r[e])return n[e]-r[e];return n.length-r.length});c(t.length);for(let[e,n]of t)p(e),u(()=>b(n))},x=e=>{l(),h(e,[`Column`,`RowId`],`key`),`Column`in e?(d(0),v(e.Column)):(d(1),y(e.RowId))},S=e=>{l(),h(e,[`Column`,`RowId`],`project`),`Column`in e?(d(0),v(e.Column)):(d(1),y(e.RowId))},C=e=>{l(),h(e,[`Literal`,`Param`,`SessionRef`,`OuterColumn`,`FrontierColumn`,`RowId`],`value`),`Literal`in e?(d(0),b(e.Literal)):`Param`in e?(d(1),p(e.Param)):`SessionRef`in e?(d(2),c(e.SessionRef.length),e.SessionRef.forEach(p)):`OuterColumn`in e?(d(3),v(e.OuterColumn)):`FrontierColumn`in e?(d(4),v(e.FrontierColumn)):(d(5),y(e.RowId))},w=e=>{if(l(),e===`True`){d(9);return}if(e===`False`){d(10);return}if(h(e,[`Cmp`,`IsNull`,`IsNotNull`,`In`,`Contains`,`And`,`Or`,`Not`],`predicate`),`Cmp`in e){d(0),v(e.Cmp.left);let t=[`Eq`,`Ne`,`Lt`,`Le`,`Gt`,`Ge`].indexOf(e.Cmp.op);t<0&&o(`comparison operator`),d(t),u(()=>C(e.Cmp.right))}else `IsNull`in e?(d(1),v(e.IsNull.column)):`IsNotNull`in e?(d(2),v(e.IsNotNull.column)):`In`in e?(d(3),v(e.In.left),c(e.In.values.length),e.In.values.forEach(e=>u(()=>C(e)))):`Contains`in e?(d(4),v(e.Contains.left),u(()=>C(e.Contains.right))):`And`in e?(d(6),c(e.And.length),e.And.forEach(e=>u(()=>w(e)))):`Or`in e?(d(7),c(e.Or.length),e.Or.forEach(e=>u(()=>w(e)))):(d(8),u(()=>w(e.Not)))},T=e=>{l(),h(e,[`TableScan`,`Filter`,`Union`,`Join`,`Project`,`Gather`,`Distinct`,`OrderBy`,`Offset`,`Limit`],`expression`),`TableScan`in e?(g(e.TableScan,[`table`,`alias`],`table scan`),d(0),p(e.TableScan.table),m(e.TableScan.alias,()=>p(e.TableScan.alias))):`Filter`in e?(d(1),u(()=>T(e.Filter.input)),u(()=>w(e.Filter.predicate))):`Union`in e?(d(2),c(e.Union.inputs.length),e.Union.inputs.forEach(e=>{p(e.label),u(()=>T(e.input))})):`Join`in e?(g(e.Join,[`left`,`right`,`on`,`join_kind`],`join`),d(3),u(()=>T(e.Join.left)),u(()=>T(e.Join.right)),c(e.Join.on.length),e.Join.on.forEach(e=>{l(),v(e.left),v(e.right)}),e.Join.join_kind!==`Inner`&&e.Join.join_kind!==`Left`&&o(`join kind`),d(e.Join.join_kind===`Inner`?0:1)):`Project`in e?(d(4),u(()=>T(e.Project.input)),c(e.Project.columns.length),e.Project.columns.forEach(e=>{p(e.alias),S(e.expr)})):`Gather`in e?(d(5),u(()=>T(e.Gather.seed)),u(()=>T(e.Gather.step)),x(e.Gather.frontier_key),e.Gather.bound===`Fixpoint`?d(0):(d(1),_(e.Gather.bound.MaxDepth)),c(e.Gather.dedupe_key.length),e.Gather.dedupe_key.forEach(x)):`Distinct`in e?(d(6),u(()=>T(e.Distinct.input)),c(e.Distinct.key.length),e.Distinct.key.forEach(x)):`OrderBy`in e?(d(7),u(()=>T(e.OrderBy.input)),c(e.OrderBy.terms.length),e.OrderBy.terms.forEach(e=>{l(),g(e,[`column`,`direction`],`order term`),v(e.column),e.direction!==`Asc`&&e.direction!==`Desc`&&o(`order direction`),d(e.direction===`Asc`?0:1)})):`Offset`in e?(d(8),u(()=>T(e.Offset.input)),_(e.Offset.offset)):(d(9),u(()=>T(e.Limit.input)),_(e.Limit.limit))};return T(e),Uint8Array.from(n)}Pe({issuer:tt,user_id:`system`,claims:{},authMode:`external`});var Em=-(1n<<63n),Dm=(1n<<63n)-1n;function Om(e,t){if(typeof e==`number`&&!Number.isSafeInteger(e))throw Error(`${t} must be a safe integer when passed as a number, got ${e}`);let n=BigInt(e);if(n<Em||n>Dm)throw Error(`${t} must be a signed 64-bit integer`);return n}var km=new T({fatal:!0});function Am(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function jm(e){return{table:e.string(),descriptor:Nm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Mm(e,t){e.vec((e,n)=>{let r=t[n];e.u64(r.kind===`stored-column`?0:r.kind===`result-field`?1:2),r.kind===`stored-column`?(e.u64(r.id),e.string(r.outputName)):e.string(r.name),Um(e,r.valueType)},t.length)}function Nm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:Wm(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:Wm(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:Wm(e)}:Pm(t)})}function Pm(e){throw Error(`unknown native row descriptor field kind ${e}`)}function Fm(e){let t={added:e.readVec(jm),updated:e.readVec(jm),removed:e.readVec(Bm),addedOccurrenceKeys:e.readVec(e=>Im(e)),updatedOccurrenceKeys:e.readVec(e=>Im(e)),removedOccurrenceKeys:e.readVec(e=>Im(e)),addedIndices:e.readVec(e=>e.u64()),updatedPreviousIndices:e.readVec(e=>e.u64()),updatedIndices:e.readVec(e=>e.u64()),removedIndices:e.readVec(e=>e.u64()),updatedSplices:e.readVec(e=>e.readVec(e=>({column:e.string(),splices:e.readVec(e=>({at:e.u64(),delete:e.u64(),insert:e.bytes(),atUtf16:e.u64(),deleteUtf16:e.u64()}))})))},n=e=>e.reduce((e,t)=>e+t.rows.length,0);if(t.addedOccurrenceKeys.length!==n(t.added)||t.updatedOccurrenceKeys.length!==n(t.updated)||t.removedOccurrenceKeys.length!==t.removed.length||t.addedIndices.length!==n(t.added)||t.updatedPreviousIndices.length!==n(t.updated)||t.updatedIndices.length!==n(t.updated)||t.removedIndices.length!==t.removed.length||t.updatedSplices.length!==n(t.updated))throw Error(`subscription occurrence sidecar length mismatch`);return zm(e,`subscription delta`),t}function Im(e){let t=e.bytes();if(t[0]!==2||!Lm(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Lm(e){let t=t=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;if(e.length<25)return!1;let n=16,r=t(n);if(n+=4,r>256||n+r*16+4>e.length)return!1;n+=r*16;let i=t(n);if(n+=4,i>r+1)return!1;let a=-1;for(let o=0;o<i;o++){if(n+8>e.length)return!1;let i=t(n),o=t(n+4);if(n+=8,i>r||i<=a||o===0||o>4096||n+o>e.length||!le(e.subarray(n,n+o)))return!1;a=i,n+=o}for(let t=0;t<=r;t++){let t=e[n++];if(t===1)n+=24;else if(t!==0)return!1}return n===e.length}function Rm(e){let t=e.u64(),n=e.readVec(jm);return zm(e,`relation snapshot`),{rootCount:t,rows:n}}function zm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Bm(e){return{table:e.string(),rowId:e.bytes()}}function Vm(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),Um(e,t[n].valueType)},t.length)}function Hm(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:Wm(e)}))}function Um(e,t){if(e.enumUnit(t.tag),t.tag===10){if(!t.internal)throw Error(`missing physical type for ValueType::Internal`);if(e.enumUnit(t.internal.tag),t.internal.tag===2){if(t.internal.kind==null)throw Error(`missing stored-scalar kind`);e.enumUnit(t.internal.kind)}return}if(t.tag===12){let n=t.enumSchema,r=n?.variants;if(!n||!r)throw Error(`missing enum schema for ValueType::Enum`);e.u64(n.registryId??0),e.string(n.name),e.vec((e,t)=>e.string(r[t]),r.length);return}if(t.tag===13){let n=t.members??(t.inner?[t.inner]:[]);e.vec((e,t)=>Um(e,n[t]),n.length);return}if(t.tag===14||t.tag===15){if(!t.inner)throw Error(`missing inner value type for tag ${t.tag}`);Um(e,t.inner);return}if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);Vm(e,t.record);return}if(t.tag===17){let n=t.enumSchema,r=n?.cases;if(!n||!r)throw Error(`missing cases for ValueType::Enum`);e.u64(n.registryId??0),e.string(n.name),e.vec((e,t)=>{let n=r[t];e.string(n.name),Vm(e,n.payload)},r.length)}}function Wm(e){let t=e.u64();if(t===10){let n=e.u64();return{tag:t,internal:{tag:n,kind:n===2?e.u64():void 0}}}if(t===12)return{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),variants:e.readVec(e=>e.string())}};if(t===14||t===15)return{tag:t,inner:Wm(e)};if(t===13){let n=e.readVec(Wm);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:Hm(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:Hm(e)}))}}:{tag:t}}function Gm(e,t){let n=Dh(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=Te(r),o=new jh,s=a.length+Math.max(0,i.length-1)*4;for(let e of i.slice(0,-1))s+=e.length,o.u32Le(s);return Te([a,o.finish(),...i])}function Km(e,t){let n=th(sh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:yh(e.column_type,i)})}function qm(e,t){return Object.defineProperty(e,`valuesByColumn`,{value:t,enumerable:!1,configurable:!0}),e}function Jm(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r];i&&n.set(i.name,t[r])}return n}var Ym={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function Xm(e,t,n){let r=Zm([Ym,...t],n),i=r[0];if(i?.type!==`Uuid`||i.value!==e)throw Error(`terminal record key ${i?.type===`Uuid`?i.value:`<non-uuid>`} does not match addressed key ${e}`);let a=r.slice(1);return qm({id:e,values:a},Jm(t,a))}function Zm(e,t){let n=th(sh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:Qm(e.column_type,i,e.name)})}function Qm(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:wh(t,n)};case`Array`:return{type:`Array`,value:$m(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:Xm(Th(t.subarray(0,16)),e.columns,t)};default:return yh(e,t)}}function $m(e,t){return Ch(e,t,t=>Qm(e,t))}function eh(e,t){return Gm(sh(e),e.map((e,n)=>ch(e,t[n])))}function th(e){let t=Dh(e);return(n,r)=>nh(e,t,n,r)}function nh(e,t,n,r){let i=t.fields[r];if(!i)throw Error(`field is not present`);let a=e[r].valueType;if(i.kind===`fixed`){if(i.offset+i.size>n.length)throw Error(`unexpected end of record`);return rh(n.subarray(i.offset,i.offset+i.size),a)}let o=t.fixedSize,s=t.fixedSize+Math.max(0,t.variable.length-1)*4,c=i.variableIndex===0?s:Oh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Oh(n,o+i.variableIndex*4);if(c>l||l>n.length){let t=e[r],i=l-c,o=Math.max(0,n.length-c);throw Error(`invalid offset for ${t?.name??`<field ${r}>`}: declared type ${ih(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return rh(n.subarray(c,l),a)}function rh(e,t){if(t.tag!==15)return e;let n=oh(e);return n==null?null:t.inner?rh(n,t.inner):n}function ih(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?ih(e.inner):`?`}>`:ah(e.tag)}function ah(e){switch(e){case 0:return`U8`;case 1:return`U16`;case 2:return`U32`;case 3:return`U64`;case 4:return`I32`;case 5:return`I64`;case 6:return`F64`;case 7:return`Bool`;case 8:return`String`;case 9:return`Bytes`;case 10:return`Internal`;case 11:return`Uuid`;case 12:return`EnumTag`;case 13:return`Tuple`;case 14:return`Array`;case 15:return`Nullable`;case 16:return`Record`;case 17:return`Enum`;default:return`unknown(${e})`}}function oh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function sh(e){return e.map(e=>({name:e.name,valueType:gh(e)}))}function ch(e,t){let n=vh(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return uh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return uh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=uh(r);return e.sparse?lh(t,r):t}let i=dh(e.column_type,t);return e.nullable&&(i=lh(i,n)),e.sparse?lh(i,r):i}function lh(e,t){if(Eh(t)==null)return Te([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function uh(e){let t=Eh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function dh(e,t){switch(e.type){case`Boolean`:if(t.type!==`Boolean`)throw Error(`expected Boolean value`);return Uint8Array.of(t.value?1:0);case`Integer`:{let e=kh(t),n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),n}case`Timestamp`:{if(t.type!==`Timestamp`||!Number.isSafeInteger(t.value))throw Error(`expected ${e.type} value`);if(t.value<0)throw Error(`Timestamp value must be a non-negative safe integer (dates before 1970 are not supported), got ${t.value}`);let n=new Uint8Array(8);return new DataView(n.buffer).setBigUint64(0,BigInt(t.value),!0),n}case`BigInt`:{let e=Ah(t),n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,e,!0),n}case`Double`:{if(t.type!==`Double`)throw Error(`expected Double value`);let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.value,!0),e}case`Text`:case`Json`:case`Enum`:if(t.type!==`Text`)throw Error(`expected ${e.type} value`);return Te([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return hh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return Te([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return ph(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return fh(e.columns,t.value)}}function fh(e,t){let n=eh(e,t.valuesByColumn?e.map(e=>t.valuesByColumn?.get(e.name)??(e.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`})):t.values),r=t.id?hh(t.id):new Uint8Array;return Te([Uint8Array.of(t.id?1:0),r,mh(n.byteLength),n])}function ph(e,t){let n=t.map(t=>dh(e,t));if(Eh(vh(e))!=null)return Te(n);let r=new Uint8Array(Math.max(0,t.length-1)*4),i=new DataView(r.buffer),a=4+r.byteLength;return n.slice(0,-1).forEach((e,t)=>{a+=e.length,i.setUint32(t*4,a,!0)}),Te([mh(t.length),r,...n])}function mh(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function hh(e){let t=Ze(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function gh(e){let t=vh(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function _h(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[..._h(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[..._h(e.column_type.element.columns)]}}:e.column_type}))}function vh(e){switch(e.type){case`Boolean`:return{tag:7};case`Integer`:return{tag:4};case`BigInt`:return{tag:5};case`Timestamp`:return{tag:3};case`Double`:return{tag:6};case`Text`:case`Json`:case`Enum`:return{tag:8};case`Bytea`:return{tag:9};case`Uuid`:return{tag:11};case`Array`:return{tag:14,inner:vh(e.element)};case`Row`:return{tag:9}}}function yh(e,t){let n=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e.type){case`Boolean`:return{type:`Boolean`,value:t[0]!==0};case`Integer`:return{type:`Integer`,value:n.getInt32(0,!0)};case`BigInt`:return{type:`BigInt`,value:n.getBigInt64(0,!0)};case`Double`:return{type:`Double`,value:n.getFloat64(0,!0)};case`Timestamp`:return{type:`Timestamp`,value:Number(n.getBigUint64(0,!0))};case`Text`:case`Json`:case`Enum`:return{type:`Text`,value:km.decode(bh(t))};case`Uuid`:return{type:`Uuid`,value:Th(t)};case`Bytea`:return{type:`Bytea`,value:bh(t).slice()};case`Array`:return{type:`Array`,value:Sh(e.element,t)};case`Row`:return{type:`Row`,value:xh(e.columns,t)}}}function bh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function xh(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Th(t.subarray(r,r+16)),r+=16);let a=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(r,!0);r+=4;let o=t.subarray(r,r+a);if(o.byteLength!==a)throw Error(`invalid nested row value length`);let s=Km(e,o);return qm({id:i,values:s},Jm(e,s))}function Sh(e,t){return Ch(e,t,t=>yh(e,t))}function Ch(e,t,n){let r=Eh(vh(e));if(r!=null){if(r===0)return[];if(t.length%r!==0)throw Error(`invalid fixed-width array byte length ${t.length}`);let e=[];for(let i=0;i<t.length;i+=r)e.push(n(t.subarray(i,i+r)));return e}if(t.length<4)throw Error(`invalid variable-width array byte length`);let i=Oh(t,0),a=4+Math.max(0,i-1)*4;if(a>t.length)throw Error(`invalid variable-width array offset table`);let o=[];for(let e=0;e<i;e+=1){let r=e===0?a:Oh(t,4+(e-1)*4),s=e===i-1?t.length:Oh(t,4+e*4);if(r>s||s>t.length)throw Error(`invalid variable-width array element offset`);o.push(n(t.subarray(r,s)))}return o}function wh(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Th(e){if(e.length>=16)return Ge(e,0);let t=Ie(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Eh(e){switch(e.tag){case 0:case 7:case 12:return 1;case 1:return 2;case 2:case 4:return 4;case 3:case 5:case 6:return 8;case 11:return 16;case 13:return(e.members??(e.inner?[e.inner]:[])).reduce((e,t)=>{if(e==null)return;let n=Eh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Eh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function Dh(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Eh(e[r].valueType);if(a==null)continue;let o={kind:`fixed`,logicalIndex:r,offset:i,size:a};t[r]=o,n.push(o),i+=a}for(let n=0;n<e.length;n+=1){if(Eh(e[n].valueType)!=null)continue;let i={kind:`variable`,logicalIndex:n,variableIndex:r.length};t[n]=i,r.push(i)}return{fields:t,fixed:n,variable:r,fixedSize:i}}function Oh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function kh(e){if(e.type!==`Integer`||!Number.isSafeInteger(e.value)||e.value<-2147483648||e.value>2147483647)throw Error(`Integer value must be a signed 32-bit integer`);return e.value}function Ah(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Om(e.value,`BigInt value`)}var jh=class{#e=[];u32Le(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`offset must be an unsigned 32-bit integer, got ${e}`);this.#e.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}finish(){return new Uint8Array(this.#e)}},Mh=new T({fatal:!0}),Nh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Ph(e,t){return t?Nh:e}function Fh(e,t,n,r=!1,i,a,o,s){let c=new Xh;return c.bytes(e),c.string(Ih(Ph(t,a))),n==null?c.none():c.some(e=>e.u64(n)),c.bool(r),i==null?c.none():c.some(e=>e.u64(i)),o==null?c.none():c.some(e=>e.bytes(Qh(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Ih(e){try{let t=Mh.decode(e);if(D(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Lh(e,t,n={}){let{limit:r,offset:i=0,orderBy:a=[],select:o,arraySubqueries:s=[],relation:c,partial:l=[]}=typeof n==`number`?{limit:n}:n;r!=null&&Bh(`query limit`,r),Bh(`query offset`,i);let u=new Xh;return u.string(e),u.vec((e,n)=>{let r=t[n];Hh(e,r)},t.length),u.vec(()=>void 0,0),u.none(),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec(()=>void 0,0),u.vec((e,t)=>{zh(e,s[t])},s.length),o==null?u.none():u.some(e=>{e.vec((e,t)=>{e.string(o[t])},o.length)}),u.vec((e,t)=>{let n=a[t];e.string(n.column),e.u64(n.direction===`Asc`?0:1)},a.length),u.none(),r==null?u.none():u.some(e=>e.u64(r)),u.u64(i),c==null?u.none():u.some(e=>e.bytes(Tm(c),!1)),Rh(u,l),u.finish()}function Rh(e,t){e.vec((e,n)=>{let r=t[n];if(e.string(r.column),r.kind===`json_pointer`){e.u64(3),e.string(r.at);return}Bh(`partial selection ${r.column} start`,r.from),Bh(`partial selection ${r.column} end`,r.to),e.u64(r.kind===`bytes`?0:r.kind===`text_utf16`?1:2),e.u64(r.from),e.u64(r.to)},t.length)}function zh(e,t){let{filters:n=[],select:r,orderBy:i=[],limit:a=null,offset:o=0,requirement:s=`Optional`,nestedArrays:c=[]}=t;a!=null&&Bh(`array subquery ${t.columnName} limit`,a),Bh(`array subquery ${t.columnName} offset`,o),e.string(t.columnName),e.string(t.table),e.string(t.innerColumn),e.string(t.outerColumn),e.vec((e,t)=>{Hh(e,n[t])},n.length),r==null?e.none():e.some(e=>{e.vec((e,t)=>{e.string(r[t])},r.length)}),e.vec((e,t)=>{let n=i[t];e.string(n.column),e.u64(n.direction===`Asc`?0:1)},i.length),a==null?e.none():e.some(e=>e.u64(a)),e.u64(o),e.u64(Vh(s)),e.vec((e,t)=>{zh(e,c[t])},c.length),Rh(e,[])}function Bh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function Vh(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function Hh(e,t){if(t.op===`All`||t.op===`Any`){e.u64(t.op===`All`?0:1),e.vec((e,n)=>Hh(e,t.predicates[n]),t.predicates.length);return}if(t.op===`Not`){e.u64(2),Hh(e,t.predicate);return}if(t.op===`In`){e.u64(5),Gh(e,t.column),e.vec((e,n)=>{e.u64(3),Jh(e,t.values[n])},t.values.length);return}if(t.op===`Contains`){e.u64(10),Gh(e,t.column),Kh(e,t.value);return}if(t.op===`IsNull`||t.op===`IsNotNull`){t.op===`IsNotNull`&&e.u64(2),e.u64(12),Gh(e,t.column);return}if(Uh(t)){Wh(e,t.column,t.op,t.value);return}throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Uh(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Wh(e,t,n,r){e.u64(qh(n)),Gh(e,t),Kh(e,r)}function Gh(e,t){e.u64(0),e.string(t)}function Kh(e,t){e.u64(3),Jh(e,t)}function qh(e){switch(e){case`Eq`:return 3;case`Ne`:return 4;case`Gt`:return 6;case`Gte`:return 7;case`Lt`:return 8;case`Lte`:return 9}}function Jh(e,t){if(t.type===`U64`){if(t.value<0n||t.value>(1n<<64n)-1n)throw Error(`U64 value must be an unsigned 64-bit integer`);e.u64(3),e.u64(t.value);return}if(t.type===`Nullable`){e.u64(13),t.value==null?e.none():e.some(e=>Jh(e,t.value));return}if(t.type===`Boolean`){e.u64(5),e.bool(t.value);return}if(t.type===`Integer`){if(!Number.isSafeInteger(t.value)||t.value<-2147483648||t.value>2147483647)throw Error(`Integer value must be a signed 32-bit integer`);e.u64(15),e.i64(t.value);return}if(t.type===`BigInt`){if(t.value<-(1n<<63n)||t.value>(1n<<63n)-1n)throw Error(`BigInt value must be a signed 64-bit integer`);e.u64(14),e.i64(t.value);return}if(t.type===`Timestamp`){if(!Number.isSafeInteger(t.value)||t.value<0)throw Error(`${t.type} value must be a non-negative safe integer`);e.u64(3),e.u64(t.value);return}if(t.type===`Double`){if(!Number.isFinite(t.value))throw Error(`Double value must be finite`);e.u64(4),e.f64Le(t.value);return}if(t.type===`Uuid`){e.u64(9);let n=Ze(t.value);if(!n)throw Error(`invalid uuid ${t.value}`);e.bytes(n);return}if(t.type===`Bytea`){e.u64(7),e.bytes(t.value);return}if(t.type===`Array`){e.u64(12),e.vec((e,n)=>Jh(e,t.value[n]),t.value.length);return}e.u64(6),e.string(t.value)}var Yh=64,Xh=class{chunks=[];parts=[];partsBytes=0;finish(){if(this.parts.length===0)return Uint8Array.from(this.chunks);this.flushChunks();let e=new Uint8Array(this.partsBytes),t=0;for(let n of this.parts)e.set(n,t),t+=n.byteLength;return e}flushChunks(){this.chunks.length!==0&&(this.pushPart(Uint8Array.from(this.chunks)),this.chunks=[])}pushPart(e){this.parts.push(e),this.partsBytes+=e.byteLength}u64(e){if(typeof e==`bigint`){if(e<0n||e>18446744073709551615n)throw Error(`u64 out of range: ${e}`);this.u64Big(e);return}if(!Number.isSafeInteger(e)||e<0)throw Error(`u64 must be a non-negative safe integer, got ${e}`);let t=e;do{let e=t&127;t=Math.floor(t/128),t!==0&&(e|=128),this.chunks.push(e)}while(t!==0)}i64(e){let t=Om(e,`i64`),n=t<0n?(-t<<1n)-1n:t<<1n;this.u64Big(n)}u64Big(e){let t=e;do{let e=Number(t&127n);t>>=7n,t!==0n&&(e|=128),this.chunks.push(e)}while(t!==0n)}u32Le(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw Error(`u32Le must be an unsigned 32-bit integer, got ${e}`);this.chunks.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}f64Le(e){let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e,!0),this.bytes(t,!1)}bool(e){this.chunks.push(e?1:0)}string(e){this.bytes($h(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<Yh){for(let t of e)this.chunks.push(t);return}this.flushChunks(),this.pushPart(new Uint8Array(e))}vec(e,t){this.u64(t);for(let n=0;n<t;n+=1)e(this,n)}map(e){this.u64(e)}set(e){this.u64(e)}none(){this.chunks.push(0)}some(e){this.chunks.push(1),e(this)}enumUnit(e){this.u64(e)}},Zh=class{bytesValue;offset=0;constructor(e){this.bytesValue=e}u64(){let e=this.readCanonicalU64();if(e>BigInt(2**53-1))throw Error(`postcard u64 exceeds Number.MAX_SAFE_INTEGER: ${e}`);return Number(e)}u64BigInt(){return this.readCanonicalU64()}i64(){let e=this.readCanonicalU64();return(e&1n)==0n?e>>1n:-(e+1n>>1n)}readCanonicalU64(){let e=0n;for(let t=0;t<10;t+=1){let n=this.readByte(),r=BigInt(n&127);if(t===9&&r>1n)throw Error(`postcard u64 overflow`);if(e|=r<<BigInt(t*7),!(n&128)){if(t!==0&&e<1n<<BigInt(t*7))throw Error(`postcard u64 is not minimally encoded`);return e}}throw Error(`postcard u64 overflow`)}string(){return Mh.decode(this.bytes())}bool(){let e=this.readByte();if(e===0)return!1;if(e===1)return!0;throw Error(`invalid bool tag ${e}`)}f64Le(){let e=this.bytesOfLength(8);return new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(0,!0)}bytes(e=!0){let t=e?this.u64():16;return this.bytesOfLength(t)}bytesAtMost(e,t){let n=this.u64();if(n>e)throw Error(`${t} exceeds maximum length of ${e} bytes`);return this.bytesOfLength(n)}bytesOfLength(e){let t=this.offset+e;if(t>this.bytesValue.length)throw Error(`postcard bytes overflow`);let n=this.bytesValue.subarray(this.offset,t);return this.offset=t,n}option(e){let t=this.readByte();if(t!==0){if(t!==1)throw Error(`invalid option tag ${t}`);return e(this)}}readVec(e){let t=this.u64();return Array.from({length:t},()=>e(this))}done(){return this.offset===this.bytesValue.length}readByte(){if(this.offset>=this.bytesValue.length)throw Error(`postcard eof`);return this.bytesValue[this.offset++]}};function Qh(e){return $h(JSON.stringify(e,b))}function $h(e){return new TextEncoder().encode(e)}var eg=new TextEncoder;function tg(e){return eg.encode(ge(e))}function ng(e){let t=new Xh;return t.string(e.table),Mm(t,[...e.descriptor]),Ie(t.finish())}var rg=3600*1e3,ig=500,ag=`jazz-http-stream-endpoints`,og=`endpoints`;function sg(){return globalThis.indexedDB!==void 0}function cg(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(ag,1);r.onupgradeneeded=()=>r.result.createObjectStore(og),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function lg(e,t){let n=cg();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(og,e).objectStore(og));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var ug=`jazz-stream-endpoint:`,dg=600*1e3;function fg(){if(!(typeof document>`u`))try{return globalThis.localStorage??void 0}catch{return}}function pg(e,t=Date.now()){let n=fg();if(n)try{let r=n.getItem(ug+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(ug+e);return}return i===`stream`}catch{return}}function mg(e,t,n){let r=fg();if(r)try{r.setItem(ug+e,`${t}:${n}`)}catch{try{r.removeItem(ug+e)}catch{}}}async function hg(e,t=Date.now()){let n,r=await Promise.race([lg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),ig)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?mg(e,`stream`,r.until):mg(e,`none`,t+dg),i}function gg(e,t=Date.now()){return mg(e,`stream`,t+rg),lg(`readwrite`,n=>n.put(t+rg,e)).then(()=>void 0,()=>void 0)}function _g(e){return mg(e,`none`,Date.now()+dg),lg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var vg=`x-jazz-stream-key`;function yg(e,t){let n=new Uint8Array(5+t.byteLength);return n[0]=e,new DataView(n.buffer).setUint32(1,t.byteLength,!1),n.set(t,5),n}function bg(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}var xg=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?bg([this.buffered,e]):e;let t=[],n=0;for(;this.buffered.byteLength-n>=5;){let e=new DataView(this.buffered.buffer,this.buffered.byteOffset+n).getUint32(1,!1);if(this.buffered.byteLength-n<5+e)break;t.push({kind:this.buffered[n],payload:this.buffered.slice(n+5,n+5+e)}),n+=5+e}return this.buffered=this.buffered.slice(n),t}get pending(){return this.buffered.byteLength}},Sg=new TextEncoder,Cg=new TextDecoder;function wg(e){let t=new URL(e);return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t.pathname=t.pathname.replace(/\/ws\/?$/,`/stream`),t.toString()}var Tg=class{listeners=new Map;addEventListener(e,t){let n=this.listeners.get(e)??[];n.push(t),this.listeners.set(e,n)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}},Eg=4*1024*1024,Dg=(e,t)=>fetch(e,t),Og=class extends Tg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=Dg){super(),this.request=t,this.streamUrl=wg(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?Sg.encode(e):e;this.queued.push(yg(1,t)),this.flush()}close(){if(this.readyState>=2)return;let e=this.session;if(!e)return this.finish(1e3,`client closed`);this.finish(1e3,`client closed`,!1),this.request(`${this.streamUrl}/${encodeURIComponent(e.id)}`,{method:`DELETE`,credentials:`same-origin`,headers:{[vg]:e.key},signal:AbortSignal.timeout?.(jg)}).catch(()=>void 0).finally(()=>this.abort.abort())}async run(){try{let e=await this.request(this.streamUrl,{method:`POST`,credentials:`same-origin`,signal:this.abort.signal});if(!e.ok||!e.body)throw Error(`HTTP stream refused (${e.status})`);let t=e.body.getReader(),n=new xg;for(;;){let{done:e,value:r}=await t.read();if(e)break;for(let e of n.push(r)){if(this.readyState>=2)return;this.receive(e.kind,e.payload)}}this.fail(1006,`HTTP stream ended`)}catch(e){if(this.readyState>=2)return;this.emit(`error`,e),this.fail(1006,e instanceof Error?e.message:String(e))}}receive(e,t){if(e===0)this.session=JSON.parse(Cg.decode(t)),this.readyState=1,this.emit(`open`);else if(e===1){let e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.emit(`message`,{data:e})}else if(e===2){let{code:e,reason:n}=JSON.parse(Cg.decode(t));this.finish(e,n)}}async flush(){if(!(this.sending||!this.session)){this.sending=!0;try{for(;this.queued.length>0&&this.readyState===1;){let e=0,t=0;for(;e<this.queued.length&&(e===0||t+this.queued[e].byteLength<=Eg);)t+=this.queued[e].byteLength,e+=1;let n=bg(this.queued.splice(0,e)),r=await this.request(`${this.streamUrl}/${encodeURIComponent(this.session.id)}`,{method:`POST`,credentials:`same-origin`,headers:{"Content-Type":`application/octet-stream`,[vg]:this.session.key},body:n});if(!r.ok)throw Error(`HTTP stream send refused (${r.status})`)}}catch(e){this.emit(`error`,e),this.close()}finally{this.sending=!1}}}fail(e,t){this.finish(e,t)}finish(e,t,n=!0){this.readyState>=2||(this.readyState=3,n&&this.abort.abort(),this.emit(`close`,{code:e,reason:t}))}},kg=new Set,Ag=new Map,jg=1e4,Mg=new Map,Ng=`x-jazz-stream`,Pg=new Set,Fg=`x-jazz-store-error`,Ig=new Set;async function Lg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(jg)});if(n.status===503&&n.headers.get(Fg)===`1`){let t=await n.text().catch(()=>``);return t&&!Ig.has(`${e}\n${t}`)&&(Ig.add(`${e}\n${t}`),console.error(`jazz: the backend at ${e} can't serve: ${t}`)),`other`}return n.body?.cancel().catch(()=>void 0),n.status===403?`refused`:n.status===426?n.headers.get(Ng)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function Rg(e,t,n){let r=await Lg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return Ag.delete(e),Mg.delete(e),r===`refused`&&!Pg.has(e)&&(Pg.add(e),console.warn(`jazz: the backend at ${e} refuses this page's origin (403). If a proxy rewrites the Host header, set the backend's publicUrl or allowedOrigins.`)),r;let i=(Ag.get(e)??0)+1;Ag.set(e,i);let a=t?(Mg.get(e)??0)+1:0;t?Mg.set(e,a):Mg.delete(e);let o=a>=2;return i<3&&!o?r:(Ag.delete(e),Mg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${jg/1e3} s, although the backend answers and upgrades them: something in between (a proxy or dev server) doesn't pass WebSocket upgrades on. Syncing over the HTTP stream instead, for as long as this client runs.`),`stream-in-between`):(console.warn(`jazz: ${i} WebSockets in a row to ${e} failed, although the backend answers and upgrades them: something in between (a proxy or dev server) doesn't pass WebSocket upgrades on. Syncing over the HTTP stream instead, for as long as this client runs.`),`stream-in-between`))}function zg(e,t={}){let n=t.fetch??Dg,r=t.describeFailedUpgrade;return class extends Tg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,kg.has(e)){this.openStream();return}if(!sg()){this.inner=this.openNative();return}let t=pg(e);if(t===!0){kg.add(e),this.openStream();return}if(t===!1){this.inner=this.openNative();return}hg(e).then(t=>{this.closedEarly||(t?(kg.add(e),this.openStream()):this.inner=this.openNative())})}get readyState(){return this.inner?this.probing?0:this.inner.readyState:this.closedEarly?3:0}send(e){if(!this.inner)throw Error(`WebSocket is not open`);this.inner.send(e)}close(){if(this.closedByClient=!0,this.settled=!0,this.probing=!1,clearTimeout(this.openDeadline),this.abort.abort(),this.inner)return this.inner.close();this.closedEarly||(this.closedEarly=!0,queueMicrotask(()=>this.emit(`close`,{code:1e3,reason:``})))}openStream(){let e=new Og(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(kg.delete(this.url),_g(this.url))}),this.inner=e,this.forward(e)}openNative(){let t=new e(this.url);t.binaryType=`arraybuffer`;let i=!1,a,o=(e,t,i=!1)=>{if(clearTimeout(this.openDeadline),!this.settled){if(a){a[e]??=t;return}a={[e]:t},this.probing=!0,Rg(this.url,i,n).then(async e=>{let t=e===`stream`||e===`stream-in-between`,n=!(!i&&(e===`upgrades`||e===`other`))||this.settled?void 0:await r?.(this.url,this.abort.signal).catch(()=>void 0);if(this.probing=!1,!this.settled){if(this.settled=!0,t){kg.add(this.url),e===`stream`&&gg(this.url),this.openStream();return}if(n){this.emit(`error`,Error(n)),this.emit(`close`,{code:1006,reason:n});return}a?.error!==void 0&&this.emit(`error`,a.error),this.emit(`close`,a?.close??{code:1006,reason:``})}})}};return this.openDeadline=setTimeout(()=>{o(`close`,{code:1006,reason:`the WebSocket upgrade got no answer`},!0),t.close()},jg),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,Ag.delete(this.url),Mg.delete(this.url),this.settled=!0,this.emit(`open`))}),t.addEventListener(`message`,e=>{a||this.emit(`message`,e)}),t.addEventListener(`error`,e=>{i?this.emit(`error`,e):o(`error`,e)}),t.addEventListener(`close`,e=>{i?this.emit(`close`,e):o(`close`,e)}),t}forward(e){e.addEventListener(`open`,()=>this.emit(`open`)),e.addEventListener(`message`,e=>this.emit(`message`,e)),e.addEventListener(`error`,e=>this.emit(`error`,e)),e.addEventListener(`close`,e=>this.emit(`close`,e))}}}var Bg=`jazz_renewal`,Vg=`X-Jazz-Renew`,Hg=2048;function Ug(e){let t=new Zh(e);if(t.u64()!==64)throw Error(`not a renew-soon frame`);let n=t.string(),r=t.u64();if(!t.done()||!n||n.length>Hg)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function Wg(e){let t=new Xh;return t.u64(65),t.string(e),t.finish()}function Gg(e){return e[0]===64}function Kg(e){try{let t=new URL(e);return/\/ws\/?$/.test(t.pathname)?(t.protocol=t.protocol===`wss:`?`https:`:t.protocol===`ws:`?`http:`:t.protocol,t.pathname=t.pathname.replace(/\/ws\/?$/,`/accounts/backend-user`),t.search=``,t.hash=``,t.toString()):null}catch{return null}}function qg(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var Jg=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function Yg(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function Xg(e){return e.code===`auth_failed`&&e.retry===`after_resume`&&e.message.startsWith(`reauthenticate:`)}function Zg(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}var Qg=2048,$g=12e4,e_=1e3,t_=7,n_=4496,r_=1<<20,i_=5,a_=5,o_=2*1024*1024,s_=4096;function c_(e){u_(e);let t=new Xh;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>o_)throw Error(`websocket frame batch exceeds maximum length of ${o_} bytes`);return n}function l_(e){if(e.byteLength>o_)throw Error(`websocket frame batch exceeds maximum length of ${o_} bytes`);let t=new Zh(e),n=t.u64();if(n===0||n>s_)throw Error(`websocket frame batch exceeds frame-count limit of ${s_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(o_,`websocket frame`));return w_(t,`websocket frame batch`),r}function u_(e){if(e.length===0||e.length>s_)throw Error(`websocket frame batch exceeds frame-count limit of ${s_}`);for(let t of e)if(t.byteLength>o_)throw Error(`websocket frame exceeds maximum length of ${o_} bytes`)}function d_(e=n_){x_(e,`client wire features`);let t=new Xh;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var f_=0,p_=1;function m_(e){if(e[0]!==f_)return!1;let t=new Zh(e);t.u64();let{min:n,max:r}=S_(t);return n===6&&r===6&&C_(t),!0}function h_(e){if(e[0]!==p_)return!1;let t=new Zh(e);return t.u64(),__(t),!0}function g_(e){let t=new Zh(e),n=t.u64();if(n!==1)throw Error(`expected WireFrame::Error, got tag ${n}`);return __(t)}function __(e){let t={code:U_(e.u64()),retry:W_(e.u64()),message:e.string()};return w_(e,`WireFrame::Error`),t}function v_(e){return e.code===`auth_failed`?S(e.message):null}var y_=class{url;socket;onFrame;onError;onTerminal;localFeatures;opened;resolveNegotiation;rejectNegotiation;negotiated=!1;closing=!1;terminated=!1;lastInbound=performance.now();silenceTimer;handshakeTimer;renewalUrl;renewalTimer;constructor(e){this.url=e.endpointUrl;let t=e.WebSocket??Xe(this.url)??B_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??4496)|Qg,this.renewalUrl=D_(e.authJson)?Kg(this.url):null,x_(this.localFeatures,`client wire features`),this.socket=new t(this.url),this.socket.binaryType=`arraybuffer`,this.watchHandshake(e.handshakeTimeoutMs??1e4),this.opened=new Promise((e,t)=>{this.resolveNegotiation=e,this.rejectNegotiation=t}),G_(this.socket).then(()=>{this.closing||(this.socket.send(E_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(c_([d_(this.localFeatures)])))},e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:String(e)}),this.close()}),this.socket.addEventListener(`message`,e=>{this.lastInbound=performance.now(),this.handleMessage(e.data).catch(e=>{this.reportTerminal({code:`protocol_error`,retry:`never`,message:e instanceof Error?e.message:String(e)},void 0,!1),this.close()})}),this.socket.addEventListener(`error`,e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:`websocket transport error`})}),this.socket.addEventListener(`close`,e=>{let t=T_(e);this.reportTerminal({code:`websocket_closed`,retry:`later`,message:`websocket closed (code=${t.code??`unknown`}, reason=${t.reason??`none`})`})})}async send(e){await this.sendBatch([e])}async sendBatch(e){await this.ready();let t=[],n=a_;for(let r of e){let e=r.byteLength+i_;t.length>0&&(t.length>=s_||n+e>r_)&&(this.socket.send(c_(t)),t=[],n=a_),t.push(r),n+=e}t.length>0&&this.socket.send(c_(t))}ready(){return this.opened}get hasNegotiated(){return this.negotiated}close(){if(!this.closing){this.closing=!0,clearTimeout(this.silenceTimer),clearTimeout(this.handshakeTimer),clearTimeout(this.renewalTimer),this.reportTerminal({code:`websocket_closed`,retry:`never`,message:`websocket closed before server hello`},Error(`websocket closed before server hello`),!1,!1);try{this.socket.close()}catch{}}}reportTerminal(e,t=Error(e.message),n=!0,r=!0){this.terminated||(this.terminated=!0,clearTimeout(this.silenceTimer),clearTimeout(this.handshakeTimer),clearTimeout(this.renewalTimer),this.rejectNegotiation(t),n&&this.onError?.(e),r&&this.onTerminal?.(e))}watchHandshake(e){this.handshakeTimer=setTimeout(()=>{this.handshakeTimer=setTimeout(()=>{this.negotiated||this.terminated||(this.reportTerminal({code:`websocket_silent`,retry:`later`,message:`the server did not answer the connection within ${Math.round(e/1e3)} s`}),this.close())},e_)},e)}scheduleRenewal({session:e,renewInMs:t}){clearTimeout(this.renewalTimer);let n=this.renewalUrl;n&&(this.renewalTimer=setTimeout(()=>{this.renewalTimer=void 0,!(this.closing||this.terminated)&&k_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send(Wg(e))}).catch(()=>{})},Math.min(t,2**31-1)))}watchSilence(e=!1){if(clearTimeout(this.silenceTimer),this.closing||this.terminated)return;let t=performance.now()-this.lastInbound;if(t>=12e4&&!e){this.silenceTimer=setTimeout(()=>this.watchSilence(!0),e_);return}if(t>=12e4){this.reportTerminal({code:`websocket_silent`,retry:`later`,message:`the server sent nothing for ${Math.round(t/1e3)} s, not even a heartbeat`}),this.close();return}this.silenceTimer=setTimeout(()=>this.watchSilence(),$g-t)}async handleMessage(e){for(let t of l_(await z_(e))){if(this.closing)return;if(m_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=b_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&~Qg});continue}if(!(this.negotiated&&t.byteLength===1&&t[0]===t_)){if(this.negotiated&&this.renewalUrl&&Gg(t)){this.scheduleRenewal(Ug(t));continue}if(!this.negotiated){if(h_(t)){let e=g_(t);if(v_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new Jg(e)),this.close();return}this.reportTerminal({code:`protocol_error`,retry:`never`,message:`websocket received semantic frame before server hello`},void 0,!1),this.close();return}if(h_(t)){let e=g_(t);if(Yg(e)){this.reportTerminal(e),this.close();return}this.onError?.(e);continue}this.onFrame(t)}}}};function b_(e,t=n_){let n=new Zh(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=S_(n);if(r!==6||i!==6)throw Error(`server must advertise exactly wire protocol 6, got ${r}..=${i}`);let{features:a,role:o,authority:s}=C_(n),c=a&~BigInt(t);if(c!==0n)throw Error(`server accepted unsupported wire features 0x${c.toString(16)}`);if(o!==1)throw Error(`expected WirePeerRole::Core server hello`);return{protocolVersion:6,features:Number(a),authority:s}}function x_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function S_(e){return{min:e.u64(),max:e.u64()}}function C_(e){let t=e.u64BigInt(),n=e.u64(),r=e.option(e=>{let t=e.bytes();if(t.byteLength!==16)throw Error(`WireHello.authority.node must be exactly 16 bytes, got ${t.byteLength}`);return{node:t,epoch:e.u64BigInt()}});return w_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function w_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function T_(e){if(!e||typeof e!=`object`)return{};let t=e;return{code:typeof t.code==`number`?t.code:void 0,reason:typeof t.reason==`string`?t.reason:void 0}}function E_(e,t,n,r=!1){let i=JSON.parse(e),a=new T().decode(t),o=K_(i)??R_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Bg]:1}:{}})}function D_(e){if(!e)return!1;try{let t=JSON.parse(e);return t.backend_session!=null&&t.jwt_token==null&&t.admin_secret==null&&t.backend_secret==null}catch{return!1}}var O_=3e4;async function k_(e,t){return A_(qg(e),()=>j_(e,t))}async function A_(e,t){let n=globalThis.navigator?.locks;if(!n)return t();let r,i=()=>r??=t();try{await n.request(e,()=>{let e;return Promise.race([i().catch(()=>void 0),new Promise(t=>{e=setTimeout(t,O_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function j_(e,t){try{let n=await Ue(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[Vg]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function M_(e){let t=JSON.parse(e);if(t.admin_secret)return{};if(typeof t.backend_secret==`string`){let e=t.backend_session,n=e&&typeof e==`object`?e.claims:void 0;return n&&typeof n==`object`&&!Array.isArray(n)?n:{}}if(typeof t.jwt_token!=`string`)return{};let n=Me(t.jwt_token);if(!n)return{};if(n.iss===`urn:jazz:local-first`||n.iss===`urn:jazz:anonymous`){let{jazz_pub_key:e,...t}=n;return Se(t)}return Se(n)}function N_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!F_(n))return new TextEncoder().encode(ze(`urn:jazz:system`,`system`));let r=L_(n),i=null;try{i=D(new T({fatal:!0}).decode(t))}catch{}if(i?.account_id&&r){let e=D(r);if(e.issuer!==i.issuer||e.user_id!==i.user_id||e.account_id!==void 0&&e.account_id!==i.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return r?new TextEncoder().encode(r):t}function P_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!F_(t)&&delete t.jwt_token,JSON.stringify(t)}function F_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&P(t.issuer)&&P(t.user_id)}function I_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||L_(t)!==null}function L_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&F_(e)){let t=e.backend_session;return ze(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=Me(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,r=t?.sub;if(typeof n==`string`&&typeof r==`string`&&P(n)&&P(r))return ze(n,r)}return null}function R_(e){return D(e)?.user_id??null}async function z_(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw Error(`expected binary websocket message, got ${typeof e}`)}function B_(e){let t=H_();return V_(e)?zg(t):t}function V_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function H_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function U_(e){switch(e){case 0:return`unsupported_protocol_version`;case 1:return`unsupported_feature`;case 2:return`malformed_frame`;case 3:return`auth_failed`;case 4:return`backpressure`;case 5:return`internal`;case 6:return`not_ready`;default:throw Error(`unknown WireErrorCode discriminant ${e}`)}}function W_(e){switch(e){case 0:return`never`;case 1:return`after_auth`;case 2:return`after_resume`;case 3:return`later`;default:throw Error(`unknown WireRetry discriminant ${e}`)}}function G_(e){return e.readyState===1?Promise.resolve():new Promise((t,n)=>{let r=!1,i=e=>{r||(r=!0,e())};e.addEventListener(`open`,()=>i(t)),e.addEventListener(`error`,e=>i(()=>n(e))),e.addEventListener(`close`,()=>i(()=>n(Error(`websocket closed before open`))))})}function K_(e){let t=e.sub;if(typeof t==`string`&&P(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=q_(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&P(e))return e}return null}function q_(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(J_(t[1]));return typeof e.sub==`string`&&P(e.sub)?e.sub:null}catch{return null}}function J_(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=t.padEnd(Math.ceil(t.length/4)*4,`=`);return typeof atob==`function`?atob(n):Buffer.from(n,`base64`).toString(`binary`)}var Y_=20,X_=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,Z_=16,Q_={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},$_=250,ev=4;function tv(e){return typeof e?.poll==`function`}function nv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function rv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function iv(e,t){let n=e.message;return Xg(e)?{kind:`reauthenticate`,message:n}:v_(e)?{kind:`authRejected`,message:n}:Yg(e)||e.code===`internal`&&e.retry===`later`?t?{kind:`network`,message:n}:{kind:e.code===`not_ready`?`serverNotReady`:`refused`,message:n}:Zg(e)?{kind:`network`,message:n}:{kind:`fatal`,message:n}}function av(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function ov(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var sv=new T({fatal:!0}),cv=new WeakMap;function lv(e,t,n,r,i,a=!1){try{return uv(e,t,n,r,i,a)}catch(e){throw Fe(e)}}function uv(e,t,n,r,i,a){if(i&&a)throw Error(`A native runtime cannot be both self-signed and backend-scoped`);if(a){if(!e.openPersistentAsBackend)throw Error(`Native runtime does not support explicit backend opens; rebuild the matching Jazz native artifact`);return e.openPersistentAsBackend(t,n,r)}if(i){if(!e.openPersistentWithSelfSignedProof)throw Error(`Native runtime does not support self-signed client opens; rebuild the matching Jazz native artifact`);return e.openPersistentWithSelfSignedProof(t,n,r,i.token,i.appId,i.claimedAuthor)}if(!e.openPersistent)throw Error(`Native runtime does not expose persistent storage`);return e.openPersistent(t,n,r)}function dv(e,t,n,r,i=!1){if(r&&i)throw Error(`A native runtime cannot be both self-signed and backend-scoped`);if(i){if(!e.openMemoryAsBackend)throw Error(`Native runtime does not support explicit backend opens; rebuild the matching Jazz native artifact`);return e.openMemoryAsBackend(t,n)}if(!r)return e.openMemory(t,n);if(!e.openMemoryWithSelfSignedProof)throw Error(`Native runtime does not support self-signed client opens; rebuild the matching Jazz native artifact`);return e.openMemoryWithSelfSignedProof(t,n,r.token,r.appId,r.claimedAuthor)}function fv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var pv=class e{schema;node;auxiliaryReceiveDeadlines=new Map;pendingNativeAdmissionCancels=new Set;pendingNativeReadCancels=new Set;db;schemaBytes;configBytes;peerIdentity;upstreamPrincipal=null;selfSignedClientProof;scopeIsolatedRelay;schemaHash;trustedBackend;transactionOwner;pendingTxs;completedTxs;writes;pendingLocalSettlements=new Set;localSettlementListeners=new Set;pendingStreamingMutations=new Set;streamingFinalization=Promise.resolve();ownerRuntime;slowQueryApp;slowQueryConsoleDetail;get preparationOwner(){return this.ownerRuntime}readAuthorizationHost;subscriptions=new Map;subscriptionPool;pooledSubscriptions=new Map;drainingSubscriptionPool=!1;subscriptionPoolDirty=!1;authFailureCallback=null;mutationErrorCallback=null;serverTransportErrorCallback=null;deliveredMutationErrors=new Set;serverTransport=null;peerUpstreamAttached=!1;nonDurableClient=!1;serverCarrier=null;webSocket;serverCarrierPromise=null;serverConnectionAttempt=null;serverReplacementRetirement=null;serverTransportError=null;serverTransportErrorWaiters=[];localStorageFailure=null;localStorageFailureWaiters=new Set;serverTransportWorkEpoch=0;serverTransportWorkWaiters=[];serverEndpointUrl=null;serverAuthJson=null;link=null;linkStatus=null;linkInputs=[];linkStepping=!1;linkAttemptId=null;linkTimer=null;linkConnection=null;linkFailure=null;upstreamRefusal=null;linkCloseReason=`server transport replaced`;serverTransportErrorRetrying=!1;serverTransportErrorAwaitsAuth=!1;nativeAuthRefusalRenewable=!1;nativeLinkEverConnected=!1;nativeLinkPoll=null;firstLoadWaitSeen=!1;remoteLink=new xm(()=>this.readRemoteLinkState());linkStatusPublisher=new ms(()=>this.upstreamLinkStatus(),us);syncStatusPublisher=new ms(()=>this.readSyncStatus(),(e,t)=>ps(e.uploads,t.uploads)&&us(e.link,t.link));lastFailure=null;failingAs=null;pendingInboundServerFrames=[];serverInboundRouting=Promise.resolve();serverInboundProcessed=!1;peerTransportWorkListeners=new Set;auxiliaryTraceListeners=new Set;queryCoverageTraceListeners=new Set;peerTransportActivityEpoch=0;peerTransportProcessedActivityEpoch=0;coreTickScheduled=!1;coreDeadlineTimer;coreDeadlineAt;coreTickAgain=!1;coreOperation=null;pendingTransportRetirements=new Map;serverPumpScheduled=!1;serverPumpRunning=!1;serverPumpAgain=!1;serverConnectionGeneration=0;closed=!1;foregroundLeaseQuiesced=!1;foregroundLeaseCapture=null;foregroundLeaseDraining=!1;physicalCloseStarted=!1;nextSubscriptionId=1;static fromDb(t,n,r,i,a,o,s){return new e(null,n,r,i,a,o,{db:t,selfSignedClientProof:s?.selfSignedClientProof,scopeIsolatedRelay:s?.scopeIsolatedRelay,slowQueryLog:s?.slowQueryLog})}migrations;registerSchemaView(t,n){return new e(null,t,this.node,this.peerIdentity,1,!0,{db:this.db.registerSchema(tg(t),n?Qh(n):void 0),backendMode:this.trustedBackend,owner:this})}constructor(e,t,n,r,i,a,o){if(this.schema=t,this.node=n,this.ownerRuntime=o?.owner?.ownerRuntime??this,this.readAuthorizationHost=o?.owner?.readAuthorizationHost??o?.readAuthorizationHost??`client-local`,this.transactionOwner=o?.owner?.transactionOwner??{pendingTxs:new Map,completedTxs:new Map,writes:new Map},this.pendingTxs=this.transactionOwner.pendingTxs,this.completedTxs=this.transactionOwner.completedTxs,this.writes=this.transactionOwner.writes,this.schemaBytes=tg(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=Fh(n,r,void 0,a,o?.initialSyncFlushEvery,o?.selfSignedClientProof,o?.migrations,o?.systemNode),this.peerIdentity=r,this.migrations=o?.owner?.migrations??o?.migrations,this.schemaHash=ve(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=lv(e,o.persistentPath,this.schemaBytes,this.configBytes,o?.selfSignedClientProof,o?.backendMode)}else{if(!e)throw Error(`Native runtime constructor required for memory storage`);this.db=dv(e,this.schemaBytes,this.configBytes,o?.selfSignedClientProof,o?.backendMode)}if(o?.owner)return;this.slowQueryApp=o?.slowQueryLog?.appId,this.slowQueryConsoleDetail=o?.slowQueryLog?.consoleDetail;let s=o?.slowQueryLog?.thresholdMs;if(s!==void 0){if(!Number.isFinite(s)||s<0)throw Error(`slowQueryThresholdMs must be a non-negative number of milliseconds`);this.db.setSlowQueryThresholdMs?.(s)}if(typeof this.db.setTickScheduler!=`function`)throw Error(`Native runtime requires db.setTickScheduler`);this.db.setTickScheduler(((e,t)=>{let n=typeof e==`string`?e:t;(n===`immediate`||n===`deferred`||n===`after-current-turn`||typeof n==`string`&&n.startsWith(`after:`))&&this.scheduleCoreWake(n)})),this.db.onUpstreamFailure?.(e=>{if(!e)return this.nativeAuthRefusalRenewable=!1,this.clearRemoteServerTransportError();let t=e.code?gm({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:p(),features:this.nativeWireFeatures()}}async connectUpstreamPeer(e){return this===this.ownerRuntime?(this.peerUpstreamAttached=!0,e?this.connectNegotiatedUpstream({protocolVersion:6,features:e.features,authority:e}):await this.db.connectUpstream()):await this.ownerRuntime.connectUpstreamPeer(e)}onPeerTransportWork(e){return this===this.ownerRuntime?(this.peerTransportWorkListeners.add(e),()=>{this.peerTransportWorkListeners.delete(e)}):this.ownerRuntime.onPeerTransportWork(e)}onAuxiliaryTrace(e){return this===this.ownerRuntime?(this.auxiliaryTraceListeners.add(e),this.serverTransport?.setAuxiliaryTraceEnabled?.(!0),()=>{this.auxiliaryTraceListeners.delete(e),this.auxiliaryTraceListeners.size===0&&this.serverTransport?.setAuxiliaryTraceEnabled?.(!1)}):this.ownerRuntime.onAuxiliaryTrace(e)}onQueryCoverageTrace(e){return this===this.ownerRuntime?(this.queryCoverageTraceListeners.add(e),()=>this.queryCoverageTraceListeners.delete(e)):this.ownerRuntime.onQueryCoverageTrace(e)}emitQueryCoverageTrace(e){if(this!==this.ownerRuntime){this.ownerRuntime.emitQueryCoverageTrace(e);return}let t={stage:e,peerActivityEpoch:this.peerTransportActivityEpoch,peerProcessedActivityEpoch:this.peerTransportProcessedActivityEpoch};for(let e of this.queryCoverageTraceListeners)e(t)}notifyPeerTransportActivity(){if(this!==this.ownerRuntime)return this.ownerRuntime.notifyPeerTransportActivity();this.peerTransportActivityEpoch+=1,this.notifyPeerTransportWork(!0)}async progressPeerTransport(){if(this!==this.ownerRuntime)return this.ownerRuntime.progressPeerTransport();let e=this.peerTransportActivityEpoch;await this.runCoreTick(),!this.closed&&(this.peerTransportProcessedActivityEpoch=Math.max(this.peerTransportProcessedActivityEpoch,e))}retirePeerTransport(e){return this===this.ownerRuntime?(this.auxiliaryReceiveDeadlines.get(e)?.close(),this.auxiliaryReceiveDeadlines.delete(e),this.coreOperation?new Promise((t,n)=>{let r=this.pendingTransportRetirements.get(e)??[];r.push({resolve:t,reject:n}),this.pendingTransportRetirements.set(e,r)}):(e.close(),Promise.resolve())):this.ownerRuntime.retirePeerTransport(e)}setNonDurableClient(){if(this!==this.ownerRuntime)return this.ownerRuntime.setNonDurableClient();if(!this.db.setNonDurableClient)throw Error(`Native runtime does not expose non-durable client mode`);this.db.setNonDurableClient(),this.nonDurableClient=!0}foregroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.foregroundTxTimeHighWater();if(!this.db.foregroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water`);return this.db.foregroundTxTimeHighWater()}quiesceForegroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.quiesceForegroundTxTimeHighWater();if(this.foregroundLeaseCapture)return this.foregroundLeaseCapture;if(this.closed)throw Error(`Native runtime is already closed`);this.closed=!0,this.clearCoreDeadline(),this.foregroundLeaseQuiesced=!0,this.foregroundLeaseDraining=!0;let e=this.captureForegroundTxTimeHighWater().finally(()=>{this.foregroundLeaseDraining=!1,this.clearCoreDeadline()});return this.foregroundLeaseCapture=e,e}coreProgressAllowed(){return!this.closed||this.foregroundLeaseDraining}async captureForegroundTxTimeHighWater(){return await Promise.all(this.pendingStreamingMutations),await Promise.all(this.pendingLocalSettlements),await this.coreOperation?.completion.catch(()=>void 0),await this.foregroundTxTimeHighWater()}seedForegroundTxTimeHighWater(e){if(this!==this.ownerRuntime)return this.ownerRuntime.seedForegroundTxTimeHighWater(e);if(!this.db.seedForegroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water seeding`);this.db.seedForegroundTxTimeHighWater(e)}setLargeValueStagingPolicy(e,t,n){if(this!==this.ownerRuntime)return this.ownerRuntime.setLargeValueStagingPolicy(e,t,n);if(!this.db.setLargeValueStagingPolicy)throw Error(`Native runtime does not expose large-value staging policy`);this.db.setLargeValueStagingPolicy(e,t,n)}async evictExpiredStagedLargeValues(){if(this!==this.ownerRuntime)return await this.ownerRuntime.evictExpiredStagedLargeValues();if(!this.db.evictExpiredStagedLargeValues)throw Error(`Native runtime does not expose large-value staging maintenance`);return await this.db.evictExpiredStagedLargeValues()}async acceptPeer(e={},t,n=this.peerIdentity){if(this!==this.ownerRuntime)return this.ownerRuntime.acceptPeer(e,t,n);if(this.closed)throw Error(`Native runtime is closed`);return this.runWhenCoreIdle(async()=>{if(this.closed)throw Error(`Native runtime is closed`);let r;this.coreOperation={kind:`admission`,completion:new Promise(e=>{r=e})};try{let r=this.selfSignedClientProof,i;if(r){if(!Nb(n,this.peerIdentity))throw _y();if(!this.db.acceptSubscriberWithSelfSignedProof)throw Error(`Native runtime does not support self-signed subscriber admission; rebuild the matching Jazz WASM artifact`);i=await this.db.acceptSubscriberWithSelfSignedProof(e,r.token,r.appId,r.claimedAuthor,t)}else{if(!this.db.acceptSubscriber)throw Error(`Native runtime does not expose subscriber links`);i=await this.db.acceptSubscriber(n,e,t)}if(this.closed)throw i.close(),Error(`Native runtime closed during subscriber admission`);return i}finally{this.drainTransportRetirements(),this.coreOperation=null,r(),this.coreTickAgain&&!this.closed&&this.scheduleCoreTick()}})}async runWhenCoreIdle(e){let t=this.ownerRuntime;for(;t.coreOperation;)await t.coreOperation.completion;return e()}setRemoteLinkHint(e){if(this!==this.ownerRuntime)return this.ownerRuntime.setRemoteLinkHint(e);this.closed||this.db.setRemoteLinkHint?.(Q_[e])}remoteLinkState(){return this===this.ownerRuntime?this.readRemoteLinkState():this.ownerRuntime.remoteLinkState()}onRemoteLinkStateChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onRemoteLinkStateChange(e,t);return}this.remoteLink.subscribe(e,t),this.startNativeLinkPoll()}startNativeLinkPoll(){!this.db?.nativeConnectionStatus||this.nativeLinkPoll||this.closed||!this.linkHasListeners()||(this.nativeLinkPoll=setInterval(()=>{this.linkHasListeners()?this.linkChanged():this.stopNativeLinkPoll()},$_))}noteFirstLoadWait(e){if(!Mv(e))return;let t=this.ownerRuntime;t.firstLoadWaitSeen||(t.firstLoadWaitSeen=!0,t.startNativeLinkPoll())}stopNativeLinkPoll(){this.nativeLinkPoll&&clearInterval(this.nativeLinkPoll),this.nativeLinkPoll=null}linkHasListeners(){return this.syncStatusPublisher.hasListeners||this.linkStatusPublisher.hasListeners||this.firstLoadWaitSeen&&this.remoteLink.hasListeners}linkChanged(){this===this.ownerRuntime&&this.noteLinkFailure(),this.remoteLink.changed(),this.linkStatusPublisher.changed(),this.syncStatusPublisher.changed()}upstreamLinkStatus(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamLinkStatus();if(this.closed)return K(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?K(`disconnected`):e.authRejected?K(`auth`):e.connected?cs:this.serverTransportError?this.serverTransportErrorRetrying?K(`network`):hm(this.serverTransportError)?K(`authority-changed`,!1):K(`stopped`):ss:os:this.linkStatus?.phase===`stopped`&&hm(this.upstreamRefusal)?K(`authority-changed`,!1):ls(this.linkStatus)}canClearClientStorage(){return this===this.ownerRuntime?typeof this.db?.deleteNativeStore==`function`:this.ownerRuntime.canClearClientStorage()}async clearClientStorage(){if(this!==this.ownerRuntime)return this.ownerRuntime.clearClientStorage();if(!this.db?.deleteNativeStore)throw Error(`Runtime does not support client storage reset.`);let e=this.db.deleteNativeStore();return this.closed=!0,e}uploadStatus(){return this===this.ownerRuntime?this.closed?ns:this.db?.uploadStatus?.()??ns:this.ownerRuntime.uploadStatus()}lastLinkFailure(){return this===this.ownerRuntime?(this.noteLinkFailure(),this.lastFailure):this.ownerRuntime.lastLinkFailure()}noteLinkFailure(){let e=this.upstreamLinkStatus(),t=e.state===`offline`?e.reason:null;if(t===this.failingAs)return;this.failingAs=t;let n=is(e,(this.linkFailure??this.serverTransportError)?.message);n&&(this.lastFailure=n)}onUpstreamLinkStatusChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onUpstreamLinkStatusChange(e,t);return}this.linkStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()}onSyncStatusChange(e,t){if(this!==this.ownerRuntime){this.ownerRuntime.onSyncStatusChange(e,t);return}this.syncStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()}readSyncStatus(){return{link:this.upstreamLinkStatus(),uploads:this.uploadStatus()}}readRemoteLinkState(){if(this.closed)return`unavailable`;let e=this.db?.nativeConnectionStatus?.();if(e)return e.configured?e.explicitlyOffline||e.authRejected?`unavailable`:e.connected?(this.nativeLinkEverConnected=!0,`connected`):this.serverTransportError||this.nativeLinkEverConnected?`unavailable`:`connecting`:`none`;switch(this.linkStatus?.phase??`noServer`){case`noServer`:return`none`;case`live`:return`connected`;case`connecting`:return this.serverTransportError?`unavailable`:`connecting`;default:return`unavailable`}}async waitForUpstreamServerConnection(){if(this!==this.ownerRuntime)return await this.ownerRuntime.waitForUpstreamServerConnection();if(!this.serverCarrierPromise){if(this.serverTransportError)throw this.serverTransportError;return}if(this.linkStatus?.outagePublished&&this.serverTransportError)throw this.serverTransportError;let e=this.linkStatus?.consecutiveFailures?this.waitForServerTransportError(`global`):null;try{await(e?Promise.race([this.serverCarrierPromise,e.promise]):this.serverCarrierPromise)}finally{e?.cancel()}}isClosed(){return this.ownerRuntime.closed}async close(){if(this!==this.ownerRuntime){this.closeRuntimeState();return}if(!this.physicalCloseStarted&&!(this.closed&&!this.foregroundLeaseQuiesced)){this.physicalCloseStarted=!0,this.closed=!0,this.clearCoreDeadline();for(let e of this.pendingNativeAdmissionCancels)e();for(let e of this.pendingNativeReadCancels)e();await this.foregroundLeaseCapture?.catch(()=>void 0),this.pendingStreamingMutations.size>0&&await Promise.all(this.pendingStreamingMutations),this.pendingLocalSettlements.size>0&&await Promise.all(this.pendingLocalSettlements),await this.coreOperation?.completion.catch(()=>void 0),this.closeRuntimeState(!0),await this.db.close?.()}}discard(){this.closeRuntimeState()}closeRuntimeState(e=!1){if(this.closed&&!e)return!1;this.closed=!0,this.clearCoreDeadline();for(let e of this.pendingNativeAdmissionCancels)e();for(let e of this.pendingNativeReadCancels)e();for(let[e,t]of this.subscriptions)this.terminateSubscription(e,t);if(this!==this.ownerRuntime)return this.subscriptions.clear(),!1;for(let e of this.writes.values())e.close?.();this.subscriptions.clear(),this.pendingTxs.clear(),this.completedTxs.clear(),this.writes.clear(),this.serverConnectionGeneration+=1,this.clearLinkTimer(),this.linkAttemptId=null,this.settleLinkConnection(Error(`server transport disconnected`)),this.stopNativeLinkPoll(),this.linkChanged();let t=this.serverConnectionAttempt;this.serverConnectionAttempt=null,t&&this.finishServerConnectionAttempt(t,Error(`runtime closed`)),this.serverCarrierPromise=null,this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.peerTransportWorkListeners.clear(),this.localSettlementListeners.clear(),this.pendingInboundServerFrames.length=0;let n=this.serverTransport;return this.serverTransport=null,n&&this.retirePeerTransport(n).catch(Ib),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null,!0}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Q(n):y(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Q(r):void 0,a=xv(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=wv(n),l=vv(n);bv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=$y(this.table(e),t);if(u){this.assertTransactionWriteIdentity(u,s?void 0:o);let r=this.db.insertInTransaction(u.id,e,d,{rowId:i,branch:l?.head,updatedAtMs:c??void 0});if(!(r instanceof Uint8Array))throw Error(`Native runtime transaction insert did not return a row id`);let a=this.rowStateFromValues(e,r,t);return u.hasStagedMutations=!0,{id:a.id,values:a.values,kind:`staged`,openTransactionId:_v(n)}}let f=py(`Insert`,()=>nv(this.db.insert(e,d,{rowId:i,author:s?void 0:o,attribution:s,branch:l?.head,updatedAtMs:c??void 0})));return this.finishInsert(e,i??f.rowId,t,f)}async streamingMutation(e,t,n,r,i,a,o){let s=this.db.beginStreamingMutation,c=e===`insert`?`Insert`:e===`update`?`Update`:`Upsert`;this.assertMutationAdmission(c);let l=this.currentTx(a,c),u=xv(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=vv(a),m=wv(a);if(bv(f,p),l&&(this.assertTransactionAttribution(l,f),this.assertTransactionWriteIdentity(l,f?void 0:d)),!s)throw Error(`Native runtime does not expose streaming mutations`);let h=this.table(t),g=h.columns.find(e=>e.name===r)?.column_type.type;if(g!==`Text`&&g!==`Json`&&g!==`Bytea`)throw Error(`Streaming insert requires a Text, Json, or Bytea column: ${t}.${r}`);let _=o?Q(o):y(16),v=e===`insert`?eb(h,n,r,t):tb(h,n,r),b=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!b.finishInTransaction)throw await b.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let x=this.ownerRuntime,S,C=new Promise(e=>{S=e});x.pendingStreamingMutations.add(C);let w=new TextEncoder,T=async e=>{let t=64*1024;for(let n=0;n<e.byteLength;n+=t)await b.push(e.subarray(n,n+t))},E=``;try{for await(let e of fm(i))if(typeof e==`string`){if(g===`Bytea`)throw Error(`Bytea streams require Uint8Array chunks`);let t=E+e;E=``;let n=t.charCodeAt(t.length-1);n>=55296&&n<=56319&&(E=t.slice(-1),t=t.slice(0,-1)),t.length>0&&await T(w.encode(t))}else if(e instanceof Uint8Array)E&&=(await T(w.encode(E)),``),await T(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await T(w.encode(E));let e=x.streamingFinalization,t,n=new Promise(e=>{t=e});x.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await b.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await b.finish())}finally{t()}return{id:Ce(_),...r}}catch(e){throw await b.abort(),e}finally{S(),x.pendingStreamingMutations.delete(C)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Q(t),a=xv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=wv(r),l=vv(r);bv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=$y(this.table(e),n);if(u){this.assertTransactionWriteIdentity(u,s?void 0:o),this.db.restoreInTransaction(u.id,e,i,d,{branch:l?.head,updatedAtMs:c??void 0});let t=this.rowStateFromValues(e,i,n);return u.hasStagedMutations=!0,{id:t.id,values:t.values,kind:`staged`,openTransactionId:_v(r)}}let f=py(`Restore`,()=>nv(this.db.restore(e,i,d,{author:s?void 0:o,attribution:s,branch:l?.head,updatedAtMs:c??void 0})));return this.finishInsert(e,i,n,f)}update(e,t,n,r){this.assertMutationAdmission(`Update`);let i=Q(t),a=xv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=wv(r),l=vv(r);bv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=nb(this.table(e),n);if(u)return this.assertTransactionWriteIdentity(u,s?void 0:o),this.db.updateInTransaction(u.id,e,i,d,{head:l?.head,base:l?.base,updatedAtMs:c??void 0}),u.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(r)};let f=py(`Update`,()=>nv(this.db.update(e,i,d,{author:s?void 0:o,attribution:s,head:l?.head,base:l?.base,updatedAtMs:c??void 0})));return this.finishMutation(f)}updateLargeValues(e,t,n,r,i){this.assertMutationAdmission(`Update`);let a=Q(t),o=wv(i),s=vv(i),c=this.currentTx(i,`Update`);if(s)throw Error(`Partial-value updates (applyDiffs, editedFrom) are not yet supported in branch views.`);if(c){let t=xv(i);this.applySessionClaims(t);let s=this.trustedWriteIdentity(t),l=this.backendAttribution(i);this.assertTransactionAttribution(c,l),this.assertTransactionWriteIdentity(c,l?void 0:s);let u=this.db.updateLargeValuesInTransaction;if(!u)throw my(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=nb(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(i)}}if(yv(i,this.peerIdentity))throw Error(`Partial-value updates (applyDiffs, editedFrom) do not yet support a session or attributed identity outside a transaction.`);let l=this.db.updateLargeValues;if(!l)throw Error(`Native runtime does not support typed partial-value updates.`);let u=nb(this.table(e),n),d=py(`Update`,()=>l.call(this.db,e,a,u,r,o??void 0));return this.finishMutation(d)}upsert(e,t,n,r){this.assertMutationAdmission(`Upsert`);let i=Q(t),a=this.table(e),o=xv(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=wv(r),u=vv(r);bv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=nb(a,n)}catch(e){throw my(`Upsert`,hy(gy(e)))}if(d)return this.assertTransactionWriteIdentity(d,c?void 0:s),this.db.upsertInTransaction(d.id,e,i,f,{head:u?.head,base:u?.base,updatedAtMs:l??void 0}),d.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(r)};let p=py(`Upsert`,()=>nv(this.db.upsert(e,i,f,{author:c?void 0:s,attribution:c,head:u?.head,base:u?.base,updatedAtMs:l??void 0})));return this.finishMutation(p)}delete(e,t,n){this.assertMutationAdmission(`Delete`),this.table(e);let r=Q(t),i=xv(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=wv(n),c=vv(n);bv(o,c);let l=this.currentTx(n,`Delete`);if(l&&this.assertTransactionAttribution(l,o),l)return this.assertTransactionWriteIdentity(l,o?void 0:a),this.db.deleteInTransaction(l.id,e,r,{head:c?.head,base:c?.base,updatedAtMs:s??void 0}),l.hasStagedMutations=!0,{kind:`staged`,openTransactionId:_v(n)};let u=py(`Delete`,()=>nv(this.db.delete(e,r,{author:o?void 0:a,attribution:o,head:c?.head,base:c?.base,updatedAtMs:s??void 0})));return this.finishMutation(u)}canInsertLocally(e,t,n){return`unknown`}canReadLocally(e,t,n){return`unknown`}canUpdateLocally(e,t,n,r){return`unknown`}canDeleteLocally(e,t,n){return`unknown`}isScopedPermissionAdvice(e){return this.readAuthorizationHost!==`trusted-serving`||!e?!1:!(this.trustedBackend&&e.issuer===`urn:jazz:system`&&e.user_id===`system`&&Ve(e,ct(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return Fv(JSON.stringify(e))}catch{return null}}explainReadClauses(e,t,n){if(!this.trustedBackend)throw Error(`explain runs only on a trusted backend`);let r=this.db.explainReadClauses;if(!r)throw Error(`explain is not supported yet by this runtime`);let i=Fv(JSON.stringify(n));if(!i?.identity)throw Error(`explain needs a user to explain for`);return r.call(this.db,e,t,i.identity,i.claims)}requestInsertPermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestInsertPermissionAdvice;if(!i)return Promise.resolve(`unknown`);let a=$y(this.table(e),t,e);return this.withPermissionAdviceTimeout(()=>i.call(this.db,e,a,r?.identity,r?.claims))}requestReadPermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestReadPermissionAdvice;return i?this.withPermissionAdviceTimeout(()=>i.call(this.db,e,Q(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}requestUpdatePermissionAdvice(e,t,n,r){if(this.isScopedPermissionAdvice(r)&&!this.trustedBackend)return Promise.resolve(`unknown`);let i=this.delegatedPermissionAdviceSession(r);if(this.isScopedPermissionAdvice(r)&&!i)return Promise.resolve(`unknown`);let a=this.db.requestUpdatePermissionAdvice;if(!a)return Promise.resolve(`unknown`);let o=nb(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Q(t),o,i?.identity,i?.claims))}requestDeletePermissionAdvice(e,t,n){if(this.isScopedPermissionAdvice(n)&&!this.trustedBackend)return Promise.resolve(`unknown`);let r=this.delegatedPermissionAdviceSession(n);if(this.isScopedPermissionAdvice(n)&&!r)return Promise.resolve(`unknown`);let i=this.db.requestDeletePermissionAdvice;return i?this.withPermissionAdviceTimeout(()=>i.call(this.db,e,Q(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}captureSnapshot(){if(this!==this.ownerRuntime)return this.ownerRuntime.captureSnapshot();if(this.closed)return Promise.reject(Error(`Cannot capture a snapshot: native runtime is closed`));if(!this.db.captureSnapshot)return Promise.reject(new ye);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(sv.decode(e)))}beginTransaction(e,t,n){if(this!==this.ownerRuntime)return this.ownerRuntime.beginTransaction(e,t,n);if(this.closed)throw Error(`Begin transaction failed: native runtime is closed`);if(this.pendingTxs.has(t)||this.completedTxs.has(t))throw Error(`Begin transaction failed: transaction ${t} has already been opened`);let r=xv(n);this.applySessionClaims(r);let i=this.trustedWriteIdentity(r),a=this.backendAttribution(n),o=a?void 0:i;return this.db.beginTransaction(t,e,o,a),this.pendingTxs.set(t,{id:t,kind:e,identity:o,requestSession:o?r??void 0:void 0,attribution:a,hasStagedMutations:!1}),t}hasStagedTransactionWrites(e){return this===this.ownerRuntime?this.pendingTxs.get(e)?.hasStagedMutations:this.ownerRuntime.hasStagedTransactionWrites(e)}commitTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.commitTransaction(e);if(this.closed)throw Error(`Commit transaction failed: native runtime is closed`);let t=this.pendingTxs.get(e);if(!t)throw Error(Ev(e,this.completedTxs));if(!t.hasStagedMutations&&t.kind===`mergeable`)throw Error(`Commit transaction failed: empty mergeable transaction has no committed unit; roll it back instead`);let n=this.db.commitTransaction(e,t.kind);this.pendingTxs.delete(e),this.completedTxs.set(e,{kind:t.kind,state:`committed`}),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork();let r=gv(n,this.writes);return this.nonDurableClient&&this.trackLocalSettlement(r),r}async waitForTransaction(e,t,n={}){if(this!==this.ownerRuntime)return this.ownerRuntime.waitForTransaction(e,t,n);typeof e!=`string`&&(e=await e);let r=this.writes.get(e);if(!r)throw Error(`Wait for transaction failed: unknown transaction ${e}`);let{signal:i}=n,a=n.observeOnly?r.wait(t,!0):r.wait(t);if(a.catch(()=>void 0),n.ready)if(i){let e,t=new Promise(t=>{e=()=>t(),i.addEventListener(`abort`,e,{once:!0})});try{await Promise.race([n.ready,t])}finally{i.removeEventListener(`abort`,e)}}else await n.ready;let o=a.then(()=>`settled`);for(o.catch(()=>void 0);;){if(this.closed)throw Error(`Wait for transaction failed: native runtime is closed`);i?.throwIfAborted(),this.throwServerTransportErrorForTier(t,!0);let n=this.serverTransportWorkEpoch;this.startServerPump(),this.throwServerTransportErrorForTier(t,!0);let r=this.waitForServerTransportError(t,!0),a=this.waitForServerTransportWork(t,n),s=this.waitForLocalStorageFailure(t),c;try{let e=[o];if(r&&e.push(r.promise),s&&e.push(s.promise),a&&e.push(a.promise.then(()=>`work`)),i&&e.push(new Promise(e=>{let t=()=>e(`work`);i.addEventListener(`abort`,t,{once:!0}),c=()=>i.removeEventListener(`abort`,t)})),await Promise.race(e)===`settled`){this.pumpSubscriptions();return}}catch(t){throw uy(e,t)||t}finally{c?.(),r?.cancel(),a?.cancel(),s?.cancel()}}}rollbackTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.rollbackTransaction(e);let t=this.pendingTxs.get(e);if(!t)throw Error(Dv(e,this.completedTxs));try{this.db.rollbackTransaction(e)}finally{this.pendingTxs.delete(e)}return this.completedTxs.set(e,{kind:t.kind,state:`rolled_back`}),Promise.resolve(!0)}async query(e,t,n,r){if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);Nv(n,r),this.noteFirstLoadWait(r),Ov(r,this.pendingTxs,this.completedTxs);let i=Fv(t);Uv(e);let a=sy(e),o=kv(r,this.pendingTxs),s=jv(n,Bv(a),r),c=this.nativeReadContext(i,o),l=Hv(a,this.schema);if(await this.ensureClientSessionClaims(i),await this.waitForStrictRemoteQueryTransport(n),await this.processPendingPeerActivityBeforeRead(),this.closed||this.ownerRuntime.closed)return[];if(o||this.attachLocalReadCoverageInBackground(n,l,i),this.emitQueryCoverageTrace(`attach`),Vv(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),ub(sb(e),this.schema,ty(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),ub(sb(e),this.schema,ty(a,this.schema).rootColumns)}let u=ty(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),cb(ob(d),this.schema,u)}createSubscription(e,t,n,r){Nv(n,r),this.noteFirstLoadWait(r);let i=Fv(t),a=this.nativeReadContext(i);Uv(e);let o=this.nextSubscriptionId++,s=jv(n,Bv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:ty(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=Hv(e,this.schema),u=e=>{let t=Eb(e);if(c.cancelled||this.closed||this.ownerRuntime.closed){zv(t);return}c.source=t,c.callback&&this.startSubscriptionReader(o,c)},d=e=>{c.cancelled||this.failSubscription(c,e instanceof Error?e:Error(String(e)))},f=()=>{if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);if(c.cancelled)throw Error(`native operation was cancelled`);let e=this.subscribeForContext(l,s,a);return ov(e)?this.awaitNativeOperation(e,c.openingAbort.signal):e};try{let e=this.ensureClientSessionClaims(i),t=e instanceof Promise?e.then(f):f();t instanceof Promise?t.then(u).catch(d):u(t)}catch(e){d(e)}return o}executeSubscription(e,t){let n=this.subscriptions.get(e);if(n){if(n.callback)throw Error(`Subscription has already been activated`);if(n.callback=t,n.terminalError){this.deliverSubscriptionFailure(n);return}this.startSubscriptionReader(e,n)}}unsubscribe(e){let t=this.subscriptions.get(e);t&&this.terminateSubscription(e,t)}connect(e,t){if(this!==this.ownerRuntime)return this.ownerRuntime.connect(e,t);if(this.db?.reconnectNativeUpstream){this.db.reconnectNativeUpstream(),this.nativeLinkEverConnected=!1,this.linkChanged();return}let n=P_(t);this.assertCredentialKeepsPrincipal(n),this.nativeWireFeatures(),this.link??=this.createUpstreamLink(),this.serverEndpointUrl=e,this.serverAuthJson=n,this.linkCloseReason=`server transport replaced`,this.stepLink(this.linkStatus&&this.linkStatus.phase!==`noServer`?{type:`setOffline`,offline:!1}:{type:`serverConfigured`,configured:!0})}createUpstreamLink(){if(!this.db.createUpstreamLink)throw Error(`native runtime binding does not expose the upstream link machine; install the matching Jazz native runtime package`);return this.db.createUpstreamLink(Math.floor(Math.random()*(2**53-1)))}stepLink(e){if(this.linkInputs.push(e),!this.linkStepping){this.linkStepping=!0;try{for(let e=this.linkInputs.shift();e;e=this.linkInputs.shift()){if(this.closed||!this.link)continue;let t=JSON.parse(this.link.handle(Date.now(),JSON.stringify(e))),n=this.linkStatus;this.linkStatus=t.status;for(let e of t.actions)this.runLinkAction(e);this.applyLinkStatus(n,t.status);for(let e of t.events)e.type===`authFailed`&&this.authFailureCallback?.(e.reason);this.linkChanged()}}catch(e){throw this.linkInputs.length=0,e}finally{this.linkStepping=!1}}}runLinkAction(e){switch(e.type){case`connect`:this.runLinkAttempt(e.attempt);return;case`close`:{this.linkAttemptId===e.attempt&&(this.linkAttemptId=null);let t=this.serverConnectionAttempt;t?.id===e.attempt&&this.finishServerConnectionAttempt(t,Error(this.linkCloseReason),!1),this.pendingInboundServerFrames.length=0,this.serverPumpScheduled=!1,this.serverPumpAgain=!1;return}case`armTimer`:{this.clearLinkTimer();let t=e.token;this.linkTimer={token:t,handle:setTimeout(()=>{this.linkTimer?.token===t&&(this.linkTimer=null,this.stepLink({type:`timerFired`,token:t}))},e.afterMs)};return}case`cancelTimer`:this.linkTimer?.token===e.token&&this.clearLinkTimer();return}}applyLinkStatus(e,t){let n=this.linkFailure??Error(t.reason??`server transport failed`);switch(t.phase){case`live`:e?.outagePublished&&this.forgetServerTransportError();return;case`connecting`:case`backoff`:this.linkConnection||this.awaitLinkConnection(),t.outagePublished&&!e?.outagePublished&&this.handleServerTransportError(Error(n.message),void 0,!0);return;case`awaitingCredential`:case`stopped`:if(e?.phase!==t.phase){let e=t.phase===`awaitingCredential`&&!t.terminal;this.handleServerTransportError(n,void 0,e),this.serverTransportErrorAwaitsAuth=e,this.settleLinkConnection(n)}return;case`offline`:case`noServer`:this.settleLinkConnection(Error(`server transport disconnected`));return}}awaitLinkConnection(){let e=new Promise((e,t)=>{this.linkConnection={resolve:e,reject:t}});e.catch(()=>void 0),this.serverCarrierPromise=e}settleLinkConnection(e){let t=this.linkConnection;this.linkConnection=null,e instanceof Error?(this.serverCarrierPromise=null,t?.reject(e)):(this.serverCarrierPromise=Promise.resolve(e),t?.resolve(e))}clearLinkTimer(){this.linkTimer&&clearTimeout(this.linkTimer.handle),this.linkTimer=null}endLinkAttempt(e,t,n){if(e.finished)return;let r=e.id===this.linkAttemptId;if(this.finishServerConnectionAttempt(e,t,!1),!(!r||this.closed)){this.linkAttemptId=null,this.pendingInboundServerFrames.length=0,this.linkFailure=t;try{this.stepLink({type:`ended`,attempt:e.id,failure:n})}finally{this.linkFailure=null}}}runLinkAttempt(e){this.linkAttemptId=e,this.linkConnection||this.awaitLinkConnection();let t=this.serverEndpointUrl,n=this.serverAuthJson;(async()=>{for(let e=this.serverReplacementRetirement;e;e=this.serverReplacementRetirement)await e,this.serverReplacementRetirement===e&&(this.serverReplacementRetirement=null);this.closed||this.linkAttemptId!==e||t===null||n===null||this.startServerConnection(e,t,n)})().catch(t=>{if(this.closed||this.linkAttemptId!==e)return;this.linkAttemptId=null;let n=t instanceof Error?t:Error(gy(t));this.linkFailure=n;try{this.stepLink({type:`ended`,attempt:e,failure:{kind:`fatal`,message:n.message}})}finally{this.linkFailure=null}})}startServerConnection(e,t,n){this.serverConnectionGeneration+=1;let r=this.serverConnectionGeneration,i=this.nativeWireFeatures(),a=N_(n,this.peerIdentity);this.linkStatus?.outagePublished||this.forgetServerTransportError(),this.upstreamRefusal=null,this.linkChanged();let o,s=new Promise(e=>{o=e}),c=null,l=e=>{if(!c)return;let t=this.serverTransportError&&!this.linkStatus?.outagePublished?{kind:`fatal`,message:e.message}:iv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new y_({WebSocket:this.webSocket,endpointUrl:t,peerIdentity:a,features:i,authJson:n,requestedLink:this.scopeIsolatedRelay?`scope_isolated_client_relay`:void 0,onFrame:e=>{r===this.serverConnectionGeneration&&(this.pendingInboundServerFrames.push(e),this.notifyServerTransportWork(),this.scheduleServerPump(),this.serverPumpRunning&&queueMicrotask(()=>{!this.serverPumpRunning||this.pendingInboundServerFrames.length===0||this.routePendingInboundServerFrames().catch(e=>this.handleServerTransportError(e,r))}))},onError:e=>{Yg(e)||e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`||l(e)},onTerminal:l});c={id:e,generation:r,carrier:u,terminal:s,resolveTerminal:o,finished:!1,outcome:null,transport:null,retirement:null,admission:null},this.serverConnectionAttempt=c,this.serverCarrier=u;let d=()=>!this.closed&&r===this.serverConnectionGeneration&&u===this.serverCarrier&&c===this.serverConnectionAttempt;Promise.race([u.ready(),s.then(e=>{throw e})]).then(async t=>{if(!d()){u.close();return}if(!this.trustedBackend&&(await this.runWhenCoreIdle(()=>{if(d())return this.installClientSessionClaims(M_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw vy(`connecting the negotiated upstream transport`,e)});c.admission=i;let a=await Promise.race([i.then(e=>({type:`admitted`,transport:e})),s.then(e=>({type:`terminal`,error:e}))]);if(a.type===`terminal`)return;c.admission=null;let o=a.transport;if(!d()){u.close(),c.finished?await c.retirement:await this.retirePeerTransport(o);return}c.transport=o,this.serverTransport=o,o.setAuxiliaryTraceEnabled?.(this.auxiliaryTraceListeners.size>0),this.watchAuxiliaryOutbound(o,u,r).catch(e=>this.handleServerTransportError(e,r));let l=this.pumpServerTransport();l.catch(e=>this.handleServerTransportError(e,r)),this.pumpSubscriptions(),this.pinUpstreamPrincipal(n),this.stepLink({type:`admitted`,attempt:e}),await Promise.race([l.catch(()=>void 0),new Promise(e=>setTimeout(e,0))]),d()&&this.settleLinkConnection(u)}).catch(e=>{let t=e instanceof Error?e:Error(gy(e));this.endLinkAttempt(c,t,{kind:`fatal`,message:t.message})})}async connectNegotiatedUpstream(e){let t=e.authority,n=this.db.connectUpstreamWithSession;if(!t||!n)return await this.db.connectUpstream();let r=p();return await n.call(this.db,e.protocolVersion,e.features,t.node,t.epoch,this.node,r)}nativeWireFeatures(){if(!this.db.wireFeatures)throw Error(`native runtime binding does not expose its wire feature mask; install the matching Jazz native runtime package`);let e=this.db.wireFeatures();if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`native binding returned invalid wire feature mask ${e}`);return e}nativeUpstreamConfigured(){return this===this.ownerRuntime?this.db.nativeConnectionStatus?.().configured===!0:this.ownerRuntime.nativeUpstreamConfigured()}async disconnect(e={}){if(this!==this.ownerRuntime)return this.ownerRuntime.disconnect(e);if(this.db?.disconnectNativeUpstream){this.db.disconnectNativeUpstream(),this.linkChanged();return}let t=this.serverTransport,n=this.serverConnectionAttempt,r=n?.transport;this.linkCloseReason=`server transport disconnected`,this.stepLink({type:`setOffline`,offline:!0}),this.linkCloseReason=`server transport replaced`,this.serverEndpointUrl=null,this.serverAuthJson=null,this.serverReplacementRetirement||this.forgetServerTransportError(),e.rejectWaiters??!0?this.resolveServerTransportErrorWaiters(Error(`server transport disconnected`)):this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.serverTransport=null;let i=[];n?.retirement&&i.push(n.retirement),t&&t!==r&&i.push(Promise.resolve().then(()=>this.retirePeerTransport(t))),this.linkChanged(),await Promise.all(i)}updateAuth(e){if(this!==this.ownerRuntime)return this.ownerRuntime.updateAuth(e);if(this.nativeAuthRefusalRenewable=!1,this.db?.rejectAuthUpdate)return this.db.rejectAuthUpdate();let t=P_(e);this.assertCredentialKeepsPrincipal(t),this.serverEndpointUrl&&(this.serverAuthJson=t,this.stepLink({type:`credentialUpdated`}))}assertCredentialKeepsPrincipal(e){if(this!==this.ownerRuntime)return this.ownerRuntime.assertCredentialKeepsPrincipal(e);if(!this.upstreamPrincipal)return;let t=P_(e);if(!I_(t))return;let n;try{n=N_(t,this.peerIdentity)}catch{n=null}if(!n||!Nb(n,this.upstreamPrincipal))throw _y(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){this.upstreamPrincipal||!I_(e)||(this.upstreamPrincipal=N_(e,this.peerIdentity))}onAuthFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onAuthFailure(e);this.authFailureCallback=e,this.db.onAuthRejected?.(e=>{this.nativeAuthRefusalRenewable=m(S(e)),this.authFailureCallback?.(e)})}onMutationError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onMutationError(e);this.mutationErrorCallback=e,this.db.onMutationError(e=>this.deliverMutationError(e))}onStorageFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onStorageFailure(e);this.db.onStorageFailure?.(e)}onServerTransportError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onServerTransportError(e);this.serverTransportErrorCallback=e}endCredentialWait(){if(this!==this.ownerRuntime)return this.ownerRuntime.endCredentialWait();this.nativeAuthRefusalRenewable=!1;let e=this.serverTransportError;!e||!this.serverTransportErrorRetrying||(this.serverTransportErrorAwaitsAuth=!1,this.handleServerTransportError(e,this.serverConnectionGeneration,!1))}reportRemoteServerTransportError(e,t=!1){if(this!==this.ownerRuntime)return this.ownerRuntime.reportRemoteServerTransportError(e,t);this.handleServerTransportError(e,this.serverConnectionGeneration,t)}clearRemoteServerTransportError(){if(this!==this.ownerRuntime)return this.ownerRuntime.clearRemoteServerTransportError();this.serverTransportError&&(this.forgetServerTransportError(),this.linkChanged())}reportLocalStorageFailure(e){if(this!==this.ownerRuntime)return this.ownerRuntime.reportLocalStorageFailure(e);if(e===null){this.localStorageFailure=null;return}let t=Object.assign(Error(e),{code:`storage`});this.localStorageFailure=t;for(let e of this.localStorageFailureWaiters)e(t);this.localStorageFailureWaiters.clear()}waitForLocalStorageFailure(e){if(e!==`local`||!this.nonDurableClient)return null;if(this.localStorageFailure)return{promise:Promise.reject(this.localStorageFailure),cancel:()=>{}};let t,n=new Promise((e,n)=>{t=n});return this.localStorageFailureWaiters.add(t),{promise:n,cancel:()=>this.localStorageFailureWaiters.delete(t)}}reportRemoteMutationError(e){if(this!==this.ownerRuntime)return this.ownerRuntime.reportRemoteMutationError(e);this.deliverMutationError(e)}async waitForPendingWrites(e=`global`,t={}){if(this!==this.ownerRuntime)return this.ownerRuntime.waitForPendingWrites(e,t);if(!this.db.waitForPendingWrites)throw Error(`Native runtime lacks graceful sync shutdown; rebuild its bindings`);let{throughOutage:n=!1,signal:r}=t;r?.throwIfAborted(),await this.flushLocalSettlements(),this.throwServerTransportErrorForTier(e,n),this.startServerPump();let i=this.waitForServerTransportError(e,n),a=new AbortController,o=new Promise((e,t)=>{a.signal.addEventListener(`abort`,()=>t(a.signal.reason),{once:!0})});o.catch(()=>void 0);let s=new Promise(e=>{a.signal.addEventListener(`abort`,()=>e(),{once:!0})}),c=()=>a.abort(r?.reason);r?.addEventListener(`abort`,c,{once:!0});try{let{sync:n}=t,r=n?this.db.waitForSync?this.db.waitForSync(e,this.trustedWriteIdentity(xv(n.writeContext))??null):this.db.waitForPendingWrites(e,s,!0):this.db.waitForPendingWrites(e,s),c=this.awaitNativeRead(Promise.resolve(r).then(e=>e??new Uint8Array),void 0,a.signal);c.catch(()=>void 0);let l=[c,o];i&&l.push(i.promise),await Promise.race(l)}finally{i?.cancel(),r?.removeEventListener(`abort`,c),a.abort(Error(`waitForPendingWrites ended`))}}async flushLocalSettlements(){if(this!==this.ownerRuntime)return this.ownerRuntime.flushLocalSettlements();this.pendingLocalSettlements.size>0&&await Promise.all(this.pendingLocalSettlements)}onLocalSettlementChange(e){return this===this.ownerRuntime?(this.localSettlementListeners.add(e),e(this.pendingLocalSettlements.size>0),()=>this.localSettlementListeners.delete(e)):this.ownerRuntime.onLocalSettlementChange(e)}deliverMutationError(e){let t=e.transaction.transactionId;this.deliveredMutationErrors.has(t)||(this.deliveredMutationErrors.add(t),this.mutationErrorCallback?.(e))}trackLocalSettlement(e){if(this!==this.ownerRuntime)return this.ownerRuntime.trackLocalSettlement(e);let t;t=this.waitForTransaction(e,`local`,{observeOnly:!0}).catch(()=>void 0).finally(()=>{if(this.pendingLocalSettlements.delete(t),this.pendingLocalSettlements.size===0)for(let e of this.localSettlementListeners)e(!1)});let n=this.pendingLocalSettlements.size===0;if(this.pendingLocalSettlements.add(t),n)for(let e of this.localSettlementListeners)e(!0)}finishInsert(e,t,n,r){let i=gv(r,this.writes);this.nonDurableClient&&this.trackLocalSettlement(i),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork();let a=this.rowStateFromValues(e,t,n);return{id:a.id,values:a.values,kind:`committed`,txId:i}}finishMutation(e){let t=gv(e,this.writes);return this.nonDurableClient&&this.trackLocalSettlement(t),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),{kind:`committed`,txId:t}}assertMutationAdmission(e){if(this.ownerRuntime.closed)throw Error(`${e} failed: native runtime is closed`)}rowStateFromValues(e,t,n){return Wc(e,Ce(t),this.table(e).columns,n)}async readPlainRows(e,t,n,r){let i=this.nativeReadContext(n,r);return this.readRowsForContextAsync(e,t,i,r?.id)}readRowsForContext(e,t,n){let r=this.db.all(e,{...t,sync:!0},void 0,this.nativeReadAuthor(n),this.nativeReadClaims(n));if(typeof r.then==`function`)throw Error(`native read is asynchronous; use the asynchronous read boundary`);if(tv(r))throw Error(`native read is pending; use the asynchronous read boundary`);return r}async readRowsForContextAsync(e,t,n,r){return this.awaitNativeRead(this.startRowsForContext(e,t,n,r),t.tier)}startRowsForContext(e,t,n,r){let i=this.nativeReadAuthor(n);return this.db.all(e,t,r,i,this.nativeReadClaims(n))}nativeReadAuthor(e){return e.kind===`session-authority`?e.identity:void 0}nativeReadClaims(e){return e.kind===`session-authority`?e.claims:void 0}nativeReadContext(e,t){return this.trustedBackend&&(e?.backendAuthority||!e&&!t?.identity)?{kind:`backend-authority`}:this.readAuthorizationHost===`trusted-serving`?{kind:`session-authority`,identity:t?.identity??e?.identity??this.peerIdentity,claims:t?.requestSession?.claims??e?.claims}:{kind:`client-local`}}subscribeForContext(e,t,n){if(!this.db.subscribe)throw Error(`Native runtime does not support subscriptions`);let r=n.kind===`session-authority`?n.identity:void 0;return this.db.subscribe(e,t,r,this.nativeReadClaims(n))}async awaitNativeRead(e,t,n){let r=await e;if(!tv(r))return r;let i=()=>r.cancel();this.ownerRuntime.pendingNativeReadCancels.add(i);try{for(;;){if(this.closed||this.ownerRuntime.closed)throw Error(`native read was cancelled by runtime shutdown`);n?.throwIfAborted(),t&&this.throwServerTransportErrorForTier(t);let e=r.poll();if(e!==null)return e;this.startServerPump(),t&&this.throwServerTransportErrorForTier(t),await ly(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Nb(e.identity,this.peerIdentity)?void 0:e.identity:t&&!this.trustedBackend?this.peerIdentity:void 0}backendAttribution(e){if(!this.trustedBackend||!e)return;let t;try{t=JSON.parse(e).attribution}catch{return}if(t===void 0)return;if(typeof t!=`string`||!D(t))throw Error(`backend attribution must be a canonical author subject string`);let n=xv(e);if(!n)throw Error(`backend attribution requires a valid author`);return n.identity}awaitNativeOperation(e,t){let n=0,r,i=!1,a,o=()=>{n+=1,r?.()},s=()=>{i=!0,e.cancel(),o()};this.pendingNativeAdmissionCancels.add(s),t?.addEventListener(`abort`,s,{once:!0});let c=()=>{this.pendingNativeAdmissionCancels.delete(s),t?.removeEventListener(`abort`,s),e.cancel()},l=()=>{for(;;){if(this.closed||i||t?.aborted)throw Error(`native operation was cancelled`);if(a)throw a;let s=n,c=e.poll();if(c!=null)return c;if(this.pumpServerTransport().catch(e=>{a=e,o()}),n===s)return new Promise(e=>{r=e,n!==s&&e()}).then(()=>(r=void 0,l()))}};try{e.setWake(o);let t=l();return t instanceof Promise?t.finally(c):(c(),t)}catch(e){throw c(),e}}clientSessionClaimsKey;installClientSessionClaims(e){let t=Lv(e);if(t===this.clientSessionClaimsKey)return;let n=this.db.setSessionClaims?.(e);if(n instanceof Promise)return n.then(()=>{this.clientSessionClaimsKey=t});this.clientSessionClaimsKey=t}ensureClientSessionClaims(e){if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);if(!e||e.backendAuthority||this.readAuthorizationHost===`trusted-serving`||Lv(e.claims)===this.clientSessionClaimsKey)return;let t=()=>{if(this.closed||this.ownerRuntime.closed)throw Error(`Native runtime is closed`);return this.installClientSessionClaims(e.claims)};return this.ownerRuntime.coreOperation?this.runWhenCoreIdle(t):t()}async waitForStrictRemoteQueryTransport(e){if(e!==`remote`)return;let t=this.serverEndpointUrl,n=N_(this.serverAuthJson??`{}`,this.peerIdentity);for(;!this.hasUpstream();){this.throwServerTransportErrorForTier(`global`);let e=this.serverCarrierPromise;if(!e)return;let r=this.serverConnectionAttempt,i=e.then(()=>null,e=>e instanceof Error?e:Error(gy(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(gy(e))),s;try{s=await Promise.race([i,...r?.carrier===this.serverCarrier?[r.terminal]:[],...o?[o]:[]])}finally{a?.cancel()}if(this.closed)return;let c=this.serverEndpointUrl,l=this.serverAuthJson??`{}`;if(this.serverCarrierPromise&&(c!==t||!jb(n,N_(l,this.peerIdentity))))throw Error(`server transport scope changed while waiting for remote query`);if(s){if((s.message===`server transport replaced`||s.message===`server transport disconnected`)&&this.serverCarrierPromise!==null||this.linkStatus?.phase===`connecting`&&this.serverCarrierPromise!==null)continue;throw s}}}async processPendingPeerActivityBeforeRead(){if(this.nonDurableClient)for(;!this.closed&&this.peerTransportProcessedActivityEpoch<this.peerTransportActivityEpoch;)await this.progressPeerTransport()}attachLocalReadCoverageInBackground(e,t,n){e!=null&&e!==`local-first`||this.nonDurableClient||!this.serverTransport||(async()=>{await this.serverCarrierPromise,!(this.closed||this.ownerRuntime.closed)&&(await this.waitForStrictRemoteQueryTransport(`remote`),!(this.closed||this.ownerRuntime.closed)&&await this.readRowsForContextAsync(t,jv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Ve(e,ct(e)))throw Error(`Local-first native admission requires a verified account session`);if(!this.db.admitLocalFirstSession)throw Error(`Native runtime lacks local-first session admission`);this.db.admitLocalFirstSession(t,n,new T().decode(ne(e)))}applySessionClaims(e){!e||e.backendAuthority||this.readAuthorizationHost!==`trusted-serving`||!this.db.setIdentityClaims||this.db.setIdentityClaims(e.identity,e.claims)}table(e){let t=this.schema[e];if(!t)throw Error(`unknown table ${e}`);return t}currentTx(e,t){let n=_v(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Tv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Nb(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`);return}if(e.identity&&(!t||!Nb(e.identity,t))||t&&!e.identity)throw Error(`Native runtime mergeable transaction cannot mix write identities`)}assertTransactionAttribution(e,t){if(!(!e.attribution&&!t)){if(!e.attribution)throw Error(`Native runtime transaction was opened without backend attribution`);if(!t||!Nb(e.attribution,t))throw Error(`Native runtime backend-attributed transaction requires its original provenance subject`)}}pumpSubscriptions(){this.drainSubscriptionPool();for(let[e,t]of this.subscriptions)t.poolId===void 0&&this.startSubscriptionReader(e,t)}nativeSubscriptionPool(){return this.subscriptionPool===void 0&&(this.subscriptionPool=this.db.createSubscriptionPool?.()??null),this.subscriptionPool}drainSubscriptionPool(){let e=this.subscriptionPool;if(!(!e||this.pooledSubscriptions.size===0)){if(this.drainingSubscriptionPool){this.subscriptionPoolDirty=!0;return}this.drainingSubscriptionPool=!0;try{do{this.subscriptionPoolDirty=!1;for(let t of e.drain())this.applyPooledBatch(t)}while(this.subscriptionPoolDirty&&!this.closed)}finally{this.drainingSubscriptionPool=!1}}}applyPooledBatch(e){let t=this.pooledSubscriptions.get(e.id);if(t===void 0)return;let n=this.subscriptions.get(t),r=()=>n!==void 0&&!n.cancelled&&this.subscriptions.get(t)===n;if(!n||!r()){this.pooledSubscriptions.delete(e.id);return}for(let i of e.events){if(!r())break;try{this.applySubscriptionChunk(t,n,i)}catch(e){this.failSubscription(n,e instanceof Error?e:Error(String(e)))}}if(e.error&&(this.pooledSubscriptions.delete(e.id),!this.closed&&r())){let t=Error(e.error.message);t.code=e.error.code,this.failSubscription(n,t)}r()||this.pooledSubscriptions.delete(e.id)}withPermissionAdviceTimeout(e){if(this!==this.ownerRuntime)return this.ownerRuntime.withPermissionAdviceTimeout(e);if(this.closed||(!this.serverTransport||!this.serverCarrier)&&!this.nativeUpstreamConfigured())return Promise.resolve(`unknown`);let t=e(),n=rv(t)?{promise:this.awaitNativePermissionAdvice(t),cancel:()=>t.cancel()}:typeof t==`string`?{promise:Promise.resolve(t===`allowed`||t===`denied`||t===`unknown`?t:`unknown`),cancel:()=>{}}:t;return new Promise(e=>{let t=!1,r=n=>{t||(t=!0,clearTimeout(i),e(n))},i=setTimeout(()=>{n.cancel(),r(`unknown`)},2e3);n.promise.then(r,()=>r(`unknown`))})}async awaitNativePermissionAdvice(e){for(;;){if(this.closed)return e.cancel(),`unknown`;let t=e.poll();if(t!==null)return t===`allowed`||t===`denied`||t===`unknown`?t:`unknown`;await this.pumpServerTransport(),await ly(0)}}clearCoreDeadline(){this.coreDeadlineTimer!==void 0&&clearTimeout(this.coreDeadlineTimer),this.coreDeadlineTimer=void 0,this.coreDeadlineAt=void 0}scheduleCoreWake(e){if(this.coreProgressAllowed()){if(e===`after-current-turn`){setTimeout(()=>this.scheduleCoreWake(`immediate`),0);return}if(e.startsWith(`after:`)){let t=Number(e.slice(6));if(!Number.isSafeInteger(t)||t<0)return;let n=performance.now()+t;if(this.coreDeadlineAt!==void 0&&this.coreDeadlineAt<=n)return;this.clearCoreDeadline(),this.coreDeadlineAt=n,this.coreDeadlineTimer=setTimeout(()=>{this.coreDeadlineTimer=void 0,this.coreDeadlineAt=void 0,this.scheduleCoreWake(`immediate`)},t);return}if(this.notifyPeerTransportWork(),e===`immediate`){this.scheduleCoreTick();return}queueMicrotask(()=>{this.scheduleCoreTick()})}}scheduleCoreTick(){if(this.coreProgressAllowed()){if(this.coreOperation){this.coreTickAgain=!0;return}this.coreTickScheduled||(this.coreTickScheduled=!0,queueMicrotask(()=>{if(this.coreTickScheduled=!1,this.coreProgressAllowed()){if(this.coreOperation){this.coreTickAgain=!0;return}this.runCoreTick().catch(e=>{try{if(this.db.isNativeForegroundClosed?.())return}catch(e){Ib(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Ib(e)})}}))}}runCoreTick(){if(!this.coreProgressAllowed())return Promise.resolve();let e=this.coreOperation;if(e)return this.coreTickAgain=!0,e.kind===`tick`?e.completion:e.completion.then(()=>this.runCoreTick());let t,n,r=new Promise((e,r)=>{t=e,n=r});return this.coreOperation={kind:`tick`,completion:r},this.driveCoreTicks().then(t,n),r}reportSlowQueries(){let e=this.ownerRuntime;for(let t of this.db.takeSlowQueryReport?.(e.slowQueryApp)??[]){if(e.slowQueryConsoleDetail!==`summary`){console.warn(`[jazz] ${t}`);continue}let n=fv(t);if(n===t){console.warn(`[jazz] ${t}`);continue}console.warn(`[jazz] ${n}. Plan and SQL are logged at the debug ("Verbose") level.`),console.debug(`[jazz] ${t}`)}}async driveCoreTicks(){let e=!1;try{for(let t=0;;t+=1){this.coreTickAgain=!1;try{await this.db.tick()}catch(e){throw new vm(e)}if(this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=ev){e=!0;break}}}finally{this.drainTransportRetirements(),this.coreOperation=null}e&&this.coreProgressAllowed()&&setTimeout(()=>this.scheduleCoreTick(),0)}drainTransportRetirements(){let e=[...this.pendingTransportRetirements];this.pendingTransportRetirements.clear();for(let[t,n]of e)try{t.close();for(let e of n)e.resolve()}catch(e){for(let t of n)t.reject(e)}}startSubscriptionReader(e,t){let n=t.source;if(t.cancelled||t.reading||!t.callback||!n)return;if(t.poolId!==void 0){this.drainSubscriptionPool();return}let r=n.joinPool?this.nativeSubscriptionPool():null;if(r&&n.joinPool){let i=n.joinPool(r);t.poolId=i,this.pooledSubscriptions.set(i,e),this.drainSubscriptionPool();return}t.reading=!0,this.readSubscription(e,t,n)}readSubscription(e,t,n){let r=()=>!t.cancelled&&this.subscriptions.get(e)===t,i=()=>{t.reading=!1},a=e=>{!this.closed&&r()&&this.failSubscription(t,e instanceof Error?e:Error(String(e))),i()},o=n=>{if(n.type===`closed`||!r())return n.type===`closed`&&this.terminateSubscription(e,t),i(),!1;if(n.type===`pending`)return this.pumpServerTransport().then(()=>ly(Math.max(0,n.retryAfterMs))).then(s).catch(a),!1;for(let a of n.events){if(!r())return i(),!1;try{this.applySubscriptionChunk(e,t,a)}catch(e){this.failSubscription(t,e instanceof Error?e:Error(String(e)))}}return n.events.length===0||!r()?(i(),!1):!0},s=()=>{for(;r();){let e;try{e=n.pull(e=>{o(e)&&s()},a)}catch(e){a(e);return}if(e===void 0||!o(e))return}i()};s()}applySubscriptionChunk(e,t,n){let r=Cb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Tb(r.reason));return}let i=pb(r.delta,this.schema,r.reset===!0,t.outputColumns);i.terminalOperations=ny(r.terminalOperations,t.outputColumns?.rootColumns),t.callback?.(i)}scheduleServerPump(){if(!(this.closed||!this.serverTransport)){if(this.serverPumpRunning){this.serverPumpAgain=!0;return}this.serverPumpScheduled||(this.serverPumpScheduled=!0,setTimeout(()=>{this.serverPumpScheduled=!1,!this.closed&&this.startServerPump()},Z_))}}startServerPump(){let e=this.serverConnectionGeneration;this.pumpServerTransport().catch(t=>this.handleServerTransportError(t,e))}notifyPeerTransportWork(e=!1){for(let t of this.peerTransportWorkListeners)t(e)}hasUpstream(){return this.serverTransport!=null||this.peerUpstreamAttached}async pumpServerTransport(){let e=this.serverTransport,t=this.serverCarrier,n=this.serverConnectionGeneration;if(!(this.closed||!e||!t)){if(this.serverPumpRunning){this.serverPumpAgain=!0;return}this.serverPumpRunning=!0;try{let r=this.pendingInboundServerFrames.length>0?await this.routePendingInboundServerFrames():!1;r||=this.serverInboundProcessed,this.serverInboundProcessed=!1;for(let i=0;i<32;i+=1){if(await this.runCoreTick(),this.flushAuxiliaryOutbound(e,t,n),(r||this.serverInboundProcessed)&&(r=!1,this.serverInboundProcessed=!1,this.notifyServerTransportWork(),queueMicrotask(()=>this.notifyServerTransportWork())),this.closed||n!==this.serverConnectionGeneration||e!==this.serverTransport||t!==this.serverCarrier||this.stopRefusedUpstream(e))return;let i=mv(e.recvWireFrames());if(i.length>0&&this.sendServerFrames(i,t,n),this.pumpSubscriptions(),i.length===0)return}this.serverPumpAgain=!0}finally{this.serverPumpRunning=!1,this.serverPumpAgain&&(this.serverPumpAgain=!1,this.scheduleServerPump())}}}stopRefusedUpstream(e){let t=gm(e.upstreamRefusal?.());if(!t)return!1;let n=this.serverConnectionAttempt;return!n||n.transport!==e?!1:(this.upstreamRefusal=t,this.endLinkAttempt(n,t,{kind:`fatal`,message:t.message}),!0)}async routePendingInboundServerFrames(){let e=!1,t=this.serverInboundRouting.then(async()=>{let t=this.serverTransport,n=this.serverCarrier,r=this.serverConnectionGeneration;if(!t||this.pendingInboundServerFrames.length===0)return;let i=this.pendingInboundServerFrames.splice(0);e=!0,this.serverInboundProcessed=!0;let a=[];for(let e of i){let i=t.routeAuxiliaryWireFrame?await t.routeAuxiliaryWireFrame(e):e;if(n&&this.refreshAuxiliaryReceiveDeadline(t,n,r),t!==this.serverTransport||r!==this.serverConnectionGeneration)return;i!=null&&a.push(hv(i))}if(this.publishAuxiliaryTrace(t),a.length>0)if(t.sendWireFrames)t.sendWireFrames(a);else for(let e of a)t.sendWireFrame(e);this.notifyPeerTransportWork(!0),n&&this.flushAuxiliaryOutbound(t,n,this.serverConnectionGeneration)});return this.serverInboundRouting=t.then(()=>void 0,()=>void 0),await t,e}refreshAuxiliaryReceiveDeadline(e,t,n){if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let r=this.auxiliaryReceiveDeadlines.get(e);r||(r=new Ki(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(gy(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Ib))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=mv(r.call(e));i.length>0&&this.sendServerFrames(i,t,n),this.publishAuxiliaryTrace(e)}publishAuxiliaryTrace(e){let t=e.takeAuxiliaryTrace?.();if(!(!t||t.length===0))for(let e of this.auxiliaryTraceListeners)e(t)}async watchAuxiliaryOutbound(e,t,n){for(;!this.closed&&e===this.serverTransport&&t===this.serverCarrier&&n===this.serverConnectionGeneration;){let r=e.auxiliaryOutboundReady?.();if(!r||typeof r==`boolean`||(await r,e!==this.serverTransport||t!==this.serverCarrier))return;this.flushAuxiliaryOutbound(e,t,n)}}sendServerFrames(e,t,n){n!==this.serverConnectionGeneration||t!==this.serverCarrier||t.sendBatch(e).catch(e=>{this.handleServerTransportError(e,n)})}forgetServerTransportError(){this.serverTransportError=null,this.serverTransportErrorRetrying=!1,this.serverTransportErrorAwaitsAuth=!1}handleServerTransportError(e,t=this.serverConnectionGeneration,n=!1){if(t!==this.serverConnectionGeneration&&(this.closed||!ym(e)))return;let r=gy(e);if(this.serverTransportError&&r===`websocket closed`){if(n||!this.serverTransportErrorRetrying)return;e=this.serverTransportError}e===this.serverTransportError&&this.serverTransportErrorAwaitsAuth&&(n=!0),this.serverTransportErrorAwaitsAuth=!1;let i=this.serverTransportError===null||this.serverTransportErrorRetrying&&!n;this.serverTransportError=e instanceof Error?e:Error(r),this.serverTransportErrorRetrying=n,this.linkChanged(),n||this.failRemoteSubscriptions(this.serverTransportError),this.resolveServerTransportErrorWaiters(this.serverTransportError,n),i&&this.serverTransportErrorCallback?.(this.serverTransportError,{retrying:n})}finishServerConnectionAttempt(e,t,n=!0){if(e.finished)return;e.finished=!0,this.linkChanged(),e.outcome=t,e.resolveTerminal(t);let r=e===this.serverConnectionAttempt&&e.generation===this.serverConnectionGeneration&&e.carrier===this.serverCarrier;r&&(this.serverConnectionGeneration+=1,this.serverConnectionAttempt=null,this.serverCarrier=null),e.carrier.close();let i=e.transport;if(e.transport=null,i){i===this.serverTransport&&(this.serverTransport=null);try{if(this.coreOperation){let t=Promise.resolve(this.retirePeerTransport(i));e.retirement=t,t.catch(e=>{this.closed||this.handleServerTransportError(e)})}else this.retirePeerTransport(i),e.retirement=null}catch(t){let n=Promise.reject(t);e.retirement=n,n.catch(e=>{this.closed||this.handleServerTransportError(e)})}}if(e.admission){let t=e.admission;e.admission=null,e.retirement=t.then(e=>this.retirePeerTransport(e),()=>void 0),e.retirement.catch(e=>{this.closed||this.handleServerTransportError(e)})}e.retirement&&(this.serverReplacementRetirement=av(this.serverReplacementRetirement,e.retirement),this.serverReplacementRetirement.catch(()=>void 0)),r&&(n&&this.handleServerTransportError(t),this.resolveServerTransportWorkWaiters())}failRemoteSubscriptions(e){for(let t of this.subscriptions.values())t.cancelled||t.tier===`remote`&&this.failSubscription(t,e)}terminateSubscription(e,t){this.subscriptions.get(e)===t&&this.subscriptions.delete(e),this.retireSubscriptionResources(t)}failSubscription(e,t){e.cancelled||(e.terminalError=t,this.retireSubscriptionResources(e),this.deliverSubscriptionFailure(e))}retireSubscriptionResources(e){if(e.cancelled)return;e.cancelled=!0,e.poolId!==void 0&&this.pooledSubscriptions.delete(e.poolId),e.openingAbort?.abort();let t=e.source;if(e.source=void 0,t)try{zv(t)}catch(e){console.error(`Jazz subscription source cleanup failed`,e)}}deliverSubscriptionFailure(e){if(!(!e.callback||!e.terminalError||e.terminalErrorDelivered)){e.terminalErrorDelivered=!0;try{e.callback(e.terminalError)}catch(e){setTimeout(()=>{throw e},0)}}}serverTransportErrorFor(e){return e&&this.serverTransportErrorRetrying?null:this.serverTransportError}throwServerTransportErrorForTier(e,t=!1){if(e!==`global`&&e!==`remote`)return;let n=this.serverTransportErrorFor(t);if(n)throw n}waitForServerTransportError(e,t=!1){if(e!==`global`&&e!==`remote`)return null;let n=this.serverTransportErrorFor(t);if(n)return{promise:Promise.reject(n),cancel:()=>{}};let r={active:!0,throughOutage:t,reject:()=>{}},i=new Promise((e,t)=>{r.reject=t});return this.serverTransportErrorWaiters.push(r),{promise:i,cancel:()=>{if(!r.active)return;r.active=!1;let e=this.serverTransportErrorWaiters.indexOf(r);e>=0&&this.serverTransportErrorWaiters.splice(e,1)}}}resolveServerTransportErrorWaiters(e,t=!1){let n=this.serverTransportErrorWaiters.splice(0);for(let r of n)r.active&&(t&&r.throughOutage?this.serverTransportErrorWaiters.push(r):r.reject(e))}clearServerTransportErrorWaiters(){for(let e of this.serverTransportErrorWaiters)e.active=!1;this.serverTransportErrorWaiters.length=0}waitForServerTransportWork(e,t){if(e!==`global`&&e!==`remote`)return null;if(this.serverTransportWorkEpoch!==t)return{promise:Promise.resolve(),cancel:()=>{}};let n={active:!0,resolve:()=>{}},r=new Promise(e=>{n.resolve=e});return this.serverTransportWorkWaiters.push(n),{promise:r,cancel:()=>{if(!n.active)return;n.active=!1;let e=this.serverTransportWorkWaiters.indexOf(n);e>=0&&this.serverTransportWorkWaiters.splice(e,1)}}}notifyServerTransportWork(){this.serverTransportWorkEpoch+=1,this.resolveServerTransportWorkWaiters()}resolveServerTransportWorkWaiters(){let e=this.serverTransportWorkWaiters.splice(0);for(let t of e)t.active&&t.resolve()}};function mv(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function hv(e){let t=mv([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function gv(e,t){let n=e.txId;return t.set(n,e),n}function _v(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function vv(e){if(e)try{let t=JSON.parse(e);if(!t.branch_view||typeof t.branch_view!=`object`)return;let n=t.branch_view;return n.head==null?void 0:{head:n.head,base:n.base}}catch{return}}function yv(e,t){if(!e)return!1;let n;try{if(n=JSON.parse(e),n.attribution!==void 0)return!0;if(!(n.issuer!==void 0||n.user_id!==void 0||n.session!==void 0))return!1}catch{return!1}try{let n=xv(e);return n===null||!Nb(n.identity,t)}catch{return!0}}function bv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function xv(e){if(!e)return null;try{let t=JSON.parse(e);if(t.attribution===`system`)throw Error(`Native runtime public session uses reserved issuer`);let n=typeof t.attribution==`string`?D(t.attribution):null;if(n?.issuer===`urn:jazz:system`)throw Error(`Native runtime public session uses reserved issuer`);let r=n?.user_id??(typeof t.user_id==`string`?t.user_id:typeof t.session?.user_id==`string`?t.session.user_id:void 0);if(!r||!P(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!P(i))throw Error(`session is missing issuer`);let a={account_id:Pv(n?n.account_id:(t.session??t).account_id),issuer:i,user_id:r,authMode:typeof t.session?.authMode==`string`?t.session.authMode:typeof t.authMode==`string`?t.authMode:`external`};Sv(a.issuer,a.user_id,a.authMode,t.session?.__jazz_trusted_reserved_session??t.__jazz_trusted_reserved_session,a.account_id);let o=t.session?.__jazz_trusted_reserved_session??t.__jazz_trusted_reserved_session,s=Rv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:ne(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Ve(a,o)}}catch(e){if(e instanceof Error&&(e.message===`session is missing issuer`||e.message===`session has invalid account_id`||e.message===`Native runtime public session uses reserved issuer`))throw e;return null}}function Sv(e,t,n,r,i){if(Ke(e)&&!((n===`local-first`||n===`anonymous`||n===`external`)&&Ve({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Cv(e){if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t.updated_at==`number`){if(!Number.isSafeInteger(t.updated_at)||t.updated_at<0)throw Error(`updatedAt must be a nonnegative safe integer`);return t.updated_at}}function wv(e){return Cv(e)??null}function Tv(e,t){return t.get(e)?.state===`committed`?`open transaction ${e} is already committed`:`open transaction ${e} has already been completed or was never opened`}function Ev(e,t){let n=Tv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function Dv(e,t){let n=Tv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Ov(e,t,n){let r=Av(e);if(!(!r||t.has(r)))throw Error(`Query setup failed: Write error: ${Tv(r,n)}`)}function kv(e,t){let n=Av(e);return n?t.get(n):void 0}function Av(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function jv(e,t=!1,n){let r=n==null?{}:JSON.parse(n),i={};e!=null&&(i.tier=e),t&&(i.include_deleted=!0),typeof r.first_load_remote_wait_ms==`number`&&r.first_load_remote_wait_ms>0&&(i.first_load_remote_wait_ms=r.first_load_remote_wait_ms);let a=r.read_view??r.readView;return a!=null&&(i.read_view=a),Array.isArray(r.splices)&&r.splices.length>0&&(i.splices=r.splices),i}function Mv(e){if(e==null)return!1;try{let t=JSON.parse(e);return typeof t.first_load_remote_wait_ms==`number`&&t.first_load_remote_wait_ms>0}catch{return!1}}function Nv(e,t){if(e!=null&&![`local-first`,`remote`,`local-only`].includes(e))throw Error(`Native runtime received unsupported read tier '${e}'`);t!=null&&JSON.parse(t)}function Pv(e){if(e!==void 0){if(typeof e!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e))throw Error(`session has invalid account_id`);return e}}function Fv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!P(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!P(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Pv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};Sv(n.issuer,n.user_id,n.authMode,t[De],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Ve(n,t.__jazz_trusted_reserved_session);return{...n,claims:Rv(t.claims,n),identity:ne(n),backendAuthority:r}}function Iv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lv(e){return e===null||typeof e==`boolean`||typeof e==`string`?JSON.stringify(e):typeof e==`number`?Number.isFinite(e)?JSON.stringify(e):`null`:Array.isArray(e)?`[${e.map(Lv).join(`,`)}]`:Iv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Lv(e[t])}`).join(`,`)}}`:`null`}function Rv(e,t){return{...Iv(e)?e:{},iss:t.issuer,sub:t.user_id}}function zv(e){e.close()}function Bv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function Vv(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function Hv(e,t){return Ey(e,t)}function Uv(e){if(Wv(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function Wv(e){let t=JSON.parse(e);return Yv(t.select_columns??t.select)||Xv(t.conditions)||Gv(t.relation_ir)||Kv(t.relation_ir)||Zv(t.array_subqueries)}function Gv(e){return $v(e)}function Kv(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(Kv);let t=e,n=t.Project;if(n&&typeof n==`object`){let e=n.columns;if(Array.isArray(e))for(let t of e){if(!t||typeof t!=`object`)continue;let e=t,n=Jv(e.expr??e.source);if(n&&ws(n))return!0}}return Object.values(t).some(Kv)}function qv(e){if(!e||typeof e!=`object`)return null;let t=e;return qy(t.left??t.column)}function Jv(e){return!e||typeof e!=`object`?null:`Column`in e?qy(e.Column):qy(e)}function Yv(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&ws(ey(e))):!1}function Xv(e){return Array.isArray(e)?e.some($v):!1}function Zv(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return Yv(t.select_columns??t.select)||Qv(t.filters)||Zv(t.nested_arrays)}):!1}function Qv(e){return Array.isArray(e)?e.some($v):!1}function $v(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some($v);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&ws(ey(t.column)))return!0;for(let e of[`Eq`,`Ne`,`Gt`,`Ge`,`Lt`,`Le`,`IsNull`,`IsNotNull`,`Contains`]){let n=t[e];if(!n||typeof n!=`object`)continue;let r=n.column;if(typeof r==`string`&&ws(ey(r)))return!0}let n=qv(t.Cmp)??qv(t.In)??qv(t.IsNull)??qv(t.IsNotNull)??qv(t.Contains);return n&&ws(ey(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&$v(t))}function ey(e){return hs(e)}function ty(e,t){let n=JSON.parse(e);if(typeof n.table!=`string`)throw Error(`Native runtime only supports table queries in this slice`);return{rootTable:n.table,rootColumns:oy(n.table,t,Ay(n.select_columns??n.select),My(n.array_subqueries,n.table,t)??[])}}function ny(e,t){if(!(!e||e.length===0))return e.map(e=>{let n=t,r,i=e.path.map(e=>{if(`Key`in e)return{Key:ry(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Hs.length):e.Collection,i=n.findIndex(e=>e.name===t),a=n[i]?.column_type;if(a?.type!==`Array`||a.element.type!==`Row`)throw Error(`native terminal operation addressed unknown collection ${t}`);return n=a.element.columns,r=n,{Collection:i}}),a=e.edit;if(`Insert`in a){if(!r)throw Error(`native terminal insert has no collection target`);let t=ay(a.Insert.key);return{root_key:ry(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:ry(a.Insert.key),row:Xm(t,r,iy(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=ay(a.Update.key);return{root_key:ry(e.root_key),path:i,edit:{Update:{key:ry(a.Update.key),row:Xm(t,r,iy(a.Update.value))}}}}return`Remove`in a?{root_key:ry(e.root_key),path:i,edit:{Remove:{key:ry(a.Remove.key)}}}:{root_key:ry(e.root_key),path:i,edit:{Move:{key:ry(a.Move.key),index:a.Move.index}}}})}function ry(e){return Array.isArray(e)?e:Array.from(e)}function iy(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function ay(e){let t=iy(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return Ce(t.subarray(1,17))}function oy(e,t,n,r,i=!0){let a=G(t,e);if(!a)throw Error(`missing schema for subscription table ${e}`);let o=n===void 0,s=(n??a.columns.map(e=>e.name)).map(e=>{let t=a.columns.find(t=>t.name===e);if(t)return o&&i?{...t,sparse:!0}:t;let n=Es(e);return n?{name:e,column_type:n,nullable:e===`$deletedAt`||e.startsWith(`$deletedBy`)}:void 0}).filter(e=>e!==void 0);for(let e of r){let n=oy(e.table,t,e.select,e.nestedArrays??[],!1);s.push({name:e.columnName,column_type:{type:`Array`,element:{type:`Row`,columns:n}},nullable:!1})}return s}function sy(e){let t=JSON.parse(e);return cy(t.array_subqueries),JSON.stringify(t)}function cy(e){if(Array.isArray(e))for(let t of e){if(!t||typeof t!=`object`)continue;let e=t;if(Array.isArray(e.select_columns)&&Array.isArray(e.nested_arrays))for(let t of e.nested_arrays){if(!t||typeof t!=`object`)continue;let n=t.outer_column;if(typeof n!=`string`)continue;let r=hs(n);(Ay(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}cy(e.nested_arrays)}}function ly(e){return new Promise(t=>setTimeout(t,e))}function uy(e,t){return Cy(t)?dy(e,t):wy(t)?fy(e,t):null}function dy(e,t){let n=gy(t),r={kind:`rejected`,transactionId:e,code:`transaction_conflict`,reason:/^\(transaction_conflict\):\s*(.*)$/s.exec(n)?.[1]||n,message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function fy(e,t){let n=gy(t),r={kind:`rejected`,transactionId:e,code:by(Hc(t)),reason:Sy(n,Hc(t)),message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function py(e,t){try{return t()}catch(t){if(wy(t)){let n=gy(t),r=Ty(n)??n,i=Hc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:by(i)})}throw t}}function my(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function hy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function gy(e){if(e instanceof Error)return e.message;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`&&t.trim())return t;try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)}function _y(e=`a store configured as one user serves only its own identity's peers`){return Object.assign(Error(e),{code:`protocol`,reason:`identity_mismatch`})}function vy(e,t){let n=t instanceof Error?t:Error(gy(t));return Error(`${e}: ${n.message}`,{cause:n})}var yy={authorization_denied:`permission_denied`,client_clock_too_far_ahead:`client_clock_too_far_ahead`,serialization_conflict:`serialization_conflict`,row_already_deleted:`write_rejected`,row_already_exists:`write_rejected`,row_not_deleted:`write_rejected`,missing_required:`write_rejected`,branch_move:`write_rejected`,missing_chunks:`write_rejected`,predecessor_rejected:`write_rejected`,schema_version_not_deployed:`write_rejected`,identity_mismatch:`write_rejected`};function by(e){return e===void 0?`write_rejected`:yy[e]}var xy={permission_denied:`Write rejected by server authorization`,serialization_conflict:`Serializable transaction conflicted with another write`,client_clock_too_far_ahead:`Client clock is too far ahead`};function Sy(e,t){let n=Ty(e);return n===null?e:xy[by(t)]??(n||`Write rejected`)}function Cy(e){return Bc(e)===`transaction_conflict`}function wy(e){return Bc(e)===`write_rejected`}function Ty(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Ey(e,t){let n=JSON.parse(e);if(typeof n.table!=`string`)throw Error(`Native runtime only supports table queries in this slice`);let r=n.table;if(n.relation_ir!=null){let i=wm(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Lh(r,[],{relation:i.relation_ir,select:Ay(n.select_columns??n.select),partial:ky(n.select_columns),arraySubqueries:My(n.array_subqueries,r,t)})}let i=Hy(n.conditions);if(!i)throw Z();return Lh(r,i.map(e=>Dy(r,e,t)),{limit:Xy(n.limit),offset:Zy(n.offset),orderBy:jy(n.order_by??n.orderBy),select:Ay(n.select_columns??n.select),partial:ky(n.select_columns),arraySubqueries:My(n.array_subqueries,r,t)})}function Z(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function Dy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>Dy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:Dy(e,t.predicate,n)};if(zo(e)&&`column`in t){if(t.column===`$transactionId`)throw Error(`History $transactionId predicates do not accept user-provided values`);if(t.column===`$acceptedAt`){if(t.op===`In`)return{op:`Any`,predicates:t.values.map(r=>Dy(e,{column:t.column,op:`Eq`,value:r},n))};if(Oy(t)){let r=zy(e,t.column,t.value,n);if(r.type!==`Timestamp`||!Number.isSafeInteger(r.value))throw Error(`History $acceptedAt predicates require a valid Date or integer milliseconds`);let i=BigInt(r.value)<<18n,a=i+(1n<<18n)-1n,o=(e,n)=>n<0n||n>(1n<<64n)-1n?{op:(n<0n?e===`Gt`||e===`Gte`:e===`Lt`||e===`Lte`)?`All`:`Any`,predicates:[]}:{column:t.column,op:e,value:{type:`U64`,value:n}};switch(t.op){case`Eq`:return{op:`All`,predicates:[o(`Gte`,i),o(`Lte`,a)]};case`Ne`:return{op:`Not`,predicate:{op:`All`,predicates:[o(`Gte`,i),o(`Lte`,a)]}};case`Gt`:return o(`Gt`,a);case`Gte`:return o(`Gte`,i);case`Lt`:return o(`Lt`,i);case`Lte`:return o(`Lte`,a)}}}}if(t.op===`In`){let r=t.column===`id`?{type:`Uuid`}:G(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return r?.type===`Array`?{op:`Any`,predicates:t.values.map(i=>i.type===`Array`?{column:t.column,op:`Eq`,value:zy(e,t.column,i,n)}:{column:t.column,op:`Contains`,value:By(i,r.element,!1)})}:{...t,values:t.values.map(r=>zy(e,t.column,r,n))}}if(t.op===`Contains`){let r=t.column===`id`?{type:`Uuid`}:G(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?By(t.value,r.element,!1):zy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(Oy(t))return{...t,value:zy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Oy(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function ky(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;if(e.kind===`json_pointer`){if(typeof e.at!=`string`)throw Z(`select_columns`);t.push({column:e.column,kind:`json_pointer`,at:e.at})}else if(e.kind===`bytes`||e.kind===`text_utf16`||e.kind===`text_utf8`){if(typeof e.from!=`number`||typeof e.to!=`number`)throw Z(`select_columns`);t.push({column:e.column,kind:e.kind,from:e.from,to:e.to})}}return t}function Ay(e){if(e==null)return;if(!Array.isArray(e))throw Z();let t=[];for(let n of e){if(typeof n==`string`){t.push(n);continue}if(!n||typeof n!=`object`||typeof n.column!=`string`)throw Z();let e=n;if(e.kind!==`full`&&e.kind!==`bytes`&&e.kind!==`text_utf16`&&e.kind!==`text_utf8`&&e.kind!==`json_pointer`)throw Z();t.push(e.column)}return t}function jy(e){if(e==null)return[];if(!Array.isArray(e))throw Z(`order_by`);return e.map(e=>{if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`){if(e[1]!==`asc`&&e[1]!==`desc`)throw Z(`order_by`);return{column:e[0],direction:e[1]===`asc`?`Asc`:`Desc`}}if(!e||typeof e!=`object`)throw Z(`order_by`);let t=e;if(typeof t.column!=`string`||t.direction!==`Asc`&&t.direction!==`Desc`)throw Z(`order_by`);return{column:t.column,direction:t.direction}})}function My(e,t,n){if(e!=null){if(!Array.isArray(e))throw Z(`array_subqueries`);return e.map(e=>Ny(e,t,n))}}function Ny(e,t,n){if(!e||typeof e!=`object`)throw Z(`array_subqueries`);let r=e;if(typeof r.column_name!=`string`||typeof r.table!=`string`||typeof r.inner_column!=`string`||typeof r.outer_column!=`string`)throw Z(`array_subqueries`);if(Array.isArray(r.joins)&&r.joins.length>0)throw Z(`array_subqueries.joins`);let i=Py(r.filters,r.table,n),a=Ay(r.select_columns),o=Iy(r.order_by),s=My(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:Ry(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:Yy(r.limit),offset:Zy(r.offset),requirement:Ly(r.requirement),nestedArrays:s}}function Py(e,t,n){if(e==null)return[];if(!Array.isArray(e))throw Z(`array_subqueries.filters`);let r=[];for(let i of e){let e=Fy(i);if(!e)throw Z(`array_subqueries.filters`);r.push(...e.map(e=>Dy(t,e,n)))}return r}function Fy(e){let t=Wy(e);if(t)return[t];if(!e||typeof e!=`object`)return null;let n=e;for(let[e,t]of[[`Eq`,`Eq`],[`Ne`,`Ne`],[`Gt`,`Gt`],[`Ge`,`Gte`],[`Lt`,`Lt`],[`Le`,`Lte`]]){let r=n[e];if(r&&typeof r==`object`){let{column:e,value:n}=r;return typeof e==`string`?[{column:e,op:t,value:Gy(n)}]:null}}let r=n.IsNull;if(r&&typeof r==`object`){let e=r.column;return typeof e==`string`?[{column:e,op:`IsNull`}]:null}let i=n.IsNotNull;if(i&&typeof i==`object`){let e=i.column;return typeof e==`string`?[{column:e,op:`IsNotNull`}]:null}let a=n.Contains;if(a&&typeof a==`object`){let{column:e,value:t}=a;return typeof e==`string`?[{column:e,op:`Contains`,value:Gy(t)}]:null}return null}function Iy(e){if(e==null)return[];if(!Array.isArray(e))throw Z(`array_subqueries.order_by`);return e.map(e=>{if(!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`||e[1]!==`Ascending`&&e[1]!==`Descending`)throw Z(`array_subqueries.order_by`);return{column:e[0],direction:e[1]===`Ascending`?`Asc`:`Desc`}})}function Ly(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Z(`array_subqueries.requirement`)}function Ry(e,t){let n=`${t}.`;return e.startsWith(n)?e.slice(n.length):e}function zy(e,t,n,r){let i=t===`id`?{type:`Uuid`}:Es(t)??G(r,e)?.columns.find(e=>e.name===t)?.column_type;if(i?.type===`Bytea`&&n.type===`Array`)return{type:`Bytea`,value:Uint8Array.from(n.value.map(Vy))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:G(r,e)?.columns.find(e=>e.name===t)?.column_type,a=i?.type===`Array`?i.element:i;return{type:`Array`,value:n.value.map(e=>By(e,a,!1))}}return By(n,i,!0)}function By(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:By(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&Qy(e.value))return{type:`Uuid`,value:e.value};if(t?.type===`Text`&&e.type===`Uuid`)return{type:`Text`,value:e.value};if(t?.type===`Double`&&e.type===`Integer`)return{type:`Double`,value:e.value};if(t?.type===`BigInt`&&e.type===`Integer`)return{type:`BigInt`,value:Om(e.value,`BigInt value`)};if(t?.type===`Timestamp`&&e.type===`Integer`)return{type:`Timestamp`,value:e.value};if(t?.type===`Timestamp`&&e.type===`Text`){let t=Date.parse(e.value);if(Number.isFinite(t))return{type:`Timestamp`,value:t}}return t?.type===`Bytea`&&e.type===`Array`?{type:`Bytea`,value:Uint8Array.from(e.value.map(Vy))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>By(e,t.element,!1))}:e}function Vy(e){if(e.type!==`Integer`||e.value<0||e.value>255)throw Error(`Bytea values must contain integers in range 0..255`);return e.value}function Hy(e){if(e==null)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!=`object`)return null;let e=Wy(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=hs(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:Gy(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:Gy(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:Gy(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:Gy(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:Gy(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:Gy(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:Gy(r.value)});break;case`isNull`:if(typeof r.value!=`boolean`)return null;t.push({column:i,op:r.value?`IsNull`:`IsNotNull`});break;case`in`:if(!Array.isArray(r.value))return null;t.push({column:i,op:`In`,values:r.value.map(Gy)});break;default:return null}}return t}function Uy(e){if(e===`True`)return[];if(e===`False`)return[{column:`id`,op:`In`,values:[]}];if(!e||typeof e!=`object`)return null;let t=e;if(Array.isArray(t.And)){let e=[];for(let n of t.And){let t=Uy(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=Wy(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=qy(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=qy(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=qy(e.left),n=Jy(e.right);return t&&n?[{column:t,op:`Contains`,value:n}]:null}let a=t.In;if(a&&typeof a==`object`){let e=a,t=qy(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(Jy);return n.every(e=>e!=null)?[{column:t,op:`In`,values:n}]:null}let o=t.Cmp;if(!o||typeof o!=`object`)return null;let s=o,c=Ky(s.op);if(!c)return null;let l=qy(s.left),u=Jy(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function Wy(e){if(e===`True`)return{op:`All`,predicates:[]};if(e===`False`)return{op:`Any`,predicates:[]};if(!e||typeof e!=`object`)return null;let t=e;if(Array.isArray(t.And)||Array.isArray(t.Or)){let e=Array.isArray(t.And)?`All`:`Any`,n=(t.And??t.Or).map(Wy);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=Wy(t.Not);return e?{op:`Not`,predicate:e}:null}let n=Uy(e);return n?.length===1?n[0]:null}function Gy(e){if(e==null)return{type:`Nullable`,value:null};if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`&&Number.isSafeInteger(e))return{type:`Integer`,value:e};if(typeof e==`number`&&Number.isFinite(e))return{type:`Double`,value:e};if(typeof e==`bigint`)return{type:`BigInt`,value:e};if(typeof e==`string`)return Qy(e)?{type:`Uuid`,value:e}:{type:`Text`,value:e};if(e instanceof Uint8Array)return{type:`Bytea`,value:e};if(Array.isArray(e))return{type:`Array`,value:e.map(Gy)};throw Z()}function Ky(e){switch(e){case`Eq`:case`Ne`:case`Gt`:case`Gte`:case`Lt`:case`Lte`:return e;case`Ge`:return`Gte`;case`Le`:return`Lte`;default:return null}}function qy(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?hs(t):null}function Jy(e){if(!e||typeof e!=`object`||!(`Literal`in e))return null;let t=e.Literal;if(!t||typeof t!=`object`)return null;let n=t;if(n.type===`Boolean`&&typeof n.value==`boolean`)return{type:`Boolean`,value:n.value};if(n.type===`Integer`&&typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`Integer`,value:n.value};if(n.type===`BigInt`){if(typeof n.value==`string`&&n.value.length<=Y_&&X_.test(n.value))try{return{type:`BigInt`,value:Om(BigInt(n.value),`BigInt value`)}}catch{return null}if(typeof n.value==`bigint`||typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`BigInt`,value:BigInt(n.value)}}if(n.type===`Timestamp`&&typeof n.value==`number`&&Number.isSafeInteger(n.value))return{type:`Timestamp`,value:n.value};if(n.type===`Double`&&typeof n.value==`number`&&Number.isFinite(n.value))return{type:`Double`,value:n.value};if(n.type===`Bytea`&&Array.isArray(n.value))return{type:`Bytea`,value:Uint8Array.from(n.value.map(Number))};if(n.type===`Null`)return{type:`Nullable`,value:null};if(n.type===`Array`&&Array.isArray(n.value)){let e=n.value.map(e=>Jy({Literal:e}));if(e.every(e=>e!=null))return{type:`Array`,value:e}}return n.type===`Uuid`&&typeof n.value==`string`?{type:`Uuid`,value:n.value}:(n.type===`Text`||n.type===`Enum`)&&typeof n.value==`string`?{type:`Text`,value:n.value}:null}function Yy(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function Xy(e){return e==null?void 0:Yy(e)}function Zy(e){if(e==null)return 0;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query offset must be a non-negative safe integer`);return e}function Qy(e){return/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e)}function $y(e,t,n){return ib(e.columns,t,n),rb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function eb(e,t,n,r){return ib(e.columns.filter(e=>e.name!==n),t,r),rb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function tb(e,t,n){return rb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function nb(e,t){return rb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function rb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:gh(e),column:e})),i=r.map(({column:e})=>ab(e,t(e),n)),a=new Xh;return Vm(a,r),a.bytes(Gm(r,i)),a.finish()}function ib(e,t,n){for(let r of e){let e=t[r.name]??r.default;if(!(e&&e.type!==`Null`)&&!r.nullable)throw Error(n?`encoding error: missing required field \`${r.name}\` on table \`${n}\``:`missing required column ${r.name}`)}}function ab(e,t,n){let r=t;if(!r){if(e.nullable)return uh(gh(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return ch(e,r)}function ob(e){return new Zh(e).readVec(jm)}function sb(e){return Rm(new Zh(e))}function cb(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=lb(a,t,n),o=th(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=gb(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(qm({table:a.table,id:Ce(t.rowId),values:n},s))}}return i}function lb(e,t,n){let r=cv.get(t);r||(r=new Map,cv.set(t,r));let i=ng(e),a=n?void 0:r.get(i);if(a)return a;let o=n??G(t,e.table)?.columns??[],s=new Map(o.map(e=>[e.name,e])),c=n?new Set(n.map(e=>e.name)):null,l=[];for(let t=0;t<e.descriptor.length;t+=1){let n=e.descriptor[t],r=n&&Am(n);if(!r)continue;let i=Es(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!Pb(r)&&(!Ts(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function ub(e,t,n,r=`full-record`){return fb(cb(e.rows,t,n,r),t).slice(0,e.rootCount)}var db=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function fb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((G(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of db){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:qm({...e,values:e.values.filter(e=>!i.has(e))},r)})}function pb(e,t,n=!1,r=null){let i=(e,n,i,a)=>{let o=hb(e,t,r,`full-record`);if(o.length!==n.length)throw Error(`subscription occurrence sidecar length mismatch`);return o.flatMap((e,o)=>{if(r&&e.table!==r.rootTable)return[];let s=a?.[o];return[{sourceId:e.id,occurrenceKey:n[o],index:i[o],row:Db(e,t,r),...s&&s.length>0?{splices:mb(s,t,e.table)}:{}}]})};return{added:i(e.added,e.addedOccurrenceKeys,e.addedIndices),updated:i(e.updated,e.updatedOccurrenceKeys,e.updatedIndices,e.updatedSplices),removed:e.removed.flatMap((t,n)=>r&&t.table!==r.rootTable?[]:[{sourceId:Ce(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{}}}function mb(e,t,n){let r=G(t,n)?.columns??[],i={};for(let{column:t,splices:n}of e){let e=r.find(e=>e.name===t)?.column_type.type;if(e===`Text`)i[t]=n.map(e=>({at:e.atUtf16,delete:e.deleteUtf16,insert:sv.decode(e.insert)}));else if(e===`Bytea`)i[t]=n.map(e=>({at:e.at,delete:e.delete,insert:e.insert}));else throw Error(`subscription splices for column "${t}" of type ${e} are not supported yet`)}return i}function hb(e,t,n,r){return e.flatMap(e=>cb([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function gb(e,t,n,r){let i=t(n,e.index);if(i==null)return{type:`Null`};if(!e.type)return{type:`Bytea`,value:i};try{return _b(e.type,i,e.name,e.storageType,r)}catch(t){throw Error(`${String(t)} while decoding ${e.name} as ${e.type.type} from storage tag ${e.storageType.tag} (${i.byteLength} bytes)`)}}function _b(e,t,n,r,i=`full-record`){let a=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e.type){case`Boolean`:return{type:`Boolean`,value:t[0]!==0};case`Integer`:return{type:`Integer`,value:a.getInt32(0,!0)};case`BigInt`:return{type:`BigInt`,value:vb(r)?.tag===3?a.getBigUint64(0,!0):a.getBigInt64(0,!0)};case`Double`:return{type:`Double`,value:a.getFloat64(0,!0)};case`Timestamp`:return{type:`Timestamp`,value:Number(a.getBigUint64(0,!0))};case`Text`:case`Json`:case`Enum`:if(t[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return{type:`Text`,value:sv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:Ce(t)};case`Bytea`:if(t[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return{type:`Bytea`,value:t.subarray(1).slice()};case`Array`:return{type:`Array`,value:Sb(e.element,t,yb(r),i)};case`Row`:{let a={type:`Row`,value:xb(e.columns,t,bb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ee(a),a}}}function vb(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function yb(e){let t=vb(e);return t?.tag===14?t.inner:void 0}function bb(e){let t=vb(e);return t?.tag===16?t.record:void 0}function xb(e,t,n,r=`full-record`){if(n){let i=r===`keyed-terminal`;if(i&&n[0]?.name!==`row_uuid`)throw Error(`keyed terminal nested row descriptor must start with row_uuid`);if(i&&t.byteLength<16)throw Error(`terminal nested row is missing its key`);let a=i?n.slice(1):n,o=i?t.subarray(16):t,s=th(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?Ce(t.subarray(0,16)):void 0;for(let e=0;e<a.length;e+=1){let t=a[e]?.name;if(!t)continue;let n=s(o,e);if(!i&&t===`row_uuid`&&n){u=Ce(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:_b(d.column_type,n,t,a[e]?.valueType,r))}let d=e.map(e=>l.get(e.name)??(e.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}));return qm({id:u,values:d},l)}if(t.byteLength<5)throw Error(`invalid nested row value`);let i=t[0]===1,a=1,o;if(i){if(t.byteLength<21)throw Error(`invalid nested row id`);o=Ce(t.subarray(a,a+16)),a+=16}let s=Mb(t,a);a+=4;let c=t.subarray(a,a+s);if(c.byteLength!==s)throw Error(`invalid nested row value length`);return{id:o,values:Km(e,c)}}function Sb(e,t,n,r=`full-record`){let i=Eh(n??vh(e));if(i!=null){if(i===0)return[];if(t.length%i!==0)throw Error(`invalid fixed-width array byte length ${t.length}`);let a=[];for(let o=0;o<t.length;o+=i)a.push(_b(e,t.subarray(o,o+i),void 0,n,r));return a}if(t.length<4)throw Error(`invalid variable-width array byte length`);let a=Mb(t,0),o=4+Math.max(0,a-1)*4;if(o>t.length)throw Error(`invalid variable-width array offset table`);let s=[];for(let i=0;i<a;i+=1){let c=i===0?o:Mb(t,4+(i-1)*4),l=i===a-1?t.length:Mb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(_b(e,t.subarray(c,l),void 0,n,r))}return s}function Cb(e){if(!e||typeof e!=`object`)throw Error(`expected subscription chunk`);let t=e;if(t.type===`closed`||t.type===`Closed`)return{type:`closed`};if(t.type===`delta`||t.type===`Delta`)return{type:`delta`,reset:t.reset===!0,delta:Fm(new Zh(Fb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:wb(t.reason)};throw Error(`unknown subscription chunk`)}function wb(e){if(!e||typeof e!=`object`)throw Error(`expected subscription rejection reason`);let t=e;if(t.type===`UnsupportedShapeCapability`&&typeof t.detail==`string`)return{type:`UnsupportedShapeCapability`,detail:t.detail};if(t.type===`ShapeRegistrationPendingCatalogueAdmission`)return{type:`ShapeRegistrationPendingCatalogueAdmission`};let n=t.code??t.detail;if(t.type===`ServerFailure`&&typeof n==`string`)return typeof t.errorCode==`string`?{type:`ServerFailure`,code:n,errorCode:t.errorCode}:{type:`ServerFailure`,code:n};if(t.type===`InvalidAuthoritySourceClosure`&&typeof t.transition==`string`)return{type:`InvalidAuthoritySourceClosure`,transition:t.transition};throw Error(`unknown subscription rejection reason`)}function Tb(e){let t=e.type===`UnsupportedShapeCapability`?e.detail:e.type===`ServerFailure`?e.code:e.type===`InvalidAuthoritySourceClosure`?e.transition:`catalogue admission pending`,n=`Subscription rejected: ${e.type}: ${t}`,r=e.type===`ServerFailure`?e.errorCode:void 0;return r===void 0?Error(n):gm({code:r,message:n})??Error(n)}function Eb(e){let t=e;if(typeof t.getReader==`function`){let e=t.getReader();return{pull(t,n){e.read().then(e=>t(e.done?{type:`closed`}:{type:`batch`,events:[e.value]}),n)},close(){e.cancel().catch(()=>{})}}}let n=e;return{joinPool:n.joinPool?e=>n.joinPool(e):void 0,pull(){let e=n.readAll();return Array.isArray(e)?{type:`batch`,events:e}:{type:`pending`,retryAfterMs:e.retryAfterMs?.()??0}},close(){n.close?.()}}}function Db(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?_h(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=Ab(e,i).map((e,t)=>Ob(e,i[t].column_type));return qm({id:e.id,values:a},Jm(i,a))}function Ob(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Ob(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:kb(e.value,t.columns)}:e}function kb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Ob(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return qm({id:e.id,values:r},Jm(t,r))}function Ab(e,t){if(!e.valuesByColumn)return e.values.slice(0,t.length);let n=[];n.length=t.length;for(let r=0;r<t.length;r+=1){let i=t[r];n[r]=e.valuesByColumn.get(i.name)??(i.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`})}return n}function jb(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function Q(e){let t=Ze(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Mb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Nb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pb(e){return e.startsWith(Hs)}function Fb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Ib(e){queueMicrotask(()=>{throw e})}var Lb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Ya(e,t,n,r,i,!1,a)}ready(){return this.connection.ready()}waitForServerConnection(){return this.connection.waitForServerConnection()}async updateAuth(e,t){this.connection.updateAuth(e,t)}disconnect(){return this.connection.disconnect()}reconnect(e,t){return this.connection.reconnect(e,t)}deleteStorage(){return this.connection.deleteStorage()}storePendingUploads(){return this.connection.storePendingUploads()}waitForPendingWrites(){return this.connection.waitForPendingWrites()}flushLocal(){return this.connection.flushLocal()}shutdown(){return this.connection.shutdown()}async openInspectorControlPort(){throw Error(`Inspector peers cannot open nested inspector sessions`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.connection.getAuthenticatedInspectorAttachmentPhysicalDbName()}};function Rb(e,t,n=globalThis.WebSocket){let r=new URL(e.replace(/^ws/,`http`)).origin;if(typeof n!=`function`)throw Error(`Jazz: this platform has no WebSocket`);return Vb(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return Bb(t)},`the app's bearer`)}var zb=3e4;function Bb(e){let t;return Promise.race([Promise.resolve().then(()=>e()),new Promise((e,n)=>{t=setTimeout(()=>n(Error(`the app's bearer did not answer`)),zb)})]).finally(()=>clearTimeout(t))}function Vb(e,t,n){return class{type=`arraybuffer`;inner;closed=!1;listeners=[];constructor(r){let i=t(r);if(!i){this.attach(new e(r));return}i.then(t=>{this.closed||this.attach(t?new e(r,{headers:{authorization:`Bearer ${t}`}}):new e(r))},e=>{this.closed||(this.closed=!0,console.error(`Jazz: ${n} failed`,e),this.emit(`error`,e),this.emit(`close`,{code:1006,reason:`credential unavailable`}))})}get binaryType(){return this.inner?.binaryType??this.type}set binaryType(e){this.type=e,this.inner&&(this.inner.binaryType=e)}attach(e){e.binaryType=this.type,this.inner=e;for(let[t,n]of this.listeners)e.addEventListener(t,n)}emit(e,t){for(let[n,r]of this.listeners)n===e&&r(t)}get readyState(){return this.inner?this.inner.readyState:this.closed?3:0}send(e){if(!this.inner)throw Error(`WebSocket is not open`);this.inner.send(e)}close(){if(this.inner)return this.inner.close();this.closed||(this.closed=!0,queueMicrotask(()=>this.emit(`close`,{code:1e3,reason:``})))}addEventListener(e,t){this.listeners.push([e,t]),this.inner?.addEventListener(e,t)}}}var Hb=`warn`;function Ub(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??Hb}function Wb(e){return rt({...e,trustedReservedSession:A(e)})}function Gb(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=Me(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`local-first`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Ae(n??{},r);if(!i||i.issuer!==t.issuer||i.user_id!==t.user_id||i.authMode!==t.authMode)throw Error(`Attached browser worker session does not match its identity token`);l(e,i)}function Kb(e){let t=Wb(e);if(t)return t;if(e.adminSecret)return{issuer:`https://jazz.invalid`,user_id:`backend-open`};throw Error(`Default runtime requires a verified session or admin credential`)}function qb(e){return!Wb(e)&&!!e.adminSecret}function Jb(e,t){if(!(!t||!e.jwtToken||t.issuer!==`urn:jazz:local-first`&&t.issuer!==`urn:jazz:anonymous`))return{token:e.jwtToken,appId:H(e),claimedAuthor:ze(t.issuer,t.user_id,t.account_id)}}function Yb(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function Xb(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var Zb=class extends dm{supportsBrowserWorker=!0;module=null;ownerRuntime=null;get wasmModule(){if(!this.module)throw Error(`Default runtime source is not loaded`);return this.module}async load(e){this.module??=await im(e.runtimeSources)}admitConfig(e){Gb(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,foregroundNodeLease:i}){Ub(e.logLevel);let a={onAuthFailure:r},o=Jb(e,Wb(e)),s=qb(e),c=i?.node.slice()??ie(),u=ne(Kb(e)),d=Yb(e),f=ex(e),p=e.cookieSession&&e.accountId?Qo(e):void 0,m=this.nativeSchemaView(t,c,u,d,!f,o,s,{appId:H(e),thresholdMs:e.slowQueryThresholdMs,...Qb()?{consoleDetail:`summary`}:{}},n,p&&e.serverUrl?Rb(e.serverUrl,p):void 0);if(i&&m.seedForegroundTxTimeHighWater(i.confirmedTxTime),f&&(m.setNonDurableClient(),!i))throw Error(`Persistent browser runtime requires a foreground node lease`);let h={appId:H(e),accountId:e.accountId,schema:t,driver:e.driver,serverUrl:e.serverUrl,env:e.env,jwtToken:e.jwtToken,cookieSession:e.cookieSession,adminSecret:e.adminSecret};return l(h,A(e)),te.connectWithRuntime(this.wrapClientRuntime(m,e,t),h,a)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!ex(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=iu(e);return await yo.acquire({runtimeSources:Xb(e),dbName:t,storageOwner:zi(e)})}async acquireForegroundNodeLease(t){if(!$b()||(t.driver?.type??`persistent`)!==`persistent`)return;let{acquireNodeForegroundNodeLease:n}=await e(async()=>{let{acquireNodeForegroundNodeLease:e}=await import(`./node-foreground-node-lease.browser-CH8w-D6S.js`);return{acquireNodeForegroundNodeLease:e}},[],import.meta.url);return await n({appId:H(t),env:t.env??`dev`,authScope:Ri(t)})}createBrowserWorkerConnection({config:e,schema:t,client:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l}){let u=n.getRuntime();if(!(u instanceof pv))throw Error(`Browser worker connections require the native runtime adapter`);let d=Jb(e,Wb(e));if(qb(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let f=iu(e),p=ne(Kb(e));return e.runtimeSources?.browserWorkerPort?new Lb(u,e.runtimeSources.browserWorkerPort,Wb(e)?.claims??{},f,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l},e.runtimeSources.inspectorBinding):new bo(u,{runtimeSources:Xb(e),schema:t,dbName:f,author:p,selfSignedClientProof:d,initialSyncFlushEvery:Yb(e),migrations:u.migrations,appId:H(e),slowQueryThresholdMs:e.slowQueryThresholdMs,storageOwner:zi(e),authSessionKey:Ri(e),serverUrl:e.serverUrl?ke(e.serverUrl,H(e)):void 0,authJson:JSON.stringify(tx(e)),sessionClaims:Wb(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Pi(e,f,qe(t)),{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof pv))throw Error(`Browser follower connections require the native runtime adapter`);let l=Wb(e)?.claims??{},u=new Ya(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(tx(e)),l),u}nativeSchemaView(e,t,n,r,i,a,o=!1,s,c,l){return!this.ownerRuntime||this.ownerRuntime.isClosed()?(this.ownerRuntime=new pv(this.wasmModule.WasmDb,e,t,n,1,i,{initialSyncFlushEvery:r,selfSignedClientProof:a,backendMode:o,slowQueryLog:s,migrations:c,webSocket:l}),this.ownerRuntime):Object.keys(e).length===0?this.ownerRuntime:this.ownerRuntime.registerSchemaView(e,c)}installTelemetry({config:e,collectorUrl:t,runtimeThread:n}){return li({wasmModule:this.wasmModule,collectorUrl:t,runtimeThread:n})}textAnchors(){return lm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function Qb(){return typeof window<`u`&&typeof Worker<`u`}function $b(){return typeof process<`u`&&!!process.versions?.node}function ex(e){return Qb()&&(e.driver?.type??`persistent`)===`persistent`}function tx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function nx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},cu(e),at(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(at(e))}),o=e.getSyncStatus().link.state===`connected`,s=e.onSyncStatusChange(({link:e})=>{let t=e.state===`connected`;t&&!o&&i.retryRejected(),o=t}),c=n?.(e);return ot({db:e,get session(){return r},async shutdown(t){t?.waitForSync&&await e.shutdown(t),await Ml([()=>a?.(),()=>s(),...c?[c]:[],()=>i.shutdown(),()=>e.shutdown()])}},i)}function rx(e){return(e.driver??{type:`persistent`}).type===`persistent`?iu(e):null}function ix(e){if(typeof window>`u`)return()=>{};let t=rx(e.getConfig());if(!t)return()=>{};let n=window;Lo(n);let r=To(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function ax(e){return nx(e,H(e.getConfig()),ix)}async function ox(e,t,n){await new Promise((r,i)=>{let a=t=>{clearTimeout(c),e.removeEventListener(`message`,s),e.removeEventListener(`messageerror`,o),t?i(t):r()},o=()=>a(Error(`Inspector attachment channel failed`)),s=({data:e})=>{if(!(!(`id`in e)||e.id!==-1)){if(e.type===`result`&&e.error)return a(He(e.error));if(e.type!==`inspector-binding`||e.binding.appId!==t.appId||e.binding.physicalDbName!==t.physicalDbName||e.binding.authSessionKey!==t.authSessionKey||e.binding.storageOwner!==t.storageOwner)return a(Error(`Inspector attachment receipt does not match its requested scope`));a()}},c=setTimeout(()=>a(Error(`Inspector attachment timed out`)),1e4);e.addEventListener(`message`,s),e.addEventListener(`messageerror`,o),e.start(),e.postMessage({type:`inspect-binding`,id:-1,binding:t,leasePort:n},[n])})}var sx=class extends Zb{leasePort;inspectorPort;leaseRequested=!1;constructor(e,t){super(),this.leasePort=e,this.inspectorPort=t}wrapClientRuntime(e,t,n){return mt(e,this.inspectorPort,t.runtimeSources.inspectorBinding,n)}async acquireBrowserForegroundNodeLease(e){return this.leaseRequested=!0,yo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:zi(e)})}};async function cx(e,t,n,r){let i=new MessageChannel,a=new sx(i.port1,r);try{if(!e.jwtToken)throw Error(`Inspector attachment requires the host's resolved client token`);let o={appId:t,jwtToken:e.jwtToken,accountId:e.accountId,accountRegistryAuthority:e.accountRegistryAuthority,serverUrl:e.serverUrl,env:e.env,runtimeSources:{...e.runtimeSources,browserWorkerPort:r,inspectorHostPhysicalDbName:n}};Gb(o);let s=Vi(o,``);if(!n.endsWith(s))throw Error(`Inspector storage scope mismatch`);o.driver={type:`persistent`,dbName:n.slice(0,-s.length)};let c={appId:t,physicalDbName:n,authSessionKey:Ri(o),storageOwner:zi(o)};return await ox(r,c,i.port2),o.runtimeSources.inspectorBinding=c,ts(o),await ax(await dd(o,a))}catch(e){try{r.postMessage({type:`close`})}catch{}throw r.close(),a.leaseRequested||(i.port1.postMessage({type:`cancel-foreground-node-lease`}),i.port1.close(),i.port2.close()),e}}function lx(e,t){let n=t?.runtimeSources?.inspectorHostPhysicalDbName??null;return e.find(e=>e.appId===t?.appId&&e.dbName===n)?.key??e[0]?.key??null}var $=st(),ux=200,dx=15e3,fx=1e3;function px(e,t){return t.aborted?Promise.resolve():new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n()};t.addEventListener(`abort`,i,{once:!0})})}function mx(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>mx(e,t[n]));let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length?n.every((n,i)=>n===r[i]&&mx(e[n],t[n])):!1}function hx(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.key===e.key&&r.appId===e.appId&&r.dbName===e.dbName&&mx(r.schema,e.schema)})}var gx=class extends I.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}render(){return this.state.error?(0,$.jsxs)(`p`,{style:{padding:16},children:[`Inspector connection failed: `,this.state.error.message]}):this.props.children}};function _x(){let[e,t]=(0,I.useState)(null),[n,r]=(0,I.useState)([]),[i,a]=(0,I.useState)(null),o=(0,I.useRef)(Promise.resolve()),[s,c]=(0,I.useState)(null),[l,u]=(0,I.useState)(!1),[d,f]=(0,I.useState)(null);return(0,I.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+dx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await Ne({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(lx(s.contexts,je()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await px(Math.min(ux,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,I.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await px(fx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>hx(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:lx(n,je()))}catch{}}})(),()=>t.abort()},[e]),(0,I.useEffect)(()=>{if(!e||!i)return;let t=n.find(e=>e.key===i);if(!t)return;let r,a=!0,s;c(null),f(null);let l=o.current.then(()=>{if(a){if(r=je(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){Be(e);return}let n=await cx(r,t.appId,t.dbName,e);if(!a){await n.shutdown();return}s=n,c({client:n,schema:t.schema})}).catch(e=>{a&&f(e instanceof Error?e:Error(String(e)))});return o.current=l,()=>{a=!1,o.current=l.then(()=>s?.shutdown()).catch(e=>{f(e instanceof Error?e:Error(String(e)))})}},[n,i,e]),d?(0,$.jsxs)(`p`,{style:{padding:16},children:[`Inspector connection failed: `,d.message]}):s?(0,$.jsxs)($.Fragment,{children:[n.length>1?(0,$.jsxs)(`label`,{style:{display:`block`,padding:`8px 12px`},children:[`Runtime context`,` `,(0,$.jsx)(`select`,{value:i??``,onChange:e=>a(e.target.value),children:n.map(e=>(0,$.jsxs)(`option`,{value:e.key,children:[e.appId,` / `,e.dbName]},e.key))})]}):null,(0,$.jsx)(vx,{client:s.client,wasmSchema:s.schema},i)]}):l?(0,$.jsx)(`p`,{style:{padding:16},children:`Inspector: no host connection found. Is this page running under the Jazz dev plugin?`}):(0,$.jsx)(`p`,{style:{padding:16},children:`Connecting…`})}function vx({client:e,wasmSchema:t}){return(0,$.jsx)(gx,{children:(0,$.jsx)(nt,{client:e,children:(0,$.jsx)(xe,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(we,{initialEntries:[new URLSearchParams(window.location.search).get(`route`)??`/`],children:(0,$.jsx)(Qe,{})})})})})}(0,dt.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(I.StrictMode,{children:(0,$.jsx)(_x,{})}));