jazz-tools 2.0.0-alpha.68 → 2.0.0-alpha.69
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/blobs.d.ts +7 -1
- package/dist/backend/blobs.d.ts.map +1 -1
- package/dist/backend/blobs.js +7 -1
- package/dist/backend/blobs.js.map +1 -1
- package/dist/backend/create-jazz.d.ts +4 -0
- package/dist/backend/create-jazz.d.ts.map +1 -1
- package/dist/backend/create-jazz.js +4 -0
- package/dist/backend/create-jazz.js.map +1 -1
- package/dist/backend/inspector-ui/10.js +2 -2
- package/dist/backend/inspector-ui/11.js +2 -2
- package/dist/backend/inspector-ui/12.js +2 -2
- package/dist/backend/inspector-ui/18.js +1 -1
- package/dist/backend/inspector-ui/9.js +2 -2
- package/dist/backend/inspector-ui-files.js +4 -4
- package/dist/dev/inspector-overlay/embedded/assets/{index-BMlShD3p.js → index-Dwq5UKtM.js} +3 -3
- package/dist/dev/inspector-overlay/embedded/assets/{jazz-broker-worker-DTBugu7j.js → jazz-broker-worker-BTBxu5GV.js} +2 -2
- package/dist/dev/inspector-overlay/embedded/assets/{jazz_wasm-MSQOvwc8.js → jazz_wasm-BOTo6QbW.js} +1 -1
- package/dist/dev/inspector-overlay/embedded/assets/{jazz_wasm_bg-hIvU0oYr.wasm → jazz_wasm_bg-ZDkHqBG4.wasm} +0 -0
- package/dist/dev/inspector-overlay/embedded/embedded.html +1 -1
- package/dist/durable-object/index.d.ts +6 -1
- package/dist/durable-object/index.d.ts.map +1 -1
- package/dist/durable-object/index.js +6 -1
- package/dist/durable-object/index.js.map +1 -1
- package/dist/runtime/native-artifact-fingerprint-napi.d.ts +1 -1
- package/dist/runtime/native-artifact-fingerprint-napi.js +1 -1
- package/dist/runtime/native-artifact-fingerprint-napi.js.map +1 -1
- package/dist/runtime/native-artifact-fingerprint-wasm.d.ts +1 -1
- package/dist/runtime/native-artifact-fingerprint-wasm.js +1 -1
- package/dist/runtime/native-artifact-fingerprint-wasm.js.map +1 -1
- package/dist/runtime/native-artifact-fingerprints.d.ts +2 -2
- package/dist/worker/jazz-broker-worker.js +2 -2
- package/dist/worker/jazz_wasm_bg.wasm +0 -0
- package/package.json +4 -4
|
@@ -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-DZp28PPA.js","./trace-api-BctnwbUf.js","./esm-D8VoKWz0.js","./src-C1yTrMsg.js","./src-Cq8gSOLx.css","./esm-WihpI9g6.js","./esm-CsIV7VoQ.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 ee,Nt as te,O as ne,Ot as O,P as re,Pt as ie,Q as ae,Qt as oe,R as se,Rt as k,S as ce,St as A,T as le,Tt as j,U as ue,Ut as de,V as fe,Vt as pe,W as me,Wt as M,X as he,Xt as N,Y as ge,Yt as _e,Z as ve,Zt as ye,_ as be,_t as xe,an as P,at as Se,b as Ce,bt as we,cn as Te,ct as Ee,dn as De,dt as Oe,en as ke,et as Ae,ft as je,g as Me,gt as Ne,h as Pe,ht as Fe,in as Ie,it as Le,j as Re,jt as ze,k as Be,kt as Ve,ln as He,m as Ue,mt as We,nt as Ge,on as Ke,ot as qe,pt as Je,q as Ye,qt as F,rn as Xe,rt as Ze,sn as Qe,st as $e,t as et,tt,v as nt,vt as rt,w as it,wt as I,x as at,xt as ot,y as st,yt as ct,z as lt,zt as ut}from"./src-C1yTrMsg.js";var dt=Te(),L=De(He(),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,u=({data:e})=>{let t=!1;if(e.type===`link-fate`&&(t=l===null&&e.fate.authFailure!==null,l=e.fate.authFailure),e.type===`error`||t||e.type===`storage-invalidated`||e.type===`storage-reset`){d();return}if(e.type!==`inspector-query-result`&&e.type!==`result`||e.id>=-1)return;let n=e.error&&P(e.error),r=s.get(e.id);if(r){s.delete(e.id),n?r.reject(n):e.type===`inspector-query-result`?r.resolve(e.value):r.reject(Error(`Unexpected Inspector query response`));return}let i=c.get(e.id);i&&(n||e.type===`inspector-query-result`)&&i.callback?.(n??e.value)},d=()=>{if(i)return;i=!0,t.removeEventListener(`message`,u),t.removeEventListener(`messageerror`,f);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()},f=()=>d();t.addEventListener(`message`,u),t.addEventListener(`messageerror`,f);let p=e=>e===`local-only`,m=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 m({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,m({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)=>p(r)?i?Promise.reject(Error(`Inspector cache connection closed`)):m({type:`inspect-query`,query:t,options:a}):e.query(t,n,r,a);if(s===`createSubscription`)return(n,r,a,o)=>{if(!p(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()=>(d(),e.close());if(s===`discard`)return()=>(d(),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 x(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(_e(e))}function St(e){return bt(_e(Et(F(e)).reverse()))}function Ct(e,t){x(t),e=vt(e);let n=ye(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 R=BigInt(0),z=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 B(e,t){let n=e%t;return n>=R?n:t+n}function Wt(e,t,n){let r=e;for(;t-- >R;)r*=r,r%=n;return r}function Gt(e,t){if(e===R)throw Error(`invert: expected non-zero number`);if(t<=R)throw Error(`invert: expected positive modulus, got `+t);let n=B(e,t),r=t,i=R,a=z,o=z,s=R;for(;n!==R;){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!==z)throw Error(`invert: does not exist`);return B(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+z)/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-z,n=0;for(;t%It===R;)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+z)/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=z<<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)=>(B(e,t)&z)===z,$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<R)throw Error(`invalid exponent, negatives unsupported`);if(n===R)return e.ONE;if(n===z)return t;let r=e.ONE,i=t;for(;n>R;)n&z&&(r=e.mul(r,i)),i=e.sqr(i),n>>=z;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-z)/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&&x(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=R;ONE=z;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=R)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 B(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return R<=e&&e<this.ORDER}is0(e){return e===R}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return B(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return B(e*e,this.ORDER)}add(e,t){return B(e+t,this.ORDER)}sub(e,t){return B(e-t,this.ORDER)}mul(e,t){return B(e*t,this.ORDER)}pow(e,t){return tn(this,e,t)}div(e,t){return B(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){F(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=B(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){F(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=B(n?St(e):xt(e),t-z)+z;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),V=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)-V,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?V: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:V};if(u!==V)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,V,c(a.Gx*a.Gy));static ZERO=new m(An,V,V,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,V,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=Et(F(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-V),c(o*p-i));if(!h)throw Error(`bad point: invalid y coordinate`);let _=(g&V)===V,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(ye(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===V?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===V?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&V?128:0,n}toHex(){return _e(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 _e(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,n,r={}){if(typeof n!=`function`)throw Error(`"hash" function param is required`);Nt(r,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:i}=r,{BASE:a,Fp:o,Fn:s}=e,c=r.randomBytes||t,l=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,n)=>{if(_t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function d(e){return s.create(St(e))}function f(e){let t=b.secretKey;F(e,b.secretKey,`secretKey`);let r=F(n(e),2*t,`hashedSecretKey`),i=l(r.slice(0,t));return{head:i,prefix:r.slice(t,2*t),scalar:d(i)}}function p(e){let{head:t,prefix:n,scalar:r}=f(e),i=a.multiply(r);return{head:t,prefix:n,scalar:r,point:i,pointBytes:i.toBytes()}}function m(e){return p(e).pointBytes}function h(e=Uint8Array.of(),...t){return d(n(u(N(...t),F(e,void 0,`context`),!!i)))}function g(e,t,n={}){e=F(e,void 0,`message`),i&&(e=i(e));let{prefix:r,scalar:o,pointBytes:c}=p(t),l=h(n.context,r,e),u=a.multiply(l).toBytes(),d=h(n.context,u,c,e),f=s.create(l+d*o);if(!s.isValid(f))throw Error(`sign failed: invalid s`);return F(N(u,s.toBytes(f)),b.signature,`result`)}let _={zip215:!0};function v(t,n,r,o=_){let{context:s,zip215:c}=o,l=b.signature;t=F(t,l,`signature`),n=F(n,void 0,`message`),r=F(r,b.publicKey,`publicKey`),c!==void 0&&_t(c,`zip215`),i&&(n=i(n));let u=l/2,d=t.subarray(0,u),f=St(t.subarray(u,l)),p,m,g;try{p=e.fromBytes(r,c),m=e.fromBytes(d,c),g=a.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=h(s,m.toBytes(),p.toBytes(),n);return m.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=o.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function x(e=c(b.seed)){return F(e,b.seed,`seed`)}function S(e){return oe(e)&&e.length===s.BYTES}function C(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let w={getExtendedPublicKey:p,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:C,toMontgomery(t){let{y:n}=e.fromBytes(t),r=b.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let a=i?o.div(V+n,V-n):o.div(n-V,n+V);return o.toBytes(a)},toMontgomerySecret(e){let t=b.secretKey;return F(e,t),l(n(e.subarray(0,t))).subarray(0,t)}};return Object.freeze({keygen:kn(x,m),getPublicKey:m,sign:g,verify:v,utils:w,Point:e,lengths:b})}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(!oe(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){F(e),yt(n),t=Bn(t),t.length>255&&(t=r(N(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=N(t,Rn(t.length,1)),c=Rn(0,a),l=Rn(n,2),u=Array(o),d=r(N(c,e,l,Rn(0,1),s));u[0]=r(N(d,Rn(1,1),s));for(let e=1;e<=o;e++)u[e]=r(N(zn(d,u[e-1]),Rn(e+1,1),s));return N(...u).slice(0,n)}function Hn(e,t,n,r,i){if(F(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`),F(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]=B(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:n,Point:r,hash:i}=e,{Fn:a}=r,o=(t,n)=>e.hashToGroup(t,{DST:N(Dt(`HashToGroup-`),n)}),s=(t,n)=>e.hashToScalar(t,{DST:N(Wn,n)}),c=(e=t)=>{let n=dn(e(un(a.ORDER)),a.ORDER,a.isLE);return a.isLE?St(n):xt(n)},l=(e,t)=>En(r,e,t),u=e=>N(Dt(`OPRFV1-`),new Uint8Array([e]),Dt(`-`+n)),d=u(0),f=u(1),p=u(2);function m(...e){let t=[];for(let n of e)typeof n==`number`?t.push(Ct(n,2)):typeof n==`string`?t.push(Dt(n)):(F(n),t.push(Ct(n.length,2),n));return N(...t)}let h=(...e)=>i(m(...e,`Finalize`));function g(e,t,n,r){let a=i(m(e.toBytes(),N(Dt(`Seed-`),r))),o=[];for(let e=0;e<t.length;e++){let i=t[e].toBytes(),c=n[e].toBytes(),l=s(m(a,e,i,c,`Composite`),r);o.push(l)}return o}function _(e,t,n,r){let i=g(e,t,n,r);return{M:l(t,i),Z:l(n,i)}}function v(e,t,n,r,i){let a=l(n,g(t,n,r,i));return{M:a,Z:a.multiply(e)}}function y(e,t,n,r,i,a){let[o,c,l,u,d]=[e,t,n,r,i].map(e=>e.toBytes());return s(m(o,c,l,u,d,`Challenge`),a)}function b(e,t,n,i,o,s){let{M:l,Z:u}=v(t,n,i,o,e),d=c(s),f=y(n,l,u,r.BASE.multiply(d),l.multiply(d),e);return N(...[f,a.sub(d,a.mul(f,t))].map(e=>a.toBytes(e)))}function x(e,t,n,i,o){F(o,2*a.BYTES);let{M:s,Z:c}=_(t,n,i,e),[l,u]=[o.subarray(0,a.BYTES),o.subarray(a.BYTES)].map(e=>a.fromBytes(e)),d=y(t,s,c,r.BASE.multiply(u).add(t.multiply(l)),s.multiply(u).add(c.multiply(l)),e);if(!a.eql(l,d))throw Error(`proof verification failed`)}function S(){let e=c(),t=r.BASE.multiply(e);return{secretKey:a.toBytes(e),publicKey:t.toBytes()}}function C(t,n,i){let o=N(Dt(`DeriveKeyPair`),t),s=N(n,m(i),Uint8Array.of(0));for(let t=0;t<=255;t++){s[s.length-1]=t;let n=e.hashToScalar(s,{DST:o});if(!a.is0(n))return{secretKey:a.toBytes(n),publicKey:r.BASE.multiply(n).toBytes()}}throw Error(`Cannot derive key`)}function w(e,n,i=t){let s=c(i),l=o(n,e);if(l.equals(r.ZERO))throw Error(`Input point at infinity`);let u=l.multiply(s);return{blind:a.toBytes(s),blinded:u.toBytes()}}function T(e,t,n){let i=a.fromBytes(t),s=o(n,e);if(s.equals(r.ZERO))throw Error(`Input point at infinity`);return h(n,s.multiply(i).toBytes())}let E={generateKeyPair:S,deriveKeyPair:(e,t)=>C(d,e,t),blind:(e,n=t)=>w(d,e,n),blindEvaluate(e,t){let n=a.fromBytes(e);return r.fromBytes(t).multiply(n).toBytes()},finalize(e,t,n){let i=a.fromBytes(t);return h(e,r.fromBytes(n).multiply(a.inv(i)).toBytes())},evaluate:(e,t)=>T(d,e,t)};return Object.freeze({name:n,oprf:E,voprf:{generateKeyPair:S,deriveKeyPair:(e,t)=>C(f,e,t),blind:(e,n=t)=>w(f,e,n),blindEvaluateBatch(e,n,i,o=t){if(!Array.isArray(i))throw Error(`expected array`);let s=a.fromBytes(e),c=r.fromBytes(n),l=i.map(r.fromBytes),u=l.map(e=>e.multiply(s)),d=b(f,s,c,l,u,o);return{evaluated:u.map(e=>e.toBytes()),proof:d}},blindEvaluate(e,n,r,i=t){let a=this.blindEvaluateBatch(e,n,[r],i);return{evaluated:a.evaluated[0],proof:a.proof}},finalizeBatch(e,t,n){if(!Array.isArray(e))throw Error(`expected array`);return x(f,r.fromBytes(t),e.map(e=>e.blinded).map(r.fromBytes),e.map(e=>e.evaluated).map(r.fromBytes),n),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(f,e,t)},poprf:e=>{let n=s(m(`Info`,e),p),i=r.BASE.multiply(n);return{generateKeyPair:S,deriveKeyPair:(e,t)=>C(p,e,t),blind(e,n,s=t){let l=r.fromBytes(n),u=i.add(l);if(u.equals(r.ZERO))throw Error(`tweakedKey point at infinity`);let d=c(s),f=o(e,p);if(f.equals(r.ZERO))throw Error(`Input point at infinity`);let m=f.multiply(d);return{blind:a.toBytes(d),blinded:m.toBytes(),tweakedKey:u.toBytes()}},blindEvaluateBatch(e,i,o=t){if(!Array.isArray(i))throw Error(`expected array`);let s=a.fromBytes(e),c=a.add(s,n),l=a.inv(c),u=i.map(r.fromBytes),d=u.map(e=>e.multiply(l)),f=b(p,c,r.BASE.multiply(c),d,u,o);return{evaluated:d.map(e=>e.toBytes()),proof:f}},blindEvaluate(e,n,r=t){let i=this.blindEvaluateBatch(e,[n],r);return{evaluated:i.evaluated[0],proof:i.proof}},finalizeBatch(t,n,i){if(!Array.isArray(t))throw Error(`expected array`);let o=t.map(e=>e.evaluated).map(r.fromBytes);return x(p,r.fromBytes(i),o,t.map(e=>e.blinded).map(r.fromBytes),n),t.map((t,n)=>{let r=a.fromBytes(t.blind),i=o[n].multiply(a.inv(r)).toBytes();return h(t.input,e,i)})},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate(t,i){let s=a.fromBytes(t),c=o(i,p);if(c.equals(r.ZERO))throw Error(`Input point at infinity`);let l=a.add(s,n),u=a.inv(l);return h(i,e,c.multiply(u).toBytes())}}},__tests:{Fn:a}})}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=B(t*t*t,n),i=tr(e*B(r*r*t,n)).pow_p_5_8,a=B(e*r*i,n),o=B(t*a*a,n),s=a,c=B(a*rr,n),l=o===e,u=o===B(-e,n),d=o===B(-e*rr,n);return l&&(a=s),(u||d)&&(a=c),Qt(a,n)&&(a=B(-a,n)),{isValid:l||u,value:a}}var ar=Pn(er,{uvRatio:ir}),H=ar.Fp,or=ar.Fn;function sr(e){return In(ar,h,Object.assign({adjustScalarBytes:nr},e))}var cr=sr({}),lr=($n+Xn)/Qn,ur=H.pow(Yn,lr),dr=H.sqrt(H.neg(H.ONE));function fr(e){let t=($n-Zn)/Qn,n=BigInt(486662),r=H.sqr(e);r=H.mul(r,Yn);let i=H.add(r,H.ONE),a=H.neg(n),o=H.sqr(i),s=H.mul(o,i),c=H.mul(r,n);c=H.mul(c,a),c=H.add(c,o),c=H.mul(c,a);let l=H.sqr(s);o=H.sqr(l),l=H.mul(l,s),l=H.mul(l,c),o=H.mul(o,l);let u=H.pow(o,t);u=H.mul(u,l);let d=H.mul(u,dr);o=H.sqr(u),o=H.mul(o,s);let f=H.eql(o,c),p=H.cmov(d,u,f),m=H.mul(a,r),h=H.mul(u,e);h=H.mul(h,ur);let g=H.mul(h,dr),_=H.mul(c,r);o=H.sqr(h),o=H.mul(o,s);let v=H.eql(o,_),y=H.cmov(g,h,v);o=H.sqr(p),o=H.mul(o,s);let b=H.eql(o,c),x=H.cmov(m,a,b),S=H.cmov(y,p,b),C=H.isOdd(S);return S=H.cmov(S,H.neg(S),b!==C),{xMn:x,xMd:i,yMn:S,yMd:Jn}}var pr=cn(H,H.neg(BigInt(486664)));function mr(e){let{xMn:t,xMd:n,yMn:r,yMd:i}=fr(e),a=H.mul(t,i);a=H.mul(a,pr);let o=H.mul(n,r),s=H.sub(t,n),c=H.add(t,n),l=H.mul(o,c),u=H.eql(l,H.ZERO);a=H.cmov(a,H.ZERO,u),o=H.cmov(o,H.ONE,u),s=H.cmov(s,H.ONE,u),c=H.cmov(c,H.ONE,u);let[d,f]=nn(H,[o,c],!0);return{x:H.mul(a,d),y:H.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:h});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=>H.create(St(e)&xr);function Cr(e){let{d:t}=er,n=$n,r=e=>H.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=H;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){F(t,32);let{a:n,d:r}=er,i=$n,a=e=>H.create(e),o=Sr(t);if(!Tt(H.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(ye(t))}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=$n,a=e=>H.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)),H.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>H.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,h);return Tr.deriveToCurve(n)},hashToScalar(e,t={DST:Wn}){let n=Vn(e,t.DST,64,h);return or.create(St(n))},deriveToCurve(e){F(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:h,hashToGroup:Tr.hashToCurve,hashToScalar:Tr.hashToScalar});var Er=`urn:jazz:local-first`,Dr=`jazz-auth-sign-v1`,Or=M(`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=C(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,de(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,M(e))}function Fr(e){let t=pe(e),n=M(Dr),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),h(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=_(M(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=_(M(JSON.stringify({iss:Er,sub:Ir(o),aud:n,jazz_pub_key:_(o),iat:i,exp:i+r})));return`${s}.${c}.${_(cr.sign(M(`${s}.${c}`),a))}`}function U(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Br(e.serverUrl):zr)}var zr=`local`;function Br(e){let t;try{t=new ke(tt(e.trim()))}catch{throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`)}if(t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`);return`${t.origin}${t.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-DZp28PPA.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-CsIV7VoQ.js`),__vite__mapDeps([9,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-D8VoKWz0.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-v3`,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:U(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Ui(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=ct({appId:U(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:d(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:Ii(t.authMode),user:r(t.issuer,t.user_id,t.account_id)}}function Ii(e){return e===`device-account`?`local-first`:e}function Li(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Ri(e)}:Fi(e)}function Ri(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function zi(e){return JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Fi(e),...e.accountId?{registry:Ri(e)}:{}})}function Bi(e){return JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Li(e)})}function Vi(e,t){if(Bi(e)!==Bi(t)||zi(e)!==zi(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 Hi(e,t){let n=JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Li(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Ui(e){if(e.adminSecret)return`admin`;let t=ct({appId:U(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:d(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${Ii(t.authMode)}:${r(t.issuer,t.user_id,t.account_id)}`}var Wi=`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.`,Gi=` 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 Ki(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var qi=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)}},Ji=1024*1024,Yi=class{runtime;transport;sendFrames;onError;onAuxiliaryTrace;receiveDeadline;scheduled=!1;running=!1;runAgain=!1;closed=!1;outboundDrainScheduled=!1;syncPostAwaitingTimer=!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 qi(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 settleInbound(){this.closed||(await this.inboundRouting,await this.flush())}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=Zi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=Zi(t.call(this.transport,8,Ji));return n.length>0&&this.sendFrames(n),this.publishAuxiliaryTrace(),n.length>0}scheduleOutboundDrain(){if(!(this.closed||this.outboundDrainScheduled)){if(!this.syncPostAwaitingTimer){this.syncPostAwaitingTimer=!0,setTimeout(()=>{this.syncPostAwaitingTimer=!1},0);try{let e=Zi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);return}catch(e){queueMicrotask(()=>{this.closed||this.onError(e)});return}}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(Qi(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 $i()}}};function Xi(e){return e.map(e=>e.slice())}function Zi(e){return e.map(Qi)}function Qi(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 $i(){return new Promise(e=>setTimeout(e,0))}var ea=new WeakMap;function ta(e,t){let n=ea.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 na=`jazz-idb-tree`,ra=`pages`,ia=`metadata`,W=`storage-manifest`,aa=`epoch`,oa=`browser-runtime-owner`,sa=`browser-worker-epoch-v1`,ca=`jazz-browser-worker-epoch-v1`,la=`replica-node-v1`,ua=`foreground-node-leases-v1`,da=`jazz-foreground-node-leases-v1`,fa=(1n<<64n)-1n,pa=`current`,ma=1024,ha=2147483648,ga={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},_a=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},va=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 ya(e,t){return e?.name===`QuotaExceededError`?new va(e):e??Error(t)}var ba=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(ra),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(ia),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(W);r.transaction&&(e.put(ga,aa),e.put(Sa().buffer,la))}};let a;try{a=await La(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??Ca(Sa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),Ta(r)})}async returnForegroundNodeLease(e,t){if(!ja(e)||!Pa(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(!ja(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(W,`readonly`),n=G(t);try{let r=await La(t.objectStore(W).get(ua));if(await n,r===void 0)return`missing`;let i=Ea(r),a=Fa(Ca(e));return i.active.some(e=>Fa(e.node)===a)?`active`:i.reusable.some(e=>Fa(e.node)===a)?`reusable`:i.retired.some(e=>Fa(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!Ma(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?ta(t,this.name):null,i=this.db.transaction(W,`readwrite`),a=G(i);if(i.objectStore(W).put({format:ca,epoch:e},sa),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,!Ma(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(W,`readwrite`),n=G(t),r=t.objectStore(W),i=await La(r.get(sa));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(sa),await n}async metadata(){this.assertValid();let e=this.db.transaction(ia,`readonly`),t=G(e),n=await La(e.objectStore(ia).get(pa));return await t,n===void 0?null:(za(n),n)}async assertStorageManifest(){let e=this.db.transaction(W,`readonly`),t=G(e),n=await La(e.objectStore(W).get(aa));await t,Va(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(W,`readwrite`),n=G(t),r=t.objectStore(W),i=await La(r.get(oa));if(i===void 0){r.put(e,oa),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(W,`readonly`),t=G(e),n=await La(e.objectStore(W).get(la));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=xa(this.db,[W]),n=G(t),r=t.objectStore(W);try{let t=await La(r.get(ua)),i=t===void 0?wa():Ea(t),a=e(i);return Oa(i),r.put(i,ua),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)Ua(t);if(e.length===0)return[];let t=this.db.transaction(ra,`readonly`),n=G(t),r=t.objectStore(ra),i;try{i=await Promise.all(e.map(e=>La(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Ia(e[n],t))}async commit(e,t){if(this.assertValid(),Ba(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=xa(this.db,[ra,ia]),i=G(r),a=r.objectStore(ra),o=r.objectStore(ia),s=await La(o.get(pa)),c=s===void 0?0:Ra(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:na,formatVersion:1,generation:c+1};za(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await La(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,pa),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=xa(this.db,[ra,ia]),t=G(e);e.objectStore(ra).clear(),e.objectStore(ia).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 _a(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new _a(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function xa(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function Sa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return p(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Ca(e){return e.slice().buffer}function wa(){return{format:da,active:[],reusable:[],retired:[]}}function Ta(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Ea(e){return Oa(e),{format:e.format,active:e.active.map(Da),reusable:e.reusable.map(Da),retired:e.retired.map(e=>e.slice(0))}}function Da(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Oa(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]){ka(e);let t=Fa(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=Aa(e)?Fa(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function ka(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!ja(t.leaseId)||!Aa(t.node)||!Na(t.confirmedTxTime)||!Pa(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function Aa(e){return e instanceof ArrayBuffer&&e.byteLength===16}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-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 Na(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Pa(e){return e>=0n&&e<=fa}function Fa(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Ia(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 La(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(ya(e.error,`IndexedDB request failed`))})}function G(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(ya(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(ya(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function Ra(e){return za(e),e.generation}function za(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||!Ha(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Wa(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 Ba(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(!Ha(t)||t!==16384||!Wa(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Wa(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(!Wa(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Wa(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Va(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(ga).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==ga.storageEpoch||t.adapterId!==ga.adapterId||t.adapterFormatVersion!==ga.adapterFormatVersion||t.pageSize!==ga.pageSize||t.pageChecksum!==ga.pageChecksum||t.pageFormatMagic!==ga.pageFormatMagic||t.pageFormatVersion!==ga.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=ga.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 Ke(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 Ha(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=ma&&e<=ha&&Number.isInteger(Math.log2(e))}function Ua(e){if(!Wa(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Wa(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ga(){return Error(`Inspector control opening was cancelled`)}function Ka(e){try{e.postMessage({type:`close`})}catch{}e.close()}function qa(e,t){return t?t.aborted?Promise.reject(Ga()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Ga())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var Ja=Object.freeze({intervalMs:3e4,replyMs:3e4}),Ya=1e3,Xa=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;appliedFailure=void 0;appliedAuthFailure=void 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 s=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),c=(async()=>{await s;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 Yi(e,t,e=>{let t=Xi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=I(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([s,c]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(I(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 ba.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 qa(this.ready(),e),e?.aborted)throw Ga();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,Ka(t.port1))},s=()=>{this.pending.delete(n)&&(o(),r(Ga()))};e?.addEventListener(`abort`,s,{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(I(e))}try{if(await i,e?.aborted)throw o(),Ga();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,s)}}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(I(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(I(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(Ja.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+Ya){this.sendProbe();return}let e=new Ie(`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(Ja.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(I(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===`transport-state`){this.callbacks.onExplicitOfflineChange?.(t.explicitlyDisconnected);return}if(t.type===`link-fate`){this.applyLinkFate(t.fate);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===`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===`newer-build-waiting`){this.callbacks.onNewerBuild?.();return}if(t.type===`closed-for-newer-build`){this.fail(new Ie(`The shared worker closed this tab's connection for a newer build of the app`));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(P(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(P(t.error)):(this.inspectorAttachmentPhysicalDbName??=t.inspectorAttachmentPhysicalDbName??null,n.type===`init`&&(this.peerAuthority=t.peerAuthority,this.workerRealmId=t.workerRealmId),n.resolve({pendingUploads:t.pendingUploads})))};applyLinkFate(e){let t=e.failure&&JSON.stringify(e.failure);e.failure&&t!==this.appliedFailure?this.runtime.reportRemoteServerTransportError(P(e.failure.error),e.failure.retrying):!e.failure&&(this.appliedFailure||e.state===`connected`)&&this.runtime.clearRemoteServerTransportError(),this.appliedFailure=t,e.authFailure!==this.appliedAuthFailure&&(e.authFailure===null?this.callbacks.onAuthRestored():this.callbacks.onAuthFailure(e.authFailure),this.appliedAuthFailure=e.authFailure),this.callbacks.onRemoteLinkChange?.(e.state,e.link)}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()}}},Za=e=>`jazz:store-generation:${e}`;function Qa(e){try{globalThis.localStorage?.setItem(Za(e),crypto.randomUUID())}catch{}}function $a(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Za(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Za(e),r),r}catch{return null}}function eo(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Za(e))!==t}catch{return!0}}var to=class extends Error{name=`BrowserWorkerScriptLoadError`};async function no(e){let t=e.moduleUrl!==null&&Di(e.moduleUrl)!==void 0,n=e.workerUrl?await ro(e.workerUrl,e.fetch??globalThis.fetch):null;return new to(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?Gi: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 ro(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 io(e,t){if(oo(e))return new SharedWorker(Ci(e),{type:(ao(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-DTBugu7j.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Wi);return r}function ao(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function oo(e){return ao(e)||Wr()!==null}function so(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),no({workerUrl:oo(t)?Ci(t):Di(Vr()),moduleUrl:Vr(),metro:Ki()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var co=1e4,lo=8,uo=8,fo=25,po=250,mo=5*6e4,ho=1e3,go=new Map;function _o(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function vo(e,t){return[`jazz-runtime`,t,ji(e)].join(`:`)}function yo(e,t){return`${e}\u0000${t}`}var bo=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=vo(t,e.dbName),r=yo(n,e.storageOwner);if(go.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=>io(t,e),a=Date.now()+co,o=Co(n),s=0,c=null;for(let l=0;l<lo;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,_o(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=wo(n,o);break}if(c=d.message,s+=1,s>=uo)throw Error(c);let f=Math.min(fo*2**(s-1),po,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(),co);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`),go.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&go.get(r)===p&&go.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(P(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?P(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=so(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(I(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(P(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}},xo=class{callbacks;worker=null;readyPromise;initialConfigurationAdmissionRejected=!1;heldByAnotherTab=!1;olderThanStore=!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=vo(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>io(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=I(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=Co(r);for(let s=0;s<lo;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=wo(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,s=!1,c=!1,l=Date.now(),u=l+mo,d=typeof document<`u`&&document.hidden,f,p=e=>{i||(i=!0,b(),this.cancelBootstrap===h&&(this.cancelBootstrap=null),r(e))},m=e=>{if(!i){s=!0,p(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{C(),o.close()}}},h=()=>m({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=h;let g=()=>{l=Date.now(),u=l+mo},_=()=>{let e=typeof document<`u`&&document.hidden;d&&!e&&g(),d=e},v=()=>g(),y=()=>{let e=Date.now();if((d||e-l>ho*2)&&g(),l=e,e>=u){m({connected:!1,error:new Ie(`Shared browser runtime did not finish initialization within five minutes`)});return}f=setTimeout(y,Math.min(ho,u-e))},b=()=>{clearTimeout(f),f=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,_),typeof window<`u`&&window.removeEventListener(`pageshow`,v)},x=n=>{if(s){if(n.data?.type===`runtime-ready`){if(c)return;c=!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;C(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){C(),o.close(),this.worker===a&&(this.worker=null);let e=P(n.data.error);this.olderThanStore=e.message===Xe,this.heldByAnotherTab=e.message===`this account's store is open under another sign-in in another tab`?`sign-in`:e.message===`this account's store is open with another build's schema in another tab`||this.olderThanStore?`build`:!1,this.initialConfigurationAdmissionRejected=e.message===`incompatible persistent browser configuration`||this.heldByAnotherTab!==!1,p({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;C(),this.cancelBootstrap===h&&(this.cancelBootstrap=null);let r=new Xa(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=>{Qa(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{Qa(this.dbName),this.callbacks.onStorageInvalidated?.()},onNewerBuild:this.callbacks.onNewerBuild},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>p({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),p({connected:!1,error:I(e)})})},S=()=>{C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:Error(`Shared browser runtime port message error`)})},C=()=>{b(),w(),o.removeEventListener(`message`,x),o.removeEventListener(`messageerror`,S)},w=so(a,t.runtimeSources,e=>{C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:e})});o.addEventListener(`message`,x),o.addEventListener(`messageerror`,S),typeof document<`u`&&document.addEventListener(`visibilitychange`,_),typeof window<`u`&&window.addEventListener(`pageshow`,v),f=setTimeout(y,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:I(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}waitsForAnotherTab(){return this.heldByAnotherTab}isOlderThanStore(){return this.olderThanStore}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=$a(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 eo(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(),Qa(this.dbName);try{return await this.connection?.deleteStorage()}finally{Qa(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await qa(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&&So(t,this.workerName,n),t}};function So(e,t,n){e.addEventListener(`message`,e=>{e.data?.type!==`result`||e.data.workerTerminated!==!0||wo(t,n)})}function Co(e){try{let t=Number.parseInt(localStorage.getItem(To(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function wo(e,t){try{let n=To(e);return Co(e)===t&&localStorage.setItem(n,String(t+1)),Co(e)}catch{return t+1}}function To(e){return`jazz:shared-worker-generation:${e}`}function Eo(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Do(e){return[...new Set([...Eo(e)].map(e=>e.namespace))].sort()}function Oo(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function ko(e,t){let n=[...Eo(e)],r=Do(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>").${Oo(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${Oo(r)}`);return a.db}var Ao=new Map;function jo(){let e=()=>[...Ao.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...Ao.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...Ao].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...Ao.keys()].map(t=>t.waitForSync(e)))}}}function Mo(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(Ao.set(e,t),Ro(n),()=>{Ao.delete(e)})}var No=Symbol.for(`jazz-tools.window-jazz`);function Po(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 Fo=new WeakSet;function Io(e){let t=e.__jazz;return t===void 0||Lo(t)?!1:(Fo.has(e)||(Fo.add(e),console.warn(Po(t))),!0)}function Lo(e){if(!e||typeof e!=`object`)return!1;if(No in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function Ro(e){let t=Io(e),n=(t?void 0:e.__jazz)??{};n[No]=!0;let r=Object.assign(n,jo(),{async clearStorage(t){await ko(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Do(e)},async shutdown(t){let n=[...Eo(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 zo=`history.`;function Bo(e){return Vo(e)!==void 0}function Vo(e){return e.startsWith(zo)?e.slice(8):void 0}var Ho=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Uo=new WeakMap;function K(e,t){let n=Vo(t);if(n===void 0)return e[t];if(Bo(n)||!Object.hasOwn(e,n))return;let r=Uo.get(e);r||Uo.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Ho],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Wo=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Go=class extends Error{phase;constructor(e){super(e===`draining`?`Cannot operate on a Db that is shutting down or closed: it is shutting down, waiting for its pending writes to sync.`:`Cannot operate on a Db that is shutting down or closed: it is ${e}.`),this.phase=e,this.name=`DbClosedError`}},Ko=class extends Error{code;status;constructor(e,t,n=e){super(n),this.code=e,this.status=t,this.name=`AccountAuthError`}},qo=new WeakMap;function Jo(e){let t=xe(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!ze(t.iss)||!ze(t.sub))throw new Ko(`invalid_identity_token`);return{issuer:t.iss,subject:t.sub}}function Yo(e,t){return e.issuer===t.issuer&&e.subject===t.subject}async function Xo(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 Ko(`credential_refresh_timeout`)),3e4)})])}finally{n&&clearTimeout(n)}}async function Zo(e,t,n){let r=qo.get(e);if(!r||r.registry!==t)throw new Ko(`invalid_account_handle`);if(r.delegated)throw new Ko(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new Ko(`backend_account_requires_backend_host`);let i=await Xo(r.auth,n);if(qo.get(e)!==r)throw new Ko(`account_logged_out`);if(!Yo(Jo(i),e.identity))throw new Ko(`credential_identity_changed`);return i}function Qo(e){let t=qo.get(e);if(!t)throw new Ko(`invalid_account_handle`);return t.registry}var $o=new WeakMap;function es(e){return ts(e),$o.get(e)?.bearer}function ts(e){let t=$o.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 Ko(`account_handle_required`)}function ns(e,t){if(ts(e),e.accountId!==void 0){if(t.accountId!==e.accountId||t.accountRegistryAuthority!==e.accountRegistryAuthority||$o.get(e)?.inspectorPort!==void 0&&t.runtimeSources?.browserWorkerPort!==$o.get(e)?.inspectorPort)throw new Ko(`account_application_mismatch`);$o.set(t,$o.get(e))}}function rs(e){let t=e.runtimeSources?.browserWorkerPort;if(!e.accountId||!e.accountRegistryAuthority||!t)throw new Ko(`account_handle_required`);$o.set(e,{id:e.accountId,registry:e.accountRegistryAuthority,inspectorPort:t})}function is(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a whole number of rows, at least 1: a subscription's backlog cannot be unbounded.`)}var as=Object.freeze({pending:0,oldestPendingAt:null,rejected:0,lastRejection:null});function os(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function ss(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 or with another build of the app.`}[e.reason];return{kind:e.reason,message:t||n,at:Date.now()}}function cs(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 ls=Object.freeze({state:`local-only`}),us=Object.freeze({state:`connecting`}),ds=Object.freeze({state:`connected`});function q(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function fs(e){switch(e?.phase??`noServer`){case`noServer`:return ls;case`offline`:return q(`disconnected`);case`live`:return ds;case`connecting`:case`backoff`:return e.outagePublished?q(`network`):us;case`awaitingCredential`:return q(`auth`);case`stopped`:return q(`stopped`)}}function ps(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`?!0:e.reason===t.reason&&e.retrying===t.retrying&&e.authReason===t.authReason:!1}function ms(e,t=as,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:os(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function hs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&cs(e.lastError,t.lastError)&&ps(e.link,t.link)}function gs(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 _s=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 vs(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function ys(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 bs(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 xs=class extends Error{},Ss=class extends Error{};function Cs(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 Ss(`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 xs(`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(bs(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 ws(){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 Ts=[`$canRead`],Es=[`$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 Ds(e){return Ts.includes(e)}function Os(e){return Es.includes(e)}function ks(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return ws();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=ws();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 As=`__jazz_requireIncludes`;function js(e){return Array.isArray(e)?e.filter(e=>A(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function Ms(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 Ns(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Ps(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Fs(e){if(!A(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!A(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(Ps(r.from)&&Ps(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(Ps(r.fromUtf8)&&Ps(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 Is(e){let t=A(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!A(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...A(e)&&e.seed?{seed:Ls(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:js(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Ls(e){if(!A(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:js(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Is(e.gather),...Array.isArray(e.orderBy)?{orderBy:Ms(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return A(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!A(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ls(e.input)}])}),t}function Rs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function zs(e){let t={...e};return delete t[As],Us(t)}function Bs(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Vs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function Hs(e){if(e===!0)return Rs();if(!A(e))return null;if(Bs(e)){let t=Ws(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(Vs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:js(e.conditions),includes:Us(e.includes),requireIncludes:e[As]===!0,select:Ns(e.select),partialSelect:Fs(e.partialSelect??e.select),orderBy:Ms(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:Is(e.gather)};let t=Rs();return t.requireIncludes=e[As]===!0,t.includes=zs(e),t}function Us(e){if(!A(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=Hs(r);e&&(t[n]=e)}return t}function Ws(e){let t=A(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Fs(t.partialSelect??t.select);return{table:t.table,conditions:js(t.conditions),includes:Us(t.includes),requireIncludes:t[As]===!0,select:Array.isArray(t.select)?Ns(t.select):Object.keys(n),partialSelect:n,orderBy:Ms(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:Is(t.gather),...A(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!A(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ls(e.input)}])}}:{}}}var Gs=`__jazz_include_`;function Ks(e){return`${Gs}${e}`}function qs(e,t,n){let r=K(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 Js(e,t){return t?{scope:t,column:e}:{column:e}}function Ys(e,t,n){let r=K(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:Js(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:Js(e.name,t)}}))]}function Xs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=ks(n);if(r)return r;let i=K(e,t);if(i)return i.columns.find(e=>e.name===n)?.column_type}function Zs(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 Qs(e){return Zs(e)}function $s(e,t){if(e==null)return{type:`Null`};if(t.type===`Json`)return{type:`Text`,value:ys(e)};if(t.type===`Timestamp`&&e instanceof Date)return{type:`Timestamp`,value:Qs(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=>$s(e,t.element))}}if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`){if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Qs(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:Qs(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 ec(e,t){if(!(!t||e.type!==`forward`||e.nullable))return e.isArray?`MatchCorrelationCardinality`:`AtLeastOne`}function tc(e,t,n,r){let i=Xs(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 nc(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])=>tc(e,t,n,r)):[];return i.length+a.length>0?[...i,...a]:null}function rc(e){return e.length>0?[...e]:null}function ic(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 ac(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}"`);ic(e,c,i);let l=c.select.length>0?qs(e.toTable,r,c.select):[],u=c.conditions.map(t=>oc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[vs(e),t===`desc`?`Descending`:`Ascending`]),f=ac(c.includes,e.toTable,n,r,{requireIncludes:c.requireIncludes}),p=rc(l),m=r[t]?.columns.some(e=>e.name===i)?Ks(i):i;if(e.type===`forward`){let n=ec(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 oc(e,t,n,i){let a=Js(vs(e.column),i),o=vs(e.column),s=Xs(t,n,o);if(!s)throw Error(`Unknown column "${o}" in table "${n}"`);let c=e.value===void 0?!0:e.value;if(e.op===`isNull`){if(typeof c!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return c?{IsNull:{column:a}}:{IsNotNull:{column:a}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:a}};if(e.op===`ne`)return{IsNotNull:{column:a}}}if(s.type===`Row`&&ks(o)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${o}" only supports eq/ne operators.`);let a=(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 "${o}".`);return e},s=o===`$createdBy`||o===`$updatedBy`||o===`$deletedBy`,c=s?a(e.value,[`account`,`identity`]):void 0,l=a(c?c.identity:e.value,[`issuer`,`subject`]);if(typeof l.issuer!=`string`||typeof l.subject!=`string`||c&&typeof c.account!=`string`)throw Error(`Invalid structured author condition for "${o}".`);r(l.issuer,l.subject,c?.account);let u={And:[...c?[{column:`${o}.account`,op:`eq`,value:c.account}]:[],{column:`${o}${s?`.identity`:``}.issuer`,op:`eq`,value:l.issuer},{column:`${o}${s?`.identity`:``}.subject`,op:`eq`,value:l.subject}].map(e=>oc(e,t,n,i))};return e.op===`eq`?u:{Not:u}}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:a,values:e.value.map(e=>({Literal:$s(e,s)}))}};return e.op===`notIn`?{Not:t}:t}let l=e.op===`contains`&&s.type===`Array`?s.element:s,u=sc(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:$s(e.value,l)};switch(e.op){case`eq`:return{Cmp:{left:a,op:`Eq`,right:u}};case`ne`:return{Cmp:{left:a,op:`Ne`,right:u}};case`gt`:return{Cmp:{left:a,op:`Gt`,right:u}};case`gte`:return{Cmp:{left:a,op:`Ge`,right:u}};case`lt`:return{Cmp:{left:a,op:`Lt`,right:u}};case`lte`:return{Cmp:{left:a,op:`Le`,right:u}};case`contains`:return{Contains:{left:a,right:u}};default:throw Error(`Unknown operator: ${e.op}`)}}function sc(e){return typeof e!=`object`||!e?!1:e.__jazz_ir_frontier_row_id===!0}function cc(e,t,n,r){return e.length===0?`True`:e.length===1?oc(e[0],t,n,r):{And:e.map(e=>oc(e,t,n,r))}}function lc(e,t){return t===`True`?e:{Filter:{input:e,predicate:t}}}function uc(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:Js(i.fromColumn,s),right:Js(`id`,c)}:{left:Js(`id`,s),right:Js(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:Ys(o,s,i)}}}function dc(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=lc(l,cc([...u,{column:vs(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:Js(c.fromColumn,e.step_table),right:Js(`id`,p)}],join_kind:`Inner`}},columns:Ys(t,p,i)}},frontier_key:{RowId:`Current`},bound:{MaxDepth:e.max_depth},dedupe_key:[{RowId:`Current`}]}}}function fc(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 pc(e,t,n,r=!1){if(e.union){let r=e.union.inputs.map(e=>pc(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:mc({Union:{inputs:e.union.inputs.map((e,t)=>({label:e.label,input:r[t].expr}))}},e,i.outputTable),outputTable:i.outputTable}}if(!e.table)throw Error(`gather(...) seed relation is missing table metadata.`);let i={TableScan:{table:e.table}};i=lc(i,cc(e.conditions??[],n,e.table,e.table));let a=e.table;if(e.gather){let r=e.gather.seed?pc(e.gather.seed,t,n):{expr:i,outputTable:a};i=dc(e.gather,r.outputTable,r.expr,t,n),a=r.outputTable}let o=e.hops??[];i=uc(i,a,o,t,n),a=fc(a,o,t);let s=o.length?`__hop_${o.length-1}`:a;return r&&o.length===0&&!e.gather&&(i={Project:{input:i,columns:Ys(a,s,n)}}),i=mc(i,e,s),{expr:i,outputTable:a}}function mc(e,t,n){let r=e;return t.orderBy?.length&&(r={OrderBy:{input:r,terms:_c(t.orderBy).map(({column:e,direction:t})=>({column:Js(e,n),direction:t}))}}),t.offset!==void 0&&t.offset>0&&(r={Offset:{input:r,offset:t.offset}}),t.limit!==void 0&&(r={Limit:{input:r,limit:t.limit}}),r}function hc(e,t){let n=Ws(JSON.parse(e)),r=Cs(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=pc(n.gather.seed,r,t);a=dc(n.gather,e.outputTable,e.expr,r,t),o=e.outputTable,a=lc(a,cc(n.conditions,t,o,o)),a=uc(a,o,i,r,t),o=fc(o,i,r)}else{let e=pc({table:n.table,conditions:n.conditions,hops:n.hops,gather:n.gather,union:n.union},r,t);a=e.expr,o=e.outputTable}return Array.isArray(n.orderBy)&&n.orderBy.length>0&&(a={OrderBy:{input:a,terms:n.orderBy.map(([e,t])=>({column:Js(vs(e),i.length>0?`__hop_${i.length-1}`:o),direction:t===`desc`?`Desc`:`Asc`}))}}),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 gc(e){return e.union!==void 0||e.hops.length>0||e.gather!==void 0}function _c(e){return e.map(([e,t])=>({column:vs(e),direction:t===`desc`?`Desc`:`Asc`}))}function vc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}function yc(e,t,n){return e.map(e=>oc(e,t,n))}function bc(e,t,n){let r=n??Ws(JSON.parse(e)),i=Cs(t),a=gc(r)?hc(e,t):void 0,o=a?.outputTable??r.table,s=nc(r.select.length>0?qs(o,t,r.select):[],r.partialSelect,t,o),c=ac(r.includes,r.table,i,t,{requireIncludes:r.requireIncludes});if(a)return vc({table:o,array_subqueries:c,relation_ir:a.relation,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{}});let l=_c(r.orderBy),u=typeof r.limit==`number`?r.limit:void 0,d=typeof r.offset==`number`?r.offset:void 0;return vc({table:r.table,conditions:yc(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 xc(e,t){if(t.union){let n=t.union.inputs[0];if(!n)throw Error(`union(...) requires at least one relation.`);let r=xc(e,n.input);for(let n of t.union.inputs.slice(1))if(xc(e,n.input)!==r)throw Error(`union(...) requires all relations to output the same table.`);return r}let n=t.gather?.seed?xc(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 Sc(e,t){if(e)return e instanceof Map?e.get(t)??e.get(`user_${t}`):e[t]??e[`user_${t}`]}function Cc(e,t){return e?e instanceof Map?e.has(t)||e.has(`user_${t}`):t in e||`user_${t}`in e:!1}function wc(e,t,n){let r=K(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return qs(e,t,n).map(e=>{let t=ks(e);if(t)return{name:e,columnType:t};if(Ds(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 Tc(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 Ec(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=Ec(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 Dc(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 Oc(e,t,n,r){if(e.type!==`Array`)return jc(e);let i=e.value.map(e=>{if(e.type!==`Row`)return jc(e);let i=e.value.id,a=e.value.values,o=e.value.valuesByColumn;return t.baseColumns??=wc(t.relation.toTable,n,t.projection),kc(a,n,t.relation.toTable,t.nested,t.baseColumns,i,o,r,t.nestedRelationNames)});return t.relation.isArray?i:i[0]??null}function kc(e,t,n,r,i,a,o,s,c=[],l=!0){if(!K(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=Cc(o,n.name)?Sc(o,n.name):o?void 0:e[t];r!==void 0&&(u[n.name]=jc(r,n.columnType,n.name))}for(let n=0;n<r.length;n++){let a=r[n];if(!a)continue;let c=Ks(a.relation.name),l=Cc(o,c)?Sc(o,c):Cc(o,a.relation.name)?Sc(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]=Oc(l,a,t,s)}let d=l?s?.[n]:void 0;return d?Dc(u,d,c):u}function Ac(e,t){return new Date(e)}function jc(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 Ac(e.value,n);case`Bytea`:return Tc(e.value);case`Null`:return null;case`Array`:return t?.type===`Array`?e.value.map(e=>jc(e,t.element)):e.value.map(e=>jc(e));case`Row`:return t?.type===`Row`&&n&&(Os(n)||n===`$deletedBy`||n.startsWith(`$deletedBy.`))?Object.fromEntries(t.columns.map((t,r)=>[t.name,jc(e.value.values[r],t.column_type,`${n}.${t.name}`)])):t?.type===`Row`?e.value.values.map((e,n)=>jc(e,t.columns[n]?.column_type)):e.value.values.map(e=>jc(e))}}function Mc(e,t,n,r){if(!K(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Ec(t,Us(n),r??Cs(e));return{includePlans:i,includedRelationNames:i.map(e=>e.relation.name)}}function Nc(e,t,n,r,i,a,o){return e.baseColumns??=wc(r,n,i),kc(t.values,n,r,e.includePlans,e.baseColumns,t.id,t.valuesByColumn,a,e.includedRelationNames,o)}function Pc(e,t,n,r={},i,a,o=!0){let s=Mc(t,n,r);return e.map(e=>Nc(s,e,t,n,i,a,o))}function Fc(e,t,n={},r,i,a=!0,o){let s;return c=>(s??=Mc(e,t,n,o),Nc(s,c,e,t,r,i,a))}function Ic(e,t,n,r={},i,a,o=!0){let s=Pc([e],t,n,r,i,a,o)[0];if(s===void 0)throw Error(`Failed to transform row for table "${n}"`);return s}var Lc=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}},Rc=new WeakMap;function zc(e){return Rc.get(e.preparationOwner?.()??e)}function Bc(e){let t=e.preparationOwner?.()??e,n=Rc.get(t);return n||Rc.set(t,n=new Lc),n}function J(e,t){let n=zc(e);if(n?.pending)return n.run(t);let r=t();return r instanceof Promise?Bc(e).run(()=>r):r}function Vc(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`?t:void 0}var Hc=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 Uc(e){let t=Vc(e);return t!==void 0&&Hc.has(t)?t:void 0}var Wc=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`,`schema_version_unsupported`]);function Gc(e){if(!e||typeof e!=`object`)return;let t=e.reason;return typeof t==`string`&&Wc.has(t)?t:void 0}function Kc(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 qc(e,t,n,r){let i=n.filter(e=>!e.name.startsWith(Gs)),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=>!Os(e.name)).map(e=>a.get(e.name))},`valuesByColumn`,{value:a,configurable:!0})}var Jc=new WeakMap;function Yc(e){let t=Jc.get(e);return t||(t=Object.keys(e).filter(t=>e[t].computed),Jc.set(e,t)),t}var Xc=class extends Error{constructor(e){super(`Computed dependency "${e}" is unavailable.`)}},Zc=new WeakMap,Qc=class{dependencies=new Map;version=0;observedColumns(e){let t=this.dependencies.get(e);return t||(t=new Set(Zc.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=Zc.get(e);r||Zc.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 $c(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($c(r,t,n)||$c(i,t,n))return!0}else if(e instanceof Set){for(let r of e)if($c(r,t,n))return!0}for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);if(i&&`value`in i&&$c(i.value,t,n))return!0}return!1}function el(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 Xc(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;$c(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 tl=-(1n<<63n),nl=(1n<<63n)-1n,rl=-2147483648,il=2147483647;function al(e){let t=Number(e);if(!Number.isInteger(t)||t<rl||t>il)throw Error(`Integer values must be signed 32-bit integers between ${rl} and ${il}; received ${String(e)}`);return t}function ol(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<tl||t>nl)throw Error(`Invalid BigInt value. Expected signed 64-bit integer range.`);return t}function sl(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 cl(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 ll(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:al(e)};case`BigInt`:return{type:`BigInt`,value:ol(e)};case`Double`:return{type:`Double`,value:Number(e)};case`Timestamp`:return{type:`Timestamp`,value:sl(e)};case`Uuid`:return{type:`Uuid`,value:String(e)};case`Bytea`:return{type:`Bytea`,value:cl(e)};case`Json`:return{type:`Text`,value:ys(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=>ll(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=>ll(n[e.name],e.column_type))}}}default:throw Error(`Unsupported column type: ${t.type}`)}}function ul(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`&&dl(t,a,e.column_type.schema),i[t]=ll(a,e.column_type)}return i}function dl(e,t,n){if(!n)return;let r=fl(t,n);if(r)throw Error(`encoding error: JSON schema validation failed for column \`${e}\`: ${r}`)}function fl(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=pl(t),i=new Set(ml(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=fl(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=hl(t.minLength);if(n!=null&&e.length<n)return`${JSON.stringify(e)} is shorter than ${n} character${n===1?``:`s`}`;let r=hl(t.maxLength);if(r!=null&&e.length>r)return`${JSON.stringify(e)} is longer than ${r} characters`;let i=gl(t.pattern);return i&&!new RegExp(i).test(e)?`${JSON.stringify(e)} does not match ${JSON.stringify(_l(i))}`:null}if(n===`integer`){if(typeof e!=`number`||!Number.isInteger(e))return`${JSON.stringify(e)} is not an integer`;let n=hl(t.minimum);if(n!=null&&e<n)return`${e} is less than the minimum of ${n}`;let r=hl(t.maximum);return r!=null&&e>r?`${e} is greater than the maximum of ${r}`:null}return null}function pl(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 ml(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function hl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function gl(e){return typeof e==`string`?e:null}function _l(e){return e.replaceAll(`\\d`,`[0-9]`)}var vl=1e3,yl=5*6e4;function bl(e){return Math.min(yl,vl*2**Math.min(e,20))}var xl=class{streak=0;next(){let e=this.streak++;return e===0?0:bl(e-1)}reset(){this.streak=0}},Sl=new WeakMap;function Cl(e){let t=Sl.get(e);if(t?.size)for(let e of[...t])try{e()}catch(e){console.error(`Jazz local write observer failed`,e)}}var wl=Symbol.for(`jazz-tools.shippedMigrations`);function Tl(e){return e[wl]}function El(e){return!!e.adminSecret}function Dl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,policies:void 0}]))}var Ol=new WeakMap;function kl(e){let t=Ol.get(e);if(t)return t;let n=Dl(e);return Ol.set(e,n),n}var Al=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&&El(t)?kl(e):e,i=Ye(r);if(this.client){if(!this.clientSchema||Ye(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};ns(t,a),O(a,d(t));let o=n.createClient({config:a,schema:r,migrations:Tl(e),onAuthFailure:e=>this.host.markUnauthenticated(e),onAuthRestored:()=>this.host.clearAuthError(),foregroundNodeLease:this.foregroundNodeLease});o.onMutationError(e=>this.host.onMutationError(e)),fe(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:Ye(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 ms(e);let t=this.client?.getRuntime();return ms(e,t?.uploadStatus?.()??as,t?.lastLinkFailure?.()??null)}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?ls:this.isExplicitlyOffline()?q(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??us;return e.state===`local-only`?us: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()}},jl=class extends Al{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()}}},Ml=`jazz:indexeddb-invalidation-reload`,Nl=1e4;function Pl(e={}){let t=(e.now??Date.now)();try{let n=e.storage??globalThis.sessionStorage,r=Number(n.getItem(Ml)??0);if(Number.isFinite(r)&&t-r<Nl)return!1;n.setItem(Ml,String(t))}catch{}return(e.reload??(()=>globalThis.location.reload()))(),!0}async function Fl(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 Il=`store_held_by_another_tab`,Ll=class extends Error{name=`StoreHeldByAnotherTabError`;code=Il;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)}},Rl=Symbol.for(`jazz.browser-inspector-control-registry`);function zl(){let e=globalThis;return e[Rl]??={factories:new Map,nextFactoryId:1}}function Bl(e,t){e.getConfig=t;let n=zl(),r=n.nextFactoryId++;return n.factories.set(r,e),()=>n.factories.delete(r)}var Vl=[],Hl=!1,Ul=Promise.resolve(),Wl=!1;function Gl(e){return typeof window>`u`||typeof window.addEventListener!=`function`?()=>{}:(Kl(),Vl.push(e),()=>{let t=Vl.indexOf(e);t!==-1&&Vl.splice(t,1)})}function Kl(){Wl||(Wl=!0,window.addEventListener(`pagehide`,e=>{e.persisted&&ql()}),window.addEventListener(`pageshow`,e=>{e.persisted&&Jl()}))}function ql(){if(!Hl){Hl=!0;for(let e of[...Vl])try{e.leave()}catch(e){console.warn(`Jazz could not let go of a page lock for the back/forward cache.`,e)}}}function Jl(){if(!Hl)return;Hl=!1;let e=[...Vl];Ul=Ul.then(async()=>{for(let t of e){if(Hl)return;if(Vl.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 Yl=`jazz:newer-build-reloaded-from`,Xl;function Zl(e){let t=2166136261;for(let n of Ye(e))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(16)}function Ql(e,t={}){try{return(t.storage??globalThis.sessionStorage).getItem(Yl)!==e}catch{return!0}}function $l(e,t={}){let n=()=>{try{(t.storage??globalThis.sessionStorage).setItem(Yl,e)}catch{}(t.reload??(()=>globalThis.location.reload()))()};if(!Xl)return n();try{Xl(n)}catch(e){console.warn(`Jazz: onNewerBuild threw; reloading for the newer build.`,e),n()}}var eu=class e extends Al{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;olderBuildError=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))}get dbStopping(){return this.host.phase!==`open`||this.host.draining}get dbClosing(){return this.host.phase!==`open`}getClient(e){if(this.olderBuildError)throw this.olderBuildError;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??=Gl({leave:()=>this.leaveForPageCache(),return:()=>this.returnFromPageCache()})}leaveForPageCache(){let e=this.connection;if(!e||this.pageAway||this.shutdownStarted||this.dbStopping||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.dbClosing||!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`),Pl(),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};ns(this.host.config,t),O(t,d(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,I(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r),onNewerBuild:()=>this.yieldToNewerBuild(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=Bl(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,I(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 Ie&&this.shutdownFailure.abandon(t);return}if(this.connection!==e)return;this.connectionError=t,this.recoverableConnectionFailure=!0,this.rejectReconnectWaiters(t),this.notifyWorkerRemoteLink(),e.isOlderThanStore?.()&&this.yieldToNewerBuild(e);let n=this.admissionRefused(e);n?this.startHeldPatience():t instanceof Ie||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof Ie||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.dbClosing)&&(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?.waitsForAnotherTab?.()}yieldToNewerBuild(e){if(this.olderBuildError||this.shutdownStarted||this.dbStopping)return;let t=this.browserConnectionInput;if(this.connection!==e||!t)return;let n=Zl(t.schema);Ql(n)&&(this.olderBuildError=Error(`This tab runs an older build of this app than another tab, which has its local store now: reload this tab`),this.getCurrentClient()?.refuseWrites?.(this.olderBuildError),this.wakeReplacementWaiters(),(async()=>{await e.flushLocal().catch(()=>void 0),await e.shutdown().catch(()=>void 0)})().then(()=>$l(n)))}heldByAnotherTabError(e,t){return e.waitsForAnotherTab?.()===`build`?new Ll(`Another tab runs another build of this app (another schema) and holds this account's local store: reload the tab that runs the older build, which may be this one (reloading picks up the newest build), or close it. This tab joins once the other lets go; reloading this tab loses its unsynced writes`,{cause:t}):new Ll(void 0,{cause:t})}replacementOf(e,t){return new Promise(n=>{let r=()=>{this.connection===e&&!this.olderBuildError&&!this.heldTooLong&&!this.shutdownStarted&&!this.dbStopping&&!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.dbClosing||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.dbClosing||this.storageReset)){if(this.admissionRefused(e)){await this.retryConfigurationAdmission(e),await this.connectionReady;return}this.connectionError instanceof Ie&&(this.reopenFailedFollower(),await this.connectionReady)}}).catch(e=>{this.connectionError??=I(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.olderBuildError)throw this.olderBuildError;if(this.dbStopping||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.dbStopping||t?.aborted)&&(r??=this.connection??await this.pageAway?.reopened??await this.configurationAdmissionRetry,i&&r&&(r=await this.retryConfigurationAdmission(r)),!(this.dbStopping||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 this.heldByAnotherTabError(r,e);if(await this.replacementOf(r,t),this.olderBuildError)throw this.olderBuildError;if(this.dbStopping||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.dbStopping){if(this.connectionError)throw this.connectionError;if(e!==`runtime`)for(;;){for(;this.disconnected;)if(await this.waitForReconnect(t),this.dbStopping||t?.aborted)return;if(await this.transportTransition,!this.disconnected||this.dbStopping||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.dbClosing||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(tu(this.host.config)),nu(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}};O(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Vi(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(tu(t)),nu(t)).catch(e=>{this.observeConnectionFailure(n,I(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 qa(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=Fl([()=>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??=I(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`),Pl())}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 Ie&&u(n);try{await Fl([()=>{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 Ie&&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 q(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return us;if(this.connectionError)return q(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?us:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return ds;case`unavailable`:return q(`network`);default:return us}}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 tu(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function nu(e){return ct({...e,trustedReservedSession:d(e)})?.claims??{}}var ru=new WeakMap,iu=new WeakSet;function au(e){return iu.has(typeof e?.current==`function`?e.current():e)}async function ou(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=ru.get(e);if(n)return await n(t);if(au(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 su=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}},cu=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}},lu=30;function uu(e){return e??{type:`persistent`}}function du(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function fu(e){let t=uu(e.driver);return du((t.type===`persistent`?t.dbName:void 0)??e.dbName)??U(e)}function pu(e){return Hi(e,fu(e))}function mu(e){if(!e)return;let t=e;se(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])}let a=t.backlogRows;return a!==void 0&&(is(a,`backlogRows`),n.backlogRows=a),it(e)&&(n.tier=`local-only`),n}var hu=new WeakMap,gu=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getDeviceAccountProof.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 _u(e){let t=hu.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function vu(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 yu(e,t,n,r){let i=K(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,ll(s[t],vu(e,t).column_type)]))}}function bu(e,t,n,r){let i=yu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:yu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:yu(e,t,r,`schema`)}}}function xu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:yu(e,t,r,`table`)}}function Su(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:bu(e,t,r,i)}}function Cu(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 wu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function Tu(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 ee,Nt as te,O as ne,Ot as O,P as re,Pt as ie,Q as ae,Qt as oe,R as se,Rt as k,S as ce,St as A,T as le,Tt as j,U as ue,Ut as de,V as fe,Vt as pe,W as me,Wt as M,X as he,Xt as N,Y as ge,Yt as _e,Z as ve,Zt as ye,_ as be,_t as xe,an as P,at as Se,b as Ce,bt as we,cn as Te,ct as Ee,dn as De,dt as Oe,en as ke,et as Ae,ft as je,g as Me,gt as Ne,h as Pe,ht as Fe,in as Ie,it as Le,j as Re,jt as ze,k as Be,kt as Ve,ln as He,m as Ue,mt as We,nt as Ge,on as Ke,ot as qe,pt as Je,q as Ye,qt as F,rn as Xe,rt as Ze,sn as Qe,st as $e,t as et,tt,v as nt,vt as rt,w as it,wt as I,x as at,xt as ot,y as st,yt as ct,z as lt,zt as ut}from"./src-C1yTrMsg.js";var dt=Te(),L=De(He(),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,u=({data:e})=>{let t=!1;if(e.type===`link-fate`&&(t=l===null&&e.fate.authFailure!==null,l=e.fate.authFailure),e.type===`error`||t||e.type===`storage-invalidated`||e.type===`storage-reset`){d();return}if(e.type!==`inspector-query-result`&&e.type!==`result`||e.id>=-1)return;let n=e.error&&P(e.error),r=s.get(e.id);if(r){s.delete(e.id),n?r.reject(n):e.type===`inspector-query-result`?r.resolve(e.value):r.reject(Error(`Unexpected Inspector query response`));return}let i=c.get(e.id);i&&(n||e.type===`inspector-query-result`)&&i.callback?.(n??e.value)},d=()=>{if(i)return;i=!0,t.removeEventListener(`message`,u),t.removeEventListener(`messageerror`,f);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()},f=()=>d();t.addEventListener(`message`,u),t.addEventListener(`messageerror`,f);let p=e=>e===`local-only`,m=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 m({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,m({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)=>p(r)?i?Promise.reject(Error(`Inspector cache connection closed`)):m({type:`inspect-query`,query:t,options:a}):e.query(t,n,r,a);if(s===`createSubscription`)return(n,r,a,o)=>{if(!p(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()=>(d(),e.close());if(s===`discard`)return()=>(d(),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 x(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(_e(e))}function St(e){return bt(_e(Et(F(e)).reverse()))}function Ct(e,t){x(t),e=vt(e);let n=ye(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 R=BigInt(0),z=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 B(e,t){let n=e%t;return n>=R?n:t+n}function Wt(e,t,n){let r=e;for(;t-- >R;)r*=r,r%=n;return r}function Gt(e,t){if(e===R)throw Error(`invert: expected non-zero number`);if(t<=R)throw Error(`invert: expected positive modulus, got `+t);let n=B(e,t),r=t,i=R,a=z,o=z,s=R;for(;n!==R;){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!==z)throw Error(`invert: does not exist`);return B(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+z)/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-z,n=0;for(;t%It===R;)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+z)/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=z<<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)=>(B(e,t)&z)===z,$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<R)throw Error(`invalid exponent, negatives unsupported`);if(n===R)return e.ONE;if(n===z)return t;let r=e.ONE,i=t;for(;n>R;)n&z&&(r=e.mul(r,i)),i=e.sqr(i),n>>=z;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-z)/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&&x(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=R;ONE=z;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=R)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 B(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return R<=e&&e<this.ORDER}is0(e){return e===R}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return B(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return B(e*e,this.ORDER)}add(e,t){return B(e+t,this.ORDER)}sub(e,t){return B(e-t,this.ORDER)}mul(e,t){return B(e*t,this.ORDER)}pow(e,t){return tn(this,e,t)}div(e,t){return B(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){F(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=B(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){F(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=B(n?St(e):xt(e),t-z)+z;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),V=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)-V,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?V: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:V};if(u!==V)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,V,c(a.Gx*a.Gy));static ZERO=new m(An,V,V,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,V,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=Et(F(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-V),c(o*p-i));if(!h)throw Error(`bad point: invalid y coordinate`);let _=(g&V)===V,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(ye(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===V?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===V?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&V?128:0,n}toHex(){return _e(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 _e(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,n,r={}){if(typeof n!=`function`)throw Error(`"hash" function param is required`);Nt(r,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:i}=r,{BASE:a,Fp:o,Fn:s}=e,c=r.randomBytes||t,l=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,n)=>{if(_t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function d(e){return s.create(St(e))}function f(e){let t=b.secretKey;F(e,b.secretKey,`secretKey`);let r=F(n(e),2*t,`hashedSecretKey`),i=l(r.slice(0,t));return{head:i,prefix:r.slice(t,2*t),scalar:d(i)}}function p(e){let{head:t,prefix:n,scalar:r}=f(e),i=a.multiply(r);return{head:t,prefix:n,scalar:r,point:i,pointBytes:i.toBytes()}}function m(e){return p(e).pointBytes}function h(e=Uint8Array.of(),...t){return d(n(u(N(...t),F(e,void 0,`context`),!!i)))}function g(e,t,n={}){e=F(e,void 0,`message`),i&&(e=i(e));let{prefix:r,scalar:o,pointBytes:c}=p(t),l=h(n.context,r,e),u=a.multiply(l).toBytes(),d=h(n.context,u,c,e),f=s.create(l+d*o);if(!s.isValid(f))throw Error(`sign failed: invalid s`);return F(N(u,s.toBytes(f)),b.signature,`result`)}let _={zip215:!0};function v(t,n,r,o=_){let{context:s,zip215:c}=o,l=b.signature;t=F(t,l,`signature`),n=F(n,void 0,`message`),r=F(r,b.publicKey,`publicKey`),c!==void 0&&_t(c,`zip215`),i&&(n=i(n));let u=l/2,d=t.subarray(0,u),f=St(t.subarray(u,l)),p,m,g;try{p=e.fromBytes(r,c),m=e.fromBytes(d,c),g=a.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=h(s,m.toBytes(),p.toBytes(),n);return m.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=o.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function x(e=c(b.seed)){return F(e,b.seed,`seed`)}function S(e){return oe(e)&&e.length===s.BYTES}function C(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let w={getExtendedPublicKey:p,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:C,toMontgomery(t){let{y:n}=e.fromBytes(t),r=b.publicKey,i=r===32;if(!i&&r!==57)throw Error(`only defined for 25519 and 448`);let a=i?o.div(V+n,V-n):o.div(n-V,n+V);return o.toBytes(a)},toMontgomerySecret(e){let t=b.secretKey;return F(e,t),l(n(e.subarray(0,t))).subarray(0,t)}};return Object.freeze({keygen:kn(x,m),getPublicKey:m,sign:g,verify:v,utils:w,Point:e,lengths:b})}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(!oe(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){F(e),yt(n),t=Bn(t),t.length>255&&(t=r(N(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=N(t,Rn(t.length,1)),c=Rn(0,a),l=Rn(n,2),u=Array(o),d=r(N(c,e,l,Rn(0,1),s));u[0]=r(N(d,Rn(1,1),s));for(let e=1;e<=o;e++)u[e]=r(N(zn(d,u[e-1]),Rn(e+1,1),s));return N(...u).slice(0,n)}function Hn(e,t,n,r,i){if(F(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`),F(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]=B(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:n,Point:r,hash:i}=e,{Fn:a}=r,o=(t,n)=>e.hashToGroup(t,{DST:N(Dt(`HashToGroup-`),n)}),s=(t,n)=>e.hashToScalar(t,{DST:N(Wn,n)}),c=(e=t)=>{let n=dn(e(un(a.ORDER)),a.ORDER,a.isLE);return a.isLE?St(n):xt(n)},l=(e,t)=>En(r,e,t),u=e=>N(Dt(`OPRFV1-`),new Uint8Array([e]),Dt(`-`+n)),d=u(0),f=u(1),p=u(2);function m(...e){let t=[];for(let n of e)typeof n==`number`?t.push(Ct(n,2)):typeof n==`string`?t.push(Dt(n)):(F(n),t.push(Ct(n.length,2),n));return N(...t)}let h=(...e)=>i(m(...e,`Finalize`));function g(e,t,n,r){let a=i(m(e.toBytes(),N(Dt(`Seed-`),r))),o=[];for(let e=0;e<t.length;e++){let i=t[e].toBytes(),c=n[e].toBytes(),l=s(m(a,e,i,c,`Composite`),r);o.push(l)}return o}function _(e,t,n,r){let i=g(e,t,n,r);return{M:l(t,i),Z:l(n,i)}}function v(e,t,n,r,i){let a=l(n,g(t,n,r,i));return{M:a,Z:a.multiply(e)}}function y(e,t,n,r,i,a){let[o,c,l,u,d]=[e,t,n,r,i].map(e=>e.toBytes());return s(m(o,c,l,u,d,`Challenge`),a)}function b(e,t,n,i,o,s){let{M:l,Z:u}=v(t,n,i,o,e),d=c(s),f=y(n,l,u,r.BASE.multiply(d),l.multiply(d),e);return N(...[f,a.sub(d,a.mul(f,t))].map(e=>a.toBytes(e)))}function x(e,t,n,i,o){F(o,2*a.BYTES);let{M:s,Z:c}=_(t,n,i,e),[l,u]=[o.subarray(0,a.BYTES),o.subarray(a.BYTES)].map(e=>a.fromBytes(e)),d=y(t,s,c,r.BASE.multiply(u).add(t.multiply(l)),s.multiply(u).add(c.multiply(l)),e);if(!a.eql(l,d))throw Error(`proof verification failed`)}function S(){let e=c(),t=r.BASE.multiply(e);return{secretKey:a.toBytes(e),publicKey:t.toBytes()}}function C(t,n,i){let o=N(Dt(`DeriveKeyPair`),t),s=N(n,m(i),Uint8Array.of(0));for(let t=0;t<=255;t++){s[s.length-1]=t;let n=e.hashToScalar(s,{DST:o});if(!a.is0(n))return{secretKey:a.toBytes(n),publicKey:r.BASE.multiply(n).toBytes()}}throw Error(`Cannot derive key`)}function w(e,n,i=t){let s=c(i),l=o(n,e);if(l.equals(r.ZERO))throw Error(`Input point at infinity`);let u=l.multiply(s);return{blind:a.toBytes(s),blinded:u.toBytes()}}function T(e,t,n){let i=a.fromBytes(t),s=o(n,e);if(s.equals(r.ZERO))throw Error(`Input point at infinity`);return h(n,s.multiply(i).toBytes())}let E={generateKeyPair:S,deriveKeyPair:(e,t)=>C(d,e,t),blind:(e,n=t)=>w(d,e,n),blindEvaluate(e,t){let n=a.fromBytes(e);return r.fromBytes(t).multiply(n).toBytes()},finalize(e,t,n){let i=a.fromBytes(t);return h(e,r.fromBytes(n).multiply(a.inv(i)).toBytes())},evaluate:(e,t)=>T(d,e,t)};return Object.freeze({name:n,oprf:E,voprf:{generateKeyPair:S,deriveKeyPair:(e,t)=>C(f,e,t),blind:(e,n=t)=>w(f,e,n),blindEvaluateBatch(e,n,i,o=t){if(!Array.isArray(i))throw Error(`expected array`);let s=a.fromBytes(e),c=r.fromBytes(n),l=i.map(r.fromBytes),u=l.map(e=>e.multiply(s)),d=b(f,s,c,l,u,o);return{evaluated:u.map(e=>e.toBytes()),proof:d}},blindEvaluate(e,n,r,i=t){let a=this.blindEvaluateBatch(e,n,[r],i);return{evaluated:a.evaluated[0],proof:a.proof}},finalizeBatch(e,t,n){if(!Array.isArray(e))throw Error(`expected array`);return x(f,r.fromBytes(t),e.map(e=>e.blinded).map(r.fromBytes),e.map(e=>e.evaluated).map(r.fromBytes),n),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(f,e,t)},poprf:e=>{let n=s(m(`Info`,e),p),i=r.BASE.multiply(n);return{generateKeyPair:S,deriveKeyPair:(e,t)=>C(p,e,t),blind(e,n,s=t){let l=r.fromBytes(n),u=i.add(l);if(u.equals(r.ZERO))throw Error(`tweakedKey point at infinity`);let d=c(s),f=o(e,p);if(f.equals(r.ZERO))throw Error(`Input point at infinity`);let m=f.multiply(d);return{blind:a.toBytes(d),blinded:m.toBytes(),tweakedKey:u.toBytes()}},blindEvaluateBatch(e,i,o=t){if(!Array.isArray(i))throw Error(`expected array`);let s=a.fromBytes(e),c=a.add(s,n),l=a.inv(c),u=i.map(r.fromBytes),d=u.map(e=>e.multiply(l)),f=b(p,c,r.BASE.multiply(c),d,u,o);return{evaluated:d.map(e=>e.toBytes()),proof:f}},blindEvaluate(e,n,r=t){let i=this.blindEvaluateBatch(e,[n],r);return{evaluated:i.evaluated[0],proof:i.proof}},finalizeBatch(t,n,i){if(!Array.isArray(t))throw Error(`expected array`);let o=t.map(e=>e.evaluated).map(r.fromBytes);return x(p,r.fromBytes(i),o,t.map(e=>e.blinded).map(r.fromBytes),n),t.map((t,n)=>{let r=a.fromBytes(t.blind),i=o[n].multiply(a.inv(r)).toBytes();return h(t.input,e,i)})},finalize(e,t,n,r,i,a){return this.finalizeBatch([{input:e,blind:t,evaluated:n,blinded:r}],i,a)[0]},evaluate(t,i){let s=a.fromBytes(t),c=o(i,p);if(c.equals(r.ZERO))throw Error(`Input point at infinity`);let l=a.add(s,n),u=a.inv(l);return h(i,e,c.multiply(u).toBytes())}}},__tests:{Fn:a}})}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=B(t*t*t,n),i=tr(e*B(r*r*t,n)).pow_p_5_8,a=B(e*r*i,n),o=B(t*a*a,n),s=a,c=B(a*rr,n),l=o===e,u=o===B(-e,n),d=o===B(-e*rr,n);return l&&(a=s),(u||d)&&(a=c),Qt(a,n)&&(a=B(-a,n)),{isValid:l||u,value:a}}var ar=Pn(er,{uvRatio:ir}),H=ar.Fp,or=ar.Fn;function sr(e){return In(ar,h,Object.assign({adjustScalarBytes:nr},e))}var cr=sr({}),lr=($n+Xn)/Qn,ur=H.pow(Yn,lr),dr=H.sqrt(H.neg(H.ONE));function fr(e){let t=($n-Zn)/Qn,n=BigInt(486662),r=H.sqr(e);r=H.mul(r,Yn);let i=H.add(r,H.ONE),a=H.neg(n),o=H.sqr(i),s=H.mul(o,i),c=H.mul(r,n);c=H.mul(c,a),c=H.add(c,o),c=H.mul(c,a);let l=H.sqr(s);o=H.sqr(l),l=H.mul(l,s),l=H.mul(l,c),o=H.mul(o,l);let u=H.pow(o,t);u=H.mul(u,l);let d=H.mul(u,dr);o=H.sqr(u),o=H.mul(o,s);let f=H.eql(o,c),p=H.cmov(d,u,f),m=H.mul(a,r),h=H.mul(u,e);h=H.mul(h,ur);let g=H.mul(h,dr),_=H.mul(c,r);o=H.sqr(h),o=H.mul(o,s);let v=H.eql(o,_),y=H.cmov(g,h,v);o=H.sqr(p),o=H.mul(o,s);let b=H.eql(o,c),x=H.cmov(m,a,b),S=H.cmov(y,p,b),C=H.isOdd(S);return S=H.cmov(S,H.neg(S),b!==C),{xMn:x,xMd:i,yMn:S,yMd:Jn}}var pr=cn(H,H.neg(BigInt(486664)));function mr(e){let{xMn:t,xMd:n,yMn:r,yMd:i}=fr(e),a=H.mul(t,i);a=H.mul(a,pr);let o=H.mul(n,r),s=H.sub(t,n),c=H.add(t,n),l=H.mul(o,c),u=H.eql(l,H.ZERO);a=H.cmov(a,H.ZERO,u),o=H.cmov(o,H.ONE,u),s=H.cmov(s,H.ONE,u),c=H.cmov(c,H.ONE,u);let[d,f]=nn(H,[o,c],!0);return{x:H.mul(a,d),y:H.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:h});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=>H.create(St(e)&xr);function Cr(e){let{d:t}=er,n=$n,r=e=>H.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=H;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){F(t,32);let{a:n,d:r}=er,i=$n,a=e=>H.create(e),o=Sr(t);if(!Tt(H.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(ye(t))}toBytes(){let{X:e,Y:t,Z:n,T:r}=this.ep,i=$n,a=e=>H.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)),H.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:r,Y:i}=e.ep,a=e=>H.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,h);return Tr.deriveToCurve(n)},hashToScalar(e,t={DST:Wn}){let n=Vn(e,t.DST,64,h);return or.create(St(n))},deriveToCurve(e){F(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:h,hashToGroup:Tr.hashToCurve,hashToScalar:Tr.hashToScalar});var Er=`urn:jazz:local-first`,Dr=`jazz-auth-sign-v1`,Or=M(`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=C(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,de(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,M(e))}function Fr(e){let t=pe(e),n=M(Dr),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),h(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=_(M(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=_(M(JSON.stringify({iss:Er,sub:Ir(o),aud:n,jazz_pub_key:_(o),iat:i,exp:i+r})));return`${s}.${c}.${_(cr.sign(M(`${s}.${c}`),a))}`}function U(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Br(e.serverUrl):zr)}var zr=`local`;function Br(e){let t;try{t=new ke(tt(e.trim()))}catch{throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`)}if(t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`Invalid server URL "${e}": expected http://, https://, ws://, or wss://`);return`${t.origin}${t.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-DZp28PPA.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-CsIV7VoQ.js`),__vite__mapDeps([9,1,4,5,6,7]),import.meta.url),e(()=>import(`./esm-D8VoKWz0.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-v3`,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:U(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Ui(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=ct({appId:U(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:d(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:Ii(t.authMode),user:r(t.issuer,t.user_id,t.account_id)}}function Ii(e){return e===`device-account`?`local-first`:e}function Li(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Ri(e)}:Fi(e)}function Ri(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function zi(e){return JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Fi(e),...e.accountId?{registry:Ri(e)}:{}})}function Bi(e){return JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Li(e)})}function Vi(e,t){if(Bi(e)!==Bi(t)||zi(e)!==zi(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 Hi(e,t){let n=JSON.stringify({version:1,appId:U(e),env:e.env??`dev`,auth:Li(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Ui(e){if(e.adminSecret)return`admin`;let t=ct({appId:U(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:d(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${Ii(t.authMode)}:${r(t.issuer,t.user_id,t.account_id)}`}var Wi=`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.`,Gi=` 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 Ki(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var qi=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)}},Ji=1024*1024,Yi=class{runtime;transport;sendFrames;onError;onAuxiliaryTrace;receiveDeadline;scheduled=!1;running=!1;runAgain=!1;closed=!1;outboundDrainScheduled=!1;syncPostAwaitingTimer=!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 qi(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 settleInbound(){this.closed||(await this.inboundRouting,await this.flush())}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=Zi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=Zi(t.call(this.transport,8,Ji));return n.length>0&&this.sendFrames(n),this.publishAuxiliaryTrace(),n.length>0}scheduleOutboundDrain(){if(!(this.closed||this.outboundDrainScheduled)){if(!this.syncPostAwaitingTimer){this.syncPostAwaitingTimer=!0,setTimeout(()=>{this.syncPostAwaitingTimer=!1},0);try{let e=Zi(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);return}catch(e){queueMicrotask(()=>{this.closed||this.onError(e)});return}}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(Qi(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 $i()}}};function Xi(e){return e.map(e=>e.slice())}function Zi(e){return e.map(Qi)}function Qi(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 $i(){return new Promise(e=>setTimeout(e,0))}var ea=new WeakMap;function ta(e,t){let n=ea.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 na=`jazz-idb-tree`,ra=`pages`,ia=`metadata`,W=`storage-manifest`,aa=`epoch`,oa=`browser-runtime-owner`,sa=`browser-worker-epoch-v1`,ca=`jazz-browser-worker-epoch-v1`,la=`replica-node-v1`,ua=`foreground-node-leases-v1`,da=`jazz-foreground-node-leases-v1`,fa=(1n<<64n)-1n,pa=`current`,ma=1024,ha=2147483648,ga={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},_a=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},va=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 ya(e,t){return e?.name===`QuotaExceededError`?new va(e):e??Error(t)}var ba=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(ra),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(ia),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(W);r.transaction&&(e.put(ga,aa),e.put(Sa().buffer,la))}};let a;try{a=await La(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??Ca(Sa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),Ta(r)})}async returnForegroundNodeLease(e,t){if(!ja(e)||!Pa(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(!ja(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(W,`readonly`),n=G(t);try{let r=await La(t.objectStore(W).get(ua));if(await n,r===void 0)return`missing`;let i=Ea(r),a=Fa(Ca(e));return i.active.some(e=>Fa(e.node)===a)?`active`:i.reusable.some(e=>Fa(e.node)===a)?`reusable`:i.retired.some(e=>Fa(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!Ma(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?ta(t,this.name):null,i=this.db.transaction(W,`readwrite`),a=G(i);if(i.objectStore(W).put({format:ca,epoch:e},sa),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,!Ma(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(W,`readwrite`),n=G(t),r=t.objectStore(W),i=await La(r.get(sa));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(sa),await n}async metadata(){this.assertValid();let e=this.db.transaction(ia,`readonly`),t=G(e),n=await La(e.objectStore(ia).get(pa));return await t,n===void 0?null:(za(n),n)}async assertStorageManifest(){let e=this.db.transaction(W,`readonly`),t=G(e),n=await La(e.objectStore(W).get(aa));await t,Va(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(W,`readwrite`),n=G(t),r=t.objectStore(W),i=await La(r.get(oa));if(i===void 0){r.put(e,oa),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(W,`readonly`),t=G(e),n=await La(e.objectStore(W).get(la));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=xa(this.db,[W]),n=G(t),r=t.objectStore(W);try{let t=await La(r.get(ua)),i=t===void 0?wa():Ea(t),a=e(i);return Oa(i),r.put(i,ua),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)Ua(t);if(e.length===0)return[];let t=this.db.transaction(ra,`readonly`),n=G(t),r=t.objectStore(ra),i;try{i=await Promise.all(e.map(e=>La(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Ia(e[n],t))}async commit(e,t){if(this.assertValid(),Ba(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=xa(this.db,[ra,ia]),i=G(r),a=r.objectStore(ra),o=r.objectStore(ia),s=await La(o.get(pa)),c=s===void 0?0:Ra(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:na,formatVersion:1,generation:c+1};za(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await La(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,pa),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=xa(this.db,[ra,ia]),t=G(e);e.objectStore(ra).clear(),e.objectStore(ia).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 _a(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new _a(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function xa(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function Sa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return p(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Ca(e){return e.slice().buffer}function wa(){return{format:da,active:[],reusable:[],retired:[]}}function Ta(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Ea(e){return Oa(e),{format:e.format,active:e.active.map(Da),reusable:e.reusable.map(Da),retired:e.retired.map(e=>e.slice(0))}}function Da(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Oa(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]){ka(e);let t=Fa(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=Aa(e)?Fa(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function ka(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!ja(t.leaseId)||!Aa(t.node)||!Na(t.confirmedTxTime)||!Pa(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function Aa(e){return e instanceof ArrayBuffer&&e.byteLength===16}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-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 Na(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Pa(e){return e>=0n&&e<=fa}function Fa(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Ia(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 La(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(ya(e.error,`IndexedDB request failed`))})}function G(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(ya(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(ya(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function Ra(e){return za(e),e.generation}function za(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||!Ha(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Wa(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 Ba(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(!Ha(t)||t!==16384||!Wa(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Wa(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(!Wa(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Wa(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Va(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(ga).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==ga.storageEpoch||t.adapterId!==ga.adapterId||t.adapterFormatVersion!==ga.adapterFormatVersion||t.pageSize!==ga.pageSize||t.pageChecksum!==ga.pageChecksum||t.pageFormatMagic!==ga.pageFormatMagic||t.pageFormatVersion!==ga.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=ga.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 Ke(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 Ha(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=ma&&e<=ha&&Number.isInteger(Math.log2(e))}function Ua(e){if(!Wa(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Wa(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ga(){return Error(`Inspector control opening was cancelled`)}function Ka(e){try{e.postMessage({type:`close`})}catch{}e.close()}function qa(e,t){return t?t.aborted?Promise.reject(Ga()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Ga())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var Ja=Object.freeze({intervalMs:3e4,replyMs:3e4}),Ya=1e3,Xa=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;appliedFailure=void 0;appliedAuthFailure=void 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 s=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),c=(async()=>{await s;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 Yi(e,t,e=>{let t=Xi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=I(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([s,c]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(I(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 ba.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 qa(this.ready(),e),e?.aborted)throw Ga();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,Ka(t.port1))},s=()=>{this.pending.delete(n)&&(o(),r(Ga()))};e?.addEventListener(`abort`,s,{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(I(e))}try{if(await i,e?.aborted)throw o(),Ga();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,s)}}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(I(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(I(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(Ja.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+Ya){this.sendProbe();return}let e=new Ie(`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(Ja.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(I(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===`transport-state`){this.callbacks.onExplicitOfflineChange?.(t.explicitlyDisconnected);return}if(t.type===`link-fate`){this.applyLinkFate(t.fate);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===`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===`newer-build-waiting`){this.callbacks.onNewerBuild?.();return}if(t.type===`closed-for-newer-build`){this.fail(new Ie(`The shared worker closed this tab's connection for a newer build of the app`));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(P(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(P(t.error)):(this.inspectorAttachmentPhysicalDbName??=t.inspectorAttachmentPhysicalDbName??null,n.type===`init`&&(this.peerAuthority=t.peerAuthority,this.workerRealmId=t.workerRealmId),n.resolve({pendingUploads:t.pendingUploads})))};applyLinkFate(e){let t=e.failure&&JSON.stringify(e.failure);e.failure&&t!==this.appliedFailure?this.runtime.reportRemoteServerTransportError(P(e.failure.error),e.failure.retrying):!e.failure&&(this.appliedFailure||e.state===`connected`)&&this.runtime.clearRemoteServerTransportError(),this.appliedFailure=t,e.authFailure!==this.appliedAuthFailure&&(e.authFailure===null?this.callbacks.onAuthRestored():this.callbacks.onAuthFailure(e.authFailure),this.appliedAuthFailure=e.authFailure),this.callbacks.onRemoteLinkChange?.(e.state,e.link)}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()}}},Za=e=>`jazz:store-generation:${e}`;function Qa(e){try{globalThis.localStorage?.setItem(Za(e),crypto.randomUUID())}catch{}}function $a(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Za(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Za(e),r),r}catch{return null}}function eo(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Za(e))!==t}catch{return!0}}var to=class extends Error{name=`BrowserWorkerScriptLoadError`};async function no(e){let t=e.moduleUrl!==null&&Di(e.moduleUrl)!==void 0,n=e.workerUrl?await ro(e.workerUrl,e.fetch??globalThis.fetch):null;return new to(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?Gi: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 ro(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 io(e,t){if(oo(e))return new SharedWorker(Ci(e),{type:(ao(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-BTBxu5GV.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Wi);return r}function ao(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function oo(e){return ao(e)||Wr()!==null}function so(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),no({workerUrl:oo(t)?Ci(t):Di(Vr()),moduleUrl:Vr(),metro:Ki()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var co=1e4,lo=8,uo=8,fo=25,po=250,mo=5*6e4,ho=1e3,go=new Map;function _o(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function vo(e,t){return[`jazz-runtime`,t,ji(e)].join(`:`)}function yo(e,t){return`${e}\u0000${t}`}var bo=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=vo(t,e.dbName),r=yo(n,e.storageOwner);if(go.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=>io(t,e),a=Date.now()+co,o=Co(n),s=0,c=null;for(let l=0;l<lo;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,_o(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=wo(n,o);break}if(c=d.message,s+=1,s>=uo)throw Error(c);let f=Math.min(fo*2**(s-1),po,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(),co);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`),go.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&go.get(r)===p&&go.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(P(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?P(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=so(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(I(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(P(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}},xo=class{callbacks;worker=null;readyPromise;initialConfigurationAdmissionRejected=!1;heldByAnotherTab=!1;olderThanStore=!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=vo(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>io(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=I(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=Co(r);for(let s=0;s<lo;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=wo(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,s=!1,c=!1,l=Date.now(),u=l+mo,d=typeof document<`u`&&document.hidden,f,p=e=>{i||(i=!0,b(),this.cancelBootstrap===h&&(this.cancelBootstrap=null),r(e))},m=e=>{if(!i){s=!0,p(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{C(),o.close()}}},h=()=>m({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=h;let g=()=>{l=Date.now(),u=l+mo},_=()=>{let e=typeof document<`u`&&document.hidden;d&&!e&&g(),d=e},v=()=>g(),y=()=>{let e=Date.now();if((d||e-l>ho*2)&&g(),l=e,e>=u){m({connected:!1,error:new Ie(`Shared browser runtime did not finish initialization within five minutes`)});return}f=setTimeout(y,Math.min(ho,u-e))},b=()=>{clearTimeout(f),f=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,_),typeof window<`u`&&window.removeEventListener(`pageshow`,v)},x=n=>{if(s){if(n.data?.type===`runtime-ready`){if(c)return;c=!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;C(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){C(),o.close(),this.worker===a&&(this.worker=null);let e=P(n.data.error);this.olderThanStore=e.message===Xe,this.heldByAnotherTab=e.message===`this account's store is open under another sign-in in another tab`?`sign-in`:e.message===`this account's store is open with another build's schema in another tab`||this.olderThanStore?`build`:!1,this.initialConfigurationAdmissionRejected=e.message===`incompatible persistent browser configuration`||this.heldByAnotherTab!==!1,p({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;C(),this.cancelBootstrap===h&&(this.cancelBootstrap=null);let r=new Xa(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=>{Qa(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{Qa(this.dbName),this.callbacks.onStorageInvalidated?.()},onNewerBuild:this.callbacks.onNewerBuild},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>p({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),p({connected:!1,error:I(e)})})},S=()=>{C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:Error(`Shared browser runtime port message error`)})},C=()=>{b(),w(),o.removeEventListener(`message`,x),o.removeEventListener(`messageerror`,S)},w=so(a,t.runtimeSources,e=>{C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:e})});o.addEventListener(`message`,x),o.addEventListener(`messageerror`,S),typeof document<`u`&&document.addEventListener(`visibilitychange`,_),typeof window<`u`&&window.addEventListener(`pageshow`,v),f=setTimeout(y,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){C(),o.close(),this.worker===a&&(this.worker=null),p({connected:!1,error:I(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}waitsForAnotherTab(){return this.heldByAnotherTab}isOlderThanStore(){return this.olderThanStore}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=$a(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 eo(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(),Qa(this.dbName);try{return await this.connection?.deleteStorage()}finally{Qa(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await qa(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&&So(t,this.workerName,n),t}};function So(e,t,n){e.addEventListener(`message`,e=>{e.data?.type!==`result`||e.data.workerTerminated!==!0||wo(t,n)})}function Co(e){try{let t=Number.parseInt(localStorage.getItem(To(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function wo(e,t){try{let n=To(e);return Co(e)===t&&localStorage.setItem(n,String(t+1)),Co(e)}catch{return t+1}}function To(e){return`jazz:shared-worker-generation:${e}`}function Eo(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Do(e){return[...new Set([...Eo(e)].map(e=>e.namespace))].sort()}function Oo(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function ko(e,t){let n=[...Eo(e)],r=Do(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>").${Oo(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${Oo(r)}`);return a.db}var Ao=new Map;function jo(){let e=()=>[...Ao.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...Ao.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...Ao].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...Ao.keys()].map(t=>t.waitForSync(e)))}}}function Mo(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(Ao.set(e,t),Ro(n),()=>{Ao.delete(e)})}var No=Symbol.for(`jazz-tools.window-jazz`);function Po(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 Fo=new WeakSet;function Io(e){let t=e.__jazz;return t===void 0||Lo(t)?!1:(Fo.has(e)||(Fo.add(e),console.warn(Po(t))),!0)}function Lo(e){if(!e||typeof e!=`object`)return!1;if(No in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function Ro(e){let t=Io(e),n=(t?void 0:e.__jazz)??{};n[No]=!0;let r=Object.assign(n,jo(),{async clearStorage(t){await ko(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Do(e)},async shutdown(t){let n=[...Eo(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 zo=`history.`;function Bo(e){return Vo(e)!==void 0}function Vo(e){return e.startsWith(zo)?e.slice(8):void 0}var Ho=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Uo=new WeakMap;function K(e,t){let n=Vo(t);if(n===void 0)return e[t];if(Bo(n)||!Object.hasOwn(e,n))return;let r=Uo.get(e);r||Uo.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Ho],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Wo=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Go=class extends Error{phase;constructor(e){super(e===`draining`?`Cannot operate on a Db that is shutting down or closed: it is shutting down, waiting for its pending writes to sync.`:`Cannot operate on a Db that is shutting down or closed: it is ${e}.`),this.phase=e,this.name=`DbClosedError`}},Ko=class extends Error{code;status;constructor(e,t,n=e){super(n),this.code=e,this.status=t,this.name=`AccountAuthError`}},qo=new WeakMap;function Jo(e){let t=xe(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!ze(t.iss)||!ze(t.sub))throw new Ko(`invalid_identity_token`);return{issuer:t.iss,subject:t.sub}}function Yo(e,t){return e.issuer===t.issuer&&e.subject===t.subject}async function Xo(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 Ko(`credential_refresh_timeout`)),3e4)})])}finally{n&&clearTimeout(n)}}async function Zo(e,t,n){let r=qo.get(e);if(!r||r.registry!==t)throw new Ko(`invalid_account_handle`);if(r.delegated)throw new Ko(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new Ko(`backend_account_requires_backend_host`);let i=await Xo(r.auth,n);if(qo.get(e)!==r)throw new Ko(`account_logged_out`);if(!Yo(Jo(i),e.identity))throw new Ko(`credential_identity_changed`);return i}function Qo(e){let t=qo.get(e);if(!t)throw new Ko(`invalid_account_handle`);return t.registry}var $o=new WeakMap;function es(e){return ts(e),$o.get(e)?.bearer}function ts(e){let t=$o.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 Ko(`account_handle_required`)}function ns(e,t){if(ts(e),e.accountId!==void 0){if(t.accountId!==e.accountId||t.accountRegistryAuthority!==e.accountRegistryAuthority||$o.get(e)?.inspectorPort!==void 0&&t.runtimeSources?.browserWorkerPort!==$o.get(e)?.inspectorPort)throw new Ko(`account_application_mismatch`);$o.set(t,$o.get(e))}}function rs(e){let t=e.runtimeSources?.browserWorkerPort;if(!e.accountId||!e.accountRegistryAuthority||!t)throw new Ko(`account_handle_required`);$o.set(e,{id:e.accountId,registry:e.accountRegistryAuthority,inspectorPort:t})}function is(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a whole number of rows, at least 1: a subscription's backlog cannot be unbounded.`)}var as=Object.freeze({pending:0,oldestPendingAt:null,rejected:0,lastRejection:null});function os(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function ss(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 or with another build of the app.`}[e.reason];return{kind:e.reason,message:t||n,at:Date.now()}}function cs(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 ls=Object.freeze({state:`local-only`}),us=Object.freeze({state:`connecting`}),ds=Object.freeze({state:`connected`});function q(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function fs(e){switch(e?.phase??`noServer`){case`noServer`:return ls;case`offline`:return q(`disconnected`);case`live`:return ds;case`connecting`:case`backoff`:return e.outagePublished?q(`network`):us;case`awaitingCredential`:return q(`auth`);case`stopped`:return q(`stopped`)}}function ps(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`?!0:e.reason===t.reason&&e.retrying===t.retrying&&e.authReason===t.authReason:!1}function ms(e,t=as,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:os(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function hs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&cs(e.lastError,t.lastError)&&ps(e.link,t.link)}function gs(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 _s=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 vs(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function ys(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 bs(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 xs=class extends Error{},Ss=class extends Error{};function Cs(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 Ss(`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 xs(`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(bs(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 ws(){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 Ts=[`$canRead`],Es=[`$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 Ds(e){return Ts.includes(e)}function Os(e){return Es.includes(e)}function ks(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return ws();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=ws();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 As=`__jazz_requireIncludes`;function js(e){return Array.isArray(e)?e.filter(e=>A(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function Ms(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 Ns(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Ps(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Fs(e){if(!A(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!A(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(Ps(r.from)&&Ps(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(Ps(r.fromUtf8)&&Ps(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 Is(e){let t=A(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!A(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...A(e)&&e.seed?{seed:Ls(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:js(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Ls(e){if(!A(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:js(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Is(e.gather),...Array.isArray(e.orderBy)?{orderBy:Ms(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return A(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!A(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ls(e.input)}])}),t}function Rs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function zs(e){let t={...e};return delete t[As],Us(t)}function Bs(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Vs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function Hs(e){if(e===!0)return Rs();if(!A(e))return null;if(Bs(e)){let t=Ws(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(Vs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:js(e.conditions),includes:Us(e.includes),requireIncludes:e[As]===!0,select:Ns(e.select),partialSelect:Fs(e.partialSelect??e.select),orderBy:Ms(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:Is(e.gather)};let t=Rs();return t.requireIncludes=e[As]===!0,t.includes=zs(e),t}function Us(e){if(!A(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=Hs(r);e&&(t[n]=e)}return t}function Ws(e){let t=A(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Fs(t.partialSelect??t.select);return{table:t.table,conditions:js(t.conditions),includes:Us(t.includes),requireIncludes:t[As]===!0,select:Array.isArray(t.select)?Ns(t.select):Object.keys(n),partialSelect:n,orderBy:Ms(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:Is(t.gather),...A(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!A(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Ls(e.input)}])}}:{}}}var Gs=`__jazz_include_`;function Ks(e){return`${Gs}${e}`}function qs(e,t,n){let r=K(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 Js(e,t){return t?{scope:t,column:e}:{column:e}}function Ys(e,t,n){let r=K(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:Js(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:Js(e.name,t)}}))]}function Xs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=ks(n);if(r)return r;let i=K(e,t);if(i)return i.columns.find(e=>e.name===n)?.column_type}function Zs(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 Qs(e){return Zs(e)}function $s(e,t){if(e==null)return{type:`Null`};if(t.type===`Json`)return{type:`Text`,value:ys(e)};if(t.type===`Timestamp`&&e instanceof Date)return{type:`Timestamp`,value:Qs(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=>$s(e,t.element))}}if(typeof e==`boolean`)return{type:`Boolean`,value:e};if(typeof e==`number`){if(t?.type===`Timestamp`)return{type:`Timestamp`,value:Qs(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:Qs(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 ec(e,t){if(!(!t||e.type!==`forward`||e.nullable))return e.isArray?`MatchCorrelationCardinality`:`AtLeastOne`}function tc(e,t,n,r){let i=Xs(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 nc(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])=>tc(e,t,n,r)):[];return i.length+a.length>0?[...i,...a]:null}function rc(e){return e.length>0?[...e]:null}function ic(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 ac(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}"`);ic(e,c,i);let l=c.select.length>0?qs(e.toTable,r,c.select):[],u=c.conditions.map(t=>oc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[vs(e),t===`desc`?`Descending`:`Ascending`]),f=ac(c.includes,e.toTable,n,r,{requireIncludes:c.requireIncludes}),p=rc(l),m=r[t]?.columns.some(e=>e.name===i)?Ks(i):i;if(e.type===`forward`){let n=ec(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 oc(e,t,n,i){let a=Js(vs(e.column),i),o=vs(e.column),s=Xs(t,n,o);if(!s)throw Error(`Unknown column "${o}" in table "${n}"`);let c=e.value===void 0?!0:e.value;if(e.op===`isNull`){if(typeof c!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return c?{IsNull:{column:a}}:{IsNotNull:{column:a}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:a}};if(e.op===`ne`)return{IsNotNull:{column:a}}}if(s.type===`Row`&&ks(o)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${o}" only supports eq/ne operators.`);let a=(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 "${o}".`);return e},s=o===`$createdBy`||o===`$updatedBy`||o===`$deletedBy`,c=s?a(e.value,[`account`,`identity`]):void 0,l=a(c?c.identity:e.value,[`issuer`,`subject`]);if(typeof l.issuer!=`string`||typeof l.subject!=`string`||c&&typeof c.account!=`string`)throw Error(`Invalid structured author condition for "${o}".`);r(l.issuer,l.subject,c?.account);let u={And:[...c?[{column:`${o}.account`,op:`eq`,value:c.account}]:[],{column:`${o}${s?`.identity`:``}.issuer`,op:`eq`,value:l.issuer},{column:`${o}${s?`.identity`:``}.subject`,op:`eq`,value:l.subject}].map(e=>oc(e,t,n,i))};return e.op===`eq`?u:{Not:u}}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:a,values:e.value.map(e=>({Literal:$s(e,s)}))}};return e.op===`notIn`?{Not:t}:t}let l=e.op===`contains`&&s.type===`Array`?s.element:s,u=sc(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:$s(e.value,l)};switch(e.op){case`eq`:return{Cmp:{left:a,op:`Eq`,right:u}};case`ne`:return{Cmp:{left:a,op:`Ne`,right:u}};case`gt`:return{Cmp:{left:a,op:`Gt`,right:u}};case`gte`:return{Cmp:{left:a,op:`Ge`,right:u}};case`lt`:return{Cmp:{left:a,op:`Lt`,right:u}};case`lte`:return{Cmp:{left:a,op:`Le`,right:u}};case`contains`:return{Contains:{left:a,right:u}};default:throw Error(`Unknown operator: ${e.op}`)}}function sc(e){return typeof e!=`object`||!e?!1:e.__jazz_ir_frontier_row_id===!0}function cc(e,t,n,r){return e.length===0?`True`:e.length===1?oc(e[0],t,n,r):{And:e.map(e=>oc(e,t,n,r))}}function lc(e,t){return t===`True`?e:{Filter:{input:e,predicate:t}}}function uc(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:Js(i.fromColumn,s),right:Js(`id`,c)}:{left:Js(`id`,s),right:Js(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:Ys(o,s,i)}}}function dc(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=lc(l,cc([...u,{column:vs(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:Js(c.fromColumn,e.step_table),right:Js(`id`,p)}],join_kind:`Inner`}},columns:Ys(t,p,i)}},frontier_key:{RowId:`Current`},bound:{MaxDepth:e.max_depth},dedupe_key:[{RowId:`Current`}]}}}function fc(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 pc(e,t,n,r=!1){if(e.union){let r=e.union.inputs.map(e=>pc(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:mc({Union:{inputs:e.union.inputs.map((e,t)=>({label:e.label,input:r[t].expr}))}},e,i.outputTable),outputTable:i.outputTable}}if(!e.table)throw Error(`gather(...) seed relation is missing table metadata.`);let i={TableScan:{table:e.table}};i=lc(i,cc(e.conditions??[],n,e.table,e.table));let a=e.table;if(e.gather){let r=e.gather.seed?pc(e.gather.seed,t,n):{expr:i,outputTable:a};i=dc(e.gather,r.outputTable,r.expr,t,n),a=r.outputTable}let o=e.hops??[];i=uc(i,a,o,t,n),a=fc(a,o,t);let s=o.length?`__hop_${o.length-1}`:a;return r&&o.length===0&&!e.gather&&(i={Project:{input:i,columns:Ys(a,s,n)}}),i=mc(i,e,s),{expr:i,outputTable:a}}function mc(e,t,n){let r=e;return t.orderBy?.length&&(r={OrderBy:{input:r,terms:_c(t.orderBy).map(({column:e,direction:t})=>({column:Js(e,n),direction:t}))}}),t.offset!==void 0&&t.offset>0&&(r={Offset:{input:r,offset:t.offset}}),t.limit!==void 0&&(r={Limit:{input:r,limit:t.limit}}),r}function hc(e,t){let n=Ws(JSON.parse(e)),r=Cs(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=pc(n.gather.seed,r,t);a=dc(n.gather,e.outputTable,e.expr,r,t),o=e.outputTable,a=lc(a,cc(n.conditions,t,o,o)),a=uc(a,o,i,r,t),o=fc(o,i,r)}else{let e=pc({table:n.table,conditions:n.conditions,hops:n.hops,gather:n.gather,union:n.union},r,t);a=e.expr,o=e.outputTable}return Array.isArray(n.orderBy)&&n.orderBy.length>0&&(a={OrderBy:{input:a,terms:n.orderBy.map(([e,t])=>({column:Js(vs(e),i.length>0?`__hop_${i.length-1}`:o),direction:t===`desc`?`Desc`:`Asc`}))}}),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 gc(e){return e.union!==void 0||e.hops.length>0||e.gather!==void 0}function _c(e){return e.map(([e,t])=>({column:vs(e),direction:t===`desc`?`Desc`:`Asc`}))}function vc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}function yc(e,t,n){return e.map(e=>oc(e,t,n))}function bc(e,t,n){let r=n??Ws(JSON.parse(e)),i=Cs(t),a=gc(r)?hc(e,t):void 0,o=a?.outputTable??r.table,s=nc(r.select.length>0?qs(o,t,r.select):[],r.partialSelect,t,o),c=ac(r.includes,r.table,i,t,{requireIncludes:r.requireIncludes});if(a)return vc({table:o,array_subqueries:c,relation_ir:a.relation,...r.includeDeleted?{include_deleted:!0}:{},...s?{select_columns:s}:{}});let l=_c(r.orderBy),u=typeof r.limit==`number`?r.limit:void 0,d=typeof r.offset==`number`?r.offset:void 0;return vc({table:r.table,conditions:yc(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 xc(e,t){if(t.union){let n=t.union.inputs[0];if(!n)throw Error(`union(...) requires at least one relation.`);let r=xc(e,n.input);for(let n of t.union.inputs.slice(1))if(xc(e,n.input)!==r)throw Error(`union(...) requires all relations to output the same table.`);return r}let n=t.gather?.seed?xc(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 Sc(e,t){if(e)return e instanceof Map?e.get(t)??e.get(`user_${t}`):e[t]??e[`user_${t}`]}function Cc(e,t){return e?e instanceof Map?e.has(t)||e.has(`user_${t}`):t in e||`user_${t}`in e:!1}function wc(e,t,n){let r=K(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return qs(e,t,n).map(e=>{let t=ks(e);if(t)return{name:e,columnType:t};if(Ds(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 Tc(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 Ec(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=Ec(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 Dc(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 Oc(e,t,n,r){if(e.type!==`Array`)return jc(e);let i=e.value.map(e=>{if(e.type!==`Row`)return jc(e);let i=e.value.id,a=e.value.values,o=e.value.valuesByColumn;return t.baseColumns??=wc(t.relation.toTable,n,t.projection),kc(a,n,t.relation.toTable,t.nested,t.baseColumns,i,o,r,t.nestedRelationNames)});return t.relation.isArray?i:i[0]??null}function kc(e,t,n,r,i,a,o,s,c=[],l=!0){if(!K(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=Cc(o,n.name)?Sc(o,n.name):o?void 0:e[t];r!==void 0&&(u[n.name]=jc(r,n.columnType,n.name))}for(let n=0;n<r.length;n++){let a=r[n];if(!a)continue;let c=Ks(a.relation.name),l=Cc(o,c)?Sc(o,c):Cc(o,a.relation.name)?Sc(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]=Oc(l,a,t,s)}let d=l?s?.[n]:void 0;return d?Dc(u,d,c):u}function Ac(e,t){return new Date(e)}function jc(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 Ac(e.value,n);case`Bytea`:return Tc(e.value);case`Null`:return null;case`Array`:return t?.type===`Array`?e.value.map(e=>jc(e,t.element)):e.value.map(e=>jc(e));case`Row`:return t?.type===`Row`&&n&&(Os(n)||n===`$deletedBy`||n.startsWith(`$deletedBy.`))?Object.fromEntries(t.columns.map((t,r)=>[t.name,jc(e.value.values[r],t.column_type,`${n}.${t.name}`)])):t?.type===`Row`?e.value.values.map((e,n)=>jc(e,t.columns[n]?.column_type)):e.value.values.map(e=>jc(e))}}function Mc(e,t,n,r){if(!K(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Ec(t,Us(n),r??Cs(e));return{includePlans:i,includedRelationNames:i.map(e=>e.relation.name)}}function Nc(e,t,n,r,i,a,o){return e.baseColumns??=wc(r,n,i),kc(t.values,n,r,e.includePlans,e.baseColumns,t.id,t.valuesByColumn,a,e.includedRelationNames,o)}function Pc(e,t,n,r={},i,a,o=!0){let s=Mc(t,n,r);return e.map(e=>Nc(s,e,t,n,i,a,o))}function Fc(e,t,n={},r,i,a=!0,o){let s;return c=>(s??=Mc(e,t,n,o),Nc(s,c,e,t,r,i,a))}function Ic(e,t,n,r={},i,a,o=!0){let s=Pc([e],t,n,r,i,a,o)[0];if(s===void 0)throw Error(`Failed to transform row for table "${n}"`);return s}var Lc=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}},Rc=new WeakMap;function zc(e){return Rc.get(e.preparationOwner?.()??e)}function Bc(e){let t=e.preparationOwner?.()??e,n=Rc.get(t);return n||Rc.set(t,n=new Lc),n}function J(e,t){let n=zc(e);if(n?.pending)return n.run(t);let r=t();return r instanceof Promise?Bc(e).run(()=>r):r}function Vc(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`?t:void 0}var Hc=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 Uc(e){let t=Vc(e);return t!==void 0&&Hc.has(t)?t:void 0}var Wc=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`,`schema_version_unsupported`]);function Gc(e){if(!e||typeof e!=`object`)return;let t=e.reason;return typeof t==`string`&&Wc.has(t)?t:void 0}function Kc(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 qc(e,t,n,r){let i=n.filter(e=>!e.name.startsWith(Gs)),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=>!Os(e.name)).map(e=>a.get(e.name))},`valuesByColumn`,{value:a,configurable:!0})}var Jc=new WeakMap;function Yc(e){let t=Jc.get(e);return t||(t=Object.keys(e).filter(t=>e[t].computed),Jc.set(e,t)),t}var Xc=class extends Error{constructor(e){super(`Computed dependency "${e}" is unavailable.`)}},Zc=new WeakMap,Qc=class{dependencies=new Map;version=0;observedColumns(e){let t=this.dependencies.get(e);return t||(t=new Set(Zc.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=Zc.get(e);r||Zc.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 $c(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($c(r,t,n)||$c(i,t,n))return!0}else if(e instanceof Set){for(let r of e)if($c(r,t,n))return!0}for(let r of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,r);if(i&&`value`in i&&$c(i.value,t,n))return!0}return!1}function el(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 Xc(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;$c(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 tl=-(1n<<63n),nl=(1n<<63n)-1n,rl=-2147483648,il=2147483647;function al(e){let t=Number(e);if(!Number.isInteger(t)||t<rl||t>il)throw Error(`Integer values must be signed 32-bit integers between ${rl} and ${il}; received ${String(e)}`);return t}function ol(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<tl||t>nl)throw Error(`Invalid BigInt value. Expected signed 64-bit integer range.`);return t}function sl(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 cl(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 ll(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:al(e)};case`BigInt`:return{type:`BigInt`,value:ol(e)};case`Double`:return{type:`Double`,value:Number(e)};case`Timestamp`:return{type:`Timestamp`,value:sl(e)};case`Uuid`:return{type:`Uuid`,value:String(e)};case`Bytea`:return{type:`Bytea`,value:cl(e)};case`Json`:return{type:`Text`,value:ys(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=>ll(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=>ll(n[e.name],e.column_type))}}}default:throw Error(`Unsupported column type: ${t.type}`)}}function ul(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`&&dl(t,a,e.column_type.schema),i[t]=ll(a,e.column_type)}return i}function dl(e,t,n){if(!n)return;let r=fl(t,n);if(r)throw Error(`encoding error: JSON schema validation failed for column \`${e}\`: ${r}`)}function fl(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=pl(t),i=new Set(ml(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=fl(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=hl(t.minLength);if(n!=null&&e.length<n)return`${JSON.stringify(e)} is shorter than ${n} character${n===1?``:`s`}`;let r=hl(t.maxLength);if(r!=null&&e.length>r)return`${JSON.stringify(e)} is longer than ${r} characters`;let i=gl(t.pattern);return i&&!new RegExp(i).test(e)?`${JSON.stringify(e)} does not match ${JSON.stringify(_l(i))}`:null}if(n===`integer`){if(typeof e!=`number`||!Number.isInteger(e))return`${JSON.stringify(e)} is not an integer`;let n=hl(t.minimum);if(n!=null&&e<n)return`${e} is less than the minimum of ${n}`;let r=hl(t.maximum);return r!=null&&e>r?`${e} is greater than the maximum of ${r}`:null}return null}function pl(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 ml(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function hl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function gl(e){return typeof e==`string`?e:null}function _l(e){return e.replaceAll(`\\d`,`[0-9]`)}var vl=1e3,yl=5*6e4;function bl(e){return Math.min(yl,vl*2**Math.min(e,20))}var xl=class{streak=0;next(){let e=this.streak++;return e===0?0:bl(e-1)}reset(){this.streak=0}},Sl=new WeakMap;function Cl(e){let t=Sl.get(e);if(t?.size)for(let e of[...t])try{e()}catch(e){console.error(`Jazz local write observer failed`,e)}}var wl=Symbol.for(`jazz-tools.shippedMigrations`);function Tl(e){return e[wl]}function El(e){return!!e.adminSecret}function Dl(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,policies:void 0}]))}var Ol=new WeakMap;function kl(e){let t=Ol.get(e);if(t)return t;let n=Dl(e);return Ol.set(e,n),n}var Al=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&&El(t)?kl(e):e,i=Ye(r);if(this.client){if(!this.clientSchema||Ye(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};ns(t,a),O(a,d(t));let o=n.createClient({config:a,schema:r,migrations:Tl(e),onAuthFailure:e=>this.host.markUnauthenticated(e),onAuthRestored:()=>this.host.clearAuthError(),foregroundNodeLease:this.foregroundNodeLease});o.onMutationError(e=>this.host.onMutationError(e)),fe(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:Ye(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 ms(e);let t=this.client?.getRuntime();return ms(e,t?.uploadStatus?.()??as,t?.lastLinkFailure?.()??null)}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?ls:this.isExplicitlyOffline()?q(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??us;return e.state===`local-only`?us: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()}},jl=class extends Al{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()}}},Ml=`jazz:indexeddb-invalidation-reload`,Nl=1e4;function Pl(e={}){let t=(e.now??Date.now)();try{let n=e.storage??globalThis.sessionStorage,r=Number(n.getItem(Ml)??0);if(Number.isFinite(r)&&t-r<Nl)return!1;n.setItem(Ml,String(t))}catch{}return(e.reload??(()=>globalThis.location.reload()))(),!0}async function Fl(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 Il=`store_held_by_another_tab`,Ll=class extends Error{name=`StoreHeldByAnotherTabError`;code=Il;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)}},Rl=Symbol.for(`jazz.browser-inspector-control-registry`);function zl(){let e=globalThis;return e[Rl]??={factories:new Map,nextFactoryId:1}}function Bl(e,t){e.getConfig=t;let n=zl(),r=n.nextFactoryId++;return n.factories.set(r,e),()=>n.factories.delete(r)}var Vl=[],Hl=!1,Ul=Promise.resolve(),Wl=!1;function Gl(e){return typeof window>`u`||typeof window.addEventListener!=`function`?()=>{}:(Kl(),Vl.push(e),()=>{let t=Vl.indexOf(e);t!==-1&&Vl.splice(t,1)})}function Kl(){Wl||(Wl=!0,window.addEventListener(`pagehide`,e=>{e.persisted&&ql()}),window.addEventListener(`pageshow`,e=>{e.persisted&&Jl()}))}function ql(){if(!Hl){Hl=!0;for(let e of[...Vl])try{e.leave()}catch(e){console.warn(`Jazz could not let go of a page lock for the back/forward cache.`,e)}}}function Jl(){if(!Hl)return;Hl=!1;let e=[...Vl];Ul=Ul.then(async()=>{for(let t of e){if(Hl)return;if(Vl.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 Yl=`jazz:newer-build-reloaded-from`,Xl;function Zl(e){let t=2166136261;for(let n of Ye(e))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(16)}function Ql(e,t={}){try{return(t.storage??globalThis.sessionStorage).getItem(Yl)!==e}catch{return!0}}function $l(e,t={}){let n=()=>{try{(t.storage??globalThis.sessionStorage).setItem(Yl,e)}catch{}(t.reload??(()=>globalThis.location.reload()))()};if(!Xl)return n();try{Xl(n)}catch(e){console.warn(`Jazz: onNewerBuild threw; reloading for the newer build.`,e),n()}}var eu=class e extends Al{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;olderBuildError=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))}get dbStopping(){return this.host.phase!==`open`||this.host.draining}get dbClosing(){return this.host.phase!==`open`}getClient(e){if(this.olderBuildError)throw this.olderBuildError;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??=Gl({leave:()=>this.leaveForPageCache(),return:()=>this.returnFromPageCache()})}leaveForPageCache(){let e=this.connection;if(!e||this.pageAway||this.shutdownStarted||this.dbStopping||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.dbClosing||!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`),Pl(),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};ns(this.host.config,t),O(t,d(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,I(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r),onNewerBuild:()=>this.yieldToNewerBuild(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=Bl(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,I(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 Ie&&this.shutdownFailure.abandon(t);return}if(this.connection!==e)return;this.connectionError=t,this.recoverableConnectionFailure=!0,this.rejectReconnectWaiters(t),this.notifyWorkerRemoteLink(),e.isOlderThanStore?.()&&this.yieldToNewerBuild(e);let n=this.admissionRefused(e);n?this.startHeldPatience():t instanceof Ie||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof Ie||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.dbClosing)&&(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?.waitsForAnotherTab?.()}yieldToNewerBuild(e){if(this.olderBuildError||this.shutdownStarted||this.dbStopping)return;let t=this.browserConnectionInput;if(this.connection!==e||!t)return;let n=Zl(t.schema);Ql(n)&&(this.olderBuildError=Error(`This tab runs an older build of this app than another tab, which has its local store now: reload this tab`),this.getCurrentClient()?.refuseWrites?.(this.olderBuildError),this.wakeReplacementWaiters(),(async()=>{await e.flushLocal().catch(()=>void 0),await e.shutdown().catch(()=>void 0)})().then(()=>$l(n)))}heldByAnotherTabError(e,t){return e.waitsForAnotherTab?.()===`build`?new Ll(`Another tab runs another build of this app (another schema) and holds this account's local store: reload the tab that runs the older build, which may be this one (reloading picks up the newest build), or close it. This tab joins once the other lets go; reloading this tab loses its unsynced writes`,{cause:t}):new Ll(void 0,{cause:t})}replacementOf(e,t){return new Promise(n=>{let r=()=>{this.connection===e&&!this.olderBuildError&&!this.heldTooLong&&!this.shutdownStarted&&!this.dbStopping&&!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.dbClosing||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.dbClosing||this.storageReset)){if(this.admissionRefused(e)){await this.retryConfigurationAdmission(e),await this.connectionReady;return}this.connectionError instanceof Ie&&(this.reopenFailedFollower(),await this.connectionReady)}}).catch(e=>{this.connectionError??=I(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.olderBuildError)throw this.olderBuildError;if(this.dbStopping||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.dbStopping||t?.aborted)&&(r??=this.connection??await this.pageAway?.reopened??await this.configurationAdmissionRetry,i&&r&&(r=await this.retryConfigurationAdmission(r)),!(this.dbStopping||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 this.heldByAnotherTabError(r,e);if(await this.replacementOf(r,t),this.olderBuildError)throw this.olderBuildError;if(this.dbStopping||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.dbStopping){if(this.connectionError)throw this.connectionError;if(e!==`runtime`)for(;;){for(;this.disconnected;)if(await this.waitForReconnect(t),this.dbStopping||t?.aborted)return;if(await this.transportTransition,!this.disconnected||this.dbStopping||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.dbClosing||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(tu(this.host.config)),nu(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}};O(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Vi(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(tu(t)),nu(t)).catch(e=>{this.observeConnectionFailure(n,I(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 qa(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=Fl([()=>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??=I(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`),Pl())}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 Ie&&u(n);try{await Fl([()=>{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 Ie&&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 q(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return us;if(this.connectionError)return q(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?us:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return ds;case`unavailable`:return q(`network`);default:return us}}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 tu(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function nu(e){return ct({...e,trustedReservedSession:d(e)})?.claims??{}}var ru=new WeakMap,iu=new WeakSet;function au(e){return iu.has(typeof e?.current==`function`?e.current():e)}async function ou(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=ru.get(e);if(n)return await n(t);if(au(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 su=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}},cu=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}},lu=30;function uu(e){return e??{type:`persistent`}}function du(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function fu(e){let t=uu(e.driver);return du((t.type===`persistent`?t.dbName:void 0)??e.dbName)??U(e)}function pu(e){return Hi(e,fu(e))}function mu(e){if(!e)return;let t=e;se(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])}let a=t.backlogRows;return a!==void 0&&(is(a,`backlogRows`),n.backlogRows=a),it(e)&&(n.tier=`local-only`),n}var hu=new WeakMap,gu=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getDeviceAccountProof.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 _u(e){let t=hu.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function vu(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 yu(e,t,n,r){let i=K(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,ll(s[t],vu(e,t).column_type)]))}}function bu(e,t,n,r){let i=yu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:yu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:yu(e,t,r,`schema`)}}}function xu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:yu(e,t,r,`table`)}}function Su(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:bu(e,t,r,i)}}function Cu(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 wu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function Tu(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 Eu(e){return{...e,branches:[...e.branches]}}function Du(e,t){if(K(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function Ou(e,t,n){return Su(e,t,n)??{}}function ku(e,t,n,r){let i=K(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 Au(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 Y(e){if(Bo(e._table))throw Error(`History table "${e._table}" is read-only`)}function ju(e,t,n){return Mu(e,ed(t,n),t._schema,t._table)}function Mu(e,t,n,r){try{return ul(t,n,r)}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`${e} failed: WriteError("${Gu(n)}")`)}}function Nu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Pu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Fu(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 Iu(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Lu(e,t,n){let r=zu(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 Ru(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function zu(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}=Bu(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 Bu(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(!Nu(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=Pu(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=Fu(n.fromUtf8,`fromUtf8`,t),i=Fu(n.toUtf8,`toUtf8`,t);Iu(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Fu(n.from,`from`,t),r=Fu(n.to,`to`,t);Iu(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Fu(n.from,`from`,t),r=Fu(n.to,`to`,t);Iu(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=Pu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Fu(r?n.atUtf8:n.at,`at`,t),o=Fu(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=Pu(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 Vu(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 Hu(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 Uu(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=Hu(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 Wu(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]=Uu(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 k({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(!Vu(t,a)||!Vu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Gu(e){return e.replaceAll(`"`,`\\"`)}function Ku(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function qu(e,t,n,r){let i=Ku(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=Fc(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?Cs(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 Qc,(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?el(u,g,{...e},r,f):void 0,n=S?Wu(e,x):e;if(m&&Dc(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=Fc(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 Ju(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 Xc))throw e;s=e}if(!s)return o;if(!r.computedState||r.computedState.version===r.version)throw s;r=qu(e,t,n,r.computedState),i=await a(r.physical)}}var Yu=new WeakMap;function Xu(e,t){let n=Yu.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Zu(e,t){return Qu(e,t)}function Qu(e,t){if(!e._columnTransforms||typeof t!=`object`||!t)return t;let n=t,r=Yc(e._columnTransforms),i=r.length?el(e._columnTransforms,r,n):void 0;Dc(n,e._columnTransforms,[],i);for(let e of r)n[e]=i.get(e);return n}function $u(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 ed(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 td=1e4;function nd(e,t,n,r,i){let a=JSON.stringify({table:t._table,conditions:[{column:`id`,op:`eq`,value:n}],limit:1}),o=e.queryInternal(bc(a,t._schema),i?{tier:`remote`,branch:i}:{tier:`remote`},r),s,c=new Promise(e=>{s=setTimeout(()=>e([]),td)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function rd(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function id(e,t,n){return Zu(e,Ic(qc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function ad(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)&&od(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 od(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function sd(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(od(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 cd(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 ld(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function ud(e,t,n){let r;try{r=t(cd(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 ld(e,a,s,i())}var dd=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(Yu.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 Xu(this,e)}bindOwnerClient(e){let{writeSession:t,attribution:n}=this.context??{},r=new Lc(!0),i=zc(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};Yu.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 Be(i,t):new Re(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){Y(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}=ad(t,r);$u(t,p);let m=async()=>{let r=Mu(o,ed(t,p),t._schema,t._table),u=e===`insert`?sd(t,p):void 0,m=e===`insert`?xu(t._schema,t._table,{...i,...n?{id:n}:{},...u?{branch:u}:{}}):Su(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,r,d,f,s,m,c,l,n)};return Promise.resolve(u.run(()=>J(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){Y(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||zc(r)?.pending)&&(c=rd());let d,f=()=>{d=r.insertInternal(e._table,l,xu(e._schema,e._table,c?{...n,id:c}:n),a,o,i)};s.cancelled?f():s.run(()=>J(r,()=>{s.cancelled||f()}));try{return u??(d?Zu(e,Ic(d,e._schema,e._table)):id(e,c,l))}catch(e){throw s.failure=e,e}}restore(e,t,n,r){Y(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,xu(e._schema,e._table,r),c,l,s)};return u.cancelled?d():u.run(()=>J(o,()=>{u.cancelled||d()})),a}prepareCreation(e,t,n,r){let i;try{i=e._columnTransforms?ed(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=Mu(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:id(e,n,a)}}catch(e){throw this.requireBinding(r).preparation.failure=e,e}}upsert(e,t,n,r){Y(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,Su(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){Y(e),this.bindTable(e);let{replacements:i,descriptors:a}=Lu(e,n,r);r=Ru(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=Su(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($u(e,t),(a.pending||zc(i)?.pending)&&(t={...t}),a.cancelled){r({});return}a.run(()=>J(i,()=>{if(a.cancelled)return;let i;try{i=ed(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(Mu(n,i,e._schema,e._table))}))}delete(e,t,n){Y(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`delete`),c=Su(e._schema,e._table,n),l=()=>{r.deleteInternal(e._table,t,c?.updatedAt,a,o,i,c?.branch)};s.cancelled?l():s.run(()=>J(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=Ws(JSON.parse(a)),s=Du(e._schema,o.table),c=xc(s,o),l=qu(e,o,c),u=Su(e._schema,o.table,mu(t))??{},d=await i.queryInternal(bc(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?Ju(e,o,c,l,d,e=>i.queryInternal(bc(a,s,e),{...u,openTransactionId:r},this.context?.readSession)):d.map(l.transform)}async one(e,t){return(await this.all(Cu(e),t))[0]??null}},fd=class e{config;runtimeSource;authStateStore;connection;_localFirstSecret=null;localFirstRefreshOwned=!1;localFirstRenewals=new xl;localFirstRefreshTimer=null;phase=`open`;gracefulDrain=null;teardown=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){ts(e),this.config=e,this.runtimeSource=t;let r={...e,trustedReservedSession:d(e)};l(this,ct(r)),this.authStateStore=me(r,n),this.connection=new jl(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=Mo(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}hu.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,mu(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,mu(n))})}dbForConnection(){let e=this;return{get config(){return e.config},get runtimeSource(){return e.runtimeSource},get phase(){return e.phase},get draining(){return e.gracefulDrain!==null},markUnauthenticated:e=>this.markUnauthenticated(e),renewsCredential:e=>(Td.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`),mu(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.stopping))try{let e=3600,t=this.mintLocalFirstToken(this._localFirstSecret,U(this.config),e),n=Je(xe(t)??{},`device-account`);if(!n)throw Error(`Minted device account token is missing its reserved session identity`);this.applyAuthUpdate(t,n),this.scheduleLocalFirstRefresh(e)}catch(e){console.error(`Failed to refresh device account 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){l(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=d(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};O(n,t);let r=ct(n);this.config.jwtToken=e,this.config.cookieSession=void 0,O(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=d(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=ct({...this.config,jwtToken:void 0,cookieSession:t});return this.config.jwtToken=void 0,this.config.cookieSession=t,O(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 eu(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 Cl(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){ts(this.config);let t=j(this);if(e.id!==this.config.accountId||Qo(e)!==this.config.accountRegistryAuthority||e.identity.issuer!==t?.issuer||e.identity.subject!==t?.user_id)throw Error(`Account context mismatch`);try{let t=await Zo(e,Qo(e),{fresh:!0});if(this.shutdownAbort.signal.aborted)throw Error(`Account context closed`);let n=e.identity.issuer===`urn:jazz:local-first`?Je(xe(t)??{},`device-account`):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()}getDeviceAccountProof(e){if(!this._localFirstSecret){let t=this.config.jwtToken,n=t?xe(t):null;return!t||n?.iss!==`urn:jazz:local-first`||typeof n.exp!=`number`||n.exp<=Date.now()/1e3+lu||e?.audience!==void 0&&n.aud!==Le(e.audience)?null:t}let t=e?.ttlSeconds??60,n=e?.audience??U(this.config);return this.mintLocalFirstToken(this._localFirstSecret,n,t)}getLocalFirstIdentityProof(e){return this.getDeviceAccountProof(e)}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=Dd(this.connection.syncStatus(),this.authStateStore.getState().error);return this.syncStatusSnapshot&&hs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||hs(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(),i=()=>{let t=this.getSyncStatus();t!==r&&(r=t,e(t))};this.connection.onSyncStatusChange(i,t.signal);let a=this.authStateStore.onChange(i);return t.signal.addEventListener(`abort`,a,{once:!0}),n}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;ue(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 ee(`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.stopping)throw Error(`Cannot disconnect a Db that is shutting down.`);this.offlineRequested=!0,await this.connection.disconnect()}async reconnect(){if(this.phase!==`open`)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})=>Eu(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){Y(e);let r=this.getClient(e._schema),i=n?.id,a=Mu(`Insert`,e._columnTransforms?ed(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!zc(r)?.pending;s&&!i&&(i=rd());let c=s?id(e,i,a):void 0,l=J(r,()=>r.insert(e._table,a,xu(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?Zu(e,Ic(t,e._schema,e._table)):c))}async insertStreaming(e,t,n){Y(e);let r=this.getClient(e._schema),{column:i,source:a,values:o}=ad(e,t);$u(e,o),Cl(this);let s=n?.id;return J(r,async()=>{let t=Mu(`Insert`,ed(e,o),e._schema,e._table),c=this.getAccessContext(),l=sd(e,o);return r.insertStreaming(e._table,t,i,a,xu(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){Y(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=ad(e,n);$u(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=Mu(`Update`,ed(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,Su(e._schema,e._table,r),c?.writeSession,c?.attribution)})}async upsertStreaming(e,t,n,r){Y(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=ad(e,n);$u(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=Mu(`Upsert`,ed(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,Su(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){Y(e);let i=this.getClient(e._schema),a=Mu(`Restore`,e._columnTransforms?ed(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=zc(i)?.pending?id(e,t,a):void 0,c=J(i,()=>i.restore(e._table,t,a,xu(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=>Zu(e,Ic(t,e._schema,e._table))))}upsert(e,t,n,r){return Y(e),this.prepareMutation(e,t,n,`Upsert`,r)}prepareMutation(e,t,n,r,i,a){let o=this.getClient(e._schema);$u(e,n),zc(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=Su(e._schema,e._table,i),l=J(o,()=>{let i=n=>{let i=Mu(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=ed(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Uc(n)!==`not_observed`)throw n;return nd(o,e,t,s?.readSession,c?.branch).then(()=>{try{return i(l)}catch(t){throw Uc(t)===`not_observed`?Kc(`Update`,e._table):t}})}});return this.wrapWriteWait(l instanceof Promise?new Re(l.then(e=>e.txId),o):l)}update(e,t,n,r){Y(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Lu(e,n,r);r=Ru(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,Su(e._schema,e._table,r),s?.writeSession,s?.attribution)):this.prepareMutation(e,t,n,`Update`,r)}delete(e,t,n){Y(e);let r=this.getClient(e._schema),i=this.getAccessContext(),a=J(r,()=>r.delete(e._table,t,Su(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Re(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=ju(`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=ju(`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(),Cl(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 dd.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 J(e,()=>e.captureSnapshot())}beginTransaction(){return this.createTransaction(`mergeable`)}beginSerializableTransaction(){return this.createTransaction(`serializable`)}transaction(e){let t=this.beginTransaction();return ud(t,e,()=>Xu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return ud(t,e,()=>Xu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await ou(this,e)}isLocalFirst(){return!au(this)}async deleteClientStorage(){await this.connection.deleteClientStorage()}async storePendingUploads(){return await this.connection.storePendingUploads().catch(()=>void 0)??this.getSyncStatus().pendingUploads}isUsable(){return!this.stopping&&!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,mu(t))}catch(n){if(this.successor&&Ed(n))return this.current().all(e,t);throw n}}async allInternal(e,t){let n=this.getClient(e._schema),r=zc(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=Ws(JSON.parse(o)),c=Du(e._schema,s.table),l=xc(c,s),u=qu(e,s,l),d=Ou(e._schema,s.table,t),f=bc(o,c,u.physical),p=wu(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?Ju(e,s,l,u,g,e=>n.queryInternal(bc(o,c,e),d,m?.readSession)):g.map(u.transform)}async one(e,t){return(await this.all(Cu(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===le.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t,...e.reset&&e.reason?{reason:e.reason}:{}})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,mu(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),s=this.connection.initialExplicitOfflineState(),c=new u,l=e._build(),d=Ws(JSON.parse(l)),f=Du(e._schema,d.table),p=xc(f,d),m=qu(e,d,p),h=bc(l,f,m.physical),g=s===null,_=[],v=Ou(e._schema,d.table,n);v.splices&&(ku(f,p,e,v.splices),Au(d,m.physical,v.splices));let y=this.getAccessContext()?.readSession??r,b=null,x=!1,S=!1,C=new AbortController,w=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},T=e=>{if(!a){console.error(`Unhandled Jazz subscription error`,e);return}try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},E=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||S||(e.terminalDelivered=!0,S=!0,g=!1,_.length=0,b===e&&(b=null),w(e),e.predecessor!==null&&(w(e.predecessor),e.predecessor=null),C.abort(),this.liveSubscriptionEnders.delete(se),this.unregisterActiveQuerySubscriptionTrace(re),c.clear(),T(t))},D=(e,t)=>{x||S||b!==e||e.terminalDelivered||(e.terminalError??=I(t),E(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return b=t,t},te=e=>{if(!(x||S||b===null)){if(!g){_.push(e);return}try{i(e)}catch(e){let t=b;t!==null&&D(t,e)}}},ne=t=>{if(!(x||S||b===null))try{te(c.handleDelta(t,m.transform))}catch(t){if(!(t instanceof Xc)||!m.computedState||m.computedState.version===m.version)throw t;m=qu(e,d,p,m.computedState),v.splices&&Au(d,m.physical,v.splices),h=bc(l,f,m.physical),w(b);let n=ee();c.clear(),_.length=0,this.unregisterActiveQuerySubscriptionTrace(re),re=this.registerActiveQuerySubscriptionTrace(h,d.table,v),queueMicrotask(()=>{this.stopping||O(n)})}},O=(e,t=v)=>{if(x||b!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(h,{onUpdate:t=>{if(!(x||b!==e||e.terminalError!==null)){if(e.installing){n.push(t);return}try{ne(t)}catch(t){D(e,t)}}},onError:t=>{D(e,t)}},t,y)}catch(t){return e.installing=!1,D(e,t),null}if(e.installing=!1,x||b!==e||e.retired)return w(e),null;if(e.terminalError!==null)return E(e),null;try{for(let t of n){if(b!==e||e.terminalError!==null)break;ne(t)}}catch(t){return D(e,t),null}return x||b!==e||e.retired?null:e},re=this.registerActiveQuerySubscriptionTrace(h,d.table,v),ie=()=>{x||(x=!0,this.liveSubscriptionEnders.delete(se),g=!1,_.length=0,C.abort(),this.unregisterActiveQuerySubscriptionTrace(re),b!==null&&(w(b),b.predecessor!==null&&(w(b.predecessor),b.predecessor=null)),b=null,c.clear())},ae=s?.then(()=>{if(!(x||S||b===null||this.stopping)){g=!0;for(let e of _.splice(0)){if(x||S||b===null)return;te(e)}}}).catch(e=>{if(!(x||S||b===null||this.stopping))throw D(b,e),e});ae&&ae.catch(()=>void 0);let oe=ee(),se=e=>{b!==null&&D(b,e)};this.liveSubscriptionEnders.add(se);let k=v.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(k)?this.ensureReady(k,C.signal).then(()=>O(oe)).catch(e=>{x||C.signal.aborted||this.stopping||D(oe,e)}):O(oe);let ce=ie;return ae&&Object.defineProperty(ce,`ready`,{value:ae}),ce}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new su(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&&hs(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 gu)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;ue(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 ee(`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.teardown)return this.teardown;if(this.gracefulDrain)return e.waitForSync?this.gracefulDrain.done:(this.gracefulDrain.teardownAnyway=!0,this.gracefulDrain.done.catch(()=>this.beginTeardown()));if(!e.waitForSync)return this.beginTeardown();let t,n=new Promise(e=>{t=e}),r=new AbortController,i,a=new Promise((e,t)=>{i=t}),o={done:n,cancel:()=>{r.abort(),i(Error(`Graceful shutdown cancelled`))},teardownAnyway:!1};return this.gracefulDrain=o,t((async()=>{try{await Promise.race([this.runtimeSource.waitForPendingWrites?.(r.signal)??this.connection.waitForPendingWrites({inFlightStreams:this.streamsMayFinish?.signal}),a])}catch(e){throw r.abort(),this.gracefulDrain===o&&(this.gracefulDrain=null),o.teardownAnyway&&this.beginTeardown().catch(()=>{}),new Wo(e)}let e=this.beginTeardown();return this.gracefulDrain===o&&(this.gracefulDrain=null),e})()),a.catch(()=>{}),n}abortGracefulShutdown(){this.gracefulDrain?.cancel()}get stopping(){return this.phase!==`open`||this.gracefulDrain!==null}assertOpen(){if(this.replaced)throw this.replaced;if(this.phase!==`open`)throw new Go(this.phase);if(this.gracefulDrain)throw new Go(`draining`)}shutdownListeners=new Set;onShutdown(e){return this.phase===`open`?this.shutdownListeners.add(e):e(),()=>this.shutdownListeners.delete(e)}beginTeardown(){if(this.teardown)return this.teardown;this.phase=`closing`;let e,t=new Promise(t=>{e=t});return this.teardown=t,e(this.runTeardown().finally(()=>{this.phase=`closed`})),t}async runTeardown(){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:Tu(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 pd(){let e=T(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function md(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function hd(e,t){if(!t.supportsBrowserWorker||!wd()||uu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),gd.set(n,_d(e)),n}var gd=new WeakMap;function _d(e){try{let t=e.runtimeSources;return JSON.stringify([pu(e),Bi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function vd(e,t){let n=gd.get(e);return n!==void 0&&n===_d(t)}async function yd(e){if(!(!e||xd.has(e))){xd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function bd(e,t,n){let r=n;try{return await Sd(e,t,()=>(r??=hd(e,t),r))}finally{yd(r)}}var xd=new WeakSet;async function Sd(e,t,n){if(ts(e),Cd(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?ut(e.secret):null,i={...e};O(i,d(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...l}=e,u=r;if(u){let n=u;if(!e.jwtToken){let r=t.mintLocalFirstToken(md(n,U(e),3600)),a=Je(xe(r)??{},`device-account`);i={...l,jwtToken:r},O(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=pd(),r=t.mintAnonymousToken(md(n,U(e),3600)),a=Je(xe(r)??{},`anonymous`);i={...l,jwtToken:r},O(i,a)}ns(e,i),t.admitConfig(i);let f=uu(i.driver),p=t.supportsBrowserWorker&&wd()&&f.type===`persistent`,m=a&&p&&vd(a,i)?a:void 0;m?xd.add(m):a&&await yd(a);let h=p?await fd.createWithBrowserWorker(i,t,m):await fd.createWithDirectConnection(i,t);return u&&h.initLocalFirstAuth(u,3600,!e.jwtToken),h}function Cd(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 wd(){return typeof window<`u`&&typeof Worker<`u`}var Td=new WeakMap;function Ed(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof cu)return!0;return!1}function Dd(e,t){let{link:n}=e;return n.state!==`offline`||n.reason!==`auth`||t===void 0?e:{...e,link:{...n,authReason:t}}}var Od={napi:`bbf6677c5c2c40908bcd09fe354b774ecfa8a8e32f99a5449d0b37c7929ed3ae`,wasm:`17e42320465c3a9f0208a1f5bd9e6386a045623b3df4f3e4d34254197c54e1bb`},kd=`JAZZ_NATIVE_ARTIFACT_MISMATCH`,Ad=class extends Error{kind;expected;actual;missingExport;name=`NativeArtifactMismatchError`;code=kd;constructor(e,t,n,r,i){super(e),this.kind=t,this.expected=n,this.actual=r,this.missingExport=i}};function jd(e,t,n=[]){let r=Od[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw new Ad(`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.`,t,r,void 0);let i=e.nativeArtifactFingerprint();if(i!==r)throw new Ad(`Jazz ${t} artifact ABI mismatch: expected ${r}, got ${String(i)}. In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`,t,r,String(i));for(let i of n)if(typeof e[i]!=`function`)throw new Ad(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${i}.`,t,r,r,i)}var Md=class extends Error{},Nd=class extends Error{},Pd=new Set(`\\.+*?()|[]{}^$#&-~`),Fd=new Set(`imsUuRx`),Id=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Ld(e){return Pd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Rd=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 Md&&this.fancy?new Nd(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 Md(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,Fd.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++,Ld(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||!Id.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`}}},zd={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]]},Bd=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,Vd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:Bd};function Hd(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function Ud(e){return e.map(([e,t])=>{let n=Hd(String.fromCodePoint(e));return e===t?n:`${n}-${Hd(String.fromCodePoint(t))}`}).join(``)}var Wd=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Hd(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 Nd(`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=`[${Bd}]`;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=Hd(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Hd(e.start)}-${Hd(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Gd(this.parsed.fancy?Vd[e.perl]:Ud(zd[e.perl]),e.negated);case`ascii`:return Gd(Ud(zd[e.ascii]),e.negated);case`unicode`:return Gd(Kd(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 Gd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Kd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new Nd(`the Unicode class \`${e}\``)}function qd(e){try{return new Rd(e).parse(),!0}catch(e){return e instanceof Nd}}var Jd=new Map,Yd=1024;function Xd(e){let t=Jd.get(e);if(t)return t;let n=new Rd(e).parse();if(n.fancyInvalid.length>0)throw new Md(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new Nd(n.unsupported[0]);let r=new Wd(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),Jd.size>=Yd&&Jd.clear(),Jd.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 Qd(e){return e%4==0&&e%100!=0||e%400==0}function $d(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<=(Qd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function ef(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 tf(e){let t=e.search(/[Tt]/);return t<0?!1:$d(e.slice(0,t))&&ef(e.slice(t+1))}var nf=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,rf=`${nf}(?:\\.${nf}){3}`,X=`[0-9A-Fa-f]{1,4}`,af=`(?:${X}:${X}|${rf})`,of=[`(?:${X}:){6}${af}`,`::(?:${X}:){5}${af}`,`(?:${X})?::(?:${X}:){4}${af}`,`(?:(?:${X}:){0,1}${X})?::(?:${X}:){3}${af}`,`(?:(?:${X}:){0,2}${X})?::(?:${X}:){2}${af}`,`(?:(?:${X}:){0,3}${X})?::${X}:${af}`,`(?:(?:${X}:){0,4}${X})?::${af}`,`(?:(?:${X}:){0,5}${X})?::${X}`,`(?:(?:${X}:){0,6}${X})?::`].map(e=>`(?:${e})`).join(`|`),sf=RegExp(`^${rf}$`),cf=RegExp(`^(?:${of})$`),lf=e=>sf.test(e),uf=e=>cf.test(e);function df(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=_f(e.slice(4));if(t===void 0||!xf(t))return!1}}return!0}var ff=36,pf=1,mf=26,hf=4294967295;function gf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>(ff-pf)*mf>>1;)r=Math.trunc(r/(ff-pf)),i+=ff;return i+Math.trunc((ff-pf+1)*r/(r+38))}function _f(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=ff;;e+=ff){if(c>=r.length)return;let n=vf(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>hf||s>hf))return;let i=e<=o?pf:e>=o+mf?mf:e-o;if(n<i)break;if(t*=ff-i,t>hf)return}let n=i.length+1;if(o=gf(s-e,n,e===0),a+=Math.trunc(s/n),a>hf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function vf(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 yf=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))),bf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function xf(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||!yf.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(bf.has(o))return!1}return!(n&&!r||i&&a)}var Sf=new TextEncoder;function Cf(e){return Sf.encode(e).length}function wf(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 Tf=/^[\p{Alphabetic}\p{N}]$/u,Ef=new Set("!#$%&'*+-/=?^_`{|}~");function Df(e){return Tf.test(e)||Ef.has(e)||wf(e)}function Of(e){return e.length>0&&[...e].every(Df)}function kf(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||wf(n)))return!1}return!0}function Af(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||wf(e)}function jf(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function Mf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=jf(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=jf(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||Cf(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!kf(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(Of))return!1;if(o.length===0||Cf(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(Af)?e.startsWith(`IPv6:`)?uf(e.slice(5)):lf(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!Tf.test(t[0])||!Tf.test(t[t.length-1])||Cf(e)>63||!Of(e))return!1}return df(o)}var Nf=`A-Za-z0-9\\-._~`,Pf=`!$&'()*+,;=`,Ff=`%[0-9A-Fa-f]{2}`,If=`(?:[${Nf}${Pf}:@]|${Ff})`,Lf=`${If}*`,Rf=`${If}+`,zf=`(?:[${Nf}${Pf}@]|${Ff})+`,Bf=`\\[(?:${of}|[vV][0-9A-Fa-f]+\\.[${Nf}${Pf}:]+)\\]`,Vf=`(?:[${Nf}${Pf}]|${Ff})*`,Hf=`(?:${`(?:[${Nf}${Pf}:]|${Ff})*`}@)?(?:${Bf}|${Vf})(?::[0-9]*)?`,Uf=`(?:/${Lf})*`,Wf=`/(?:${Rf}(?:/${Lf})*)?`,Gf=`${Rf}(?:/${Lf})*`,Kf=`${zf}(?:/${Lf})*`,qf=`(?:${If}|[/?])*`,Jf=`[A-Za-z][A-Za-z0-9+\\-.]*`,Yf=`(?://${Hf}${Uf}|${Wf}|${Gf}|)`,Xf=`(?://${Hf}${Uf}|${Wf}|${Kf}|)`,Zf=`(?:\\?${qf})?(?:#${qf})?`,Qf=RegExp(`^${Jf}:${Yf}${Zf}$`),$f=RegExp(`^(?:${Jf}:${Yf}|${Xf})${Zf}$`);function ep(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function tp(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&ep(n)}var np=new Set(`+#./;?&=,!@|`),rp=new Set(`"'<>%\\^\`{|}`);function ip(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||np.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||rp.has(r))return!1;t++}}return!0}var ap={date:$d,"date-time":tf,email:Mf,hostname:df,ipv4:lf,ipv6:uf,"json-pointer":ep,regex:qd,"relative-json-pointer":tp,time:ef,uri:e=>Qf.test(e),"uri-reference":e=>$f.test(e),"uri-template":ip},op=class{value;constructor(e){this.value=e}},sp=2n**64n-1n,cp=-(2n**63n),lp=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,up=/[ \t\n\r]*/y;function dp(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{up.lastIndex=t,up.test(e),t=up.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=()=>{lp.lastIndex=t;let r=lp.exec(e);if(!r)return n();t=lp.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new op(a):a;if(Object.is(a,-0))return new op(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<cp||o>sp?new op(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 fp(e){return typeof e==`number`||typeof e==`bigint`||e instanceof op}function pp(e){return e instanceof op?e.value:e}function mp(e,t){return typeof e==`bigint`?!0:e instanceof op?!t:Number.isInteger(e)}function hp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof op){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):gp(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?gp(e):Array.isArray(e)?`[${e.map(hp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${hp(t)}`).join(`,`)}}`:JSON.stringify(e)}function gp(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function _p(e){if(e instanceof op)return e.value;if(Array.isArray(e))return e.map(_p);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=_p(r);return t}function vp(e,t){if(fp(e))return fp(t)?pp(e)==pp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>vp(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||fp(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&vp(e[n],t[n])):!1}return e===t}function yp(e,t){let n=Number(pp(e)),r=Number(pp(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]=bp(n),[o,s]=bp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function bp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*xp(10,t),!Number.isFinite(n))return Sp(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(xp(10,t))]}function xp(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 Sp(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 Cp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},wp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Tp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ep=new URL(`json-schema:///`);function Dp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function Op(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kp(e,t=Object.create(null),n=[],r=Ep,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(!Op(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(wp[i]&&Array.isArray(a))for(let e of a)kp(e,t,n,r,!1);else if(Cp[i])kp(a,t,n,r,!1);else if((Tp[i]||i===`dependencies`)&&Op(a))for(let e in a)kp(a[e],t,n,r,!1)}return t}function Ap(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(Op(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||Op(i)?i:void 0}}function jp(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 Mp(e){if(e===null)return`null`;if(fp(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 Np(e,t,n,r,i){return Z(e,t,{draft:n,lookup:r,shortCircuit:i},null,`#`,`#`)}function Z(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=Mp(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:ee,unevaluatedProperties:te,minProperties:ne,maxProperties:O,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:oe,prefixItems:se,items:k,additionalItems:ce,unevaluatedItems:A,contains:le,minContains:j,maxContains:ue,minItems:de,maxItems:fe,uniqueItems:pe,minimum:me,maximum:M,exclusiveMinimum:he,exclusiveMaximum:N,multipleOf:ge,minLength:_e,maxLength:ve,pattern:ye,__absolute_ref__:be,__absolute_recursive_ref__:xe}=t,P=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?Ap(c,xe):r,l=`${a}/$recursiveRef`,u=Z(e,r===null?t:r,n,s,i,l,o);u.valid||P.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=Ap(c,be??d);if(t===void 0)throw Error(`Unresolved $ref "${d}".`);let l=`${a}/$ref`,u=Z(e,t,n,r,i,l,o);if(u.valid||P.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:P.length===0,errors:P}}let Se=u===`number`&&mp(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&Se)||P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?Se||P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!vp(e,h)&&P.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${hp(h)}.`}),g!==void 0&&!g.some(t=>vp(e,t))&&P.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${hp(g)}.`}),v!==void 0){let t=`${a}/not`;Z(e,v,n,r,i,t).valid&&P.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Ce=[];if(y!==void 0){let t=`${a}/anyOf`,s=P.length,c=!1;for(let a=0;a<y.length;a++){let s=Object.create(o),l=Z(e,y[a],n,p===!0?r:null,i,`${t}/${a}`,s);P.push(...l.errors),c||=l.valid,l.valid&&Ce.push(s)}c?P.length=s:P.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=P.length,c=!0;for(let a=0;a<b.length;a++){let s=Object.create(o),l=Z(e,b[a],n,p===!0?r:null,i,`${t}/${a}`,s);P.push(...l.errors),c&&=l.valid,l.valid&&Ce.push(s)}c?P.length=s:P.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=P.length,c=x.filter((a,s)=>{let c=Object.create(o),l=Z(e,a,n,p===!0?r:null,i,`${t}/${s}`,c);return P.push(...l.errors),l.valid&&Ce.push(c),l.valid}).length;c===1?P.length=s:P.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,...Ce),S!==void 0){let t=`${a}/if`,s=Object.create(o);if(Z(e,S,n,r,i,t,s).valid){if(Object.assign(o,s),C!==void 0){let s=Z(e,C,n,r,i,`${a}/then`,o);s.valid||P.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...s.errors)}}else if(w!==void 0){let s=Z(e,w,n,r,i,`${a}/else`,o);s.valid||P.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||P.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(ne!==void 0&&s.length<ne&&P.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ne} properties.`}),O!==void 0&&s.length>O&&P.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${O} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${Dp(a)}`,o=Z(a,re,n,r,t,e);o.valid||P.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||P.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=Z(e,ae[s],n,r,i,`${c}/${Dp(s)}`,o);t.valid||P.push({instanceLocation:i,keyword:`dependentSchemas`,keywordLocation:c,error:`Instance has "${s}" but does not match dependant schema.`},...t.errors)}}if(oe!==void 0){let o=`${a}/dependencies`;for(let a in oe)if(a in t){let s=oe[a];if(Array.isArray(s))for(let e of s)e in t||P.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not have "${e}".`});else{let t=Z(e,s,n,r,i,`${o}/${Dp(a)}`);t.valid||P.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}/${Dp(a)}`,d=Z(t[a],E[a],n,r,s,`${e}/${Dp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,P.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=Xd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${Dp(f)}`,m=Z(t[f],d,n,r,p,`${e}/${Dp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,P.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&ee!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${Dp(a)}`,d=Z(t[a],ee,n,r,s,e);d.valid?o[a]=!0:(u=l,P.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&te!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${Dp(a)}`,c=Z(t[a],te,n,r,s,e);c.valid?o[a]=!0:P.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;fe!==void 0&&s>fe&&P.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${fe}).`}),de!==void 0&&s<de&&P.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${de}).`});let c=0,u=!1;if(se!==void 0){let e=`${a}/prefixItems`,d=Math.min(se.length,s);for(;c<d;c++){let a=Z(t[c],se[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,P.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(k!==void 0){let e=`${a}/items`;if(Array.isArray(k)){let a=Math.min(k.length,s);for(;c<a;c++){let a=Z(t[c],k[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,P.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}else for(;c<s;c++){let a=Z(t[c],k,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,P.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=Z(t[c],ce,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,P.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(le!==void 0)if(s===0&&j===void 0)P.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(j!==void 0&&s<j)P.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${j}).`});else{let e=`${a}/contains`,c=P.length,l=0;for(let a=0;a<s;a++){let s=Z(t[a],le,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):P.push(...s.errors)}l>=(j||0)&&(P.length=c),j===void 0&&ue===void 0&&l===0?P.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):j!==void 0&&l<j?P.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${j} items matching schema. Only ${l} items were found.`}):ue!==void 0&&l>ue&&P.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${ue} items matching schema. ${l} items were found.`})}if(!u&&A!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=Z(t[c],A,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||P.push({instanceLocation:i,keyword:`unevaluatedItems`,keywordLocation:e,error:`Items did not match unevaluated items schema.`},...a.errors)}}if(pe){outer:for(let e=0;e<s;e++)for(let n=e+1;n<s;n++)if(vp(t[e],t[n])){P.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=pp(e);s===`4`?(me!==void 0&&(he===!0&&t<=me||t<me)&&P.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${he?`or equal to `:``}${me}.`}),M!==void 0&&(N===!0&&t>=M||t>M)&&P.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${N?`or equal to `:``}${M}.`})):(me!==void 0&&t<me&&P.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${me}.`}),M!==void 0&&t>M&&P.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${M}.`}),he!==void 0&&t<=he&&P.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${he}.`}),N!==void 0&&t>=N&&P.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${N}.`})),ge!==void 0&&!yp(e,ge)&&P.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ge}.`})}else if(u===`string`){let t=e,n=_e===void 0&&ve===void 0?0:jp(t);_e!==void 0&&n<_e&&P.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${_e}).`}),ve!==void 0&&n>ve&&P.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${ve}).`}),ye!==void 0&&!Xd(ye).test(t)&&P.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:ap[T];r&&!r(t)&&P.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:P.length===0,errors:P}}var Pp={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`}}}]},Fp={"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`},Ip=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(`.`)),Lp={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`]},Rp={...Lp,single:[...Lp.single,`contains`,`propertyNames`],plain:[...Lp.plain.filter(e=>e!==`id`),`$id`,`const`]},zp={...Rp,single:[...Rp.single,`if`,`then`,`else`]},Bp={single:[...zp.single,`unevaluatedItems`,`unevaluatedProperties`],array:zp.array,map:[...zp.map,`$defs`,`dependentSchemas`],plain:[...zp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},Vp={single:Bp.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Bp.map,plain:Bp.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)},Hp={4:Lp,6:Rp,7:zp,"2019-09":Bp,"2020-12":Vp},Up={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Wp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Gp=[...Wp,`json-pointer`,`uri-reference`,`uri-template`],Kp={4:Wp,6:Gp,7:[...Gp,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},qp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Jp={base64:Yp(`A-Za-z0-9+/`),base64url:Yp(`A-Za-z0-9\\-_`),base32:Xp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:Xp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Yp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function Xp(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 Qp(e){if(!A(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Fp[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new Zp(`unknown JSON Schema dialect "${t}"`);return n}function $p(e,t,n=[]){if(typeof e==`boolean`)return e;if(!A(e))return{};let r=Hp[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(Up[t].includes(s)&&!n.includes(s))throw new Zp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(Ip.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&tm(c),s===`patternProperties`&&A(c))for(let e of Object.keys(c))tm(e);if(s===`format`&&typeof c==`string`){if(!Kp[t]?.includes(c))continue;if(qp.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=>$p(e,t,n))]):r.single.includes(s)?o.push([s,$p(c,t,n)]):r.map.includes(s)&&A(c)?o.push([s,em(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Jp[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 em(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:$p(r,t,n)]))}function tm(e){try{Xd(e)}catch(t){throw t instanceof Md?new Zp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof Nd?new Zp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function nm(e){for(let t of e.references)if(Ap(e.lookup,t)===void 0)throw new Zp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function rm(e){if(Array.isArray(e))return e.map(rm);if(!A(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,rm(r)]);return Object.fromEntries(t)}var im={4:Pp.draft4,6:Pp.draft6,7:Pp.draft7,"2019-09":Pp.draft201909,"2020-12":Pp.draft202012};function am(e){return im[e].map(t=>e===`2020-12`?rm($p(t,e,[`$dynamicAnchor`,`$dynamicRef`])):$p(t,e))}var om=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=kp(e,void 0,this.references);for(let e of r)kp(e,this.lookup)}validate(e){return Np(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},sm=new Map;function cm(e){let t=sm.get(e);if(!t){let[n,...r]=am(e);t=new om(n,e,!1,r),sm.set(e,t)}return t}function lm(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 um(e){let t=Qp(e);if(typeof e==`boolean`){if(t===`4`)throw new Zp(`boolean schemas need draft 6 or later`)}else{let n=cm(t).validate(e);if(!n.valid)throw new Zp(lm(n.errors))}let n=new om($p(_p(e),t),t,!0,am(t));return nm(n),e=>{let t=n.validate(dp(e));return t.valid?void 0:lm(t.errors)}}function dm(e){return um(dp(e))}function fm(e){e.setJsonSchemaValidator(dm)}async function pm(){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 mm=Promise.resolve(),hm;function gm(e){let t=mm.then(()=>_m(e));return mm=t.then(()=>void 0,()=>void 0),t}async function _m(t){let n=await e(()=>import(`./jazz_wasm-MSQOvwc8.js`),[],import.meta.url),r=Qr(t);if(r)return n.initSync(r),vm(n);let i=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await pm();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 ym(n,e);else if(typeof location<`u`&&Ki())throw Error(Wi);else await n.default()}return vm(n)}function vm(e){return jd(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),fm(e),e}async function ym(e,t){if(hm===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(bm(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}),hm=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}),hm=t}function bm(e){return typeof WebAssembly.compileStreaming==`function`?e?.trim()===`application/wasm`:!1}function xm(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 Sm(e,t,n,r){return Rr(`${a}${e}`,{audience:t,ttlSeconds:n,now:r})}var Cm=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 Sm(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*wm(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 Tm=`authority_changed`,Em=class extends Error{name=`AuthorityChangedError`;code=Tm;constructor(e,t){super(e,t)}};function Dm(e){return!e||typeof e!=`object`?!1:e.code===Tm}function Om(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(Dm(e))return new Em(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 km=`core_tick_failed`,Am=class extends Error{name=`CoreTickFailedError`;code=km;constructor(e){super(`core tick failed: ${Mm(e)}`,{cause:e})}};function jm(e){return!e||typeof e!=`object`?!1:e.code===km}function Mm(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 Nm=class extends _s{},Pm=class{text;constructor(e){this.text=e}};function Fm(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 Im(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Fm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Fm(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 Pm(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 Lm(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`),Fm(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 Pm&&(/^(?: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 Pm){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`,`StartsWith`,`EndsWith`],`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 if(`IsNull`in e)d(1),v(e.IsNull.column);else if(`IsNotNull`in e)d(2),v(e.IsNotNull.column);else if(`In`in e)d(3),v(e.In.left),c(e.In.values.length),e.In.values.forEach(e=>u(()=>C(e)));else if(`Contains`in e)d(4),v(e.Contains.left),u(()=>C(e.Contains.right));else if(`StartsWith`in e||`EndsWith`in e){let t=`StartsWith`in e?e.StartsWith:e.EndsWith;d(`StartsWith`in e?11:12),v(t.left),u(()=>C(t.right))}else `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)}Ne({issuer:Oe,user_id:`system`,claims:{},authMode:`external`});var Rm=-(1n<<63n),zm=(1n<<63n)-1n;function Bm(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<Rm||n>zm)throw Error(`${t} must be a signed 64-bit integer`);return n}var Vm=new k({fatal:!0});function Hm(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function Um(e){return{table:e.string(),descriptor:Gm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Wm(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),th(e,r.valueType)},t.length)}function Gm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:nh(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:nh(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:nh(e)}:Km(t)})}function Km(e){throw Error(`unknown native row descriptor field kind ${e}`)}function qm(e){let t={added:e.readVec(Um),updated:e.readVec(Um),removed:e.readVec(Qm),addedOccurrenceKeys:e.readVec(e=>Jm(e)),updatedOccurrenceKeys:e.readVec(e=>Jm(e)),removedOccurrenceKeys:e.readVec(e=>Jm(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 Jm(e){let t=e.bytes();if(t[0]!==2||!Ym(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Ym(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||!s(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 Xm(e){let t=e.u64(),n=e.readVec(Um);return Zm(e,`relation snapshot`),{rootCount:t,rows:n}}function Zm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Qm(e){return{table:e.string(),rowId:e.bytes()}}function $m(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),th(e,t[n].valueType)},t.length)}function eh(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:nh(e)}))}function th(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)=>th(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}`);th(e,t.inner);return}if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);$m(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),$m(e,n.payload)},r.length)}}function nh(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:nh(e)};if(t===13){let n=e.readVec(nh);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:eh(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:eh(e)}))}}:{tag:t}}function rh(e,t){let n=zh(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=ot(r),o=new Uh,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 ot([a,o.finish(),...i])}function ih(e,t){let n=ph(yh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:jh(e.column_type,i)})}function ah(e,t){return Object.defineProperty(e,`valuesByColumn`,{value:t,enumerable:!1,configurable:!0}),e}function oh(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 sh={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function ch(e,t,n){let r=lh([sh,...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 ah({id:e,values:a},oh(t,a))}function lh(e,t){let n=ph(yh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:uh(e.column_type,i,e.name)})}function uh(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:Ih(t,n)};case`Array`:return{type:`Array`,value:dh(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:ch(Lh(t.subarray(0,16)),e.columns,t)};default:return jh(e,t)}}function dh(e,t){return Fh(e,t,t=>uh(e,t))}function fh(e,t){return rh(yh(e),e.map((e,n)=>bh(e,t[n])))}function ph(e){let t=zh(e);return(n,r)=>mh(e,t,n,r)}function mh(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 hh(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:Bh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Bh(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 ${gh(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return hh(n.subarray(c,l),a)}function hh(e,t){if(t.tag!==15)return e;let n=vh(e);return n==null?null:t.inner?hh(n,t.inner):n}function gh(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?gh(e.inner):`?`}>`:_h(e.tag)}function _h(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 vh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function yh(e){return e.map(e=>({name:e.name,valueType:Oh(e)}))}function bh(e,t){let n=Ah(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return Sh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return Sh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=Sh(r);return e.sparse?xh(t,r):t}let i=Ch(e.column_type,t);return e.nullable&&(i=xh(i,n)),e.sparse?xh(i,r):i}function xh(e,t){if(Rh(t)==null)return ot([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function Sh(e){let t=Rh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function Ch(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=Vh(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=Hh(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 ot([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return Dh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return ot([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return Th(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return wh(e.columns,t.value)}}function wh(e,t){let n=fh(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?Dh(t.id):new Uint8Array;return ot([Uint8Array.of(t.id?1:0),r,Eh(n.byteLength),n])}function Th(e,t){let n=t.map(t=>Ch(e,t));if(Rh(Ah(e))!=null)return ot(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)}),ot([Eh(t.length),r,...n])}function Eh(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function Dh(e){let t=Ee(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function Oh(e){let t=Ah(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function kh(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[...kh(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[...kh(e.column_type.element.columns)]}}:e.column_type}))}function Ah(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:Ah(e.element)};case`Row`:return{tag:9}}}function jh(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:Vm.decode(Mh(t))};case`Uuid`:return{type:`Uuid`,value:Lh(t)};case`Bytea`:return{type:`Bytea`,value:Mh(t).slice()};case`Array`:return{type:`Array`,value:Ph(e.element,t)};case`Row`:return{type:`Row`,value:Nh(e.columns,t)}}}function Mh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function Nh(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Lh(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=ih(e,o);return ah({id:i,values:s},oh(e,s))}function Ph(e,t){return Fh(e,t,t=>jh(e,t))}function Fh(e,t,n){let r=Rh(Ah(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=Bh(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:Bh(t,4+(e-1)*4),s=e===i-1?t.length:Bh(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 Ih(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Lh(e){if(e.length>=16)return $e(e,0);let t=Se(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Rh(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=Rh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Rh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function zh(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Rh(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(Rh(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 Bh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Vh(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 Hh(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Bm(e.value,`BigInt value`)}var Uh=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)}},Wh=new k({fatal:!0}),Gh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Kh(e,t){return t?Gh:e}function qh(e,t,n,r=!1,i,a,o,s){let c=new cg;return c.bytes(e),c.string(Jh(Kh(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(ug(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Jh(e){try{let t=Wh.decode(e);if(te(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Yh(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&&Qh(`query limit`,r),Qh(`query offset`,i);let u=new cg;return u.string(e),u.vec((e,n)=>{let r=t[n];eg(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(Lm(c),!1)),Xh(u,l),u.finish()}function Xh(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}Qh(`partial selection ${r.column} start`,r.from),Qh(`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&&Qh(`array subquery ${t.columnName} limit`,a),Qh(`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)=>{eg(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($h(s)),e.vec((e,t)=>{Zh(e,c[t])},c.length),Xh(e,[])}function Qh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function $h(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function eg(e,t){if(t.op===`All`||t.op===`Any`){e.u64(t.op===`All`?0:1),e.vec((e,n)=>eg(e,t.predicates[n]),t.predicates.length);return}if(t.op===`Not`){e.u64(2),eg(e,t.predicate);return}if(t.op===`In`){e.u64(5),rg(e,t.column),e.vec((e,n)=>{e.u64(3),og(e,t.values[n])},t.values.length);return}if(t.op===`Contains`){e.u64(10),rg(e,t.column),ig(e,t.value);return}if(t.op===`StartsWith`||t.op===`EndsWith`){e.u64(t.op===`StartsWith`?13:14),rg(e,t.column),ig(e,t.value);return}if(t.op===`IsNull`||t.op===`IsNotNull`){t.op===`IsNotNull`&&e.u64(2),e.u64(12),rg(e,t.column);return}if(tg(t)){ng(e,t.column,t.op,t.value);return}throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function tg(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function ng(e,t,n,r){e.u64(ag(n)),rg(e,t),ig(e,r)}function rg(e,t){e.u64(0),e.string(t)}function ig(e,t){e.u64(3),og(e,t)}function ag(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 og(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=>og(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=Ee(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)=>og(e,t.value[n]),t.value.length);return}e.u64(6),e.string(t.value)}var sg=64,cg=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=Bm(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(dg(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<sg){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)}},lg=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 Wh.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 ug(e){return dg(JSON.stringify(e,b))}function dg(e){return new TextEncoder().encode(e)}var fg=new TextEncoder;function pg(e){return fg.encode(he(e))}function mg(e){let t=new cg;return t.string(e.table),Wm(t,[...e.descriptor]),Se(t.finish())}var hg=3600*1e3,gg=500,_g=`jazz-http-stream-endpoints`,vg=`endpoints`;function yg(){return globalThis.indexedDB!==void 0}function bg(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(_g,1);r.onupgradeneeded=()=>r.result.createObjectStore(vg),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function xg(e,t){let n=bg();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(vg,e).objectStore(vg));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var Sg=`jazz-stream-endpoint:`,Cg=600*1e3;function wg(){if(!(typeof document>`u`))try{return globalThis.localStorage??void 0}catch{return}}function Tg(e,t=Date.now()){let n=wg();if(n)try{let r=n.getItem(Sg+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(Sg+e);return}return i===`stream`}catch{return}}function Eg(e,t,n){let r=wg();if(r)try{r.setItem(Sg+e,`${t}:${n}`)}catch{try{r.removeItem(Sg+e)}catch{}}}async function Dg(e,t=Date.now()){let n,r=await Promise.race([xg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),gg)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?Eg(e,`stream`,r.until):Eg(e,`none`,t+Cg),i}function Og(e,t=Date.now()){return Eg(e,`stream`,t+hg),xg(`readwrite`,n=>n.put(t+hg,e)).then(()=>void 0,()=>void 0)}function kg(e){return Eg(e,`none`,Date.now()+Cg),xg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var Ag=`x-jazz-stream-key`;function jg(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 Mg(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 Ng=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?Mg([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}},Pg=new TextEncoder,Fg=new TextDecoder;function Ig(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 Lg=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)}},Rg=4*1024*1024,zg=(e,t)=>fetch(e,t),Bg=class extends Lg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=zg){super(),this.request=t,this.streamUrl=Ig(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?Pg.encode(e):e;this.queued.push(jg(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:{[Ag]:e.key},signal:AbortSignal.timeout?.(Ug)}).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 Ng;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(Fg.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(Fg.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<=Rg);)t+=this.queued[e].byteLength,e+=1;let n=Mg(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`,[Ag]:this.session.key},body:n,signal:this.abort.signal});if(!r.ok)throw Error(`HTTP stream send refused (${r.status})`)}}catch(e){if(this.readyState>=2)return;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,this.queued.length=0,n&&this.abort.abort(),this.emit(`close`,{code:e,reason:t}))}},Vg=new Set,Hg=new Map,Ug=1e4,Wg=new Map,Gg=`x-jazz-stream`,Kg=new Set,qg=`x-jazz-store-error`,Jg=new Set;async function Yg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(Ug)});if(n.status===503&&n.headers.get(qg)===`1`){let t=await n.text().catch(()=>``);return t&&!Jg.has(`${e}\n${t}`)&&(Jg.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(Gg)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function Xg(e,t,n){let r=await Yg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return Hg.delete(e),Wg.delete(e),r===`refused`&&!Kg.has(e)&&(Kg.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=(Hg.get(e)??0)+1;Hg.set(e,i);let a=t?(Wg.get(e)??0)+1:0;t?Wg.set(e,a):Wg.delete(e);let o=a>=2;return i<3&&!o?r:(Hg.delete(e),Wg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${Ug/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??zg,r=t.describeFailedUpgrade;return class extends Lg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,Vg.has(e)){this.openStream();return}if(!yg()){this.inner=this.openNative();return}let t=Tg(e);if(t===!0){Vg.add(e),this.openStream();return}if(t===!1){this.inner=this.openNative();return}Dg(e).then(t=>{this.closedEarly||(t?(Vg.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 Bg(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(Vg.delete(this.url),kg(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,Xg(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){Vg.add(this.url),e===`stream`&&Og(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()},Ug),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,Hg.delete(this.url),Wg.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 Qg=`jazz_renewal`,$g=`X-Jazz-Renew`,e_=2048;function t_(e){let t=new lg(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>e_)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function n_(e){let t=new cg;return t.u64(65),t.string(e),t.finish()}function r_(e){return e[0]===64}function i_(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 a_(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var o_=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function s_(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function c_(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}function l_(e){return e.code===`protocol_error`?!0:(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)&&!c_(e)}var u_=12e4,d_=1e3,f_=7,p_=12688,m_=1<<20,h_=5,g_=5,__=2*1024*1024,v_=4096;function y_(e){x_(e);let t=new cg;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>__)throw Error(`websocket frame batch exceeds maximum length of ${__} bytes`);return n}function b_(e){if(e.byteLength>__)throw Error(`websocket frame batch exceeds maximum length of ${__} bytes`);let t=new lg(e),n=t.u64();if(n===0||n>v_)throw Error(`websocket frame batch exceeds frame-count limit of ${v_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(__,`websocket frame`));return P_(t,`websocket frame batch`),r}function x_(e){if(e.length===0||e.length>v_)throw Error(`websocket frame batch exceeds frame-count limit of ${v_}`);for(let t of e)if(t.byteLength>__)throw Error(`websocket frame exceeds maximum length of ${__} bytes`)}function S_(e=p_){j_(e,`client wire features`);let t=new cg;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var C_=0,w_=1;function T_(e){if(e[0]!==C_)return!1;let t=new lg(e);t.u64();let{min:n,max:r}=M_(t);return n===6&&r===6&&N_(t),!0}function E_(e){return e[0]===w_?(D_(e),!0):!1}function D_(e){let t=new lg(e),n=t.u64();if(n!==w_)throw Error(`expected WireFrame::Error, got tag ${n}`);let r={code:$_(t.u64()),retry:tv(t.u64()),message:t.string()};return t.done()||(r.reason=ev(t.u64())),P_(t,`WireFrame::Error`),r}function O_(e){return e.code===`auth_failed`?e.reason===`reauthenticate`?`invalid`:S(e.reason!==void 0&&!e.reason.startsWith(`unknown:`)?e.reason:e.message):null}var k_=class{url;socket;onFrame;onError;onTerminal;localFeatures;opened;resolveNegotiation;rejectNegotiation;negotiated=!1;helloSent=!1;ahead=[];closing=!1;terminated=!1;lastInbound=performance.now();handlingMessages=0;afterMessages=[];silenceTimer;handshakeTimer;renewalUrl;renewalTimer;constructor(e){this.url=e.endpointUrl;let t=e.WebSocket??Ze(this.url)??X_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??12688)|18432,this.renewalUrl=L_(e.authJson)?i_(this.url):null,j_(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}),nv(this.socket).then(()=>{if(!this.closing){this.socket.send(I_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(y_([S_(this.localFeatures)])),this.helloSent=!0;for(let e of this.ahead.splice(0))this.write(e)}},e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:String(e)}),this.close()});let n=e=>{this.handlingMessages===0?e():this.afterMessages.push(e)};this.socket.addEventListener(`message`,e=>{this.lastInbound=performance.now(),this.handlingMessages+=1,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()}).finally(()=>{if(--this.handlingMessages,!(this.handlingMessages>0))for(let e of this.afterMessages.splice(0))e()})}),this.socket.addEventListener(`error`,e=>n(()=>this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:`websocket transport error`}))),this.socket.addEventListener(`close`,e=>{let t=F_(e);n(()=>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(),this.write(e)}sendAhead(e){this.closing||this.terminated||(this.helloSent?this.write(e):this.ahead.push(e))}write(e){let t=[],n=g_;for(let r of e){let e=r.byteLength+h_;t.length>0&&(t.length>=v_||n+e>m_)&&(this.socket.send(y_(t)),t=[],n=g_),t.push(r),n+=e}t.length>0&&this.socket.send(y_(t))}ready(){return this.opened}get hasNegotiated(){return this.negotiated}close(){if(!this.closing){this.closing=!0,this.ahead=[],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())},d_)},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)&&z_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send(n_(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),d_);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(),u_-t)}async handleMessage(e){for(let t of b_(await Y_(e))){if(this.closing)return;if(T_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=A_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&-18433});continue}if(!(this.negotiated&&t.byteLength===1&&t[0]===f_)){if(this.negotiated&&this.renewalUrl&&r_(t)){this.scheduleRenewal(t_(t));continue}if(!this.negotiated){if(E_(t)){let e=D_(t);if(O_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new o_(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(E_(t)){let e=D_(t);if(s_(e)){this.reportTerminal(e),this.close();return}this.onError?.(e);continue}this.onFrame(t)}}}};function A_(e,t=p_){let n=new lg(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=M_(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}=N_(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 j_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function M_(e){return{min:e.u64(),max:e.u64()}}function N_(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 P_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function P_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function F_(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 I_(e,t,n,r=!1){let i=JSON.parse(e),a=new k().decode(t),o=rv(i)??J_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Qg]:1}:{}})}function L_(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 R_=3e4;async function z_(e,t){return B_(a_(e),()=>V_(e,t))}async function B_(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,R_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function V_(e,t){try{let n=await Ge(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[$g]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function H_(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=xe(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 rt(t)}return rt(n)}function U_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!G_(n))return new TextEncoder().encode(r(`urn:jazz:system`,`system`));let i=q_(n),a=null;try{a=te(new k({fatal:!0}).decode(t))}catch{}if(a?.account_id&&i){let e=te(i);if(e.issuer!==a.issuer||e.user_id!==a.user_id||e.account_id!==void 0&&e.account_id!==a.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return i?new TextEncoder().encode(i):t}function W_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!G_(t)&&delete t.jwt_token,JSON.stringify(t)}function G_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&D(t.issuer)&&D(t.user_id)}function K_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||q_(t)!==null}function q_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&G_(e)){let t=e.backend_session;return r(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=xe(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,i=t?.sub;if(typeof n==`string`&&typeof i==`string`&&D(n)&&D(i))return r(n,i)}return null}function J_(e){return te(e)?.user_id??null}async function Y_(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 X_(e){let t=Q_();return Z_(e)?Zg(t):t}function Z_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function Q_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function $_(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:return`unknown:${e}`}}function ev(e){switch(e){case 0:return`expired`;case 1:return`missing`;case 2:return`invalid`;case 3:return`disabled`;case 4:return`revoked`;case 5:return`reauthenticate`;default:return`unknown:${e}`}}function tv(e){switch(e){case 0:return`never`;case 1:return`after_auth`;case 2:return`after_resume`;case 3:return`later`;default:return`unknown:${e}`}}function nv(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 rv(e){let t=e.sub;if(typeof t==`string`&&D(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=iv(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&D(e))return e}return null}function iv(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(av(t[1]));return typeof e.sub==`string`&&D(e.sub)?e.sub:null}catch{return null}}function av(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 ov=20,sv=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,cv=16,lv={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},uv=250,dv=4;function fv(e){return typeof e?.poll==`function`}function pv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function mv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function hv(e,t){return c_(e)?{kind:`network`,message:e.message}:l_(e)?{kind:`fatal`,message:e.message}:{kind:`wire`,...e,admitted:t}}function gv(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function _v(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var vv=new k({fatal:!0}),yv=new WeakMap;function bv(e,t,n,r,i,a=!1){try{return xv(e,t,n,r,i,a)}catch(e){throw Qe(e)}}function xv(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 Sv(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 Cv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var wv={open:0,quiesced:1,storageCleared:1,closing:2,closed:3},Tv=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;authRestoredCallback=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 Nm(()=>this.readRemoteLinkState());linkStatusPublisher=new _s(()=>this.upstreamLinkStatus(),ps);syncStatusPublisher=new _s(()=>this.readSyncStatus(),(e,t)=>gs(e.uploads,t.uploads)&&ps(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;phase=`open`;foregroundLeaseCapture=null;foregroundLeaseDraining=!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,subscriptionBacklogRows:s?.subscriptionBacklogRows})}migrations;registerSchemaView(t,n){return new e(null,t,this.node,this.peerIdentity,1,!0,{db:this.db.registerSchema(pg(t),n?ug(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=pg(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=qh(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=ge(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=bv(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=Sv(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)}let c=o?.subscriptionBacklogRows;if(c!==void 0&&(is(c,`subscriptionBacklogRows`),this.db.setSubscriptionBacklogRows?.(c)),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?Om({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:y(),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 ${this.phase}`);this.advancePhase(`quiesced`),this.clearCoreDeadline(),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(!Kb(n,this.peerIdentity))throw ky();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?.(lv[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()},uv))}noteFirstLoadWait(e){if(!Wv(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 q(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?q(`disconnected`):e.authRejected?q(`auth`):e.connected?ds:this.serverTransportError?this.serverTransportErrorRetrying?q(`network`):Dm(this.serverTransportError)?q(`authority-changed`,!1):q(`stopped`):us:ls:this.linkStatus?.phase===`stopped`&&Dm(this.upstreamRefusal)?q(`authority-changed`,!1):fs(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.`);if(this.closed)throw Error(`Cannot clear client storage: native runtime is ${this.phase}`);let e=this.db.deleteNativeStore();return this.advancePhase(`storageCleared`),e}uploadStatus(){return this===this.ownerRuntime?this.closed?as:this.db?.uploadStatus?.()??as: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=ss(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}get closed(){return this.phase!==`open`}advancePhase(e){if(wv[e]<=wv[this.phase])throw Error(`Native runtime cannot move from ${this.phase} back to ${e}`);this.phase=e}async close(){if(this!==this.ownerRuntime){if(this.phase===`closed`)return;this.advancePhase(`closed`),this.closeRuntimeState();return}if(!(this.phase===`closing`||this.phase===`closed`)){this.advancePhase(`closing`),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);try{this.closeRuntimeState(),await this.db.close?.()}finally{this.advancePhase(`closed`)}}}discard(){this.phase===`open`&&(this.advancePhase(`closed`),this.closeRuntimeState())}closeRuntimeState(){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){this.subscriptions.clear();return}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 e=this.serverConnectionAttempt;this.serverConnectionAttempt=null,e&&this.finishServerConnectionAttempt(e,Error(`runtime closed`)),this.serverCarrierPromise=null,this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.peerTransportWorkListeners.clear(),this.localSettlementListeners.clear(),this.pendingInboundServerFrames.length=0;let t=this.serverTransport;this.serverTransport=null,t&&this.retirePeerTransport(t).catch(Yb),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Wb(n):T(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Wb(r):void 0,a=Nv(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=Iv(n),l=Av(n);Mv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=db(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:kv(n)}}let f=Ty(`Insert`,()=>pv(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=Nv(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=Av(a),m=Iv(a);if(Mv(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?Wb(o):T(16),v=e===`insert`?fb(h,n,r,t):pb(h,n,r),y=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!y.finishInTransaction)throw await y.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let b=this.ownerRuntime,x,S=new Promise(e=>{x=e});b.pendingStreamingMutations.add(S);let C=new TextEncoder,w=async e=>{let t=64*1024;for(let n=0;n<e.byteLength;n+=t)await y.push(e.subarray(n,n+t))},E=``;try{for await(let e of wm(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 w(C.encode(t))}else if(e instanceof Uint8Array)E&&=(await w(C.encode(E)),``),await w(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await w(C.encode(E));let e=b.streamingFinalization,t,n=new Promise(e=>{t=e});b.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await y.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await y.finish())}finally{t()}return{id:qe(_),...r}}catch(e){throw await y.abort(),e}finally{x(),b.pendingStreamingMutations.delete(S)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Wb(t),a=Nv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Iv(r),l=Av(r);Mv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=db(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:kv(r)}}let f=Ty(`Restore`,()=>pv(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=Wb(t),a=Nv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Iv(r),l=Av(r);Mv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=mb(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:kv(r)};let f=Ty(`Update`,()=>pv(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=Wb(t),o=Iv(i),s=Av(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=Nv(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 Ey(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=mb(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:kv(i)}}if(jv(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=mb(this.table(e),n),d=Ty(`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=Wb(t),a=this.table(e),o=Nv(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=Iv(r),u=Av(r);Mv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=mb(a,n)}catch(e){throw Ey(`Upsert`,Dy(Oy(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:kv(r)};let p=Ty(`Upsert`,()=>pv(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=Wb(t),i=Nv(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=Iv(n),c=Av(n);Mv(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:kv(n)};let u=Ty(`Delete`,()=>pv(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`&&Fe(e,we(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return qv(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=qv(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=db(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,Wb(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=mb(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Wb(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,Wb(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}serveThinTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.serveThinTransaction(e);if(this.closed)return Promise.reject(Error(`the native runtime is closed`));if(!this.db.serveThinTransaction)return Promise.reject(Error(`this native binding serves no thin transactions`));let t=this.db.serveThinTransaction(e);return this.scheduleCoreTick(),this.awaitNativeRead(t)}async releaseThinTransactions(){if(this!==this.ownerRuntime)return this.ownerRuntime.releaseThinTransactions();if(this.closed||!this.db.releaseThinTransactions)return;let e=this.db.releaseThinTransactions();this.scheduleCoreTick(),await this.awaitNativeRead(e)}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 ve);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(vv.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=Nv(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(Rv(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=Ov(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 Sy(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(zv(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`);Gv(n,r),this.noteFirstLoadWait(r),Bv(r,this.pendingTxs,this.completedTxs);let i=qv(t);ty(e);let a=yy(e),o=Vv(r,this.pendingTxs),s=Uv(n,Qv(a),r),c=this.nativeReadContext(i,o),l=ey(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`),$v(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),Sb(yb(e),this.schema,py(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),Sb(yb(e),this.schema,py(a,this.schema).rootColumns)}let u=py(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),bb(vb(d),this.schema,u)}createSubscription(e,t,n,r){Gv(n,r),this.noteFirstLoadWait(r);let i=qv(t),a=this.nativeReadContext(i);ty(e);let o=this.nextSubscriptionId++,s=Uv(n,Qv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:py(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=ey(e,this.schema),u=e=>{let t=Rb(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 _v(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=W_(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(),e?.phase!==`live`&&this.authRestoredCallback?.();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(Oy(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=U_(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}:hv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new k_({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=>{s_(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(H_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw Ay(`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(Oy(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=y();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=W_(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=W_(e);if(!K_(t))return;let n;try{n=U_(t,this.peerIdentity)}catch{n=null}if(!n||!Kb(n,this.upstreamPrincipal))throw ky(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){this.upstreamPrincipal||!K_(e)||(this.upstreamPrincipal=U_(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)})}onAuthRestored(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onAuthRestored(e);this.authRestoredCallback=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}upstreamFailure(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamFailure();let e=this.serverTransportError;return e?{error:e,retrying:this.serverTransportErrorRetrying}:null}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(Nv(n.writeContext))??null,s):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=Ov(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=Ov(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 qc(e,qe(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(fv(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(!fv(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 xy(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Kb(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`||!te(t))throw Error(`backend attribution must be a canonical author subject string`);let n=Nv(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=Yv(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`||Yv(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=U_(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(Oy(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(Oy(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||!Ub(n,U_(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,Uv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Fe(e,we(e)))throw Error(`Device account native admission requires a verified account session`);if(!this.db.admitLocalFirstSession)throw Error(`Native runtime lacks device account session admission`);this.db.admitLocalFirstSession(t,n,new k().decode(Ve(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=kv(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Lv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Kb(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`);return}if(e.identity&&(!t||!Kb(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||!Kb(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=mv(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 xy(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){Yb(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Yb(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=Cv(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 Am(e)}if(this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=dv){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(()=>xy(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=Fb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Lb(r.reason));return}let i=Tb(r.delta,this.schema,r.reset===!0,t.outputColumns,r.coalesced===!0);i.terminalOperations=my(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()},cv))}}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=Ev(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=Om(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(Dv(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 qi(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(Oy(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Yb))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=Ev(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||!jm(e)))return;let r=Oy(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=gv(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 Ev(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function Dv(e){let t=Ev([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function Ov(e,t){let n=e.txId;return t.set(n,e),n}function kv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Av(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 jv(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=Nv(e);return n===null||!Kb(n.identity,t)}catch{return!0}}function Mv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function Nv(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`?te(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||!D(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!D(i))throw Error(`session is missing issuer`);let a={account_id:Kv(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`};Pv(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=Xv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:Ve(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Fe(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 Pv(e,t,n,r,i){if(We(e)&&!((n===`device-account`||n===`anonymous`||n===`external`)&&Fe({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Fv(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 Iv(e){return Fv(e)??null}function Lv(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 Rv(e,t){let n=Lv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function zv(e,t){let n=Lv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Bv(e,t,n){let r=Hv(e);if(!(!r||t.has(r)))throw Error(`Query setup failed: Write error: ${Lv(r,n)}`)}function Vv(e,t){let n=Hv(e);return n?t.get(n):void 0}function Hv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Uv(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 Wv(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 Gv(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 Kv(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 qv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!D(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!D(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Kv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};Pv(n.issuer,n.user_id,n.authMode,t[je],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Fe(n,t.__jazz_trusted_reserved_session);return{...n,claims:Xv(t.claims,n),identity:Ve(n),backendAuthority:r}}function Jv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yv(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(Yv).join(`,`)}]`:Jv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yv(e[t])}`).join(`,`)}}`:`null`}function Xv(e,t){return{...Jv(e)?e:{},iss:t.issuer,sub:t.user_id}}function Zv(e){e.close()}function Qv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function $v(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function ey(e,t){return Ry(e,t)}function ty(e){if(ny(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function ny(e){let t=JSON.parse(e);return sy(t.select_columns??t.select)||cy(t.conditions)||ry(t.relation_ir)||iy(t.relation_ir)||ly(t.array_subqueries)}function ry(e){return dy(e)}function iy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(iy);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=oy(e.expr??e.source);if(n&&Ds(n))return!0}}return Object.values(t).some(iy)}function ay(e){if(!e||typeof e!=`object`)return null;let t=e;return ab(t.left??t.column)}function oy(e){return!e||typeof e!=`object`?null:`Column`in e?ab(e.Column):ab(e)}function sy(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&Ds(fy(e))):!1}function cy(e){return Array.isArray(e)?e.some(dy):!1}function ly(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return sy(t.select_columns??t.select)||uy(t.filters)||ly(t.nested_arrays)}):!1}function uy(e){return Array.isArray(e)?e.some(dy):!1}function dy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(dy);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&Ds(fy(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`&&Ds(fy(r)))return!0}let n=ay(t.Cmp)??ay(t.In)??ay(t.IsNull)??ay(t.IsNotNull)??ay(t.Contains);return n&&Ds(fy(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&dy(t))}function fy(e){return vs(e)}function py(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:vy(n.table,t,Hy(n.select_columns??n.select),Wy(n.array_subqueries,n.table,t)??[])}}function my(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:hy(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Gs.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=_y(a.Insert.key);return{root_key:hy(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:hy(a.Insert.key),row:ch(t,r,gy(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=_y(a.Update.key);return{root_key:hy(e.root_key),path:i,edit:{Update:{key:hy(a.Update.key),row:ch(t,r,gy(a.Update.value))}}}}return`Remove`in a?{root_key:hy(e.root_key),path:i,edit:{Remove:{key:hy(a.Remove.key)}}}:{root_key:hy(e.root_key),path:i,edit:{Move:{key:hy(a.Move.key),index:a.Move.index}}}})}function hy(e){return Array.isArray(e)?e:Array.from(e)}function gy(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function _y(e){let t=gy(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return qe(t.subarray(1,17))}function vy(e,t,n,r,i=!0){let a=K(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=ks(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=vy(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 yy(e){let t=JSON.parse(e);return by(t.array_subqueries),JSON.stringify(t)}function by(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=vs(n);(Hy(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}by(e.nested_arrays)}}function xy(e){return new Promise(t=>setTimeout(t,e))}function Sy(e,t){return Fy(t)?Cy(e,t):Iy(t)?wy(e,t):null}function Cy(e,t){let n=Oy(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 wy(e,t){let n=Oy(t),r={kind:`rejected`,transactionId:e,code:My(Gc(t)),reason:Py(n,Gc(t)),message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function Ty(e,t){try{return t()}catch(t){if(Iy(t)){let n=Oy(t),r=Ly(n)??n,i=Gc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:My(i)})}throw t}}function Ey(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function Dy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function Oy(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 ky(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 Ay(e,t){let n=t instanceof Error?t:Error(Oy(t));return Error(`${e}: ${n.message}`,{cause:n})}var jy={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`,schema_version_unsupported:`write_rejected`};function My(e){return e===void 0?`write_rejected`:jy[e]}var Ny={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 Py(e,t){let n=Ly(e);return n===null?e:Ny[My(t)]??(n||`Write rejected`)}function Fy(e){return Uc(e)===`transaction_conflict`}function Iy(e){return Uc(e)===`write_rejected`}function Ly(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Ry(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=Im(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Yh(r,[],{relation:i.relation_ir,select:Hy(n.select_columns??n.select),partial:Vy(n.select_columns),arraySubqueries:Wy(n.array_subqueries,r,t)})}let i=eb(n.conditions);if(!i)throw Q();return Yh(r,i.map(e=>zy(r,e,t)),{limit:cb(n.limit),offset:lb(n.offset),orderBy:Uy(n.order_by??n.orderBy),select:Hy(n.select_columns??n.select),partial:Vy(n.select_columns),arraySubqueries:Wy(n.array_subqueries,r,t)})}function Q(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function zy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>zy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:zy(e,t.predicate,n)};if(Bo(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=>zy(e,{column:t.column,op:`Eq`,value:r},n))};if(By(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`}:K(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:Qy(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`}:K(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?Qy(t.value,r.element,!1):Zy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(By(t))return{...t,value:Zy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function By(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Vy(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 Q(`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 Q(`select_columns`);t.push({column:e.column,kind:e.kind,from:e.from,to:e.to})}}return t}function Hy(e){if(e==null)return;if(!Array.isArray(e))throw Q();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 Q();let e=n;if(e.kind!==`full`&&e.kind!==`bytes`&&e.kind!==`text_utf16`&&e.kind!==`text_utf8`&&e.kind!==`json_pointer`)throw Q();t.push(e.column)}return t}function Uy(e){if(e==null)return[];if(!Array.isArray(e))throw Q(`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 Q(`order_by`);return{column:e[0],direction:e[1]===`asc`?`Asc`:`Desc`}}if(!e||typeof e!=`object`)throw Q(`order_by`);let t=e;if(typeof t.column!=`string`||t.direction!==`Asc`&&t.direction!==`Desc`)throw Q(`order_by`);return{column:t.column,direction:t.direction}})}function Wy(e,t,n){if(e!=null){if(!Array.isArray(e))throw Q(`array_subqueries`);return e.map(e=>Gy(e,t,n))}}function Gy(e,t,n){if(!e||typeof e!=`object`)throw Q(`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 Q(`array_subqueries`);if(Array.isArray(r.joins)&&r.joins.length>0)throw Q(`array_subqueries.joins`);let i=Ky(r.filters,r.table,n),a=Hy(r.select_columns),o=Jy(r.order_by),s=Wy(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:Xy(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:sb(r.limit),offset:lb(r.offset),requirement:Yy(r.requirement),nestedArrays:s}}function Ky(e,t,n){if(e==null)return[];if(!Array.isArray(e))throw Q(`array_subqueries.filters`);let r=[];for(let i of e){let e=qy(i);if(!e)throw Q(`array_subqueries.filters`);r.push(...e.map(e=>zy(t,e,n)))}return r}function qy(e){let t=nb(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:rb(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:rb(t)}]:null}return null}function Jy(e){if(e==null)return[];if(!Array.isArray(e))throw Q(`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 Q(`array_subqueries.order_by`);return{column:e[0],direction:e[1]===`Ascending`?`Asc`:`Desc`}})}function Yy(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Q(`array_subqueries.requirement`)}function Xy(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`}:ks(t)??K(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($y))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:K(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=>Qy(e,a,!1))}}return Qy(n,i,!0)}function Qy(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:Qy(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&ub(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:Bm(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($y))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Qy(e,t.element,!1))}:e}function $y(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 eb(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=nb(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=vs(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:rb(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:rb(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:rb(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:rb(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:rb(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:rb(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:rb(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(rb)});break;default:return null}}return t}function tb(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=tb(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=nb(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=ab(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=ab(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=ab(e.left),n=ob(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=ab(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(ob);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=ib(s.op);if(!c)return null;let l=ab(s.left),u=ob(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function nb(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(nb);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=nb(t.Not);return e?{op:`Not`,predicate:e}:null}let n=tb(e);return n?.length===1?n[0]:null}function rb(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 ub(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(rb)};throw Q()}function ib(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 ab(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?vs(t):null}function ob(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<=ov&&sv.test(n.value))try{return{type:`BigInt`,value:Bm(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=>ob({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 sb(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function cb(e){return e==null?void 0:sb(e)}function lb(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 ub(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 db(e,t,n){return gb(e.columns,t,n),hb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function fb(e,t,n,r){return gb(e.columns.filter(e=>e.name!==n),t,r),hb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function pb(e,t,n){return hb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function mb(e,t){return hb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function hb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:Oh(e),column:e})),i=r.map(({column:e})=>_b(e,t(e),n)),a=new cg;return $m(a,r),a.bytes(rh(r,i)),a.finish()}function gb(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 _b(e,t,n){let r=t;if(!r){if(e.nullable)return Sh(Oh(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return bh(e,r)}function vb(e){return new lg(e).readVec(Um)}function yb(e){return Xm(new lg(e))}function bb(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=xb(a,t,n),o=ph(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=Ob(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(ah({table:a.table,id:qe(t.rowId),values:n},s))}}return i}function xb(e,t,n){let r=yv.get(t);r||(r=new Map,yv.set(t,r));let i=mg(e),a=n?void 0:r.get(i);if(a)return a;let o=n??K(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&&Hm(n);if(!r)continue;let i=ks(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!qb(r)&&(!Os(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function Sb(e,t,n,r=`full-record`){return wb(bb(e.rows,t,n,r),t).slice(0,e.rootCount)}var Cb=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function wb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((K(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of Cb){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:ah({...e,values:e.values.filter(e=>!i.has(e))},r)})}function Tb(e,t,n=!1,r=null,i=!1){let a=(e,n,i,a)=>{let o=Db(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:zb(e,t,r),...s&&s.length>0?{splices:Eb(s,t,e.table)}:{}}]})};return{added:a(e.added,e.addedOccurrenceKeys,e.addedIndices),updated:a(e.updated,e.updatedOccurrenceKeys,e.updatedIndices,e.updatedSplices),removed:e.removed.flatMap((t,n)=>r&&t.table!==r.rootTable?[]:[{sourceId:qe(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{},...n&&i?{reason:`backlog`}:{}}}function Eb(e,t,n){let r=K(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:vv.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 Db(e,t,n,r){return e.flatMap(e=>bb([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function Ob(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 kb(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 kb(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:Ab(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:vv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:qe(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:Pb(e.element,t,jb(r),i)};case`Row`:{let a={type:`Row`,value:Nb(e.columns,t,Mb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ie(a),a}}}function Ab(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function jb(e){let t=Ab(e);return t?.tag===14?t.inner:void 0}function Mb(e){let t=Ab(e);return t?.tag===16?t.record:void 0}function Nb(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=ph(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?qe(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=qe(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:kb(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 ah({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=qe(t.subarray(a,a+16)),a+=16}let s=Gb(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:ih(e,c)}}function Pb(e,t,n,r=`full-record`){let i=Rh(n??Ah(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(kb(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=Gb(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:Gb(t,4+(i-1)*4),l=i===a-1?t.length:Gb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(kb(e,t.subarray(c,l),void 0,n,r))}return s}function Fb(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,coalesced:t.coalesced===!0,delta:qm(new lg(Jb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:Ib(t.reason)};throw Error(`unknown subscription chunk`)}function Ib(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 Lb(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):Om({code:r,message:n})??Error(n)}function Rb(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 zb(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?kh(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=Hb(e,i).map((e,t)=>Bb(e,i[t].column_type));return ah({id:e.id,values:a},oh(i,a))}function Bb(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Bb(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:Vb(e.value,t.columns)}:e}function Vb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Bb(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return ah({id:e.id,values:r},oh(t,r))}function Hb(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 Ub(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function Wb(e){let t=Ee(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Gb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Kb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function qb(e){return e.startsWith(Gs)}function Jb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Yb(e){queueMicrotask(()=>{throw e})}var Xb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Xa(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 Zb(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 ex(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return $b(t)},`the app's bearer`)}var Qb=3e4;function $b(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`)),Qb)})]).finally(()=>clearTimeout(t))}function ex(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 tx=`warn`;function nx(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??tx}function rx(e){return ct({...e,trustedReservedSession:d(e)})}function ix(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=xe(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`device-account`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Je(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`);O(e,i)}function ax(e){let t=rx(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 ox(e){return!rx(e)&&!!e.adminSecret}function sx(e,t){if(!(!t||!e.jwtToken||t.issuer!==`urn:jazz:local-first`&&t.issuer!==`urn:jazz:anonymous`))return{token:e.jwtToken,appId:U(e),claimedAuthor:r(t.issuer,t.user_id,t.account_id)}}function cx(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function lx(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var ux=class extends Cm{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 gm(e.runtimeSources)}admitConfig(e){ix(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,onAuthRestored:i,foregroundNodeLease:a}){nx(e.logLevel);let o={onAuthFailure:r,onAuthRestored:i},s=sx(e,rx(e)),c=ox(e),l=a?.node.slice()??p(),u=Ve(ax(e)),f=cx(e),m=px(e),h=e.cookieSession&&e.accountId?es(e):void 0,g=this.nativeSchemaView(t,l,u,f,!m,s,c,{appId:U(e),thresholdMs:e.slowQueryThresholdMs,...dx()?{consoleDetail:`summary`}:{}},n,h&&e.serverUrl?Zb(e.serverUrl,h):void 0,e.subscriptionBacklogRows);if(a&&g.seedForegroundTxTimeHighWater(a.confirmedTxTime),m&&(g.setNonDurableClient(),!a))throw Error(`Persistent browser runtime requires a foreground node lease`);let _={appId:U(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 O(_,d(e)),ne.connectWithRuntime(this.wrapClientRuntime(g,e,t),_,o)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!px(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=pu(e);return await bo.acquire({runtimeSources:lx(e),dbName:t,storageOwner:Bi(e)})}async acquireForegroundNodeLease(t){if(!fx()||(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:U(t),env:t.env??`dev`,authScope:zi(t)})}createBrowserWorkerConnection({config:e,schema:t,client:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l,onNewerBuild:u}){let d=n.getRuntime();if(!(d instanceof Tv))throw Error(`Browser worker connections require the native runtime adapter`);let f=sx(e,rx(e));if(ox(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let p=pu(e),m=Ve(ax(e));return e.runtimeSources?.browserWorkerPort?new Xb(d,e.runtimeSources.browserWorkerPort,rx(e)?.claims??{},p,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l},e.runtimeSources.inspectorBinding):new xo(d,{runtimeSources:lx(e),schema:t,dbName:p,author:m,selfSignedClientProof:f,initialSyncFlushEvery:cx(e),migrations:d.migrations,appId:U(e),slowQueryThresholdMs:e.slowQueryThresholdMs,...e.subscriptionBacklogRows===void 0?{}:{subscriptionBacklogRows:e.subscriptionBacklogRows},storageOwner:Bi(e),authSessionKey:zi(e),serverUrl:e.serverUrl?Ae(e.serverUrl,U(e)):void 0,authJson:JSON.stringify(mx(e)),sessionClaims:rx(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Pi(e,p,Ye(t)),{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l,onNewerBuild:u})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof Tv))throw Error(`Browser follower connections require the native runtime adapter`);let l=rx(e)?.claims??{},u=new Xa(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(mx(e)),l),u}nativeSchemaView(e,t,n,r,i,a,o=!1,s,c,l,u){return!this.ownerRuntime||this.ownerRuntime.isClosed()?(this.ownerRuntime=new Tv(this.wasmModule.WasmDb,e,t,n,1,i,{initialSyncFlushEvery:r,selfSignedClientProof:a,backendMode:o,slowQueryLog:s,subscriptionBacklogRows:u,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 xm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function dx(){return typeof window<`u`&&typeof Worker<`u`}function fx(){return typeof process<`u`&&!!process.versions?.node}function px(e){return dx()&&(e.driver?.type??`persistent`)===`persistent`}function mx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function hx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},_u(e),j(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(j(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 at({db:e,get session(){return r},async shutdown(t){t?.waitForSync&&await e.shutdown(t),await Fl([()=>a?.(),()=>s(),...c?[c]:[],()=>i.shutdown(),()=>e.shutdown()])}},i)}function gx(e){return(e.driver??{type:`persistent`}).type===`persistent`?pu(e):null}function _x(e){if(typeof window>`u`)return()=>{};let t=gx(e.getConfig());if(!t)return()=>{};let n=window;Ro(n);let r=Eo(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function vx(e){return hx(e,U(e.getConfig()),_x)}async function yx(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(P(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 bx=class extends ux{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,bo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:Bi(e)})}};async function xx(e,t,n,r){let i=new MessageChannel,a=new bx(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}};ix(o);let s=Hi(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:zi(o),storageOwner:Bi(o)};return await yx(r,c,i.port2),o.runtimeSources.inspectorBinding=c,rs(o),await vx(await bd(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 Sx(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(),Cx=200,wx=15e3,Tx=1e3;function Ex(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 Dx(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)=>Dx(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]&&Dx(e[n],t[n])):!1}function Ox(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&&Dx(r.schema,e.schema)})}var kx=class extends L.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 Ax(){let[e,t]=(0,L.useState)(null),[n,r]=(0,L.useState)([]),[i,a]=(0,L.useState)(null),o=(0,L.useRef)(Promise.resolve()),[s,c]=(0,L.useState)(null),[l,u]=(0,L.useState)(!1),[d,f]=(0,L.useState)(null);return(0,L.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+wx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await Pe({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(Sx(s.contexts,Me()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await Ex(Math.min(Cx,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,L.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await Ex(Tx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>Ox(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:Sx(n,Me()))}catch{}}})(),()=>t.abort()},[e]),(0,L.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=Me(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){Ue(e);return}let n=await xx(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)(jx,{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 jx({client:e,wasmSchema:t}){return(0,$.jsx)(kx,{children:(0,$.jsx)(nt,{client:e,children:(0,$.jsx)(be,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(Ce,{initialEntries:[new URLSearchParams(window.location.search).get(`route`)??`/`],children:(0,$.jsx)(et,{})})})})})}(0,dt.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(L.StrictMode,{children:(0,$.jsx)(Ax,{})}));
|
|
4
|
+
`)}function Eu(e){return{...e,branches:[...e.branches]}}function Du(e,t){if(K(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function Ou(e,t,n){return Su(e,t,n)??{}}function ku(e,t,n,r){let i=K(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 Au(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 Y(e){if(Bo(e._table))throw Error(`History table "${e._table}" is read-only`)}function ju(e,t,n){return Mu(e,ed(t,n),t._schema,t._table)}function Mu(e,t,n,r){try{return ul(t,n,r)}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`${e} failed: WriteError("${Gu(n)}")`)}}function Nu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Pu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Fu(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 Iu(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Lu(e,t,n){let r=zu(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 Ru(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function zu(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}=Bu(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 Bu(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(!Nu(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=Pu(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=Fu(n.fromUtf8,`fromUtf8`,t),i=Fu(n.toUtf8,`toUtf8`,t);Iu(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Fu(n.from,`from`,t),r=Fu(n.to,`to`,t);Iu(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Fu(n.from,`from`,t),r=Fu(n.to,`to`,t);Iu(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=Pu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Fu(r?n.atUtf8:n.at,`at`,t),o=Fu(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=Pu(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 Vu(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 Hu(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 Uu(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=Hu(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 Wu(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]=Uu(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 k({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(!Vu(t,a)||!Vu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Gu(e){return e.replaceAll(`"`,`\\"`)}function Ku(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function qu(e,t,n,r){let i=Ku(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=Fc(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?Cs(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 Qc,(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?el(u,g,{...e},r,f):void 0,n=S?Wu(e,x):e;if(m&&Dc(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=Fc(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 Ju(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 Xc))throw e;s=e}if(!s)return o;if(!r.computedState||r.computedState.version===r.version)throw s;r=qu(e,t,n,r.computedState),i=await a(r.physical)}}var Yu=new WeakMap;function Xu(e,t){let n=Yu.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Zu(e,t){return Qu(e,t)}function Qu(e,t){if(!e._columnTransforms||typeof t!=`object`||!t)return t;let n=t,r=Yc(e._columnTransforms),i=r.length?el(e._columnTransforms,r,n):void 0;Dc(n,e._columnTransforms,[],i);for(let e of r)n[e]=i.get(e);return n}function $u(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 ed(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 td=1e4;function nd(e,t,n,r,i){let a=JSON.stringify({table:t._table,conditions:[{column:`id`,op:`eq`,value:n}],limit:1}),o=e.queryInternal(bc(a,t._schema),i?{tier:`remote`,branch:i}:{tier:`remote`},r),s,c=new Promise(e=>{s=setTimeout(()=>e([]),td)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function rd(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function id(e,t,n){return Zu(e,Ic(qc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function ad(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)&&od(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 od(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function sd(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(od(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 cd(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 ld(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function ud(e,t,n){let r;try{r=t(cd(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 ld(e,a,s,i())}var dd=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(Yu.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 Xu(this,e)}bindOwnerClient(e){let{writeSession:t,attribution:n}=this.context??{},r=new Lc(!0),i=zc(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};Yu.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 Be(i,t):new Re(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){Y(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}=ad(t,r);$u(t,p);let m=async()=>{let r=Mu(o,ed(t,p),t._schema,t._table),u=e===`insert`?sd(t,p):void 0,m=e===`insert`?xu(t._schema,t._table,{...i,...n?{id:n}:{},...u?{branch:u}:{}}):Su(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,r,d,f,s,m,c,l,n)};return Promise.resolve(u.run(()=>J(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){Y(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||zc(r)?.pending)&&(c=rd());let d,f=()=>{d=r.insertInternal(e._table,l,xu(e._schema,e._table,c?{...n,id:c}:n),a,o,i)};s.cancelled?f():s.run(()=>J(r,()=>{s.cancelled||f()}));try{return u??(d?Zu(e,Ic(d,e._schema,e._table)):id(e,c,l))}catch(e){throw s.failure=e,e}}restore(e,t,n,r){Y(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,xu(e._schema,e._table,r),c,l,s)};return u.cancelled?d():u.run(()=>J(o,()=>{u.cancelled||d()})),a}prepareCreation(e,t,n,r){let i;try{i=e._columnTransforms?ed(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=Mu(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:id(e,n,a)}}catch(e){throw this.requireBinding(r).preparation.failure=e,e}}upsert(e,t,n,r){Y(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,Su(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){Y(e),this.bindTable(e);let{replacements:i,descriptors:a}=Lu(e,n,r);r=Ru(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=Su(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($u(e,t),(a.pending||zc(i)?.pending)&&(t={...t}),a.cancelled){r({});return}a.run(()=>J(i,()=>{if(a.cancelled)return;let i;try{i=ed(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(Mu(n,i,e._schema,e._table))}))}delete(e,t,n){Y(e),this.bindTable(e);let r=this.resolveClient(e._schema),{openTransactionId:i,session:a,attribution:o,preparation:s}=this.requireBinding(`delete`),c=Su(e._schema,e._table,n),l=()=>{r.deleteInternal(e._table,t,c?.updatedAt,a,o,i,c?.branch)};s.cancelled?l():s.run(()=>J(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=Ws(JSON.parse(a)),s=Du(e._schema,o.table),c=xc(s,o),l=qu(e,o,c),u=Su(e._schema,o.table,mu(t))??{},d=await i.queryInternal(bc(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?Ju(e,o,c,l,d,e=>i.queryInternal(bc(a,s,e),{...u,openTransactionId:r},this.context?.readSession)):d.map(l.transform)}async one(e,t){return(await this.all(Cu(e),t))[0]??null}},fd=class e{config;runtimeSource;authStateStore;connection;_localFirstSecret=null;localFirstRefreshOwned=!1;localFirstRenewals=new xl;localFirstRefreshTimer=null;phase=`open`;gracefulDrain=null;teardown=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){ts(e),this.config=e,this.runtimeSource=t;let r={...e,trustedReservedSession:d(e)};l(this,ct(r)),this.authStateStore=me(r,n),this.connection=new jl(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=Mo(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}hu.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,mu(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,mu(n))})}dbForConnection(){let e=this;return{get config(){return e.config},get runtimeSource(){return e.runtimeSource},get phase(){return e.phase},get draining(){return e.gracefulDrain!==null},markUnauthenticated:e=>this.markUnauthenticated(e),renewsCredential:e=>(Td.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`),mu(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.stopping))try{let e=3600,t=this.mintLocalFirstToken(this._localFirstSecret,U(this.config),e),n=Je(xe(t)??{},`device-account`);if(!n)throw Error(`Minted device account token is missing its reserved session identity`);this.applyAuthUpdate(t,n),this.scheduleLocalFirstRefresh(e)}catch(e){console.error(`Failed to refresh device account 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){l(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=d(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};O(n,t);let r=ct(n);this.config.jwtToken=e,this.config.cookieSession=void 0,O(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=d(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=ct({...this.config,jwtToken:void 0,cookieSession:t});return this.config.jwtToken=void 0,this.config.cookieSession=t,O(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 eu(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 Cl(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){ts(this.config);let t=j(this);if(e.id!==this.config.accountId||Qo(e)!==this.config.accountRegistryAuthority||e.identity.issuer!==t?.issuer||e.identity.subject!==t?.user_id)throw Error(`Account context mismatch`);try{let t=await Zo(e,Qo(e),{fresh:!0});if(this.shutdownAbort.signal.aborted)throw Error(`Account context closed`);let n=e.identity.issuer===`urn:jazz:local-first`?Je(xe(t)??{},`device-account`):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()}getDeviceAccountProof(e){if(!this._localFirstSecret){let t=this.config.jwtToken,n=t?xe(t):null;return!t||n?.iss!==`urn:jazz:local-first`||typeof n.exp!=`number`||n.exp<=Date.now()/1e3+lu||e?.audience!==void 0&&n.aud!==Le(e.audience)?null:t}let t=e?.ttlSeconds??60,n=e?.audience??U(this.config);return this.mintLocalFirstToken(this._localFirstSecret,n,t)}getLocalFirstIdentityProof(e){return this.getDeviceAccountProof(e)}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=Dd(this.connection.syncStatus(),this.authStateStore.getState().error);return this.syncStatusSnapshot&&hs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||hs(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(),i=()=>{let t=this.getSyncStatus();t!==r&&(r=t,e(t))};this.connection.onSyncStatusChange(i,t.signal);let a=this.authStateStore.onChange(i);return t.signal.addEventListener(`abort`,a,{once:!0}),n}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;ue(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 ee(`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.stopping)throw Error(`Cannot disconnect a Db that is shutting down.`);this.offlineRequested=!0,await this.connection.disconnect()}async reconnect(){if(this.phase!==`open`)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})=>Eu(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){Y(e);let r=this.getClient(e._schema),i=n?.id,a=Mu(`Insert`,e._columnTransforms?ed(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!zc(r)?.pending;s&&!i&&(i=rd());let c=s?id(e,i,a):void 0,l=J(r,()=>r.insert(e._table,a,xu(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?Zu(e,Ic(t,e._schema,e._table)):c))}async insertStreaming(e,t,n){Y(e);let r=this.getClient(e._schema),{column:i,source:a,values:o}=ad(e,t);$u(e,o),Cl(this);let s=n?.id;return J(r,async()=>{let t=Mu(`Insert`,ed(e,o),e._schema,e._table),c=this.getAccessContext(),l=sd(e,o);return r.insertStreaming(e._table,t,i,a,xu(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){Y(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=ad(e,n);$u(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=Mu(`Update`,ed(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,Su(e._schema,e._table,r),c?.writeSession,c?.attribution)})}async upsertStreaming(e,t,n,r){Y(e);let i=this.getClient(e._schema),{column:a,source:o,values:s}=ad(e,n);$u(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=Mu(`Upsert`,ed(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,Su(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){Y(e);let i=this.getClient(e._schema),a=Mu(`Restore`,e._columnTransforms?ed(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=zc(i)?.pending?id(e,t,a):void 0,c=J(i,()=>i.restore(e._table,t,a,xu(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=>Zu(e,Ic(t,e._schema,e._table))))}upsert(e,t,n,r){return Y(e),this.prepareMutation(e,t,n,`Upsert`,r)}prepareMutation(e,t,n,r,i,a){let o=this.getClient(e._schema);$u(e,n),zc(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=Su(e._schema,e._table,i),l=J(o,()=>{let i=n=>{let i=Mu(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=ed(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Uc(n)!==`not_observed`)throw n;return nd(o,e,t,s?.readSession,c?.branch).then(()=>{try{return i(l)}catch(t){throw Uc(t)===`not_observed`?Kc(`Update`,e._table):t}})}});return this.wrapWriteWait(l instanceof Promise?new Re(l.then(e=>e.txId),o):l)}update(e,t,n,r){Y(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Lu(e,n,r);r=Ru(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,Su(e._schema,e._table,r),s?.writeSession,s?.attribution)):this.prepareMutation(e,t,n,`Update`,r)}delete(e,t,n){Y(e);let r=this.getClient(e._schema),i=this.getAccessContext(),a=J(r,()=>r.delete(e._table,t,Su(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Re(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=ju(`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=ju(`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(),Cl(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 dd.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 J(e,()=>e.captureSnapshot())}beginTransaction(){return this.createTransaction(`mergeable`)}beginSerializableTransaction(){return this.createTransaction(`serializable`)}transaction(e){let t=this.beginTransaction();return ud(t,e,()=>Xu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return ud(t,e,()=>Xu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await ou(this,e)}isLocalFirst(){return!au(this)}async deleteClientStorage(){await this.connection.deleteClientStorage()}async storePendingUploads(){return await this.connection.storePendingUploads().catch(()=>void 0)??this.getSyncStatus().pendingUploads}isUsable(){return!this.stopping&&!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,mu(t))}catch(n){if(this.successor&&Ed(n))return this.current().all(e,t);throw n}}async allInternal(e,t){let n=this.getClient(e._schema),r=zc(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=Ws(JSON.parse(o)),c=Du(e._schema,s.table),l=xc(c,s),u=qu(e,s,l),d=Ou(e._schema,s.table,t),f=bc(o,c,u.physical),p=wu(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?Ju(e,s,l,u,g,e=>n.queryInternal(bc(o,c,e),d,m?.readSession)):g.map(u.transform)}async one(e,t){return(await this.all(Cu(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===le.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t,...e.reset&&e.reason?{reason:e.reason}:{}})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,mu(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),s=this.connection.initialExplicitOfflineState(),c=new u,l=e._build(),d=Ws(JSON.parse(l)),f=Du(e._schema,d.table),p=xc(f,d),m=qu(e,d,p),h=bc(l,f,m.physical),g=s===null,_=[],v=Ou(e._schema,d.table,n);v.splices&&(ku(f,p,e,v.splices),Au(d,m.physical,v.splices));let y=this.getAccessContext()?.readSession??r,b=null,x=!1,S=!1,C=new AbortController,w=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},T=e=>{if(!a){console.error(`Unhandled Jazz subscription error`,e);return}try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},E=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||S||(e.terminalDelivered=!0,S=!0,g=!1,_.length=0,b===e&&(b=null),w(e),e.predecessor!==null&&(w(e.predecessor),e.predecessor=null),C.abort(),this.liveSubscriptionEnders.delete(se),this.unregisterActiveQuerySubscriptionTrace(re),c.clear(),T(t))},D=(e,t)=>{x||S||b!==e||e.terminalDelivered||(e.terminalError??=I(t),E(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return b=t,t},te=e=>{if(!(x||S||b===null)){if(!g){_.push(e);return}try{i(e)}catch(e){let t=b;t!==null&&D(t,e)}}},ne=t=>{if(!(x||S||b===null))try{te(c.handleDelta(t,m.transform))}catch(t){if(!(t instanceof Xc)||!m.computedState||m.computedState.version===m.version)throw t;m=qu(e,d,p,m.computedState),v.splices&&Au(d,m.physical,v.splices),h=bc(l,f,m.physical),w(b);let n=ee();c.clear(),_.length=0,this.unregisterActiveQuerySubscriptionTrace(re),re=this.registerActiveQuerySubscriptionTrace(h,d.table,v),queueMicrotask(()=>{this.stopping||O(n)})}},O=(e,t=v)=>{if(x||b!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(h,{onUpdate:t=>{if(!(x||b!==e||e.terminalError!==null)){if(e.installing){n.push(t);return}try{ne(t)}catch(t){D(e,t)}}},onError:t=>{D(e,t)}},t,y)}catch(t){return e.installing=!1,D(e,t),null}if(e.installing=!1,x||b!==e||e.retired)return w(e),null;if(e.terminalError!==null)return E(e),null;try{for(let t of n){if(b!==e||e.terminalError!==null)break;ne(t)}}catch(t){return D(e,t),null}return x||b!==e||e.retired?null:e},re=this.registerActiveQuerySubscriptionTrace(h,d.table,v),ie=()=>{x||(x=!0,this.liveSubscriptionEnders.delete(se),g=!1,_.length=0,C.abort(),this.unregisterActiveQuerySubscriptionTrace(re),b!==null&&(w(b),b.predecessor!==null&&(w(b.predecessor),b.predecessor=null)),b=null,c.clear())},ae=s?.then(()=>{if(!(x||S||b===null||this.stopping)){g=!0;for(let e of _.splice(0)){if(x||S||b===null)return;te(e)}}}).catch(e=>{if(!(x||S||b===null||this.stopping))throw D(b,e),e});ae&&ae.catch(()=>void 0);let oe=ee(),se=e=>{b!==null&&D(b,e)};this.liveSubscriptionEnders.add(se);let k=v.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(k)?this.ensureReady(k,C.signal).then(()=>O(oe)).catch(e=>{x||C.signal.aborted||this.stopping||D(oe,e)}):O(oe);let ce=ie;return ae&&Object.defineProperty(ce,`ready`,{value:ae}),ce}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new su(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&&hs(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 gu)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;ue(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 ee(`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.teardown)return this.teardown;if(this.gracefulDrain)return e.waitForSync?this.gracefulDrain.done:(this.gracefulDrain.teardownAnyway=!0,this.gracefulDrain.done.catch(()=>this.beginTeardown()));if(!e.waitForSync)return this.beginTeardown();let t,n=new Promise(e=>{t=e}),r=new AbortController,i,a=new Promise((e,t)=>{i=t}),o={done:n,cancel:()=>{r.abort(),i(Error(`Graceful shutdown cancelled`))},teardownAnyway:!1};return this.gracefulDrain=o,t((async()=>{try{await Promise.race([this.runtimeSource.waitForPendingWrites?.(r.signal)??this.connection.waitForPendingWrites({inFlightStreams:this.streamsMayFinish?.signal}),a])}catch(e){throw r.abort(),this.gracefulDrain===o&&(this.gracefulDrain=null),o.teardownAnyway&&this.beginTeardown().catch(()=>{}),new Wo(e)}let e=this.beginTeardown();return this.gracefulDrain===o&&(this.gracefulDrain=null),e})()),a.catch(()=>{}),n}abortGracefulShutdown(){this.gracefulDrain?.cancel()}get stopping(){return this.phase!==`open`||this.gracefulDrain!==null}assertOpen(){if(this.replaced)throw this.replaced;if(this.phase!==`open`)throw new Go(this.phase);if(this.gracefulDrain)throw new Go(`draining`)}shutdownListeners=new Set;onShutdown(e){return this.phase===`open`?this.shutdownListeners.add(e):e(),()=>this.shutdownListeners.delete(e)}beginTeardown(){if(this.teardown)return this.teardown;this.phase=`closing`;let e,t=new Promise(t=>{e=t});return this.teardown=t,e(this.runTeardown().finally(()=>{this.phase=`closed`})),t}async runTeardown(){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:Tu(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 pd(){let e=T(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function md(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function hd(e,t){if(!t.supportsBrowserWorker||!wd()||uu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),gd.set(n,_d(e)),n}var gd=new WeakMap;function _d(e){try{let t=e.runtimeSources;return JSON.stringify([pu(e),Bi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function vd(e,t){let n=gd.get(e);return n!==void 0&&n===_d(t)}async function yd(e){if(!(!e||xd.has(e))){xd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function bd(e,t,n){let r=n;try{return await Sd(e,t,()=>(r??=hd(e,t),r))}finally{yd(r)}}var xd=new WeakSet;async function Sd(e,t,n){if(ts(e),Cd(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?ut(e.secret):null,i={...e};O(i,d(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...l}=e,u=r;if(u){let n=u;if(!e.jwtToken){let r=t.mintLocalFirstToken(md(n,U(e),3600)),a=Je(xe(r)??{},`device-account`);i={...l,jwtToken:r},O(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=pd(),r=t.mintAnonymousToken(md(n,U(e),3600)),a=Je(xe(r)??{},`anonymous`);i={...l,jwtToken:r},O(i,a)}ns(e,i),t.admitConfig(i);let f=uu(i.driver),p=t.supportsBrowserWorker&&wd()&&f.type===`persistent`,m=a&&p&&vd(a,i)?a:void 0;m?xd.add(m):a&&await yd(a);let h=p?await fd.createWithBrowserWorker(i,t,m):await fd.createWithDirectConnection(i,t);return u&&h.initLocalFirstAuth(u,3600,!e.jwtToken),h}function Cd(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 wd(){return typeof window<`u`&&typeof Worker<`u`}var Td=new WeakMap;function Ed(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof cu)return!0;return!1}function Dd(e,t){let{link:n}=e;return n.state!==`offline`||n.reason!==`auth`||t===void 0?e:{...e,link:{...n,authReason:t}}}var Od={napi:`5c243927a8228e339a72613c233fb3e90732f8843cfc4cc35fe2d192bb0a2547`,wasm:`190c82211fdb6dd352084577811d1a7c2088d1ac0b391e9b6e98e2dea9123f64`},kd=`JAZZ_NATIVE_ARTIFACT_MISMATCH`,Ad=class extends Error{kind;expected;actual;missingExport;name=`NativeArtifactMismatchError`;code=kd;constructor(e,t,n,r,i){super(e),this.kind=t,this.expected=n,this.actual=r,this.missingExport=i}};function jd(e,t,n=[]){let r=Od[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw new Ad(`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.`,t,r,void 0);let i=e.nativeArtifactFingerprint();if(i!==r)throw new Ad(`Jazz ${t} artifact ABI mismatch: expected ${r}, got ${String(i)}. In this monorepo rebuild generated bindings; for installed packages reinstall matching Jazz package versions.`,t,r,String(i));for(let i of n)if(typeof e[i]!=`function`)throw new Ad(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${i}.`,t,r,r,i)}var Md=class extends Error{},Nd=class extends Error{},Pd=new Set(`\\.+*?()|[]{}^$#&-~`),Fd=new Set(`imsUuRx`),Id=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Ld(e){return Pd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Rd=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 Md&&this.fancy?new Nd(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 Md(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,Fd.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++,Ld(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||!Id.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`}}},zd={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]]},Bd=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,Vd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:Bd};function Hd(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function Ud(e){return e.map(([e,t])=>{let n=Hd(String.fromCodePoint(e));return e===t?n:`${n}-${Hd(String.fromCodePoint(t))}`}).join(``)}var Wd=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Hd(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 Nd(`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=`[${Bd}]`;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=Hd(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Hd(e.start)}-${Hd(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Gd(this.parsed.fancy?Vd[e.perl]:Ud(zd[e.perl]),e.negated);case`ascii`:return Gd(Ud(zd[e.ascii]),e.negated);case`unicode`:return Gd(Kd(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 Gd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Kd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new Nd(`the Unicode class \`${e}\``)}function qd(e){try{return new Rd(e).parse(),!0}catch(e){return e instanceof Nd}}var Jd=new Map,Yd=1024;function Xd(e){let t=Jd.get(e);if(t)return t;let n=new Rd(e).parse();if(n.fancyInvalid.length>0)throw new Md(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new Nd(n.unsupported[0]);let r=new Wd(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),Jd.size>=Yd&&Jd.clear(),Jd.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 Qd(e){return e%4==0&&e%100!=0||e%400==0}function $d(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<=(Qd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function ef(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 tf(e){let t=e.search(/[Tt]/);return t<0?!1:$d(e.slice(0,t))&&ef(e.slice(t+1))}var nf=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,rf=`${nf}(?:\\.${nf}){3}`,X=`[0-9A-Fa-f]{1,4}`,af=`(?:${X}:${X}|${rf})`,of=[`(?:${X}:){6}${af}`,`::(?:${X}:){5}${af}`,`(?:${X})?::(?:${X}:){4}${af}`,`(?:(?:${X}:){0,1}${X})?::(?:${X}:){3}${af}`,`(?:(?:${X}:){0,2}${X})?::(?:${X}:){2}${af}`,`(?:(?:${X}:){0,3}${X})?::${X}:${af}`,`(?:(?:${X}:){0,4}${X})?::${af}`,`(?:(?:${X}:){0,5}${X})?::${X}`,`(?:(?:${X}:){0,6}${X})?::`].map(e=>`(?:${e})`).join(`|`),sf=RegExp(`^${rf}$`),cf=RegExp(`^(?:${of})$`),lf=e=>sf.test(e),uf=e=>cf.test(e);function df(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=_f(e.slice(4));if(t===void 0||!xf(t))return!1}}return!0}var ff=36,pf=1,mf=26,hf=4294967295;function gf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>(ff-pf)*mf>>1;)r=Math.trunc(r/(ff-pf)),i+=ff;return i+Math.trunc((ff-pf+1)*r/(r+38))}function _f(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=ff;;e+=ff){if(c>=r.length)return;let n=vf(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>hf||s>hf))return;let i=e<=o?pf:e>=o+mf?mf:e-o;if(n<i)break;if(t*=ff-i,t>hf)return}let n=i.length+1;if(o=gf(s-e,n,e===0),a+=Math.trunc(s/n),a>hf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function vf(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 yf=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))),bf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function xf(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||!yf.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(bf.has(o))return!1}return!(n&&!r||i&&a)}var Sf=new TextEncoder;function Cf(e){return Sf.encode(e).length}function wf(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 Tf=/^[\p{Alphabetic}\p{N}]$/u,Ef=new Set("!#$%&'*+-/=?^_`{|}~");function Df(e){return Tf.test(e)||Ef.has(e)||wf(e)}function Of(e){return e.length>0&&[...e].every(Df)}function kf(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||wf(n)))return!1}return!0}function Af(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||wf(e)}function jf(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function Mf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=jf(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=jf(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||Cf(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!kf(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(Of))return!1;if(o.length===0||Cf(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(Af)?e.startsWith(`IPv6:`)?uf(e.slice(5)):lf(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!Tf.test(t[0])||!Tf.test(t[t.length-1])||Cf(e)>63||!Of(e))return!1}return df(o)}var Nf=`A-Za-z0-9\\-._~`,Pf=`!$&'()*+,;=`,Ff=`%[0-9A-Fa-f]{2}`,If=`(?:[${Nf}${Pf}:@]|${Ff})`,Lf=`${If}*`,Rf=`${If}+`,zf=`(?:[${Nf}${Pf}@]|${Ff})+`,Bf=`\\[(?:${of}|[vV][0-9A-Fa-f]+\\.[${Nf}${Pf}:]+)\\]`,Vf=`(?:[${Nf}${Pf}]|${Ff})*`,Hf=`(?:${`(?:[${Nf}${Pf}:]|${Ff})*`}@)?(?:${Bf}|${Vf})(?::[0-9]*)?`,Uf=`(?:/${Lf})*`,Wf=`/(?:${Rf}(?:/${Lf})*)?`,Gf=`${Rf}(?:/${Lf})*`,Kf=`${zf}(?:/${Lf})*`,qf=`(?:${If}|[/?])*`,Jf=`[A-Za-z][A-Za-z0-9+\\-.]*`,Yf=`(?://${Hf}${Uf}|${Wf}|${Gf}|)`,Xf=`(?://${Hf}${Uf}|${Wf}|${Kf}|)`,Zf=`(?:\\?${qf})?(?:#${qf})?`,Qf=RegExp(`^${Jf}:${Yf}${Zf}$`),$f=RegExp(`^(?:${Jf}:${Yf}|${Xf})${Zf}$`);function ep(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function tp(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&ep(n)}var np=new Set(`+#./;?&=,!@|`),rp=new Set(`"'<>%\\^\`{|}`);function ip(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||np.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||rp.has(r))return!1;t++}}return!0}var ap={date:$d,"date-time":tf,email:Mf,hostname:df,ipv4:lf,ipv6:uf,"json-pointer":ep,regex:qd,"relative-json-pointer":tp,time:ef,uri:e=>Qf.test(e),"uri-reference":e=>$f.test(e),"uri-template":ip},op=class{value;constructor(e){this.value=e}},sp=2n**64n-1n,cp=-(2n**63n),lp=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,up=/[ \t\n\r]*/y;function dp(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{up.lastIndex=t,up.test(e),t=up.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=()=>{lp.lastIndex=t;let r=lp.exec(e);if(!r)return n();t=lp.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new op(a):a;if(Object.is(a,-0))return new op(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<cp||o>sp?new op(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 fp(e){return typeof e==`number`||typeof e==`bigint`||e instanceof op}function pp(e){return e instanceof op?e.value:e}function mp(e,t){return typeof e==`bigint`?!0:e instanceof op?!t:Number.isInteger(e)}function hp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof op){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):gp(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?gp(e):Array.isArray(e)?`[${e.map(hp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${hp(t)}`).join(`,`)}}`:JSON.stringify(e)}function gp(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function _p(e){if(e instanceof op)return e.value;if(Array.isArray(e))return e.map(_p);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=_p(r);return t}function vp(e,t){if(fp(e))return fp(t)?pp(e)==pp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>vp(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||fp(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length?n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&vp(e[n],t[n])):!1}return e===t}function yp(e,t){let n=Number(pp(e)),r=Number(pp(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]=bp(n),[o,s]=bp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function bp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*xp(10,t),!Number.isFinite(n))return Sp(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(xp(10,t))]}function xp(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 Sp(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 Cp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},wp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Tp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ep=new URL(`json-schema:///`);function Dp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function Op(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kp(e,t=Object.create(null),n=[],r=Ep,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(!Op(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(wp[i]&&Array.isArray(a))for(let e of a)kp(e,t,n,r,!1);else if(Cp[i])kp(a,t,n,r,!1);else if((Tp[i]||i===`dependencies`)&&Op(a))for(let e in a)kp(a[e],t,n,r,!1)}return t}function Ap(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(Op(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||Op(i)?i:void 0}}function jp(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 Mp(e){if(e===null)return`null`;if(fp(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 Np(e,t,n,r,i){return Z(e,t,{draft:n,lookup:r,shortCircuit:i},null,`#`,`#`)}function Z(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=Mp(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:ee,unevaluatedProperties:te,minProperties:ne,maxProperties:O,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:oe,prefixItems:se,items:k,additionalItems:ce,unevaluatedItems:A,contains:le,minContains:j,maxContains:ue,minItems:de,maxItems:fe,uniqueItems:pe,minimum:me,maximum:M,exclusiveMinimum:he,exclusiveMaximum:N,multipleOf:ge,minLength:_e,maxLength:ve,pattern:ye,__absolute_ref__:be,__absolute_recursive_ref__:xe}=t,P=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?Ap(c,xe):r,l=`${a}/$recursiveRef`,u=Z(e,r===null?t:r,n,s,i,l,o);u.valid||P.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=Ap(c,be??d);if(t===void 0)throw Error(`Unresolved $ref "${d}".`);let l=`${a}/$ref`,u=Z(e,t,n,r,i,l,o);if(u.valid||P.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:P.length===0,errors:P}}let Se=u===`number`&&mp(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&Se)||P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?Se||P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&P.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!vp(e,h)&&P.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${hp(h)}.`}),g!==void 0&&!g.some(t=>vp(e,t))&&P.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${hp(g)}.`}),v!==void 0){let t=`${a}/not`;Z(e,v,n,r,i,t).valid&&P.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Ce=[];if(y!==void 0){let t=`${a}/anyOf`,s=P.length,c=!1;for(let a=0;a<y.length;a++){let s=Object.create(o),l=Z(e,y[a],n,p===!0?r:null,i,`${t}/${a}`,s);P.push(...l.errors),c||=l.valid,l.valid&&Ce.push(s)}c?P.length=s:P.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=P.length,c=!0;for(let a=0;a<b.length;a++){let s=Object.create(o),l=Z(e,b[a],n,p===!0?r:null,i,`${t}/${a}`,s);P.push(...l.errors),c&&=l.valid,l.valid&&Ce.push(s)}c?P.length=s:P.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=P.length,c=x.filter((a,s)=>{let c=Object.create(o),l=Z(e,a,n,p===!0?r:null,i,`${t}/${s}`,c);return P.push(...l.errors),l.valid&&Ce.push(c),l.valid}).length;c===1?P.length=s:P.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,...Ce),S!==void 0){let t=`${a}/if`,s=Object.create(o);if(Z(e,S,n,r,i,t,s).valid){if(Object.assign(o,s),C!==void 0){let s=Z(e,C,n,r,i,`${a}/then`,o);s.valid||P.push({instanceLocation:i,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...s.errors)}}else if(w!==void 0){let s=Z(e,w,n,r,i,`${a}/else`,o);s.valid||P.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||P.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(ne!==void 0&&s.length<ne&&P.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ne} properties.`}),O!==void 0&&s.length>O&&P.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${O} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${Dp(a)}`,o=Z(a,re,n,r,t,e);o.valid||P.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||P.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=Z(e,ae[s],n,r,i,`${c}/${Dp(s)}`,o);t.valid||P.push({instanceLocation:i,keyword:`dependentSchemas`,keywordLocation:c,error:`Instance has "${s}" but does not match dependant schema.`},...t.errors)}}if(oe!==void 0){let o=`${a}/dependencies`;for(let a in oe)if(a in t){let s=oe[a];if(Array.isArray(s))for(let e of s)e in t||P.push({instanceLocation:i,keyword:`dependencies`,keywordLocation:o,error:`Instance has "${a}" but does not have "${e}".`});else{let t=Z(e,s,n,r,i,`${o}/${Dp(a)}`);t.valid||P.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}/${Dp(a)}`,d=Z(t[a],E[a],n,r,s,`${e}/${Dp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,P.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=Xd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${Dp(f)}`,m=Z(t[f],d,n,r,p,`${e}/${Dp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,P.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&ee!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${Dp(a)}`,d=Z(t[a],ee,n,r,s,e);d.valid?o[a]=!0:(u=l,P.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&te!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${Dp(a)}`,c=Z(t[a],te,n,r,s,e);c.valid?o[a]=!0:P.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;fe!==void 0&&s>fe&&P.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${fe}).`}),de!==void 0&&s<de&&P.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${de}).`});let c=0,u=!1;if(se!==void 0){let e=`${a}/prefixItems`,d=Math.min(se.length,s);for(;c<d;c++){let a=Z(t[c],se[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,P.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(k!==void 0){let e=`${a}/items`;if(Array.isArray(k)){let a=Math.min(k.length,s);for(;c<a;c++){let a=Z(t[c],k[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,P.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}else for(;c<s;c++){let a=Z(t[c],k,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,P.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=Z(t[c],ce,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,P.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(le!==void 0)if(s===0&&j===void 0)P.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(j!==void 0&&s<j)P.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${j}).`});else{let e=`${a}/contains`,c=P.length,l=0;for(let a=0;a<s;a++){let s=Z(t[a],le,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):P.push(...s.errors)}l>=(j||0)&&(P.length=c),j===void 0&&ue===void 0&&l===0?P.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):j!==void 0&&l<j?P.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${j} items matching schema. Only ${l} items were found.`}):ue!==void 0&&l>ue&&P.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${ue} items matching schema. ${l} items were found.`})}if(!u&&A!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=Z(t[c],A,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||P.push({instanceLocation:i,keyword:`unevaluatedItems`,keywordLocation:e,error:`Items did not match unevaluated items schema.`},...a.errors)}}if(pe){outer:for(let e=0;e<s;e++)for(let n=e+1;n<s;n++)if(vp(t[e],t[n])){P.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=pp(e);s===`4`?(me!==void 0&&(he===!0&&t<=me||t<me)&&P.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${he?`or equal to `:``}${me}.`}),M!==void 0&&(N===!0&&t>=M||t>M)&&P.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${N?`or equal to `:``}${M}.`})):(me!==void 0&&t<me&&P.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${me}.`}),M!==void 0&&t>M&&P.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${M}.`}),he!==void 0&&t<=he&&P.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${he}.`}),N!==void 0&&t>=N&&P.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${N}.`})),ge!==void 0&&!yp(e,ge)&&P.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ge}.`})}else if(u===`string`){let t=e,n=_e===void 0&&ve===void 0?0:jp(t);_e!==void 0&&n<_e&&P.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${_e}).`}),ve!==void 0&&n>ve&&P.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${ve}).`}),ye!==void 0&&!Xd(ye).test(t)&&P.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:ap[T];r&&!r(t)&&P.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:P.length===0,errors:P}}var Pp={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`}}}]},Fp={"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`},Ip=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(`.`)),Lp={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`]},Rp={...Lp,single:[...Lp.single,`contains`,`propertyNames`],plain:[...Lp.plain.filter(e=>e!==`id`),`$id`,`const`]},zp={...Rp,single:[...Rp.single,`if`,`then`,`else`]},Bp={single:[...zp.single,`unevaluatedItems`,`unevaluatedProperties`],array:zp.array,map:[...zp.map,`$defs`,`dependentSchemas`],plain:[...zp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},Vp={single:Bp.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Bp.map,plain:Bp.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)},Hp={4:Lp,6:Rp,7:zp,"2019-09":Bp,"2020-12":Vp},Up={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Wp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Gp=[...Wp,`json-pointer`,`uri-reference`,`uri-template`],Kp={4:Wp,6:Gp,7:[...Gp,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},qp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Jp={base64:Yp(`A-Za-z0-9+/`),base64url:Yp(`A-Za-z0-9\\-_`),base32:Xp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:Xp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Yp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function Xp(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 Qp(e){if(!A(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Fp[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new Zp(`unknown JSON Schema dialect "${t}"`);return n}function $p(e,t,n=[]){if(typeof e==`boolean`)return e;if(!A(e))return{};let r=Hp[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(Up[t].includes(s)&&!n.includes(s))throw new Zp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(Ip.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&tm(c),s===`patternProperties`&&A(c))for(let e of Object.keys(c))tm(e);if(s===`format`&&typeof c==`string`){if(!Kp[t]?.includes(c))continue;if(qp.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=>$p(e,t,n))]):r.single.includes(s)?o.push([s,$p(c,t,n)]):r.map.includes(s)&&A(c)?o.push([s,em(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Jp[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 em(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:$p(r,t,n)]))}function tm(e){try{Xd(e)}catch(t){throw t instanceof Md?new Zp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof Nd?new Zp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function nm(e){for(let t of e.references)if(Ap(e.lookup,t)===void 0)throw new Zp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function rm(e){if(Array.isArray(e))return e.map(rm);if(!A(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,rm(r)]);return Object.fromEntries(t)}var im={4:Pp.draft4,6:Pp.draft6,7:Pp.draft7,"2019-09":Pp.draft201909,"2020-12":Pp.draft202012};function am(e){return im[e].map(t=>e===`2020-12`?rm($p(t,e,[`$dynamicAnchor`,`$dynamicRef`])):$p(t,e))}var om=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=kp(e,void 0,this.references);for(let e of r)kp(e,this.lookup)}validate(e){return Np(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},sm=new Map;function cm(e){let t=sm.get(e);if(!t){let[n,...r]=am(e);t=new om(n,e,!1,r),sm.set(e,t)}return t}function lm(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 um(e){let t=Qp(e);if(typeof e==`boolean`){if(t===`4`)throw new Zp(`boolean schemas need draft 6 or later`)}else{let n=cm(t).validate(e);if(!n.valid)throw new Zp(lm(n.errors))}let n=new om($p(_p(e),t),t,!0,am(t));return nm(n),e=>{let t=n.validate(dp(e));return t.valid?void 0:lm(t.errors)}}function dm(e){return um(dp(e))}function fm(e){e.setJsonSchemaValidator(dm)}async function pm(){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 mm=Promise.resolve(),hm;function gm(e){let t=mm.then(()=>_m(e));return mm=t.then(()=>void 0,()=>void 0),t}async function _m(t){let n=await e(()=>import(`./jazz_wasm-BOTo6QbW.js`),[],import.meta.url),r=Qr(t);if(r)return n.initSync(r),vm(n);let i=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await pm();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 ym(n,e);else if(typeof location<`u`&&Ki())throw Error(Wi);else await n.default()}return vm(n)}function vm(e){return jd(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),fm(e),e}async function ym(e,t){if(hm===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(bm(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}),hm=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}),hm=t}function bm(e){return typeof WebAssembly.compileStreaming==`function`?e?.trim()===`application/wasm`:!1}function xm(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 Sm(e,t,n,r){return Rr(`${a}${e}`,{audience:t,ttlSeconds:n,now:r})}var Cm=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 Sm(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*wm(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 Tm=`authority_changed`,Em=class extends Error{name=`AuthorityChangedError`;code=Tm;constructor(e,t){super(e,t)}};function Dm(e){return!e||typeof e!=`object`?!1:e.code===Tm}function Om(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(Dm(e))return new Em(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 km=`core_tick_failed`,Am=class extends Error{name=`CoreTickFailedError`;code=km;constructor(e){super(`core tick failed: ${Mm(e)}`,{cause:e})}};function jm(e){return!e||typeof e!=`object`?!1:e.code===km}function Mm(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 Nm=class extends _s{},Pm=class{text;constructor(e){this.text=e}};function Fm(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 Im(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Fm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Fm(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 Pm(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 Lm(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`),Fm(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 Pm&&(/^(?: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 Pm){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`,`StartsWith`,`EndsWith`],`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 if(`IsNull`in e)d(1),v(e.IsNull.column);else if(`IsNotNull`in e)d(2),v(e.IsNotNull.column);else if(`In`in e)d(3),v(e.In.left),c(e.In.values.length),e.In.values.forEach(e=>u(()=>C(e)));else if(`Contains`in e)d(4),v(e.Contains.left),u(()=>C(e.Contains.right));else if(`StartsWith`in e||`EndsWith`in e){let t=`StartsWith`in e?e.StartsWith:e.EndsWith;d(`StartsWith`in e?11:12),v(t.left),u(()=>C(t.right))}else `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)}Ne({issuer:Oe,user_id:`system`,claims:{},authMode:`external`});var Rm=-(1n<<63n),zm=(1n<<63n)-1n;function Bm(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<Rm||n>zm)throw Error(`${t} must be a signed 64-bit integer`);return n}var Vm=new k({fatal:!0});function Hm(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function Um(e){return{table:e.string(),descriptor:Gm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Wm(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),th(e,r.valueType)},t.length)}function Gm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:nh(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:nh(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:nh(e)}:Km(t)})}function Km(e){throw Error(`unknown native row descriptor field kind ${e}`)}function qm(e){let t={added:e.readVec(Um),updated:e.readVec(Um),removed:e.readVec(Qm),addedOccurrenceKeys:e.readVec(e=>Jm(e)),updatedOccurrenceKeys:e.readVec(e=>Jm(e)),removedOccurrenceKeys:e.readVec(e=>Jm(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 Jm(e){let t=e.bytes();if(t[0]!==2||!Ym(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Ym(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||!s(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 Xm(e){let t=e.u64(),n=e.readVec(Um);return Zm(e,`relation snapshot`),{rootCount:t,rows:n}}function Zm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Qm(e){return{table:e.string(),rowId:e.bytes()}}function $m(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),th(e,t[n].valueType)},t.length)}function eh(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:nh(e)}))}function th(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)=>th(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}`);th(e,t.inner);return}if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);$m(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),$m(e,n.payload)},r.length)}}function nh(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:nh(e)};if(t===13){let n=e.readVec(nh);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:eh(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:eh(e)}))}}:{tag:t}}function rh(e,t){let n=zh(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=ot(r),o=new Uh,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 ot([a,o.finish(),...i])}function ih(e,t){let n=ph(yh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:jh(e.column_type,i)})}function ah(e,t){return Object.defineProperty(e,`valuesByColumn`,{value:t,enumerable:!1,configurable:!0}),e}function oh(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 sh={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function ch(e,t,n){let r=lh([sh,...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 ah({id:e,values:a},oh(t,a))}function lh(e,t){let n=ph(yh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:uh(e.column_type,i,e.name)})}function uh(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:Ih(t,n)};case`Array`:return{type:`Array`,value:dh(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:ch(Lh(t.subarray(0,16)),e.columns,t)};default:return jh(e,t)}}function dh(e,t){return Fh(e,t,t=>uh(e,t))}function fh(e,t){return rh(yh(e),e.map((e,n)=>bh(e,t[n])))}function ph(e){let t=zh(e);return(n,r)=>mh(e,t,n,r)}function mh(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 hh(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:Bh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Bh(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 ${gh(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return hh(n.subarray(c,l),a)}function hh(e,t){if(t.tag!==15)return e;let n=vh(e);return n==null?null:t.inner?hh(n,t.inner):n}function gh(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?gh(e.inner):`?`}>`:_h(e.tag)}function _h(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 vh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function yh(e){return e.map(e=>({name:e.name,valueType:Oh(e)}))}function bh(e,t){let n=Ah(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return Sh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return Sh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=Sh(r);return e.sparse?xh(t,r):t}let i=Ch(e.column_type,t);return e.nullable&&(i=xh(i,n)),e.sparse?xh(i,r):i}function xh(e,t){if(Rh(t)==null)return ot([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function Sh(e){let t=Rh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function Ch(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=Vh(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=Hh(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 ot([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return Dh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return ot([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return Th(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return wh(e.columns,t.value)}}function wh(e,t){let n=fh(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?Dh(t.id):new Uint8Array;return ot([Uint8Array.of(t.id?1:0),r,Eh(n.byteLength),n])}function Th(e,t){let n=t.map(t=>Ch(e,t));if(Rh(Ah(e))!=null)return ot(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)}),ot([Eh(t.length),r,...n])}function Eh(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function Dh(e){let t=Ee(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function Oh(e){let t=Ah(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function kh(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[...kh(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[...kh(e.column_type.element.columns)]}}:e.column_type}))}function Ah(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:Ah(e.element)};case`Row`:return{tag:9}}}function jh(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:Vm.decode(Mh(t))};case`Uuid`:return{type:`Uuid`,value:Lh(t)};case`Bytea`:return{type:`Bytea`,value:Mh(t).slice()};case`Array`:return{type:`Array`,value:Ph(e.element,t)};case`Row`:return{type:`Row`,value:Nh(e.columns,t)}}}function Mh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function Nh(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Lh(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=ih(e,o);return ah({id:i,values:s},oh(e,s))}function Ph(e,t){return Fh(e,t,t=>jh(e,t))}function Fh(e,t,n){let r=Rh(Ah(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=Bh(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:Bh(t,4+(e-1)*4),s=e===i-1?t.length:Bh(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 Ih(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Lh(e){if(e.length>=16)return $e(e,0);let t=Se(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Rh(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=Rh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Rh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function zh(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Rh(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(Rh(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 Bh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Vh(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 Hh(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Bm(e.value,`BigInt value`)}var Uh=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)}},Wh=new k({fatal:!0}),Gh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Kh(e,t){return t?Gh:e}function qh(e,t,n,r=!1,i,a,o,s){let c=new cg;return c.bytes(e),c.string(Jh(Kh(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(ug(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Jh(e){try{let t=Wh.decode(e);if(te(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Yh(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&&Qh(`query limit`,r),Qh(`query offset`,i);let u=new cg;return u.string(e),u.vec((e,n)=>{let r=t[n];eg(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(Lm(c),!1)),Xh(u,l),u.finish()}function Xh(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}Qh(`partial selection ${r.column} start`,r.from),Qh(`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&&Qh(`array subquery ${t.columnName} limit`,a),Qh(`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)=>{eg(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($h(s)),e.vec((e,t)=>{Zh(e,c[t])},c.length),Xh(e,[])}function Qh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function $h(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function eg(e,t){if(t.op===`All`||t.op===`Any`){e.u64(t.op===`All`?0:1),e.vec((e,n)=>eg(e,t.predicates[n]),t.predicates.length);return}if(t.op===`Not`){e.u64(2),eg(e,t.predicate);return}if(t.op===`In`){e.u64(5),rg(e,t.column),e.vec((e,n)=>{e.u64(3),og(e,t.values[n])},t.values.length);return}if(t.op===`Contains`){e.u64(10),rg(e,t.column),ig(e,t.value);return}if(t.op===`StartsWith`||t.op===`EndsWith`){e.u64(t.op===`StartsWith`?13:14),rg(e,t.column),ig(e,t.value);return}if(t.op===`IsNull`||t.op===`IsNotNull`){t.op===`IsNotNull`&&e.u64(2),e.u64(12),rg(e,t.column);return}if(tg(t)){ng(e,t.column,t.op,t.value);return}throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function tg(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function ng(e,t,n,r){e.u64(ag(n)),rg(e,t),ig(e,r)}function rg(e,t){e.u64(0),e.string(t)}function ig(e,t){e.u64(3),og(e,t)}function ag(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 og(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=>og(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=Ee(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)=>og(e,t.value[n]),t.value.length);return}e.u64(6),e.string(t.value)}var sg=64,cg=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=Bm(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(dg(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<sg){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)}},lg=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 Wh.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 ug(e){return dg(JSON.stringify(e,b))}function dg(e){return new TextEncoder().encode(e)}var fg=new TextEncoder;function pg(e){return fg.encode(he(e))}function mg(e){let t=new cg;return t.string(e.table),Wm(t,[...e.descriptor]),Se(t.finish())}var hg=3600*1e3,gg=500,_g=`jazz-http-stream-endpoints`,vg=`endpoints`;function yg(){return globalThis.indexedDB!==void 0}function bg(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(_g,1);r.onupgradeneeded=()=>r.result.createObjectStore(vg),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function xg(e,t){let n=bg();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(vg,e).objectStore(vg));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var Sg=`jazz-stream-endpoint:`,Cg=600*1e3;function wg(){if(!(typeof document>`u`))try{return globalThis.localStorage??void 0}catch{return}}function Tg(e,t=Date.now()){let n=wg();if(n)try{let r=n.getItem(Sg+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(Sg+e);return}return i===`stream`}catch{return}}function Eg(e,t,n){let r=wg();if(r)try{r.setItem(Sg+e,`${t}:${n}`)}catch{try{r.removeItem(Sg+e)}catch{}}}async function Dg(e,t=Date.now()){let n,r=await Promise.race([xg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),gg)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?Eg(e,`stream`,r.until):Eg(e,`none`,t+Cg),i}function Og(e,t=Date.now()){return Eg(e,`stream`,t+hg),xg(`readwrite`,n=>n.put(t+hg,e)).then(()=>void 0,()=>void 0)}function kg(e){return Eg(e,`none`,Date.now()+Cg),xg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var Ag=`x-jazz-stream-key`;function jg(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 Mg(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 Ng=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?Mg([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}},Pg=new TextEncoder,Fg=new TextDecoder;function Ig(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 Lg=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)}},Rg=4*1024*1024,zg=(e,t)=>fetch(e,t),Bg=class extends Lg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=zg){super(),this.request=t,this.streamUrl=Ig(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?Pg.encode(e):e;this.queued.push(jg(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:{[Ag]:e.key},signal:AbortSignal.timeout?.(Ug)}).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 Ng;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(Fg.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(Fg.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<=Rg);)t+=this.queued[e].byteLength,e+=1;let n=Mg(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`,[Ag]:this.session.key},body:n,signal:this.abort.signal});if(!r.ok)throw Error(`HTTP stream send refused (${r.status})`)}}catch(e){if(this.readyState>=2)return;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,this.queued.length=0,n&&this.abort.abort(),this.emit(`close`,{code:e,reason:t}))}},Vg=new Set,Hg=new Map,Ug=1e4,Wg=new Map,Gg=`x-jazz-stream`,Kg=new Set,qg=`x-jazz-store-error`,Jg=new Set;async function Yg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(Ug)});if(n.status===503&&n.headers.get(qg)===`1`){let t=await n.text().catch(()=>``);return t&&!Jg.has(`${e}\n${t}`)&&(Jg.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(Gg)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function Xg(e,t,n){let r=await Yg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return Hg.delete(e),Wg.delete(e),r===`refused`&&!Kg.has(e)&&(Kg.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=(Hg.get(e)??0)+1;Hg.set(e,i);let a=t?(Wg.get(e)??0)+1:0;t?Wg.set(e,a):Wg.delete(e);let o=a>=2;return i<3&&!o?r:(Hg.delete(e),Wg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${Ug/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??zg,r=t.describeFailedUpgrade;return class extends Lg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,Vg.has(e)){this.openStream();return}if(!yg()){this.inner=this.openNative();return}let t=Tg(e);if(t===!0){Vg.add(e),this.openStream();return}if(t===!1){this.inner=this.openNative();return}Dg(e).then(t=>{this.closedEarly||(t?(Vg.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 Bg(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(Vg.delete(this.url),kg(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,Xg(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){Vg.add(this.url),e===`stream`&&Og(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()},Ug),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,Hg.delete(this.url),Wg.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 Qg=`jazz_renewal`,$g=`X-Jazz-Renew`,e_=2048;function t_(e){let t=new lg(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>e_)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function n_(e){let t=new cg;return t.u64(65),t.string(e),t.finish()}function r_(e){return e[0]===64}function i_(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 a_(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var o_=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function s_(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function c_(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}function l_(e){return e.code===`protocol_error`?!0:(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)&&!c_(e)}var u_=12e4,d_=1e3,f_=7,p_=12688,m_=1<<20,h_=5,g_=5,__=2*1024*1024,v_=4096;function y_(e){x_(e);let t=new cg;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>__)throw Error(`websocket frame batch exceeds maximum length of ${__} bytes`);return n}function b_(e){if(e.byteLength>__)throw Error(`websocket frame batch exceeds maximum length of ${__} bytes`);let t=new lg(e),n=t.u64();if(n===0||n>v_)throw Error(`websocket frame batch exceeds frame-count limit of ${v_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(__,`websocket frame`));return P_(t,`websocket frame batch`),r}function x_(e){if(e.length===0||e.length>v_)throw Error(`websocket frame batch exceeds frame-count limit of ${v_}`);for(let t of e)if(t.byteLength>__)throw Error(`websocket frame exceeds maximum length of ${__} bytes`)}function S_(e=p_){j_(e,`client wire features`);let t=new cg;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var C_=0,w_=1;function T_(e){if(e[0]!==C_)return!1;let t=new lg(e);t.u64();let{min:n,max:r}=M_(t);return n===6&&r===6&&N_(t),!0}function E_(e){return e[0]===w_?(D_(e),!0):!1}function D_(e){let t=new lg(e),n=t.u64();if(n!==w_)throw Error(`expected WireFrame::Error, got tag ${n}`);let r={code:$_(t.u64()),retry:tv(t.u64()),message:t.string()};return t.done()||(r.reason=ev(t.u64())),P_(t,`WireFrame::Error`),r}function O_(e){return e.code===`auth_failed`?e.reason===`reauthenticate`?`invalid`:S(e.reason!==void 0&&!e.reason.startsWith(`unknown:`)?e.reason:e.message):null}var k_=class{url;socket;onFrame;onError;onTerminal;localFeatures;opened;resolveNegotiation;rejectNegotiation;negotiated=!1;helloSent=!1;ahead=[];closing=!1;terminated=!1;lastInbound=performance.now();handlingMessages=0;afterMessages=[];silenceTimer;handshakeTimer;renewalUrl;renewalTimer;constructor(e){this.url=e.endpointUrl;let t=e.WebSocket??Ze(this.url)??X_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??12688)|18432,this.renewalUrl=L_(e.authJson)?i_(this.url):null,j_(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}),nv(this.socket).then(()=>{if(!this.closing){this.socket.send(I_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(y_([S_(this.localFeatures)])),this.helloSent=!0;for(let e of this.ahead.splice(0))this.write(e)}},e=>{this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:String(e)}),this.close()});let n=e=>{this.handlingMessages===0?e():this.afterMessages.push(e)};this.socket.addEventListener(`message`,e=>{this.lastInbound=performance.now(),this.handlingMessages+=1,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()}).finally(()=>{if(--this.handlingMessages,!(this.handlingMessages>0))for(let e of this.afterMessages.splice(0))e()})}),this.socket.addEventListener(`error`,e=>n(()=>this.reportTerminal({code:`websocket_error`,retry:`later`,message:e instanceof Error?e.message:`websocket transport error`}))),this.socket.addEventListener(`close`,e=>{let t=F_(e);n(()=>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(),this.write(e)}sendAhead(e){this.closing||this.terminated||(this.helloSent?this.write(e):this.ahead.push(e))}write(e){let t=[],n=g_;for(let r of e){let e=r.byteLength+h_;t.length>0&&(t.length>=v_||n+e>m_)&&(this.socket.send(y_(t)),t=[],n=g_),t.push(r),n+=e}t.length>0&&this.socket.send(y_(t))}ready(){return this.opened}get hasNegotiated(){return this.negotiated}close(){if(!this.closing){this.closing=!0,this.ahead=[],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())},d_)},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)&&z_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send(n_(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),d_);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(),u_-t)}async handleMessage(e){for(let t of b_(await Y_(e))){if(this.closing)return;if(T_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=A_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&-18433});continue}if(!(this.negotiated&&t.byteLength===1&&t[0]===f_)){if(this.negotiated&&this.renewalUrl&&r_(t)){this.scheduleRenewal(t_(t));continue}if(!this.negotiated){if(E_(t)){let e=D_(t);if(O_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new o_(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(E_(t)){let e=D_(t);if(s_(e)){this.reportTerminal(e),this.close();return}this.onError?.(e);continue}this.onFrame(t)}}}};function A_(e,t=p_){let n=new lg(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=M_(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}=N_(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 j_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function M_(e){return{min:e.u64(),max:e.u64()}}function N_(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 P_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function P_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function F_(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 I_(e,t,n,r=!1){let i=JSON.parse(e),a=new k().decode(t),o=rv(i)??J_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Qg]:1}:{}})}function L_(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 R_=3e4;async function z_(e,t){return B_(a_(e),()=>V_(e,t))}async function B_(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,R_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function V_(e,t){try{let n=await Ge(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[$g]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function H_(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=xe(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 rt(t)}return rt(n)}function U_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!G_(n))return new TextEncoder().encode(r(`urn:jazz:system`,`system`));let i=q_(n),a=null;try{a=te(new k({fatal:!0}).decode(t))}catch{}if(a?.account_id&&i){let e=te(i);if(e.issuer!==a.issuer||e.user_id!==a.user_id||e.account_id!==void 0&&e.account_id!==a.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return i?new TextEncoder().encode(i):t}function W_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!G_(t)&&delete t.jwt_token,JSON.stringify(t)}function G_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&D(t.issuer)&&D(t.user_id)}function K_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||q_(t)!==null}function q_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&G_(e)){let t=e.backend_session;return r(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=xe(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,i=t?.sub;if(typeof n==`string`&&typeof i==`string`&&D(n)&&D(i))return r(n,i)}return null}function J_(e){return te(e)?.user_id??null}async function Y_(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 X_(e){let t=Q_();return Z_(e)?Zg(t):t}function Z_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function Q_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function $_(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:return`unknown:${e}`}}function ev(e){switch(e){case 0:return`expired`;case 1:return`missing`;case 2:return`invalid`;case 3:return`disabled`;case 4:return`revoked`;case 5:return`reauthenticate`;default:return`unknown:${e}`}}function tv(e){switch(e){case 0:return`never`;case 1:return`after_auth`;case 2:return`after_resume`;case 3:return`later`;default:return`unknown:${e}`}}function nv(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 rv(e){let t=e.sub;if(typeof t==`string`&&D(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=iv(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&D(e))return e}return null}function iv(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(av(t[1]));return typeof e.sub==`string`&&D(e.sub)?e.sub:null}catch{return null}}function av(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 ov=20,sv=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,cv=16,lv={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},uv=250,dv=4;function fv(e){return typeof e?.poll==`function`}function pv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function mv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function hv(e,t){return c_(e)?{kind:`network`,message:e.message}:l_(e)?{kind:`fatal`,message:e.message}:{kind:`wire`,...e,admitted:t}}function gv(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function _v(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var vv=new k({fatal:!0}),yv=new WeakMap;function bv(e,t,n,r,i,a=!1){try{return xv(e,t,n,r,i,a)}catch(e){throw Qe(e)}}function xv(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 Sv(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 Cv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var wv={open:0,quiesced:1,storageCleared:1,closing:2,closed:3},Tv=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;authRestoredCallback=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 Nm(()=>this.readRemoteLinkState());linkStatusPublisher=new _s(()=>this.upstreamLinkStatus(),ps);syncStatusPublisher=new _s(()=>this.readSyncStatus(),(e,t)=>gs(e.uploads,t.uploads)&&ps(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;phase=`open`;foregroundLeaseCapture=null;foregroundLeaseDraining=!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,subscriptionBacklogRows:s?.subscriptionBacklogRows})}migrations;registerSchemaView(t,n){return new e(null,t,this.node,this.peerIdentity,1,!0,{db:this.db.registerSchema(pg(t),n?ug(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=pg(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=qh(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=ge(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=bv(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=Sv(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)}let c=o?.subscriptionBacklogRows;if(c!==void 0&&(is(c,`subscriptionBacklogRows`),this.db.setSubscriptionBacklogRows?.(c)),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?Om({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:y(),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 ${this.phase}`);this.advancePhase(`quiesced`),this.clearCoreDeadline(),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(!Kb(n,this.peerIdentity))throw ky();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?.(lv[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()},uv))}noteFirstLoadWait(e){if(!Wv(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 q(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?q(`disconnected`):e.authRejected?q(`auth`):e.connected?ds:this.serverTransportError?this.serverTransportErrorRetrying?q(`network`):Dm(this.serverTransportError)?q(`authority-changed`,!1):q(`stopped`):us:ls:this.linkStatus?.phase===`stopped`&&Dm(this.upstreamRefusal)?q(`authority-changed`,!1):fs(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.`);if(this.closed)throw Error(`Cannot clear client storage: native runtime is ${this.phase}`);let e=this.db.deleteNativeStore();return this.advancePhase(`storageCleared`),e}uploadStatus(){return this===this.ownerRuntime?this.closed?as:this.db?.uploadStatus?.()??as: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=ss(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}get closed(){return this.phase!==`open`}advancePhase(e){if(wv[e]<=wv[this.phase])throw Error(`Native runtime cannot move from ${this.phase} back to ${e}`);this.phase=e}async close(){if(this!==this.ownerRuntime){if(this.phase===`closed`)return;this.advancePhase(`closed`),this.closeRuntimeState();return}if(!(this.phase===`closing`||this.phase===`closed`)){this.advancePhase(`closing`),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);try{this.closeRuntimeState(),await this.db.close?.()}finally{this.advancePhase(`closed`)}}}discard(){this.phase===`open`&&(this.advancePhase(`closed`),this.closeRuntimeState())}closeRuntimeState(){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){this.subscriptions.clear();return}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 e=this.serverConnectionAttempt;this.serverConnectionAttempt=null,e&&this.finishServerConnectionAttempt(e,Error(`runtime closed`)),this.serverCarrierPromise=null,this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.peerTransportWorkListeners.clear(),this.localSettlementListeners.clear(),this.pendingInboundServerFrames.length=0;let t=this.serverTransport;this.serverTransport=null,t&&this.retirePeerTransport(t).catch(Yb),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Wb(n):T(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Wb(r):void 0,a=Nv(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=Iv(n),l=Av(n);Mv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=db(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:kv(n)}}let f=Ty(`Insert`,()=>pv(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=Nv(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=Av(a),m=Iv(a);if(Mv(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?Wb(o):T(16),v=e===`insert`?fb(h,n,r,t):pb(h,n,r),y=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!y.finishInTransaction)throw await y.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let b=this.ownerRuntime,x,S=new Promise(e=>{x=e});b.pendingStreamingMutations.add(S);let C=new TextEncoder,w=async e=>{let t=64*1024;for(let n=0;n<e.byteLength;n+=t)await y.push(e.subarray(n,n+t))},E=``;try{for await(let e of wm(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 w(C.encode(t))}else if(e instanceof Uint8Array)E&&=(await w(C.encode(E)),``),await w(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await w(C.encode(E));let e=b.streamingFinalization,t,n=new Promise(e=>{t=e});b.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await y.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await y.finish())}finally{t()}return{id:qe(_),...r}}catch(e){throw await y.abort(),e}finally{x(),b.pendingStreamingMutations.delete(S)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Wb(t),a=Nv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Iv(r),l=Av(r);Mv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=db(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:kv(r)}}let f=Ty(`Restore`,()=>pv(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=Wb(t),a=Nv(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Iv(r),l=Av(r);Mv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=mb(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:kv(r)};let f=Ty(`Update`,()=>pv(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=Wb(t),o=Iv(i),s=Av(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=Nv(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 Ey(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=mb(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:kv(i)}}if(jv(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=mb(this.table(e),n),d=Ty(`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=Wb(t),a=this.table(e),o=Nv(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=Iv(r),u=Av(r);Mv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=mb(a,n)}catch(e){throw Ey(`Upsert`,Dy(Oy(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:kv(r)};let p=Ty(`Upsert`,()=>pv(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=Wb(t),i=Nv(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=Iv(n),c=Av(n);Mv(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:kv(n)};let u=Ty(`Delete`,()=>pv(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`&&Fe(e,we(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return qv(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=qv(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=db(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,Wb(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=mb(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Wb(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,Wb(t),r?.identity,r?.claims)):Promise.resolve(`unknown`)}serveThinTransaction(e){if(this!==this.ownerRuntime)return this.ownerRuntime.serveThinTransaction(e);if(this.closed)return Promise.reject(Error(`the native runtime is closed`));if(!this.db.serveThinTransaction)return Promise.reject(Error(`this native binding serves no thin transactions`));let t=this.db.serveThinTransaction(e);return this.scheduleCoreTick(),this.awaitNativeRead(t)}async releaseThinTransactions(){if(this!==this.ownerRuntime)return this.ownerRuntime.releaseThinTransactions();if(this.closed||!this.db.releaseThinTransactions)return;let e=this.db.releaseThinTransactions();this.scheduleCoreTick(),await this.awaitNativeRead(e)}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 ve);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(vv.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=Nv(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(Rv(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=Ov(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 Sy(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(zv(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`);Gv(n,r),this.noteFirstLoadWait(r),Bv(r,this.pendingTxs,this.completedTxs);let i=qv(t);ty(e);let a=yy(e),o=Vv(r,this.pendingTxs),s=Uv(n,Qv(a),r),c=this.nativeReadContext(i,o),l=ey(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`),$v(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),Sb(yb(e),this.schema,py(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),Sb(yb(e),this.schema,py(a,this.schema).rootColumns)}let u=py(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),bb(vb(d),this.schema,u)}createSubscription(e,t,n,r){Gv(n,r),this.noteFirstLoadWait(r);let i=qv(t),a=this.nativeReadContext(i);ty(e);let o=this.nextSubscriptionId++,s=Uv(n,Qv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:py(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=ey(e,this.schema),u=e=>{let t=Rb(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 _v(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=W_(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(),e?.phase!==`live`&&this.authRestoredCallback?.();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(Oy(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=U_(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}:hv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new k_({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=>{s_(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(H_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw Ay(`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(Oy(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=y();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=W_(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=W_(e);if(!K_(t))return;let n;try{n=U_(t,this.peerIdentity)}catch{n=null}if(!n||!Kb(n,this.upstreamPrincipal))throw ky(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){this.upstreamPrincipal||!K_(e)||(this.upstreamPrincipal=U_(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)})}onAuthRestored(e){if(this!==this.ownerRuntime)return this.ownerRuntime.onAuthRestored(e);this.authRestoredCallback=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}upstreamFailure(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamFailure();let e=this.serverTransportError;return e?{error:e,retrying:this.serverTransportErrorRetrying}:null}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(Nv(n.writeContext))??null,s):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=Ov(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=Ov(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 qc(e,qe(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(fv(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(!fv(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 xy(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Kb(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`||!te(t))throw Error(`backend attribution must be a canonical author subject string`);let n=Nv(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=Yv(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`||Yv(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=U_(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(Oy(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(Oy(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||!Ub(n,U_(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,Uv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Fe(e,we(e)))throw Error(`Device account native admission requires a verified account session`);if(!this.db.admitLocalFirstSession)throw Error(`Native runtime lacks device account session admission`);this.db.admitLocalFirstSession(t,n,new k().decode(Ve(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=kv(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Lv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Kb(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`);return}if(e.identity&&(!t||!Kb(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||!Kb(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=mv(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 xy(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){Yb(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Yb(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=Cv(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 Am(e)}if(this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=dv){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(()=>xy(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=Fb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Lb(r.reason));return}let i=Tb(r.delta,this.schema,r.reset===!0,t.outputColumns,r.coalesced===!0);i.terminalOperations=my(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()},cv))}}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=Ev(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=Om(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(Dv(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 qi(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(Oy(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Yb))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=Ev(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||!jm(e)))return;let r=Oy(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=gv(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 Ev(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function Dv(e){let t=Ev([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function Ov(e,t){let n=e.txId;return t.set(n,e),n}function kv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Av(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 jv(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=Nv(e);return n===null||!Kb(n.identity,t)}catch{return!0}}function Mv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function Nv(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`?te(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||!D(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!D(i))throw Error(`session is missing issuer`);let a={account_id:Kv(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`};Pv(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=Xv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:Ve(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Fe(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 Pv(e,t,n,r,i){if(We(e)&&!((n===`device-account`||n===`anonymous`||n===`external`)&&Fe({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Fv(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 Iv(e){return Fv(e)??null}function Lv(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 Rv(e,t){let n=Lv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function zv(e,t){let n=Lv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Bv(e,t,n){let r=Hv(e);if(!(!r||t.has(r)))throw Error(`Query setup failed: Write error: ${Lv(r,n)}`)}function Vv(e,t){let n=Hv(e);return n?t.get(n):void 0}function Hv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Uv(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 Wv(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 Gv(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 Kv(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 qv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!D(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!D(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Kv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};Pv(n.issuer,n.user_id,n.authMode,t[je],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Fe(n,t.__jazz_trusted_reserved_session);return{...n,claims:Xv(t.claims,n),identity:Ve(n),backendAuthority:r}}function Jv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yv(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(Yv).join(`,`)}]`:Jv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yv(e[t])}`).join(`,`)}}`:`null`}function Xv(e,t){return{...Jv(e)?e:{},iss:t.issuer,sub:t.user_id}}function Zv(e){e.close()}function Qv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function $v(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function ey(e,t){return Ry(e,t)}function ty(e){if(ny(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function ny(e){let t=JSON.parse(e);return sy(t.select_columns??t.select)||cy(t.conditions)||ry(t.relation_ir)||iy(t.relation_ir)||ly(t.array_subqueries)}function ry(e){return dy(e)}function iy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(iy);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=oy(e.expr??e.source);if(n&&Ds(n))return!0}}return Object.values(t).some(iy)}function ay(e){if(!e||typeof e!=`object`)return null;let t=e;return ab(t.left??t.column)}function oy(e){return!e||typeof e!=`object`?null:`Column`in e?ab(e.Column):ab(e)}function sy(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&Ds(fy(e))):!1}function cy(e){return Array.isArray(e)?e.some(dy):!1}function ly(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return sy(t.select_columns??t.select)||uy(t.filters)||ly(t.nested_arrays)}):!1}function uy(e){return Array.isArray(e)?e.some(dy):!1}function dy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(dy);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&Ds(fy(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`&&Ds(fy(r)))return!0}let n=ay(t.Cmp)??ay(t.In)??ay(t.IsNull)??ay(t.IsNotNull)??ay(t.Contains);return n&&Ds(fy(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&dy(t))}function fy(e){return vs(e)}function py(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:vy(n.table,t,Hy(n.select_columns??n.select),Wy(n.array_subqueries,n.table,t)??[])}}function my(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:hy(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Gs.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=_y(a.Insert.key);return{root_key:hy(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:hy(a.Insert.key),row:ch(t,r,gy(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=_y(a.Update.key);return{root_key:hy(e.root_key),path:i,edit:{Update:{key:hy(a.Update.key),row:ch(t,r,gy(a.Update.value))}}}}return`Remove`in a?{root_key:hy(e.root_key),path:i,edit:{Remove:{key:hy(a.Remove.key)}}}:{root_key:hy(e.root_key),path:i,edit:{Move:{key:hy(a.Move.key),index:a.Move.index}}}})}function hy(e){return Array.isArray(e)?e:Array.from(e)}function gy(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function _y(e){let t=gy(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return qe(t.subarray(1,17))}function vy(e,t,n,r,i=!0){let a=K(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=ks(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=vy(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 yy(e){let t=JSON.parse(e);return by(t.array_subqueries),JSON.stringify(t)}function by(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=vs(n);(Hy(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}by(e.nested_arrays)}}function xy(e){return new Promise(t=>setTimeout(t,e))}function Sy(e,t){return Fy(t)?Cy(e,t):Iy(t)?wy(e,t):null}function Cy(e,t){let n=Oy(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 wy(e,t){let n=Oy(t),r={kind:`rejected`,transactionId:e,code:My(Gc(t)),reason:Py(n,Gc(t)),message:n};return Object.defineProperty(r,`message`,{enumerable:!1}),r}function Ty(e,t){try{return t()}catch(t){if(Iy(t)){let n=Oy(t),r=Ly(n)??n,i=Gc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:My(i)})}throw t}}function Ey(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function Dy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function Oy(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 ky(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 Ay(e,t){let n=t instanceof Error?t:Error(Oy(t));return Error(`${e}: ${n.message}`,{cause:n})}var jy={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`,schema_version_unsupported:`write_rejected`};function My(e){return e===void 0?`write_rejected`:jy[e]}var Ny={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 Py(e,t){let n=Ly(e);return n===null?e:Ny[My(t)]??(n||`Write rejected`)}function Fy(e){return Uc(e)===`transaction_conflict`}function Iy(e){return Uc(e)===`write_rejected`}function Ly(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Ry(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=Im(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Yh(r,[],{relation:i.relation_ir,select:Hy(n.select_columns??n.select),partial:Vy(n.select_columns),arraySubqueries:Wy(n.array_subqueries,r,t)})}let i=eb(n.conditions);if(!i)throw Q();return Yh(r,i.map(e=>zy(r,e,t)),{limit:cb(n.limit),offset:lb(n.offset),orderBy:Uy(n.order_by??n.orderBy),select:Hy(n.select_columns??n.select),partial:Vy(n.select_columns),arraySubqueries:Wy(n.array_subqueries,r,t)})}function Q(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function zy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>zy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:zy(e,t.predicate,n)};if(Bo(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=>zy(e,{column:t.column,op:`Eq`,value:r},n))};if(By(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`}:K(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:Qy(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`}:K(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?Qy(t.value,r.element,!1):Zy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(By(t))return{...t,value:Zy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function By(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Vy(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 Q(`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 Q(`select_columns`);t.push({column:e.column,kind:e.kind,from:e.from,to:e.to})}}return t}function Hy(e){if(e==null)return;if(!Array.isArray(e))throw Q();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 Q();let e=n;if(e.kind!==`full`&&e.kind!==`bytes`&&e.kind!==`text_utf16`&&e.kind!==`text_utf8`&&e.kind!==`json_pointer`)throw Q();t.push(e.column)}return t}function Uy(e){if(e==null)return[];if(!Array.isArray(e))throw Q(`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 Q(`order_by`);return{column:e[0],direction:e[1]===`asc`?`Asc`:`Desc`}}if(!e||typeof e!=`object`)throw Q(`order_by`);let t=e;if(typeof t.column!=`string`||t.direction!==`Asc`&&t.direction!==`Desc`)throw Q(`order_by`);return{column:t.column,direction:t.direction}})}function Wy(e,t,n){if(e!=null){if(!Array.isArray(e))throw Q(`array_subqueries`);return e.map(e=>Gy(e,t,n))}}function Gy(e,t,n){if(!e||typeof e!=`object`)throw Q(`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 Q(`array_subqueries`);if(Array.isArray(r.joins)&&r.joins.length>0)throw Q(`array_subqueries.joins`);let i=Ky(r.filters,r.table,n),a=Hy(r.select_columns),o=Jy(r.order_by),s=Wy(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:Xy(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:sb(r.limit),offset:lb(r.offset),requirement:Yy(r.requirement),nestedArrays:s}}function Ky(e,t,n){if(e==null)return[];if(!Array.isArray(e))throw Q(`array_subqueries.filters`);let r=[];for(let i of e){let e=qy(i);if(!e)throw Q(`array_subqueries.filters`);r.push(...e.map(e=>zy(t,e,n)))}return r}function qy(e){let t=nb(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:rb(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:rb(t)}]:null}return null}function Jy(e){if(e==null)return[];if(!Array.isArray(e))throw Q(`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 Q(`array_subqueries.order_by`);return{column:e[0],direction:e[1]===`Ascending`?`Asc`:`Desc`}})}function Yy(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Q(`array_subqueries.requirement`)}function Xy(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`}:ks(t)??K(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($y))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:K(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=>Qy(e,a,!1))}}return Qy(n,i,!0)}function Qy(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:Qy(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&ub(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:Bm(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($y))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Qy(e,t.element,!1))}:e}function $y(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 eb(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=nb(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=vs(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:rb(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:rb(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:rb(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:rb(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:rb(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:rb(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:rb(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(rb)});break;default:return null}}return t}function tb(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=tb(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=nb(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=ab(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=ab(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=ab(e.left),n=ob(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=ab(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(ob);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=ib(s.op);if(!c)return null;let l=ab(s.left),u=ob(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function nb(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(nb);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=nb(t.Not);return e?{op:`Not`,predicate:e}:null}let n=tb(e);return n?.length===1?n[0]:null}function rb(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 ub(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(rb)};throw Q()}function ib(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 ab(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?vs(t):null}function ob(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<=ov&&sv.test(n.value))try{return{type:`BigInt`,value:Bm(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=>ob({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 sb(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function cb(e){return e==null?void 0:sb(e)}function lb(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 ub(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 db(e,t,n){return gb(e.columns,t,n),hb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function fb(e,t,n,r){return gb(e.columns.filter(e=>e.name!==n),t,r),hb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function pb(e,t,n){return hb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function mb(e,t){return hb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function hb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:Oh(e),column:e})),i=r.map(({column:e})=>_b(e,t(e),n)),a=new cg;return $m(a,r),a.bytes(rh(r,i)),a.finish()}function gb(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 _b(e,t,n){let r=t;if(!r){if(e.nullable)return Sh(Oh(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return bh(e,r)}function vb(e){return new lg(e).readVec(Um)}function yb(e){return Xm(new lg(e))}function bb(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=xb(a,t,n),o=ph(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=Ob(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(ah({table:a.table,id:qe(t.rowId),values:n},s))}}return i}function xb(e,t,n){let r=yv.get(t);r||(r=new Map,yv.set(t,r));let i=mg(e),a=n?void 0:r.get(i);if(a)return a;let o=n??K(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&&Hm(n);if(!r)continue;let i=ks(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!qb(r)&&(!Os(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function Sb(e,t,n,r=`full-record`){return wb(bb(e.rows,t,n,r),t).slice(0,e.rootCount)}var Cb=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function wb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((K(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of Cb){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:ah({...e,values:e.values.filter(e=>!i.has(e))},r)})}function Tb(e,t,n=!1,r=null,i=!1){let a=(e,n,i,a)=>{let o=Db(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:zb(e,t,r),...s&&s.length>0?{splices:Eb(s,t,e.table)}:{}}]})};return{added:a(e.added,e.addedOccurrenceKeys,e.addedIndices),updated:a(e.updated,e.updatedOccurrenceKeys,e.updatedIndices,e.updatedSplices),removed:e.removed.flatMap((t,n)=>r&&t.table!==r.rootTable?[]:[{sourceId:qe(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{},...n&&i?{reason:`backlog`}:{}}}function Eb(e,t,n){let r=K(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:vv.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 Db(e,t,n,r){return e.flatMap(e=>bb([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function Ob(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 kb(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 kb(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:Ab(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:vv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:qe(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:Pb(e.element,t,jb(r),i)};case`Row`:{let a={type:`Row`,value:Nb(e.columns,t,Mb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ie(a),a}}}function Ab(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function jb(e){let t=Ab(e);return t?.tag===14?t.inner:void 0}function Mb(e){let t=Ab(e);return t?.tag===16?t.record:void 0}function Nb(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=ph(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?qe(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=qe(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:kb(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 ah({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=qe(t.subarray(a,a+16)),a+=16}let s=Gb(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:ih(e,c)}}function Pb(e,t,n,r=`full-record`){let i=Rh(n??Ah(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(kb(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=Gb(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:Gb(t,4+(i-1)*4),l=i===a-1?t.length:Gb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(kb(e,t.subarray(c,l),void 0,n,r))}return s}function Fb(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,coalesced:t.coalesced===!0,delta:qm(new lg(Jb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:Ib(t.reason)};throw Error(`unknown subscription chunk`)}function Ib(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 Lb(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):Om({code:r,message:n})??Error(n)}function Rb(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 zb(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?kh(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=Hb(e,i).map((e,t)=>Bb(e,i[t].column_type));return ah({id:e.id,values:a},oh(i,a))}function Bb(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Bb(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:Vb(e.value,t.columns)}:e}function Vb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Bb(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return ah({id:e.id,values:r},oh(t,r))}function Hb(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 Ub(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function Wb(e){let t=Ee(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Gb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Kb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function qb(e){return e.startsWith(Gs)}function Jb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Yb(e){queueMicrotask(()=>{throw e})}var Xb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Xa(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 Zb(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 ex(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return $b(t)},`the app's bearer`)}var Qb=3e4;function $b(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`)),Qb)})]).finally(()=>clearTimeout(t))}function ex(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 tx=`warn`;function nx(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??tx}function rx(e){return ct({...e,trustedReservedSession:d(e)})}function ix(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=xe(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`device-account`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Je(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`);O(e,i)}function ax(e){let t=rx(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 ox(e){return!rx(e)&&!!e.adminSecret}function sx(e,t){if(!(!t||!e.jwtToken||t.issuer!==`urn:jazz:local-first`&&t.issuer!==`urn:jazz:anonymous`))return{token:e.jwtToken,appId:U(e),claimedAuthor:r(t.issuer,t.user_id,t.account_id)}}function cx(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function lx(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var ux=class extends Cm{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 gm(e.runtimeSources)}admitConfig(e){ix(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,onAuthRestored:i,foregroundNodeLease:a}){nx(e.logLevel);let o={onAuthFailure:r,onAuthRestored:i},s=sx(e,rx(e)),c=ox(e),l=a?.node.slice()??p(),u=Ve(ax(e)),f=cx(e),m=px(e),h=e.cookieSession&&e.accountId?es(e):void 0,g=this.nativeSchemaView(t,l,u,f,!m,s,c,{appId:U(e),thresholdMs:e.slowQueryThresholdMs,...dx()?{consoleDetail:`summary`}:{}},n,h&&e.serverUrl?Zb(e.serverUrl,h):void 0,e.subscriptionBacklogRows);if(a&&g.seedForegroundTxTimeHighWater(a.confirmedTxTime),m&&(g.setNonDurableClient(),!a))throw Error(`Persistent browser runtime requires a foreground node lease`);let _={appId:U(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 O(_,d(e)),ne.connectWithRuntime(this.wrapClientRuntime(g,e,t),_,o)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!px(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=pu(e);return await bo.acquire({runtimeSources:lx(e),dbName:t,storageOwner:Bi(e)})}async acquireForegroundNodeLease(t){if(!fx()||(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:U(t),env:t.env??`dev`,authScope:zi(t)})}createBrowserWorkerConnection({config:e,schema:t,client:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l,onNewerBuild:u}){let d=n.getRuntime();if(!(d instanceof Tv))throw Error(`Browser worker connections require the native runtime adapter`);let f=sx(e,rx(e));if(ox(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let p=pu(e),m=Ve(ax(e));return e.runtimeSources?.browserWorkerPort?new Xb(d,e.runtimeSources.browserWorkerPort,rx(e)?.claims??{},p,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l},e.runtimeSources.inspectorBinding):new xo(d,{runtimeSources:lx(e),schema:t,dbName:p,author:m,selfSignedClientProof:f,initialSyncFlushEvery:cx(e),migrations:d.migrations,appId:U(e),slowQueryThresholdMs:e.slowQueryThresholdMs,...e.subscriptionBacklogRows===void 0?{}:{subscriptionBacklogRows:e.subscriptionBacklogRows},storageOwner:Bi(e),authSessionKey:zi(e),serverUrl:e.serverUrl?Ae(e.serverUrl,U(e)):void 0,authJson:JSON.stringify(mx(e)),sessionClaims:rx(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Pi(e,p,Ye(t)),{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s,onStorageReset:c,onStorageInvalidated:l,onNewerBuild:u})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof Tv))throw Error(`Browser follower connections require the native runtime adapter`);let l=rx(e)?.claims??{},u=new Xa(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(mx(e)),l),u}nativeSchemaView(e,t,n,r,i,a,o=!1,s,c,l,u){return!this.ownerRuntime||this.ownerRuntime.isClosed()?(this.ownerRuntime=new Tv(this.wasmModule.WasmDb,e,t,n,1,i,{initialSyncFlushEvery:r,selfSignedClientProof:a,backendMode:o,slowQueryLog:s,subscriptionBacklogRows:u,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 xm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function dx(){return typeof window<`u`&&typeof Worker<`u`}function fx(){return typeof process<`u`&&!!process.versions?.node}function px(e){return dx()&&(e.driver?.type??`persistent`)===`persistent`}function mx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function hx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},_u(e),j(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(j(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 at({db:e,get session(){return r},async shutdown(t){t?.waitForSync&&await e.shutdown(t),await Fl([()=>a?.(),()=>s(),...c?[c]:[],()=>i.shutdown(),()=>e.shutdown()])}},i)}function gx(e){return(e.driver??{type:`persistent`}).type===`persistent`?pu(e):null}function _x(e){if(typeof window>`u`)return()=>{};let t=gx(e.getConfig());if(!t)return()=>{};let n=window;Ro(n);let r=Eo(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function vx(e){return hx(e,U(e.getConfig()),_x)}async function yx(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(P(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 bx=class extends ux{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,bo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:Bi(e)})}};async function xx(e,t,n,r){let i=new MessageChannel,a=new bx(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}};ix(o);let s=Hi(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:zi(o),storageOwner:Bi(o)};return await yx(r,c,i.port2),o.runtimeSources.inspectorBinding=c,rs(o),await vx(await bd(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 Sx(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(),Cx=200,wx=15e3,Tx=1e3;function Ex(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 Dx(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)=>Dx(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]&&Dx(e[n],t[n])):!1}function Ox(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&&Dx(r.schema,e.schema)})}var kx=class extends L.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 Ax(){let[e,t]=(0,L.useState)(null),[n,r]=(0,L.useState)([]),[i,a]=(0,L.useState)(null),o=(0,L.useRef)(Promise.resolve()),[s,c]=(0,L.useState)(null),[l,u]=(0,L.useState)(!1),[d,f]=(0,L.useState)(null);return(0,L.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+wx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await Pe({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(Sx(s.contexts,Me()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await Ex(Math.min(Cx,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,L.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await Ex(Tx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>Ox(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:Sx(n,Me()))}catch{}}})(),()=>t.abort()},[e]),(0,L.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=Me(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){Ue(e);return}let n=await xx(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)(jx,{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 jx({client:e,wasmSchema:t}){return(0,$.jsx)(kx,{children:(0,$.jsx)(nt,{client:e,children:(0,$.jsx)(be,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(Ce,{initialEntries:[new URLSearchParams(window.location.search).get(`route`)??`/`],children:(0,$.jsx)(et,{})})})})})}(0,dt.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(L.StrictMode,{children:(0,$.jsx)(Ax,{})}));
|