jazz-tools 2.0.0-alpha.70 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/bin/jazz-tools.js +0 -3
- package/dist/accounts/account-manager-core.d.ts +54 -1
- package/dist/accounts/account-manager-core.d.ts.map +1 -1
- package/dist/accounts/account-manager-core.js +2 -2
- package/dist/accounts/account-manager-core.js.map +1 -1
- package/dist/accounts/context.js +1 -1
- package/dist/accounts/context.js.map +1 -1
- package/dist/backend/api.d.ts +1 -2
- package/dist/backend/api.d.ts.map +1 -1
- package/dist/backend/api.js +0 -2
- package/dist/backend/api.js.map +1 -1
- package/dist/backend/create-jazz.d.ts +0 -6
- package/dist/backend/create-jazz.d.ts.map +1 -1
- package/dist/backend/create-jazz.js +1 -1
- package/dist/backend/create-jazz.js.map +1 -1
- package/dist/backend/inspector-ui/11.js +2 -2
- package/dist/backend/inspector-ui/12.js +2 -2
- package/dist/backend/inspector-ui/13.js +2 -2
- package/dist/backend/inspector-ui/14.js +2 -2
- package/dist/backend/inspector-ui/20.js +1 -1
- package/dist/backend/inspector-ui-files.js +4 -4
- package/dist/backend/no-account-error.d.ts +1 -1
- package/dist/backend/no-account-error.js +1 -1
- package/dist/backend/no-account-error.js.map +1 -1
- package/dist/cli.d.ts +0 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +8 -22
- package/dist/cli.js.map +1 -1
- package/dist/client/index.d.ts +0 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +0 -2
- package/dist/client/index.js.map +1 -1
- package/dist/dev/app-files.js +1 -1
- package/dist/dev/app-files.js.map +1 -1
- package/dist/dev/catalogue-api.d.ts.map +1 -1
- package/dist/dev/catalogue-api.js +3 -6
- package/dist/dev/catalogue-api.js.map +1 -1
- package/dist/dev/inspector-overlay/embedded/assets/{index-D3RK8wNj.js → index-DUKUt96e.js} +3 -3
- package/dist/dev/inspector-overlay/embedded/assets/{jazz-broker-worker-EyaWhBtz.js → jazz-broker-worker-C_mr9Omd.js} +2 -2
- package/dist/dev/inspector-overlay/embedded/assets/{jazz_wasm-O10pptvY.js → jazz_wasm-BOvbCHn3.js} +1 -1
- package/dist/dev/inspector-overlay/embedded/assets/{jazz_wasm_bg-wI43fvvq.wasm → jazz_wasm_bg-BG8gazqt.wasm} +0 -0
- package/dist/dev/inspector-overlay/embedded/embedded.html +1 -1
- package/dist/dev/project.js +1 -1
- package/dist/dev/project.js.map +1 -1
- package/dist/dev/ts-project.d.ts.map +1 -1
- package/dist/dev/ts-project.js +3 -2
- package/dist/dev/ts-project.js.map +1 -1
- package/dist/expo/create-account-manager.d.ts +1 -1
- package/dist/expo/create-account-manager.js.map +1 -1
- package/dist/expo/index.d.ts +1 -2
- package/dist/expo/index.d.ts.map +1 -1
- package/dist/expo/index.js +1 -3
- package/dist/expo/index.js.map +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -4
- package/dist/index.js.map +1 -1
- package/dist/printer/index.d.ts +2 -2
- package/dist/printer/index.d.ts.map +1 -1
- package/dist/printer/index.js +4 -1
- package/dist/printer/index.js.map +1 -1
- package/dist/react/index.d.ts +1 -2
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -3
- package/dist/react/index.js.map +1 -1
- package/dist/react/provider.d.ts +0 -2
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +1 -2
- package/dist/react/provider.js.map +1 -1
- package/dist/react-core/index.d.ts +1 -2
- package/dist/react-core/index.d.ts.map +1 -1
- package/dist/react-core/index.js +3 -5
- package/dist/react-core/index.js.map +1 -1
- package/dist/react-core/provider.d.ts +0 -8
- package/dist/react-core/provider.d.ts.map +1 -1
- package/dist/react-core/provider.js +0 -13
- package/dist/react-core/provider.js.map +1 -1
- package/dist/react-native/create-account-manager.d.ts +1 -1
- package/dist/react-native/create-account-manager.js.map +1 -1
- package/dist/react-native/index.d.ts +1 -3
- package/dist/react-native/index.d.ts.map +1 -1
- package/dist/react-native/index.js +1 -5
- package/dist/react-native/index.js.map +1 -1
- package/dist/react-native/provider.d.ts +0 -2
- package/dist/react-native/provider.d.ts.map +1 -1
- package/dist/react-native/provider.js +1 -2
- package/dist/react-native/provider.js.map +1 -1
- package/dist/runtime/db.d.ts +0 -5
- package/dist/runtime/db.d.ts.map +1 -1
- package/dist/runtime/db.js +0 -5
- package/dist/runtime/db.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/schema-builders.d.ts +0 -7
- package/dist/schema-builders.d.ts.map +1 -1
- package/dist/schema-builders.js +0 -7
- package/dist/schema-builders.js.map +1 -1
- package/dist/session/create-jazz-session.d.ts +1 -1
- package/dist/session/create-jazz-session.d.ts.map +1 -1
- package/dist/session/create-jazz-session.js.map +1 -1
- package/dist/solid/index.d.ts +1 -2
- package/dist/solid/index.d.ts.map +1 -1
- package/dist/solid/index.js +7 -8
- package/dist/solid/index.ssr.js +2 -3
- package/dist/solid/provider.d.ts +1 -12
- package/dist/solid/provider.d.ts.map +1 -1
- package/dist/solid/provider.js +12 -18
- package/dist/solid/provider.js.map +1 -1
- package/dist/solid/provider.ssr.js +1 -11
- package/dist/solid/provider.ssr.js.map +1 -1
- package/dist/svelte/context.svelte.d.ts +1 -12
- package/dist/svelte/context.svelte.d.ts.map +1 -1
- package/dist/svelte/context.svelte.js +2 -20
- package/dist/svelte/index.d.ts +1 -2
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +1 -3
- package/dist/thin/index.d.ts +0 -1
- package/dist/thin/index.d.ts.map +1 -1
- package/dist/thin/index.js +0 -2
- package/dist/thin/index.js.map +1 -1
- package/dist/typed-app.d.ts +1 -1
- package/dist/typed-app.js.map +1 -1
- package/dist/vue/index.d.ts +1 -2
- package/dist/vue/index.d.ts.map +1 -1
- package/dist/vue/index.js +1 -3
- package/dist/vue/index.js.map +1 -1
- package/dist/vue/provider.d.ts +2 -35
- package/dist/vue/provider.d.ts.map +1 -1
- package/dist/vue/provider.js +1 -135
- package/dist/vue/provider.js.map +1 -1
- package/dist/web/lazy-local-first.d.ts +0 -3
- package/dist/web/lazy-local-first.d.ts.map +1 -1
- package/dist/web/lazy-local-first.js +1 -6
- package/dist/web/lazy-local-first.js.map +1 -1
- package/dist/worker/jazz-broker-worker.js +2 -2
- package/dist/worker/jazz_wasm_bg.wasm +0 -0
- package/package.json +4 -8
- package/dist/accounts/create-account-manager.d.ts +0 -57
- package/dist/accounts/create-account-manager.d.ts.map +0 -1
- package/dist/accounts/create-account-manager.js +0 -17
- package/dist/accounts/create-account-manager.js.map +0 -1
- package/dist/permissions/index.d.ts +0 -5
- package/dist/permissions/index.d.ts.map +0 -1
- package/dist/permissions/index.js +0 -11
- package/dist/permissions/index.js.map +0 -1
- package/dist/removed-api.d.ts +0 -87
- package/dist/removed-api.d.ts.map +0 -1
- package/dist/removed-api.js +0 -95
- package/dist/removed-api.js.map +0 -1
- package/dist/removed-schema-api.d.ts +0 -80
- package/dist/removed-schema-api.d.ts.map +0 -1
- package/dist/removed-schema-api.js +0 -128
- package/dist/removed-schema-api.js.map +0 -1
- package/dist/session/deprecated-session-hook.d.ts +0 -8
- package/dist/session/deprecated-session-hook.d.ts.map +0 -1
- package/dist/session/deprecated-session-hook.js +0 -28
- package/dist/session/deprecated-session-hook.js.map +0 -1
- package/dist/svelte/JazzSvelteProvider.svelte +0 -181
- package/dist/svelte/JazzSvelteProvider.svelte.d.ts +0 -14
- package/dist/svelte/JazzSvelteProvider.svelte.d.ts.map +0 -1
- package/dist/upgrade/aliases.d.ts +0 -25
- package/dist/upgrade/aliases.d.ts.map +0 -1
- package/dist/upgrade/aliases.js +0 -80
- package/dist/upgrade/aliases.js.map +0 -1
- package/dist/upgrade/app-json.d.ts +0 -32
- package/dist/upgrade/app-json.d.ts.map +0 -1
- package/dist/upgrade/app-json.js +0 -145
- package/dist/upgrade/app-json.js.map +0 -1
- package/dist/upgrade/constants.d.ts +0 -25
- package/dist/upgrade/constants.d.ts.map +0 -1
- package/dist/upgrade/constants.js +0 -136
- package/dist/upgrade/constants.js.map +0 -1
- package/dist/upgrade/edits.d.ts +0 -10
- package/dist/upgrade/edits.d.ts.map +0 -1
- package/dist/upgrade/edits.js +0 -21
- package/dist/upgrade/edits.js.map +0 -1
- package/dist/upgrade/errors.d.ts +0 -12
- package/dist/upgrade/errors.d.ts.map +0 -1
- package/dist/upgrade/errors.js +0 -18
- package/dist/upgrade/errors.js.map +0 -1
- package/dist/upgrade/extras.d.ts +0 -42
- package/dist/upgrade/extras.d.ts.map +0 -1
- package/dist/upgrade/extras.js +0 -487
- package/dist/upgrade/extras.js.map +0 -1
- package/dist/upgrade/fresh.d.ts +0 -36
- package/dist/upgrade/fresh.d.ts.map +0 -1
- package/dist/upgrade/fresh.js +0 -154
- package/dist/upgrade/fresh.js.map +0 -1
- package/dist/upgrade/index.d.ts +0 -79
- package/dist/upgrade/index.d.ts.map +0 -1
- package/dist/upgrade/index.js +0 -806
- package/dist/upgrade/index.js.map +0 -1
- package/dist/upgrade/json-only.d.ts +0 -24
- package/dist/upgrade/json-only.d.ts.map +0 -1
- package/dist/upgrade/json-only.js +0 -124
- package/dist/upgrade/json-only.js.map +0 -1
- package/dist/upgrade/names.d.ts +0 -29
- package/dist/upgrade/names.d.ts.map +0 -1
- package/dist/upgrade/names.js +0 -105
- package/dist/upgrade/names.js.map +0 -1
- package/dist/upgrade/payload-enums.d.ts +0 -18
- package/dist/upgrade/payload-enums.d.ts.map +0 -1
- package/dist/upgrade/payload-enums.js +0 -52
- package/dist/upgrade/payload-enums.js.map +0 -1
- package/dist/upgrade/permissions-check.d.ts +0 -10
- package/dist/upgrade/permissions-check.d.ts.map +0 -1
- package/dist/upgrade/permissions-check.js +0 -85
- package/dist/upgrade/permissions-check.js.map +0 -1
- package/dist/upgrade/program.d.ts +0 -18
- package/dist/upgrade/program.d.ts.map +0 -1
- package/dist/upgrade/program.js +0 -56
- package/dist/upgrade/program.js.map +0 -1
- package/dist/upgrade/project.d.ts +0 -56
- package/dist/upgrade/project.d.ts.map +0 -1
- package/dist/upgrade/project.js +0 -254
- package/dist/upgrade/project.js.map +0 -1
- package/dist/upgrade/rewrite.d.ts +0 -34
- package/dist/upgrade/rewrite.d.ts.map +0 -1
- package/dist/upgrade/rewrite.js +0 -500
- package/dist/upgrade/rewrite.js.map +0 -1
- package/dist/upgrade/schema-ts.d.ts +0 -59
- package/dist/upgrade/schema-ts.d.ts.map +0 -1
- package/dist/upgrade/schema-ts.js +0 -582
- package/dist/upgrade/schema-ts.js.map +0 -1
- package/dist/upgrade/snapshot.d.ts +0 -11
- package/dist/upgrade/snapshot.d.ts.map +0 -1
- package/dist/upgrade/snapshot.js +0 -90
- package/dist/upgrade/snapshot.js.map +0 -1
- package/dist/upgrade/upgrade-test-helpers.d.ts +0 -12
- package/dist/upgrade/upgrade-test-helpers.d.ts.map +0 -1
- package/dist/upgrade/upgrade-test-helpers.js +0 -72
- package/dist/upgrade/upgrade-test-helpers.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./esm-k373aadI.js","./create-legacy-browser-delegate-DeI8PAZ5.js","./diag-api-3Z_Eel3W.js","./ExportResult-C0ZojfNk.js","./esm-DZrCzNXM.js","./esm-CcBEG-yV.js","./rolldown-runtime-XKyaHtl9.js","./esm-BB6DtWpZ.js","./esm-B_xpsQL2.js","./esm-CE7mSo95.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{$ as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as D,N as O,Nt as ee,O as te,Ot as ne,P as re,Pt as ie,Q as ae,R as oe,Rt as se,S as ce,St as le,T as ue,Tt as k,U as A,Ut as de,V as fe,Vt as j,W as pe,Wt as me,X as he,Xt as ge,Y as _e,Yt as ve,Z as ye,Zt as be,_ as xe,_t as Se,an as Ce,at as M,b as we,bt as N,dt as Te,en as Ee,et as De,ft as Oe,g as ke,gt as Ae,h as je,ht as Me,in as Ne,it as Pe,j as Fe,jt as Ie,k as Le,kt as Re,m as ze,mt as Be,nn as Ve,nt as He,on as Ue,ot as We,pt as Ge,q as Ke,qt as qe,rn as Je,rt as Ye,st as Xe,t as Ze,tn as Qe,tt as $e,ut as et,v as tt,vt as nt,w as rt,wt as it,x as at,xt as P,y as ot,yt as st,z as ct,zt as lt}from"./src-4JwhxZaW.js";var F=e(Ue(),1),ut=Ce(),dt=new WeakMap;function ft(e){let t=dt.get(e)??-2;if(!Number.isSafeInteger(t))throw Error(`Inspector request identifiers exhausted`);return dt.set(e,t-1),t}function pt(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&&Ve(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=ft(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=ft(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 mt=BigInt(2**32-1),ht=BigInt(32);function gt(e,t=!1){return t?{h:Number(e&mt),l:Number(e>>ht&mt)}:{h:Number(e>>ht&mt)|0,l:Number(e&mt)|0}}function _t(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=gt(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var vt=(e,t,n)=>e>>>n,yt=(e,t,n)=>e<<32-n|t>>>n,bt=(e,t,n)=>e>>>n|t<<32-n,xt=(e,t,n)=>e<<32-n|t>>>n,St=(e,t,n)=>e<<64-n|t>>>n-32,Ct=(e,t,n)=>e>>>n-32|t<<64-n;function wt(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Tt=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Et=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Dt=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ot=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,kt=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),At=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,jt=_t(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),Mt=jt[0],Nt=jt[1],Pt=new Uint32Array(80),Ft=new Uint32Array(80),It=class extends lt{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)Pt[n]=e.getUint32(t),Ft[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=Pt[e-15]|0,n=Ft[e-15]|0,r=bt(t,n,1)^bt(t,n,8)^vt(t,n,7),i=xt(t,n,1)^xt(t,n,8)^yt(t,n,7),a=Pt[e-2]|0,o=Ft[e-2]|0,s=bt(a,o,19)^St(a,o,61)^vt(a,o,6),c=Dt(i,xt(a,o,19)^Ct(a,o,61)^yt(a,o,6),Ft[e-7],Ft[e-16]),l=Ot(c,r,s,Pt[e-7],Pt[e-16]);Pt[e]=l|0,Ft[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=bt(u,d,14)^bt(u,d,18)^St(u,d,41),v=xt(u,d,14)^xt(u,d,18)^Ct(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=kt(_,v,b,Nt[e],Ft[e]),S=At(x,g,t,y,Mt[e],Pt[e]),C=x|0,w=bt(n,r,28)^St(n,r,34)^St(n,r,39),T=xt(n,r,28)^Ct(n,r,34)^Ct(n,r,39),E=n&i^n&o^i&o,D=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=wt(c|0,l|0,S|0,C|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let O=Tt(C,T,D);n=Et(O,S,w,E),r=O|0}({h:n,l:r}=wt(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=wt(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=wt(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=wt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=wt(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=wt(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=wt(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=wt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){me(Pt,Ft)}destroy(){me(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Lt=class extends It{Ah=a[0]|0;Al=a[1]|0;Bh=a[2]|0;Bl=a[3]|0;Ch=a[4]|0;Cl=a[5]|0;Dh=a[6]|0;Dl=a[7]|0;Eh=a[8]|0;El=a[9]|0;Fh=a[10]|0;Fl=a[11]|0;Gh=a[12]|0;Gl=a[13]|0;Hh=a[14]|0;Hl=a[15]|0;constructor(){super(64)}},Rt=C(()=>new Lt,ve(3)),zt=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function Bt(e){return zt.encode(e)}function Vt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ht(e,t=!1){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw Error(`invalid base64url`);let n=`=`.repeat((4-e.length%4)%4),r=atob(e.replace(/-/g,`+`).replace(/_/g,`/`)+n),i=Uint8Array.from(r,e=>e.charCodeAt(0));if(!t&&Vt(i)!==e)throw Error(`non-canonical base64url`);return i}function Ut(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function Wt(e){let t=Ut(e.subarray(0,16));return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Gt=`jazz-auth-v1:`,Kt=32,qt=/^[A-Za-z0-9_-]{43}$/,Jt=class extends Error{constructor(e){super(e),this.name=`SecretFormatError`}};function Yt(e){if(e.byteLength!==Kt)throw new Jt(`A device account key must contain exactly ${Kt} bytes`);return`${Gt}${Vt(e)}`}function Xt(e){if(typeof e!=`string`||!e.startsWith(`jazz-auth-v1:`))throw new Jt(`A device account key must start with ${Gt}`);let t=e.slice(13);if(!qt.test(t))throw new Jt(`A device account key must use 43 unpadded base64url characters`);let n;try{n=Ht(t,!0)}catch{throw new Jt(`A device account key is not valid base64url`)}if(n.byteLength!==Kt||Yt(n)!==e)throw new Jt(`A device account key is not canonical`);return n}var Zt=BigInt(0),Qt=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 en(e){if(typeof e==`bigint`){if(!cn(e))throw Error(`positive bigint expected, got `+e)}else _(e);return e}function tn(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?Zt:BigInt(`0x`+e)}function nn(e){return tn(de(e))}function rn(e){return tn(de(sn(j(e)).reverse()))}function an(e,t){_(t),e=en(e);let n=qe(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function on(e,t){return an(e,t).reverse()}function sn(e){return Uint8Array.from(e)}var cn=e=>typeof e==`bigint`&&Zt<=e;function ln(e,t,n){return cn(e)&&cn(t)&&cn(n)&&t<=e&&e<n}function un(e,t,n,r){if(!ln(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}var dn=e=>(Qt<<BigInt(e))-Qt;function fn(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)}function pn(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 I=BigInt(0),L=BigInt(1),mn=BigInt(2),hn=BigInt(3),gn=BigInt(4),_n=BigInt(5),vn=BigInt(7),yn=BigInt(8),bn=BigInt(9),xn=BigInt(16);function R(e,t){let n=e%t;return n>=I?n:t+n}function Sn(e,t,n){let r=e;for(;t-->I;)r*=r,r%=n;return r}function Cn(e,t){if(e===I)throw Error(`invert: expected non-zero number`);if(t<=I)throw Error(`invert: expected positive modulus, got `+t);let n=R(e,t),r=t,i=I,a=L,o=L,s=I;for(;n!==I;){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!==L)throw Error(`invert: does not exist`);return R(i,t)}function wn(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Tn(e,t){let n=(e.ORDER+L)/gn,r=e.pow(t,n);return wn(e,r,t),r}function En(e,t){let n=(e.ORDER-_n)/yn,r=e.mul(t,mn),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,mn),i),s=e.mul(a,e.sub(o,e.ONE));return wn(e,s,t),s}function Dn(e){let t=Rn(e),n=On(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+vn)/xn;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 wn(e,p,t),p}}function On(e){if(e<hn)throw Error(`sqrt is not defined for small field`);let t=e-L,n=0;for(;t%mn===I;)t/=mn,n++;let r=mn,i=Rn(e);for(;Fn(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Tn;let a=i.pow(r,t),o=(t+L)/mn;return function(e,r){if(e.is0(r))return r;if(Fn(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=L<<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 kn(e){return e%gn===hn?Tn:e%yn===_n?En:e%xn===bn?Dn(e):On(e)}var An=(e,t)=>(R(e,t)&L)===L,jn=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Mn(e){return fn(e,jn.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,BYTES:`number`,BITS:`number`})),e}function Nn(e,t,n){if(n<I)throw Error(`invalid exponent, negatives unsupported`);if(n===I)return e.ONE;if(n===L)return t;let r=e.ONE,i=t;for(;n>I;)n&L&&(r=e.mul(r,i)),i=e.sqr(i),n>>=L;return r}function Pn(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 Fn(e,t){let n=(e.ORDER-L)/mn,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 In(e,t){t!==void 0&&_(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}var Ln=class{ORDER;BITS;BYTES;isLE;ZERO=I;ONE=L;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=I)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}=In(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 R(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return I<=e&&e<this.ORDER}is0(e){return e===I}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&L)===L}neg(e){return R(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return R(e*e,this.ORDER)}add(e,t){return R(e+t,this.ORDER)}sub(e,t){return R(e-t,this.ORDER)}mul(e,t){return R(e*t,this.ORDER)}pow(e,t){return Nn(this,e,t)}div(e,t){return R(e*Cn(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 Cn(e,this.ORDER)}sqrt(e){return this._sqrt||=kn(this.ORDER),this._sqrt(this,e)}toBytes(e){return this.isLE?on(e,this.BYTES):an(e,this.BYTES)}fromBytes(e,t=!1){j(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?rn(e):nn(e);if(o&&(s=R(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return Pn(this,e)}cmov(e,t,n){return n?t:e}};function Rn(e,t={}){return new Ln(e,t)}var zn=BigInt(0),Bn=BigInt(1);function Vn(e,t){let n=t.negate();return e?n:t}function Hn(e,t){let n=Pn(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Un(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function Wn(e,t){Un(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:dn(e),maxNumber:i,shiftBy:BigInt(e)}}function Gn(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+=Bn);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}}var Kn=new WeakMap,qn=new WeakMap;function Jn(e){return qn.get(e)||1}function Yn(e){if(e!==zn)throw Error(`invalid wNAF`)}var Xn=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>zn;)t&Bn&&(n=n.add(r)),r=r.double(),t>>=Bn;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=Wn(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=Wn(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Gn(n,e,a);n=o,c?i=i.add(Vn(u,t[d])):r=r.add(Vn(l,t[s]))}return Yn(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=Wn(e,this.bits);for(let e=0;e<i.windows&&n!==zn;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=Gn(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Yn(n),r}getPrecomputes(e,t,n){let r=Kn.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),Kn.set(t,r))),r}cached(e,t,n){let r=Jn(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Jn(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Un(t,this.bits),qn.set(e,t),Kn.delete(e)}hasCache(e){return Jn(e)!==1}};function Zn(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Mn(t),t}return Rn(e,{isLE:n})}function Qn(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>zn))throw Error(`CURVE.${e} must be positive bigint`)}let i=Zn(t.p,n.Fp,r),a=Zn(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 $n(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var er=BigInt(0),z=BigInt(1),tr=BigInt(2),nr=BigInt(8);function rr(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 ir(e,t={}){let n=Qn(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;fn(t,{},{uvRatio:`function`});let s=tr<<BigInt(i.BYTES*8)-z,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:er}}});if(!rr(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?z:er;return un(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`EdwardsPoint expected`)}let f=pn((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?nr:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:er,y:z};if(u!==z)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=pn(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),p=c(l*t);if(c(d*c(p+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,z,c(a.Gx*a.Gy));static ZERO=new m(er,z,z,er);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,z,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=sn(j(e,n,`point`)),$t(t,`zip215`);let u=sn(e),d=e[n-1];u[n-1]=d&-129;let f=rn(u);un(`point.y`,f,er,t?s:r.ORDER);let p=c(f*f),h=c(p-z),g=c(o*p-i),{isValid:_,value:v}=l(h,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=(v&z)===z,b=!!(d&128);if(!t&&v===er&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=c(-v)),m.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return m.fromBytes(qe(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(tr),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(tr*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),y=c(p*f);return new m(g,_,y,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),E=c(b*x);return new m(C,w,E,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===er?m.ZERO:this.is0()||e===z?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===z?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&z?128:0,n}toHex(){return de(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let h=new Xn(m,i.BITS);return m.BASE.precompute(8),m}function ar(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);fn(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||ge,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if($t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(rn(e))}function d(e){let n=b.secretKey;j(e,b.secretKey,`secretKey`);let r=j(t(e),2*n,`hashedSecretKey`),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){let i=h(...n);return u(t(l(i,j(e,void 0,`context`),!!r)))}function g(e,t,n={}){e=j(e,void 0,`message`),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);let g=h(u,o.toBytes(p));return j(g,b.signature,`result`)}let _={zip215:!0};function v(t,n,a,o=_){let{context:s,zip215:c}=o,l=b.signature;t=j(t,l,`signature`),n=j(n,void 0,`message`),a=j(a,b.publicKey,`publicKey`),c!==void 0&&$t(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=rn(t.subarray(u,l)),p,h,g;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),g=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=a.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function S(e=s(b.seed)){return j(e,b.seed,`seed`)}function C(e){return x(e)&&e.length===o.BYTES}function w(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let T={getExtendedPublicKey:f,randomSecretKey:S,isValidSecretKey:C,isValidPublicKey:w,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 o=i?a.div(z+n,z-n):a.div(n-z,n+z);return a.toBytes(o)},toMontgomerySecret(e){let n=b.secretKey;j(e,n);let r=t(e.subarray(0,n));return c(r).subarray(0,n)}};return Object.freeze({keygen:$n(S,p),getPublicKey:p,sign:g,verify:v,utils:T,Point:e,lengths:b})}var or=BigInt(1),sr=BigInt(2),cr=BigInt(5),lr=BigInt(8),ur=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),dr={p:ur,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:lr,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function fr(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=ur,o=e*e%a*e%a,s=Sn(Sn(o,sr,a)*o%a,or,a)*e%a,c=Sn(s,cr,a)*s%a,l=Sn(c,t,a)*c%a,u=Sn(l,n,a)*l%a,d=Sn(u,r,a)*u%a;return{pow_p_5_8:Sn(Sn(Sn(Sn(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,sr,a)*e%a,b2:o}}function pr(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var mr=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function hr(e,t){let n=ur,r=R(t*t*t,n),i=fr(e*R(r*r*t,n)).pow_p_5_8,a=R(e*r*i,n),o=R(t*a*a,n),s=a,c=R(a*mr,n),l=o===e,u=o===R(-e,n),d=o===R(-e*mr,n);return l&&(a=s),(u||d)&&(a=c),An(a,n)&&(a=R(-a,n)),{isValid:l||u,value:a}}var gr=ir(dr,{uvRatio:hr});function _r(e){return ar(gr,Rt,Object.assign({adjustScalarBytes:pr},e))}var vr=_r({}),yr=`urn:jazz:local-first`,br=`jazz-auth-sign-v1`,xr=Bt(`jazz-auth-key-v1`),Sr=3600,Cr=class extends Error{constructor(e){super(e),this.name=`LocalFirstTokenError`}};function wr(e,t){let n=new Uint8Array(e.length+t.length);n.set(e),n.set(t,e.length);let r=se(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,Wt(r)}var Tr=Uint8Array.from([107,167,184,16,157,173,17,209,128,180,0,192,79,212,48,200]),Er=[/^([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 Dr(e){if(typeof e!=`string`||e.length===0)throw TypeError(`audience must be a non-empty string`);for(let t of Er){let n=t.exec(e);if(n)return n.slice(1).join(`-`).toLowerCase()}return wr(Tr,Bt(e))}function Or(e){let t=Xt(e),n=Bt(br),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),Rt(r).slice(0,32)}function kr(e){return wr(xr,e)}var Ar=()=>Math.floor(Date.now()/1e3);function jr(e,t){let n=Dr(t.audience),r=t.ttlSeconds??Sr;if(!Number.isSafeInteger(r)||r<=0)throw new Cr(`ttlSeconds must be a positive integer`);let i=t.now??Ar();if(!Number.isSafeInteger(i)||i<0)throw new Cr(`now must be a non-negative integer`);let a=Or(e),o=vr.getPublicKey(a),s=Vt(Bt(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=Vt(Bt(JSON.stringify({iss:yr,sub:kr(o),aud:n,jazz_pub_key:Vt(o),iat:i,exp:i+r})));return`${s}.${c}.${Vt(vr.sign(Bt(`${s}.${c}`),a))}`}var Mr=Gt,Nr=Xt;function Pr(e){return Nr(e),e.slice(Mr.length)}function B(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Ir(e.serverUrl):Fr)}var Fr=`local`;function Ir(e){let t;try{t=new be(De(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 Lr(){return import.meta.url}function Rr(){let e=import.meta.url;return new URL(`../worker/jazz-broker-worker.js`,e).href}function zr(){return null}function Br(){return null}function Vr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`}function Hr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`blob:`}function Ur(e){return new URL(`/`,e).href}function Wr(e,t){try{return new URL(e).href}catch{}if(t)try{return new URL(e,t).href}catch{}return e}function Gr(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 Kr(e,t){try{return new URL(e).href}catch{}return t?new URL(e,t).href:null}function qr(e,t,n){return!t||Vr(e)||!n&&Hr(t)?null:new URL(`jazz_wasm_bg.wasm`,Ur(t)).href}function Jr(e){return e?.wasmModule?{module:e.wasmModule}:e?.wasmSource?{module:e.wasmSource}:null}function Yr(e,t,n){if(n?.wasmUrl)return Gr(Wr(n.wasmUrl,t),n);if(n?.baseUrl){let e=Kr(n.baseUrl,t);if(e)return Gr(new URL(`jazz_wasm_bg.wasm`,e).href,n)}return qr(typeof e==`function`?e():e,t,!1)}function Xr(e,t,n){if(n?.brokerWorkerUrl)return Gr(Wr(n.brokerWorkerUrl,t),n);if(n?.baseUrl){let e=Kr(n.baseUrl,t);if(e)return Gr(new URL(`worker/jazz-broker-worker.js`,e).href,n)}return!t||Vr(e)?Gr(new URL(`../worker/jazz-broker-worker.js`,e).href,n):Gr(new URL(`worker/jazz-broker-worker.js`,Ur(t)).href,n)}function Zr(){let e=typeof process<`u`;return Qr(e?{}.VITE_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.NEXT_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.EXPO_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(void 0)}function Qr(e){return e?.trim()||void 0}var $r=`modulepreload`,ei=function(e,t){return new URL(e,t).href},ti={},ni=function(e){return e.pathname.endsWith(`.css`)},ri=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},ii=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=ei(t,n);let r=s(t),i=ni(r);return ri(ti,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:$r,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ai=new WeakMap,oi=256,si=5e3,ci=1,li={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17};function ui(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 di(e){if(!e.collectorUrl)return()=>void 0;let t={traceUrl:ui(e.collectorUrl,`traces`),logUrl:ui(e.collectorUrl,`logs`)},{runtimeThread:n,wasmModule:r}=e;if(!hi(r))return console.warn(`[jazz] WASM telemetry unavailable: trace entry hooks are missing.`),()=>void 0;let i=ai.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 fi(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},ai.set(r,i);let a=()=>{let e=r.drainTraceEntries();Array.isArray(e)&&e.length!==0&&pi(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),fi(r,i)}catch(e){if(s)try{r.setTraceEntryCollectionEnabled(!1)}catch{}try{i.unsubscribe?.()}catch{}throw i.unsubscribe=null,ai.get(r)===i&&ai.delete(r),e}}function fi(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&&pi(t,n)}catch(e){i??=e}finally{try{e.setTraceEntryCollectionEnabled(!1)}catch(e){i??=e}finally{t.unsubscribe=null,mi(t),!i&&ai.get(e)===t&&ai.delete(e)}}}if(i)throw i}}function pi(e,t){e.exportTail=e.exportTail.catch(()=>void 0).then(async()=>{e.exporter||=_i(e.identity.traceUrl,e.identity.logUrl);try{let n=await e.exporter;for(let r of t)try{gi(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 mi(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 hi(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 gi(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":xi(n.fields)};e.tracer.startSpan(n.name||`wasm span`,{kind:ci,startTime:n.startUnixNano,attributes:bi(n.fields)?{...vi(n.fields),...r}:r}).end(n.endUnixNano)}else if(n.kind===`log`){let r={"jazz.runtime_thread":t,"jazz.log.sequence":n.sequence,"jazz.log.target":n.target,"jazz.log.fields":xi(n.fields)};e.logger.emit({timestamp:n.timestampUnixNano,severityNumber:yi(n.level),severityText:n.level,body:n.message,attributes:bi(n.fields)?{...vi(n.fields),...r}:r})}else e.logger.emit({severityNumber:li.WARN,severityText:`WARN`,body:`Dropped ${n.count} WASM telemetry records`,attributes:{"jazz.runtime_thread":t,"jazz.telemetry.dropped_count":n.count}})}async function _i(e,t){let[{OTLPTraceExporter:n},{BasicTracerProvider:r,BatchSpanProcessor:i},{OTLPLogExporter:a},{LoggerProvider:o,BatchLogRecordProcessor:s},{resourceFromAttributes:c}]=await Promise.all([ii(()=>import(`./esm-k373aadI.js`),__vite__mapDeps([0,1,2,3]),import.meta.url),ii(()=>import(`./esm-DZrCzNXM.js`),__vite__mapDeps([4,5,6,2,7,3]),import.meta.url),ii(()=>import(`./esm-B_xpsQL2.js`),__vite__mapDeps([8,1,2,3]),import.meta.url),ii(()=>import(`./esm-CE7mSo95.js`),__vite__mapDeps([9,2,5,6,7,3]),import.meta.url),ii(()=>import(`./esm-CcBEG-yV.js`).then(e=>e.t),__vite__mapDeps([5,6,2]),import.meta.url)]),l=c({"service.name":`jazz-browser`,"telemetry.sdk.language":`webjs`}),u={maxExportBatchSize:oi,maxQueueSize:si,scheduledDelayMillis:1e3},d=new r({resource:l,spanProcessors:[new i(new n({url:e}),u)]}),f=new o({resource:l,processors:[new s(new a({url:t}),u)]});return{tracer:d.getTracer(`jazz-wasm.tracing`),logger:f.getLogger(`jazz-wasm.tracing`),shutdown:async()=>{await Promise.all([typeof d.shutdown==`function`?d.shutdown():void 0,typeof f.shutdown==`function`?f.shutdown():void 0])}}}function vi(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))n.startsWith(`jazz.`)||r!=null&&(t[n]=typeof r==`string`||typeof r==`number`||typeof r==`boolean`?r:JSON.stringify(r));return t}function yi(e){switch(e.toUpperCase()){case`TRACE`:return li.TRACE;case`DEBUG`:return li.DEBUG;case`INFO`:return li.INFO;case`WARN`:case`WARNING`:return li.WARN;case`ERROR`:return li.ERROR;default:return 0}}function bi(e){if(!e)return!1;for(let t in e)return!0;return!1}function xi(e){return bi(e)?JSON.stringify(e):`{}`}var Si=`jazz-shared-runtime-v3`,Ci=`idbtree-v1`,wi=new WeakMap;function Ti(e){if(e?.brokerWorkerUrl||e?.baseUrl)return Xr(Lr(),typeof location<`u`?location.href:void 0,e);let t=ki(Lr());return t?e?.wasmVersion?`${t}&jazz-runtime-version=${encodeURIComponent(e.wasmVersion)}`:t:Gr(Wr(Rr(),typeof location<`u`?location.href:void 0),e)}var Ei=/^(.*?\/)node_modules\/\.vite\/(?:.*\/)?deps(?:_[^/]*)?\/[^/]+$/,Di=`worker_file&type=module`,Oi=`jazz-tools/_worker/broker`;function ki(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`http:`&&t.protocol!==`https:`)return;let n=Ei.exec(t.pathname);return n?`${t.origin}${n[1]}@id/${Oi}?${Di}`:void 0}function Ai(e){if(!e)return ji(e);if((e.baseUrl||e.wasmUrl&&!Mi(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=Pi(e);if(t)return{...e,workerWasmAssetIdentity:t};let n=Yr(Lr(),typeof location<`u`?location.href:void 0,e);return n?{...e,wasmUrl:n}:ji(e)}function ji(e){let t=zr();return t?{...e,wasmUrl:t}:e}function Mi(e){return e===zr()}function Ni(e){let t=Ai(e);return JSON.stringify({protocolVersion:Si,workerUrl:Ti(t),wasmAsset:Fi(t)})}function Pi(e){let[t,n]=e.wasmModule?[e.wasmModule,`module`]:e.wasmSource?[e.wasmSource,`source`]:[];if(!t||!n)return;let r=wi.get(t);return r||(r=`${n}:${crypto.randomUUID()}`,wi.set(t,r)),r}function Fi(e){return e?.wasmModule?`module:${e.workerWasmAssetIdentity??`unscoped`}`:e?.wasmSource?`source:${e.workerWasmAssetIdentity??`unscoped`}`:`url:${e?.wasmUrl??`worker-local`}`}function Ii(e,t,n){let r=e.telemetryCollectorUrl?.trim()||void 0;return JSON.stringify({protocolVersion:Si,storageFormatVersion:Ci,appId:B(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Gi(e),workerUrl:Ti(e.runtimeSources),workerAssetScope:Ni(e.runtimeSources),telemetryCollector:r?{traceUrl:ui(r,`traces`),logUrl:ui(r,`logs`)}:void 0,wasmLogLevel:e.logLevel??`warn`})}function Li(e){if(e.adminSecret)return{kind:`system`};let t=nt({appId:B(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:k(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:Ri(t.authMode),user:Re(t.issuer,t.user_id,t.account_id)}}function Ri(e){return e===`device-account`?`local-first`:e}function zi(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Bi(e)}:Li(e)}function Bi(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function Vi(e){return JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:Li(e),...e.accountId?{registry:Bi(e)}:{}})}function Hi(e){return JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:zi(e)})}function Ui(e,t){if(Hi(e)!==Hi(t)||Vi(e)!==Vi(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 Wi(e,t){let n=JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:zi(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Gi(e){if(e.adminSecret)return`admin`;let t=nt({appId:B(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:k(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${Ri(t.authMode)}:${Re(t.issuer,t.user_id,t.account_id)}`}var Ki=`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.`,qi=` 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 Ji(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var Yi=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)}},Xi=1048576,Zi=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 Yi(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){if(this.closed||e.length===0)return;let t=this.inboundRouting.then(()=>this.routeInboundFrames(e));this.inboundRouting=t.catch(e=>{this.closed||this.onError(e)})}schedule(e=!0){this.closed||(this.requestedGeneration+=1,this.running?this.runAgain||=e: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=$i(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=$i(t.call(this.transport,8,Xi));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=$i(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(ea(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 ta()}}};function Qi(e){return e.map(e=>e.slice())}function $i(e){return e.map(ea)}function ea(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 ta(){return new Promise(e=>setTimeout(e,0))}var na=new WeakMap;function ra(e,t){let n=na.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 ia=`jazz-idb-tree`,aa=`pages`,oa=`metadata`,V=`storage-manifest`,sa=`epoch`,ca=`browser-runtime-owner`,la=`browser-worker-epoch-v1`,ua=`jazz-browser-worker-epoch-v1`,da=`replica-node-v1`,fa=`foreground-node-leases-v1`,pa=`jazz-foreground-node-leases-v1`,ma=(1n<<64n)-1n,ha=`current`,ga=1024,_a=2147483648,va={storageEpoch:1,adapterId:`jazz-idb-tree`,adapterFormatVersion:1,requiredCodecIds:[`jazz.sqlite-storage.v1`],pageSize:16384,pageChecksum:`xxh3-64-le`,pageFormatMagic:`IDBTREE\0`,pageFormatVersion:1},ya=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},ba=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 xa(e,t){return e?.name===`QuotaExceededError`?new ba(e):e??Error(t)}var Sa=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(aa),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(oa),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(V);r.transaction&&(e.put(va,sa),e.put(wa().buffer,da))}};let a;try{a=await H(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??Ta(wa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),Da(r)})}async returnForegroundNodeLease(e,t){if(!Na(e)||!Ia(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(!Na(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(V,`readonly`),n=U(t);try{let r=await H(t.objectStore(V).get(fa));if(await n,r===void 0)return`missing`;let i=Oa(r),a=La(Ta(e));return i.active.some(e=>La(e.node)===a)?`active`:i.reusable.some(e=>La(e.node)===a)?`reusable`:i.retired.some(e=>La(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!Pa(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?ra(t,this.name):null,i=this.db.transaction(V,`readwrite`),a=U(i);if(i.objectStore(V).put({format:ua,epoch:e},la),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,!Pa(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(V,`readwrite`),n=U(t),r=t.objectStore(V),i=await H(r.get(la));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(la),await n}async metadata(){this.assertValid();let e=this.db.transaction(oa,`readonly`),t=U(e),n=await H(e.objectStore(oa).get(ha));return await t,n===void 0?null:(Ba(n),n)}async assertStorageManifest(){let e=this.db.transaction(V,`readonly`),t=U(e),n=await H(e.objectStore(V).get(sa));await t,Ha(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(V,`readwrite`),n=U(t),r=t.objectStore(V),i=await H(r.get(ca));if(i===void 0)r.put(e,ca),await n;else if(i===e)await n;else 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(V,`readonly`),t=U(e),n=await H(e.objectStore(V).get(da));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=Ca(this.db,[V]),n=U(t),r=t.objectStore(V);try{let t=await H(r.get(fa)),i=t===void 0?Ea():Oa(t),a=e(i);return Aa(i),r.put(i,fa),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)Wa(t);if(e.length===0)return[];let t=this.db.transaction(aa,`readonly`),n=U(t),r=t.objectStore(aa),i;try{i=await Promise.all(e.map(e=>H(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Ra(e[n],t))}async commit(e,t){if(this.assertValid(),Va(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=Ca(this.db,[aa,oa]),i=U(r),a=r.objectStore(aa),o=r.objectStore(oa),s=await H(o.get(ha)),c=s===void 0?0:za(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:ia,formatVersion:1,generation:c+1};Ba(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await H(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,ha),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=Ca(this.db,[aa,oa]),t=U(e);e.objectStore(aa).clear(),e.objectStore(oa).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 ya(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new ya(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function Ca(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function wa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return ie(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Ta(e){return e.slice().buffer}function Ea(){return{format:pa,active:[],reusable:[],retired:[]}}function Da(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Oa(e){return Aa(e),{format:e.format,active:e.active.map(ka),reusable:e.reusable.map(ka),retired:e.retired.map(e=>e.slice(0))}}function ka(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Aa(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]){ja(e);let t=La(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=Ma(e)?La(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function ja(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!Na(t.leaseId)||!Ma(t.node)||!Fa(t.confirmedTxTime)||!Ia(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function Ma(e){return e instanceof ArrayBuffer&&e.byteLength===16}function Na(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 Pa(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 Fa(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Ia(e){return e>=0n&&e<=ma}function La(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Ra(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 H(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(xa(e.error,`IndexedDB request failed`))})}function U(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(xa(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(xa(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function za(e){return Ba(e),e.generation}function Ba(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||!Ua(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Ga(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 Va(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(!Ua(t)||t!==16384||!Ga(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Ga(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(!Ga(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Ga(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Ha(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(va).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==va.storageEpoch||t.adapterId!==va.adapterId||t.adapterFormatVersion!==va.adapterFormatVersion||t.pageSize!==va.pageSize||t.pageChecksum!==va.pageChecksum||t.pageFormatMagic!==va.pageFormatMagic||t.pageFormatVersion!==va.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=va.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 Je(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 Ua(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=ga&&e<=_a&&Number.isInteger(Math.log2(e))}function Wa(e){if(!Ga(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Ga(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ka(){return Error(`Inspector control opening was cancelled`)}function qa(e){try{e.postMessage({type:`close`})}catch{}e.close()}function Ja(e,t){return t?t.aborted?Promise.reject(Ka()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Ka())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var Ya=Object.freeze({intervalMs:3e4,replyMs:3e4}),Xa=1e3,Za=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 c=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),l=(async()=>{await c;let t=await e.connectUpstreamPeer(this.peerAuthority);if(this.closed||this.failed)throw await e.retirePeerTransport(t),this.failed??Error(`Browser follower connection is closed`);this.pump=new Zi(e,t,e=>{let t=Qi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=s(t);this.failed||this.closed||(e.reportRemoteServerTransportError(n),this.fail(n))},a?e=>{console.debug(`JAZZ_AUX_RELAY`,e.map(e=>({...e,hop:`tab-worker`})))}:void 0);for(let e of this.pendingFrames.splice(0))this.pump.receive(e)})();this.readyPromise=Promise.all([c,l]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(s(e)))}async ready(){if(await this.readyPromise,this.failed)throw this.failed;if(this.closed)throw Error(`Browser follower connection is closed`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.inspectorAttachmentPhysicalDbName}async waitForServerConnection(){await this.ready(),await this.request({type:`wait-server`})}async disconnect(){await this.ready(),await this.request({type:`disconnect`})}async deleteStorage(){if(await this.ready(),!this.dbName)throw Error(`Browser storage reset requires its IndexedDB name`);let e=await this.request({type:`prepare-storage-reset`});try{await Sa.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 Ja(this.ready(),e),e?.aborted)throw Ka();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,qa(t.port1))},c=()=>{this.pending.delete(n)&&(o(),r(Ka()))};e?.addEventListener(`abort`,c,{once:!0}),this.armWatchdog();try{this.port.postMessage({type:`open-inspector-control`,id:n,port:t.port2},[t.port2])}catch(e){t.port2.close(),this.fail(s(e))}try{if(await i,e?.aborted)throw o(),Ka();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,c)}}async reconnect(e,t){await this.ready(),await this.request({type:`reconnect`,authJson:e,sessionClaims:t}),await this.request({type:`wait-server`}),this.runtime.clearRemoteServerTransportError()}updateAuth(e,t){this.closed||this.failed||this.ready().then(()=>{this.port.postMessage({type:`update-auth`,authJson:e,sessionClaims:t})}).catch(e=>this.fail(s(e)))}async shutdown(e=!1){this.closed||(await this.request({type:`close`,releaseContext:e}),this.dispose(Error(`Browser follower connection is closed`)))}leaveForPageCache(){if(this.closed||this.failed||!this.established||this.hasPendingWork())return!1;try{this.port.postMessage({type:`close`,releaseContext:!0})}catch{}return this.dispose(Error(`Browser follower connection left for the back/forward cache`)),!0}async waitForPendingWrites(){await this.flushLocal(),await this.request({type:`flush-pending-writes`})}async flushLocal(){await this.ready(),await this.pump.flush();let e=this.request({type:`flush-local`});await this.runtime.flushLocalSettlements(),this.port.postMessage({type:`flush-local-observed`}),await e}detachForReconnect(){this.dispose(Error(`Browser follower connection is reconnecting`))}request(e){if(this.failed)return Promise.reject(this.failed);if(this.closed)return Promise.reject(Error(`Browser follower connection is closed`));let t=this.nextRequestId++,n={...e,id:t},r=new Promise((n,r)=>{this.pending.set(t,{type:e.type,resolve:n,reject:r})});this.armWatchdog();try{this.port.postMessage(n)}catch(e){this.fail(s(e))}return r}clearWatchdog(){this.watchdogTimer!==null&&clearTimeout(this.watchdogTimer),this.watchdogTimer=null,this.probeNonce=null,this.watchdogEpoch++}armWatchdog(){this.closed||this.failed||!this.wantsWatchdog()||this.watchdogTimer!==null||this.scheduleWatchdog(Ya.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+Xa){this.sendProbe();return}let e=new Qe(`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(Ya.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(s(e))}}onResume=()=>{this.resumeProbePending=!0,this.sendProbe()};hasPendingWork(){return this.pending.size>0||this.localSettlementsPending||this.resumeProbePending}wantsWatchdog(){return this.hasPendingWork()||this.established&&globalThis.document?.visibilityState===`visible`}onVisibilityChange=()=>{globalThis.document?.visibilityState===`visible`&&this.onResume()};onMessage=e=>{if(this.closed||this.failed)return;let t=e.data;if(t.type===`runtime-pong`){if(t.connectionId!==this.connectionId||t.nonce!==this.probeNonce)return;this.resumeProbePending=!1,this.clearWatchdog(),this.armWatchdog();return}if(t.type===`frames`){this.pump?this.pump.receive(t.frames):this.pendingFrames.push(t.frames);return}if(t.type===`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 Qe(`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(Ve(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(Ve(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(Ve(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()}}},Qa=e=>`jazz:store-generation:${e}`;function $a(e){try{globalThis.localStorage?.setItem(Qa(e),crypto.randomUUID())}catch{}}function eo(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Qa(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Qa(e),r),r}catch{return null}}function to(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Qa(e))!==t}catch{return!0}}var no=class extends Error{name=`BrowserWorkerScriptLoadError`};async function ro(e){let t=e.moduleUrl!==null&&ki(e.moduleUrl)!==void 0,n=e.workerUrl?await io(e.workerUrl,e.fetch??globalThis.fetch):null;return new no(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?qi: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 io(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 ao(e,t){if(so(e))return new SharedWorker(Ti(e),{type:(oo(e)?null:Br())??`module`,name:t});let n=ki(Lr());if(n)return new SharedWorker(n,{type:`module`,name:t});let r=new SharedWorker(new URL(new URL(`jazz-broker-worker-EyaWhBtz.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Ki);return r}function oo(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function so(e){return oo(e)||Br()!==null}function co(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),ro({workerUrl:so(t)?Ti(t):ki(Lr()),moduleUrl:Lr(),metro:Ji()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var lo=1e4,uo=8,fo=8,po=25,mo=250,ho=3e5,go=1e3,_o=new Map;function vo(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function yo(e,t){return[`jazz-runtime`,t,Ni(e)].join(`:`)}function bo(e,t){return`${e}\u0000${t}`}var xo=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=Ai(e.runtimeSources),n=yo(t,e.dbName),r=bo(n,e.storageOwner);if(_o.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=>ao(t,e),a=Date.now()+lo,o=wo(n),s=0,c=null;for(let l=0;l<uo;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,vo(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=To(n,o);break}if(c=d.message,s+=1,s>=fo)throw Error(c);let f=Math.min(po*2**(s-1),mo,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(),lo);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`),_o.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&_o.get(r)===p&&_o.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(Ve(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?Ve(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=co(t,s,e=>{v(),c.close(),g(e)});c.addEventListener(`message`,y),c.addEventListener(`messageerror`,b),c.start(),m=_(),c.postMessage({type:`probe-foreground-node-lease-worker`,attemptId:i,...o?{wasmPrefetch:o}:{}})})}async returnWithHighWater(e){if(this.terminalError)throw this.terminalError;if(e<0n)throw Error(`Invalid foreground transaction high-water`);await this.finish({type:`return-foreground-node-lease`,confirmedTxTime:e.toString()})}async retire(){if(this.terminalError)throw this.terminalError;this.closed||await this.finish({type:`retire-foreground-node-lease`})}abandonAfterWorkerFailure(e){if(!this.terminalError&&(this.terminalError=e,this.finishWaiter?.reject(e),this.finishWaiter=null,!this.closed&&this.port&&(this.listenForFinish(),!this.terminalRequestSent))){this.terminalRequestSent=!0;try{this.port.postMessage({type:`retire-foreground-node-lease`})}catch{this.closeFinishPort()}}}releaseAfterStorageReset(e){this.failFinish(e)}releaseAfterWorkerReplacement(e){this.failFinish(e)}failFinish(e){this.terminalError??=e,this.finishWaiter?.reject(this.terminalError),this.closeFinishPort()}finish(e){if(this.terminalError)return Promise.reject(this.terminalError);if(this.closed)return Promise.reject(Error(`Shared browser foreground lease is already closed`));if(this.finishPromise)return this.finishPromise;let t=this.port;if(!t)return Promise.reject(Error(`Shared browser foreground lease port is unavailable`));this.listenForFinish(),this.finishPromise=new Promise((e,t)=>{this.finishWaiter={resolve:e,reject:t}}),this.terminalRequestSent=!0;try{t.postMessage(e)}catch(e){this.failFinish(s(e))}return this.finishPromise}listenForFinish(){this.listeningForFinish||(this.listeningForFinish=!0,this.port?.addEventListener(`message`,this.onFinishResult),this.port?.addEventListener(`messageerror`,this.onFinishError))}onFinishResult=e=>{let t=e.data;t?.type===`foreground-node-lease-result`&&(t.error?this.failFinish(Ve(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}},So=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=Ai(t.runtimeSources),a=yo(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>ao(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=s(e),this.releaseLivenessLock?.(),r.onFailure(this.readyError)})}holdLivenessLock(){let e=globalThis.navigator?.locks;if(!e)return;let t=`jazz-tab-alive:${crypto.randomUUID()}`,n,r=new Promise(e=>n=e);this.releaseLivenessLock=n;let i=new Promise((n,i)=>{e.request(t,()=>(n(),r)).catch(i)});return i.catch(()=>void 0),{name:t,granted:i}}announceLivenessLock(e,t){e.granted.then(()=>{this.closed||this.worker?.port!==t||t.postMessage({type:`liveness-lock`,name:e.name})},()=>void 0)}async connect(e,t,n,r,i){let a=this.holdLivenessLock(),o=wo(r);for(let s=0;s<uo;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=To(r,o)}throw Error(`Shared browser runtime did not answer after its previous realm closed`)}connectOnce(e,t,n,r,i){let a=i(r);this.worker=a;let o=a.port;return o.start(),new Promise(r=>{let i=!1,c=!1,l=!1,u=Date.now(),d=u+ho,f=typeof document<`u`&&document.hidden,p,m=e=>{i||(i=!0,x(),this.cancelBootstrap===g&&(this.cancelBootstrap=null),r(e))},h=e=>{if(!i){c=!0,m(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{w(),o.close()}}},g=()=>h({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=g;let _=()=>{u=Date.now(),d=u+ho},v=()=>{let e=typeof document<`u`&&document.hidden;f&&!e&&_(),f=e},y=()=>_(),b=()=>{let e=Date.now();(f||e-u>go*2)&&_(),u=e,e>=d?h({connected:!1,error:new Qe(`Shared browser runtime did not finish initialization within five minutes`)}):p=setTimeout(b,Math.min(go,d-e))},x=()=>{clearTimeout(p),p=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,v),typeof window<`u`&&window.removeEventListener(`pageshow`,y)},S=n=>{if(c){if(n.data?.type===`runtime-ready`){if(l)return;l=!0,o.postMessage({type:`close`,id:0,releaseContext:!0});return}if(n.data?.type!==`runtime-bootstrap-cancelled`&&n.data?.type!==`runtime-error`&&n.data?.type!==`worker-closing`&&(n.data?.type!==`result`||n.data.id!==0))return;w(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){w(),o.close(),this.worker===a&&(this.worker=null);let e=Ve(n.data.error);this.olderThanStore=e.message===Ee,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,m({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;w(),this.cancelBootstrap===g&&(this.cancelBootstrap=null);let r=new Za(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=>{$a(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{$a(this.dbName),this.callbacks.onStorageInvalidated?.()},onNewerBuild:this.callbacks.onNewerBuild},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>m({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})})},C=()=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:Error(`Shared browser runtime port message error`)})},w=()=>{x(),T(),o.removeEventListener(`message`,S),o.removeEventListener(`messageerror`,C)},T=co(a,t.runtimeSources,e=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:e})});o.addEventListener(`message`,S),o.addEventListener(`messageerror`,C),typeof document<`u`&&document.addEventListener(`visibilitychange`,v),typeof window<`u`&&window.addEventListener(`pageshow`,y),p=setTimeout(b,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})}})}getWorkerRealmId(){return this.connection?.getWorkerRealmId()}ready(){return this.readyPromise.then(()=>{if(this.readyError)throw this.readyError})}async waitForServerConnection(){await this.ready(),await this.connection?.waitForServerConnection()}async updateAuth(e,t){await this.ready(),this.connection?.updateAuth(e,t)}async disconnect(){await this.ready(),await this.connection?.disconnect()}async reconnect(e,t){await this.ready(),await this.connection?.reconnect(e,t)}canRetryInitialConfigurationAdmission(){return this.initialConfigurationAdmissionRejected}waitsForAnotherTab(){return this.heldByAnotherTab}isOlderThanStore(){return this.olderThanStore}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=eo(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 to(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(),$a(this.dbName);try{return await this.connection?.deleteStorage()}finally{$a(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await Ja(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&&Co(t,this.workerName,n),t}};function Co(e,t,n){e.addEventListener(`message`,e=>{e.data?.type===`result`&&e.data.workerTerminated===!0&&To(t,n)})}function wo(e){try{let t=Number.parseInt(localStorage.getItem(Eo(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function To(e,t){try{let n=Eo(e);return wo(e)===t&&localStorage.setItem(n,String(t+1)),wo(e)}catch{return t+1}}function Eo(e){return`jazz:shared-worker-generation:${e}`}function Do(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Oo(e){return[...new Set([...Do(e)].map(e=>e.namespace))].sort()}function ko(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function Ao(e,t){let n=[...Do(e)],r=Oo(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>").${ko(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${ko(r)}`);return a.db}var jo=new Map;function Mo(){let e=()=>[...jo.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...jo.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...jo].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...jo.keys()].map(t=>t.waitForSync(e)))}}}function No(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(jo.set(e,t),zo(n),()=>{jo.delete(e)})}var Po=Symbol.for(`jazz-tools.window-jazz`);function Fo(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 Io=new WeakSet;function Lo(e){let t=e.__jazz;return t===void 0||Ro(t)?!1:(Io.has(e)||(Io.add(e),console.warn(Fo(t))),!0)}function Ro(e){if(!e||typeof e!=`object`)return!1;if(Po in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function zo(e){let t=Lo(e),n=(t?void 0:e.__jazz)??{};n[Po]=!0;let r=Object.assign(n,Mo(),{async clearStorage(t){await Ao(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Oo(e)},async shutdown(t){let n=[...Do(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 Bo=`history.`;function Vo(e){return Ho(e)!==void 0}function Ho(e){return e.startsWith(Bo)?e.slice(8):void 0}var Uo=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Wo=new WeakMap;function W(e,t){let n=Ho(t);if(n===void 0)return e[t];if(Vo(n)||!Object.hasOwn(e,n))return;let r=Wo.get(e);r||Wo.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Uo],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Go=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Ko=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`}},G=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=Ae(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!r(t.iss)||!r(t.sub))throw new G(`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 G(`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 G(`invalid_account_handle`);if(r.delegated)throw new G(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new G(`backend_account_requires_backend_host`);let i=await Xo(r.auth,n);if(qo.get(e)!==r)throw new G(`account_logged_out`);if(!Yo(Jo(i),e.identity))throw new G(`credential_identity_changed`);return i}function Qo(e){let t=qo.get(e);if(!t)throw new G(`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 G(`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 G(`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 G(`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,pendingRevision:0});function os(e,t){return e===t?!0:e===null||t===null||e.length!==t.length?!1:e.every((e,n)=>e===t[n])}function ss(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function cs(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 ls(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 us=Object.freeze({state:`local-only`}),ds=Object.freeze({state:`connecting`}),fs=Object.freeze({state:`connected`});function K(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function ps(e){switch(e?.phase??`noServer`){case`noServer`:return us;case`offline`:return K(`disconnected`);case`live`:return fs;case`connecting`:case`backoff`:return e.outagePublished?K(`network`):ds;case`awaitingCredential`:return K(`auth`);case`stopped`:return K(`stopped`)}}function ms(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`||e.reason===t.reason&&e.retrying===t.retrying&&e.authReason===t.authReason:!1}function hs(e,t=as,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:ss(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function gs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&ls(e.lastError,t.lastError)&&ms(e.link,t.link)}function _s(e,t){return e.pending===t.pending&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&(e.pendingRevision??0)===(t.pendingRevision??0)&&e.lastRejection?.at===t.lastRejection?.at&&e.lastRejection?.code===t.lastRejection?.code}var vs=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 ys(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function bs(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 xs(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 Ss=class extends Error{},Cs=class extends Error{};function ws(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 Cs(`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 Ss(`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(xs(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 Ts(){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 Es=[`$canRead`],Ds=[`$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 Os(e){return Es.includes(e)}function ks(e){return Ds.includes(e)}function As(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return Ts();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=Ts();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 js=`__jazz_requireIncludes`;function Ms(e){return Array.isArray(e)?e.filter(e=>P(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function Ns(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 Ps(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Fs(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Is(e){if(!P(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!P(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(Fs(r.from)&&Fs(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(Fs(r.fromUtf8)&&Fs(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 Ls(e){let t=P(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!P(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...P(e)&&e.seed?{seed:Rs(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:Ms(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Rs(e){if(!P(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:Ms(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ls(e.gather),...Array.isArray(e.orderBy)?{orderBy:Ns(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return P(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!P(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Rs(e.input)}])}),t}function zs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function Bs(e){let t={...e};return delete t[js],Ws(t)}function Vs(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Hs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function Us(e){if(e===!0)return zs();if(!P(e))return null;if(Vs(e)){let t=Gs(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(Hs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:Ms(e.conditions),includes:Ws(e.includes),requireIncludes:e[js]===!0,select:Ps(e.select),partialSelect:Is(e.partialSelect??e.select),orderBy:Ns(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:Ls(e.gather)};let t=zs();return t.requireIncludes=e[js]===!0,t.includes=Bs(e),t}function Ws(e){if(!P(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=Us(r);e&&(t[n]=e)}return t}function Gs(e){let t=P(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Is(t.partialSelect??t.select);return{table:t.table,conditions:Ms(t.conditions),includes:Ws(t.includes),requireIncludes:t[js]===!0,select:Array.isArray(t.select)?Ps(t.select):Object.keys(n),partialSelect:n,orderBy:Ns(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:Ls(t.gather),...P(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!P(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Rs(e.input)}])}}:{}}}var Ks=`__jazz_include_`;function qs(e){return`${Ks}${e}`}function Js(e,t,n){let r=W(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)e===`*`?a.hasWildcard=!0: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 q(e,t){return t?{scope:t,column:e}:{column:e}}function Ys(e,t,n){let r=W(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:q(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:q(e.name,t)}}))]}function Xs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=As(n);if(r)return r;let i=W(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:bs(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?Js(e.toTable,r,c.select):[],u=c.conditions.map(t=>oc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[ys(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)?qs(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,r){let i=q(ys(e.column),r),a=ys(e.column),o=Xs(t,n,a);if(!o)throw Error(`Unknown column "${a}" in table "${n}"`);let s=e.value===void 0||e.value;if(e.op===`isNull`){if(typeof s!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return s?{IsNull:{column:i}}:{IsNotNull:{column:i}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:i}};if(e.op===`ne`)return{IsNotNull:{column:i}}}if(o.type===`Row`&&As(a)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${a}" only supports eq/ne operators.`);let i=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw Error(`Invalid structured author condition for "${a}".`);return e},o=a===`$createdBy`||a===`$updatedBy`||a===`$deletedBy`,s=o?i(e.value,[`account`,`identity`]):void 0,c=i(s?s.identity:e.value,[`issuer`,`subject`]);if(typeof c.issuer!=`string`||typeof c.subject!=`string`||s&&typeof s.account!=`string`)throw Error(`Invalid structured author condition for "${a}".`);Re(c.issuer,c.subject,s?.account);let l={And:[...s?[{column:`${a}.account`,op:`eq`,value:s.account}]:[],{column:`${a}${o?`.identity`:``}.issuer`,op:`eq`,value:c.issuer},{column:`${a}${o?`.identity`:``}.subject`,op:`eq`,value:c.subject}].map(e=>oc(e,t,n,r))};return e.op===`eq`?l:{Not:l}}if(e.op===`in`||e.op===`notIn`){if(!Array.isArray(e.value))throw Error(`"${e.op}" operator requires an array value.`);if(e.value.some(e=>e===null))throw Error(`"${e.op}" does not accept null membership values; use isNull or isNotNull separately.`);let t={In:{left:i,values:e.value.map(e=>({Literal:$s(e,o)}))}};return e.op===`notIn`?{Not:t}:t}let c=e.op===`contains`&&o.type===`Array`?o.element:o,l=sc(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:$s(e.value,c)};switch(e.op){case`eq`:return{Cmp:{left:i,op:`Eq`,right:l}};case`ne`:return{Cmp:{left:i,op:`Ne`,right:l}};case`gt`:return{Cmp:{left:i,op:`Gt`,right:l}};case`gte`:return{Cmp:{left:i,op:`Ge`,right:l}};case`lt`:return{Cmp:{left:i,op:`Lt`,right:l}};case`lte`:return{Cmp:{left:i,op:`Le`,right:l}};case`contains`:return{Contains:{left:i,right:l}};default:throw Error(`Unknown operator: ${e.op}`)}}function 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:q(i.fromColumn,s),right:q(`id`,c)}:{left:q(`id`,s),right:q(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:ys(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:q(c.fromColumn,e.step_table),right:q(`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:q(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=Gs(JSON.parse(e)),r=ws(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:q(ys(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:ys(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??Gs(JSON.parse(e)),i=ws(t),a=gc(r)?hc(e,t):void 0,o=a?.outputTable??r.table,s=nc(r.select.length>0?Js(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=W(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return Js(e,t,n).map(e=>{let t=As(e);if(t)return{name:e,columnType:t};if(Os(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(!W(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=qs(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];l===void 0?u[a.relation.name]=a.relation.isArray?[]:null: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&&(ks(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(!W(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Ec(t,Ws(n),r??ws(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(Ks)),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=>!ks(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:bs(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=3e5;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=Ke(r);if(this.client){if(!this.clientSchema||Ke(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),l(a,k(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:Ke(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 hs(e);let t=this.client?.getRuntime();return hs(e,t?.uploadStatus?.()??as,t?.lastLinkFailure?.()??null)}pendingUploadRows(e){return this.client?.getRuntime()?.pendingUploadRows?.(e)??null}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?us:this.isExplicitlyOffline()?K(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??ds;return e.state===`local-only`?ds: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){e.mode===`bearer`?e.jwtToken&&e.trustedReservedSession?this.client?.updateTrustedAuthToken(e.jwtToken,e.trustedReservedSession):this.client?.updateAuthToken(e.jwtToken):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 Zr()??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)}else 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;n?.onExplicitOfflineChange?n.onExplicitOfflineChange(e,t):super.onExplicitOfflineChange(e,t)}async waitForReconnect(e){if(e?.aborted)return;let t=this.host.runtimeSource?.nativeConnection;t?.waitForReconnect?await t.waitForReconnect(e):!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`;function Xl(e){let t=2166136261;for(let n of Ke(e))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(16)}function Zl(e,t={}){try{return(t.storage??globalThis.sessionStorage).getItem(Yl)!==e}catch{return!0}}function Ql(e,t={}){return(()=>{try{(t.storage??globalThis.sessionStorage).setItem(Yl,e)}catch{}(t.reload??(()=>globalThis.location.reload()))()})()}var $l=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,n=new Promise(e=>t=e);this.pageAway={left:e,reopened:n,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);else{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),l(t,k(this.host.config));let n,r=this.host.runtimeSource.createBrowserWorkerConnection({config:t,schema:e.schema,client:e.client,onAuthFailure:t=>{ct(e.client,t),this.host.markUnauthenticated(t)},onAuthRestored:()=>this.host.clearAuthError(),onExplicitOfflineChange:e=>this.setExplicitOffline(r,e),onRemoteLinkChange:(e,t)=>this.setWorkerRemoteLink(r,e,t),onFailure:e=>this.observeConnectionFailure(r,s(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r),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,s(e)),this.connection}),this.disconnected){let e=this.connectionReady;this.enqueueTransportTransition(async()=>{await e,await r.disconnect()}).catch(()=>void 0)}return r}observeConnectionFailure(e,t){if(this.shutdownFailure?.connection===e){t instanceof Qe&&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 Qe||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof Qe||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=Xl(t.schema);Zl(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(()=>Ql(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()=>{this.connection!==e||this.shutdownStarted||this.dbClosing||this.storageReset||(this.admissionRefused(e)?(await this.retryConfigurationAdmission(e),await this.connectionReady):this.connectionError instanceof Qe&&(this.reopenFailedFollower(),await this.connectionReady))}).catch(e=>{this.connectionError??=s(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.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(eu(this.host.config)),tu(this.host.config)),this.disconnected=!1,this.publishExplicitOfflineState()}),this.disconnected||this.resolveReconnectWaiters()}updateAuth(e){let t={...this.host.config,...e.mode===`bearer`?{jwtToken:e.jwtToken,cookieSession:void 0}:{jwtToken:void 0,cookieSession:e.cookieSession}};l(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Ui(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(eu(t)),tu(t)).catch(e=>{this.observeConnectionFailure(n,s(e))})}async deleteClientStorage(){if(this.storageReset)return this.storageReset;!this.connection&&!this.getCurrentClient()&&this.getClient({});let e=this.connection;if(e&&this.heldTooLong&&this.admissionRefused(e)&&await this.retryConfigurationAdmission(e),await this.ensureReady(`runtime`),this.storageReset)return this.storageReset;if(!this.connection)throw Error(`deleteClientStorage(): the browser worker is not connected`);let t=await this.connection.deleteStorage();return await this.storageReset,t}async storePendingUploads(){if(this.connection&&!this.storageReset)return await this.connection.storePendingUploads?.().catch(()=>void 0)??void 0}isUsable(){return!this.shutdownStarted&&!this.storageReset&&!this.storageResetError}async openInspectorControlPort(e){if(await Ja(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??=s(e)})}reopenFailedFollower(){this.recoverableConnectionFailure&&(this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.connectionError=null,this.initialExplicitOfflineStateKnown=!1,this.recoverableConnectionFailure=!1,this.openBrowserWorkerConnection())}reloadAfterStorageInvalidation(e){this.connection===e&&(this.connectionError=Error(`IndexedDB storage was externally invalidated`),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 Qe&&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 Qe&&u(e),e)}},async()=>{if(o)throw o;if(t?.resetReason||!i)return;let e=!1,n;await Promise.race([(async()=>{try{let e=a?.getRuntime();if(!e)s?await i.retire():await i.returnWithHighWater(i.confirmedTxTime);else if(!e.quiesceForegroundTxTimeHighWater)await i.retire();else{let n=await e.quiesceForegroundTxTimeHighWater();if(t?.resetReason)return;t?.leaseWorkerReplaced&&i.releaseAfterWorkerReplacement?i.releaseAfterWorkerReplacement(Error(`Foreground lease owner was replaced`)):s?await i.retire():await i.returnWithHighWater(n)}}catch(r){if(r===t?.resetReason)return;throw e=!0,n=o??r,await i.retire().catch(()=>void 0),n}})(),l.then(()=>{if(e)throw n;if(o)throw o})])},()=>{this.detachClient()?.discard()},()=>super.shutdown(),()=>t?.resetReason?void 0:e?.shutdown(),()=>this.storageReset??void 0,()=>{if(o)throw o}])}finally{this.shutdownFailure=null,this.connectionScope===t&&(this.connectionScope=null)}}resolveReconnectWaiters(){let e=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let t of e)t()}rejectReconnectWaiters(e){let t=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let n of t)n(e)}setExplicitOffline(e,t){this.connection===e&&(this.disconnected=t,this.publishExplicitOfflineState(),t||this.resolveReconnectWaiters())}transportLinkState(){return this.heldTooLong?`unavailable`:this.connectionError&&this.admissionRefused(this.connection)?`connecting`:this.connectionError?`unavailable`:this.workerRemoteLink}onTransportLinkStateChange(e,t){t.aborted||(this.workerRemoteLinkListeners.add(e),t.addEventListener(`abort`,()=>this.workerRemoteLinkListeners.delete(e),{once:!0}))}transportLinkStatus(){if(this.heldTooLong)return K(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return ds;if(this.connectionError)return K(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?ds:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return fs;case`unavailable`:return K(`network`);default:return ds}}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 eu(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function tu(e){return nt({...e,trustedReservedSession:k(e)})?.claims??{}}var nu=new WeakMap,ru=new WeakSet;function iu(e){return ru.has(typeof e?.current==`function`?e.current():e)}async function au(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=nu.get(e);if(n)return await n(t);if(iu(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 ou=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}},su=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}},cu=30;function lu(e){return e??{type:`persistent`}}function uu(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function du(e){let t=lu(e.driver);return uu((t.type===`persistent`?t.dbName:void 0)??e.dbName)??B(e)}function fu(e){return Wi(e,du(e))}function pu(e){if(!e)return;let t=e;oe(t.tier);let n={};v(t.tier)&&(n.tier=t.tier);let r=w(t.firstLoadRemoteWaitMs);r!==void 0&&(n.firstLoadRemoteWaitMs=r),t.branch!==void 0&&(n.branch=t.branch),t.base!==void 0&&(n.base=t.base);let i=t.splices;if(i!==void 0){if(!Array.isArray(i)||!i.every(e=>typeof e==`string`))throw Error(`splices must be an array of column names.`);i.length>0&&(n.splices=[...i])}let a=t.backlogRows;return a!==void 0&&(is(a,`backlogRows`),n.backlogRows=a),rt(e)&&(n.tier=`local-only`),n}var mu=new WeakMap,hu=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getDeviceAccountProof.getLocalFirstIdentityProof.onAuthChanged.onMutationError.textAnchors.getSyncStatus.getPendingUploadRows.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 gu(e){let t=mu.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function _u(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 vu(e,t,n,r){let i=W(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],_u(e,t).column_type)]))}}function yu(e,t,n,r){let i=vu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:vu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:vu(e,t,r,`schema`)}}}function bu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:vu(e,t,r,`table`)}}function xu(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:yu(e,t,r,i)}}function Su(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 Cu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function wu(e){if(!e)return e;let t=e.split(`
|
|
2
|
+
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{$ as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as D,N as O,Nt as ee,O as te,Ot as ne,P as re,Pt as ie,Q as ae,R as oe,Rt as se,S as ce,St as le,T as ue,Tt as k,U as A,Ut as de,V as fe,Vt as j,W as pe,Wt as me,X as he,Xt as ge,Y as _e,Yt as ve,Z as ye,Zt as be,_ as xe,_t as Se,an as Ce,at as M,b as we,bt as N,dt as Te,en as Ee,et as De,ft as Oe,g as ke,gt as Ae,h as je,ht as Me,in as Ne,it as Pe,j as Fe,jt as Ie,k as Le,kt as Re,m as ze,mt as Be,nn as Ve,nt as He,on as Ue,ot as We,pt as Ge,q as Ke,qt as qe,rn as Je,rt as Ye,st as Xe,t as Ze,tn as Qe,tt as $e,ut as et,v as tt,vt as nt,w as rt,wt as it,x as at,xt as P,y as ot,yt as st,z as ct,zt as lt}from"./src-4JwhxZaW.js";var F=e(Ue(),1),ut=Ce(),dt=new WeakMap;function ft(e){let t=dt.get(e)??-2;if(!Number.isSafeInteger(t))throw Error(`Inspector request identifiers exhausted`);return dt.set(e,t-1),t}function pt(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&&Ve(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=ft(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=ft(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 mt=BigInt(2**32-1),ht=BigInt(32);function gt(e,t=!1){return t?{h:Number(e&mt),l:Number(e>>ht&mt)}:{h:Number(e>>ht&mt)|0,l:Number(e&mt)|0}}function _t(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=gt(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}var vt=(e,t,n)=>e>>>n,yt=(e,t,n)=>e<<32-n|t>>>n,bt=(e,t,n)=>e>>>n|t<<32-n,xt=(e,t,n)=>e<<32-n|t>>>n,St=(e,t,n)=>e<<64-n|t>>>n-32,Ct=(e,t,n)=>e>>>n-32|t<<64-n;function wt(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Tt=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Et=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Dt=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ot=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,kt=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),At=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,jt=_t(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),Mt=jt[0],Nt=jt[1],Pt=new Uint32Array(80),Ft=new Uint32Array(80),It=class extends lt{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)Pt[n]=e.getUint32(t),Ft[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=Pt[e-15]|0,n=Ft[e-15]|0,r=bt(t,n,1)^bt(t,n,8)^vt(t,n,7),i=xt(t,n,1)^xt(t,n,8)^yt(t,n,7),a=Pt[e-2]|0,o=Ft[e-2]|0,s=bt(a,o,19)^St(a,o,61)^vt(a,o,6),c=Dt(i,xt(a,o,19)^Ct(a,o,61)^yt(a,o,6),Ft[e-7],Ft[e-16]),l=Ot(c,r,s,Pt[e-7],Pt[e-16]);Pt[e]=l|0,Ft[e]=c|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=bt(u,d,14)^bt(u,d,18)^St(u,d,41),v=xt(u,d,14)^xt(u,d,18)^Ct(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=kt(_,v,b,Nt[e],Ft[e]),S=At(x,g,t,y,Mt[e],Pt[e]),C=x|0,w=bt(n,r,28)^St(n,r,34)^St(n,r,39),T=xt(n,r,28)^Ct(n,r,34)^Ct(n,r,39),E=n&i^n&o^i&o,D=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=wt(c|0,l|0,S|0,C|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let O=Tt(C,T,D);n=Et(O,S,w,E),r=O|0}({h:n,l:r}=wt(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=wt(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=wt(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=wt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=wt(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=wt(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=wt(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=wt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){me(Pt,Ft)}destroy(){me(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Lt=class extends It{Ah=a[0]|0;Al=a[1]|0;Bh=a[2]|0;Bl=a[3]|0;Ch=a[4]|0;Cl=a[5]|0;Dh=a[6]|0;Dl=a[7]|0;Eh=a[8]|0;El=a[9]|0;Fh=a[10]|0;Fl=a[11]|0;Gh=a[12]|0;Gl=a[13]|0;Hh=a[14]|0;Hl=a[15]|0;constructor(){super(64)}},Rt=C(()=>new Lt,ve(3)),zt=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0});function Bt(e){return zt.encode(e)}function Vt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ht(e,t=!1){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw Error(`invalid base64url`);let n=`=`.repeat((4-e.length%4)%4),r=atob(e.replace(/-/g,`+`).replace(/_/g,`/`)+n),i=Uint8Array.from(r,e=>e.charCodeAt(0));if(!t&&Vt(i)!==e)throw Error(`non-canonical base64url`);return i}function Ut(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function Wt(e){let t=Ut(e.subarray(0,16));return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Gt=`jazz-auth-v1:`,Kt=32,qt=/^[A-Za-z0-9_-]{43}$/,Jt=class extends Error{constructor(e){super(e),this.name=`SecretFormatError`}};function Yt(e){if(e.byteLength!==Kt)throw new Jt(`A device account key must contain exactly ${Kt} bytes`);return`${Gt}${Vt(e)}`}function Xt(e){if(typeof e!=`string`||!e.startsWith(`jazz-auth-v1:`))throw new Jt(`A device account key must start with ${Gt}`);let t=e.slice(13);if(!qt.test(t))throw new Jt(`A device account key must use 43 unpadded base64url characters`);let n;try{n=Ht(t,!0)}catch{throw new Jt(`A device account key is not valid base64url`)}if(n.byteLength!==Kt||Yt(n)!==e)throw new Jt(`A device account key is not canonical`);return n}var Zt=BigInt(0),Qt=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 en(e){if(typeof e==`bigint`){if(!cn(e))throw Error(`positive bigint expected, got `+e)}else _(e);return e}function tn(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?Zt:BigInt(`0x`+e)}function nn(e){return tn(de(e))}function rn(e){return tn(de(sn(j(e)).reverse()))}function an(e,t){_(t),e=en(e);let n=qe(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function on(e,t){return an(e,t).reverse()}function sn(e){return Uint8Array.from(e)}var cn=e=>typeof e==`bigint`&&Zt<=e;function ln(e,t,n){return cn(e)&&cn(t)&&cn(n)&&t<=e&&e<n}function un(e,t,n,r){if(!ln(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}var dn=e=>(Qt<<BigInt(e))-Qt;function fn(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)}function pn(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 I=BigInt(0),L=BigInt(1),mn=BigInt(2),hn=BigInt(3),gn=BigInt(4),_n=BigInt(5),vn=BigInt(7),yn=BigInt(8),bn=BigInt(9),xn=BigInt(16);function R(e,t){let n=e%t;return n>=I?n:t+n}function Sn(e,t,n){let r=e;for(;t-->I;)r*=r,r%=n;return r}function Cn(e,t){if(e===I)throw Error(`invert: expected non-zero number`);if(t<=I)throw Error(`invert: expected positive modulus, got `+t);let n=R(e,t),r=t,i=I,a=L,o=L,s=I;for(;n!==I;){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!==L)throw Error(`invert: does not exist`);return R(i,t)}function wn(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Tn(e,t){let n=(e.ORDER+L)/gn,r=e.pow(t,n);return wn(e,r,t),r}function En(e,t){let n=(e.ORDER-_n)/yn,r=e.mul(t,mn),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,mn),i),s=e.mul(a,e.sub(o,e.ONE));return wn(e,s,t),s}function Dn(e){let t=Rn(e),n=On(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+vn)/xn;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 wn(e,p,t),p}}function On(e){if(e<hn)throw Error(`sqrt is not defined for small field`);let t=e-L,n=0;for(;t%mn===I;)t/=mn,n++;let r=mn,i=Rn(e);for(;Fn(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Tn;let a=i.pow(r,t),o=(t+L)/mn;return function(e,r){if(e.is0(r))return r;if(Fn(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=L<<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 kn(e){return e%gn===hn?Tn:e%yn===_n?En:e%xn===bn?Dn(e):On(e)}var An=(e,t)=>(R(e,t)&L)===L,jn=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Mn(e){return fn(e,jn.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,BYTES:`number`,BITS:`number`})),e}function Nn(e,t,n){if(n<I)throw Error(`invalid exponent, negatives unsupported`);if(n===I)return e.ONE;if(n===L)return t;let r=e.ONE,i=t;for(;n>I;)n&L&&(r=e.mul(r,i)),i=e.sqr(i),n>>=L;return r}function Pn(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 Fn(e,t){let n=(e.ORDER-L)/mn,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 In(e,t){t!==void 0&&_(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}var Ln=class{ORDER;BITS;BYTES;isLE;ZERO=I;ONE=L;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=I)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}=In(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 R(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof e);return I<=e&&e<this.ORDER}is0(e){return e===I}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&L)===L}neg(e){return R(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return R(e*e,this.ORDER)}add(e,t){return R(e+t,this.ORDER)}sub(e,t){return R(e-t,this.ORDER)}mul(e,t){return R(e*t,this.ORDER)}pow(e,t){return Nn(this,e,t)}div(e,t){return R(e*Cn(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 Cn(e,this.ORDER)}sqrt(e){return this._sqrt||=kn(this.ORDER),this._sqrt(this,e)}toBytes(e){return this.isLE?on(e,this.BYTES):an(e,this.BYTES)}fromBytes(e,t=!1){j(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?rn(e):nn(e);if(o&&(s=R(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return Pn(this,e)}cmov(e,t,n){return n?t:e}};function Rn(e,t={}){return new Ln(e,t)}var zn=BigInt(0),Bn=BigInt(1);function Vn(e,t){let n=t.negate();return e?n:t}function Hn(e,t){let n=Pn(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Un(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function Wn(e,t){Un(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:dn(e),maxNumber:i,shiftBy:BigInt(e)}}function Gn(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+=Bn);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}}var Kn=new WeakMap,qn=new WeakMap;function Jn(e){return qn.get(e)||1}function Yn(e){if(e!==zn)throw Error(`invalid wNAF`)}var Xn=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>zn;)t&Bn&&(n=n.add(r)),r=r.double(),t>>=Bn;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=Wn(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=Wn(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Gn(n,e,a);n=o,c?i=i.add(Vn(u,t[d])):r=r.add(Vn(l,t[s]))}return Yn(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=Wn(e,this.bits);for(let e=0;e<i.windows&&n!==zn;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=Gn(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return Yn(n),r}getPrecomputes(e,t,n){let r=Kn.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),Kn.set(t,r))),r}cached(e,t,n){let r=Jn(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=Jn(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Un(t,this.bits),qn.set(e,t),Kn.delete(e)}hasCache(e){return Jn(e)!==1}};function Zn(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Mn(t),t}return Rn(e,{isLE:n})}function Qn(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>zn))throw Error(`CURVE.${e} must be positive bigint`)}let i=Zn(t.p,n.Fp,r),a=Zn(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 $n(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}var er=BigInt(0),z=BigInt(1),tr=BigInt(2),nr=BigInt(8);function rr(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 ir(e,t={}){let n=Qn(`edwards`,e,t,t.FpFnLE),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o}=a;fn(t,{},{uvRatio:`function`});let s=tr<<BigInt(i.BYTES*8)-z,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:er}}});if(!rr(r,a,a.Gx,a.Gy))throw Error(`bad curve params: generator point`);function u(e,t,n=!1){let r=n?z:er;return un(`coordinate `+e,t,r,s),t}function d(e){if(!(e instanceof m))throw Error(`EdwardsPoint expected`)}let f=pn((e,t)=>{let{X:n,Y:i,Z:a}=e,o=e.is0();t??=o?nr:r.inv(a);let s=c(n*t),l=c(i*t),u=r.mul(a,t);if(o)return{x:er,y:z};if(u!==z)throw Error(`invZ was invalid`);return{x:s,y:l}}),p=pn(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),p=c(l*t);if(c(d*c(p+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,z,c(a.Gx*a.Gy));static ZERO=new m(er,z,z,er);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,z,c(t*n))}static fromBytes(e,t=!1){let n=r.BYTES,{a:i,d:o}=a;e=sn(j(e,n,`point`)),$t(t,`zip215`);let u=sn(e),d=e[n-1];u[n-1]=d&-129;let f=rn(u);un(`point.y`,f,er,t?s:r.ORDER);let p=c(f*f),h=c(p-z),g=c(o*p-i),{isValid:_,value:v}=l(h,g);if(!_)throw Error(`bad point: invalid y coordinate`);let y=(v&z)===z,b=!!(d&128);if(!t&&v===er&&b)throw Error(`bad point: x=0 and x_0=1`);return b!==y&&(v=c(-v)),m.fromAffine({x:v,y:f})}static fromHex(e,t=!1){return m.fromBytes(qe(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(tr),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(tr*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),y=c(p*f);return new m(g,_,y,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),E=c(b*x);return new m(C,w,E,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===er?m.ZERO:this.is0()||e===z?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===z?this:this.multiplyUnsafe(o)}toBytes(){let{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&z?128:0,n}toHex(){return de(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let h=new Xn(m,i.BITS);return m.BASE.precompute(8),m}function ar(e,t,n={}){if(typeof t!=`function`)throw Error(`"hash" function param is required`);fn(n,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,mapToCurve:`function`});let{prehash:r}=n,{BASE:i,Fp:a,Fn:o}=e,s=n.randomBytes||ge,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if($t(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e});function u(e){return o.create(rn(e))}function d(e){let n=b.secretKey;j(e,b.secretKey,`secretKey`);let r=j(t(e),2*n,`hashedSecretKey`),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}function f(e){let{head:t,prefix:n,scalar:r}=d(e),a=i.multiply(r);return{head:t,prefix:n,scalar:r,point:a,pointBytes:a.toBytes()}}function p(e){return f(e).pointBytes}function m(e=Uint8Array.of(),...n){let i=h(...n);return u(t(l(i,j(e,void 0,`context`),!!r)))}function g(e,t,n={}){e=j(e,void 0,`message`),r&&(e=r(e));let{prefix:a,scalar:s,pointBytes:c}=f(t),l=m(n.context,a,e),u=i.multiply(l).toBytes(),d=m(n.context,u,c,e),p=o.create(l+d*s);if(!o.isValid(p))throw Error(`sign failed: invalid s`);let g=h(u,o.toBytes(p));return j(g,b.signature,`result`)}let _={zip215:!0};function v(t,n,a,o=_){let{context:s,zip215:c}=o,l=b.signature;t=j(t,l,`signature`),n=j(n,void 0,`message`),a=j(a,b.publicKey,`publicKey`),c!==void 0&&$t(c,`zip215`),r&&(n=r(n));let u=l/2,d=t.subarray(0,u),f=rn(t.subarray(u,l)),p,h,g;try{p=e.fromBytes(a,c),h=e.fromBytes(d,c),g=i.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let v=m(s,h.toBytes(),p.toBytes(),n);return h.add(p.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()}let y=a.BYTES,b={secretKey:y,publicKey:y,signature:2*y,seed:y};function S(e=s(b.seed)){return j(e,b.seed,`seed`)}function C(e){return x(e)&&e.length===o.BYTES}function w(t,n){try{return!!e.fromBytes(t,n)}catch{return!1}}let T={getExtendedPublicKey:f,randomSecretKey:S,isValidSecretKey:C,isValidPublicKey:w,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 o=i?a.div(z+n,z-n):a.div(n-z,n+z);return a.toBytes(o)},toMontgomerySecret(e){let n=b.secretKey;j(e,n);let r=t(e.subarray(0,n));return c(r).subarray(0,n)}};return Object.freeze({keygen:$n(S,p),getPublicKey:p,sign:g,verify:v,utils:T,Point:e,lengths:b})}var or=BigInt(1),sr=BigInt(2),cr=BigInt(5),lr=BigInt(8),ur=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),dr={p:ur,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:lr,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function fr(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=ur,o=e*e%a*e%a,s=Sn(Sn(o,sr,a)*o%a,or,a)*e%a,c=Sn(s,cr,a)*s%a,l=Sn(c,t,a)*c%a,u=Sn(l,n,a)*l%a,d=Sn(u,r,a)*u%a;return{pow_p_5_8:Sn(Sn(Sn(Sn(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,sr,a)*e%a,b2:o}}function pr(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var mr=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function hr(e,t){let n=ur,r=R(t*t*t,n),i=fr(e*R(r*r*t,n)).pow_p_5_8,a=R(e*r*i,n),o=R(t*a*a,n),s=a,c=R(a*mr,n),l=o===e,u=o===R(-e,n),d=o===R(-e*mr,n);return l&&(a=s),(u||d)&&(a=c),An(a,n)&&(a=R(-a,n)),{isValid:l||u,value:a}}var gr=ir(dr,{uvRatio:hr});function _r(e){return ar(gr,Rt,Object.assign({adjustScalarBytes:pr},e))}var vr=_r({}),yr=`urn:jazz:local-first`,br=`jazz-auth-sign-v1`,xr=Bt(`jazz-auth-key-v1`),Sr=3600,Cr=class extends Error{constructor(e){super(e),this.name=`LocalFirstTokenError`}};function wr(e,t){let n=new Uint8Array(e.length+t.length);n.set(e),n.set(t,e.length);let r=se(n).slice(0,16);return r[6]=r[6]&15|80,r[8]=r[8]&63|128,Wt(r)}var Tr=Uint8Array.from([107,167,184,16,157,173,17,209,128,180,0,192,79,212,48,200]),Er=[/^([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 Dr(e){if(typeof e!=`string`||e.length===0)throw TypeError(`audience must be a non-empty string`);for(let t of Er){let n=t.exec(e);if(n)return n.slice(1).join(`-`).toLowerCase()}return wr(Tr,Bt(e))}function Or(e){let t=Xt(e),n=Bt(br),r=new Uint8Array(n.length+t.length);return r.set(n),r.set(t,n.length),Rt(r).slice(0,32)}function kr(e){return wr(xr,e)}var Ar=()=>Math.floor(Date.now()/1e3);function jr(e,t){let n=Dr(t.audience),r=t.ttlSeconds??Sr;if(!Number.isSafeInteger(r)||r<=0)throw new Cr(`ttlSeconds must be a positive integer`);let i=t.now??Ar();if(!Number.isSafeInteger(i)||i<0)throw new Cr(`now must be a non-negative integer`);let a=Or(e),o=vr.getPublicKey(a),s=Vt(Bt(JSON.stringify({alg:`EdDSA`,typ:`JWT`}))),c=Vt(Bt(JSON.stringify({iss:yr,sub:kr(o),aud:n,jazz_pub_key:Vt(o),iat:i,exp:i+r})));return`${s}.${c}.${Vt(vr.sign(Bt(`${s}.${c}`),a))}`}var Mr=Gt,Nr=Xt;function Pr(e){return Nr(e),e.slice(Mr.length)}function B(e){return e.appId?.trim()||e.scope?.trim()||(e.serverUrl?Ir(e.serverUrl):Fr)}var Fr=`local`;function Ir(e){let t;try{t=new be(De(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 Lr(){return import.meta.url}function Rr(){let e=import.meta.url;return new URL(`../worker/jazz-broker-worker.js`,e).href}function zr(){return null}function Br(){return null}function Vr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`}function Hr(e){let t=new URL(e).protocol;return t===`http:`||t===`https:`||t===`blob:`}function Ur(e){return new URL(`/`,e).href}function Wr(e,t){try{return new URL(e).href}catch{}if(t)try{return new URL(e,t).href}catch{}return e}function Gr(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 Kr(e,t){try{return new URL(e).href}catch{}return t?new URL(e,t).href:null}function qr(e,t,n){return!t||Vr(e)||!n&&Hr(t)?null:new URL(`jazz_wasm_bg.wasm`,Ur(t)).href}function Jr(e){return e?.wasmModule?{module:e.wasmModule}:e?.wasmSource?{module:e.wasmSource}:null}function Yr(e,t,n){if(n?.wasmUrl)return Gr(Wr(n.wasmUrl,t),n);if(n?.baseUrl){let e=Kr(n.baseUrl,t);if(e)return Gr(new URL(`jazz_wasm_bg.wasm`,e).href,n)}return qr(typeof e==`function`?e():e,t,!1)}function Xr(e,t,n){if(n?.brokerWorkerUrl)return Gr(Wr(n.brokerWorkerUrl,t),n);if(n?.baseUrl){let e=Kr(n.baseUrl,t);if(e)return Gr(new URL(`worker/jazz-broker-worker.js`,e).href,n)}return!t||Vr(e)?Gr(new URL(`../worker/jazz-broker-worker.js`,e).href,n):Gr(new URL(`worker/jazz-broker-worker.js`,Ur(t)).href,n)}function Zr(){let e=typeof process<`u`;return Qr(e?{}.VITE_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.NEXT_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(e?{}.EXPO_PUBLIC_JAZZ_TELEMETRY_COLLECTOR_URL:void 0)??Qr(void 0)}function Qr(e){return e?.trim()||void 0}var $r=`modulepreload`,ei=function(e,t){return new URL(e,t).href},ti={},ni=function(e){return e.pathname.endsWith(`.css`)},ri=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},ii=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=ei(t,n);let r=s(t),i=ni(r);return ri(ti,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:$r,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ai=new WeakMap,oi=256,si=5e3,ci=1,li={TRACE:1,DEBUG:5,INFO:9,WARN:13,ERROR:17};function ui(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 di(e){if(!e.collectorUrl)return()=>void 0;let t={traceUrl:ui(e.collectorUrl,`traces`),logUrl:ui(e.collectorUrl,`logs`)},{runtimeThread:n,wasmModule:r}=e;if(!hi(r))return console.warn(`[jazz] WASM telemetry unavailable: trace entry hooks are missing.`),()=>void 0;let i=ai.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 fi(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},ai.set(r,i);let a=()=>{let e=r.drainTraceEntries();Array.isArray(e)&&e.length!==0&&pi(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),fi(r,i)}catch(e){if(s)try{r.setTraceEntryCollectionEnabled(!1)}catch{}try{i.unsubscribe?.()}catch{}throw i.unsubscribe=null,ai.get(r)===i&&ai.delete(r),e}}function fi(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&&pi(t,n)}catch(e){i??=e}finally{try{e.setTraceEntryCollectionEnabled(!1)}catch(e){i??=e}finally{t.unsubscribe=null,mi(t),!i&&ai.get(e)===t&&ai.delete(e)}}}if(i)throw i}}function pi(e,t){e.exportTail=e.exportTail.catch(()=>void 0).then(async()=>{e.exporter||=_i(e.identity.traceUrl,e.identity.logUrl);try{let n=await e.exporter;for(let r of t)try{gi(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 mi(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 hi(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 gi(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":xi(n.fields)};e.tracer.startSpan(n.name||`wasm span`,{kind:ci,startTime:n.startUnixNano,attributes:bi(n.fields)?{...vi(n.fields),...r}:r}).end(n.endUnixNano)}else if(n.kind===`log`){let r={"jazz.runtime_thread":t,"jazz.log.sequence":n.sequence,"jazz.log.target":n.target,"jazz.log.fields":xi(n.fields)};e.logger.emit({timestamp:n.timestampUnixNano,severityNumber:yi(n.level),severityText:n.level,body:n.message,attributes:bi(n.fields)?{...vi(n.fields),...r}:r})}else e.logger.emit({severityNumber:li.WARN,severityText:`WARN`,body:`Dropped ${n.count} WASM telemetry records`,attributes:{"jazz.runtime_thread":t,"jazz.telemetry.dropped_count":n.count}})}async function _i(e,t){let[{OTLPTraceExporter:n},{BasicTracerProvider:r,BatchSpanProcessor:i},{OTLPLogExporter:a},{LoggerProvider:o,BatchLogRecordProcessor:s},{resourceFromAttributes:c}]=await Promise.all([ii(()=>import(`./esm-k373aadI.js`),__vite__mapDeps([0,1,2,3]),import.meta.url),ii(()=>import(`./esm-DZrCzNXM.js`),__vite__mapDeps([4,5,6,2,7,3]),import.meta.url),ii(()=>import(`./esm-B_xpsQL2.js`),__vite__mapDeps([8,1,2,3]),import.meta.url),ii(()=>import(`./esm-CE7mSo95.js`),__vite__mapDeps([9,2,5,6,7,3]),import.meta.url),ii(()=>import(`./esm-CcBEG-yV.js`).then(e=>e.t),__vite__mapDeps([5,6,2]),import.meta.url)]),l=c({"service.name":`jazz-browser`,"telemetry.sdk.language":`webjs`}),u={maxExportBatchSize:oi,maxQueueSize:si,scheduledDelayMillis:1e3},d=new r({resource:l,spanProcessors:[new i(new n({url:e}),u)]}),f=new o({resource:l,processors:[new s(new a({url:t}),u)]});return{tracer:d.getTracer(`jazz-wasm.tracing`),logger:f.getLogger(`jazz-wasm.tracing`),shutdown:async()=>{await Promise.all([typeof d.shutdown==`function`?d.shutdown():void 0,typeof f.shutdown==`function`?f.shutdown():void 0])}}}function vi(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))n.startsWith(`jazz.`)||r!=null&&(t[n]=typeof r==`string`||typeof r==`number`||typeof r==`boolean`?r:JSON.stringify(r));return t}function yi(e){switch(e.toUpperCase()){case`TRACE`:return li.TRACE;case`DEBUG`:return li.DEBUG;case`INFO`:return li.INFO;case`WARN`:case`WARNING`:return li.WARN;case`ERROR`:return li.ERROR;default:return 0}}function bi(e){if(!e)return!1;for(let t in e)return!0;return!1}function xi(e){return bi(e)?JSON.stringify(e):`{}`}var Si=`jazz-shared-runtime-v3`,Ci=`idbtree-v1`,wi=new WeakMap;function Ti(e){if(e?.brokerWorkerUrl||e?.baseUrl)return Xr(Lr(),typeof location<`u`?location.href:void 0,e);let t=ki(Lr());return t?e?.wasmVersion?`${t}&jazz-runtime-version=${encodeURIComponent(e.wasmVersion)}`:t:Gr(Wr(Rr(),typeof location<`u`?location.href:void 0),e)}var Ei=/^(.*?\/)node_modules\/\.vite\/(?:.*\/)?deps(?:_[^/]*)?\/[^/]+$/,Di=`worker_file&type=module`,Oi=`jazz-tools/_worker/broker`;function ki(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`http:`&&t.protocol!==`https:`)return;let n=Ei.exec(t.pathname);return n?`${t.origin}${n[1]}@id/${Oi}?${Di}`:void 0}function Ai(e){if(!e)return ji(e);if((e.baseUrl||e.wasmUrl&&!Mi(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=Pi(e);if(t)return{...e,workerWasmAssetIdentity:t};let n=Yr(Lr(),typeof location<`u`?location.href:void 0,e);return n?{...e,wasmUrl:n}:ji(e)}function ji(e){let t=zr();return t?{...e,wasmUrl:t}:e}function Mi(e){return e===zr()}function Ni(e){let t=Ai(e);return JSON.stringify({protocolVersion:Si,workerUrl:Ti(t),wasmAsset:Fi(t)})}function Pi(e){let[t,n]=e.wasmModule?[e.wasmModule,`module`]:e.wasmSource?[e.wasmSource,`source`]:[];if(!t||!n)return;let r=wi.get(t);return r||(r=`${n}:${crypto.randomUUID()}`,wi.set(t,r)),r}function Fi(e){return e?.wasmModule?`module:${e.workerWasmAssetIdentity??`unscoped`}`:e?.wasmSource?`source:${e.workerWasmAssetIdentity??`unscoped`}`:`url:${e?.wasmUrl??`worker-local`}`}function Ii(e,t,n){let r=e.telemetryCollectorUrl?.trim()||void 0;return JSON.stringify({protocolVersion:Si,storageFormatVersion:Ci,appId:B(e),dbName:t,env:e.env??`dev`,schemaHash:n,authClass:Gi(e),workerUrl:Ti(e.runtimeSources),workerAssetScope:Ni(e.runtimeSources),telemetryCollector:r?{traceUrl:ui(r,`traces`),logUrl:ui(r,`logs`)}:void 0,wasmLogLevel:e.logLevel??`warn`})}function Li(e){if(e.adminSecret)return{kind:`system`};let t=nt({appId:B(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:k(e)});return!t||t.authMode===`anonymous`?{kind:`anonymous`}:{kind:`principal`,authMode:Ri(t.authMode),user:Re(t.issuer,t.user_id,t.account_id)}}function Ri(e){return e===`device-account`?`local-first`:e}function zi(e){return e.accountId&&!e.adminSecret?{kind:`account`,account:e.accountId,registry:Bi(e)}:Li(e)}function Bi(e){if(!e.accountRegistryAuthority)throw Error(`Account storage requires its registry authority`);return e.accountRegistryAuthority}function Vi(e){return JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:Li(e),...e.accountId?{registry:Bi(e)}:{}})}function Hi(e){return JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:zi(e)})}function Ui(e,t){if(Hi(e)!==Hi(t)||Vi(e)!==Vi(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 Wi(e,t){let n=JSON.stringify({version:1,appId:B(e),env:e.env??`dev`,auth:zi(e)});return`${t}::jazz-browser-v1::${encodeURIComponent(n)}`}function Gi(e){if(e.adminSecret)return`admin`;let t=nt({appId:B(e),accountId:e.accountId,jwtToken:e.jwtToken,cookieSession:e.cookieSession,trustedReservedSession:k(e)});return!t?.user_id||t.authMode===`anonymous`?`anonymous`:`${Ri(t.authMode)}:${Re(t.issuer,t.user_id,t.account_id)}`}var Ki=`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.`,qi=` 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 Ji(){return`__METRO_GLOBAL_PREFIX__`in globalThis}var Yi=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)}},Xi=1048576,Zi=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 Yi(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){if(this.closed||e.length===0)return;let t=this.inboundRouting.then(()=>this.routeInboundFrames(e));this.inboundRouting=t.catch(e=>{this.closed||this.onError(e)})}schedule(e=!0){this.closed||(this.requestedGeneration+=1,this.running?this.runAgain||=e: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=$i(this.transport.recvWireFrames());e.length>0&&this.sendFrames(e);let t=this.transport.recvAuxiliaryWireFrames;if(!t)return!1;let n=$i(t.call(this.transport,8,Xi));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=$i(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(ea(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 ta()}}};function Qi(e){return e.map(e=>e.slice())}function $i(e){return e.map(ea)}function ea(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 ta(){return new Promise(e=>setTimeout(e,0))}var na=new WeakMap;function ra(e,t){let n=na.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 ia=`jazz-idb-tree`,aa=`pages`,oa=`metadata`,V=`storage-manifest`,sa=`epoch`,ca=`browser-runtime-owner`,la=`browser-worker-epoch-v1`,ua=`jazz-browser-worker-epoch-v1`,da=`replica-node-v1`,fa=`foreground-node-leases-v1`,pa=`jazz-foreground-node-leases-v1`,ma=(1n<<64n)-1n,ha=`current`,ga=1024,_a=2147483648,va={storageEpoch:1,adapterId:`jazz-idb-tree`,adapterFormatVersion:1,requiredCodecIds:[`jazz.sqlite-storage.v1`],pageSize:16384,pageChecksum:`xxh3-64-le`,pageFormatMagic:`IDBTREE\0`,pageFormatVersion:1},ya=class extends Error{databaseName;constructor(e){super(`IndexedDB storage was invalidated: ${e}`),this.databaseName=e,this.name=`IndexedDbStorageInvalidatedError`}},ba=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 xa(e,t){return e?.name===`QuotaExceededError`?new ba(e):e??Error(t)}var Sa=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(aa),t.objectStoreNames.contains(`metadata`)||t.createObjectStore(oa),!t.objectStoreNames.contains(`storage-manifest`)){let e=t.createObjectStore(V);r.transaction&&(e.put(va,sa),e.put(wa().buffer,da))}};let a;try{a=await H(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??Ta(wa()),confirmedTxTime:n?.confirmedTxTime??`0`};return t.active.push(r),Da(r)})}async returnForegroundNodeLease(e,t){if(!Na(e)||!Ia(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(!Na(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(V,`readonly`),n=U(t);try{let r=await H(t.objectStore(V).get(fa));if(await n,r===void 0)return`missing`;let i=Oa(r),a=La(Ta(e));return i.active.some(e=>La(e.node)===a)?`active`:i.reusable.some(e=>La(e.node)===a)?`reusable`:i.retired.some(e=>La(e)===a)?`retired`:`missing`}catch(e){throw await n.catch(()=>void 0),e}}async claimBrowserWorkerEpoch(e,t){if(!Pa(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?ra(t,this.name):null,i=this.db.transaction(V,`readwrite`),a=U(i);if(i.objectStore(V).put({format:ua,epoch:e},la),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,!Pa(e))throw Error(`Invalid browser worker epoch`);this.assertValid();let t=this.db.transaction(V,`readwrite`),n=U(t),r=t.objectStore(V),i=await H(r.get(la));i&&typeof i==`object`&&i.format===`jazz-browser-worker-epoch-v1`&&i.epoch===e&&r.delete(la),await n}async metadata(){this.assertValid();let e=this.db.transaction(oa,`readonly`),t=U(e),n=await H(e.objectStore(oa).get(ha));return await t,n===void 0?null:(Ba(n),n)}async assertStorageManifest(){let e=this.db.transaction(V,`readonly`),t=U(e),n=await H(e.objectStore(V).get(sa));await t,Ha(n)}async claimBrowserRuntimeOwner(e){if(typeof e!=`string`||e.length===0)throw Error(`Invalid browser IndexedDB runtime owner`);let t=this.db.transaction(V,`readwrite`),n=U(t),r=t.objectStore(V),i=await H(r.get(ca));if(i===void 0)r.put(e,ca),await n;else if(i===e)await n;else 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(V,`readonly`),t=U(e),n=await H(e.objectStore(V).get(da));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=Ca(this.db,[V]),n=U(t),r=t.objectStore(V);try{let t=await H(r.get(fa)),i=t===void 0?Ea():Oa(t),a=e(i);return Aa(i),r.put(i,fa),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)Wa(t);if(e.length===0)return[];let t=this.db.transaction(aa,`readonly`),n=U(t),r=t.objectStore(aa),i;try{i=await Promise.all(e.map(e=>H(r.get(e))))}catch(e){throw await n.catch(()=>void 0),e}return await n,i.map((t,n)=>Ra(e[n],t))}async commit(e,t){if(this.assertValid(),Va(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=Ca(this.db,[aa,oa]),i=U(r),a=r.objectStore(aa),o=r.objectStore(oa),s=await H(o.get(ha)),c=s===void 0?0:za(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:ia,formatVersion:1,generation:c+1};Ba(l);try{if(l.rootPageId!==null&&!e.pages.has(l.rootPageId)&&await H(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,ha),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=Ca(this.db,[aa,oa]),t=U(e);e.objectStore(aa).clear(),e.objectStore(oa).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 ya(this.name);for(let t of this.invalidationListeners)t(e)}assertValid(){if(this.invalidated)throw new ya(this.name)}removeInvalidationListeners(){this.db.removeEventListener(`versionchange`,this.handleVersionChange),this.db.removeEventListener(`close`,this.handleUnexpectedClose)}};function Ca(e,t){return e.transaction(t,`readwrite`,{durability:`relaxed`})}function wa(){if(!globalThis.crypto?.getRandomValues)throw Error(`Browser storage requires cryptographic random values for its replica identity`);return ie(globalThis.crypto.getRandomValues(new Uint8Array(16)))}function Ta(e){return e.slice().buffer}function Ea(){return{format:pa,active:[],reusable:[],retired:[]}}function Da(e){return{leaseId:e.leaseId,node:new Uint8Array(e.node).slice(),confirmedTxTime:BigInt(e.confirmedTxTime)}}function Oa(e){return Aa(e),{format:e.format,active:e.active.map(ka),reusable:e.reusable.map(ka),retired:e.retired.map(e=>e.slice(0))}}function ka(e){return{leaseId:e.leaseId,node:e.node.slice(0),confirmedTxTime:e.confirmedTxTime}}function Aa(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]){ja(e);let t=La(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=Ma(e)?La(e):null;if(!t||n.has(t))throw Error(`Invalid IndexedDB foreground node lease pool`);n.add(t)}}function ja(e){if(!e||typeof e!=`object`)throw Error(`Invalid IndexedDB foreground node lease`);let t=e;if(!Na(t.leaseId)||!Ma(t.node)||!Fa(t.confirmedTxTime)||!Ia(BigInt(t.confirmedTxTime)))throw Error(`Invalid IndexedDB foreground node lease`)}function Ma(e){return e instanceof ArrayBuffer&&e.byteLength===16}function Na(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 Pa(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 Fa(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Ia(e){return e>=0n&&e<=ma}function La(e){return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``)}function Ra(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 H(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(xa(e.error,`IndexedDB request failed`))})}function U(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(xa(e.error,`IndexedDB transaction aborted`)),e.onerror=t=>{let r=t.target===e?null:t.target;n(xa(e.error??r?.error??null,`IndexedDB transaction failed`))}})}function za(e){return Ba(e),e.generation}function Ba(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||!Ua(t.pageSize)||t.pageSize!==16384||!Number.isSafeInteger(t.generation)||Number(t.generation)<1||t.rootPageId!==null&&!Ga(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 Va(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(!Ua(t)||t!==16384||!Ga(r))throw Error(`Invalid IndexedDB B-tree commit metadata`);if(n!==null&&(!Ga(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(!Ga(n)||n>=r||a.byteLength>t)throw Error(`Invalid IndexedDB B-tree page commit`);i.add(n)}for(let t of e.deletedPageIds??[])if(!Ga(t)||t>=r||t===n||i.has(t))throw Error(`Invalid IndexedDB B-tree deleted page commit`)}function Ha(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(va).sort();if(n.length!==r.length||n.some((e,t)=>e!==r[t])||t.storageEpoch!==va.storageEpoch||t.adapterId!==va.adapterId||t.adapterFormatVersion!==va.adapterFormatVersion||t.pageSize!==va.pageSize||t.pageChecksum!==va.pageChecksum||t.pageFormatMagic!==va.pageFormatMagic||t.pageFormatVersion!==va.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=va.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 Je(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 Ua(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=ga&&e<=_a&&Number.isInteger(Math.log2(e))}function Wa(e){if(!Ga(e))throw Error(`Invalid IndexedDB B-tree page id: ${e}`)}function Ga(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Ka(){return Error(`Inspector control opening was cancelled`)}function qa(e){try{e.postMessage({type:`close`})}catch{}e.close()}function Ja(e,t){return t?t.aborted?Promise.reject(Ka()):new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(Ka())};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})}):e}var Ya=Object.freeze({intervalMs:3e4,replyMs:3e4}),Xa=1e3,Za=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 c=this.request({type:`init`,sessionClaims:n,...o?{inspectorBinding:o}:{}}),l=(async()=>{await c;let t=await e.connectUpstreamPeer(this.peerAuthority);if(this.closed||this.failed)throw await e.retirePeerTransport(t),this.failed??Error(`Browser follower connection is closed`);this.pump=new Zi(e,t,e=>{let t=Qi(e);this.port.postMessage({type:`frames`,frames:t},t.map(e=>e.buffer))},t=>{let n=s(t);this.failed||this.closed||(e.reportRemoteServerTransportError(n),this.fail(n))},a?e=>{console.debug(`JAZZ_AUX_RELAY`,e.map(e=>({...e,hop:`tab-worker`})))}:void 0);for(let e of this.pendingFrames.splice(0))this.pump.receive(e)})();this.readyPromise=Promise.all([c,l]).then(()=>void 0),this.readyPromise.then(()=>{this.established=!0,this.armWatchdog()},e=>this.fail(s(e)))}async ready(){if(await this.readyPromise,this.failed)throw this.failed;if(this.closed)throw Error(`Browser follower connection is closed`)}getAuthenticatedInspectorAttachmentPhysicalDbName(){return this.inspectorAttachmentPhysicalDbName}async waitForServerConnection(){await this.ready(),await this.request({type:`wait-server`})}async disconnect(){await this.ready(),await this.request({type:`disconnect`})}async deleteStorage(){if(await this.ready(),!this.dbName)throw Error(`Browser storage reset requires its IndexedDB name`);let e=await this.request({type:`prepare-storage-reset`});try{await Sa.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 Ja(this.ready(),e),e?.aborted)throw Ka();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,qa(t.port1))},c=()=>{this.pending.delete(n)&&(o(),r(Ka()))};e?.addEventListener(`abort`,c,{once:!0}),this.armWatchdog();try{this.port.postMessage({type:`open-inspector-control`,id:n,port:t.port2},[t.port2])}catch(e){t.port2.close(),this.fail(s(e))}try{if(await i,e?.aborted)throw o(),Ka();return t.port1}catch(e){throw this.pending.delete(n),o(),e}finally{e?.removeEventListener(`abort`,c)}}async reconnect(e,t){await this.ready(),await this.request({type:`reconnect`,authJson:e,sessionClaims:t}),await this.request({type:`wait-server`}),this.runtime.clearRemoteServerTransportError()}updateAuth(e,t){this.closed||this.failed||this.ready().then(()=>{this.port.postMessage({type:`update-auth`,authJson:e,sessionClaims:t})}).catch(e=>this.fail(s(e)))}async shutdown(e=!1){this.closed||(await this.request({type:`close`,releaseContext:e}),this.dispose(Error(`Browser follower connection is closed`)))}leaveForPageCache(){if(this.closed||this.failed||!this.established||this.hasPendingWork())return!1;try{this.port.postMessage({type:`close`,releaseContext:!0})}catch{}return this.dispose(Error(`Browser follower connection left for the back/forward cache`)),!0}async waitForPendingWrites(){await this.flushLocal(),await this.request({type:`flush-pending-writes`})}async flushLocal(){await this.ready(),await this.pump.flush();let e=this.request({type:`flush-local`});await this.runtime.flushLocalSettlements(),this.port.postMessage({type:`flush-local-observed`}),await e}detachForReconnect(){this.dispose(Error(`Browser follower connection is reconnecting`))}request(e){if(this.failed)return Promise.reject(this.failed);if(this.closed)return Promise.reject(Error(`Browser follower connection is closed`));let t=this.nextRequestId++,n={...e,id:t},r=new Promise((n,r)=>{this.pending.set(t,{type:e.type,resolve:n,reject:r})});this.armWatchdog();try{this.port.postMessage(n)}catch(e){this.fail(s(e))}return r}clearWatchdog(){this.watchdogTimer!==null&&clearTimeout(this.watchdogTimer),this.watchdogTimer=null,this.probeNonce=null,this.watchdogEpoch++}armWatchdog(){this.closed||this.failed||!this.wantsWatchdog()||this.watchdogTimer!==null||this.scheduleWatchdog(Ya.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+Xa){this.sendProbe();return}let e=new Qe(`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(Ya.replyMs,!0);try{this.port.postMessage({type:`runtime-probe`,connectionId:this.connectionId,nonce:e})}catch(e){this.fail(s(e))}}onResume=()=>{this.resumeProbePending=!0,this.sendProbe()};hasPendingWork(){return this.pending.size>0||this.localSettlementsPending||this.resumeProbePending}wantsWatchdog(){return this.hasPendingWork()||this.established&&globalThis.document?.visibilityState===`visible`}onVisibilityChange=()=>{globalThis.document?.visibilityState===`visible`&&this.onResume()};onMessage=e=>{if(this.closed||this.failed)return;let t=e.data;if(t.type===`runtime-pong`){if(t.connectionId!==this.connectionId||t.nonce!==this.probeNonce)return;this.resumeProbePending=!1,this.clearWatchdog(),this.armWatchdog();return}if(t.type===`frames`){this.pump?this.pump.receive(t.frames):this.pendingFrames.push(t.frames);return}if(t.type===`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 Qe(`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(Ve(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(Ve(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(Ve(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()}}},Qa=e=>`jazz:store-generation:${e}`;function $a(e){try{globalThis.localStorage?.setItem(Qa(e),crypto.randomUUID())}catch{}}function eo(e){try{let t=globalThis.localStorage;if(!t)return null;let n=t.getItem(Qa(e));if(n!==null)return n;let r=crypto.randomUUID();return t.setItem(Qa(e),r),r}catch{return null}}function to(e,t){if(t===null)return!1;try{return globalThis.localStorage?.getItem(Qa(e))!==t}catch{return!0}}var no=class extends Error{name=`BrowserWorkerScriptLoadError`};async function ro(e){let t=e.moduleUrl!==null&&ki(e.moduleUrl)!==void 0,n=e.workerUrl?await io(e.workerUrl,e.fetch??globalThis.fetch):null;return new no(`${e.workerUrl?`Jazz's browser worker script ${e.workerUrl} did not load${n?`: ${n}`:``}.`:`Jazz's browser worker script did not load.`}${e.metro?qi: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 io(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 ao(e,t){if(so(e))return new SharedWorker(Ti(e),{type:(oo(e)?null:Br())??`module`,name:t});let n=ki(Lr());if(n)return new SharedWorker(n,{type:`module`,name:t});let r=new SharedWorker(new URL(new URL(`jazz-broker-worker-C_mr9Omd.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:t});if(!(`port`in r))throw r.terminate?.(),Error(Ki);return r}function oo(e){return!!(e?.brokerWorkerUrl||e?.baseUrl)}function so(e){return oo(e)||Br()!==null}function co(e,t,n){if(typeof e.addEventListener!=`function`)return()=>void 0;let r=!0,i=()=>{r&&(a(),ro({workerUrl:so(t)?Ti(t):ki(Lr()),moduleUrl:Lr(),metro:Ji()}).then(n))},a=()=>{r=!1,e.removeEventListener?.(`error`,i)};return e.addEventListener(`error`,i),a}var lo=1e4,uo=8,fo=8,po=25,mo=250,ho=3e5,go=1e3,_o=new Map;function vo(e){if(!(e?.wasmModule||e?.wasmSource))return{runtimeSources:e}}function yo(e,t){return[`jazz-runtime`,t,Ni(e)].join(`:`)}function bo(e,t){return`${e}\u0000${t}`}var xo=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=Ai(e.runtimeSources),n=yo(t,e.dbName),r=bo(n,e.storageOwner);if(_o.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=>ao(t,e),a=Date.now()+lo,o=wo(n),s=0,c=null;for(let l=0;l<uo;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,vo(t),t);if(d.type===`ready`)return d.lease;if(d.type===`worker-closing`){o=To(n,o);break}if(c=d.message,s+=1,s>=fo)throw Error(c);let f=Math.min(po*2**(s-1),mo,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(),lo);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`),_o.set(r,p),c.postMessage({type:`cancel-foreground-node-lease`}),g(h)},a),v=()=>{m&&clearTimeout(m),m=null,x(),p!==null&&_o.get(r)===p&&_o.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(Ve(a.error));return}if(a?.type===`foreground-node-lease-cancelled`){v(),c.close(),g(a.error?Ve(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=co(t,s,e=>{v(),c.close(),g(e)});c.addEventListener(`message`,y),c.addEventListener(`messageerror`,b),c.start(),m=_(),c.postMessage({type:`probe-foreground-node-lease-worker`,attemptId:i,...o?{wasmPrefetch:o}:{}})})}async returnWithHighWater(e){if(this.terminalError)throw this.terminalError;if(e<0n)throw Error(`Invalid foreground transaction high-water`);await this.finish({type:`return-foreground-node-lease`,confirmedTxTime:e.toString()})}async retire(){if(this.terminalError)throw this.terminalError;this.closed||await this.finish({type:`retire-foreground-node-lease`})}abandonAfterWorkerFailure(e){if(!this.terminalError&&(this.terminalError=e,this.finishWaiter?.reject(e),this.finishWaiter=null,!this.closed&&this.port&&(this.listenForFinish(),!this.terminalRequestSent))){this.terminalRequestSent=!0;try{this.port.postMessage({type:`retire-foreground-node-lease`})}catch{this.closeFinishPort()}}}releaseAfterStorageReset(e){this.failFinish(e)}releaseAfterWorkerReplacement(e){this.failFinish(e)}failFinish(e){this.terminalError??=e,this.finishWaiter?.reject(this.terminalError),this.closeFinishPort()}finish(e){if(this.terminalError)return Promise.reject(this.terminalError);if(this.closed)return Promise.reject(Error(`Shared browser foreground lease is already closed`));if(this.finishPromise)return this.finishPromise;let t=this.port;if(!t)return Promise.reject(Error(`Shared browser foreground lease port is unavailable`));this.listenForFinish(),this.finishPromise=new Promise((e,t)=>{this.finishWaiter={resolve:e,reject:t}}),this.terminalRequestSent=!0;try{t.postMessage(e)}catch(e){this.failFinish(s(e))}return this.finishPromise}listenForFinish(){this.listeningForFinish||(this.listeningForFinish=!0,this.port?.addEventListener(`message`,this.onFinishResult),this.port?.addEventListener(`messageerror`,this.onFinishError))}onFinishResult=e=>{let t=e.data;t?.type===`foreground-node-lease-result`&&(t.error?this.failFinish(Ve(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}},So=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=Ai(t.runtimeSources),a=yo(i,t.dbName);this.workerName=a,this.dbName=t.dbName;let o=e=>ao(i,e);this.readyPromise=this.connect(e,{...t,runtimeSources:i},n,a,o).then(()=>void 0,e=>{this.readyError=s(e),this.releaseLivenessLock?.(),r.onFailure(this.readyError)})}holdLivenessLock(){let e=globalThis.navigator?.locks;if(!e)return;let t=`jazz-tab-alive:${crypto.randomUUID()}`,n,r=new Promise(e=>n=e);this.releaseLivenessLock=n;let i=new Promise((n,i)=>{e.request(t,()=>(n(),r)).catch(i)});return i.catch(()=>void 0),{name:t,granted:i}}announceLivenessLock(e,t){e.granted.then(()=>{this.closed||this.worker?.port!==t||t.postMessage({type:`liveness-lock`,name:e.name})},()=>void 0)}async connect(e,t,n,r,i){let a=this.holdLivenessLock(),o=wo(r);for(let s=0;s<uo;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=To(r,o)}throw Error(`Shared browser runtime did not answer after its previous realm closed`)}connectOnce(e,t,n,r,i){let a=i(r);this.worker=a;let o=a.port;return o.start(),new Promise(r=>{let i=!1,c=!1,l=!1,u=Date.now(),d=u+ho,f=typeof document<`u`&&document.hidden,p,m=e=>{i||(i=!0,x(),this.cancelBootstrap===g&&(this.cancelBootstrap=null),r(e))},h=e=>{if(!i){c=!0,m(e),this.worker===a&&(this.worker=null);try{o.postMessage({type:`cancel-runtime-bootstrap`})}catch{w(),o.close()}}},g=()=>h({connected:!1,error:Error(`Shared browser runtime connection is closed`)});this.cancelBootstrap=g;let _=()=>{u=Date.now(),d=u+ho},v=()=>{let e=typeof document<`u`&&document.hidden;f&&!e&&_(),f=e},y=()=>_(),b=()=>{let e=Date.now();(f||e-u>go*2)&&_(),u=e,e>=d?h({connected:!1,error:new Qe(`Shared browser runtime did not finish initialization within five minutes`)}):p=setTimeout(b,Math.min(go,d-e))},x=()=>{clearTimeout(p),p=void 0,typeof document<`u`&&document.removeEventListener(`visibilitychange`,v),typeof window<`u`&&window.removeEventListener(`pageshow`,y)},S=n=>{if(c){if(n.data?.type===`runtime-ready`){if(l)return;l=!0,o.postMessage({type:`close`,id:0,releaseContext:!0});return}if(n.data?.type!==`runtime-bootstrap-cancelled`&&n.data?.type!==`runtime-error`&&n.data?.type!==`worker-closing`&&(n.data?.type!==`result`||n.data.id!==0))return;w(),o.close();return}if(n.data?.type===`worker-alive`)return;if(n.data?.type===`runtime-error`){w(),o.close(),this.worker===a&&(this.worker=null);let e=Ve(n.data.error);this.olderThanStore=e.message===Ee,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,m({connected:!1,error:e});return}if(n.data?.type===`worker-closing`){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1});return}if(n.data?.type!==`runtime-ready`)return;w(),this.cancelBootstrap===g&&(this.cancelBootstrap=null);let r=new Za(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=>{$a(this.dbName),this.callbacks.onStorageReset?.(e)},onStorageInvalidated:()=>{$a(this.dbName),this.callbacks.onStorageInvalidated?.()},onNewerBuild:this.callbacks.onNewerBuild},t.logLevel===`trace`);this.connection=r,r.ready().then(()=>m({connected:!0}),e=>{o.close(),this.connection===r&&(this.connection=null),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})})},C=()=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:Error(`Shared browser runtime port message error`)})},w=()=>{x(),T(),o.removeEventListener(`message`,S),o.removeEventListener(`messageerror`,C)},T=co(a,t.runtimeSources,e=>{w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:e})});o.addEventListener(`message`,S),o.addEventListener(`messageerror`,C),typeof document<`u`&&document.addEventListener(`visibilitychange`,v),typeof window<`u`&&window.addEventListener(`pageshow`,y),p=setTimeout(b,1e3);try{o.postMessage({type:`connect-runtime`,tabId:crypto.randomUUID(),fingerprint:n,options:t})}catch(e){w(),o.close(),this.worker===a&&(this.worker=null),m({connected:!1,error:s(e)})}})}getWorkerRealmId(){return this.connection?.getWorkerRealmId()}ready(){return this.readyPromise.then(()=>{if(this.readyError)throw this.readyError})}async waitForServerConnection(){await this.ready(),await this.connection?.waitForServerConnection()}async updateAuth(e,t){await this.ready(),this.connection?.updateAuth(e,t)}async disconnect(){await this.ready(),await this.connection?.disconnect()}async reconnect(e,t){await this.ready(),await this.connection?.reconnect(e,t)}canRetryInitialConfigurationAdmission(){return this.initialConfigurationAdmissionRejected}waitsForAnotherTab(){return this.heldByAnotherTab}isOlderThanStore(){return this.olderThanStore}leaveForPageCache(){if(this.closed||this.readyError||!this.connection)return!1;let e=eo(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 to(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(),$a(this.dbName);try{return await this.connection?.deleteStorage()}finally{$a(this.dbName)}}async storePendingUploads(){return await this.ready(),this.connection?.storePendingUploads()}async openInspectorControlPort(e){if(await Ja(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&&Co(t,this.workerName,n),t}};function Co(e,t,n){e.addEventListener(`message`,e=>{e.data?.type===`result`&&e.data.workerTerminated===!0&&To(t,n)})}function wo(e){try{let t=Number.parseInt(localStorage.getItem(Eo(e))??`0`,10);return Number.isSafeInteger(t)&&t>=0?t:0}catch{return 0}}function To(e,t){try{let n=Eo(e);return wo(e)===t&&localStorage.setItem(n,String(t+1)),wo(e)}catch{return t+1}}function Eo(e){return`jazz:shared-worker-generation:${e}`}function Do(e){return e.__jazzWindowStorageContexts__||=new Set,e.__jazzWindowStorageContexts__}function Oo(e){return[...new Set([...Do(e)].map(e=>e.namespace))].sort()}function ko(e){return e.length===0?``:` Available namespaces: ${e.join(`, `)}.`}function Ao(e,t){let n=[...Do(e)],r=Oo(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>").${ko(r)}`)}let a=n.find(e=>e.namespace===i);if(!a)throw Error(`No live Jazz storage context matches "${i}".${ko(r)}`);return a.db}var jo=new Map;function Mo(){let e=()=>[...jo.keys()].at(-1)??null;return{version:1,status:()=>e()?.getSyncStatus()??null,pending:()=>[...jo.keys()].reduce((e,t)=>e+t.getSyncStatus().pendingUploads,0),dbs:()=>[...jo].map(([e,t])=>({appId:t,status:e.getSyncStatus()})),waitForSync:async(e={})=>{await Promise.all([...jo.keys()].map(t=>t.waitForSync(e)))}}}function No(e,t){let n=globalThis.window;return!n||n.document===void 0?()=>{}:(jo.set(e,t),zo(n),()=>{jo.delete(e)})}var Po=Symbol.for(`jazz-tools.window-jazz`);function Fo(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 Io=new WeakSet;function Lo(e){let t=e.__jazz;return t===void 0||Ro(t)?!1:(Io.has(e)||(Io.add(e),console.warn(Fo(t))),!0)}function Ro(e){if(!e||typeof e!=`object`)return!1;if(Po in e)return!0;let t=e;return t.version===1&&typeof t.status==`function`}function zo(e){let t=Lo(e),n=(t?void 0:e.__jazz)??{};n[Po]=!0;let r=Object.assign(n,Mo(),{async clearStorage(t){await Ao(e,t).deleteClientStorage()},listLiveStorageNamespaces(){return Oo(e)},async shutdown(t){let n=[...Do(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 Bo=`history.`;function Vo(e){return Ho(e)!==void 0}function Ho(e){return e.startsWith(Bo)?e.slice(8):void 0}var Uo=[{name:`$transactionId`,column_type:{type:`Text`},nullable:!1},{name:`$acceptedAt`,column_type:{type:`Timestamp`},nullable:!1}],Wo=new WeakMap;function W(e,t){let n=Ho(t);if(n===void 0)return e[t];if(Vo(n)||!Object.hasOwn(e,n))return;let r=Wo.get(e);r||Wo.set(e,r=new Map);let i=r.get(t);if(!i){let a=e[n];i={columns:[...a.columns,...Uo],...a.branchBy?{branchBy:a.branchBy}:{}},r.set(t,i)}return i}var Go=class extends Error{constructor(e){super(`Graceful shutdown could not synchronize pending writes; the context remains open`,{cause:e}),this.name=`GracefulShutdownSyncError`}},Ko=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`}},G=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=Ae(e);if(typeof t?.iss!=`string`||typeof t.sub!=`string`||!r(t.iss)||!r(t.sub))throw new G(`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 G(`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 G(`invalid_account_handle`);if(r.delegated)throw new G(`backend_signed_in_account_has_no_token`);if(r.backend||!r.auth)throw new G(`backend_account_requires_backend_host`);let i=await Xo(r.auth,n);if(qo.get(e)!==r)throw new G(`account_logged_out`);if(!Yo(Jo(i),e.identity))throw new G(`credential_identity_changed`);return i}function Qo(e){let t=qo.get(e);if(!t)throw new G(`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 G(`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 G(`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 G(`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,pendingRevision:0});function os(e,t){return e===t?!0:e===null||t===null||e.length!==t.length?!1:e.every((e,n)=>e===t[n])}function ss(e,t){let n=e.lastRejection?{kind:`rejected`,...e.lastRejection}:null;return n?t&&t.at>n.at?t:n:t}function cs(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 ls(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 us=Object.freeze({state:`local-only`}),ds=Object.freeze({state:`connecting`}),fs=Object.freeze({state:`connected`});function K(e,t=e===`network`){return{state:`offline`,reason:e,retrying:t}}function ps(e){switch(e?.phase??`noServer`){case`noServer`:return us;case`offline`:return K(`disconnected`);case`live`:return fs;case`connecting`:case`backoff`:return e.outagePublished?K(`network`):ds;case`awaitingCredential`:return K(`auth`);case`stopped`:return K(`stopped`)}}function ms(e,t){return e.state===t.state?e.state!==`offline`||t.state!==`offline`||e.reason===t.reason&&e.retrying===t.retrying&&e.authReason===t.authReason:!1}function hs(e,t=as,n=null){return{link:e,pendingUploads:t.pending,oldestPendingAt:t.pending===0?null:t.oldestPendingAt,rejected:t.rejected,lastError:ss(t,n),synced:t.pending===0&&(e.state===`connected`||e.state===`local-only`)}}function gs(e,t){return e.pendingUploads===t.pendingUploads&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&ls(e.lastError,t.lastError)&&ms(e.link,t.link)}function _s(e,t){return e.pending===t.pending&&e.oldestPendingAt===t.oldestPendingAt&&e.rejected===t.rejected&&(e.pendingRevision??0)===(t.pendingRevision??0)&&e.lastRejection?.at===t.lastRejection?.at&&e.lastRejection?.code===t.lastRejection?.code}var vs=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 ys(e){if(e.startsWith(`$`))return e;let t=e.indexOf(`.$`);return t>=0?e.slice(t+1):e.split(`.`).at(-1)??e}function bs(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 xs(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 Ss=class extends Error{},Cs=class extends Error{};function ws(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 Cs(`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 Ss(`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(xs(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 Ts(){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 Es=[`$canRead`],Ds=[`$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 Os(e){return Es.includes(e)}function ks(e){return Ds.includes(e)}function As(e){if(e===`$createdBy`||e===`$updatedBy`||e===`$deletedBy`)return Ts();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=Ts();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 js=`__jazz_requireIncludes`;function Ms(e){return Array.isArray(e)?e.filter(e=>P(e)&&typeof e.column==`string`&&typeof e.op==`string`):[]}function Ns(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 Ps(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Fs(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Is(e){if(!P(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!n||!P(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(Fs(r.from)&&Fs(r.to)&&e.length===2)t[n]={from:r.from,to:r.to};else if(Fs(r.fromUtf8)&&Fs(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 Ls(e){let t=P(e)&&typeof e.max_depth==`number`?e.max_depth:NaN;if(!(!P(e)||!Number.isInteger(t)||t<0||typeof e.step_table!=`string`||typeof e.step_current_column!=`string`))return{...P(e)&&e.seed?{seed:Rs(e.seed)}:{},max_depth:t,step_table:e.step_table,step_current_column:e.step_current_column,step_conditions:Ms(e.step_conditions),step_hops:Array.isArray(e.step_hops)?e.step_hops.filter(e=>typeof e==`string`):[]}}function Rs(e){if(!P(e))return{};let t={...typeof e.table==`string`&&e.table.length>0?{table:e.table}:{},conditions:Ms(e.conditions),hops:Array.isArray(e.hops)?e.hops.filter(e=>typeof e==`string`):[],gather:Ls(e.gather),...Array.isArray(e.orderBy)?{orderBy:Ns(e.orderBy)}:{},...typeof e.limit==`number`?{limit:e.limit}:{},...typeof e.offset==`number`?{offset:e.offset}:{}};return P(e.union)&&Array.isArray(e.union.inputs)&&(t.union={inputs:e.union.inputs.flatMap(e=>!P(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Rs(e.input)}])}),t}function zs(){return{conditions:[],includes:{},requireIncludes:!1,select:[],partialSelect:{},orderBy:[],hops:[]}}function Bs(e){let t={...e};return delete t[js],Ws(t)}function Vs(e){return`table`in e&&`conditions`in e&&`includes`in e&&`orderBy`in e}function Hs(e){return`conditions`in e&&`includes`in e&&`select`in e&&`orderBy`in e}function Us(e){if(e===!0)return zs();if(!P(e))return null;if(Vs(e)){let t=Gs(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(Hs(e))return{table:typeof e.table==`string`?e.table:void 0,conditions:Ms(e.conditions),includes:Ws(e.includes),requireIncludes:e[js]===!0,select:Ps(e.select),partialSelect:Is(e.partialSelect??e.select),orderBy:Ns(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:Ls(e.gather)};let t=zs();return t.requireIncludes=e[js]===!0,t.includes=Bs(e),t}function Ws(e){if(!P(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r)continue;let e=Us(r);e&&(t[n]=e)}return t}function Gs(e){let t=P(e)?e:{};if(typeof t.table!=`string`||t.table.length===0)throw Error(`QueryBuilder._build() must include a non-empty table.`);let n=Is(t.partialSelect??t.select);return{table:t.table,conditions:Ms(t.conditions),includes:Ws(t.includes),requireIncludes:t[js]===!0,select:Array.isArray(t.select)?Ps(t.select):Object.keys(n),partialSelect:n,orderBy:Ns(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:Ls(t.gather),...P(t.union)&&Array.isArray(t.union.inputs)?{union:{inputs:t.union.inputs.flatMap(e=>!P(e)||typeof e.label!=`string`?[]:[{label:e.label,input:Rs(e.input)}])}}:{}}}var Ks=`__jazz_include_`;function qs(e){return`${Ks}${e}`}function Js(e,t,n){let r=W(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)e===`*`?a.hasWildcard=!0: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 q(e,t){return t?{scope:t,column:e}:{column:e}}function Ys(e,t,n){let r=W(n,e);if(!r)throw Error(`Unknown table "${e}" in relation projection.`);return[{alias:`id`,expr:{Column:q(`id`,t)}},...r.columns.map(e=>({alias:e.name,expr:{Column:q(e.name,t)}}))]}function Xs(e,t,n){if(n===`id`)return{type:`Uuid`};let r=As(n);if(r)return r;let i=W(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:bs(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?Js(e.toTable,r,c.select):[],u=c.conditions.map(t=>oc(t,r,e.toTable)),d=c.orderBy.map(([e,t])=>[ys(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)?qs(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,r){let i=q(ys(e.column),r),a=ys(e.column),o=Xs(t,n,a);if(!o)throw Error(`Unknown column "${a}" in table "${n}"`);let s=e.value===void 0||e.value;if(e.op===`isNull`){if(typeof s!=`boolean`)throw Error(`"isNull" operator requires a boolean value.`);return s?{IsNull:{column:i}}:{IsNotNull:{column:i}}}if(e.value===null){if(e.op===`eq`)return{IsNull:{column:i}};if(e.op===`ne`)return{IsNotNull:{column:i}}}if(o.type===`Row`&&As(a)){if(e.op!==`eq`&&e.op!==`ne`)throw Error(`Structured author column "${a}" only supports eq/ne operators.`);let i=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).length!==t.length||t.some(t=>!Object.hasOwn(e,t)))throw Error(`Invalid structured author condition for "${a}".`);return e},o=a===`$createdBy`||a===`$updatedBy`||a===`$deletedBy`,s=o?i(e.value,[`account`,`identity`]):void 0,c=i(s?s.identity:e.value,[`issuer`,`subject`]);if(typeof c.issuer!=`string`||typeof c.subject!=`string`||s&&typeof s.account!=`string`)throw Error(`Invalid structured author condition for "${a}".`);Re(c.issuer,c.subject,s?.account);let l={And:[...s?[{column:`${a}.account`,op:`eq`,value:s.account}]:[],{column:`${a}${o?`.identity`:``}.issuer`,op:`eq`,value:c.issuer},{column:`${a}${o?`.identity`:``}.subject`,op:`eq`,value:c.subject}].map(e=>oc(e,t,n,r))};return e.op===`eq`?l:{Not:l}}if(e.op===`in`||e.op===`notIn`){if(!Array.isArray(e.value))throw Error(`"${e.op}" operator requires an array value.`);if(e.value.some(e=>e===null))throw Error(`"${e.op}" does not accept null membership values; use isNull or isNotNull separately.`);let t={In:{left:i,values:e.value.map(e=>({Literal:$s(e,o)}))}};return e.op===`notIn`?{Not:t}:t}let c=e.op===`contains`&&o.type===`Array`?o.element:o,l=sc(e.value)&&e.op===`eq`?{RowId:`Frontier`}:{Literal:$s(e.value,c)};switch(e.op){case`eq`:return{Cmp:{left:i,op:`Eq`,right:l}};case`ne`:return{Cmp:{left:i,op:`Ne`,right:l}};case`gt`:return{Cmp:{left:i,op:`Gt`,right:l}};case`gte`:return{Cmp:{left:i,op:`Ge`,right:l}};case`lt`:return{Cmp:{left:i,op:`Lt`,right:l}};case`lte`:return{Cmp:{left:i,op:`Le`,right:l}};case`contains`:return{Contains:{left:i,right:l}};default:throw Error(`Unknown operator: ${e.op}`)}}function 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:q(i.fromColumn,s),right:q(`id`,c)}:{left:q(`id`,s),right:q(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:ys(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:q(c.fromColumn,e.step_table),right:q(`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:q(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=Gs(JSON.parse(e)),r=ws(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:q(ys(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:ys(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??Gs(JSON.parse(e)),i=ws(t),a=gc(r)?hc(e,t):void 0,o=a?.outputTable??r.table,s=nc(r.select.length>0?Js(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=W(t,e);if(!r)throw Error(`Unknown table "${e}" in schema`);return Js(e,t,n).map(e=>{let t=As(e);if(t)return{name:e,columnType:t};if(Os(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(!W(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=qs(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];l===void 0?u[a.relation.name]=a.relation.isArray?[]:null: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&&(ks(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(!W(e,t))throw Error(`Unknown table "${t}" in schema`);let i=Object.keys(n).length===0?[]:Ec(t,Ws(n),r??ws(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(Ks)),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=>!ks(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:bs(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=3e5;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=Ke(r);if(this.client){if(!this.clientSchema||Ke(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),l(a,k(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:Ke(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 hs(e);let t=this.client?.getRuntime();return hs(e,t?.uploadStatus?.()??as,t?.lastLinkFailure?.()??null)}pendingUploadRows(e){return this.client?.getRuntime()?.pendingUploadRows?.(e)??null}linkStatus(){let{config:e,runtimeSource:t}=this.host;return!e.serverUrl&&t?.nativeConnection?.configured()!==!0?us:this.isExplicitlyOffline()?K(`disconnected`):this.transportLinkStatus()}transportLinkStatus(){let e=this.client?.getRuntime().upstreamLinkStatus?.()??ds;return e.state===`local-only`?ds: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){e.mode===`bearer`?e.jwtToken&&e.trustedReservedSession?this.client?.updateTrustedAuthToken(e.jwtToken,e.trustedReservedSession):this.client?.updateAuthToken(e.jwtToken):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 Zr()??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)}else 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;n?.onExplicitOfflineChange?n.onExplicitOfflineChange(e,t):super.onExplicitOfflineChange(e,t)}async waitForReconnect(e){if(e?.aborted)return;let t=this.host.runtimeSource?.nativeConnection;t?.waitForReconnect?await t.waitForReconnect(e):!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`;function Xl(e){let t=2166136261;for(let n of Ke(e))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(16)}function Zl(e,t={}){try{return(t.storage??globalThis.sessionStorage).getItem(Yl)!==e}catch{return!0}}function Ql(e,t={}){return(()=>{try{(t.storage??globalThis.sessionStorage).setItem(Yl,e)}catch{}(t.reload??(()=>globalThis.location.reload()))()})()}var $l=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,n=new Promise(e=>t=e);this.pageAway={left:e,reopened:n,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);else{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),l(t,k(this.host.config));let n,r=this.host.runtimeSource.createBrowserWorkerConnection({config:t,schema:e.schema,client:e.client,onAuthFailure:t=>{ct(e.client,t),this.host.markUnauthenticated(t)},onAuthRestored:()=>this.host.clearAuthError(),onExplicitOfflineChange:e=>this.setExplicitOffline(r,e),onRemoteLinkChange:(e,t)=>this.setWorkerRemoteLink(r,e,t),onFailure:e=>this.observeConnectionFailure(r,s(e)),onStorageReset:e=>this.beginStorageReset(n,e),onStorageInvalidated:()=>this.reloadAfterStorageInvalidation(r),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,s(e)),this.connection}),this.disconnected){let e=this.connectionReady;this.enqueueTransportTransition(async()=>{await e,await r.disconnect()}).catch(()=>void 0)}return r}observeConnectionFailure(e,t){if(this.shutdownFailure?.connection===e){t instanceof Qe&&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 Qe||this.clearHeldPatience(),!n&&!e.canRetryInitialConfigurationAdmission?.()&&e.shutdown().catch(()=>void 0),(t instanceof Qe||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=Xl(t.schema);Zl(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(()=>Ql(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()=>{this.connection!==e||this.shutdownStarted||this.dbClosing||this.storageReset||(this.admissionRefused(e)?(await this.retryConfigurationAdmission(e),await this.connectionReady):this.connectionError instanceof Qe&&(this.reopenFailedFollower(),await this.connectionReady))}).catch(e=>{this.connectionError??=s(e),this.notifyWorkerRemoteLink()})},t)}clearWorkerRecoveryTimer(){this.workerRecoveryTimer!==null&&clearTimeout(this.workerRecoveryTimer),this.workerRecoveryTimer=null}async ensureReady(e,t){if(this.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(eu(this.host.config)),tu(this.host.config)),this.disconnected=!1,this.publishExplicitOfflineState()}),this.disconnected||this.resolveReconnectWaiters()}updateAuth(e){let t={...this.host.config,...e.mode===`bearer`?{jwtToken:e.jwtToken,cookieSession:void 0}:{jwtToken:void 0,cookieSession:e.cookieSession}};l(t,e.mode===`bearer`?e.trustedReservedSession:void 0),Ui(this.host.config,t),super.updateAuth(e);let n=this.connection;n&&n.updateAuth(JSON.stringify(eu(t)),tu(t)).catch(e=>{this.observeConnectionFailure(n,s(e))})}async deleteClientStorage(){if(this.storageReset)return this.storageReset;!this.connection&&!this.getCurrentClient()&&this.getClient({});let e=this.connection;if(e&&this.heldTooLong&&this.admissionRefused(e)&&await this.retryConfigurationAdmission(e),await this.ensureReady(`runtime`),this.storageReset)return this.storageReset;if(!this.connection)throw Error(`deleteClientStorage(): the browser worker is not connected`);let t=await this.connection.deleteStorage();return await this.storageReset,t}async storePendingUploads(){if(this.connection&&!this.storageReset)return await this.connection.storePendingUploads?.().catch(()=>void 0)??void 0}isUsable(){return!this.shutdownStarted&&!this.storageReset&&!this.storageResetError}async openInspectorControlPort(e){if(await Ja(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??=s(e)})}reopenFailedFollower(){this.recoverableConnectionFailure&&(this.clearWorkerRecoveryTimer(),this.host.clearAuthenticatedInspectorLocalReads(),this.connection=null,this.connectionReady=null,this.connectionError=null,this.initialExplicitOfflineStateKnown=!1,this.recoverableConnectionFailure=!1,this.openBrowserWorkerConnection())}reloadAfterStorageInvalidation(e){this.connection===e&&(this.connectionError=Error(`IndexedDB storage was externally invalidated`),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 Qe&&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 Qe&&u(e),e)}},async()=>{if(o)throw o;if(t?.resetReason||!i)return;let e=!1,n;await Promise.race([(async()=>{try{let e=a?.getRuntime();if(!e)s?await i.retire():await i.returnWithHighWater(i.confirmedTxTime);else if(!e.quiesceForegroundTxTimeHighWater)await i.retire();else{let n=await e.quiesceForegroundTxTimeHighWater();if(t?.resetReason)return;t?.leaseWorkerReplaced&&i.releaseAfterWorkerReplacement?i.releaseAfterWorkerReplacement(Error(`Foreground lease owner was replaced`)):s?await i.retire():await i.returnWithHighWater(n)}}catch(r){if(r===t?.resetReason)return;throw e=!0,n=o??r,await i.retire().catch(()=>void 0),n}})(),l.then(()=>{if(e)throw n;if(o)throw o})])},()=>{this.detachClient()?.discard()},()=>super.shutdown(),()=>t?.resetReason?void 0:e?.shutdown(),()=>this.storageReset??void 0,()=>{if(o)throw o}])}finally{this.shutdownFailure=null,this.connectionScope===t&&(this.connectionScope=null)}}resolveReconnectWaiters(){let e=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let t of e)t()}rejectReconnectWaiters(e){let t=[...this.reconnectWaiters];this.reconnectWaiters.clear();for(let n of t)n(e)}setExplicitOffline(e,t){this.connection===e&&(this.disconnected=t,this.publishExplicitOfflineState(),t||this.resolveReconnectWaiters())}transportLinkState(){return this.heldTooLong?`unavailable`:this.connectionError&&this.admissionRefused(this.connection)?`connecting`:this.connectionError?`unavailable`:this.workerRemoteLink}onTransportLinkStateChange(e,t){t.aborted||(this.workerRemoteLinkListeners.add(e),t.addEventListener(`abort`,()=>this.workerRemoteLinkListeners.delete(e),{once:!0}))}transportLinkStatus(){if(this.heldTooLong)return K(`held-by-another-tab`,!0);if(this.connectionError&&this.admissionRefused(this.connection))return ds;if(this.connectionError)return K(`stopped`);if(this.workerLinkStatus)return this.workerLinkStatus.state===`local-only`?ds:this.workerLinkStatus;switch(this.workerRemoteLink){case`connected`:return fs;case`unavailable`:return K(`network`);default:return ds}}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 eu(e){return{jwt_token:e.jwtToken??null,...e.adminSecret?{admin_secret:e.adminSecret}:{},...e.cookieSession?{backend_session:e.cookieSession}:{}}}function tu(e){return nt({...e,trustedReservedSession:k(e)})?.claims??{}}var nu=new WeakMap,ru=new WeakSet;function iu(e){return ru.has(typeof e?.current==`function`?e.current():e)}async function au(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=nu.get(e);if(n)return await n(t);if(iu(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 ou=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}},su=class extends Error{constructor(e){super(e),this.name=`RuntimeClosedError`}},cu=30;function lu(e){return e??{type:`persistent`}}function uu(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function du(e){let t=lu(e.driver);return uu((t.type===`persistent`?t.dbName:void 0)??e.dbName)??B(e)}function fu(e){return Wi(e,du(e))}function pu(e){if(!e)return;let t=e;oe(t.tier);let n={};v(t.tier)&&(n.tier=t.tier);let r=w(t.firstLoadRemoteWaitMs);r!==void 0&&(n.firstLoadRemoteWaitMs=r),t.branch!==void 0&&(n.branch=t.branch),t.base!==void 0&&(n.base=t.base);let i=t.splices;if(i!==void 0){if(!Array.isArray(i)||!i.every(e=>typeof e==`string`))throw Error(`splices must be an array of column names.`);i.length>0&&(n.splices=[...i])}let a=t.backlogRows;return a!==void 0&&(is(a,`backlogRows`),n.backlogRows=a),rt(e)&&(n.tier=`local-only`),n}var mu=new WeakMap,hu=`allFromInspectorAttachment.subscribeFromInspectorAttachment.currentRuntime.prefetchRuntimeQueries.refreshAccountAuth.updateAuthToken.updateCookieSession.getAuthState.getDeviceAccountProof.onAuthChanged.onMutationError.textAnchors.getSyncStatus.getPendingUploadRows.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 gu(e){let t=mu.get(e);if(!t)throw Error(`Jazz Db is missing its internal subscription source.`);return t}function _u(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 vu(e,t,n,r){let i=W(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],_u(e,t).column_type)]))}}function yu(e,t,n,r){let i=vu(e,t,n,`schema`);return r===void 0?{head:i}:Array.isArray(r)?{head:i,base:{kind:`snapshot`,branch:vu(e,t,r[0],`schema`),snapshot:ae(r[1])}}:{head:i,base:{kind:`current`,branch:vu(e,t,r,`schema`)}}}function bu(e,t,n){if(!n)return;let{branch:r,...i}=n;return r===void 0?i:{...i,branch:vu(e,t,r,`table`)}}function xu(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:yu(e,t,r,i)}}function Su(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 Cu(e){return e.hops.length>0||e.gather!==void 0||Object.keys(e.includes).length>0}function wu(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 Tu(e){return{...e,branches:[...e.branches]}}function Eu(e,t){if(W(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function Du(e,t,n){return xu(e,t,n)??{}}function Ou(e,t,n,r){let i=W(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 ku(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(Vo(e._table))throw Error(`History table "${e._table}" is read-only`)}function Au(e,t,n){return ju(e,$u(t,n),t._schema,t._table)}function ju(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("${Wu(n)}")`)}}function Mu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Nu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Pu(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 Fu(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Iu(e,t,n){let r=Ru(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 Lu(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function Ru(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}=zu(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 zu(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(!Mu(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=Nu(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=Pu(n.fromUtf8,`fromUtf8`,t),i=Pu(n.toUtf8,`toUtf8`,t);Fu(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Pu(n.from,`from`,t),r=Pu(n.to,`to`,t);Fu(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Pu(n.from,`from`,t),r=Pu(n.to,`to`,t);Fu(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=Nu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Pu(r?n.atUtf8:n.at,`at`,t),o=Pu(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}})})}else 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=Nu(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}})})}else r[t]=o}return{ordinary:r,descriptors:i}}function Bu(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 Vu(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 Hu(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=Vu(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 Uu(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]=Hu(t,r.at);continue}if(t instanceof Uint8Array){if(`fromUtf8`in r)throw Error(`Byte range for "${e}" takes from and to, not fromUtf8 and toUtf8.`);if(r.from>r.to)throw Error(`Byte range for "${e}" ends before it starts.`);n[e]=t.slice(r.from,r.to);continue}if(typeof t!=`string`)throw Error(`Large-value selection for "${e}" has an incompatible column type.`);if(`fromUtf8`in r){let i=new TextEncoder().encode(t),a=Math.min(r.toUtf8,i.length),o=Math.min(r.fromUtf8,a);if(r.fromUtf8>r.toUtf8)throw Error(`UTF-8 range for "${e}" ends before it starts.`);if(o<i.length&&(i[o]&192)==128||a<i.length&&(i[a]&192)==128)throw Error(`UTF-8 range for "${e}" splits a code point.`);n[e]=new T({fatal:!0}).decode(i.slice(o,a));continue}let i=Math.min(r.to,t.length),a=Math.min(r.from,i);if(r.from>r.to)throw Error(`UTF-16 range for "${e}" ends before it starts.`);if(!Bu(t,a)||!Bu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Wu(e){return e.replaceAll(`"`,`\\"`)}function Gu(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function Ku(e,t,n,r){let i=Gu(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?ws(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?Uu(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 qu(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=Ku(e,t,n,r.computedState),i=await a(r.physical)}}var Ju=new WeakMap;function Yu(e,t){let n=Ju.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Xu(e,t){return Zu(e,t)}function Zu(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 Qu(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 $u(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 ed=1e4;function td(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([]),ed)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function nd(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function rd(e,t,n){return Xu(e,Ic(qc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function id(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)&&ad(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 ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function od(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(ad(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 sd(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 cd(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function ld(e,t,n){let r;try{r=t(sd(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 cd(e,a,s,i())}var ud=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(Ju.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 Yu(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};Ju.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 Le(i,t):new Fe(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}=id(t,r);Qu(t,p);let m=async()=>{let r=$u(t,p),u=ju(o,r,t._schema,t._table),m=e===`insert`?od(t,p):void 0,h=e===`insert`?bu(t._schema,t._table,{...i,...n?{id:n}:{},...m?{branch:m}:{}}):xu(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,u,d,f,s,h,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=nd());let d,f=()=>{d=r.insertInternal(e._table,l,bu(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?Xu(e,Ic(d,e._schema,e._table)):rd(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,bu(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?$u(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=ju(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:rd(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,xu(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){Y(e),this.bindTable(e);let{replacements:i,descriptors:a}=Iu(e,n,r);r=Lu(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=xu(e._schema,e._table,r);this.prepareMutation(e,i,`Update`,n=>{a.length>0?o.updateLargeValuesInternal(e._table,t,n,a,u?.updatedAt,c,l,s,u?.branch):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);Qu(e,t),(a.pending||zc(i)?.pending)&&(t={...t}),a.cancelled?r({}):a.run(()=>J(i,()=>{if(a.cancelled)return;let i;try{i=$u(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(ju(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=xu(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=Gs(JSON.parse(a)),s=Eu(e._schema,o.table),c=xc(s,o),l=Ku(e,o,c),u=xu(e._schema,o.table,pu(t))??{},d=await i.queryInternal(bc(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?qu(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(Su(e),t))[0]??null}},dd=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;pendingUploadRowsSnapshots=new Map;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:k(e)};d(this,nt(r)),this.authStateStore=pe(r,n),this.connection=new jl(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=No(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}mu.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,pu(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,pu(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=>(wd.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`),pu(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,B(this.config),e),n=Oe(Ae(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();e===0?this.refreshLocalFirstToken():(this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer),this.localFirstRefreshTimer=setTimeout(()=>this.refreshLocalFirstToken(),e))}publishAuthStateWithInternalSession(e,t){d(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=k(this.config);return r===n&&i===void 0&&JSON.stringify(a)===JSON.stringify(t)&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateJwtToken(n,t)?!1:(this.connection.updateAuth({mode:`bearer`,jwtToken:n,trustedReservedSession:t}),this.publishAuthUpdate(n,t),!0)}publishAuthUpdate(e,t){let n={...this.config,jwtToken:e,cookieSession:void 0};l(n,t);let r=nt(n);this.config.jwtToken=e,this.config.cookieSession=void 0,l(this.config,t),this.publishAuthStateWithInternalSession(r,()=>{this.authStateStore.applyJwtToken(e,t)})}applyCookieSessionUpdate(e){this.runtimeSource.assertAuthUpdateAllowed();let t=e??void 0,n=this.config.cookieSession,r=this.config.jwtToken,i=k(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={...this.config,jwtToken:void 0,cookieSession:t},s=nt(o);return this.config.jwtToken=void 0,this.config.cookieSession=t,l(this.config,void 0),this.publishAuthStateWithInternalSession(s,()=>{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 $l(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);else for(let t of this.mutationErrorListeners)t(e)}async refreshAccountAuth(e){return this.refreshOwnAccountAuth(e)}async refreshOwnAccountAuth(e){ts(this.config);let t=it(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`?Oe(Ae(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}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?Ae(t):null;return!t||n?.iss!==`urn:jazz:local-first`||typeof n.exp!=`number`||n.exp<=Date.now()/1e3+cu||e?.audience!==void 0&&n.aud!==Ye(e.audience)?null:t}let t=e?.ttlSeconds??60,n=e?.audience??B(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=Ed(this.connection.syncStatus(),this.authStateStore.getState().error);return this.syncStatusSnapshot&&gs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||gs(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}getPendingUploadRows(e){return this.pendingUploadRowsSnapshot(e._table,this.connection.pendingUploadRows(e._table))}pendingUploadRowsSnapshot(e,t){let n=this.pendingUploadRowsSnapshots.get(e);return n!==void 0&&os(n,t)?n:(this.pendingUploadRowsSnapshots.set(e,t),t)}onPendingUploadRowsChange(e,t){let n=this.getPendingUploadRows(e),r=e=>{os(e,n)||(n=e,t(e))};return this.registerMovable(t=>{let n=t.pendingUploadRowsChangeRegistration(e,r);return t.successor&&r(t.getPendingUploadRows(e)),n},!0)}pendingUploadRowsChangeRegistration(e,t){return this.onPendingUploadRowsChangeHere(e,t)}onPendingUploadRowsChangeHere(e,t){let n=new AbortController,r=()=>n.abort();this.shutdownAbort.signal.addEventListener(`abort`,r,{once:!0}),n.signal.addEventListener(`abort`,()=>this.shutdownAbort.signal.removeEventListener(`abort`,r),{once:!0});let i=this.getPendingUploadRows(e);return this.connection.onSyncStatusChange(()=>{let n=this.getPendingUploadRows(e);n!==i&&(i=n,t(n))},n.signal),r}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;A(t),this.assertOpen(),n?.throwIfAborted();let r=new AbortController,i=()=>r.abort(n.reason);n?.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort(Error(`Db was shut down`));this.shutdownAbort.signal.addEventListener(`abort`,a,{once:!0});let o=t===void 0?void 0:setTimeout(()=>r.abort(new O(`global`,t)),t);try{await this.waitForUpstreamSync(r.signal)}finally{o!==void 0&&clearTimeout(o),n?.removeEventListener(`abort`,i),this.shutdownAbort.signal.removeEventListener(`abort`,a)}}waitForUpstreamSync(e){return this.connection.waitForSync(e)}getConfig(){let{browserWorkerPort:e,browserWorkerSession:t,...n}=this.config.runtimeSources??{};return structuredClone({...this.config,runtimeSources:Object.keys(n).length>0?n:void 0})}setDevMode(e){this.config.devMode=e}async disconnect(){if(this.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})=>Tu(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=ju(`Insert`,e._columnTransforms?$u(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!zc(r)?.pending;s&&!i&&(i=nd());let c=s?rd(e,i,a):void 0,l=J(r,()=>r.insert(e._table,a,bu(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?Xu(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}=id(e,t);Qu(e,o),Cl(this);let s=n?.id;return J(r,async()=>{let t=ju(`Insert`,$u(e,o),e._schema,e._table),c=this.getAccessContext(),l=od(e,o);return r.insertStreaming(e._table,t,i,a,bu(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}=id(e,n);Qu(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=ju(`Update`,$u(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,xu(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}=id(e,n);Qu(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=ju(`Upsert`,$u(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,xu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){Y(e);let i=this.getClient(e._schema),a=ju(`Restore`,e._columnTransforms?$u(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=zc(i)?.pending?rd(e,t,a):void 0,c=J(i,()=>i.restore(e._table,t,a,bu(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=>Xu(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);Qu(e,n),zc(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=xu(e._schema,e._table,i),l=J(o,()=>{let i=n=>{let i=ju(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=$u(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Uc(n)!==`not_observed`)throw n;return td(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 Fe(l.then(e=>e.txId),o):l)}update(e,t,n,r){Y(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Iu(e,n,r);r=Lu(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,xu(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,xu(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Fe(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=Au(`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=Au(`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 ud.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 ld(t,e,()=>Yu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return ld(t,e,()=>Yu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await au(this,e)}isLocalFirst(){return!iu(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,pu(t))}catch(n){if(this.successor&&Td(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=Gs(JSON.parse(o)),c=Eu(e._schema,s.table),l=xc(c,s),u=Ku(e,s,l),d=Du(e._schema,s.table,t),f=bc(o,c,u.physical),p=Cu(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?qu(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(Su(e),t))[0]??null}subscribe(e,t,n,r){let{onUpdate:i,onError:a}=typeof t==`function`?{onUpdate:t,onError:void 0}:t,o={onDelta:e=>{if(e.all===void 0)throw Error(`Jazz subscription update is missing its materialized result.`);let t=new Map;for(let n of e.delta)n.kind===ue.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t,...e.reset&&e.reason?{reason:e.reason}:{}})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,pu(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=>{c?(c=!1,i({delta:e.delta,all:e.all??[],reset:!0})):i(e)},...a===void 0?{}:{onError:a}},n,r);return o??=l.ready,l}),l=(()=>c());return o&&Object.defineProperty(l,"ready",{value:o}),l}subscribeDeltaHere(e,t,n,r){let{onDelta:i,onError:a}=t,o=this.getClient(e._schema),c=this.connection.initialExplicitOfflineState(),l=new u,d=e._build(),f=Gs(JSON.parse(d)),p=Eu(e._schema,f.table),m=xc(p,f),h=Ku(e,f,m),g=bc(d,p,h.physical),_=c===null,v=[],y=Du(e._schema,f.table,n);y.splices&&(Ou(p,m,e,y.splices),ku(f,h.physical,y.splices));let b=this.getAccessContext()?.readSession??r,x=null,S=!1,C=!1,w=new AbortController,T=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},E=e=>{if(!a)console.error(`Unhandled Jazz subscription error`,e);else try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},D=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||C||(e.terminalDelivered=!0,C=!0,_=!1,v.length=0,x===e&&(x=null),T(e),e.predecessor!==null&&(T(e.predecessor),e.predecessor=null),w.abort(),this.liveSubscriptionEnders.delete(ce),this.unregisterActiveQuerySubscriptionTrace(ie),l.clear(),E(t))},O=(e,t)=>{S||C||x!==e||e.terminalDelivered||(e.terminalError??=s(t),D(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return x=t,t},te=e=>{if(!(S||C||x===null)){if(!_)v.push(e);else try{i(e)}catch(e){let t=x;t!==null&&O(t,e)}}},ne=t=>{if(!(S||C||x===null))try{te(l.handleDelta(t,h.transform))}catch(t){if(!(t instanceof Xc)||!h.computedState||h.computedState.version===h.version)throw t;h=Ku(e,f,m,h.computedState),y.splices&&ku(f,h.physical,y.splices),g=bc(d,p,h.physical),T(x);let n=ee();l.clear(),v.length=0,this.unregisterActiveQuerySubscriptionTrace(ie),ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),queueMicrotask(()=>{this.stopping||re(n)})}},re=(e,t=y)=>{if(S||x!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(g,{onUpdate:t=>{if(!(S||x!==e||e.terminalError!==null)){if(e.installing)n.push(t);else try{ne(t)}catch(t){O(e,t)}}},onError:t=>{O(e,t)}},t,b)}catch(t){return e.installing=!1,O(e,t),null}if(e.installing=!1,S||x!==e||e.retired)return T(e),null;if(e.terminalError!==null)return D(e),null;try{for(let t of n){if(x!==e||e.terminalError!==null)break;ne(t)}}catch(t){return O(e,t),null}return S||x!==e||e.retired?null:e},ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),ae=()=>{S||(S=!0,this.liveSubscriptionEnders.delete(ce),_=!1,v.length=0,w.abort(),this.unregisterActiveQuerySubscriptionTrace(ie),x!==null&&(T(x),x.predecessor!==null&&(T(x.predecessor),x.predecessor=null)),x=null,l.clear())},oe=c?.then(()=>{if(!(S||C||x===null||this.stopping)){_=!0;for(let e of v.splice(0)){if(S||C||x===null)return;te(e)}}}).catch(e=>{if(!(S||C||x===null||this.stopping))throw O(x,e),e});oe&&oe.catch(()=>void 0);let se=ee(),ce=e=>{x!==null&&O(x,e)};this.liveSubscriptionEnders.add(ce);let le=y.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(le)?this.ensureReady(le,w.signal).then(()=>re(se)).catch(e=>{S||w.signal.aborted||this.stopping||O(se,e)}):re(se);let ue=ae;return oe&&Object.defineProperty(ue,"ready",{value:oe}),ue}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new ou(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&&gs(a,s)?s:s=a},l=new Map,u=n=>{let r=t.getPendingUploadRows(n);if(!i)return r;let a=e.prototype.getPendingUploadRows.call(this,n),o=r===null||a===null?null:[...new Set([...r,...a])].sort(),s=l.get(n._table);return s!==void 0&&os(s,o)?s:(l.set(n._table,o),o)},d={getSyncStatus:c,getPendingUploadRows:u,pendingUploadRowsChangeRegistration:(e,n)=>{let r=u(e),o=()=>{let t=u(e);t!==r&&(r=t,n(t))},s=t.onPendingUploadRowsChange(e,o),c=i?this.onPendingUploadRowsChangeHere(e,o):()=>{};return a.add(o),()=>{s(),c(),a.delete(o)}},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 hu)Object.defineProperty(this,e,{configurable:!0,value:d[e]??((...n)=>t[e](...n))});Object.defineProperty(this,"syncStatusChangeRegistration",{configurable:!0,value:d.syncStatusChangeRegistration}),Object.defineProperty(this,"pendingUploadRowsChangeRegistration",{configurable:!0,value:d.pendingUploadRowsChangeRegistration}),(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;A(n),r?.throwIfAborted();let i=new AbortController,a=()=>i.abort(r.reason);r?.addEventListener(`abort`,a,{once:!0});let o=n===void 0?void 0:setTimeout(()=>i.abort(new O(`global`,n)),n);try{await Promise.race([this.connection.waitForSync(i.signal),t])}finally{o!==void 0&&clearTimeout(o),r?.removeEventListener(`abort`,a)}}offlineRequested;drain=null;streamsMayFinish=null;letStreamsFinish(){return this.streamsMayFinish?.abort(),this.streamsMayFinish=new AbortController,this.streamsMayFinish}async stopOwnRuntime(t={}){let n=this.drain;if(!n)return this.shutdown(t);n.endStreamWait(),t.waitForSync||n.abort(),await n.done.catch(()=>{}),await e.prototype.shutdown.call(this)}current(){return this.successor?.current()??this}shutdown(e={}){if(this.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 Go(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 Ko(this.phase);if(this.gracefulDrain)throw new Ko(`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:wu(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 fd(){let e=y(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function pd(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function md(e,t){if(!t.supportsBrowserWorker||!Cd()||lu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),hd.set(n,gd(e)),n}var hd=new WeakMap;function gd(e){try{let t=e.runtimeSources;return JSON.stringify([fu(e),Hi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function _d(e,t){let n=hd.get(e);return n!==void 0&&n===gd(t)}async function vd(e){if(e&&!bd.has(e)){bd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function yd(e,t,n){let r=n;try{return await xd(e,t,()=>(r??=md(e,t),r))}finally{vd(r)}}var bd=new WeakSet;async function xd(e,t,n){if(ts(e),Sd(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?Pr(e.secret):null,i={...e};l(i,k(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...u}=e,d=r;if(d){let n=d;if(!e.jwtToken){let r=t.mintLocalFirstToken(pd(n,B(e),3600)),a=Oe(Ae(r)??{},`device-account`);i={...u,jwtToken:r},l(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=fd(),r=t.mintAnonymousToken(pd(n,B(e),3600)),a=Oe(Ae(r)??{},`anonymous`);i={...u,jwtToken:r},l(i,a)}ns(e,i),t.admitConfig(i);let f=lu(i.driver),p=t.supportsBrowserWorker&&Cd()&&f.type===`persistent`,m=a&&p&&_d(a,i)?a:void 0;m?bd.add(m):a&&await vd(a);let h=p?await dd.createWithBrowserWorker(i,t,m):await dd.createWithDirectConnection(i,t);return d&&h.initLocalFirstAuth(d,3600,!e.jwtToken),h}function Sd(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 Cd(){return typeof window<`u`&&typeof Worker<`u`}var wd=new WeakMap;function Td(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof su)return!0;return!1}function Ed(e,t){let{link:n}=e;return n.state!==`offline`||n.reason!==`auth`||t===void 0?e:{...e,link:{...n,authReason:t}}}var Dd={napi:`2aa41bdb29defc8fa5cb9310ca1bf511e3a632b9651ec544e714dbaf6ccc7eda`,wasm:`c151a2db288d61260dafc209785e0c70b19b2a540772785547056f5f743fc24c`},Od=`JAZZ_NATIVE_ARTIFACT_MISMATCH`,kd=class extends Error{kind;expected;actual;missingExport;name=`NativeArtifactMismatchError`;code=Od;constructor(e,t,n,r,i){super(e),this.kind=t,this.expected=n,this.actual=r,this.missingExport=i}};function Ad(e,t,n=[]){let r=Dd[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw new kd(`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 kd(`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 kd(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${i}.`,t,r,r,i)}var jd=class extends Error{},Md=class extends Error{},Nd=new Set(`\\.+*?()|[]{}^$#&-~`),Pd=new Set(`imsUuRx`),Fd=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Id(e){return Nd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Ld=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 jd&&this.fancy?new Md(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 jd(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,Pd.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++,Id(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&&Fd.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`}}},Rd={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]]},zd=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,Bd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:zd};function Vd(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function Hd(e){return e.map(([e,t])=>{let n=Vd(String.fromCodePoint(e));return e===t?n:`${n}-${Vd(String.fromCodePoint(t))}`}).join(``)}var Ud=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Vd(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 Md(`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=`[${zd}]`;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=Vd(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Vd(e.start)}-${Vd(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Wd(this.parsed.fancy?Bd[e.perl]:Hd(Rd[e.perl]),e.negated);case`ascii`:return Wd(Hd(Rd[e.ascii]),e.negated);case`unicode`:return Wd(Gd(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 Wd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Gd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new Md(`the Unicode class \`${e}\``)}function Kd(e){try{return new Ld(e).parse(),!0}catch(e){return e instanceof Md}}var qd=new Map,Jd=1024;function Yd(e){let t=qd.get(e);if(t)return t;let n=new Ld(e).parse();if(n.fancyInvalid.length>0)throw new jd(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new Md(n.unsupported[0]);let r=new Ud(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),qd.size>=Jd&&qd.clear(),qd.set(e,t),t}function Xd(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 Zd(e){return e%4==0&&e%100!=0||e%400==0}function Qd(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=Xd(e,5),r=Xd(e,8);return n===void 0||n<1||n>12||r===void 0||r===0?!1:n===2?r<=(Zd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function $d(e){if(e.length<9||e[2]!==`:`||e[5]!==`:`)return!1;let t=Xd(e,0),n=Xd(e,3),r=Xd(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=Xd(e,i+1),s=Xd(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 ef(e){let t=e.search(/[Tt]/);return t<0?!1:Qd(e.slice(0,t))&&$d(e.slice(t+1))}var tf=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,nf=`${tf}(?:\\.${tf}){3}`,X=`[0-9A-Fa-f]{1,4}`,rf=`(?:${X}:${X}|${nf})`,af=[`(?:${X}:){6}${rf}`,`::(?:${X}:){5}${rf}`,`(?:${X})?::(?:${X}:){4}${rf}`,`(?:(?:${X}:){0,1}${X})?::(?:${X}:){3}${rf}`,`(?:(?:${X}:){0,2}${X})?::(?:${X}:){2}${rf}`,`(?:(?:${X}:){0,3}${X})?::${X}:${rf}`,`(?:(?:${X}:){0,4}${X})?::${rf}`,`(?:(?:${X}:){0,5}${X})?::${X}`,`(?:(?:${X}:){0,6}${X})?::`].map(e=>`(?:${e})`).join(`|`),of=RegExp(`^${nf}$`),sf=RegExp(`^(?:${af})$`),cf=e=>of.test(e),lf=e=>sf.test(e);function uf(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=gf(e.slice(4));if(t===void 0||!bf(t))return!1}}return!0}var df=36,ff=1,pf=26,mf=4294967295;function hf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>455;)r=Math.trunc(r/35),i+=df;return i+Math.trunc(36*r/(r+38))}function gf(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=df;;e+=df){if(c>=r.length)return;let n=_f(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>mf||s>mf))return;let i=e<=o?ff:e>=o+pf?pf:e-o;if(n<i)break;if(t*=df-i,t>mf)return}let n=i.length+1;if(o=hf(s-e,n,e===0),a+=Math.trunc(s/n),a>mf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function _f(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 vf=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))),yf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function bf(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||!vf.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(yf.has(o))return!1}return!(n&&!r||i&&a)}var xf=new TextEncoder;function Sf(e){return xf.encode(e).length}function Cf(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)}var wf=/^[\p{Alphabetic}\p{N}]$/u,Tf=new Set("!#$%&'*+-/=?^_`{|}~");function Ef(e){return wf.test(e)||Tf.has(e)||Cf(e)}function Df(e){return e.length>0&&[...e].every(Ef)}function Of(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||Cf(n)))return!1}return!0}function kf(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||Cf(e)}function Af(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function jf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=Af(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=Af(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||Sf(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!Of(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(Df))return!1;if(o.length===0||Sf(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(kf)?e.startsWith(`IPv6:`)?lf(e.slice(5)):cf(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!wf.test(t[0])||!wf.test(t[t.length-1])||Sf(e)>63||!Df(e))return!1}return uf(o)}var Mf=`A-Za-z0-9\\-._~`,Nf=`!$&'()*+,;=`,Pf=`%[0-9A-Fa-f]{2}`,Ff=`(?:[${Mf}${Nf}:@]|${Pf})`,If=`${Ff}*`,Lf=`${Ff}+`,Rf=`(?:[${Mf}${Nf}@]|${Pf})+`,zf=`\\[(?:${af}|[vV][0-9A-Fa-f]+\\.[${Mf}${Nf}:]+)\\]`,Bf=`(?:${`(?:[${Mf}${Nf}:]|${Pf})*`}@)?(?:${zf}|${`(?:[${Mf}${Nf}]|${Pf})*`})(?::[0-9]*)?`,Vf=`(?:/${If})*`,Hf=`/(?:${Lf}(?:/${If})*)?`,Uf=`${Lf}(?:/${If})*`,Wf=`${Rf}(?:/${If})*`,Gf=`(?:${Ff}|[/?])*`,Kf=`[A-Za-z][A-Za-z0-9+\\-.]*`,qf=`(?://${Bf}${Vf}|${Hf}|${Uf}|)`,Jf=`(?://${Bf}${Vf}|${Hf}|${Wf}|)`,Yf=`(?:\\?${Gf})?(?:#${Gf})?`,Xf=RegExp(`^${Kf}:${qf}${Yf}$`),Zf=RegExp(`^(?:${Kf}:${qf}|${Jf})${Yf}$`);function Qf(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function $f(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&Qf(n)}var ep=new Set(`+#./;?&=,!@|`),tp=new Set(`"'<>%\\^\`{|}`);function np(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||ep.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||tp.has(r))return!1;t++}}return!0}var rp={date:Qd,"date-time":ef,email:jf,hostname:uf,ipv4:cf,ipv6:lf,"json-pointer":Qf,regex:Kd,"relative-json-pointer":$f,time:$d,uri:e=>Xf.test(e),"uri-reference":e=>Zf.test(e),"uri-template":np},ip=class{value;constructor(e){this.value=e}},ap=2n**64n-1n,op=-(2n**63n),sp=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,cp=/[ \t\n\r]*/y;function lp(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{cp.lastIndex=t,cp.test(e),t=cp.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=()=>{sp.lastIndex=t;let r=sp.exec(e);if(!r)return n();t=sp.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new ip(a):a;if(Object.is(a,-0))return new ip(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<op||o>ap?new ip(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 up(e){return typeof e==`number`||typeof e==`bigint`||e instanceof ip}function dp(e){return e instanceof ip?e.value:e}function fp(e,t){return typeof e==`bigint`?!0:e instanceof ip?!t:Number.isInteger(e)}function pp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof ip){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):mp(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?mp(e):Array.isArray(e)?`[${e.map(pp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${pp(t)}`).join(`,`)}}`:JSON.stringify(e)}function mp(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function hp(e){if(e instanceof ip)return e.value;if(Array.isArray(e))return e.map(hp);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=hp(r);return t}function gp(e,t){if(up(e))return up(t)?dp(e)==dp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>gp(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||up(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&gp(e[n],t[n]))}return e===t}function _p(e,t){let n=Number(dp(e)),r=Number(dp(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]=vp(n),[o,s]=vp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function vp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*yp(10,t),!Number.isFinite(n))return bp(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(yp(10,t))]}function yp(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 bp(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 xp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Sp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Cp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},wp=new URL(`json-schema:///`);function Tp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function Ep(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dp(e,t=Object.create(null),n=[],r=wp,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(!Ep(e))return t;let o=e.$id??e.id;if(typeof o==`string`){let t=new URL(o,r.href);t.hash.length>1||(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(Sp[i]&&Array.isArray(a))for(let e of a)Dp(e,t,n,r,!1);else if(xp[i])Dp(a,t,n,r,!1);else if((Cp[i]||i===`dependencies`)&&Ep(a))for(let e in a)Dp(a[e],t,n,r,!1)}return t}function Op(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(Ep(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||Ep(i)?i:void 0}}function kp(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 Ap(e){if(e===null)return`null`;if(up(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 jp(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=Ap(e),{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:E,patternProperties:D,additionalProperties:O,unevaluatedProperties:ee,minProperties:te,maxProperties:ne,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:oe,prefixItems:se,items:ce,additionalItems:le,unevaluatedItems:ue,contains:k,minContains:A,maxContains:de,minItems:fe,maxItems:j,uniqueItems:pe,minimum:me,maximum:he,exclusiveMinimum:ge,exclusiveMaximum:_e,multipleOf:ve,minLength:ye,maxLength:be,pattern:xe,__absolute_ref__:Se,__absolute_recursive_ref__:Ce}=t,M=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?Op(c,Ce):r,l=`${a}/$recursiveRef`,u=Z(e,r===null?t:r,n,s,i,l,o);u.valid||M.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=Op(c,Se??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||M.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:M.length===0,errors:M}}let we=u===`number`&&fp(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&we)||M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?we||M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!gp(e,h)&&M.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${pp(h)}.`}),g!==void 0&&!g.some(t=>gp(e,t))&&M.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${pp(g)}.`}),v!==void 0){let t=`${a}/not`;Z(e,v,n,r,i,t).valid&&M.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let N=[];if(y!==void 0){let t=`${a}/anyOf`,s=M.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);M.push(...l.errors),c||=l.valid,l.valid&&N.push(s)}c?M.length=s:M.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=M.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);M.push(...l.errors),c&&=l.valid,l.valid&&N.push(s)}c?M.length=s:M.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=M.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 M.push(...l.errors),l.valid&&N.push(c),l.valid}).length;c===1?M.length=s:M.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,...N),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||M.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||M.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||M.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(te!==void 0&&s.length<te&&M.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0&&s.length>ne&&M.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${ne} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${Tp(a)}`,o=Z(a,re,n,r,t,e);o.valid||M.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||M.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}/${Tp(s)}`,o);t.valid||M.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||M.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}/${Tp(a)}`);t.valid||M.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}/${Tp(a)}`,d=Z(t[a],E[a],n,r,s,`${e}/${Tp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,M.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=Yd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${Tp(f)}`,m=Z(t[f],d,n,r,p,`${e}/${Tp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,M.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&O!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${Tp(a)}`,d=Z(t[a],O,n,r,s,e);d.valid?o[a]=!0:(u=l,M.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&ee!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${Tp(a)}`,c=Z(t[a],ee,n,r,s,e);c.valid?o[a]=!0:M.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;j!==void 0&&s>j&&M.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${j}).`}),fe!==void 0&&s<fe&&M.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${fe}).`});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,M.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(ce!==void 0){let e=`${a}/items`;if(Array.isArray(ce)){let a=Math.min(ce.length,s);for(;c<a;c++){let a=Z(t[c],ce[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,M.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],ce,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,M.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}if(!u&&le!==void 0){let e=`${a}/additionalItems`;for(;c<s;c++){let a=Z(t[c],le,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,M.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(k!==void 0){if(s===0&&A===void 0)M.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(A!==void 0&&s<A)M.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${A}).`});else{let e=`${a}/contains`,c=M.length,l=0;for(let a=0;a<s;a++){let s=Z(t[a],k,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):M.push(...s.errors)}l>=(A||0)&&(M.length=c),A===void 0&&de===void 0&&l===0?M.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):A!==void 0&&l<A?M.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${A} items matching schema. Only ${l} items were found.`}):de!==void 0&&l>de&&M.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${de} items matching schema. ${l} items were found.`})}}if(!u&&ue!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=Z(t[c],ue,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||M.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(gp(t[e],t[n])){M.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=dp(e);s===`4`?(me!==void 0&&(ge===!0&&t<=me||t<me)&&M.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${ge?`or equal to `:``}${me}.`}),he!==void 0&&(_e===!0&&t>=he||t>he)&&M.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${_e?`or equal to `:``}${he}.`})):(me!==void 0&&t<me&&M.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${me}.`}),he!==void 0&&t>he&&M.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${he}.`}),ge!==void 0&&t<=ge&&M.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${ge}.`}),_e!==void 0&&t>=_e&&M.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${_e}.`})),ve!==void 0&&!_p(e,ve)&&M.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ve}.`})}else if(u===`string`){let t=e,n=ye===void 0&&be===void 0?0:kp(t);ye!==void 0&&n<ye&&M.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${ye}).`}),be!==void 0&&n>be&&M.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${be}).`}),xe!==void 0&&!Yd(xe).test(t)&&M.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:rp[T];r&&!r(t)&&M.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:M.length===0,errors:M}}var Mp={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`}}}]},Np={"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`},Pp=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(`.`)),Fp={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`]},Ip={...Fp,single:[...Fp.single,`contains`,`propertyNames`],plain:[...Fp.plain.filter(e=>e!==`id`),`$id`,`const`]},Lp={...Ip,single:[...Ip.single,`if`,`then`,`else`]},Rp={single:[...Lp.single,`unevaluatedItems`,`unevaluatedProperties`],array:Lp.array,map:[...Lp.map,`$defs`,`dependentSchemas`],plain:[...Lp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},zp={4:Fp,6:Ip,7:Lp,"2019-09":Rp,"2020-12":{single:Rp.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Rp.map,plain:Rp.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)}},Bp={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Vp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Hp=[...Vp,`json-pointer`,`uri-reference`,`uri-template`],Up={4:Vp,6:Hp,7:[...Hp,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},Wp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Gp={base64:Kp(`A-Za-z0-9+/`),base64url:Kp(`A-Za-z0-9\\-_`),base32:qp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:qp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Kp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function qp(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 Jp=class extends Error{};function Yp(e){if(!P(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Np[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new Jp(`unknown JSON Schema dialect "${t}"`);return n}function Xp(e,t,n=[]){if(typeof e==`boolean`)return e;if(!P(e))return{};let r=zp[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(Bp[t].includes(s)&&!n.includes(s))throw new Jp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(Pp.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&Qp(c),s===`patternProperties`&&P(c))for(let e of Object.keys(c))Qp(e);if(s===`format`&&typeof c==`string`){if(!Up[t]?.includes(c))continue;if(Wp.includes(c))throw new Jp(`the "${c}" format is not supported by the browser runtime yet`)}r.array.includes(s)&&Array.isArray(c)?o.push([s,c.map(e=>Xp(e,t,n))]):r.single.includes(s)?o.push([s,Xp(c,t,n)]):r.map.includes(s)&&P(c)?o.push([s,Zp(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Gp[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 Zp(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:Xp(r,t,n)]))}function Qp(e){try{Yd(e)}catch(t){throw t instanceof jd?new Jp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof Md?new Jp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function $p(e){for(let t of e.references)if(Op(e.lookup,t)===void 0)throw new Jp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function em(e){if(Array.isArray(e))return e.map(em);if(!P(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,em(r)]);return Object.fromEntries(t)}var tm={4:Mp.draft4,6:Mp.draft6,7:Mp.draft7,"2019-09":Mp.draft201909,"2020-12":Mp.draft202012};function nm(e){return tm[e].map(t=>e===`2020-12`?em(Xp(t,e,[`$dynamicAnchor`,`$dynamicRef`])):Xp(t,e))}var rm=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=Dp(e,void 0,this.references);for(let e of r)Dp(e,this.lookup)}validate(e){return jp(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},im=new Map;function am(e){let t=im.get(e);if(!t){let[n,...r]=nm(e);t=new rm(n,e,!1,r),im.set(e,t)}return t}function om(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 sm(e){let t=Yp(e);if(typeof e==`boolean`){if(t===`4`)throw new Jp(`boolean schemas need draft 6 or later`)}else{let n=am(t).validate(e);if(!n.valid)throw new Jp(om(n.errors))}let n=new rm(Xp(hp(e),t),t,!0,nm(t));return $p(n),e=>{let t=n.validate(lp(e));return t.valid?void 0:om(t.errors)}}function cm(e){return sm(lp(e))}function lm(e){e.setJsonSchemaValidator(cm)}async function um(){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 dm=Promise.resolve(),fm;function pm(e){let t=dm.then(()=>mm(e));return dm=t.then(()=>void 0,()=>void 0),t}async function mm(e){let t=await ii(()=>import(`./jazz_wasm-O10pptvY.js`),[],import.meta.url),n=Jr(e);if(n)return t.initSync(n),hm(t);let r=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await um();e&&(t.initSync({module:e}),r=!0)}catch{}if(!r&&typeof t.default==`function`){let n=typeof location<`u`?Yr(Lr,location.href,e)??zr():null;if(n)await gm(t,n);else if(typeof location<`u`&&Ji())throw Error(Ki);else await t.default()}return hm(t)}function hm(e){return Ad(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),lm(e),e}async function gm(e,t){if(fm===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(_m(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}),fm=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}),fm=t}function _m(e){return typeof WebAssembly.compileStreaming==`function`&&e?.trim()===`application/wasm`}function vm(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 ym(e,t,n,r){return jr(`${Gt}${e}`,{audience:t,ttlSeconds:n,now:r})}var bm=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 ym(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*xm(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 Sm=`authority_changed`,Cm=class extends Error{name=`AuthorityChangedError`;code=Sm;constructor(e,t){super(e,t)}};function wm(e){return!e||typeof e!=`object`?!1:e.code===Sm}function Tm(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(wm(e))return new Cm(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 Em=`core_tick_failed`,Dm=class extends Error{name=`CoreTickFailedError`;code=Em;constructor(e){super(`core tick failed: ${km(e)}`,{cause:e})}};function Om(e){return!e||typeof e!=`object`?!1:e.code===Em}function km(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 Am=class extends vs{},jm=class{text;constructor(e){this.text=e}};function Mm(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 Nm(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Mm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Mm(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);else if(n===`"`)o=!0,a+=n;else{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 jm(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 Pm(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`),Mm(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 jm&&(/^(?: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 jm){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);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);else if(e===`False`)d(10);else 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)}Me({issuer:et,user_id:`system`,claims:{},authMode:`external`});var Fm=-(1n<<63n),Im=(1n<<63n)-1n;function Lm(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<Fm||n>Im)throw Error(`${t} must be a signed 64-bit integer`);return n}var Rm=new T({fatal:!0});function zm(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function Bm(e){return{table:e.string(),descriptor:Hm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Vm(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),Qm(e,r.valueType)},t.length)}function Hm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:$m(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:$m(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:$m(e)}:Um(t)})}function Um(e){throw Error(`unknown native row descriptor field kind ${e}`)}function Wm(e){let t={added:e.readVec(Bm),updated:e.readVec(Bm),removed:e.readVec(Ym),addedOccurrenceKeys:e.readVec(e=>Gm(e)),updatedOccurrenceKeys:e.readVec(e=>Gm(e)),removedOccurrenceKeys:e.readVec(e=>Gm(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 Jm(e,`subscription delta`),t}function Gm(e){let t=e.bytes();if(t[0]!==2||!Km(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Km(e){let t=t=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;if(e.length<25)return!1;let n=16,r=t(n);if(n+=4,r>256||n+r*16+4>e.length)return!1;n+=r*16;let i=t(n);if(n+=4,i>r+1)return!1;let a=-1;for(let o=0;o<i;o++){if(n+8>e.length)return!1;let i=t(n),o=t(n+4);if(n+=8,i>r||i<=a||o===0||o>4096||n+o>e.length||!le(e.subarray(n,n+o)))return!1;a=i,n+=o}for(let t=0;t<=r;t++){let t=e[n++];if(t===1)n+=24;else if(t!==0)return!1}return n===e.length}function qm(e){let t=e.u64(),n=e.readVec(Bm);return Jm(e,`relation snapshot`),{rootCount:t,rows:n}}function Jm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Ym(e){return{table:e.string(),rowId:e.bytes()}}function Xm(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),Qm(e,t[n].valueType)},t.length)}function Zm(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:$m(e)}))}function Qm(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)}}else 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)}else if(t.tag===13){let n=t.members??(t.inner?[t.inner]:[]);e.vec((e,t)=>Qm(e,n[t]),n.length)}else if(t.tag===14||t.tag===15){if(!t.inner)throw Error(`missing inner value type for tag ${t.tag}`);Qm(e,t.inner)}else if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);Xm(e,t.record)}else 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),Xm(e,n.payload)},r.length)}}function $m(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:$m(e)};if(t===13){let n=e.readVec($m);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:Zm(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:Zm(e)}))}}:{tag:t}}function eh(e,t){let n=Ih(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=N(r),o=new Bh,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 N([a,o.finish(),...i])}function th(e,t){let n=uh(gh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:Oh(e.column_type,i)})}function nh(e,t){return Object.defineProperty(e,"valuesByColumn",{value:t,enumerable:!1,configurable:!0}),e}function rh(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 ih={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function ah(e,t,n){let r=oh([ih,...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 nh({id:e,values:a},rh(t,a))}function oh(e,t){let n=uh(gh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:sh(e.column_type,i,e.name)})}function sh(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:Nh(t,n)};case`Array`:return{type:`Array`,value:ch(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:ah(Ph(t.subarray(0,16)),e.columns,t)};default:return Oh(e,t)}}function ch(e,t){return Mh(e,t,t=>sh(e,t))}function lh(e,t){return eh(gh(e),e.map((e,n)=>_h(e,t[n])))}function uh(e){let t=Ih(e);return(n,r)=>dh(e,t,n,r)}function dh(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 fh(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:Lh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Lh(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 ${ph(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return fh(n.subarray(c,l),a)}function fh(e,t){if(t.tag!==15)return e;let n=hh(e);return n==null?null:t.inner?fh(n,t.inner):n}function ph(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?ph(e.inner):`?`}>`:mh(e.tag)}function mh(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 hh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function gh(e){return e.map(e=>({name:e.name,valueType:Th(e)}))}function _h(e,t){let n=Dh(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return yh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return yh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=yh(r);return e.sparse?vh(t,r):t}let i=bh(e.column_type,t);return e.nullable&&(i=vh(i,n)),e.sparse?vh(i,r):i}function vh(e,t){if(Fh(t)==null)return N([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function yh(e){let t=Fh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function bh(e,t){switch(e.type){case`Boolean`:if(t.type!==`Boolean`)throw Error(`expected Boolean value`);return Uint8Array.of(+!!t.value);case`Integer`:{let e=Rh(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=zh(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 N([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return wh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return N([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return Sh(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return xh(e.columns,t.value)}}function xh(e,t){let n=lh(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?wh(t.id):new Uint8Array;return N([Uint8Array.of(+!!t.id),r,Ch(n.byteLength),n])}function Sh(e,t){let n=t.map(t=>bh(e,t));if(Fh(Dh(e))!=null)return N(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)}),N([Ch(t.length),r,...n])}function Ch(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function wh(e){let t=Xe(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function Th(e){let t=Dh(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function Eh(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[...Eh(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[...Eh(e.column_type.element.columns)]}}:e.column_type}))}function Dh(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:Dh(e.element)};case`Row`:return{tag:9}}}function Oh(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:Rm.decode(kh(t))};case`Uuid`:return{type:`Uuid`,value:Ph(t)};case`Bytea`:return{type:`Bytea`,value:kh(t).slice()};case`Array`:return{type:`Array`,value:jh(e.element,t)};case`Row`:return{type:`Row`,value:Ah(e.columns,t)}}}function kh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function Ah(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Ph(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=th(e,o);return nh({id:i,values:s},rh(e,s))}function jh(e,t){return Mh(e,t,t=>Oh(e,t))}function Mh(e,t,n){let r=Fh(Dh(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=Lh(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:Lh(t,4+(e-1)*4),s=e===i-1?t.length:Lh(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 Nh(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Ph(e){if(e.length>=16)return We(e,0);let t=Pe(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Fh(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=Fh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Fh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function Ih(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Fh(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(Fh(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 Lh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Rh(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 zh(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Lm(e.value,`BigInt value`)}var Bh=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)}},Vh=new T({fatal:!0}),Hh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Uh(e,t){return t?Hh:e}function Wh(e,t,n,r=!1,i,a,o,s){let c=new ag;return c.bytes(e),c.string(Gh(Uh(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(sg(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Gh(e){try{let t=Vh.decode(e);if(D(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Kh(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&&Yh(`query limit`,r),Yh(`query offset`,i);let u=new ag;return u.string(e),u.vec((e,n)=>{let r=t[n];Zh(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)=>{Jh(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(Pm(c),!1)),qh(u,l),u.finish()}function qh(e,t){e.vec((e,n)=>{let r=t[n];e.string(r.column),r.kind===`json_pointer`?(e.u64(3),e.string(r.at)):(Yh(`partial selection ${r.column} start`,r.from),Yh(`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 Jh(e,t){let{filters:n=[],select:r,orderBy:i=[],limit:a=null,offset:o=0,requirement:s=`Optional`,nestedArrays:c=[]}=t;a!=null&&Yh(`array subquery ${t.columnName} limit`,a),Yh(`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)=>{Zh(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(Xh(s)),e.vec((e,t)=>{Jh(e,c[t])},c.length),qh(e,[])}function Yh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function Xh(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function Zh(e,t){if(t.op===`All`||t.op===`Any`)e.u64(t.op===`All`?0:1),e.vec((e,n)=>Zh(e,t.predicates[n]),t.predicates.length);else if(t.op===`Not`)e.u64(2),Zh(e,t.predicate);else if(t.op===`In`)e.u64(5),eg(e,t.column),e.vec((e,n)=>{e.u64(3),rg(e,t.values[n])},t.values.length);else if(t.op===`Contains`)e.u64(10),eg(e,t.column),tg(e,t.value);else if(t.op===`StartsWith`||t.op===`EndsWith`)e.u64(t.op===`StartsWith`?13:14),eg(e,t.column),tg(e,t.value);else if(t.op===`IsNull`||t.op===`IsNotNull`)t.op===`IsNotNull`&&e.u64(2),e.u64(12),eg(e,t.column);else if(Qh(t))$h(e,t.column,t.op,t.value);else throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Qh(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function $h(e,t,n,r){e.u64(ng(n)),eg(e,t),tg(e,r)}function eg(e,t){e.u64(0),e.string(t)}function tg(e,t){e.u64(3),rg(e,t)}function ng(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 rg(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)}else if(t.type===`Nullable`)e.u64(13),t.value==null?e.none():e.some(e=>rg(e,t.value));else if(t.type===`Boolean`)e.u64(5),e.bool(t.value);else 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)}else 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)}else 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)}else if(t.type===`Double`){if(!Number.isFinite(t.value))throw Error(`Double value must be finite`);e.u64(4),e.f64Le(t.value)}else if(t.type===`Uuid`){e.u64(9);let n=Xe(t.value);if(!n)throw Error(`invalid uuid ${t.value}`);e.bytes(n)}else t.type===`Bytea`?(e.u64(7),e.bytes(t.value)):t.type===`Array`?(e.u64(12),e.vec((e,n)=>rg(e,t.value[n]),t.value.length)):(e.u64(6),e.string(t.value))}var ig=64,ag=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=Lm(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)}string(e){this.bytes(cg(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<ig)for(let t of e)this.chunks.push(t);else 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)}},og=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 Vh.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 sg(e){return cg(JSON.stringify(e,b))}function cg(e){return new TextEncoder().encode(e)}var lg=new TextEncoder;function ug(e){return lg.encode(he(e))}function dg(e){let t=new ag;return t.string(e.table),Vm(t,[...e.descriptor]),Pe(t.finish())}var fg=36e5,pg=500,mg=`jazz-http-stream-endpoints`,hg=`endpoints`;function gg(){return globalThis.indexedDB!==void 0}function _g(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(mg,1);r.onupgradeneeded=()=>r.result.createObjectStore(hg),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function vg(e,t){let n=_g();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(hg,e).objectStore(hg));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var yg=`jazz-stream-endpoint:`,bg=6e5;function xg(){if(typeof document<`u`)try{return globalThis.localStorage??void 0}catch{return}}function Sg(e,t=Date.now()){let n=xg();if(n)try{let r=n.getItem(yg+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(yg+e);return}return i===`stream`}catch{return}}function Cg(e,t,n){let r=xg();if(r)try{r.setItem(yg+e,`${t}:${n}`)}catch{try{r.removeItem(yg+e)}catch{}}}async function wg(e,t=Date.now()){let n,r=await Promise.race([vg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),pg)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?Cg(e,`stream`,r.until):Cg(e,`none`,t+bg),i}function Tg(e,t=Date.now()){return Cg(e,`stream`,t+fg),vg(`readwrite`,n=>n.put(t+fg,e)).then(()=>void 0,()=>void 0)}function Eg(e){return Cg(e,`none`,Date.now()+bg),vg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var Dg=`x-jazz-stream-key`;function Og(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 kg(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 Ag=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?kg([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}},jg=new TextEncoder,Mg=new TextDecoder;function Ng(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 Pg=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)}},Fg=4194304,Ig=(e,t)=>fetch(e,t),Lg=class extends Pg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=Ig){super(),this.request=t,this.streamUrl=Ng(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?jg.encode(e):e;this.queued.push(Og(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:{[Dg]:e.key},signal:AbortSignal.timeout?.(Bg)}).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 Ag;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(Mg.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(Mg.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<=Fg);)t+=this.queued[e].byteLength,e+=1;let n=kg(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`,[Dg]: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}))}},Rg=new Set,zg=new Map,Bg=1e4,Vg=new Map,Hg=`x-jazz-stream`,Ug=new Set,Wg=`x-jazz-store-error`,Gg=new Set;async function Kg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(Bg)});if(n.status===503&&n.headers.get(Wg)===`1`){let t=await n.text().catch(()=>``);return t&&!Gg.has(`${e}\n${t}`)&&(Gg.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(Hg)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function qg(e,t,n){let r=await Kg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return zg.delete(e),Vg.delete(e),r===`refused`&&!Ug.has(e)&&(Ug.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=(zg.get(e)??0)+1;zg.set(e,i);let a=t?(Vg.get(e)??0)+1:0;t?Vg.set(e,a):Vg.delete(e);let o=a>=2;return i<3&&!o?r:(zg.delete(e),Vg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${Bg/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 Jg(e,t={}){let n=t.fetch??Ig,r=t.describeFailedUpgrade;return class extends Pg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,Rg.has(e)){this.openStream();return}if(!gg()){this.inner=this.openNative();return}let t=Sg(e);t===!0?(Rg.add(e),this.openStream()):t===!1?this.inner=this.openNative():wg(e).then(t=>{this.closedEarly||(t?(Rg.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 Lg(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(Rg.delete(this.url),Eg(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)=>{clearTimeout(this.openDeadline),this.settled||(a?a[e]??=t:(a={[e]:t},this.probing=!0,qg(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);this.probing=!1,this.settled||(this.settled=!0,t?(Rg.add(this.url),e===`stream`&&Tg(this.url),this.openStream()):n?(this.emit(`error`,Error(n)),this.emit(`close`,{code:1006,reason:n})):(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()},Bg),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,zg.delete(this.url),Vg.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 Yg=`jazz_renewal`,Xg=`X-Jazz-Renew`,Zg=2048;function Qg(e){let t=new og(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>Zg)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function $g(e){let t=new ag;return t.u64(65),t.string(e),t.finish()}function e_(e){return e[0]===64}function t_(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 n_(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var r_=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function i_(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function a_(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}function o_(e){return e.code===`protocol_error`||(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)&&!a_(e)}var s_=12e4,c_=1e3,l_=7,u_=12688,d_=1<<20,f_=5,p_=5,m_=2097152,h_=4096;function g_(e){v_(e);let t=new ag;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>m_)throw Error(`websocket frame batch exceeds maximum length of ${m_} bytes`);return n}function __(e){if(e.byteLength>m_)throw Error(`websocket frame batch exceeds maximum length of ${m_} bytes`);let t=new og(e),n=t.u64();if(n===0||n>h_)throw Error(`websocket frame batch exceeds frame-count limit of ${h_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(m_,`websocket frame`));return j_(t,`websocket frame batch`),r}function v_(e){if(e.length===0||e.length>h_)throw Error(`websocket frame batch exceeds frame-count limit of ${h_}`);for(let t of e)if(t.byteLength>m_)throw Error(`websocket frame exceeds maximum length of ${m_} bytes`)}function y_(e=u_){O_(e,`client wire features`);let t=new ag;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var b_=0,x_=1;function S_(e){if(e[0]!==b_)return!1;let t=new og(e);t.u64();let{min:n,max:r}=k_(t);return n===6&&r===6&&A_(t),!0}function C_(e){return e[0]===x_&&(w_(e),!0)}function w_(e){let t=new og(e),n=t.u64();if(n!==x_)throw Error(`expected WireFrame::Error, got tag ${n}`);let r={code:X_(t.u64()),retry:Q_(t.u64()),message:t.string()};return t.done()||(r.reason=Z_(t.u64())),j_(t,`WireFrame::Error`),r}function T_(e){if(e.code!==`auth_failed`)return null;if(e.reason===`reauthenticate`)return`invalid`;let t=e.reason!==void 0&&!e.reason.startsWith(`unknown:`);return S(t?e.reason:e.message)}var E_=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??He(this.url)??q_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??12688)|18432,this.renewalUrl=P_(e.authJson)?t_(this.url):null,O_(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}),$_(this.socket).then(()=>{if(!this.closing){this.socket.send(N_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(g_([y_(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=M_(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=p_;for(let r of e){let e=r.byteLength+f_;t.length>0&&(t.length>=h_||n+e>d_)&&(this.socket.send(g_(t)),t=[],n=p_),t.push(r),n+=e}t.length>0&&this.socket.send(g_(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())},c_)},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||I_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send($g(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;t>=12e4&&!e?this.silenceTimer=setTimeout(()=>this.watchSilence(!0),c_):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()):this.silenceTimer=setTimeout(()=>this.watchSilence(),s_-t)}async handleMessage(e){for(let t of __(await K_(e))){if(this.closing)return;if(S_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=D_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&-18433})}else if(!(this.negotiated&&t.byteLength===1&&t[0]===l_)){if(this.negotiated&&this.renewalUrl&&e_(t))this.scheduleRenewal(Qg(t));else{if(!this.negotiated){if(C_(t)){let e=w_(t);if(T_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new r_(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(C_(t)){let e=w_(t);if(i_(e)){this.reportTerminal(e),this.close();return}this.onError?.(e)}else this.onFrame(t)}}}}};function D_(e,t=u_){let n=new og(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=k_(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}=A_(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 O_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function k_(e){return{min:e.u64(),max:e.u64()}}function A_(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 j_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function j_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function M_(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 N_(e,t,n,r=!1){let i=JSON.parse(e),a=new T().decode(t),o=ev(i)??G_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Yg]:1}:{}})}function P_(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 F_=3e4;async function I_(e,t){return L_(n_(e),()=>R_(e,t))}async function L_(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,F_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function R_(e,t){try{let n=await $e(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[Xg]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function z_(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=Ae(t.jwt_token);if(!n)return{};if(n.iss===`urn:jazz:local-first`||n.iss===`urn:jazz:anonymous`){let{jazz_pub_key:e,...t}=n;return Se(t)}return Se(n)}function B_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!H_(n))return new TextEncoder().encode(Re(`urn:jazz:system`,`system`));let r=W_(n),i=null;try{i=D(new T({fatal:!0}).decode(t))}catch{}if(i?.account_id&&r){let e=D(r);if(e.issuer!==i.issuer||e.user_id!==i.user_id||e.account_id!==void 0&&e.account_id!==i.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return r?new TextEncoder().encode(r):t}function V_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!H_(t)&&delete t.jwt_token,JSON.stringify(t)}function H_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&Ie(t.issuer)&&Ie(t.user_id)}function U_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||W_(t)!==null}function W_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&H_(e)){let t=e.backend_session;return Re(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=Ae(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,r=t?.sub;if(typeof n==`string`&&typeof r==`string`&&Ie(n)&&Ie(r))return Re(n,r)}return null}function G_(e){return D(e)?.user_id??null}async function K_(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 q_(e){let t=Y_();return J_(e)?Jg(t):t}function J_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function Y_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function X_(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 Z_(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 Q_(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 $_(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 ev(e){let t=e.sub;if(typeof t==`string`&&Ie(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=tv(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&Ie(e))return e}return null}function tv(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(nv(t[1]));return typeof e.sub==`string`&&Ie(e.sub)?e.sub:null}catch{return null}}function nv(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 rv=20,iv=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,av=16,ov={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},sv=250,cv=4;function lv(e){return typeof e?.poll==`function`}function uv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function dv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function fv(e,t){return a_(e)?{kind:`network`,message:e.message}:o_(e)?{kind:`fatal`,message:e.message}:{kind:`wire`,...e,admitted:t}}function pv(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function mv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var hv=new T({fatal:!0}),gv=new WeakMap;function _v(e,t,n,r,i,a=!1){try{return vv(e,t,n,r,i,a)}catch(e){throw Ne(e)}}function vv(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 yv(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 bv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var xv={open:0,quiesced:1,storageCleared:1,closing:2,closed:3},Sv=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;nativeAuthRefused=!1;nativeLinkEverConnected=!1;nativeLinkPoll=null;firstLoadWaitSeen=!1;remoteLink=new Am(()=>this.readRemoteLinkState());linkStatusPublisher=new vs(()=>this.upstreamLinkStatus(),ms);syncStatusPublisher=new vs(()=>this.readSyncStatus(),(e,t)=>_s(e.uploads,t.uploads)&&ms(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(ug(t),n?sg(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=ug(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=Wh(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=_e(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=_v(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=yv(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(this.noteNativeAuthRestored(),!e)return this.nativeAuthRefusalRenewable=!1,this.clearRemoteServerTransportError();let t=e.code?Tm({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:p(),features:this.nativeWireFeatures()}}async connectUpstreamPeer(e){return this===this.ownerRuntime?(this.peerUpstreamAttached=!0,e?this.connectNegotiatedUpstream({protocolVersion:6,features:e.features,authority:e}):await this.db.connectUpstream()):await this.ownerRuntime.connectUpstreamPeer(e)}onPeerTransportWork(e){return this===this.ownerRuntime?(this.peerTransportWorkListeners.add(e),()=>{this.peerTransportWorkListeners.delete(e)}):this.ownerRuntime.onPeerTransportWork(e)}onAuxiliaryTrace(e){return this===this.ownerRuntime?(this.auxiliaryTraceListeners.add(e),this.serverTransport?.setAuxiliaryTraceEnabled?.(!0),()=>{this.auxiliaryTraceListeners.delete(e),this.auxiliaryTraceListeners.size===0&&this.serverTransport?.setAuxiliaryTraceEnabled?.(!1)}):this.ownerRuntime.onAuxiliaryTrace(e)}onQueryCoverageTrace(e){return this===this.ownerRuntime?(this.queryCoverageTraceListeners.add(e),()=>this.queryCoverageTraceListeners.delete(e)):this.ownerRuntime.onQueryCoverageTrace(e)}emitQueryCoverageTrace(e){if(this!==this.ownerRuntime){this.ownerRuntime.emitQueryCoverageTrace(e);return}let t={stage:e,peerActivityEpoch:this.peerTransportActivityEpoch,peerProcessedActivityEpoch:this.peerTransportProcessedActivityEpoch};for(let e of this.queryCoverageTraceListeners)e(t)}notifyPeerTransportActivity(){if(this!==this.ownerRuntime)return this.ownerRuntime.notifyPeerTransportActivity();this.peerTransportActivityEpoch+=1,this.notifyPeerTransportWork(!0)}async progressPeerTransport(){if(this!==this.ownerRuntime)return this.ownerRuntime.progressPeerTransport();let e=this.peerTransportActivityEpoch;await this.runCoreTick(),this.closed||(this.peerTransportProcessedActivityEpoch=Math.max(this.peerTransportProcessedActivityEpoch,e))}retirePeerTransport(e){return this===this.ownerRuntime?(this.auxiliaryReceiveDeadlines.get(e)?.close(),this.auxiliaryReceiveDeadlines.delete(e),this.coreOperation?new Promise((t,n)=>{let r=this.pendingTransportRetirements.get(e)??[];r.push({resolve:t,reject:n}),this.pendingTransportRetirements.set(e,r)}):(e.close(),Promise.resolve())):this.ownerRuntime.retirePeerTransport(e)}setNonDurableClient(){if(this!==this.ownerRuntime)return this.ownerRuntime.setNonDurableClient();if(!this.db.setNonDurableClient)throw Error(`Native runtime does not expose non-durable client mode`);this.db.setNonDurableClient(),this.nonDurableClient=!0}foregroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.foregroundTxTimeHighWater();if(!this.db.foregroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water`);return this.db.foregroundTxTimeHighWater()}quiesceForegroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.quiesceForegroundTxTimeHighWater();if(this.foregroundLeaseCapture)return this.foregroundLeaseCapture;if(this.closed)throw Error(`Native runtime is already ${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(!Ub(n,this.peerIdentity))throw Ey();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?.(ov[e])}remoteLinkState(){return this===this.ownerRuntime?this.readRemoteLinkState():this.ownerRuntime.remoteLinkState()}onRemoteLinkStateChange(e,t){this===this.ownerRuntime?(this.remoteLink.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onRemoteLinkStateChange(e,t)}startNativeLinkPoll(){this.db?.nativeConnectionStatus&&!this.nativeLinkPoll&&!this.closed&&this.linkHasListeners()&&(this.nativeLinkPoll=setInterval(()=>{this.linkHasListeners()?this.linkChanged():this.stopNativeLinkPoll()},sv))}noteFirstLoadWait(e){if(!Vv(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.noteNativeAuthRestored(),this.noteLinkFailure()),this.remoteLink.changed(),this.linkStatusPublisher.changed(),this.syncStatusPublisher.changed()}upstreamLinkStatus(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamLinkStatus();if(this.closed)return K(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?K(`disconnected`):e.authRejected?K(`auth`):e.connected?fs:this.serverTransportError?this.serverTransportErrorRetrying?K(`network`):wm(this.serverTransportError)?K(`authority-changed`,!1):K(`stopped`):ds:us:this.linkStatus?.phase===`stopped`&&wm(this.upstreamRefusal)?K(`authority-changed`,!1):ps(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()}pendingUploadRows(e){return this===this.ownerRuntime?this.closed?null:this.db?.pendingUploadRows?.(e)??null:this.ownerRuntime.pendingUploadRows(e)}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=cs(e,(this.linkFailure??this.serverTransportError)?.message);n&&(this.lastFailure=n)}onUpstreamLinkStatusChange(e,t){this===this.ownerRuntime?(this.linkStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onUpstreamLinkStatusChange(e,t)}onSyncStatusChange(e,t){this===this.ownerRuntime?(this.syncStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onSyncStatusChange(e,t)}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(xv[e]<=xv[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()}else 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(Kb),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Vb(n):y(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Vb(r):void 0,a=Av(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=Nv(n),l=Dv(n);kv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=cb(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:Ev(n)}}let f=Sy(`Insert`,()=>uv(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=Av(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=Dv(a),m=Nv(a);if(kv(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?Vb(o):y(16),v=e===`insert`?lb(h,n,r,t):ub(h,n,r),b=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!b.finishInTransaction)throw await b.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let x=this.ownerRuntime,S,C=new Promise(e=>{S=e});x.pendingStreamingMutations.add(C);let w=new TextEncoder,T=async e=>{let t=65536;for(let n=0;n<e.byteLength;n+=t)await b.push(e.subarray(n,n+t))},E=``;try{for await(let e of xm(i))if(typeof e==`string`){if(g===`Bytea`)throw Error(`Bytea streams require Uint8Array chunks`);let t=E+e;E=``;let n=t.charCodeAt(t.length-1);n>=55296&&n<=56319&&(E=t.slice(-1),t=t.slice(0,-1)),t.length>0&&await T(w.encode(t))}else if(e instanceof Uint8Array)E&&=(await T(w.encode(E)),``),await T(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await T(w.encode(E));let e=x.streamingFinalization,t,n=new Promise(e=>{t=e});x.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await b.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await b.finish())}finally{t()}return{id:M(_),...r}}catch(e){throw await b.abort(),e}finally{S(),x.pendingStreamingMutations.delete(C)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Vb(t),a=Av(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Nv(r),l=Dv(r);kv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=cb(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:Ev(r)}}let f=Sy(`Restore`,()=>uv(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=Vb(t),a=Av(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Nv(r),l=Dv(r);kv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=db(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:Ev(r)};let f=Sy(`Update`,()=>uv(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=Vb(t),o=Nv(i),s=Dv(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=Av(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 Cy(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=db(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:Ev(i)}}if(Ov(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=db(this.table(e),n),d=Sy(`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=Vb(t),a=this.table(e),o=Av(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=Nv(r),u=Dv(r);kv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=db(a,n)}catch(e){throw Cy(`Upsert`,wy(Ty(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:Ev(r)};let p=Sy(`Upsert`,()=>uv(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=Vb(t),i=Av(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=Nv(n),c=Dv(n);kv(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:Ev(n)};let u=Sy(`Delete`,()=>uv(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`&&Be(e,st(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return Wv(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=Wv(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=cb(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,Vb(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=db(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Vb(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,Vb(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 ye);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(hv.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=Av(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(Fv(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=Tv(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 yy(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(Iv(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`);Hv(n,r),this.noteFirstLoadWait(r),Lv(r,this.pendingTxs,this.completedTxs);let i=Wv(t);Qv(e);let a=gy(e),o=Rv(r,this.pendingTxs),s=Bv(n,Yv(a),r),c=this.nativeReadContext(i,o),l=Zv(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`),Xv(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),yb(gb(e),this.schema,uy(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),yb(gb(e),this.schema,uy(a,this.schema).rootColumns)}let u=uy(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),_b(hb(d),this.schema,u)}createSubscription(e,t,n,r){Hv(n,r),this.noteFirstLoadWait(r);let i=Wv(t),a=this.nativeReadContext(i);Qv(e);let o=this.nextSubscriptionId++,s=Bv(n,Yv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:uy(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=Zv(e,this.schema),u=e=>{let t=Fb(e);c.cancelled||this.closed||this.ownerRuntime.closed?Jv(t):(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 mv(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`);n.callback=t,n.terminalError?this.deliverSubscriptionFailure(n):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=V_(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,n=setTimeout(()=>{this.linkTimer?.token===t&&(this.linkTimer=null,this.stepLink({type:`timerFired`,token:t}))},e.afterMs);this.linkTimer={token:t,handle:n};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(Ty(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=B_(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}:fv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new E_({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=>{i_(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()||!this.trustedBackend&&(await this.runWhenCoreIdle(()=>{if(d())return this.installClientSessionClaims(z_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw Dy(`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(Ty(e));this.endLinkAttempt(c,t,{kind:`fatal`,message:t.message})})}async connectNegotiatedUpstream(e){let t=e.authority,n=this.db.connectUpstreamWithSession;if(!t||!n)return await this.db.connectUpstream();let r=p();return await n.call(this.db,e.protocolVersion,e.features,t.node,t.epoch,this.node,r)}nativeWireFeatures(){if(!this.db.wireFeatures)throw Error(`native runtime binding does not expose its wire feature mask; install the matching Jazz native runtime package`);let e=this.db.wireFeatures();if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`native binding returned invalid wire feature mask ${e}`);return e}nativeUpstreamConfigured(){return this===this.ownerRuntime?this.db.nativeConnectionStatus?.().configured===!0:this.ownerRuntime.nativeUpstreamConfigured()}async disconnect(e={}){if(this!==this.ownerRuntime)return this.ownerRuntime.disconnect(e);if(this.db?.disconnectNativeUpstream){this.db.disconnectNativeUpstream(),this.linkChanged();return}let t=this.serverTransport,n=this.serverConnectionAttempt,r=n?.transport;this.linkCloseReason=`server transport disconnected`,this.stepLink({type:`setOffline`,offline:!0}),this.linkCloseReason=`server transport replaced`,this.serverEndpointUrl=null,this.serverAuthJson=null,this.serverReplacementRetirement||this.forgetServerTransportError(),e.rejectWaiters??!0?this.resolveServerTransportErrorWaiters(Error(`server transport disconnected`)):this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.serverTransport=null;let i=[];n?.retirement&&i.push(n.retirement),t&&t!==r&&i.push(Promise.resolve().then(()=>this.retirePeerTransport(t))),this.linkChanged(),await Promise.all(i)}updateAuth(e){if(this!==this.ownerRuntime)return this.ownerRuntime.updateAuth(e);if(this.nativeAuthRefusalRenewable=!1,this.db?.rejectAuthUpdate)return this.db.rejectAuthUpdate();let t=V_(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=V_(e);if(!U_(t))return;let n;try{n=B_(t,this.peerIdentity)}catch{n=null}if(!n||!Ub(n,this.upstreamPrincipal))throw Ey(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){!this.upstreamPrincipal&&U_(e)&&(this.upstreamPrincipal=B_(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.nativeAuthRefused=!0,this.authFailureCallback?.(e)})}noteNativeAuthRestored(){if(!this.nativeAuthRefused||this.closed)return;let e=!1;try{let t=this.db?.nativeConnectionStatus?.();e=!(!t?.connected||t.authRejected)}catch{return}e&&(this.nativeAuthRefused=!1,this.authRestoredCallback?.())}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(Av(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=Tv(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=Tv(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,M(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(lv(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(!lv(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 vy(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Ub(e.identity,this.peerIdentity)?void 0:e.identity:t&&!this.trustedBackend?this.peerIdentity:void 0}backendAttribution(e){if(!this.trustedBackend||!e)return;let t;try{t=JSON.parse(e).attribution}catch{return}if(t===void 0)return;if(typeof t!=`string`||!D(t))throw Error(`backend attribution must be a canonical author subject string`);let n=Av(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=Kv(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`||Kv(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=B_(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(Ty(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(Ty(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||!Bb(n,B_(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,Bv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Be(e,st(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 T().decode(ne(e)))}applySessionClaims(e){e&&!e.backendAuthority&&this.readAuthorizationHost===`trusted-serving`&&this.db.setIdentityClaims&&this.db.setIdentityClaims(e.identity,e.claims)}table(e){let t=this.schema[e];if(!t)throw Error(`unknown table ${e}`);return t}currentTx(e,t){let n=Ev(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Pv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Ub(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`)}else if(e.identity&&(!t||!Ub(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||!Ub(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;else{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);else{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=dv(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 vy(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);else 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)}else this.notifyPeerTransportWork(),e===`immediate`?this.scheduleCoreTick():queueMicrotask(()=>{this.scheduleCoreTick()})}}scheduleCoreTick(){this.coreProgressAllowed()&&(this.coreOperation?this.coreTickAgain=!0:this.coreTickScheduled||(this.coreTickScheduled=!0,queueMicrotask(()=>{this.coreTickScheduled=!1,this.coreProgressAllowed()&&(this.coreOperation?this.coreTickAgain=!0:this.runCoreTick().catch(e=>{try{if(this.db.isNativeForegroundClosed?.())return}catch(e){Kb(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Kb(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=bv(t);n===t?console.warn(`[jazz] ${t}`):(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 Dm(e)}if(this.ownerRuntime.noteNativeAuthRestored(),this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=cv){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()}else 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(()=>vy(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=Mb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Pb(r.reason));return}let i=Sb(r.delta,this.schema,r.reset===!0,t.outputColumns,r.coalesced===!0);i.terminalOperations=dy(r.terminalOperations,t.outputColumns?.rootColumns),t.callback?.(i)}scheduleServerPump(){!this.closed&&this.serverTransport&&(this.serverPumpRunning?this.serverPumpAgain=!0:this.serverPumpScheduled||(this.serverPumpScheduled=!0,setTimeout(()=>{this.serverPumpScheduled=!1,this.closed||this.startServerPump()},av)))}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;else{this.serverPumpRunning=!0;try{let r=this.pendingInboundServerFrames.length>0&&await this.routePendingInboundServerFrames();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=Cv(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=Tm(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(wv(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 Yi(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(Ty(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Kb))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=Cv(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||!Om(e)))return;let r=Ty(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=pv(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{Jv(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 Cv(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function wv(e){let t=Cv([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function Tv(e,t){let n=e.txId;return t.set(n,e),n}function Ev(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Dv(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 Ov(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=Av(e);return n===null||!Ub(n.identity,t)}catch{return!0}}function kv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function Av(e){if(!e)return null;try{let t=JSON.parse(e);if(t.attribution===`system`)throw Error(`Native runtime public session uses reserved issuer`);let n=typeof t.attribution==`string`?D(t.attribution):null;if(n?.issuer===`urn:jazz:system`)throw Error(`Native runtime public session uses reserved issuer`);let r=n?.user_id??(typeof t.user_id==`string`?t.user_id:typeof t.session?.user_id==`string`?t.session.user_id:void 0);if(!r||!Ie(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!Ie(i))throw Error(`session is missing issuer`);let a={account_id:Uv(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`};jv(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=qv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:ne(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Be(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 jv(e,t,n,r,i){if(Ge(e)&&(n!==`device-account`&&n!==`anonymous`&&n!==`external`||!Be({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Mv(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 Nv(e){return Mv(e)??null}function Pv(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 Fv(e,t){let n=Pv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function Iv(e,t){let n=Pv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Lv(e,t,n){let r=zv(e);if(r&&!t.has(r))throw Error(`Query setup failed: Write error: ${Pv(r,n)}`)}function Rv(e,t){let n=zv(e);return n?t.get(n):void 0}function zv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Bv(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 Vv(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 Hv(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 Uv(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 Wv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!Ie(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!Ie(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Uv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};jv(n.issuer,n.user_id,n.authMode,t[Te],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Be(n,t.__jazz_trusted_reserved_session);return{...n,claims:qv(t.claims,n),identity:ne(n),backendAuthority:r}}function Gv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kv(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(Kv).join(`,`)}]`:Gv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Kv(e[t])}`).join(`,`)}}`:`null`}function qv(e,t){return{...Gv(e)?e:{},iss:t.issuer,sub:t.user_id}}function Jv(e){e.close()}function Yv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function Xv(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function Zv(e,t){return Fy(e,t)}function Qv(e){if($v(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function $v(e){let t=JSON.parse(e);return iy(t.select_columns??t.select)||ay(t.conditions)||ey(t.relation_ir)||ty(t.relation_ir)||oy(t.array_subqueries)}function ey(e){return cy(e)}function ty(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(ty);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=ry(e.expr??e.source);if(n&&Os(n))return!0}}return Object.values(t).some(ty)}function ny(e){if(!e||typeof e!=`object`)return null;let t=e;return nb(t.left??t.column)}function ry(e){return!e||typeof e!=`object`?null:`Column`in e?nb(e.Column):nb(e)}function iy(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&Os(ly(e))):!1}function ay(e){return Array.isArray(e)?e.some(cy):!1}function oy(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return iy(t.select_columns??t.select)||sy(t.filters)||oy(t.nested_arrays)}):!1}function sy(e){return Array.isArray(e)?e.some(cy):!1}function cy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(cy);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&Os(ly(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`&&Os(ly(r)))return!0}let n=ny(t.Cmp)??ny(t.In)??ny(t.IsNull)??ny(t.IsNotNull)??ny(t.Contains);return n&&Os(ly(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&cy(t))}function ly(e){return ys(e)}function uy(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:hy(n.table,t,zy(n.select_columns??n.select),Vy(n.array_subqueries,n.table,t)??[])}}function dy(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:fy(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Ks.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=my(a.Insert.key);return{root_key:fy(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:fy(a.Insert.key),row:ah(t,r,py(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=my(a.Update.key);return{root_key:fy(e.root_key),path:i,edit:{Update:{key:fy(a.Update.key),row:ah(t,r,py(a.Update.value))}}}}return`Remove`in a?{root_key:fy(e.root_key),path:i,edit:{Remove:{key:fy(a.Remove.key)}}}:{root_key:fy(e.root_key),path:i,edit:{Move:{key:fy(a.Move.key),index:a.Move.index}}}})}function fy(e){return Array.isArray(e)?e:Array.from(e)}function py(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function my(e){let t=py(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return M(t.subarray(1,17))}function hy(e,t,n,r,i=!0){let a=W(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=As(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=hy(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 gy(e){let t=JSON.parse(e);return _y(t.array_subqueries),JSON.stringify(t)}function _y(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=ys(n);(zy(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}_y(e.nested_arrays)}}function vy(e){return new Promise(t=>setTimeout(t,e))}function yy(e,t){return My(t)?by(e,t):Ny(t)?xy(e,t):null}function by(e,t){let n=Ty(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 xy(e,t){let n=Ty(t),r={kind:`rejected`,transactionId:e,code:ky(Gc(t)),reason:jy(n,Gc(t)),message:n};return Object.defineProperty(r,"message",{enumerable:!1}),r}function Sy(e,t){try{return t()}catch(t){if(Ny(t)){let n=Ty(t),r=Py(n)??n,i=Gc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:ky(i)})}throw t}}function Cy(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function wy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function Ty(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 Ey(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 Dy(e,t){let n=t instanceof Error?t:Error(Ty(t));return Error(`${e}: ${n.message}`,{cause:n})}var Oy={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 ky(e){return e===void 0?`write_rejected`:Oy[e]}var Ay={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 jy(e,t){let n=Py(e);return n===null?e:Ay[ky(t)]??(n||`Write rejected`)}function My(e){return Uc(e)===`transaction_conflict`}function Ny(e){return Uc(e)===`write_rejected`}function Py(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Fy(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=Nm(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Kh(r,[],{relation:i.relation_ir,select:zy(n.select_columns??n.select),partial:Ry(n.select_columns),arraySubqueries:Vy(n.array_subqueries,r,t)})}let i=Zy(n.conditions);if(!i)throw Q();return Kh(r,i.map(e=>Iy(r,e,t)),{limit:ab(n.limit),offset:ob(n.offset),orderBy:By(n.order_by??n.orderBy),select:zy(n.select_columns??n.select),partial:Ry(n.select_columns),arraySubqueries:Vy(n.array_subqueries,r,t)})}function Q(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function Iy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>Iy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:Iy(e,t.predicate,n)};if(Vo(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=>Iy(e,{column:t.column,op:`Eq`,value:r},n))};if(Ly(t)){let r=Jy(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`}:W(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:Jy(e,t.column,i,n)}:{column:t.column,op:`Contains`,value:Yy(i,r.element,!1)})}:{...t,values:t.values.map(r=>Jy(e,t.column,r,n))}}if(t.op===`Contains`){let r=t.column===`id`?{type:`Uuid`}:W(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?Yy(t.value,r.element,!1):Jy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(Ly(t))return{...t,value:Jy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Ly(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Ry(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 zy(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 By(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 Vy(e,t,n){if(e!=null){if(!Array.isArray(e))throw Q(`array_subqueries`);return e.map(e=>Hy(e,t,n))}}function Hy(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=Uy(r.filters,r.table,n),a=zy(r.select_columns),o=Gy(r.order_by),s=Vy(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:qy(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:ib(r.limit),offset:ob(r.offset),requirement:Ky(r.requirement),nestedArrays:s}}function Uy(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=Wy(i);if(!e)throw Q(`array_subqueries.filters`);r.push(...e.map(e=>Iy(t,e,n)))}return r}function Wy(e){let t=$y(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:eb(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:eb(t)}]:null}return null}function Gy(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 Ky(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Q(`array_subqueries.requirement`)}function qy(e,t){let n=`${t}.`;return e.startsWith(n)?e.slice(n.length):e}function Jy(e,t,n,r){let i=t===`id`?{type:`Uuid`}:As(t)??W(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(Xy))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:W(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=>Yy(e,a,!1))}}return Yy(n,i,!0)}function Yy(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:Yy(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&sb(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:Lm(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(Xy))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Yy(e,t.element,!1))}:e}function Xy(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 Zy(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=$y(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=ys(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:eb(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:eb(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:eb(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:eb(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:eb(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:eb(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:eb(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(eb)});break;default:return null}}return t}function Qy(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=Qy(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=$y(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=nb(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=nb(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=nb(e.left),n=rb(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=nb(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(rb);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=tb(s.op);if(!c)return null;let l=nb(s.left),u=rb(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function $y(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($y);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=$y(t.Not);return e?{op:`Not`,predicate:e}:null}let n=Qy(e);return n?.length===1?n[0]:null}function eb(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 sb(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(eb)};throw Q()}function tb(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 nb(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?ys(t):null}function rb(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<=rv&&iv.test(n.value))try{return{type:`BigInt`,value:Lm(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=>rb({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 ib(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function ab(e){return e==null?void 0:ib(e)}function ob(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 sb(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 cb(e,t,n){return pb(e.columns,t,n),fb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function lb(e,t,n,r){return pb(e.columns.filter(e=>e.name!==n),t,r),fb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function ub(e,t,n){return fb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function db(e,t){return fb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function fb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:Th(e),column:e})),i=r.map(({column:e})=>mb(e,t(e),n)),a=new ag;return Xm(a,r),a.bytes(eh(r,i)),a.finish()}function pb(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 mb(e,t,n){let r=t;if(!r){if(e.nullable)return yh(Th(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return _h(e,r)}function hb(e){return new og(e).readVec(Bm)}function gb(e){return qm(new og(e))}function _b(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=vb(a,t,n),o=uh(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=Tb(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(nh({table:a.table,id:M(t.rowId),values:n},s))}}return i}function vb(e,t,n){let r=gv.get(t);r||(r=new Map,gv.set(t,r));let i=dg(e),a=n?void 0:r.get(i);if(a)return a;let o=n??W(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&&zm(n);if(!r)continue;let i=As(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!Wb(r)&&(!ks(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function yb(e,t,n,r=`full-record`){return xb(_b(e.rows,t,n,r),t).slice(0,e.rootCount)}var bb=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function xb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((W(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of bb){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:nh({...e,values:e.values.filter(e=>!i.has(e))},r)})}function Sb(e,t,n=!1,r=null,i=!1){let a=(e,n,i,a)=>{let o=wb(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:Ib(e,t,r),...s&&s.length>0?{splices:Cb(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:M(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{},...n&&i?{reason:`backlog`}:{}}}function Cb(e,t,n){let r=W(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:hv.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 wb(e,t,n,r){return e.flatMap(e=>_b([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function Tb(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 Eb(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 Eb(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:Db(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:hv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:M(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:jb(e.element,t,Ob(r),i)};case`Row`:{let a={type:`Row`,value:Ab(e.columns,t,kb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ee(a),a}}}function Db(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function Ob(e){let t=Db(e);return t?.tag===14?t.inner:void 0}function kb(e){let t=Db(e);return t?.tag===16?t.record:void 0}function Ab(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=uh(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?M(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=M(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:Eb(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 nh({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=M(t.subarray(a,a+16)),a+=16}let s=Hb(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:th(e,c)}}function jb(e,t,n,r=`full-record`){let i=Fh(n??Dh(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(Eb(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=Hb(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:Hb(t,4+(i-1)*4),l=i===a-1?t.length:Hb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(Eb(e,t.subarray(c,l),void 0,n,r))}return s}function Mb(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:Wm(new og(Gb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:Nb(t.reason)};throw Error(`unknown subscription chunk`)}function Nb(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 Pb(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):Tm({code:r,message:n})??Error(n)}function Fb(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 Ib(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?Eh(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=zb(e,i).map((e,t)=>Lb(e,i[t].column_type));return nh({id:e.id,values:a},rh(i,a))}function Lb(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Lb(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:Rb(e.value,t.columns)}:e}function Rb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Lb(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return nh({id:e.id,values:r},rh(t,r))}function zb(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],a=e.valuesByColumn.get(i.name)??(i.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`});n[r]=a}return n}function Bb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Vb(e){let t=Xe(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Hb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ub(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Wb(e){return e.startsWith(Ks)}function Gb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Kb(e){queueMicrotask(()=>{throw e})}var qb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Za(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 Jb(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 Zb(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return Xb(t)},`the app's bearer`)}var Yb=3e4;function Xb(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`)),Yb)})]).finally(()=>clearTimeout(t))}function Zb(e,t,n){return class{type=`arraybuffer`;inner;closed=!1;listeners=[];constructor(r){let i=t(r);i?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`}))}):this.attach(new e(r))}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 Qb=`warn`;function $b(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??Qb}function ex(e){return nt({...e,trustedReservedSession:k(e)})}function tx(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=Ae(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`device-account`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Oe(n??{},r);if(!i||i.issuer!==t.issuer||i.user_id!==t.user_id||i.authMode!==t.authMode)throw Error(`Attached browser worker session does not match its identity token`);l(e,i)}function nx(e){let t=ex(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 rx(e){return!ex(e)&&!!e.adminSecret}function ix(e,t){if(t&&e.jwtToken&&(t.issuer===`urn:jazz:local-first`||t.issuer===`urn:jazz:anonymous`))return{token:e.jwtToken,appId:B(e),claimedAuthor:Re(t.issuer,t.user_id,t.account_id)}}function ax(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function ox(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var sx=class extends bm{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 pm(e.runtimeSources)}admitConfig(e){tx(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,onAuthRestored:i,foregroundNodeLease:a}){$b(e.logLevel);let o={onAuthFailure:r,onAuthRestored:i},s=ix(e,ex(e)),c=rx(e),u=a?.node.slice()??ie(),d=ne(nx(e)),f=ax(e),p=ux(e),m=e.cookieSession&&e.accountId?es(e):void 0,h=this.nativeSchemaView(t,u,d,f,!p,s,c,{appId:B(e),thresholdMs:e.slowQueryThresholdMs,...cx()?{consoleDetail:`summary`}:{}},n,m&&e.serverUrl?Jb(e.serverUrl,m):void 0,e.subscriptionBacklogRows);if(a&&h.seedForegroundTxTimeHighWater(a.confirmedTxTime),p&&(h.setNonDurableClient(),!a))throw Error(`Persistent browser runtime requires a foreground node lease`);let g={appId:B(e),accountId:e.accountId,schema:t,driver:e.driver,serverUrl:e.serverUrl,env:e.env,jwtToken:e.jwtToken,cookieSession:e.cookieSession,adminSecret:e.adminSecret};return l(g,k(e)),te.connectWithRuntime(this.wrapClientRuntime(h,e,t),g,o)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!ux(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=fu(e);return await xo.acquire({runtimeSources:ox(e),dbName:t,storageOwner:Hi(e)})}async acquireForegroundNodeLease(e){if(!lx()||(e.driver?.type??`persistent`)!==`persistent`)return;let{acquireNodeForegroundNodeLease:t}=await ii(async()=>{let{acquireNodeForegroundNodeLease:e}=await import(`./node-foreground-node-lease.browser-2mfp13Qb.js`);return{acquireNodeForegroundNodeLease:e}},[],import.meta.url);return await t({appId:B(e),env:e.env??`dev`,authScope:Vi(e)})}createBrowserWorkerConnection({config:e,schema:n,client:r,onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u,onNewerBuild:d}){let f=r.getRuntime();if(!(f instanceof Sv))throw Error(`Browser worker connections require the native runtime adapter`);let p=ix(e,ex(e));if(rx(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let m=fu(e),h=ne(nx(e));return e.runtimeSources?.browserWorkerPort?new qb(f,e.runtimeSources.browserWorkerPort,ex(e)?.claims??{},m,{onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u},e.runtimeSources.inspectorBinding):new So(f,{runtimeSources:ox(e),schema:n,dbName:m,author:h,selfSignedClientProof:p,initialSyncFlushEvery:ax(e),migrations:f.migrations,appId:B(e),slowQueryThresholdMs:e.slowQueryThresholdMs,...e.subscriptionBacklogRows===void 0?{}:{subscriptionBacklogRows:e.subscriptionBacklogRows},storageOwner:Hi(e),authSessionKey:Vi(e),serverUrl:e.serverUrl?t(e.serverUrl,B(e)):void 0,authJson:JSON.stringify(dx(e)),sessionClaims:ex(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Ii(e,m,Ke(n)),{onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u,onNewerBuild:d})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof Sv))throw Error(`Browser follower connections require the native runtime adapter`);let l=ex(e)?.claims??{},u=new Za(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(dx(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 Sv(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 di({wasmModule:this.wasmModule,collectorUrl:t,runtimeThread:n})}textAnchors(){return vm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function cx(){return typeof window<`u`&&typeof Worker<`u`}function lx(){return typeof process<`u`&&!!process.versions?.node}function ux(e){return cx()&&(e.driver?.type??`persistent`)===`persistent`}function dx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function fx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},gu(e),it(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(it(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 px(e){return(e.driver??{type:`persistent`}).type===`persistent`?fu(e):null}function mx(e){if(typeof window>`u`)return()=>{};let t=px(e.getConfig());if(!t)return()=>{};let n=window;zo(n);let r=Do(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function hx(e){return fx(e,B(e.getConfig()),mx)}async function gx(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(Ve(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 _x=class extends sx{leasePort;inspectorPort;leaseRequested=!1;constructor(e,t){super(),this.leasePort=e,this.inspectorPort=t}wrapClientRuntime(e,t,n){return pt(e,this.inspectorPort,t.runtimeSources.inspectorBinding,n)}async acquireBrowserForegroundNodeLease(e){return this.leaseRequested=!0,xo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:Hi(e)})}};async function vx(e,t,n,r){let i=new MessageChannel,a=new _x(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}};tx(o);let s=Wi(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:Vi(o),storageOwner:Hi(o)};return await gx(r,c,i.port2),o.runtimeSources.inspectorBinding=c,rs(o),await hx(await yd(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 yx(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 $=ot(),bx=200,xx=15e3,Sx=1e3;function Cx(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 wx(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)=>wx(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]&&wx(e[n],t[n]))}function Tx(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&&wx(r.schema,e.schema)})}var Ex=class extends F.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 Dx(){let[e,t]=(0,F.useState)(null),[n,r]=(0,F.useState)([]),[i,a]=(0,F.useState)(null),o=(0,F.useRef)(Promise.resolve()),[s,c]=(0,F.useState)(null),[l,u]=(0,F.useState)(!1),[d,f]=(0,F.useState)(null);return(0,F.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+xx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await je({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(yx(s.contexts,ke()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await Cx(Math.min(bx,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,F.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await Cx(Sx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>Tx(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:yx(n,ke()))}catch{}}})(),()=>t.abort()},[e]),(0,F.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=ke(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){ze(e);return}let n=await vx(r,t.appId,t.dbName,e);a?(s=n,c({client:n,schema:t.schema})):await n.shutdown()}).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)(Ox,{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 Ox({client:e,wasmSchema:t}){let n=new URLSearchParams(window.location.search).get(`route`)??`/`;return(0,$.jsx)(Ex,{children:(0,$.jsx)(tt,{client:e,children:(0,$.jsx)(xe,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(we,{initialEntries:[n],children:(0,$.jsx)(Ze,{})})})})})}(0,ut.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(F.StrictMode,{children:(0,$.jsx)(Dx,{})}));
|
|
4
|
+
`)}function Tu(e){return{...e,branches:[...e.branches]}}function Eu(e,t){if(W(e,t))return e;throw Error(`Query schema is missing table "${t}".`)}function Du(e,t,n){return xu(e,t,n)??{}}function Ou(e,t,n,r){let i=W(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 ku(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(Vo(e._table))throw Error(`History table "${e._table}" is read-only`)}function Au(e,t,n){return ju(e,$u(t,n),t._schema,t._table)}function ju(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("${Wu(n)}")`)}}function Mu(e){return typeof e==`object`&&!!e&&(`splices`in e||`edits`in e)}function Nu(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e}function Pu(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 Fu(e,t,n){if(e>t)throw Error(`Large-value page for "${n}" must have from <= to.`)}function Iu(e,t,n){let r=Ru(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 Lu(e){if(e?.editedFrom===void 0)return e;let{editedFrom:t,...n}=e;return n}function Ru(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}=zu(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 zu(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(!Mu(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=Nu(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=Pu(n.fromUtf8,`fromUtf8`,t),i=Pu(n.toUtf8,`toUtf8`,t);Fu(r,i,t),a={kind:`text_utf8`,from:r,to:i}}else if(e.type===`Bytea`){let e=Pu(n.from,`from`,t),r=Pu(n.to,`to`,t);Fu(e,r,t),a={kind:`bytes`,from:e,to:r}}else if(e.type===`Text`){let e=Pu(n.from,`from`,t),r=Pu(n.to,`to`,t);Fu(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=Nu(e,`Large-value splice for "${t}" is invalid.`),r=a.kind===`text_utf8`,i=Pu(r?n.atUtf8:n.at,`at`,t),o=Pu(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}})})}else 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=Nu(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}})})}else r[t]=o}return{ordinary:r,descriptors:i}}function Bu(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 Vu(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 Hu(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=Vu(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 Uu(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]=Hu(t,r.at);continue}if(t instanceof Uint8Array){if(`fromUtf8`in r)throw Error(`Byte range for "${e}" takes from and to, not fromUtf8 and toUtf8.`);if(r.from>r.to)throw Error(`Byte range for "${e}" ends before it starts.`);n[e]=t.slice(r.from,r.to);continue}if(typeof t!=`string`)throw Error(`Large-value selection for "${e}" has an incompatible column type.`);if(`fromUtf8`in r){let i=new TextEncoder().encode(t),a=Math.min(r.toUtf8,i.length),o=Math.min(r.fromUtf8,a);if(r.fromUtf8>r.toUtf8)throw Error(`UTF-8 range for "${e}" ends before it starts.`);if(o<i.length&&(i[o]&192)==128||a<i.length&&(i[a]&192)==128)throw Error(`UTF-8 range for "${e}" splits a code point.`);n[e]=new T({fatal:!0}).decode(i.slice(o,a));continue}let i=Math.min(r.to,t.length),a=Math.min(r.from,i);if(r.from>r.to)throw Error(`UTF-16 range for "${e}" ends before it starts.`);if(!Bu(t,a)||!Bu(t,i))throw Error(`UTF-16 range for "${e}" splits a surrogate pair.`);n[e]=t.slice(a,i)}return n}function Wu(e){return e.replaceAll(`"`,`\\"`)}function Gu(e,t,n){return e._columnTransformsByTable?.[n]??(t===n?e._columnTransforms:void 0)}function Ku(e,t,n,r){let i=Gu(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?ws(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?Uu(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 qu(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=Ku(e,t,n,r.computedState),i=await a(r.physical)}}var Ju=new WeakMap;function Yu(e,t){let n=Ju.get(e);if(!n)throw Error(`DbTransaction.${t}() requires at least one table operation first`);return n}function Xu(e,t){return Zu(e,t)}function Zu(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 Qu(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 $u(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 ed=1e4;function td(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([]),ed)});return Promise.race([o,c]).finally(()=>clearTimeout(s))}function nd(){let e=f();return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function rd(e,t,n){return Xu(e,Ic(qc(e._table,t,e._schema[e._table].columns,n),e._schema,e._table))}function id(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)&&ad(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 ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.getReader==`function`||typeof t[Symbol.asyncIterator]==`function`}function od(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(ad(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 sd(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 cd(e,t,r,i){return e.kind===`serializable`?new n(t,r,i):new E(t,r,i)}async function ld(e,t,n){let r;try{r=t(sd(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 cd(e,a,s,i())}var ud=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(Ju.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 Yu(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};Ju.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 Le(i,t):new Fe(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}=id(t,r);Qu(t,p);let m=async()=>{let r=$u(t,p),u=ju(o,r,t._schema,t._table),m=e===`insert`?od(t,p):void 0,h=e===`insert`?bu(t._schema,t._table,{...i,...n?{id:n}:{},...m?{branch:m}:{}}):xu(t._schema,t._table,i);return a.streamingMutationInTransaction(e,t._table,u,d,f,s,h,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=nd());let d,f=()=>{d=r.insertInternal(e._table,l,bu(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?Xu(e,Ic(d,e._schema,e._table)):rd(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,bu(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?$u(e,t):t}catch(e){throw this.requireBinding(r).preparation.failure=e,e}let a=ju(r,i,e._schema,e._table);try{return{values:a,value:n===void 0?void 0:rd(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,xu(e._schema,e._table,r),o,s,a)})}update(e,t,n,r){Y(e),this.bindTable(e);let{replacements:i,descriptors:a}=Iu(e,n,r);r=Lu(r);let o=this.resolveClient(e._schema),{openTransactionId:s,session:c,attribution:l}=this.requireBinding(`update`),u=xu(e._schema,e._table,r);this.prepareMutation(e,i,`Update`,n=>{a.length>0?o.updateLargeValuesInternal(e._table,t,n,a,u?.updatedAt,c,l,s,u?.branch):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);Qu(e,t),(a.pending||zc(i)?.pending)&&(t={...t}),a.cancelled?r({}):a.run(()=>J(i,()=>{if(a.cancelled)return;let i;try{i=$u(e,t)}catch(e){throw a.failure=e,e}if(a.failed)throw a.failure;r(ju(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=xu(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=Gs(JSON.parse(a)),s=Eu(e._schema,o.table),c=xc(s,o),l=Ku(e,o,c),u=xu(e._schema,o.table,pu(t))??{},d=await i.queryInternal(bc(a,s,l.physical),{...u,openTransactionId:r},this.context?.readSession);return l.computedState?qu(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(Su(e),t))[0]??null}},dd=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;pendingUploadRowsSnapshots=new Map;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:k(e)};d(this,nt(r)),this.authStateStore=pe(r,n),this.connection=new jl(this.dbForConnection());let i=e.runtimeSources?.browserWorkerPort!==void 0&&e.runtimeSources.inspectorHostPhysicalDbName!==void 0;if(!i){let t=No(this,e.appId??null);this.shutdownAbort.signal.addEventListener(`abort`,t,{once:!0})}mu.set(this,{...i?{prepareQueryOptions:e=>o(e)}:{},all:(e,t)=>i?this.allFromInspectorAttachment(e,t):this.allInternal(e,pu(t)),subscribeDelta:(e,t,n)=>i?this.subscribeFromInspectorAttachment(e,t,n):this.subscribeDelta(e,t,pu(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=>(wd.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`),pu(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,B(this.config),e),n=Oe(Ae(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();e===0?this.refreshLocalFirstToken():(this.localFirstRefreshTimer&&clearTimeout(this.localFirstRefreshTimer),this.localFirstRefreshTimer=setTimeout(()=>this.refreshLocalFirstToken(),e))}publishAuthStateWithInternalSession(e,t){d(this,e),t()}applyAuthUpdate(e,t){this.runtimeSource.assertAuthUpdateAllowed();let n=e??void 0,r=this.config.jwtToken,i=this.config.cookieSession,a=k(this.config);return r===n&&i===void 0&&JSON.stringify(a)===JSON.stringify(t)&&this.authStateStore.getState().error===void 0||!this.authStateStore.validateJwtToken(n,t)?!1:(this.connection.updateAuth({mode:`bearer`,jwtToken:n,trustedReservedSession:t}),this.publishAuthUpdate(n,t),!0)}publishAuthUpdate(e,t){let n={...this.config,jwtToken:e,cookieSession:void 0};l(n,t);let r=nt(n);this.config.jwtToken=e,this.config.cookieSession=void 0,l(this.config,t),this.publishAuthStateWithInternalSession(r,()=>{this.authStateStore.applyJwtToken(e,t)})}applyCookieSessionUpdate(e){this.runtimeSource.assertAuthUpdateAllowed();let t=e??void 0,n=this.config.cookieSession,r=this.config.jwtToken,i=k(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={...this.config,jwtToken:void 0,cookieSession:t},s=nt(o);return this.config.jwtToken=void 0,this.config.cookieSession=t,l(this.config,void 0),this.publishAuthStateWithInternalSession(s,()=>{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 $l(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);else for(let t of this.mutationErrorListeners)t(e)}async refreshAccountAuth(e){return this.refreshOwnAccountAuth(e)}async refreshOwnAccountAuth(e){ts(this.config);let t=it(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`?Oe(Ae(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}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?Ae(t):null;return!t||n?.iss!==`urn:jazz:local-first`||typeof n.exp!=`number`||n.exp<=Date.now()/1e3+cu||e?.audience!==void 0&&n.aud!==Ye(e.audience)?null:t}let t=e?.ttlSeconds??60,n=e?.audience??B(this.config);return this.mintLocalFirstToken(this._localFirstSecret,n,t)}onOwnAuthChanged(e){return this.authStateStore.onChange(t=>e(t))}onAuthChanged(e){return this.registerMovable(t=>t.authStateStore.onChange(t=>{e(t)}))}registerMovable(e,t=!1){let n=e(this),r=!1,i={move:i=>{r||(n(),n=t?e(this):i.registerMovable(e))}};return this.movable.add(i),()=>{r||(r=!0,this.movable.delete(i),n())}}onMutationError(e){if(this.replaced)throw this.replaced;return this.registerMovable(t=>{for(t.mutationErrorListeners.add(e);t.pendingMutationErrorEvents.length>0;)e(t.pendingMutationErrorEvents.shift());return()=>{t.mutationErrorListeners.delete(e)}})}textAnchors(){return this.runtimeSource.textAnchors()}getSyncStatus(){let e=Ed(this.connection.syncStatus(),this.authStateStore.getState().error);return this.syncStatusSnapshot&&gs(e,this.syncStatusSnapshot)?this.syncStatusSnapshot:(this.syncStatusSnapshot=e,e)}onSyncStatusChange(e){let t=this.getSyncStatus(),n=n=>{n===t||gs(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}getPendingUploadRows(e){return this.pendingUploadRowsSnapshot(e._table,this.connection.pendingUploadRows(e._table))}pendingUploadRowsSnapshot(e,t){let n=this.pendingUploadRowsSnapshots.get(e);return n!==void 0&&os(n,t)?n:(this.pendingUploadRowsSnapshots.set(e,t),t)}onPendingUploadRowsChange(e,t){let n=this.getPendingUploadRows(e),r=e=>{os(e,n)||(n=e,t(e))};return this.registerMovable(t=>{let n=t.pendingUploadRowsChangeRegistration(e,r);return t.successor&&r(t.getPendingUploadRows(e)),n},!0)}pendingUploadRowsChangeRegistration(e,t){return this.onPendingUploadRowsChangeHere(e,t)}onPendingUploadRowsChangeHere(e,t){let n=new AbortController,r=()=>n.abort();this.shutdownAbort.signal.addEventListener(`abort`,r,{once:!0}),n.signal.addEventListener(`abort`,()=>this.shutdownAbort.signal.removeEventListener(`abort`,r),{once:!0});let i=this.getPendingUploadRows(e);return this.connection.onSyncStatusChange(()=>{let n=this.getPendingUploadRows(e);n!==i&&(i=n,t(n))},n.signal),r}async waitForSync(e={}){let{timeoutMs:t,signal:n}=e;A(t),this.assertOpen(),n?.throwIfAborted();let r=new AbortController,i=()=>r.abort(n.reason);n?.addEventListener(`abort`,i,{once:!0});let a=()=>r.abort(Error(`Db was shut down`));this.shutdownAbort.signal.addEventListener(`abort`,a,{once:!0});let o=t===void 0?void 0:setTimeout(()=>r.abort(new O(`global`,t)),t);try{await this.waitForUpstreamSync(r.signal)}finally{o!==void 0&&clearTimeout(o),n?.removeEventListener(`abort`,i),this.shutdownAbort.signal.removeEventListener(`abort`,a)}}waitForUpstreamSync(e){return this.connection.waitForSync(e)}getConfig(){let{browserWorkerPort:e,browserWorkerSession:t,...n}=this.config.runtimeSources??{};return structuredClone({...this.config,runtimeSources:Object.keys(n).length>0?n:void 0})}setDevMode(e){this.config.devMode=e}async disconnect(){if(this.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})=>Tu(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=ju(`Insert`,e._columnTransforms?$u(e,t):t,e._schema,e._table),o=this.getAccessContext(),s=!!zc(r)?.pending;s&&!i&&(i=nd());let c=s?rd(e,i,a):void 0,l=J(r,()=>r.insert(e._table,a,bu(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?Xu(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}=id(e,t);Qu(e,o),Cl(this);let s=n?.id;return J(r,async()=>{let t=ju(`Insert`,$u(e,o),e._schema,e._table),c=this.getAccessContext(),l=od(e,o);return r.insertStreaming(e._table,t,i,a,bu(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}=id(e,n);Qu(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=ju(`Update`,$u(e,s),e._schema,e._table);return i.updateStreaming(e._table,t,n,a,o,xu(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}=id(e,n);Qu(e,s),Cl(this);let c=this.getAccessContext();return J(i,async()=>{let n=ju(`Upsert`,$u(e,s),e._schema,e._table);return i.upsertStreaming(e._table,t,n,a,o,xu(e._schema,e._table,r),c?.writeSession,c?.attribution)})}restore(e,t,n,r){Y(e);let i=this.getClient(e._schema),a=ju(`Restore`,e._columnTransforms?$u(e,n):n,e._schema,e._table),o=this.getAccessContext(),s=zc(i)?.pending?rd(e,t,a):void 0,c=J(i,()=>i.restore(e._table,t,a,bu(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=>Xu(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);Qu(e,n),zc(o)?.pending&&(n={...n});let s=this.getAccessContext(),c=xu(e._schema,e._table,i),l=J(o,()=>{let i=n=>{let i=ju(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=$u(e,n);if(r!==`Update`)return i(l);try{return i(l)}catch(n){if(Uc(n)!==`not_observed`)throw n;return td(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 Fe(l.then(e=>e.txId),o):l)}update(e,t,n,r){Y(e);let i=this.getClient(e._schema),{replacements:a,descriptors:o}=Iu(e,n,r);r=Lu(r);let s=this.getAccessContext();return o.length>0?this.prepareMutation(e,t,a,`Update`,r,n=>i.updateLargeValues(e._table,t,n,o,xu(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,xu(e._schema,e._table,n),i?.writeSession,i?.attribution));return this.wrapWriteWait(a instanceof Promise?new Fe(a.then(e=>e.txId),r):a)}async canInsert(e,t){let n=this.getClient(e._schema),r=Au(`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=Au(`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 ud.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 ld(t,e,()=>Yu(t,`result`).ownerClient)}serializableTransaction(e){let t=this.beginSerializableTransaction();return ld(t,e,()=>Yu(t,`result`).ownerClient)}async upgradeToLocalFirst(e){await au(this,e)}isLocalFirst(){return!iu(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,pu(t))}catch(n){if(this.successor&&Td(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=Gs(JSON.parse(o)),c=Eu(e._schema,s.table),l=xc(c,s),u=Ku(e,s,l),d=Du(e._schema,s.table,t),f=bc(o,c,u.physical),p=Cu(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?qu(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(Su(e),t))[0]??null}subscribe(e,t,n,r){let{onUpdate:i,onError:a}=typeof t==`function`?{onUpdate:t,onError:void 0}:t,o={onDelta:e=>{if(e.all===void 0)throw Error(`Jazz subscription update is missing its materialized result.`);let t=new Map;for(let n of e.delta)n.kind===ue.Updated&&n.splices&&t.set(n.id,n.splices);i(e.all,{splices:t,...e.reset&&e.reason?{reason:e.reason}:{}})},...a===void 0?{}:{onError:a}};return this.subscribeDelta(e,o,pu(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=>{c?(c=!1,i({delta:e.delta,all:e.all??[],reset:!0})):i(e)},...a===void 0?{}:{onError:a}},n,r);return o??=l.ready,l}),l=(()=>c());return o&&Object.defineProperty(l,"ready",{value:o}),l}subscribeDeltaHere(e,t,n,r){let{onDelta:i,onError:a}=t,o=this.getClient(e._schema),c=this.connection.initialExplicitOfflineState(),l=new u,d=e._build(),f=Gs(JSON.parse(d)),p=Eu(e._schema,f.table),m=xc(p,f),h=Ku(e,f,m),g=bc(d,p,h.physical),_=c===null,v=[],y=Du(e._schema,f.table,n);y.splices&&(Ou(p,m,e,y.splices),ku(f,h.physical,y.splices));let b=this.getAccessContext()?.readSession??r,x=null,S=!1,C=!1,w=new AbortController,T=e=>{e.retired=!0;let t=e.id;t===null||e.nativeUnsubscribed||(e.nativeUnsubscribed=!0,o.unsubscribe(t))},E=e=>{if(!a)console.error(`Unhandled Jazz subscription error`,e);else try{a(e)}catch(e){console.error(`Jazz subscription error callback failed`,e)}},D=e=>{if(e.installing)return;let t=e.terminalError;t===null||e.terminalDelivered||C||(e.terminalDelivered=!0,C=!0,_=!1,v.length=0,x===e&&(x=null),T(e),e.predecessor!==null&&(T(e.predecessor),e.predecessor=null),w.abort(),this.liveSubscriptionEnders.delete(ce),this.unregisterActiveQuerySubscriptionTrace(ie),l.clear(),E(t))},O=(e,t)=>{S||C||x!==e||e.terminalDelivered||(e.terminalError??=s(t),D(e))},ee=(e=null)=>{let t={id:null,installing:!1,terminalError:null,terminalDelivered:!1,retired:!1,nativeUnsubscribed:!1,predecessor:e};return x=t,t},te=e=>{if(!(S||C||x===null)){if(!_)v.push(e);else try{i(e)}catch(e){let t=x;t!==null&&O(t,e)}}},ne=t=>{if(!(S||C||x===null))try{te(l.handleDelta(t,h.transform))}catch(t){if(!(t instanceof Xc)||!h.computedState||h.computedState.version===h.version)throw t;h=Ku(e,f,m,h.computedState),y.splices&&ku(f,h.physical,y.splices),g=bc(d,p,h.physical),T(x);let n=ee();l.clear(),v.length=0,this.unregisterActiveQuerySubscriptionTrace(ie),ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),queueMicrotask(()=>{this.stopping||re(n)})}},re=(e,t=y)=>{if(S||x!==e||e.retired||e.terminalError!==null)return null;let n=[];e.installing=!0;try{e.id=o.subscribeInternal(g,{onUpdate:t=>{if(!(S||x!==e||e.terminalError!==null)){if(e.installing)n.push(t);else try{ne(t)}catch(t){O(e,t)}}},onError:t=>{O(e,t)}},t,b)}catch(t){return e.installing=!1,O(e,t),null}if(e.installing=!1,S||x!==e||e.retired)return T(e),null;if(e.terminalError!==null)return D(e),null;try{for(let t of n){if(x!==e||e.terminalError!==null)break;ne(t)}}catch(t){return O(e,t),null}return S||x!==e||e.retired?null:e},ie=this.registerActiveQuerySubscriptionTrace(g,f.table,y),ae=()=>{S||(S=!0,this.liveSubscriptionEnders.delete(ce),_=!1,v.length=0,w.abort(),this.unregisterActiveQuerySubscriptionTrace(ie),x!==null&&(T(x),x.predecessor!==null&&(T(x.predecessor),x.predecessor=null)),x=null,l.clear())},oe=c?.then(()=>{if(!(S||C||x===null||this.stopping)){_=!0;for(let e of v.splice(0)){if(S||C||x===null)return;te(e)}}}).catch(e=>{if(!(S||C||x===null||this.stopping))throw O(x,e),e});oe&&oe.catch(()=>void 0);let se=ee(),ce=e=>{x!==null&&O(x,e)};this.liveSubscriptionEnders.add(ce);let le=y.tier===`remote`?`server`:`runtime`;this.connection.shouldDeferSubscriptionStart(le)?this.ensureReady(le,w.signal).then(()=>re(se)).catch(e=>{S||w.signal.aborted||this.stopping||O(se,e)}):re(se);let ue=ae;return oe&&Object.defineProperty(ue,"ready",{value:oe}),ue}markReplaced(e){if(this.successor?.markReplaced(e),this.replaced)return;let t=new ou(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&&gs(a,s)?s:s=a},l=new Map,u=n=>{let r=t.getPendingUploadRows(n);if(!i)return r;let a=e.prototype.getPendingUploadRows.call(this,n),o=r===null||a===null?null:[...new Set([...r,...a])].sort(),s=l.get(n._table);return s!==void 0&&os(s,o)?s:(l.set(n._table,o),o)},d={getSyncStatus:c,getPendingUploadRows:u,pendingUploadRowsChangeRegistration:(e,n)=>{let r=u(e),o=()=>{let t=u(e);t!==r&&(r=t,n(t))},s=t.onPendingUploadRowsChange(e,o),c=i?this.onPendingUploadRowsChangeHere(e,o):()=>{};return a.add(o),()=>{s(),c(),a.delete(o)}},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 hu)Object.defineProperty(this,e,{configurable:!0,value:d[e]??((...n)=>t[e](...n))});Object.defineProperty(this,"syncStatusChangeRegistration",{configurable:!0,value:d.syncStatusChangeRegistration}),Object.defineProperty(this,"pendingUploadRowsChangeRegistration",{configurable:!0,value:d.pendingUploadRowsChangeRegistration}),(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;A(n),r?.throwIfAborted();let i=new AbortController,a=()=>i.abort(r.reason);r?.addEventListener(`abort`,a,{once:!0});let o=n===void 0?void 0:setTimeout(()=>i.abort(new O(`global`,n)),n);try{await Promise.race([this.connection.waitForSync(i.signal),t])}finally{o!==void 0&&clearTimeout(o),r?.removeEventListener(`abort`,a)}}offlineRequested;drain=null;streamsMayFinish=null;letStreamsFinish(){return this.streamsMayFinish?.abort(),this.streamsMayFinish=new AbortController,this.streamsMayFinish}async stopOwnRuntime(t={}){let n=this.drain;if(!n)return this.shutdown(t);n.endStreamWait(),t.waitForSync||n.abort(),await n.done.catch(()=>{}),await e.prototype.shutdown.call(this)}current(){return this.successor?.current()??this}shutdown(e={}){if(this.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 Go(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 Ko(this.phase);if(this.gracefulDrain)throw new Ko(`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:wu(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 fd(){let e=y(32),t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function pd(e,t,n){return{secret:e,audience:t,ttlSeconds:n,nowSeconds:BigInt(Math.floor(Date.now()/1e3))}}function md(e,t){if(!t.supportsBrowserWorker||!Cd()||lu(e.driver).type!==`persistent`||!e.accountId||!e.accountRegistryAuthority||e.adminSecret||e.runtimeSources?.browserWorkerPort)return;let n=t.acquireBrowserForegroundNodeLease(e);return n.catch(()=>void 0),hd.set(n,gd(e)),n}var hd=new WeakMap;function gd(e){try{let t=e.runtimeSources;return JSON.stringify([fu(e),Hi(e),t?.wasmUrl??null,t?.baseUrl??null,t?.brokerWorkerUrl??null,t?.wasmVersion??null,!!(t?.wasmModule||t?.wasmSource)])}catch{return}}function _d(e,t){let n=hd.get(e);return n!==void 0&&n===gd(t)}async function vd(e){if(e&&!bd.has(e)){bd.add(e);try{let t=await e;await t.returnWithHighWater(t.confirmedTxTime)}catch{}}}async function yd(e,t,n){let r=n;try{return await xd(e,t,()=>(r??=md(e,t),r))}finally{vd(r)}}var bd=new WeakSet;async function xd(e,t,n){if(ts(e),Sd(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?Pr(e.secret):null,i={...e};l(i,k(e));let a=n();await t.load(e);let{secret:o,jwtToken:s,cookieSession:c,...u}=e,d=r;if(d){let n=d;if(!e.jwtToken){let r=t.mintLocalFirstToken(pd(n,B(e),3600)),a=Oe(Ae(r)??{},`device-account`);i={...u,jwtToken:r},l(i,a)}}else if(!e.jwtToken&&!e.cookieSession&&!e.adminSecret){let n=fd(),r=t.mintAnonymousToken(pd(n,B(e),3600)),a=Oe(Ae(r)??{},`anonymous`);i={...u,jwtToken:r},l(i,a)}ns(e,i),t.admitConfig(i);let f=lu(i.driver),p=t.supportsBrowserWorker&&Cd()&&f.type===`persistent`,m=a&&p&&_d(a,i)?a:void 0;m?bd.add(m):a&&await vd(a);let h=p?await dd.createWithBrowserWorker(i,t,m):await dd.createWithDirectConnection(i,t);return d&&h.initLocalFirstAuth(d,3600,!e.jwtToken),h}function Sd(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 Cd(){return typeof window<`u`&&typeof Worker<`u`}var wd=new WeakMap;function Td(e){for(let t=e;t instanceof Error;t=t.cause)if(t instanceof su)return!0;return!1}function Ed(e,t){let{link:n}=e;return n.state!==`offline`||n.reason!==`auth`||t===void 0?e:{...e,link:{...n,authReason:t}}}var Dd={napi:`2cfa240f13ba55959d2723add8049c60d5d69bea2f5d6dc93d458912b8aaaff2`,wasm:`bde0b4f806aadc6d6864c014b53311739bb921aeb9855eb6b18f26dd14babc04`},Od=`JAZZ_NATIVE_ARTIFACT_MISMATCH`,kd=class extends Error{kind;expected;actual;missingExport;name=`NativeArtifactMismatchError`;code=Od;constructor(e,t,n,r,i){super(e),this.kind=t,this.expected=n,this.actual=r,this.missingExport=i}};function Ad(e,t,n=[]){let r=Dd[t.toLowerCase()];if(typeof e.nativeArtifactFingerprint!=`function`)throw new kd(`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 kd(`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 kd(`Jazz ${t} artifact is incomplete despite matching fingerprint: missing ${i}.`,t,r,r,i)}var jd=class extends Error{},Md=class extends Error{},Nd=new Set(`\\.+*?()|[]{}^$#&-~`),Pd=new Set(`imsUuRx`),Fd=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]);function Id(e){return Nd.has(e)?!0:e.codePointAt(0)>127?!1:!/[0-9A-Za-z<>]/.test(e)}var Ld=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 jd&&this.fancy?new Md(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 jd(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,Pd.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++,Id(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&&Fd.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`}}},Rd={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]]},zd=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\p{Join_Control}`,Bd={d:`\\p{Nd}`,s:`\\p{White_Space}`,w:zd};function Vd(e){return/^[A-Za-z0-9]$/.test(e)?e:`\\u{${e.codePointAt(0).toString(16)}}`}function Hd(e){return e.map(([e,t])=>{let n=Vd(String.fromCodePoint(e));return e===t?n:`${n}-${Vd(String.fromCodePoint(t))}`}).join(``)}var Ud=class{parsed;constructor(e){this.parsed=e}emit(e){switch(e.kind){case`flags`:return``;case`literal`:return Vd(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 Md(`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=`[${zd}]`;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=Vd(e.char);return{fragment:t,atom:`[${t}]`}}case`range`:{let t=`${Vd(e.start)}-${Vd(e.end)}`;return{fragment:t,atom:`[${t}]`}}case`perl`:return Wd(this.parsed.fancy?Bd[e.perl]:Hd(Rd[e.perl]),e.negated);case`ascii`:return Wd(Hd(Rd[e.ascii]),e.negated);case`unicode`:return Wd(Gd(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 Wd(e,t){return t?{atom:`[^${e}]`}:{fragment:e,atom:`[${e}]`}}function Gd(e){for(let t of[e,`Script=${e}`])try{return RegExp(`\\p{${t}}`,`u`),`\\p{${t}}`}catch{}throw new Md(`the Unicode class \`${e}\``)}function Kd(e){try{return new Ld(e).parse(),!0}catch(e){return e instanceof Md}}var qd=new Map,Jd=1024;function Yd(e){let t=qd.get(e);if(t)return t;let n=new Ld(e).parse();if(n.fancyInvalid.length>0)throw new jd(n.fancyInvalid[0]);if(n.unsupported.length>0)throw new Md(n.unsupported[0]);let r=new Ud(n).emit(n.node);return t=new RegExp(r,n.caseInsensitive?`iu`:`u`),qd.size>=Jd&&qd.clear(),qd.set(e,t),t}function Xd(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 Zd(e){return e%4==0&&e%100!=0||e%400==0}function Qd(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=Xd(e,5),r=Xd(e,8);return n===void 0||n<1||n>12||r===void 0||r===0?!1:n===2?r<=(Zd(t)?29:28):r<=([4,6,9,11].includes(n)?30:31)}function $d(e){if(e.length<9||e[2]!==`:`||e[5]!==`:`)return!1;let t=Xd(e,0),n=Xd(e,3),r=Xd(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=Xd(e,i+1),s=Xd(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 ef(e){let t=e.search(/[Tt]/);return t<0?!1:Qd(e.slice(0,t))&&$d(e.slice(t+1))}var tf=`(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`,nf=`${tf}(?:\\.${tf}){3}`,X=`[0-9A-Fa-f]{1,4}`,rf=`(?:${X}:${X}|${nf})`,af=[`(?:${X}:){6}${rf}`,`::(?:${X}:){5}${rf}`,`(?:${X})?::(?:${X}:){4}${rf}`,`(?:(?:${X}:){0,1}${X})?::(?:${X}:){3}${rf}`,`(?:(?:${X}:){0,2}${X})?::(?:${X}:){2}${rf}`,`(?:(?:${X}:){0,3}${X})?::${X}:${rf}`,`(?:(?:${X}:){0,4}${X})?::${rf}`,`(?:(?:${X}:){0,5}${X})?::${X}`,`(?:(?:${X}:){0,6}${X})?::`].map(e=>`(?:${e})`).join(`|`),of=RegExp(`^${nf}$`),sf=RegExp(`^(?:${af})$`),cf=e=>of.test(e),lf=e=>sf.test(e);function uf(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=gf(e.slice(4));if(t===void 0||!bf(t))return!1}}return!0}var df=36,ff=1,pf=26,mf=4294967295;function hf(e,t,n){let r=Math.trunc(e/(n?700:2));r+=Math.trunc(r/t);let i=0;for(;r>455;)r=Math.trunc(r/35),i+=df;return i+Math.trunc(36*r/(r+38))}function gf(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=df;;e+=df){if(c>=r.length)return;let n=_f(r.charCodeAt(c++));if(n===void 0||(s+=n*t,n*t>mf||s>mf))return;let i=e<=o?ff:e>=o+pf?pf:e-o;if(n<i)break;if(t*=df-i,t>mf)return}let n=i.length+1;if(o=hf(s-e,n,e===0),a+=Math.trunc(s/n),a>mf||(s%=n,a>1114111||a>=55296&&a<=57343))return;i.splice(s,0,a),s++}return String.fromCodePoint(...i)}function _f(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 vf=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))),yf=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347].map(e=>String.fromCodePoint(e)));function bf(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||!vf.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(yf.has(o))return!1}return!(n&&!r||i&&a)}var xf=new TextEncoder;function Sf(e){return xf.encode(e).length}function Cf(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)}var wf=/^[\p{Alphabetic}\p{N}]$/u,Tf=new Set("!#$%&'*+-/=?^_`{|}~");function Ef(e){return wf.test(e)||Tf.has(e)||Cf(e)}function Df(e){return e.length>0&&[...e].every(Ef)}function Of(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||Cf(n)))return!1}return!0}function kf(e){let t=e.codePointAt(0);return t>=33&&t<=90||t>=94&&t<=126||Cf(e)}function Af(e){return e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu,``)}function jf(e){let t=e,n=``,r=e.lastIndexOf(` <`);if(r>=0){let i=Af(e.slice(r+2));if(!i.endsWith(`>`))return!1;t=i.slice(0,-1),n=Af(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||Sf(a)>64)return!1;if(a.startsWith(`"`)&&a.endsWith(`"`)){if(a.length<=2||!Of(a.slice(1,-1)))return!1}else if(!a.split(`.`).every(Df))return!1;if(o.length===0||Sf(o)>254)return!1;if(o.startsWith(`[`)&&o.endsWith(`]`)){let e=o.slice(1,-1);return[...e].every(kf)?e.startsWith(`IPv6:`)?lf(e.slice(5)):cf(e):!1}for(let e of o.split(`.`)){let t=[...e];if(t.length===0||!wf.test(t[0])||!wf.test(t[t.length-1])||Sf(e)>63||!Df(e))return!1}return uf(o)}var Mf=`A-Za-z0-9\\-._~`,Nf=`!$&'()*+,;=`,Pf=`%[0-9A-Fa-f]{2}`,Ff=`(?:[${Mf}${Nf}:@]|${Pf})`,If=`${Ff}*`,Lf=`${Ff}+`,Rf=`(?:[${Mf}${Nf}@]|${Pf})+`,zf=`\\[(?:${af}|[vV][0-9A-Fa-f]+\\.[${Mf}${Nf}:]+)\\]`,Bf=`(?:${`(?:[${Mf}${Nf}:]|${Pf})*`}@)?(?:${zf}|${`(?:[${Mf}${Nf}]|${Pf})*`})(?::[0-9]*)?`,Vf=`(?:/${If})*`,Hf=`/(?:${Lf}(?:/${If})*)?`,Uf=`${Lf}(?:/${If})*`,Wf=`${Rf}(?:/${If})*`,Gf=`(?:${Ff}|[/?])*`,Kf=`[A-Za-z][A-Za-z0-9+\\-.]*`,qf=`(?://${Bf}${Vf}|${Hf}|${Uf}|)`,Jf=`(?://${Bf}${Vf}|${Hf}|${Wf}|)`,Yf=`(?:\\?${Gf})?(?:#${Gf})?`,Xf=RegExp(`^${Kf}:${qf}${Yf}$`),Zf=RegExp(`^(?:${Kf}:${qf}|${Jf})${Yf}$`);function Qf(e){return e===``||/^(?:\/(?:[^~/]|~[01])*)+$/.test(e)}function $f(e){let t=/^(0|[1-9][0-9]*)(.*)$/s.exec(e);if(!t)return!1;let n=t[2];return n===``||n===`#`||n.startsWith(`/`)&&Qf(n)}var ep=new Set(`+#./;?&=,!@|`),tp=new Set(`"'<>%\\^\`{|}`);function np(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||ep.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||tp.has(r))return!1;t++}}return!0}var rp={date:Qd,"date-time":ef,email:jf,hostname:uf,ipv4:cf,ipv6:lf,"json-pointer":Qf,regex:Kd,"relative-json-pointer":$f,time:$d,uri:e=>Xf.test(e),"uri-reference":e=>Zf.test(e),"uri-template":np},ip=class{value;constructor(e){this.value=e}},ap=2n**64n-1n,op=-(2n**63n),sp=/-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y,cp=/[ \t\n\r]*/y;function lp(e){let t=0,n=()=>{throw SyntaxError(`invalid JSON at position ${t}`)},r=()=>{cp.lastIndex=t,cp.test(e),t=cp.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=()=>{sp.lastIndex=t;let r=sp.exec(e);if(!r)return n();t=sp.lastIndex;let i=r[0],a=Number(i);if(r[1]!==void 0||r[2]!==void 0)return Number.isInteger(a)?new ip(a):a;if(Object.is(a,-0))return new ip(a);if(Number.isSafeInteger(a))return a;let o=BigInt(i);return o<op||o>ap?new ip(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 up(e){return typeof e==`number`||typeof e==`bigint`||e instanceof ip}function dp(e){return e instanceof ip?e.value:e}function fp(e,t){return typeof e==`bigint`?!0:e instanceof ip?!t:Number.isInteger(e)}function pp(e){if(typeof e==`bigint`)return e.toString();if(e instanceof ip){if(Object.is(e.value,-0))return`-0.0`;let t=Number.isSafeInteger(e.value)?String(e.value):mp(e.value);return/[.e]/.test(t)?t:`${t}.0`}return typeof e==`number`&&Number.isInteger(e)?mp(e):Array.isArray(e)?`[${e.map(pp).join(`,`)}]`:typeof e==`object`&&e?`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${pp(t)}`).join(`,`)}}`:JSON.stringify(e)}function mp(e){return Number.isFinite(e)&&Math.abs(e)<1e21?BigInt(e).toString():String(e)}function hp(e){if(e instanceof ip)return e.value;if(Array.isArray(e))return e.map(hp);if(typeof e!=`object`||!e)return e;let t=Object.create(null);for(let[n,r]of Object.entries(e))t[n]=hp(r);return t}function gp(e,t){if(up(e))return up(t)?dp(e)==dp(t):!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>gp(e,t[n]));if(typeof e==`object`&&e){if(typeof t!=`object`||!t||Array.isArray(t)||up(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&gp(e[n],t[n]))}return e===t}function _p(e,t){let n=Number(dp(e)),r=Number(dp(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]=vp(n),[o,s]=vp(r);if(o===0n)return!0;let c=a*o;return i*s%c===0n}function vp(e){let t=0,n=e;for(;!(Math.abs(Math.floor(n)-n)<2**-52);)if(t++,n=e*yp(10,t),!Number.isFinite(n))return bp(e);let r=BigInt(Math.trunc(Math.abs(n)));return[e<0?-r:r,BigInt(yp(10,t))]}function yp(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 bp(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 xp={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Sp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Cp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},wp=new URL(`json-schema:///`);function Tp(e){return encodeURI(e.replace(/~/g,`~0`).replace(/\//g,`~1`))}function Ep(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dp(e,t=Object.create(null),n=[],r=wp,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(!Ep(e))return t;let o=e.$id??e.id;if(typeof o==`string`){let t=new URL(o,r.href);t.hash.length>1||(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(Sp[i]&&Array.isArray(a))for(let e of a)Dp(e,t,n,r,!1);else if(xp[i])Dp(a,t,n,r,!1);else if((Cp[i]||i===`dependencies`)&&Ep(a))for(let e in a)Dp(a[e],t,n,r,!1)}return t}function Op(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(Ep(i)&&Object.prototype.hasOwnProperty.call(i,t))i=i[t];else return}return typeof i==`boolean`||Ep(i)?i:void 0}}function kp(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 Ap(e){if(e===null)return`null`;if(up(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 jp(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=Ap(e),{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:E,patternProperties:D,additionalProperties:O,unevaluatedProperties:ee,minProperties:te,maxProperties:ne,propertyNames:re,dependentRequired:ie,dependentSchemas:ae,dependencies:oe,prefixItems:se,items:ce,additionalItems:le,unevaluatedItems:ue,contains:k,minContains:A,maxContains:de,minItems:fe,maxItems:j,uniqueItems:pe,minimum:me,maximum:he,exclusiveMinimum:ge,exclusiveMaximum:_e,multipleOf:ve,minLength:ye,maxLength:be,pattern:xe,__absolute_ref__:Se,__absolute_recursive_ref__:Ce}=t,M=[];if(p===!0&&r===null&&(r=t),f===`#`){let s=r===null?Op(c,Ce):r,l=`${a}/$recursiveRef`,u=Z(e,r===null?t:r,n,s,i,l,o);u.valid||M.push({instanceLocation:i,keyword:`$recursiveRef`,keywordLocation:l,error:`A subschema had errors.`},...u.errors)}if(d!==void 0){let t=Op(c,Se??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||M.push({instanceLocation:i,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),s===`4`||s===`6`||s===`7`)return{valid:M.length===0,errors:M}}let we=u===`number`&&fp(e,s===`4`);if(Array.isArray(m)?m.some(e=>e===u||e===`integer`&&we)||M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`}):m===`integer`?we||M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&M.push({instanceLocation:i,keyword:`type`,keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}),h!==void 0&&!gp(e,h)&&M.push({instanceLocation:i,keyword:`const`,keywordLocation:`${a}/const`,error:`Instance does not match ${pp(h)}.`}),g!==void 0&&!g.some(t=>gp(e,t))&&M.push({instanceLocation:i,keyword:`enum`,keywordLocation:`${a}/enum`,error:`Instance does not match any of ${pp(g)}.`}),v!==void 0){let t=`${a}/not`;Z(e,v,n,r,i,t).valid&&M.push({instanceLocation:i,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let N=[];if(y!==void 0){let t=`${a}/anyOf`,s=M.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);M.push(...l.errors),c||=l.valid,l.valid&&N.push(s)}c?M.length=s:M.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=M.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);M.push(...l.errors),c&&=l.valid,l.valid&&N.push(s)}c?M.length=s:M.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=M.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 M.push(...l.errors),l.valid&&N.push(c),l.valid}).length;c===1?M.length=s:M.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,...N),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||M.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||M.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||M.push({instanceLocation:i,keyword:`required`,keywordLocation:`${a}/required`,error:`Instance does not have required property "${e}".`});let s=Object.keys(t);if(te!==void 0&&s.length<te&&M.push({instanceLocation:i,keyword:`minProperties`,keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0&&s.length>ne&&M.push({instanceLocation:i,keyword:`maxProperties`,keywordLocation:`${a}/maxProperties`,error:`Instance has more than ${ne} properties.`}),re!==void 0){let e=`${a}/propertyNames`;for(let a in t){let t=`${i}/${Tp(a)}`,o=Z(a,re,n,r,t,e);o.valid||M.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||M.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}/${Tp(s)}`,o);t.valid||M.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||M.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}/${Tp(a)}`);t.valid||M.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}/${Tp(a)}`,d=Z(t[a],E[a],n,r,s,`${e}/${Tp(a)}`);if(d.valid)o[a]=c[a]=!0;else if(u=l,M.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=Yd(a),d=D[a];for(let f in t){if(!s.test(f))continue;let p=`${i}/${Tp(f)}`,m=Z(t[f],d,n,r,p,`${e}/${Tp(a)}`);m.valid?o[f]=c[f]=!0:(u=l,M.push({instanceLocation:i,keyword:`patternProperties`,keywordLocation:e,error:`Property "${f}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(!u&&O!==void 0){let e=`${a}/additionalProperties`;for(let a in t){if(c[a])continue;let s=`${i}/${Tp(a)}`,d=Z(t[a],O,n,r,s,e);d.valid?o[a]=!0:(u=l,M.push({instanceLocation:i,keyword:`additionalProperties`,keywordLocation:e,error:`Property "${a}" does not match additional properties schema.`},...d.errors))}}else if(!u&&ee!==void 0){let e=`${a}/unevaluatedProperties`;for(let a in t)if(!o[a]){let s=`${i}/${Tp(a)}`,c=Z(t[a],ee,n,r,s,e);c.valid?o[a]=!0:M.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;j!==void 0&&s>j&&M.push({instanceLocation:i,keyword:`maxItems`,keywordLocation:`${a}/maxItems`,error:`Array has too many items (${s} > ${j}).`}),fe!==void 0&&s<fe&&M.push({instanceLocation:i,keyword:`minItems`,keywordLocation:`${a}/minItems`,error:`Array has too few items (${s} < ${fe}).`});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,M.push({instanceLocation:i,keyword:`prefixItems`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}}if(ce!==void 0){let e=`${a}/items`;if(Array.isArray(ce)){let a=Math.min(ce.length,s);for(;c<a;c++){let a=Z(t[c],ce[c],n,r,`${i}/${c}`,`${e}/${c}`);if(o[c]=!0,!a.valid&&(u=l,M.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],ce,n,r,`${i}/${c}`,e);if(o[c]=!0,!a.valid&&(u=l,M.push({instanceLocation:i,keyword:`items`,keywordLocation:e,error:`Items did not match schema.`},...a.errors),u))break}if(!u&&le!==void 0){let e=`${a}/additionalItems`;for(;c<s;c++){let a=Z(t[c],le,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||(u=l,M.push({instanceLocation:i,keyword:`additionalItems`,keywordLocation:e,error:`Items did not match additional items schema.`},...a.errors))}}}if(k!==void 0){if(s===0&&A===void 0)M.push({instanceLocation:i,keyword:`contains`,keywordLocation:`${a}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(A!==void 0&&s<A)M.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array has less items (${s}) than minContains (${A}).`});else{let e=`${a}/contains`,c=M.length,l=0;for(let a=0;a<s;a++){let s=Z(t[a],k,n,r,`${i}/${a}`,e);s.valid?(o[a]=!0,l++):M.push(...s.errors)}l>=(A||0)&&(M.length=c),A===void 0&&de===void 0&&l===0?M.splice(c,0,{instanceLocation:i,keyword:`contains`,keywordLocation:e,error:`Array does not contain item matching schema.`}):A!==void 0&&l<A?M.push({instanceLocation:i,keyword:`minContains`,keywordLocation:`${a}/minContains`,error:`Array must contain at least ${A} items matching schema. Only ${l} items were found.`}):de!==void 0&&l>de&&M.push({instanceLocation:i,keyword:`maxContains`,keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${de} items matching schema. ${l} items were found.`})}}if(!u&&ue!==void 0){let e=`${a}/unevaluatedItems`;for(;c<s;c++){if(o[c])continue;let a=Z(t[c],ue,n,r,`${i}/${c}`,e);o[c]=!0,a.valid||M.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(gp(t[e],t[n])){M.push({instanceLocation:i,keyword:`uniqueItems`,keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${e} and ${n}.`});break outer}}}else if(u===`number`){let t=dp(e);s===`4`?(me!==void 0&&(ge===!0&&t<=me||t<me)&&M.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${ge?`or equal to `:``}${me}.`}),he!==void 0&&(_e===!0&&t>=he||t>he)&&M.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${_e?`or equal to `:``}${he}.`})):(me!==void 0&&t<me&&M.push({instanceLocation:i,keyword:`minimum`,keywordLocation:`${a}/minimum`,error:`${t} is less than ${me}.`}),he!==void 0&&t>he&&M.push({instanceLocation:i,keyword:`maximum`,keywordLocation:`${a}/maximum`,error:`${t} is greater than ${he}.`}),ge!==void 0&&t<=ge&&M.push({instanceLocation:i,keyword:`exclusiveMinimum`,keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than or equal to ${ge}.`}),_e!==void 0&&t>=_e&&M.push({instanceLocation:i,keyword:`exclusiveMaximum`,keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${_e}.`})),ve!==void 0&&!_p(e,ve)&&M.push({instanceLocation:i,keyword:`multipleOf`,keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ve}.`})}else if(u===`string`){let t=e,n=ye===void 0&&be===void 0?0:kp(t);ye!==void 0&&n<ye&&M.push({instanceLocation:i,keyword:`minLength`,keywordLocation:`${a}/minLength`,error:`String is too short (${n} < ${ye}).`}),be!==void 0&&n>be&&M.push({instanceLocation:i,keyword:`maxLength`,keywordLocation:`${a}/maxLength`,error:`String is too long (${n} > ${be}).`}),xe!==void 0&&!Yd(xe).test(t)&&M.push({instanceLocation:i,keyword:`pattern`,keywordLocation:`${a}/pattern`,error:`String does not match pattern.`});let r=T===void 0?void 0:rp[T];r&&!r(t)&&M.push({instanceLocation:i,keyword:`format`,keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:M.length===0,errors:M}}var Mp={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`}}}]},Np={"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`},Pp=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(`.`)),Fp={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`]},Ip={...Fp,single:[...Fp.single,`contains`,`propertyNames`],plain:[...Fp.plain.filter(e=>e!==`id`),`$id`,`const`]},Lp={...Ip,single:[...Ip.single,`if`,`then`,`else`]},Rp={single:[...Lp.single,`unevaluatedItems`,`unevaluatedProperties`],array:Lp.array,map:[...Lp.map,`$defs`,`dependentSchemas`],plain:[...Lp.plain.filter(e=>e!==`format`),`$anchor`,`$recursiveAnchor`,`$recursiveRef`,`dependentRequired`,`maxContains`,`minContains`]},zp={4:Fp,6:Ip,7:Lp,"2019-09":Rp,"2020-12":{single:Rp.single.filter(e=>e!==`additionalItems`),array:[`allOf`,`anyOf`,`oneOf`,`prefixItems`],map:Rp.map,plain:Rp.plain.filter(e=>e!==`$recursiveAnchor`&&e!==`$recursiveRef`)}},Bp={4:[],6:[`contentMediaType`],7:[`contentMediaType`],"2019-09":[],"2020-12":[`$dynamicAnchor`,`$dynamicRef`]},Vp=[`date`,`date-time`,`email`,`hostname`,`idn-email`,`ipv4`,`ipv6`,`regex`,`time`,`uri`],Hp=[...Vp,`json-pointer`,`uri-reference`,`uri-template`],Up={4:Vp,6:Hp,7:[...Hp,`idn-hostname`,`iri`,`iri-reference`,`relative-json-pointer`]},Wp=[`idn-email`,`idn-hostname`,`iri`,`iri-reference`],Gp={base64:Kp(`A-Za-z0-9+/`),base64url:Kp(`A-Za-z0-9\\-_`),base32:qp(`A-Z2-7`,`AEIMQUY4`,`AQ`,`ACEGIKMOQSUWY246`,`AIQY`),base32hex:qp(`0-9A-V`,`048CGKOS`,`0G`,`02468ACEGIKMOQSU`,`08GO`),base16:`^(?:[0-9A-Fa-f]{2})*$`};function Kp(e){let t=`[${e}]`;return`^(?:${t}{4})*(?:${t}[AQgw]==|${t}{2}[AEIMQUYcgkosw048]=)?$`}function qp(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 Jp=class extends Error{};function Yp(e){if(!P(e))return`2020-12`;let t=e.$schema;if(typeof t!=`string`)return`2020-12`;let n=Np[t.replace(/#+$/,``).replace(/^https?:\/\//,``)];if(!n)throw new Jp(`unknown JSON Schema dialect "${t}"`);return n}function Xp(e,t,n=[]){if(typeof e==`boolean`)return e;if(!P(e))return{};let r=zp[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(Bp[t].includes(s)&&!n.includes(s))throw new Jp(`the \`${s}\` keyword is not supported by the browser runtime yet`);if(!(Pp.has(s)&&(!i.has(s)||a&&s!==`$ref`))){if(s===`pattern`&&typeof c==`string`&&Qp(c),s===`patternProperties`&&P(c))for(let e of Object.keys(c))Qp(e);if(s===`format`&&typeof c==`string`){if(!Up[t]?.includes(c))continue;if(Wp.includes(c))throw new Jp(`the "${c}" format is not supported by the browser runtime yet`)}r.array.includes(s)&&Array.isArray(c)?o.push([s,c.map(e=>Xp(e,t,n))]):r.single.includes(s)?o.push([s,Xp(c,t,n)]):r.map.includes(s)&&P(c)?o.push([s,Zp(c,t,n)]):o.push([s,c])}}let s=e.contentEncoding;if(!a&&(t===`6`||t===`7`)&&typeof s==`string`){let e=Gp[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 Zp(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Array.isArray(r)?r:Xp(r,t,n)]))}function Qp(e){try{Yd(e)}catch(t){throw t instanceof jd?new Jp(`"${e}" is not a valid regular expression: ${t.message}`):t instanceof Md?new Jp(`the regular expression "${e}" is not supported by the browser runtime yet: ${t.message}`):t}}function $p(e){for(let t of e.references)if(Op(e.lookup,t)===void 0)throw new Jp(`unresolvable reference "${decodeURI(t.replace(/^json-schema:\/\/\//,``))}"`)}function em(e){if(Array.isArray(e))return e.map(em);if(!P(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,em(r)]);return Object.fromEntries(t)}var tm={4:Mp.draft4,6:Mp.draft6,7:Mp.draft7,"2019-09":Mp.draft201909,"2020-12":Mp.draft202012};function nm(e){return tm[e].map(t=>e===`2020-12`?em(Xp(t,e,[`$dynamicAnchor`,`$dynamicRef`])):Xp(t,e))}var rm=class{schema;dialect;shortCircuit;lookup;references=[];constructor(e,t,n,r){this.schema=e,this.dialect=t,this.shortCircuit=n,this.lookup=Dp(e,void 0,this.references);for(let e of r)Dp(e,this.lookup)}validate(e){return jp(e,this.schema,this.dialect,this.lookup,this.shortCircuit)}},im=new Map;function am(e){let t=im.get(e);if(!t){let[n,...r]=nm(e);t=new rm(n,e,!1,r),im.set(e,t)}return t}function om(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 sm(e){let t=Yp(e);if(typeof e==`boolean`){if(t===`4`)throw new Jp(`boolean schemas need draft 6 or later`)}else{let n=am(t).validate(e);if(!n.valid)throw new Jp(om(n.errors))}let n=new rm(Xp(hp(e),t),t,!0,nm(t));return $p(n),e=>{let t=n.validate(lp(e));return t.valid?void 0:om(t.errors)}}function cm(e){return sm(lp(e))}function lm(e){e.setJsonSchemaValidator(cm)}async function um(){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 dm=Promise.resolve(),fm;function pm(e){let t=dm.then(()=>mm(e));return dm=t.then(()=>void 0,()=>void 0),t}async function mm(e){let t=await ii(()=>import(`./jazz_wasm-BOvbCHn3.js`),[],import.meta.url),n=Jr(e);if(n)return t.initSync(n),hm(t);let r=!1;if(typeof process<`u`&&process.versions?.node)try{let e=await um();e&&(t.initSync({module:e}),r=!0)}catch{}if(!r&&typeof t.default==`function`){let n=typeof location<`u`?Yr(Lr,location.href,e)??zr():null;if(n)await gm(t,n);else if(typeof location<`u`&&Ji())throw Error(Ki);else await t.default()}return hm(t)}function hm(e){return Ad(e,`WASM`,[`initSync`,`WasmDb`,`setJsonSchemaValidator`]),lm(e),e}async function gm(e,t){if(fm===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(_m(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}),fm=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}),fm=t}function _m(e){return typeof WebAssembly.compileStreaming==`function`&&e?.trim()===`application/wasm`}function vm(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 ym(e,t,n,r){return jr(`${Gt}${e}`,{audience:t,ttlSeconds:n,now:r})}var bm=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 ym(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*xm(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 Sm=`authority_changed`,Cm=class extends Error{name=`AuthorityChangedError`;code=Sm;constructor(e,t){super(e,t)}};function wm(e){return!e||typeof e!=`object`?!1:e.code===Sm}function Tm(e){if(e==null)return null;let t=typeof e==`object`&&typeof e.message==`string`?e.message:String(e);if(wm(e))return new Cm(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 Em=`core_tick_failed`,Dm=class extends Error{name=`CoreTickFailedError`;code=Em;constructor(e){super(`core tick failed: ${km(e)}`,{cause:e})}};function Om(e){return!e||typeof e!=`object`?!1:e.code===Em}function km(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 Am=class extends vs{},jm=class{text;constructor(e){this.text=e}};function Mm(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 Nm(e){let t=JSON.parse(e),n=(e,t)=>typeof e==`string`?(Mm(e),e.includes(t)):Array.isArray(e)?e.some(e=>n(e,t)):e&&typeof e==`object`?Object.entries(e).some(([e,r])=>(Mm(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);else if(n===`"`)o=!0,a+=n;else{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 jm(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 Pm(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`),Mm(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 jm&&(/^(?: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 jm){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);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);else if(e===`False`)d(10);else 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)}Me({issuer:et,user_id:`system`,claims:{},authMode:`external`});var Fm=-(1n<<63n),Im=(1n<<63n)-1n;function Lm(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<Fm||n>Im)throw Error(`${t} must be a signed 64-bit integer`);return n}var Rm=new T({fatal:!0});function zm(e){if(e.kind!==`hidden-metadata`)return e.kind===`stored-column`?e.outputName:e.name}function Bm(e){return{table:e.string(),descriptor:Hm(e),rows:e.readVec(e=>({rowId:e.bytes(),deleted:e.bool(),raw:e.bytes()}))}}function Vm(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),Qm(e,r.valueType)},t.length)}function Hm(e){return e.readVec(e=>{let t=e.u64();return t===0?{kind:`stored-column`,id:e.u64(),outputName:e.string(),valueType:$m(e)}:t===1?{kind:`result-field`,name:e.string(),valueType:$m(e)}:t===2?{kind:`hidden-metadata`,name:e.string(),valueType:$m(e)}:Um(t)})}function Um(e){throw Error(`unknown native row descriptor field kind ${e}`)}function Wm(e){let t={added:e.readVec(Bm),updated:e.readVec(Bm),removed:e.readVec(Ym),addedOccurrenceKeys:e.readVec(e=>Gm(e)),updatedOccurrenceKeys:e.readVec(e=>Gm(e)),removedOccurrenceKeys:e.readVec(e=>Gm(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 Jm(e,`subscription delta`),t}function Gm(e){let t=e.bytes();if(t[0]!==2||!Km(t.subarray(1)))throw Error(`malformed ResultKey`);return t}function Km(e){let t=t=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;if(e.length<25)return!1;let n=16,r=t(n);if(n+=4,r>256||n+r*16+4>e.length)return!1;n+=r*16;let i=t(n);if(n+=4,i>r+1)return!1;let a=-1;for(let o=0;o<i;o++){if(n+8>e.length)return!1;let i=t(n),o=t(n+4);if(n+=8,i>r||i<=a||o===0||o>4096||n+o>e.length||!le(e.subarray(n,n+o)))return!1;a=i,n+=o}for(let t=0;t<=r;t++){let t=e[n++];if(t===1)n+=24;else if(t!==0)return!1}return n===e.length}function qm(e){let t=e.u64(),n=e.readVec(Bm);return Jm(e,`relation snapshot`),{rootCount:t,rows:n}}function Jm(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function Ym(e){return{table:e.string(),rowId:e.bytes()}}function Xm(e,t){e.vec((e,n)=>{e.some(e=>e.string(t[n].name??``)),Qm(e,t[n].valueType)},t.length)}function Zm(e){return e.readVec(e=>({name:e.option(e=>e.string()),valueType:$m(e)}))}function Qm(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)}}else 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)}else if(t.tag===13){let n=t.members??(t.inner?[t.inner]:[]);e.vec((e,t)=>Qm(e,n[t]),n.length)}else if(t.tag===14||t.tag===15){if(!t.inner)throw Error(`missing inner value type for tag ${t.tag}`);Qm(e,t.inner)}else if(t.tag===16){if(!t.record)throw Error(`missing inline record descriptor for tag 16`);Xm(e,t.record)}else 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),Xm(e,n.payload)},r.length)}}function $m(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:$m(e)};if(t===13){let n=e.readVec($m);return{tag:t,members:n,inner:n[0]}}return t===16?{tag:t,record:Zm(e)}:t===17?{tag:t,enumSchema:{registryId:e.u64(),name:e.string(),cases:e.readVec(e=>({name:e.string(),payload:Zm(e)}))}}:{tag:t}}function eh(e,t){let n=Ih(e),r=n.fixed.map(e=>t[e.logicalIndex]),i=n.variable.map(e=>t[e.logicalIndex]),a=N(r),o=new Bh,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 N([a,o.finish(),...i])}function th(e,t){let n=uh(gh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:Oh(e.column_type,i)})}function nh(e,t){return Object.defineProperty(e,"valuesByColumn",{value:t,enumerable:!1,configurable:!0}),e}function rh(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 ih={name:`__jazz_terminal_row_key`,column_type:{type:`Uuid`},nullable:!1};function ah(e,t,n){let r=oh([ih,...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 nh({id:e,values:a},rh(t,a))}function oh(e,t){let n=uh(gh(e));return e.map((e,r)=>{let i=n(t,r);return i==null?{type:`Null`}:sh(e.column_type,i,e.name)})}function sh(e,t,n){switch(e.type){case`Timestamp`:return{type:`Timestamp`,value:Nh(t,n)};case`Array`:return{type:`Array`,value:ch(e.element,t)};case`Row`:if(t.byteLength<16)throw Error(`terminal nested row is missing its physical key`);return{type:`Row`,value:ah(Ph(t.subarray(0,16)),e.columns,t)};default:return Oh(e,t)}}function ch(e,t){return Mh(e,t,t=>sh(e,t))}function lh(e,t){return eh(gh(e),e.map((e,n)=>_h(e,t[n])))}function uh(e){let t=Ih(e);return(n,r)=>dh(e,t,n,r)}function dh(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 fh(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:Lh(n,o+(i.variableIndex-1)*4),l=i.variableIndex===t.variable.length-1?n.length:Lh(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 ${ph(a)}, tag ${a.tag}, claimed width ${i}, remaining buffer ${o}, current offset ${c}, end offset ${l}, record length ${n.length}`)}return fh(n.subarray(c,l),a)}function fh(e,t){if(t.tag!==15)return e;let n=hh(e);return n==null?null:t.inner?fh(n,t.inner):n}function ph(e){return e.tag===14||e.tag===15?`${e.tag===14?`Array`:`Nullable`}<${e.inner?ph(e.inner):`?`}>`:mh(e.tag)}function mh(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 hh(e){return e[0]===0?null:e[0]===1?e.subarray(1):e}function gh(e){return e.map(e=>({name:e.name,valueType:Th(e)}))}function _h(e,t){let n=Dh(e.column_type),r=e.nullable?{tag:15,inner:n}:n;if(!t){if(e.sparse)return yh({tag:15,inner:r});if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);return yh(r)}if(t.type===`Null`){if(!e.nullable)throw Error(`missing non-nullable value for ${e.name}`);let t=yh(r);return e.sparse?vh(t,r):t}let i=bh(e.column_type,t);return e.nullable&&(i=vh(i,n)),e.sparse?vh(i,r):i}function vh(e,t){if(Fh(t)==null)return N([Uint8Array.of(1),e]);let n=new Uint8Array(1+e.length);return n[0]=1,n.set(e,1),n}function yh(e){let t=Fh(e);return t==null?Uint8Array.of(0):new Uint8Array(t)}function bh(e,t){switch(e.type){case`Boolean`:if(t.type!==`Boolean`)throw Error(`expected Boolean value`);return Uint8Array.of(+!!t.value);case`Integer`:{let e=Rh(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=zh(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 N([Uint8Array.of(0),new TextEncoder().encode(t.value)]);case`Uuid`:if(t.type!==`Uuid`)throw Error(`expected Uuid value`);return wh(t.value);case`Bytea`:if(t.type!==`Bytea`)throw Error(`expected Bytea value`);return N([Uint8Array.of(0),t.value]);case`Array`:if(t.type!==`Array`)throw Error(`expected Array value`);return Sh(e.element,t.value);case`Row`:if(t.type!==`Row`)throw Error(`expected Row value`);return xh(e.columns,t.value)}}function xh(e,t){let n=lh(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?wh(t.id):new Uint8Array;return N([Uint8Array.of(+!!t.id),r,Ch(n.byteLength),n])}function Sh(e,t){let n=t.map(t=>bh(e,t));if(Fh(Dh(e))!=null)return N(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)}),N([Ch(t.length),r,...n])}function Ch(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t}function wh(e){let t=Xe(e);if(!t)throw Error(`invalid UUID value ${e}`);return t}function Th(e){let t=Dh(e.column_type);return e.nullable&&(t={tag:15,inner:t}),e.sparse?{tag:15,inner:t}:t}function Eh(e){return e.map(e=>({...e,sparse:void 0,column_type:e.column_type.type===`Row`?{...e.column_type,columns:[...Eh(e.column_type.columns)]}:e.column_type.type===`Array`&&e.column_type.element.type===`Row`?{...e.column_type,element:{...e.column_type.element,columns:[...Eh(e.column_type.element.columns)]}}:e.column_type}))}function Dh(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:Dh(e.element)};case`Row`:return{tag:9}}}function Oh(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:Rm.decode(kh(t))};case`Uuid`:return{type:`Uuid`,value:Ph(t)};case`Bytea`:return{type:`Bytea`,value:kh(t).slice()};case`Array`:return{type:`Array`,value:jh(e.element,t)};case`Row`:return{type:`Row`,value:Ah(e.columns,t)}}}function kh(e){if(e[0]!==0)throw Error(`indirect scalar crossed a logical binding boundary`);return e.subarray(1)}function Ah(e,t){if(t.byteLength<5)throw Error(`invalid nested row value`);let n=t[0]===1,r=1,i;n&&(i=Ph(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=th(e,o);return nh({id:i,values:s},rh(e,s))}function jh(e,t){return Mh(e,t,t=>Oh(e,t))}function Mh(e,t,n){let r=Fh(Dh(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=Lh(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:Lh(t,4+(e-1)*4),s=e===i-1?t.length:Lh(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 Nh(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0,!0);return Number(n)}function Ph(e){if(e.length>=16)return We(e,0);let t=Pe(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Fh(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=Fh(t);return n==null?void 0:e+n},0);case 10:case 14:return;case 15:{let t=e.inner?Fh(e.inner):void 0;return t==null?void 0:t+1}default:return}}function Ih(e){let t=[];t.length=e.length;let n=[],r=[],i=0;for(let r=0;r<e.length;r+=1){let a=Fh(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(Fh(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 Lh(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Rh(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 zh(e){if(e.type!==`BigInt`)throw Error(`expected BigInt value`);return Lm(e.value,`BigInt value`)}var Bh=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)}},Vh=new T({fatal:!0}),Hh=new TextEncoder().encode(`["https://jazz.invalid","self-signed-open"]`);function Uh(e,t){return t?Hh:e}function Wh(e,t,n,r=!1,i,a,o,s){let c=new ag;return c.bytes(e),c.string(Gh(Uh(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(sg(o))),s==null?c.none():c.some(e=>e.bytes(s)),c.finish()}function Gh(e){try{let t=Vh.decode(e);if(D(t))return t}catch{}throw Error(`native open config author must be a canonical UTF-8 author identity`)}function Kh(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&&Yh(`query limit`,r),Yh(`query offset`,i);let u=new ag;return u.string(e),u.vec((e,n)=>{let r=t[n];Zh(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)=>{Jh(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(Pm(c),!1)),qh(u,l),u.finish()}function qh(e,t){e.vec((e,n)=>{let r=t[n];e.string(r.column),r.kind===`json_pointer`?(e.u64(3),e.string(r.at)):(Yh(`partial selection ${r.column} start`,r.from),Yh(`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 Jh(e,t){let{filters:n=[],select:r,orderBy:i=[],limit:a=null,offset:o=0,requirement:s=`Optional`,nestedArrays:c=[]}=t;a!=null&&Yh(`array subquery ${t.columnName} limit`,a),Yh(`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)=>{Zh(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(Xh(s)),e.vec((e,t)=>{Jh(e,c[t])},c.length),qh(e,[])}function Yh(e,t){if(!Number.isSafeInteger(t)||t<0)throw Error(`${e} must be a non-negative safe integer`)}function Xh(e){switch(e){case`Optional`:return 0;case`AtLeastOne`:return 1;case`MatchCorrelationCardinality`:return 2}}function Zh(e,t){if(t.op===`All`||t.op===`Any`)e.u64(t.op===`All`?0:1),e.vec((e,n)=>Zh(e,t.predicates[n]),t.predicates.length);else if(t.op===`Not`)e.u64(2),Zh(e,t.predicate);else if(t.op===`In`)e.u64(5),eg(e,t.column),e.vec((e,n)=>{e.u64(3),rg(e,t.values[n])},t.values.length);else if(t.op===`Contains`)e.u64(10),eg(e,t.column),tg(e,t.value);else if(t.op===`StartsWith`||t.op===`EndsWith`)e.u64(t.op===`StartsWith`?13:14),eg(e,t.column),tg(e,t.value);else if(t.op===`IsNull`||t.op===`IsNotNull`)t.op===`IsNotNull`&&e.u64(2),e.u64(12),eg(e,t.column);else if(Qh(t))$h(e,t.column,t.op,t.value);else throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Qh(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function $h(e,t,n,r){e.u64(ng(n)),eg(e,t),tg(e,r)}function eg(e,t){e.u64(0),e.string(t)}function tg(e,t){e.u64(3),rg(e,t)}function ng(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 rg(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)}else if(t.type===`Nullable`)e.u64(13),t.value==null?e.none():e.some(e=>rg(e,t.value));else if(t.type===`Boolean`)e.u64(5),e.bool(t.value);else 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)}else 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)}else 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)}else if(t.type===`Double`){if(!Number.isFinite(t.value))throw Error(`Double value must be finite`);e.u64(4),e.f64Le(t.value)}else if(t.type===`Uuid`){e.u64(9);let n=Xe(t.value);if(!n)throw Error(`invalid uuid ${t.value}`);e.bytes(n)}else t.type===`Bytea`?(e.u64(7),e.bytes(t.value)):t.type===`Array`?(e.u64(12),e.vec((e,n)=>rg(e,t.value[n]),t.value.length)):(e.u64(6),e.string(t.value))}var ig=64,ag=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=Lm(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)}string(e){this.bytes(cg(e))}bytes(e,t=!0){if(t&&this.u64(e.length),e.length<ig)for(let t of e)this.chunks.push(t);else 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)}},og=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 Vh.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 sg(e){return cg(JSON.stringify(e,b))}function cg(e){return new TextEncoder().encode(e)}var lg=new TextEncoder;function ug(e){return lg.encode(he(e))}function dg(e){let t=new ag;return t.string(e.table),Vm(t,[...e.descriptor]),Pe(t.finish())}var fg=36e5,pg=500,mg=`jazz-http-stream-endpoints`,hg=`endpoints`;function gg(){return globalThis.indexedDB!==void 0}function _g(){let e=globalThis.indexedDB;if(e)return new Promise((t,n)=>{let r=e.open(mg,1);r.onupgradeneeded=()=>r.result.createObjectStore(hg),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`blocked`))})}async function vg(e,t){let n=_g();if(!n)return;let r=await n;try{return await new Promise((n,i)=>{let a=t(r.transaction(hg,e).objectStore(hg));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error)})}finally{r.close()}}var yg=`jazz-stream-endpoint:`,bg=6e5;function xg(){if(typeof document<`u`)try{return globalThis.localStorage??void 0}catch{return}}function Sg(e,t=Date.now()){let n=xg();if(n)try{let r=n.getItem(yg+e);if(r===null)return;let[i,a]=r.split(`:`);if(i!==`stream`&&i!==`none`||!(Number(a)>t)){n.removeItem(yg+e);return}return i===`stream`}catch{return}}function Cg(e,t,n){let r=xg();if(r)try{r.setItem(yg+e,`${t}:${n}`)}catch{try{r.removeItem(yg+e)}catch{}}}async function wg(e,t=Date.now()){let n,r=await Promise.race([vg(`readonly`,t=>t.get(e)).then(e=>({until:e}),()=>void 0),new Promise(e=>{n=setTimeout(()=>e(void 0),pg)})]).finally(()=>clearTimeout(n));if(!r)return!1;let i=typeof r.until==`number`&&r.until>t;return i?Cg(e,`stream`,r.until):Cg(e,`none`,t+bg),i}function Tg(e,t=Date.now()){return Cg(e,`stream`,t+fg),vg(`readwrite`,n=>n.put(t+fg,e)).then(()=>void 0,()=>void 0)}function Eg(e){return Cg(e,`none`,Date.now()+bg),vg(`readwrite`,t=>t.delete(e)).then(()=>void 0,()=>void 0)}var Dg=`x-jazz-stream-key`;function Og(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 kg(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 Ag=class{buffered=new Uint8Array;push(e){this.buffered=this.buffered.byteLength?kg([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}},jg=new TextEncoder,Mg=new TextDecoder;function Ng(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 Pg=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)}},Fg=4194304,Ig=(e,t)=>fetch(e,t),Lg=class extends Pg{request;binaryType=`arraybuffer`;readyState=0;streamUrl;abort=new AbortController;session;queued=[];sending=!1;constructor(e,t=Ig){super(),this.request=t,this.streamUrl=Ng(e),this.run()}send(e){if(this.readyState!==1)throw Error(`HTTP stream session is not open`);let t=typeof e==`string`?jg.encode(e):e;this.queued.push(Og(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:{[Dg]:e.key},signal:AbortSignal.timeout?.(Bg)}).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 Ag;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(Mg.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(Mg.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<=Fg);)t+=this.queued[e].byteLength,e+=1;let n=kg(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`,[Dg]: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}))}},Rg=new Set,zg=new Map,Bg=1e4,Vg=new Map,Hg=`x-jazz-stream`,Ug=new Set,Wg=`x-jazz-store-error`,Gg=new Set;async function Kg(e,t){try{let n=await t(e.replace(/^ws/,`http`),{method:`POST`,credentials:`same-origin`,signal:AbortSignal.timeout?.(Bg)});if(n.status===503&&n.headers.get(Wg)===`1`){let t=await n.text().catch(()=>``);return t&&!Gg.has(`${e}\n${t}`)&&(Gg.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(Hg)===`1`?`stream`:`upgrades`:`other`}catch{return`silent`}}async function qg(e,t,n){let r=await Kg(e,n);if(r===`stream`)return r;if(r!==`upgrades`)return zg.delete(e),Vg.delete(e),r===`refused`&&!Ug.has(e)&&(Ug.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=(zg.get(e)??0)+1;zg.set(e,i);let a=t?(Vg.get(e)??0)+1:0;t?Vg.set(e,a):Vg.delete(e);let o=a>=2;return i<3&&!o?r:(zg.delete(e),Vg.delete(e),o?(console.warn(`jazz: ${a} WebSockets in a row to ${e} got no answer in ${Bg/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 Jg(e,t={}){let n=t.fetch??Ig,r=t.describeFailedUpgrade;return class extends Pg{url;binaryType=`arraybuffer`;inner;closedEarly=!1;closedByClient=!1;settled=!1;probing=!1;openDeadline;abort=new AbortController;constructor(e){if(super(),this.url=e,Rg.has(e)){this.openStream();return}if(!gg()){this.inner=this.openNative();return}let t=Sg(e);t===!0?(Rg.add(e),this.openStream()):t===!1?this.inner=this.openNative():wg(e).then(t=>{this.closedEarly||(t?(Rg.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 Lg(this.url,n),t=!1;e.addEventListener(`open`,()=>{t=!0}),e.addEventListener(`close`,()=>{!t&&!this.closedByClient&&(Rg.delete(this.url),Eg(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)=>{clearTimeout(this.openDeadline),this.settled||(a?a[e]??=t:(a={[e]:t},this.probing=!0,qg(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);this.probing=!1,this.settled||(this.settled=!0,t?(Rg.add(this.url),e===`stream`&&Tg(this.url),this.openStream()):n?(this.emit(`error`,Error(n)),this.emit(`close`,{code:1006,reason:n})):(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()},Bg),t.addEventListener(`open`,()=>{a||(clearTimeout(this.openDeadline),i=!0,zg.delete(this.url),Vg.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 Yg=`jazz_renewal`,Xg=`X-Jazz-Renew`,Zg=2048;function Qg(e){let t=new og(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>Zg)throw Error(`malformed renew-soon frame`);return{session:n,renewInMs:r}}function $g(e){let t=new ag;return t.u64(65),t.string(e),t.finish()}function e_(e){return e[0]===64}function t_(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 n_(e){try{return`jazz-session-refresh:${new URL(e.replace(/^ws/,`http`)).origin}`}catch{return`jazz-session-refresh:${e}`}}var r_=class extends Error{wireError;constructor(e){super(`websocket ${e.code} before server hello: ${e.message}`),this.name=`PreHelloWireError`,this.wireError=e}};function i_(e){return e.retry===`later`&&(e.code===`not_ready`||e.code===`backpressure`)}function a_(e){return e.retry===`later`&&(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)}function o_(e){return e.code===`protocol_error`||(e.code===`websocket_closed`||e.code===`websocket_error`||e.code===`websocket_silent`)&&!a_(e)}var s_=12e4,c_=1e3,l_=7,u_=12688,d_=1<<20,f_=5,p_=5,m_=2097152,h_=4096;function g_(e){v_(e);let t=new ag;t.vec((t,n)=>t.bytes(e[n]),e.length);let n=t.finish();if(n.byteLength>m_)throw Error(`websocket frame batch exceeds maximum length of ${m_} bytes`);return n}function __(e){if(e.byteLength>m_)throw Error(`websocket frame batch exceeds maximum length of ${m_} bytes`);let t=new og(e),n=t.u64();if(n===0||n>h_)throw Error(`websocket frame batch exceeds frame-count limit of ${h_}`);let r=[];for(let e=0;e<n;e+=1)r.push(t.bytesAtMost(m_,`websocket frame`));return j_(t,`websocket frame batch`),r}function v_(e){if(e.length===0||e.length>h_)throw Error(`websocket frame batch exceeds frame-count limit of ${h_}`);for(let t of e)if(t.byteLength>m_)throw Error(`websocket frame exceeds maximum length of ${m_} bytes`)}function y_(e=u_){O_(e,`client wire features`);let t=new ag;return t.u64(0),t.u64(6),t.u64(6),t.u64(e),t.u64(0),t.none(),t.finish()}var b_=0,x_=1;function S_(e){if(e[0]!==b_)return!1;let t=new og(e);t.u64();let{min:n,max:r}=k_(t);return n===6&&r===6&&A_(t),!0}function C_(e){return e[0]===x_&&(w_(e),!0)}function w_(e){let t=new og(e),n=t.u64();if(n!==x_)throw Error(`expected WireFrame::Error, got tag ${n}`);let r={code:X_(t.u64()),retry:Q_(t.u64()),message:t.string()};return t.done()||(r.reason=Z_(t.u64())),j_(t,`WireFrame::Error`),r}function T_(e){if(e.code!==`auth_failed`)return null;if(e.reason===`reauthenticate`)return`invalid`;let t=e.reason!==void 0&&!e.reason.startsWith(`unknown:`);return S(t?e.reason:e.message)}var E_=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??He(this.url)??q_(this.url);this.onFrame=e.onFrame,this.onError=e.onError,this.onTerminal=e.onTerminal,this.localFeatures=(e.features??12688)|18432,this.renewalUrl=P_(e.authJson)?t_(this.url):null,O_(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}),$_(this.socket).then(()=>{if(!this.closing){this.socket.send(N_(e.authJson??`{}`,e.peerIdentity,e.requestedLink,this.renewalUrl!==null)),this.socket.send(g_([y_(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=M_(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=p_;for(let r of e){let e=r.byteLength+f_;t.length>0&&(t.length>=h_||n+e>d_)&&(this.socket.send(g_(t)),t=[],n=p_),t.push(r),n+=e}t.length>0&&this.socket.send(g_(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())},c_)},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||I_(n,e).then(e=>{if(!(!e||this.closing||this.terminated))return this.send($g(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;t>=12e4&&!e?this.silenceTimer=setTimeout(()=>this.watchSilence(!0),c_):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()):this.silenceTimer=setTimeout(()=>this.watchSilence(),s_-t)}async handleMessage(e){for(let t of __(await K_(e))){if(this.closing)return;if(S_(t)){if(this.negotiated)continue;this.negotiated=!0,clearTimeout(this.handshakeTimer);let e=D_(t,this.localFeatures);e.features&2048&&this.watchSilence(),this.resolveNegotiation({...e,features:e.features&-18433})}else if(!(this.negotiated&&t.byteLength===1&&t[0]===l_)){if(this.negotiated&&this.renewalUrl&&e_(t))this.scheduleRenewal(Qg(t));else{if(!this.negotiated){if(C_(t)){let e=w_(t);if(T_(e)){this.reportTerminal(e,Error(`websocket authentication failed before server hello: ${e.message}`)),this.close();return}this.reportTerminal(e,new r_(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(C_(t)){let e=w_(t);if(i_(e)){this.reportTerminal(e),this.close();return}this.onError?.(e)}else this.onFrame(t)}}}}};function D_(e,t=u_){let n=new og(e);if(n.u64()!==0)throw Error(`expected WireFrame::Hello`);let{min:r,max:i}=k_(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}=A_(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 O_(e,t){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`${t} must be an unsigned 32-bit integer, got ${e}`)}function k_(e){return{min:e.u64(),max:e.u64()}}function A_(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 j_(e,`WireFrame::Hello`),{features:t,role:n,authority:r}}function j_(e,t){if(!e.done())throw Error(`${t} has trailing postcard bytes`)}function M_(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 N_(e,t,n,r=!1){let i=JSON.parse(e),a=new T().decode(t),o=ev(i)??G_(a)??a;return JSON.stringify({peer_identity:a,...i,auth:{...i,sub:o},sub:o,...n?{requested_link:n}:{},...r?{[Yg]:1}:{}})}function P_(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 F_=3e4;async function I_(e,t){return L_(n_(e),()=>R_(e,t))}async function L_(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,F_)})]).finally(()=>clearTimeout(e))})}catch{}return i()}async function R_(e,t){try{let n=await $e(e)(e,{method:`POST`,credentials:`same-origin`,redirect:`error`,headers:{[Xg]:t}});if(!n.ok)return null;let r=await n.json();return typeof r.renewal==`string`?r.renewal:null}catch{return null}}function z_(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=Ae(t.jwt_token);if(!n)return{};if(n.iss===`urn:jazz:local-first`||n.iss===`urn:jazz:anonymous`){let{jazz_pub_key:e,...t}=n;return Se(t)}return Se(n)}function B_(e,t){let n=JSON.parse(e);if(typeof n.admin_secret==`string`||typeof n.backend_secret==`string`&&!H_(n))return new TextEncoder().encode(Re(`urn:jazz:system`,`system`));let r=W_(n),i=null;try{i=D(new T({fatal:!0}).decode(t))}catch{}if(i?.account_id&&r){let e=D(r);if(e.issuer!==i.issuer||e.user_id!==i.user_id||e.account_id!==void 0&&e.account_id!==i.account_id)throw Error(`WebSocket credential must match the context account identity`);return t}return r?new TextEncoder().encode(r):t}function V_(e){let t=JSON.parse(e);return typeof t.backend_secret==`string`&&!t.admin_secret&&!H_(t)&&delete t.jwt_token,JSON.stringify(t)}function H_(e){let t=e.backend_session;return typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.issuer==`string`&&typeof t.user_id==`string`&&Ie(t.issuer)&&Ie(t.user_id)}function U_(e){let t=JSON.parse(e);return typeof t.admin_secret==`string`||typeof t.backend_secret==`string`||W_(t)!==null}function W_(e){if(typeof e.admin_secret==`string`)return null;if(typeof e.backend_secret==`string`&&H_(e)){let t=e.backend_session;return Re(t.issuer,t.user_id,t.account_id)}if(typeof e.jwt_token==`string`){let t=Ae(e.jwt_token),n=typeof t?.iss==`string`?t.iss:void 0,r=t?.sub;if(typeof n==`string`&&typeof r==`string`&&Ie(n)&&Ie(r))return Re(n,r)}return null}function G_(e){return D(e)?.user_id??null}async function K_(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 q_(e){let t=Y_();return J_(e)?Jg(t):t}function J_(e){let t=globalThis.location;if(!t?.host)return!1;try{return new URL(e).host===t.host}catch{return!1}}function Y_(){let e=globalThis.WebSocket;if(!e)throw Error(`browser WebSocket is not available`);return e}function X_(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 Z_(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 Q_(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 $_(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 ev(e){let t=e.sub;if(typeof t==`string`&&Ie(t))return t;let n=e.jwt_token;if(typeof n==`string`){let e=tv(n);if(e)return e}let r=e.backend_session;if(r&&typeof r==`object`){let e=r.user_id;if(typeof e==`string`&&Ie(e))return e}return null}function tv(e){let t=e.split(`.`);if(t.length<2)return null;try{let e=JSON.parse(nv(t[1]));return typeof e.sub==`string`&&Ie(e.sub)?e.sub:null}catch{return null}}function nv(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 rv=20,iv=/^(?:0|[1-9][0-9]*|-[1-9][0-9]*)$/,av=16,ov={none:`none`,connecting:`attempting`,connected:`live`,unavailable:`failed`},sv=250,cv=4;function lv(e){return typeof e?.poll==`function`}function uv(e){if(!e||e instanceof Uint8Array)throw Error(`Native runtime direct mutation did not return a write receipt`);return e}function dv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`}function fv(e,t){return a_(e)?{kind:`network`,message:e.message}:o_(e)?{kind:`fatal`,message:e.message}:{kind:`wire`,...e,admitted:t}}function pv(e,t){return e?Promise.allSettled([e,t]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason}):t}function mv(e){let t=e;return typeof t?.poll==`function`&&typeof t.cancel==`function`&&typeof t.setWake==`function`}var hv=new T({fatal:!0}),gv=new WeakMap;function _v(e,t,n,r,i,a=!1){try{return vv(e,t,n,r,i,a)}catch(e){throw Ne(e)}}function vv(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 yv(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 bv(e){let t=e.indexOf(`. Plan: `);return t===-1?e:e.slice(0,t)}var xv={open:0,quiesced:1,storageCleared:1,closing:2,closed:3},Sv=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;nativeAuthRefused=!1;nativeLinkEverConnected=!1;nativeLinkPoll=null;firstLoadWaitSeen=!1;remoteLink=new Am(()=>this.readRemoteLinkState());linkStatusPublisher=new vs(()=>this.upstreamLinkStatus(),ms);syncStatusPublisher=new vs(()=>this.readSyncStatus(),(e,t)=>_s(e.uploads,t.uploads)&&ms(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(ug(t),n?sg(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=ug(t),this.trustedBackend=(o?.owner?.trustedBackend??o?.backendMode)===!0,this.selfSignedClientProof=o?.selfSignedClientProof,this.scopeIsolatedRelay=o?.scopeIsolatedRelay===!0,this.webSocket=o?.webSocket,this.configBytes=Wh(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=_e(t),o?.db)this.db=o.db;else if(o?.persistentPath){if(!e)throw Error(`Native runtime constructor required for persistent storage`);this.db=_v(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=yv(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(this.noteNativeAuthRestored(),!e)return this.nativeAuthRefusalRenewable=!1,this.clearRemoteServerTransportError();let t=e.code?Tm({code:e.code,message:e.reason}):Error(e.reason);this.handleServerTransportError(t,this.serverConnectionGeneration,e.retrying||this.nativeAuthRefusalRenewable)})}createPeerAuthority(){return{node:this.node,epoch:p(),features:this.nativeWireFeatures()}}async connectUpstreamPeer(e){return this===this.ownerRuntime?(this.peerUpstreamAttached=!0,e?this.connectNegotiatedUpstream({protocolVersion:6,features:e.features,authority:e}):await this.db.connectUpstream()):await this.ownerRuntime.connectUpstreamPeer(e)}onPeerTransportWork(e){return this===this.ownerRuntime?(this.peerTransportWorkListeners.add(e),()=>{this.peerTransportWorkListeners.delete(e)}):this.ownerRuntime.onPeerTransportWork(e)}onAuxiliaryTrace(e){return this===this.ownerRuntime?(this.auxiliaryTraceListeners.add(e),this.serverTransport?.setAuxiliaryTraceEnabled?.(!0),()=>{this.auxiliaryTraceListeners.delete(e),this.auxiliaryTraceListeners.size===0&&this.serverTransport?.setAuxiliaryTraceEnabled?.(!1)}):this.ownerRuntime.onAuxiliaryTrace(e)}onQueryCoverageTrace(e){return this===this.ownerRuntime?(this.queryCoverageTraceListeners.add(e),()=>this.queryCoverageTraceListeners.delete(e)):this.ownerRuntime.onQueryCoverageTrace(e)}emitQueryCoverageTrace(e){if(this!==this.ownerRuntime){this.ownerRuntime.emitQueryCoverageTrace(e);return}let t={stage:e,peerActivityEpoch:this.peerTransportActivityEpoch,peerProcessedActivityEpoch:this.peerTransportProcessedActivityEpoch};for(let e of this.queryCoverageTraceListeners)e(t)}notifyPeerTransportActivity(){if(this!==this.ownerRuntime)return this.ownerRuntime.notifyPeerTransportActivity();this.peerTransportActivityEpoch+=1,this.notifyPeerTransportWork(!0)}async progressPeerTransport(){if(this!==this.ownerRuntime)return this.ownerRuntime.progressPeerTransport();let e=this.peerTransportActivityEpoch;await this.runCoreTick(),this.closed||(this.peerTransportProcessedActivityEpoch=Math.max(this.peerTransportProcessedActivityEpoch,e))}retirePeerTransport(e){return this===this.ownerRuntime?(this.auxiliaryReceiveDeadlines.get(e)?.close(),this.auxiliaryReceiveDeadlines.delete(e),this.coreOperation?new Promise((t,n)=>{let r=this.pendingTransportRetirements.get(e)??[];r.push({resolve:t,reject:n}),this.pendingTransportRetirements.set(e,r)}):(e.close(),Promise.resolve())):this.ownerRuntime.retirePeerTransport(e)}setNonDurableClient(){if(this!==this.ownerRuntime)return this.ownerRuntime.setNonDurableClient();if(!this.db.setNonDurableClient)throw Error(`Native runtime does not expose non-durable client mode`);this.db.setNonDurableClient(),this.nonDurableClient=!0}foregroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.foregroundTxTimeHighWater();if(!this.db.foregroundTxTimeHighWater)throw Error(`Native runtime does not expose foreground transaction high-water`);return this.db.foregroundTxTimeHighWater()}quiesceForegroundTxTimeHighWater(){if(this!==this.ownerRuntime)return this.ownerRuntime.quiesceForegroundTxTimeHighWater();if(this.foregroundLeaseCapture)return this.foregroundLeaseCapture;if(this.closed)throw Error(`Native runtime is already ${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(!Ub(n,this.peerIdentity))throw Ey();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?.(ov[e])}remoteLinkState(){return this===this.ownerRuntime?this.readRemoteLinkState():this.ownerRuntime.remoteLinkState()}onRemoteLinkStateChange(e,t){this===this.ownerRuntime?(this.remoteLink.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onRemoteLinkStateChange(e,t)}startNativeLinkPoll(){this.db?.nativeConnectionStatus&&!this.nativeLinkPoll&&!this.closed&&this.linkHasListeners()&&(this.nativeLinkPoll=setInterval(()=>{this.linkHasListeners()?this.linkChanged():this.stopNativeLinkPoll()},sv))}noteFirstLoadWait(e){if(!Vv(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.noteNativeAuthRestored(),this.noteLinkFailure()),this.remoteLink.changed(),this.linkStatusPublisher.changed(),this.syncStatusPublisher.changed()}upstreamLinkStatus(){if(this!==this.ownerRuntime)return this.ownerRuntime.upstreamLinkStatus();if(this.closed)return K(`stopped`,!1);let e=this.db?.nativeConnectionStatus?.();return e?e.configured?e.explicitlyOffline?K(`disconnected`):e.authRejected?K(`auth`):e.connected?fs:this.serverTransportError?this.serverTransportErrorRetrying?K(`network`):wm(this.serverTransportError)?K(`authority-changed`,!1):K(`stopped`):ds:us:this.linkStatus?.phase===`stopped`&&wm(this.upstreamRefusal)?K(`authority-changed`,!1):ps(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()}pendingUploadRows(e){return this===this.ownerRuntime?this.closed?null:this.db?.pendingUploadRows?.(e)??null:this.ownerRuntime.pendingUploadRows(e)}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=cs(e,(this.linkFailure??this.serverTransportError)?.message);n&&(this.lastFailure=n)}onUpstreamLinkStatusChange(e,t){this===this.ownerRuntime?(this.linkStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onUpstreamLinkStatusChange(e,t)}onSyncStatusChange(e,t){this===this.ownerRuntime?(this.syncStatusPublisher.subscribe(e,t),this.startNativeLinkPoll()):this.ownerRuntime.onSyncStatusChange(e,t)}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(xv[e]<=xv[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()}else 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(Kb),this.peerUpstreamAttached=!1,this.serverCarrier?.close(),this.serverCarrier=null}previewInsert(e,t,n){let r=this.rowStateFromValues(e,n?Vb(n):y(16),t);return{id:r.id,values:r.values}}insert(e,t,n,r){this.assertMutationAdmission(`Insert`);let i=r?Vb(r):void 0,a=Av(n);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(n),c=Nv(n),l=Dv(n);kv(s,l);let u=this.currentTx(n,`Insert`);u&&this.assertTransactionAttribution(u,s);let d=cb(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:Ev(n)}}let f=Sy(`Insert`,()=>uv(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=Av(a);this.applySessionClaims(u);let d=this.trustedWriteIdentity(u),f=this.backendAttribution(a),p=Dv(a),m=Nv(a);if(kv(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?Vb(o):y(16),v=e===`insert`?lb(h,n,r,t):ub(h,n,r),b=s.call(this.db,t,_,v,r,e,f?void 0:d,f,m??void 0,p?.head,p?.base,l?.id);if(l&&!b.finishInTransaction)throw await b.abort(),Error(`This native runtime does not support streaming inside a transaction yet`);let x=this.ownerRuntime,S,C=new Promise(e=>{S=e});x.pendingStreamingMutations.add(C);let w=new TextEncoder,T=async e=>{let t=65536;for(let n=0;n<e.byteLength;n+=t)await b.push(e.subarray(n,n+t))},E=``;try{for await(let e of xm(i))if(typeof e==`string`){if(g===`Bytea`)throw Error(`Bytea streams require Uint8Array chunks`);let t=E+e;E=``;let n=t.charCodeAt(t.length-1);n>=55296&&n<=56319&&(E=t.slice(-1),t=t.slice(0,-1)),t.length>0&&await T(w.encode(t))}else if(e instanceof Uint8Array)E&&=(await T(w.encode(E)),``),await T(e);else throw Error(`Streaming insert chunks must be strings or Uint8Array values`);E&&await T(w.encode(E));let e=x.streamingFinalization,t,n=new Promise(e=>{t=e});x.streamingFinalization=e.then(()=>n),await e;let r;try{l?(await b.finishInTransaction(),l.hasStagedMutations=!0,r={kind:`staged`,openTransactionId:l.id}):r=this.finishMutation(await b.finish())}finally{t()}return{id:M(_),...r}}catch(e){throw await b.abort(),e}finally{S(),x.pendingStreamingMutations.delete(C)}}restore(e,t,n,r){this.assertMutationAdmission(`Restore`);let i=Vb(t),a=Av(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Nv(r),l=Dv(r);kv(s,l);let u=this.currentTx(r,`Restore`);u&&this.assertTransactionAttribution(u,s);let d=cb(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:Ev(r)}}let f=Sy(`Restore`,()=>uv(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=Vb(t),a=Av(r);this.applySessionClaims(a);let o=this.trustedWriteIdentity(a),s=this.backendAttribution(r),c=Nv(r),l=Dv(r);kv(s,l);let u=this.currentTx(r,`Update`);u&&this.assertTransactionAttribution(u,s);let d=db(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:Ev(r)};let f=Sy(`Update`,()=>uv(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=Vb(t),o=Nv(i),s=Dv(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=Av(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 Cy(`Update`,`typed partial-value updates in transactions are not supported by this runtime`);let d=db(this.table(e),n);return u.call(this.db,c.id,e,a,d,r,o??void 0),c.hasStagedMutations=!0,{kind:`staged`,openTransactionId:Ev(i)}}if(Ov(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=db(this.table(e),n),d=Sy(`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=Vb(t),a=this.table(e),o=Av(r);this.applySessionClaims(o);let s=this.trustedWriteIdentity(o),c=this.backendAttribution(r),l=Nv(r),u=Dv(r);kv(c,u);let d=this.currentTx(r,`Upsert`);d&&this.assertTransactionAttribution(d,c);let f;try{f=db(a,n)}catch(e){throw Cy(`Upsert`,wy(Ty(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:Ev(r)};let p=Sy(`Upsert`,()=>uv(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=Vb(t),i=Av(n);this.applySessionClaims(i);let a=this.trustedWriteIdentity(i),o=this.backendAttribution(n),s=Nv(n),c=Dv(n);kv(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:Ev(n)};let u=Sy(`Delete`,()=>uv(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`&&Be(e,st(e)))}delegatedPermissionAdviceSession(e){if(!this.trustedBackend||!e||!this.isScopedPermissionAdvice(e))return null;try{return Wv(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=Wv(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=cb(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,Vb(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=db(this.table(e),n);return this.withPermissionAdviceTimeout(()=>a.call(this.db,e,Vb(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,Vb(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 ye);let e=this.db.captureSnapshot();return this.scheduleCoreTick(),this.awaitNativeRead(e).then(e=>ae(hv.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=Av(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(Fv(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=Tv(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 yy(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(Iv(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`);Hv(n,r),this.noteFirstLoadWait(r),Lv(r,this.pendingTxs,this.completedTxs);let i=Wv(t);Qv(e);let a=gy(e),o=Rv(r,this.pendingTxs),s=Bv(n,Yv(a),r),c=this.nativeReadContext(i,o),l=Zv(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`),Xv(a)){if(o){let e=await this.readRowsForContextAsync(l,s,c,o.id);return this.emitQueryCoverageTrace(`covered`),yb(gb(e),this.schema,uy(a,this.schema).rootColumns)}let e=await this.readRowsForContextAsync(l,s,c);return this.emitQueryCoverageTrace(`covered`),yb(gb(e),this.schema,uy(a,this.schema).rootColumns)}let u=uy(a,this.schema).rootColumns,d=await this.readPlainRows(l,s,i??void 0,o);return this.emitQueryCoverageTrace(`covered`),_b(hb(d),this.schema,u)}createSubscription(e,t,n,r){Hv(n,r),this.noteFirstLoadWait(r);let i=Wv(t),a=this.nativeReadContext(i);Qv(e);let o=this.nextSubscriptionId++,s=Bv(n,Yv(e),r);this.subscriptions.set(o,{openingAbort:new AbortController,reading:!1,outputColumns:uy(e,this.schema),tier:n??`local-first`,cancelled:!1});let c=this.subscriptions.get(o),l=Zv(e,this.schema),u=e=>{let t=Fb(e);c.cancelled||this.closed||this.ownerRuntime.closed?Jv(t):(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 mv(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`);n.callback=t,n.terminalError?this.deliverSubscriptionFailure(n):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=V_(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,n=setTimeout(()=>{this.linkTimer?.token===t&&(this.linkTimer=null,this.stepLink({type:`timerFired`,token:t}))},e.afterMs);this.linkTimer={token:t,handle:n};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(Ty(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=B_(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}:fv(e,c.carrier.hasNegotiated);this.endLinkAttempt(c,Error(e.message),t)},u=new E_({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=>{i_(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()||!this.trustedBackend&&(await this.runWhenCoreIdle(()=>{if(d())return this.installClientSessionClaims(z_(n))}),!d())){u.close();return}let i=this.connectNegotiatedUpstream(t).catch(e=>{throw Dy(`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(Ty(e));this.endLinkAttempt(c,t,{kind:`fatal`,message:t.message})})}async connectNegotiatedUpstream(e){let t=e.authority,n=this.db.connectUpstreamWithSession;if(!t||!n)return await this.db.connectUpstream();let r=p();return await n.call(this.db,e.protocolVersion,e.features,t.node,t.epoch,this.node,r)}nativeWireFeatures(){if(!this.db.wireFeatures)throw Error(`native runtime binding does not expose its wire feature mask; install the matching Jazz native runtime package`);let e=this.db.wireFeatures();if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error(`native binding returned invalid wire feature mask ${e}`);return e}nativeUpstreamConfigured(){return this===this.ownerRuntime?this.db.nativeConnectionStatus?.().configured===!0:this.ownerRuntime.nativeUpstreamConfigured()}async disconnect(e={}){if(this!==this.ownerRuntime)return this.ownerRuntime.disconnect(e);if(this.db?.disconnectNativeUpstream){this.db.disconnectNativeUpstream(),this.linkChanged();return}let t=this.serverTransport,n=this.serverConnectionAttempt,r=n?.transport;this.linkCloseReason=`server transport disconnected`,this.stepLink({type:`setOffline`,offline:!0}),this.linkCloseReason=`server transport replaced`,this.serverEndpointUrl=null,this.serverAuthJson=null,this.serverReplacementRetirement||this.forgetServerTransportError(),e.rejectWaiters??!0?this.resolveServerTransportErrorWaiters(Error(`server transport disconnected`)):this.clearServerTransportErrorWaiters(),this.resolveServerTransportWorkWaiters(),this.serverTransport=null;let i=[];n?.retirement&&i.push(n.retirement),t&&t!==r&&i.push(Promise.resolve().then(()=>this.retirePeerTransport(t))),this.linkChanged(),await Promise.all(i)}updateAuth(e){if(this!==this.ownerRuntime)return this.ownerRuntime.updateAuth(e);if(this.nativeAuthRefusalRenewable=!1,this.db?.rejectAuthUpdate)return this.db.rejectAuthUpdate();let t=V_(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=V_(e);if(!U_(t))return;let n;try{n=B_(t,this.peerIdentity)}catch{n=null}if(!n||!Ub(n,this.upstreamPrincipal))throw Ey(`a credential refresh must keep the principal this store connects upstream as`)}pinUpstreamPrincipal(e){!this.upstreamPrincipal&&U_(e)&&(this.upstreamPrincipal=B_(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.nativeAuthRefused=!0,this.authFailureCallback?.(e)})}noteNativeAuthRestored(){if(!this.nativeAuthRefused||this.closed)return;let e=!1;try{let t=this.db?.nativeConnectionStatus?.();e=!(!t?.connected||t.authRejected)}catch{return}e&&(this.nativeAuthRefused=!1,this.authRestoredCallback?.())}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(Av(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=Tv(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=Tv(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,M(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(lv(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(!lv(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 vy(0)}}finally{this.ownerRuntime.pendingNativeReadCancels.delete(i),i(),this.ownerRuntime.scheduleCoreTick()}}trustedWriteIdentity(e){let t=this.readAuthorizationHost===`trusted-serving`;return e?!this.trustedBackend&&!t&&Ub(e.identity,this.peerIdentity)?void 0:e.identity:t&&!this.trustedBackend?this.peerIdentity:void 0}backendAttribution(e){if(!this.trustedBackend||!e)return;let t;try{t=JSON.parse(e).attribution}catch{return}if(t===void 0)return;if(typeof t!=`string`||!D(t))throw Error(`backend attribution must be a canonical author subject string`);let n=Av(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=Kv(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`||Kv(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=B_(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(Ty(e))),a=this.waitForServerTransportError(`global`),o=a?.promise.catch(e=>e instanceof Error?e:Error(Ty(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||!Bb(n,B_(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,Bv(`remote`,!1),this.nativeReadContext(n)))})().catch(()=>void 0)}admitLocalFirstSession(e,t,n){if(!this.trustedBackend||e.issuer!==`urn:jazz:local-first`||!e.account_id||!Be(e,st(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 T().decode(ne(e)))}applySessionClaims(e){e&&!e.backendAuthority&&this.readAuthorizationHost===`trusted-serving`&&this.db.setIdentityClaims&&this.db.setIdentityClaims(e.identity,e.claims)}table(e){let t=this.schema[e];if(!t)throw Error(`unknown table ${e}`);return t}currentTx(e,t){let n=Ev(e);if(!n)return;let r=this.pendingTxs.get(n);if(r)return r;throw Error(`${t} failed: WriteError("${Pv(n,this.completedTxs)}")`)}assertTransactionWriteIdentity(e,t){if(e.kind===`serializable`){if(e.identity&&(!t||!Ub(e.identity,t)))throw Error(`Native runtime serializable transaction cannot mix write identities`)}else if(e.identity&&(!t||!Ub(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||!Ub(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;else{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);else{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=dv(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 vy(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);else 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)}else this.notifyPeerTransportWork(),e===`immediate`?this.scheduleCoreTick():queueMicrotask(()=>{this.scheduleCoreTick()})}}scheduleCoreTick(){this.coreProgressAllowed()&&(this.coreOperation?this.coreTickAgain=!0:this.coreTickScheduled||(this.coreTickScheduled=!0,queueMicrotask(()=>{this.coreTickScheduled=!1,this.coreProgressAllowed()&&(this.coreOperation?this.coreTickAgain=!0:this.runCoreTick().catch(e=>{try{if(this.db.isNativeForegroundClosed?.())return}catch(e){Kb(e);return}this.serverTransport!==null||this.serverEndpointUrl!==null?this.handleServerTransportError(e):Kb(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=bv(t);n===t?console.warn(`[jazz] ${t}`):(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 Dm(e)}if(this.ownerRuntime.noteNativeAuthRestored(),this.syncStatusPublisher.changed(),this.reportSlowQueries(),this.pumpSubscriptions(),this.scheduleServerPump(),this.notifyPeerTransportWork(),!this.coreProgressAllowed()||!this.coreTickAgain)break;if(t+1>=cv){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()}else 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(()=>vy(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=Mb(n);if(r.type===`closed`){this.terminateSubscription(e,t);return}if(r.type===`rejected`){if(r.reason.type===`ShapeRegistrationPendingCatalogueAdmission`)return;this.failSubscription(t,Pb(r.reason));return}let i=Sb(r.delta,this.schema,r.reset===!0,t.outputColumns,r.coalesced===!0);i.terminalOperations=dy(r.terminalOperations,t.outputColumns?.rootColumns),t.callback?.(i)}scheduleServerPump(){!this.closed&&this.serverTransport&&(this.serverPumpRunning?this.serverPumpAgain=!0:this.serverPumpScheduled||(this.serverPumpScheduled=!0,setTimeout(()=>{this.serverPumpScheduled=!1,this.closed||this.startServerPump()},av)))}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;else{this.serverPumpRunning=!0;try{let r=this.pendingInboundServerFrames.length>0&&await this.routePendingInboundServerFrames();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=Cv(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=Tm(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(wv(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 Yi(e,r=>{if(this.closed||e!==this.serverTransport||n!==this.serverConnectionGeneration)return;let i=r instanceof Error?r:Error(Ty(r)),a=this.serverConnectionAttempt;a?.transport===e?this.finishServerConnectionAttempt(a,i):(t.close(),this.handleServerTransportError(i,n),this.retirePeerTransport(e).catch(Kb))}),this.auxiliaryReceiveDeadlines.set(e,r)),r.refresh()}flushAuxiliaryOutbound(e,t,n){let r=e.recvAuxiliaryWireFrames;if(!r)return;let i=Cv(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||!Om(e)))return;let r=Ty(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=pv(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{Jv(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 Cv(e){return e.filter(e=>ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`)}function wv(e){let t=Cv([e])[0];if(!t)throw Error(`native transport returned a non-byte wire frame`);return t}function Tv(e,t){let n=e.txId;return t.set(n,e),n}function Ev(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Dv(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 Ov(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=Av(e);return n===null||!Ub(n.identity,t)}catch{return!0}}function kv(e,t){if(e&&t)throw Error(`Backend-attributed writes do not support branch views`)}function Av(e){if(!e)return null;try{let t=JSON.parse(e);if(t.attribution===`system`)throw Error(`Native runtime public session uses reserved issuer`);let n=typeof t.attribution==`string`?D(t.attribution):null;if(n?.issuer===`urn:jazz:system`)throw Error(`Native runtime public session uses reserved issuer`);let r=n?.user_id??(typeof t.user_id==`string`?t.user_id:typeof t.session?.user_id==`string`?t.session.user_id:void 0);if(!r||!Ie(r))return null;let i=n?.issuer??t.session?.issuer??t.issuer;if(typeof i!=`string`||!Ie(i))throw Error(`session is missing issuer`);let a={account_id:Uv(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`};jv(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=qv(t.session?.claims??t.claims,a);return{...a,claims:s,identity:ne(a),backendAuthority:a.issuer===`urn:jazz:system`&&a.user_id===`system`&&Be(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 jv(e,t,n,r,i){if(Ge(e)&&(n!==`device-account`&&n!==`anonymous`&&n!==`external`||!Be({issuer:e,user_id:t,authMode:n,account_id:i},r)))throw Error(`Native runtime public session uses reserved issuer`)}function Mv(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 Nv(e){return Mv(e)??null}function Pv(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 Fv(e,t){let n=Pv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Commit transaction failed: Write error: ${n}`}function Iv(e,t){let n=Pv(e,t);return t.get(e)?.state===`committed`?`Write error: ${n}`:`Rollback transaction failed: Write error: ${n}`}function Lv(e,t,n){let r=zv(e);if(r&&!t.has(r))throw Error(`Query setup failed: Write error: ${Pv(r,n)}`)}function Rv(e,t){let n=zv(e);return n?t.get(n):void 0}function zv(e){if(e)try{let t=JSON.parse(e);return typeof t.transaction_id==`string`?t.transaction_id:void 0}catch{return}}function Bv(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 Vv(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 Hv(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 Uv(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 Wv(e){if(e==null)return null;let t=JSON.parse(e);if(typeof t.user_id!=`string`||!Ie(t.user_id))throw Error(`Native runtime session is missing user_id`);if(typeof t.issuer!=`string`||!Ie(t.issuer))throw Error(`Native runtime session is missing issuer`);let n={account_id:Uv(t.account_id),issuer:t.issuer,user_id:t.user_id,authMode:typeof t.authMode==`string`?t.authMode:`external`};jv(n.issuer,n.user_id,n.authMode,t[Te],n.account_id);let r=n.issuer===`urn:jazz:system`&&n.user_id===`system`&&Be(n,t.__jazz_trusted_reserved_session);return{...n,claims:qv(t.claims,n),identity:ne(n),backendAuthority:r}}function Gv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kv(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(Kv).join(`,`)}]`:Gv(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Kv(e[t])}`).join(`,`)}}`:`null`}function qv(e,t){return{...Gv(e)?e:{},iss:t.issuer,sub:t.user_id}}function Jv(e){e.close()}function Yv(e){try{return JSON.parse(e).include_deleted===!0}catch{return!1}}function Xv(e){try{let t=JSON.parse(e).array_subqueries;return Array.isArray(t)&&t.length>0}catch{return!1}}function Zv(e,t){return Fy(e,t)}function Qv(e){if($v(e))throw Error(`Native runtime does not support permission-introspection query columns or predicates ($canRead) until unified policy lowering exists.`)}function $v(e){let t=JSON.parse(e);return iy(t.select_columns??t.select)||ay(t.conditions)||ey(t.relation_ir)||ty(t.relation_ir)||oy(t.array_subqueries)}function ey(e){return cy(e)}function ty(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(ty);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=ry(e.expr??e.source);if(n&&Os(n))return!0}}return Object.values(t).some(ty)}function ny(e){if(!e||typeof e!=`object`)return null;let t=e;return nb(t.left??t.column)}function ry(e){return!e||typeof e!=`object`?null:`Column`in e?nb(e.Column):nb(e)}function iy(e){return Array.isArray(e)?e.some(e=>typeof e==`string`&&Os(ly(e))):!1}function ay(e){return Array.isArray(e)?e.some(cy):!1}function oy(e){return Array.isArray(e)?e.some(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return iy(t.select_columns??t.select)||sy(t.filters)||oy(t.nested_arrays)}):!1}function sy(e){return Array.isArray(e)?e.some(cy):!1}function cy(e){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e))return e.some(cy);let t=e;if(typeof t.op==`string`&&typeof t.column==`string`&&Os(ly(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`&&Os(ly(r)))return!0}let n=ny(t.Cmp)??ny(t.In)??ny(t.IsNull)??ny(t.IsNotNull)??ny(t.Contains);return n&&Os(ly(n))?!0:Object.entries(t).some(([e,t])=>e!==`Literal`&&cy(t))}function ly(e){return ys(e)}function uy(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:hy(n.table,t,zy(n.select_columns??n.select),Vy(n.array_subqueries,n.table,t)??[])}}function dy(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:fy(e.Key)};if(!n)throw Error(`native terminal collection path requires subscription output columns`);let t=e.Collection.startsWith(`__jazz_include_`)?e.Collection.slice(Ks.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=my(a.Insert.key);return{root_key:fy(e.root_key),path:i,edit:{Insert:{index:a.Insert.index,key:fy(a.Insert.key),row:ah(t,r,py(a.Insert.value))}}}}if(`Update`in a){if(!r)throw Error(`native terminal update has no collection target`);let t=my(a.Update.key);return{root_key:fy(e.root_key),path:i,edit:{Update:{key:fy(a.Update.key),row:ah(t,r,py(a.Update.value))}}}}return`Remove`in a?{root_key:fy(e.root_key),path:i,edit:{Remove:{key:fy(a.Remove.key)}}}:{root_key:fy(e.root_key),path:i,edit:{Move:{key:fy(a.Move.key),index:a.Move.index}}}})}function fy(e){return Array.isArray(e)?e:Array.from(e)}function py(e){return e instanceof Uint8Array?e:Uint8Array.from(e)}function my(e){let t=py(e);if(t.length<17||t[0]!==10)throw Error(`terminal key must begin with a UUID row key`);return M(t.subarray(1,17))}function hy(e,t,n,r,i=!0){let a=W(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=As(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=hy(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 gy(e){let t=JSON.parse(e);return _y(t.array_subqueries),JSON.stringify(t)}function _y(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=ys(n);(zy(e.select_columns)??[]).includes(r)||e.select_columns.push(r)}_y(e.nested_arrays)}}function vy(e){return new Promise(t=>setTimeout(t,e))}function yy(e,t){return My(t)?by(e,t):Ny(t)?xy(e,t):null}function by(e,t){let n=Ty(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 xy(e,t){let n=Ty(t),r={kind:`rejected`,transactionId:e,code:ky(Gc(t)),reason:jy(n,Gc(t)),message:n};return Object.defineProperty(r,"message",{enumerable:!1}),r}function Sy(e,t){try{return t()}catch(t){if(Ny(t)){let n=Ty(t),r=Py(n)??n,i=Gc(t)??(r.startsWith(`authorization_denied:`)?`authorization_denied`:void 0);throw Object.assign(Error(`${e} failed: WriteError("${r}")`),{code:ky(i)})}throw t}}function Cy(e,t){return Error(`${e} failed: WriteError("${t.replaceAll(`"`,`\\"`)}")`)}function wy(e){let t=/^missing required column ([A-Za-z_$][\w$]*)$/.exec(e);return t?`missing required field \`${t[1]}\``:e}function Ty(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 Ey(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 Dy(e,t){let n=t instanceof Error?t:Error(Ty(t));return Error(`${e}: ${n.message}`,{cause:n})}var Oy={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 ky(e){return e===void 0?`write_rejected`:Oy[e]}var Ay={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 jy(e,t){let n=Py(e);return n===null?e:Ay[ky(t)]??(n||`Write rejected`)}function My(e){return Uc(e)===`transaction_conflict`}function Ny(e){return Uc(e)===`write_rejected`}function Py(e){let t=/^WriteRejected:\s*(.*)$/s.exec(e);return t?t[1]:null}function Fy(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=Nm(e);if(!i.relation_ir||typeof i.relation_ir!=`object`)throw Error(`Relation query is missing relation_ir`);return Kh(r,[],{relation:i.relation_ir,select:zy(n.select_columns??n.select),partial:Ry(n.select_columns),arraySubqueries:Vy(n.array_subqueries,r,t)})}let i=Zy(n.conditions);if(!i)throw Q();return Kh(r,i.map(e=>Iy(r,e,t)),{limit:ab(n.limit),offset:ob(n.offset),orderBy:By(n.order_by??n.orderBy),select:zy(n.select_columns??n.select),partial:Ry(n.select_columns),arraySubqueries:Vy(n.array_subqueries,r,t)})}function Q(e){let t=e?` (${e})`:``;return Error(`Native runtime cannot encode this query shape${t}.`)}function Iy(e,t,n){if(t.op===`All`||t.op===`Any`)return{op:t.op,predicates:t.predicates.map(t=>Iy(e,t,n))};if(t.op===`Not`)return{op:`Not`,predicate:Iy(e,t.predicate,n)};if(Vo(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=>Iy(e,{column:t.column,op:`Eq`,value:r},n))};if(Ly(t)){let r=Jy(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`}:W(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:Jy(e,t.column,i,n)}:{column:t.column,op:`Contains`,value:Yy(i,r.element,!1)})}:{...t,values:t.values.map(r=>Jy(e,t.column,r,n))}}if(t.op===`Contains`){let r=t.column===`id`?{type:`Uuid`}:W(n,e)?.columns.find(e=>e.name===t.column)?.column_type;return{...t,value:r?.type===`Array`?Yy(t.value,r.element,!1):Jy(e,t.column,t.value,n)}}if(t.op===`IsNull`||t.op===`IsNotNull`)return t;if(Ly(t))return{...t,value:Jy(e,t.column,t.value,n)};throw Error(`unsupported query predicate ${JSON.stringify(t)}`)}function Ly(e){return e.op===`Eq`||e.op===`Ne`||e.op===`Gt`||e.op===`Gte`||e.op===`Lt`||e.op===`Lte`}function Ry(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 zy(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 By(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 Vy(e,t,n){if(e!=null){if(!Array.isArray(e))throw Q(`array_subqueries`);return e.map(e=>Hy(e,t,n))}}function Hy(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=Uy(r.filters,r.table,n),a=zy(r.select_columns),o=Gy(r.order_by),s=Vy(r.nested_arrays,r.table,n)??[];return{columnName:r.column_name,table:r.table,innerColumn:r.inner_column,outerColumn:qy(r.outer_column,t),filters:i,select:a,orderBy:o,limit:r.limit==null?null:ib(r.limit),offset:ob(r.offset),requirement:Ky(r.requirement),nestedArrays:s}}function Uy(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=Wy(i);if(!e)throw Q(`array_subqueries.filters`);r.push(...e.map(e=>Iy(t,e,n)))}return r}function Wy(e){let t=$y(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:eb(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:eb(t)}]:null}return null}function Gy(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 Ky(e){if(e==null||e===`Optional`)return`Optional`;if(e===`AtLeastOne`||e===`MatchCorrelationCardinality`)return e;throw Q(`array_subqueries.requirement`)}function qy(e,t){let n=`${t}.`;return e.startsWith(n)?e.slice(n.length):e}function Jy(e,t,n,r){let i=t===`id`?{type:`Uuid`}:As(t)??W(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(Xy))};if(n.type===`Array`){let i=t===`id`?{type:`Uuid`}:W(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=>Yy(e,a,!1))}}return Yy(n,i,!0)}function Yy(e,t,n){if(e.type===`Nullable`)return n&&e.value?{type:`Nullable`,value:Yy(e.value,t,!1)}:e;if(t?.type===`Uuid`&&e.type===`Text`&&sb(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:Lm(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(Xy))}:t?.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Yy(e,t.element,!1))}:e}function Xy(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 Zy(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=$y(n);if(e){t.push(e);continue}let r=n;if(typeof r.column!=`string`||typeof r.op!=`string`)return null;let i=ys(r.column);switch(r.op){case`eq`:r.value===null?t.push({column:i,op:`IsNull`}):t.push({column:i,op:`Eq`,value:eb(r.value)});break;case`ne`:r.value===null?t.push({column:i,op:`IsNotNull`}):t.push({column:i,op:`Ne`,value:eb(r.value)});break;case`gt`:t.push({column:i,op:`Gt`,value:eb(r.value)});break;case`gte`:t.push({column:i,op:`Gte`,value:eb(r.value)});break;case`lt`:t.push({column:i,op:`Lt`,value:eb(r.value)});break;case`lte`:t.push({column:i,op:`Lte`,value:eb(r.value)});break;case`contains`:t.push({column:i,op:`Contains`,value:eb(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(eb)});break;default:return null}}return t}function Qy(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=Qy(n);if(!t)return null;e.push(...t)}return e}if(Array.isArray(t.Or))return null;if(t.Not){let e=$y(t.Not);return e?[{op:`Not`,predicate:e}]:null}let n=t.IsNull;if(n&&typeof n==`object`){let e=nb(n.column);return e?[{column:e,op:`IsNull`}]:null}let r=t.IsNotNull;if(r&&typeof r==`object`){let e=nb(r.column);return e?[{column:e,op:`IsNotNull`}]:null}let i=t.Contains;if(i&&typeof i==`object`){let e=i,t=nb(e.left),n=rb(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=nb(e.left);if(!t||!Array.isArray(e.values))return null;let n=e.values.map(rb);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=tb(s.op);if(!c)return null;let l=nb(s.left),u=rb(s.right);return l&&u?[{column:l,op:c,value:u}]:null}function $y(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($y);return n.every(e=>e!==null)?{op:e,predicates:n}:null}if(t.Not){let e=$y(t.Not);return e?{op:`Not`,predicate:e}:null}let n=Qy(e);return n?.length===1?n[0]:null}function eb(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 sb(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(eb)};throw Q()}function tb(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 nb(e){if(!e||typeof e!=`object`)return null;let t=e.column;return typeof t==`string`?ys(t):null}function rb(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<=rv&&iv.test(n.value))try{return{type:`BigInt`,value:Lm(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=>rb({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 ib(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`query limit must be a non-negative safe integer`);return e}function ab(e){return e==null?void 0:ib(e)}function ob(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 sb(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 cb(e,t,n){return pb(e.columns,t,n),fb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function lb(e,t,n,r){return pb(e.columns.filter(e=>e.name!==n),t,r),fb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!0)}function ub(e,t,n){return fb(e.columns.filter(e=>e.name!==n&&Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function db(e,t){return fb(e.columns.filter(e=>Object.hasOwn(t,e.name)),e=>t[e.name],!1)}function fb(e,t,n){let r=[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({name:e.name,valueType:Th(e),column:e})),i=r.map(({column:e})=>mb(e,t(e),n)),a=new ag;return Xm(a,r),a.bytes(eh(r,i)),a.finish()}function pb(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 mb(e,t,n){let r=t;if(!r){if(e.nullable)return yh(Th(e));if(n&&e.default==null)throw Error(`missing required column ${e.name}`);return new Uint8Array}return _h(e,r)}function hb(e){return new og(e).readVec(Bm)}function gb(e){return qm(new og(e))}function _b(e,t,n,r=`full-record`){let i=[];for(let a of e){let e=vb(a,t,n),o=uh(a.descriptor);for(let t of a.rows){let n=[],s=new Map;for(let i of e){let e=Tb(i,o,t.raw,r);s.set(i.name,e),i.includeInValues&&n.push(e)}i.push(nh({table:a.table,id:M(t.rowId),values:n},s))}}return i}function vb(e,t,n){let r=gv.get(t);r||(r=new Map,gv.set(t,r));let i=dg(e),a=n?void 0:r.get(i);if(a)return a;let o=n??W(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&&zm(n);if(!r)continue;let i=As(r)??s.get(r)?.column_type;l.push({name:r,index:t,type:i,storageType:e.descriptor[t].valueType,includeInValues:!Wb(r)&&(!ks(r)||c?.has(r)===!0)})}return n||r.set(i,l),l}function yb(e,t,n,r=`full-record`){return xb(_b(e.rows,t,n,r),t).slice(0,e.rootCount)}var bb=new Set([`table`,`layer`,`schema_version`,`parents`,`created_by`,`created_at`,`updated_by`,`updated_at`]);function xb(e,t){return e.map(e=>{if(!e.valuesByColumn)return e;let n=new Set((W(t,e.table)?.columns??[]).map(e=>e.name)),r=new Map(e.valuesByColumn),i=new Set;for(let e of bb){if(n.has(e))continue;let t=r.get(e);t&&(i.add(t),r.delete(e))}return i.size===0?e:nh({...e,values:e.values.filter(e=>!i.has(e))},r)})}function Sb(e,t,n=!1,r=null,i=!1){let a=(e,n,i,a)=>{let o=wb(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:Ib(e,t,r),...s&&s.length>0?{splices:Cb(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:M(t.rowId),occurrenceKey:e.removedOccurrenceKeys[n],index:e.removedIndices[n]}]),...n?{reset:!0}:{},...n&&i?{reason:`backlog`}:{}}}function Cb(e,t,n){let r=W(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:hv.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 wb(e,t,n,r){return e.flatMap(e=>_b([e],t,e.table===n?.rootTable?n.rootColumns:void 0,r))}function Tb(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 Eb(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 Eb(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:Db(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:hv.decode(t.subarray(1))};case`Uuid`:return{type:`Uuid`,value:M(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:jb(e.element,t,Ob(r),i)};case`Row`:{let a={type:`Row`,value:Ab(e.columns,t,kb(r),i)};return(n===`$createdBy`||n===`$updatedBy`)&&ee(a),a}}}function Db(e){let t=e;for(;t?.tag===15;)t=t.inner;return t}function Ob(e){let t=Db(e);return t?.tag===14?t.inner:void 0}function kb(e){let t=Db(e);return t?.tag===16?t.record:void 0}function Ab(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=uh(a),c=new Map(e.map(e=>[e.name,e])),l=new Map,u=i?M(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=M(n);continue}let d=c.get(t);d&&l.set(t,n==null?{type:`Null`}:Eb(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 nh({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=M(t.subarray(a,a+16)),a+=16}let s=Hb(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:th(e,c)}}function jb(e,t,n,r=`full-record`){let i=Fh(n??Dh(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(Eb(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=Hb(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:Hb(t,4+(i-1)*4),l=i===a-1?t.length:Hb(t,4+i*4);if(c>l||l>t.length)throw Error(`invalid variable-width array element offset`);s.push(Eb(e,t.subarray(c,l),void 0,n,r))}return s}function Mb(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:Wm(new og(Gb(t.delta,`subscription delta`))),terminalOperations:Array.isArray(t.terminalOperations)?t.terminalOperations:void 0};if(t.type===`rejected`||t.type===`Rejected`)return{type:`rejected`,reason:Nb(t.reason)};throw Error(`unknown subscription chunk`)}function Nb(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 Pb(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):Tm({code:r,message:n})??Error(n)}function Fb(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 Ib(e,t,n=null){let r=n&&e.table===n.rootTable?n.rootColumns:t?.[e.table]?.columns,i=r?Eh(r):void 0;if(!i)throw Error(`missing schema for subscription row table ${e.table}`);let a=zb(e,i).map((e,t)=>Lb(e,i[t].column_type));return nh({id:e.id,values:a},rh(i,a))}function Lb(e,t){return e.type===`Null`?e:t.type===`Array`&&e.type===`Array`?{type:`Array`,value:e.value.map(e=>Lb(e,t.element))}:t.type===`Row`&&e.type===`Row`?{type:`Row`,value:Rb(e.value,t.columns)}:e}function Rb(e,t){let n=e.valuesByColumn,r=t.map((t,r)=>Lb(n?.get(t.name)??e.values[r]??(t.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`}),t.column_type));return nh({id:e.id,values:r},rh(t,r))}function zb(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],a=e.valuesByColumn.get(i.name)??(i.column_type.type===`Array`?{type:`Array`,value:[]}:{type:`Null`});n[r]=a}return n}function Bb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Vb(e){let t=Xe(e);if(!t)throw Error(`invalid uuid ${e}`);return t}function Hb(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function Ub(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Wb(e){return e.startsWith(Ks)}function Gb(e,t){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return Uint8Array.from(e);throw Error(`expected ${t} bytes`)}function Kb(e){queueMicrotask(()=>{throw e})}var qb=class{connection;constructor(e,t,n,r,i,a){this.connection=new Za(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 Jb(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 Zb(n,e=>{try{if(new URL(e.replace(/^ws/,`http`)).origin!==r)return null}catch{return null}return Xb(t)},`the app's bearer`)}var Yb=3e4;function Xb(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`)),Yb)})]).finally(()=>clearTimeout(t))}function Zb(e,t,n){return class{type=`arraybuffer`;inner;closed=!1;listeners=[];constructor(r){let i=t(r);i?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`}))}):this.attach(new e(r))}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 Qb=`warn`;function $b(e){globalThis.__JAZZ_WASM_LOG_LEVEL=e??Qb}function ex(e){return nt({...e,trustedReservedSession:k(e)})}function tx(e){let t=e.runtimeSources?.browserWorkerSession;if(!e.runtimeSources?.browserWorkerPort||!t)return;let n=Ae(e.jwtToken??``),r=n?.iss===`urn:jazz:local-first`?`device-account`:n?.iss===`urn:jazz:anonymous`?`anonymous`:null;if(!r)return;let i=Oe(n??{},r);if(!i||i.issuer!==t.issuer||i.user_id!==t.user_id||i.authMode!==t.authMode)throw Error(`Attached browser worker session does not match its identity token`);l(e,i)}function nx(e){let t=ex(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 rx(e){return!ex(e)&&!!e.adminSecret}function ix(e,t){if(t&&e.jwtToken&&(t.issuer===`urn:jazz:local-first`||t.issuer===`urn:jazz:anonymous`))return{token:e.jwtToken,appId:B(e),claimedAuthor:Re(t.issuer,t.user_id,t.account_id)}}function ax(e){let t=e.initialSyncFlushEvery??512;if(!Number.isSafeInteger(t)||t<1)throw Error(`initialSyncFlushEvery must be a positive integer`);return t}function ox(e){let t=e.runtimeSources;return t?.wasmModule||t?.wasmSource||t?.wasmUrl||t?.baseUrl,t}var sx=class extends bm{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 pm(e.runtimeSources)}admitConfig(e){tx(e)}createClient({config:e,schema:t,migrations:n,onAuthFailure:r,onAuthRestored:i,foregroundNodeLease:a}){$b(e.logLevel);let o={onAuthFailure:r,onAuthRestored:i},s=ix(e,ex(e)),c=rx(e),u=a?.node.slice()??ie(),d=ne(nx(e)),f=ax(e),p=ux(e),m=e.cookieSession&&e.accountId?es(e):void 0,h=this.nativeSchemaView(t,u,d,f,!p,s,c,{appId:B(e),thresholdMs:e.slowQueryThresholdMs,...cx()?{consoleDetail:`summary`}:{}},n,m&&e.serverUrl?Jb(e.serverUrl,m):void 0,e.subscriptionBacklogRows);if(a&&h.seedForegroundTxTimeHighWater(a.confirmedTxTime),p&&(h.setNonDurableClient(),!a))throw Error(`Persistent browser runtime requires a foreground node lease`);let g={appId:B(e),accountId:e.accountId,schema:t,driver:e.driver,serverUrl:e.serverUrl,env:e.env,jwtToken:e.jwtToken,cookieSession:e.cookieSession,adminSecret:e.adminSecret};return l(g,k(e)),te.connectWithRuntime(this.wrapClientRuntime(h,e,t),g,o)}wrapClientRuntime(e,t,n){return e}async acquireBrowserForegroundNodeLease(e){if(!ux(e))throw Error(`Browser foreground node leases require persistent browser storage`);let t=fu(e);return await xo.acquire({runtimeSources:ox(e),dbName:t,storageOwner:Hi(e)})}async acquireForegroundNodeLease(e){if(!lx()||(e.driver?.type??`persistent`)!==`persistent`)return;let{acquireNodeForegroundNodeLease:t}=await ii(async()=>{let{acquireNodeForegroundNodeLease:e}=await import(`./node-foreground-node-lease.browser-2mfp13Qb.js`);return{acquireNodeForegroundNodeLease:e}},[],import.meta.url);return await t({appId:B(e),env:e.env??`dev`,authScope:Vi(e)})}createBrowserWorkerConnection({config:e,schema:n,client:r,onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u,onNewerBuild:d}){let f=r.getRuntime();if(!(f instanceof Sv))throw Error(`Browser worker connections require the native runtime adapter`);let p=ix(e,ex(e));if(rx(e))throw Error(`Persistent browser workers require a verified client session, not backend credentials`);let m=fu(e),h=ne(nx(e));return e.runtimeSources?.browserWorkerPort?new qb(f,e.runtimeSources.browserWorkerPort,ex(e)?.claims??{},m,{onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u},e.runtimeSources.inspectorBinding):new So(f,{runtimeSources:ox(e),schema:n,dbName:m,author:h,selfSignedClientProof:p,initialSyncFlushEvery:ax(e),migrations:f.migrations,appId:B(e),slowQueryThresholdMs:e.slowQueryThresholdMs,...e.subscriptionBacklogRows===void 0?{}:{subscriptionBacklogRows:e.subscriptionBacklogRows},storageOwner:Hi(e),authSessionKey:Vi(e),serverUrl:e.serverUrl?t(e.serverUrl,B(e)):void 0,authJson:JSON.stringify(dx(e)),sessionClaims:ex(e)?.claims??{},logLevel:e.logLevel,telemetryCollectorUrl:e.telemetryCollectorUrl},Ii(e,m,Ke(n)),{onAuthFailure:i,onAuthRestored:a,onExplicitOfflineChange:o,onRemoteLinkChange:s,onFailure:c,onStorageReset:l,onStorageInvalidated:u,onNewerBuild:d})}createBrowserFollowerConnection({config:e,client:t,port:n,onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s}){let c=t.getRuntime();if(!(c instanceof Sv))throw Error(`Browser follower connections require the native runtime adapter`);let l=ex(e)?.claims??{},u=new Za(c,n,l,null,{onAuthFailure:r,onAuthRestored:i,onExplicitOfflineChange:a,onRemoteLinkChange:o,onFailure:s});return u.updateAuth(JSON.stringify(dx(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 Sv(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 di({wasmModule:this.wasmModule,collectorUrl:t,runtimeThread:n})}textAnchors(){return vm(this.wasmModule)}mintAnonymousToken(e){return this.wasmModule.mintAnonymousToken(e.secret,e.audience,e.ttlSeconds,e.nowSeconds)}};function cx(){return typeof window<`u`&&typeof Worker<`u`}function lx(){return typeof process<`u`&&!!process.versions?.node}function ux(e){return cx()&&(e.driver?.type??`persistent`)===`persistent`}function dx(e){return{jwt_token:e.jwtToken??null,...e.cookieSession?{backend_session:e.cookieSession}:{}}}async function fx(e,t,n){let r=e.getAuthState().session,i=new ce({appId:t},gu(e),it(e));await i.init();let a=e.onAuthChanged(({session:t})=>{r=t??null,i.setSession(it(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 px(e){return(e.driver??{type:`persistent`}).type===`persistent`?fu(e):null}function mx(e){if(typeof window>`u`)return()=>{};let t=px(e.getConfig());if(!t)return()=>{};let n=window;zo(n);let r=Do(n),i={db:e,namespace:t};return r.add(i),()=>{n.__jazzWindowStorageContexts__?.delete(i)}}function hx(e){return fx(e,B(e.getConfig()),mx)}async function gx(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(Ve(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 _x=class extends sx{leasePort;inspectorPort;leaseRequested=!1;constructor(e,t){super(),this.leasePort=e,this.inspectorPort=t}wrapClientRuntime(e,t,n){return pt(e,this.inspectorPort,t.runtimeSources.inspectorBinding,n)}async acquireBrowserForegroundNodeLease(e){return this.leaseRequested=!0,xo.acquireFromPort(this.leasePort,{dbName:e.runtimeSources.inspectorHostPhysicalDbName,storageOwner:Hi(e)})}};async function vx(e,t,n,r){let i=new MessageChannel,a=new _x(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}};tx(o);let s=Wi(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:Vi(o),storageOwner:Hi(o)};return await gx(r,c,i.port2),o.runtimeSources.inspectorBinding=c,rs(o),await hx(await yd(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 yx(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 $=ot(),bx=200,xx=15e3,Sx=1e3;function Cx(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 wx(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)=>wx(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]&&wx(e[n],t[n]))}function Tx(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&&wx(r.schema,e.schema)})}var Ex=class extends F.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 Dx(){let[e,t]=(0,F.useState)(null),[n,r]=(0,F.useState)([]),[i,a]=(0,F.useState)(null),o=(0,F.useRef)(Promise.resolve()),[s,c]=(0,F.useState)(null),[l,u]=(0,F.useState)(!1),[d,f]=(0,F.useState)(null);return(0,F.useEffect)(()=>{let e=new AbortController,n=!0,i=null,o=Date.now()+xx;return(async()=>{for(;n&&Date.now()<o;){try{let s=await je({signal:e.signal,deadline:o});if(s&&s.contexts.length>0){if(!n){s.close();return}i=s,t(s),r(s.contexts),a(yx(s.contexts,ke()));return}s?.close()}catch{if(!n)return}if(!n)return;let s=o-Date.now();if(s<=0)break;await Cx(Math.min(bx,s),e.signal)}n&&u(!0)})(),()=>{n=!1,e.abort(),i?.close()}},[]),(0,F.useEffect)(()=>{if(!e)return;let t=new AbortController;return(async()=>{for(;!t.signal.aborted;){if(await Cx(Sx,t.signal),t.signal.aborted)return;try{let n=await e.listContexts();if(t.signal.aborted)return;r(e=>Tx(e,n)?e:n),a(e=>e&&n.some(t=>t.key===e)?e:yx(n,ke()))}catch{}}})(),()=>t.abort()},[e]),(0,F.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=ke(i),!r)throw Error(`Inspector host is no longer available`);return e.attach(i)}}).then(async e=>{if(!e)return;if(!a){ze(e);return}let n=await vx(r,t.appId,t.dbName,e);a?(s=n,c({client:n,schema:t.schema})):await n.shutdown()}).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)(Ox,{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 Ox({client:e,wasmSchema:t}){let n=new URLSearchParams(window.location.search).get(`route`)??`/`;return(0,$.jsx)(Ex,{children:(0,$.jsx)(tt,{client:e,children:(0,$.jsx)(xe,{wasmSchema:t,runtime:`overlay`,children:(0,$.jsx)(we,{initialEntries:[n],children:(0,$.jsx)(Ze,{})})})})})}(0,ut.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(F.StrictMode,{children:(0,$.jsx)(Dx,{})}));
|