@lunora/client 1.0.0-alpha.287 → 1.0.0-alpha.289
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/LICENSE.md +201 -104
- package/README.md +3 -3
- package/dist/admin/index.d.mts +2 -1
- package/dist/admin/index.d.ts +2 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/auth/index.d.mts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{LunoraAdminClient-BNTNmvKI.mjs → LunoraAdminClient-07hHGDCO.mjs} +1 -1
- package/dist/packem_shared/{LunoraClient-C3DtHrrg.mjs → LunoraClient-Ccy4qHHH.mjs} +1 -1
- package/dist/packem_shared/SubscriptionRegistry-_FfLskdB.mjs +1 -0
- package/dist/packem_shared/{createLocalStore-D38o4O8Z.mjs → createLocalStore-CDCtdy5O.mjs} +1 -1
- package/dist/packem_shared/{createServerClient-BVO1J9Oo.mjs → createServerClient-YR31uvMw.mjs} +1 -1
- package/dist/packem_shared/lunora-client-B8nAHjip.mjs +1 -0
- package/dist/packem_shared/{lunora-client.d-DkNQbtBO.d.ts → lunora-client.d-DKfDdnjJ.d.ts} +21 -0
- package/dist/packem_shared/{lunora-client.d-BKXjhLZZ.d.mts → lunora-client.d-Ezp1eG81.d.mts} +21 -0
- package/dist/packem_shared/{preload.d-ChTijpQB.d.mts → preload.d-qnL9TXVr.d.mts} +1 -1
- package/dist/packem_shared/{preload.d-B7ZB99ag.d.ts → preload.d-wJ_ggZsg.d.ts} +1 -1
- package/dist/pagination/index.d.mts +25 -1
- package/dist/pagination/index.d.ts +25 -1
- package/dist/pagination/index.mjs +1 -1
- package/dist/query/index.d.mts +2 -2
- package/dist/query/index.d.ts +2 -2
- package/dist/ssr/index.d.mts +2 -2
- package/dist/ssr/index.d.ts +2 -2
- package/dist/ssr/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/SubscriptionRegistry-BKgQtuh9.mjs +0 -1
- package/dist/packem_shared/lunora-client-D728AUWA.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y,OFFLINE_NOT_QUEUED_HINT as Ye}from"@lunora/errors";import{decodeWire as _,encodeWire as ce,stableWireKey as ue}from"@lunora/wire";import{t as Fe}from"./base64-849R7V-V.mjs";import{r as Xe,U as Ze,P as et}from"./delta-merge-C6OqMEPH.mjs";import tt from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as A,u as de,s as Me,a as st,i as x,r as G,e as q,b as fe,c as it,d as pe,f as rt}from"./wire-errors-BDckSTKZ.mjs";import{ClientQueryStore as nt}from"./createClientQuery-B8Nfj-7o.mjs";import{D as ot,a as at,b as ct,c as dt,d as ht,S as me,M as lt,I as ut,Q as ft,R as pt,e as ye,f as mt,g as yt}from"./client-tuning-C10B2KCO.mjs";import{j as w,d as ve,p as K,s as Se}from"./client-urls-BHLUjjcG.mjs";import{TabCoordinator as vt}from"./TabCoordinator-IUCwjnqX.mjs";import{TransportError as L,getRetryAfterMs as St,AUTH_REPLAY_ERROR_CODES as bt,isAuthReplayFailure as j}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ct,pumpSseBody as wt}from"./httpStream-DN3D9WqW.mjs";import{createLocalStore as gt}from"./createLocalStore-CDCtdy5O.mjs";import{O as Tt,n as be,i as kt}from"./offline-queue-BEqCPDmw.mjs";import{d as Et,b as ie,r as R,c as F,a as At,w as _t,e as Rt,f as It}from"./optimistic-layers-D-7D3yeJ.mjs";import{resolvePersistenceAdapter as Ot}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as H,a as Ce,b as Lt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as Pt,queryCacheKey as M}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as we}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as he,setSubscriptionAck as I,SubscriptionRegistry as g,wrapSubscriber as $,failSubscription as B,releaseSubscribeFrame as J}from"./SubscriptionRegistry-_FfLskdB.mjs";import{c as Ft,s as ge,r as Mt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as Ht}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const Te="/_lunora/rpc",z="/_lunora/rpc-batch",Y="/_lunora/ws",Oi="/_lunora/admin/shard-traffic",Ut="/_lunora/admin/scheduled",Nt="/_lunora/admin/scheduled/status",Bt="/_lunora/admin/scheduled/ws",Dt="/_lunora/admin/scheduled/cancel",ke="/_lunora/admin/scheduled/dead",Wt="/_lunora/admin/scheduled/dead/retry",Qt="/_lunora/admin/scheduled/dead/cancel",Ee="/_lunora/admin/scheduled/history",xt="/_lunora/admin/scheduled/job",qt="/_lunora/admin/scheduled/cron-runs",He="/_lunora/admin/pause",Kt="/_lunora/admin/workflows/instances",jt="/_lunora/admin/workflows/instance",Vt="/_lunora/admin/workflows/status",Gt="/_lunora/admin/workflows/create",$t="/_lunora/admin/workflows/event",Li="/_lunora/admin/storage",Pi="/_lunora/admin/storage/url",Fi="/_lunora/admin/storage/buckets",Mi="/_lunora/admin/functions",Hi="/_lunora/admin/cron-jobs",Ui="/_lunora/admin/cron-jobs/run",Ni="/_lunora/admin/architecture",Bi="/_lunora/admin/openapi",Di="/_lunora/admin/openrpc",Wi="/_lunora/admin/global/tables",Qi="/_lunora/admin/global/table",xi="/_lunora/admin/global/facet",qi="/_lunora/admin/vector/indexes",Ki="/_lunora/admin/vector/query",ji="/_lunora/admin/logs/archive",Vi="/_lunora/admin/kv/namespaces",Gi="/_lunora/admin/tokens",$i="/_lunora/admin/kv/keys",Ji="/_lunora/admin/kv/value",zi="/_lunora/admin/auth/users",Yi="/_lunora/admin/auth/sessions",Xi="/_lunora/admin/auth/users/create",Zi="/_lunora/admin/auth/users/role",er="/_lunora/admin/auth/users/ban",tr="/_lunora/admin/auth/users/unban",sr="/_lunora/admin/auth/users/password",ir="/_lunora/admin/auth/users/remove",rr="/_lunora/admin/auth/users/impersonate",nr="/_lunora/admin/auth/sessions/revoke",or="/_lunora/admin/auth/sessions/revoke-all",ar="/_lunora/admin/auth/capabilities",cr="/_lunora/admin/auth/users/update",dr="/_lunora/admin/auth/accounts",hr="/_lunora/admin/auth/accounts/unlink",lr="/_lunora/admin/auth/passkeys",ur="/_lunora/admin/auth/passkeys/delete",fr="/_lunora/admin/auth/two-factor/disable",pr="/_lunora/admin/auth/organizations",mr="/_lunora/admin/auth/organizations/members",yr="/_lunora/admin/auth/organizations/invitations",vr="/_lunora/admin/auth/organizations/members/remove",Sr="/_lunora/admin/auth/organizations/invitations/cancel",br="/_lunora/admin/auth/config",Cr="/_lunora/admin/auth/sign-up-invitations",wr="/_lunora/admin/auth/sign-up-invitations/create",gr="/_lunora/admin/auth/sign-up-invitations/revoke",Tr="/_lunora/admin/auth/organizations/create",kr="/_lunora/admin/auth/organizations/update",Er="/_lunora/admin/auth/organizations/remove",Ar="/_lunora/admin/auth/organizations/members/add",_r="/_lunora/admin/auth/organizations/members/invite",Rr="/_lunora/admin/auth/organizations/members/role",Ir="/_lunora/admin/auth/organizations/teams",Or="/_lunora/admin/auth/organizations/teams/create",Lr="/_lunora/admin/auth/organizations/teams/update",Pr="/_lunora/admin/auth/organizations/teams/remove",Fr="/_lunora/admin/auth/organizations/teams/members",Mr="/_lunora/admin/auth/organizations/teams/members/add",Hr="/_lunora/admin/auth/organizations/teams/members/remove",Ur="/_lunora/admin/auth/organizations/roles",Nr="/_lunora/admin/auth/organizations/roles/create",Br="/_lunora/admin/auth/organizations/roles/update",Dr="/_lunora/admin/auth/organizations/roles/remove",Jt="/api/auth",zt="/get-session",Yt="lunora-ping",X=500,Ue=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)};new TextDecoder;const Xt=new TextEncoder,Zt=n=>Fe(Xt.encode(n)),es=n=>Zt(JSON.stringify(n)),ts="x-lunora-expect-subject",ss=n=>es({subject:n}),is="refreshBatch",Ae=Symbol.for("lunora:session-change"),rs="lunora:session-change",ns="better-auth.message",os="signout",Ne=()=>{const n=globalThis;let e=n[Ae];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[Ae]=e),e},as=()=>"document"in globalThis,cs=async()=>{const n=[];for(const e of Ne().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},ds=(n,e)=>{if(n!==ns||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===os}catch{return!1}},hs=n=>{const e=[],t=()=>{cs().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(rs):void 0}catch{s=void 0}if(s!==void 0){const r=s;r.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==n&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=a=>{ds(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},ls=n=>{const e=Ne();return e.listeners.add(n),e.detach===void 0&&as()&&(e.detach=hs(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},_e="/_lunora/ws/reauth",us=4005,fs="identity_changed",ps="/_lunora/claims",ms="lunora",ys="lunora.bearer.",vs=n=>`${ys}${Fe(new TextEncoder().encode(n))}`,Ss=async n=>{const e=[];let t;for(;;){const s=await n(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},Be=n=>({paused:n.paused===!0,...typeof n.pausedAt=="number"?{pausedAt:n.pausedAt}:{},...typeof n.reason=="string"?{reason:n.reason}:{},supported:n.supported===!0}),Q=n=>"args"in n?{...n,args:_(n.args)}:n,Wr=async n=>(n.assertOpen(),((await n.adminFetch(Ut,"GET")).records??[]).map(t=>Q(t))),Qr=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(`${xt}?id=${encodeURIComponent(e)}`,"GET");return t.record===void 0?null:Q(t.record)},xr=async(n,e={})=>{n.assertOpen();const t=e.cursor===void 0?Ee:`${Ee}?cursor=${encodeURIComponent(e.cursor)}`,s=await n.adminFetch(t,"GET"),i=(s.records??[]).map(r=>Q(r));return s.truncated===!0&&s.cursor!==void 0?{cursor:s.cursor,records:i}:{records:i}},qr=async n=>{n.assertOpen();const e=await n.adminFetch(qt,"GET");return{inFlight:e.inFlight??[],runs:e.runs??[]}},Kr=async n=>(n.assertOpen(),Be(await n.adminFetch(He,"GET"))),jr=async(n,e,t)=>(n.assertOpen(),Be(await n.adminFetch(He,"POST",t===void 0?{paused:e}:{paused:e,reason:t}))),Vr=async n=>{n.assertOpen();const e=await n.adminFetch(Nt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Gr=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(Dt,"POST",{id:e})).cancelled===!0}),$r=async n=>(n.assertOpen(),(await Ss(async t=>await n.adminFetch(t===void 0?ke:`${ke}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>Q(t))),Jr=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(Wt,"POST",{id:e})).retried===!0}),zr=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(Qt,"POST",{id:e})).removed===!0}),Yr=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await n.adminFetch(`${Kt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},Xr=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${jt}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},Zr=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(Gt,"POST",{id:e.id,name:e.name,params:e.params}),s=t.id??e.id;if(s===void 0)throw new y("WORKFLOWS_REST_ERROR","Workflows create response carried no instance id",{status:502});return{id:s,status:t.status??"unknown"}},en=async(n,e)=>{n.assertOpen();const t=await n.adminFetch($t,"POST",{id:e.id,name:e.name,payload:e.payload,type:e.type});return{instanceId:t.instanceId??e.id,timestamp:t.timestamp}},tn=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Vt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),k=(n,e)=>{try{return ce(n)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},re=n=>{try{return ce(n),!0}catch{return!1}},De=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),bs=(n,e,t)=>{const s=Array.from({length:e}),i=r=>({error:A(Me(r),t),ok:!1});for(const r of n){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!De(r.body)){s[r.id]=i({});continue}const a=r.body;if("error"in a){s[r.id]=i(a);continue}try{s[r.id]={ok:!0,value:_(a.result)}}catch(o){s[r.id]={error:A(de(o),t),ok:!1}}}return s.map(r=>r??{error:A(new Error("batch call returned no result"),t),ok:!1})},Z=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},D=n=>n==="connected"||n==="polling",f=n=>n??"",E=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},Cs=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)E(n,t)},ws=new TextDecoder,gs=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return ws.decode(n)};class O{listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const U=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},Ts=(n,e,t)=>{U(n),!(e<=0)&&(n.heartbeatTimer=setInterval(()=>{if(!n.socket)return;const{socket:s}=n;if(Date.now()-n.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Yt)}catch{}},e))},Re=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const o=s.protocols===void 0?new i(e):new i(e,s.protocols);n.socket=o;const c=()=>{U(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},d=h=>{c(),s.onClose(h)};r>0&&(n.connectTimer=setTimeout(()=>{if(n.connectTimer=void 0,n.socket===o){try{o.close()}catch{}d()}},r)),o.addEventListener("open",()=>{if(n.socket===o){n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}n.socket===o&&Ts(n,a,d)}}),o.addEventListener("message",h=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),o.addEventListener("close",h=>{n.socket===o&&d(h)}),o.addEventListener("error",()=>{n.socket===o&&d()})},ks=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,d=!1,h=!1;const l=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},u=v=>{if(c!==void 0){if(!v){l();return}d||(d=!0,i()),s()}},p=()=>{h||(h=!0,r().then(u).finally(()=>{h=!1}).catch(()=>{}))};return{hasFailedOpen:()=>o>0,isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,l()},stop:l}},Es=1e4,Ie=async n=>H(Es,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),We=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Oe=n=>{if(n instanceof L)return!0;const e=n?.code;return e===void 0||We.has(e)||bt.has(e)},As=1e3,Qe=6e4,_s={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},W=(n,e,t)=>{const s=st(t.get("retry-after")),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${n.toString()}${e?` ${e}`:""})`,a=n<400||n>=500||n===408?new L(r,i):new y(_s[n]??"BAD_REQUEST",r,{data:i});return A(a,t)},ne=(n,e=Math.random)=>{const t=Math.min(As*2**Math.max(n-1,0),Qe);return Math.round(t*(.5+e()*.5))},Rs=n=>{const e=n?.code;return n instanceof L||e===void 0||We.has(e)},Is=(n,e,t)=>{const s=St(n);return s!==void 0&&s>0?Math.min(s,Qe):Rs(n)?ne(e,t):void 0},Os=983040,Ls=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,Ps=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&De(t.body)&&e.set(t.id,t.body);return e},Fs=(n,e)=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:A(Me(n),e),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:_(n.result)}}catch(t){return{commitCursor:n.commitCursor,error:A(de(t),e),kind:"undecodable"}}},ee=(n,e)=>`${f(n)}\0${e}`,Ms=(n,e)=>{for(const t of e)t.op==="delete"?n.delete(t.key):t.value!==void 0&&n.set(t.key,t.value)};class Hs{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Ue(this.buffers,this.maxBuffers),this.buffers.set(ee(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(ee(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:_(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const r=s.parts.get(t.shapeId)??[];for(const o of i)r.push(o);s.parts.set(t.shapeId,r),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const a=t.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(t.shapeId,a),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=ee(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const Us=(n,e,t)=>{const s=e.parts.get(n.id)??[],i=e.resets.has(n.id),r=e.bases.get(n.id),a=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,o=r!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r;if(!i&&(a||o))return n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,n.answered=!1,"reseed";i&&n.rows.clear(),Ms(n.rows,s),n.answered=!0,t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const c=e.lastMutationId.get(n.id);return c!==void 0&&(n.lastMutationId=c),"applied"},Le=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},Ns=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&he(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},oe=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},ae=(n,e=!1)=>{const t=n.serverCursor,s=n.lastMutationId;Et(()=>{for(const i of n.checkpointCallbacks)i({checkpoint:t,mutationId:s,...e&&{rowsFollow:!0}})})},xe=(n,e,t)=>{n.serverBase=e,n.serverBaseCommitted=!0,n.awaitingSnapshot=!1,n.serverClaims=t.claims,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Bs=n=>n.awaitingSnapshot===!0?void 0:n.lastValue,Ds=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&(n.serverBase!==void 0||n.serverBaseCommitted===!0)&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,Ws=n=>n.type==="delta"&&n.more===!0,V=(n,e)=>n!==void 0&&n!==e,Qs=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",le=(n,e,t,s,i=!1)=>{if(t===void 0)return!i||n.ownClaims(e,s,"")===null;const r=n.ownClaims(e,s,t);return r!==void 0&&(r===null||r===t)},xs=n=>{for(const e of n.activeSubscriptions())I(e,"idle"),e.valueReceived=!1,n.ensureSocket(e.shardKey),n.queueResubscribe(e);for(const e of n.activeShapes())e.answered=!1,n.ensureSocket(e.shardKey);for(const e of n.queuedShardKeys())n.ensureSocket(e);n.broadcastStatus(n.computeStatus(),n.identityFingerprint()),n.emitConnectionStatus()},qs=n=>{n.closeConnections();const e=n.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of n.activeSubscriptions())I(t,"idle"),t.valueReceived=!1;for(const t of n.activeShapes())t.answered=!1;n.emitConnectionStatus()},Ks=(n,e,t)=>{if(V(t,n.identityFingerprint()))return;const s=n.leader,i=Qs(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&(n.awaitLeaderAnswers(),n.flushOfflineQueues())},js=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},qe=(n,e,t,s,i,r,a)=>{if(V(r,n.identityFingerprint())||!le(n,e,a,()=>{qe(n,e,t,s,i,r,a)},t!==void 0))return;const o=n.subscription(e);if(!o)return;n.dropCacheSeed(e);const c=!o.valueReceived;o.valueReceived=!0,xe(o,t,s===void 0?{claims:a}:{claims:a,cursor:s,epoch:i}),s!==void 0&&ie(o,s),R(o,t),c&&n.emitConnectionStatus(),n.settleAwaitedAnswer(o,!0)},Ke=(n,e,t,s,i)=>{if(V(s,n.identityFingerprint())||!le(n,`error:${e}`,i,()=>{Ke(n,e,t,s,i)}))return;const r=n.subscription(e);if(r){const a=!r.valueReceived;r.valueReceived=!0,he(r.errorCallbacks,t),a&&n.emitConnectionStatus(),n.settleAwaitedAnswer(r,!1)}},je=(n,e,t,s,i,r,a,o)=>{if(V(a,n.identityFingerprint()))return;const c=n.subscription(e);c&&le(n,`settled:${e}`,o,()=>{je(n,e,t,s,i,r,a,o)})&&(n.ackAndAdvanceCursor(c,t,s),i!==void 0&&r===n.clientIdentifier()&&oe(c,i),ae(c))},Vs=(n,e,t)=>n!==null||e&&t===null,Gs=n=>n.sensitive===!0,$s=(n,e)=>{if(!Gs(n))return e;if(e.onlineOnly===!1)throw new y("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},Js=[et,is],zs=n=>n.type==="data"||n.type==="delta"||n.type==="settled"||n.type==="resume"||n.type==="error"&&typeof n.id=="string",Ys=100,Ve=1e4,Xs=5,Zs=500,ei=1e4,ti=(n,e)=>{let t;const s=new Promise((r,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>n())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},si=(n,e)=>{const t=[n===void 0?"":`shard=${encodeURIComponent(n)}`,e===void 0?"":`token=${encodeURIComponent(e)}`].filter(Boolean).join("&");return t===""?_e:`${_e}?${t}`},te=async n=>typeof n=="function"?await n():n,se=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Ve);try{const a=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return{status:a.status,text:await a.text()}}finally{clearTimeout(r)}},Pe=(n,e)=>new y("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Ye}),ii=(n,e)=>n instanceof TypeError&&re(e),ri=()=>globalThis.navigator?.onLine===!1,ni=(n,e,t,s)=>e||n===!0&&t&&!s,oi=Promise.resolve(),ai=async(n,e,t)=>{let s,i;const r=new AbortController,a=()=>{r.abort(e?.reason)};e?.addEventListener("abort",a,{once:!0});try{await wt(n,{complete:o=>{e?.aborted!==!0&&(s=o)},fail:o=>{i=o},push:o=>{e?.aborted!==!0&&t?.(o)}},{},r)}finally{e?.removeEventListener("abort",a)}if(e?.aborted===!0)throw e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError");return{failure:i,terminal:s}};class Ge{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;ownClaimsValue;heldLeaderFrames=new Map;ownClaimsFetch;claimsVerifiedAgainst=new Set;ownClaimsRetryTimer;ownClaimsFailures=0;suspendedFollowerValues=new Map;frameClaims;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;queryCacheEpoch=0;queryCacheChain=Promise.resolve();hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new O;statusListeners=new O;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new O;identityChangeListeners=new O;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new O;pendingChangeListeners=new O;syncStatusListeners=new O;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Hs(Ge.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(ve(e.url),Y),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??Jt;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??tt(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ot,this.connectTimeoutMs=e.connectTimeoutMs??at,this.rpcTimeoutMs=e.rpcTimeoutMs??ct,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??dt,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??ht,this.defaultConnectionContext=e.connectionContext,this.persistence=Ot(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Pt(e.queryCache),this.clientQueryStore=new nt,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=oi),this.offlineQueue=new Tt(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${be()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=ls(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e;s&&this.resetOwnClaims();const i=this.identityFingerprint(),r=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,s&&(this.tokenFingerprint=void 0),this.applySubject(e,t);const d=this.identityFingerprint(),h=!s&&e!==null&&r,l=!s&&e===null&&i===null&&r&&!o,u=d!==i;let p=!1;u&&(h?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):p=this.retirePreviousIdentity(i,o,c,e)),p||this.applyUpgradeBearer(this.reconcileUpgradeBearer(c,e,u)),u&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&D(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:l=>{o=l}})}catch(l){if(!x(l))throw l;d=l}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(r)??0)){let l=this.clientWatermarks.get(a??"");l===void 0&&(Ue(this.clientWatermarks,yt),l=new Map,this.clientWatermarks.set(a??"",l)),l.set(r,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const i=await this.fetchImpl(w(this.url,`${this.authBasePath}${zt}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,a,s),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=f(t.shardKey),i={context:e},r=this.connectionContextHolders.get(s);r?r.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;const o=this.connectionContextHolders.get(s);if(!o)return;const c=o.indexOf(i);c!==-1&&o.splice(c,1),o.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=f(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let a=r.get(e);const o=a===void 0;if(a||(a=new Set,r.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const h=this.getConnection(s.shardKey);h&&E(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:r,topic:a}=e;if(a.length===0)throw new y("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=f(i),d=`/live/${r}/control`;let l=this.whisperSubscribe(a,()=>{},{shardKey:i});const u=()=>{const S=l;l=void 0,S?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:u,stream:r,topic:a});const v=this.getConnection(i)?.connectionId;v!==void 0&&this.grantWhenJoined(i,o,v);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),b=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const C=this.getConnection(i)?.connectionId;b&&C!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:C,stream:r,subscriptionId:o,topic:a}),u()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,k(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,r=this.whisperSubscribe(i,u=>{t.onMessage(u)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},h=f(s.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(c),r()},send:u=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=k(u,`room message for '${i}'`),v=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,v,s)?!0:o.length>=Ys?!1:(o.push(v),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let r;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:()=>{clearTimeout(r),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(_(c.data))}))},onOpen:()=>{clearTimeout(r);const o=a.socket();r=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},me),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(k(o,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const r of this.subscriptions.all())(t||this.connectionGateState(r.shardKey).polling?r.valueReceived:r.ack==="acked")||(s+=1);for(const r of this.shapeSubscriptions.values())r.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:D(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const r of s){const a=this.connections.get(r);e.push({confirmedMutationWatermark:t?.get(r)??0,hasSocket:a?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(r=>({acked:r.ack==="acked",functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())i.push({acked:r.answered,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((r,a)=>(r.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((r,a)=>r.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){const{WebSocketImpl:e}=this;if(e===void 0)return;const t=a=>a.protocol==="wss:"||a.protocol==="https:",s=K(this.wsUrl),i=a=>{const o=K(String(a));return o.host===s.host&&t(o)===t(s)},r=e;return new Proxy(e,{construct:(a,[o,c,...d])=>new r(o,c??(i(o)?this.upgradeProtocols():void 0),...d)})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){const t=this.getConnection(e.shardKey);return t===void 0||t.wsState==="open"?!0:t.polling.isPolling()||!t.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Ft(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Ce(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ue(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=M(e,t,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return this.cachedQueryMatchesIdentity(r)?r.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=g.key(e,t,s),r=this.subscriptions.get(i);return{answered:r!==void 0&&(r.lastValue!==void 0||r.ack==="acked"||r.valueReceived),present:r!==void 0,value:r?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return H(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw Lt(s.signal);const{value:i}=await Ce(this.runMutation(e,t,s),s.signal);return i}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(h=>({rows:h})),a=t.length;let o=0,c=0,d=0;for(let h=0;h<a;h+=i){const l=t.slice(h,h+i),u=d,{committed:p}=await this.runMutation(e,r(l),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey});d+=1,o+=l.length,p&&(c+=l.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(w(ve(this.url),Bt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(r=>Q(r))))}});return t.close}resnapshot(e,t,s={}){this.assertOpen();const i=this.subscriptions.get(g.key(e.__lunoraRef,t??{},s.shardKey));i!==void 0&&this.resnapshotSubscription(i)&&(i.awaitingSnapshot=!0)}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=g.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=$(s),d=$(i.onError),h=$(i.onCheckpoint);if(!o){this.nextSubId+=1;const m=`sub_${this.nextSubId.toString()}`,S=ue(r),b=this.takeHydratedCache(e.__lunoraRef,S,i.shardKey);o={ack:"idle",args:r,argsKey:S,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:b?.value,optimisticLayers:[],serverBase:b?.value,serverCursor:b?.serverCursor,serverClaims:b?.claims,shardKey:i.shardKey,valueReceived:!1,wireArgs:k(r,`args for '${e.__lunoraRef}'`),...b?.serverEpoch===void 0?{}:{serverEpoch:b.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&D(this.computeStatus())&&this.awaitLeaderAnswer(o),b!==void 0&&this.cacheSeededQueries.set(a,b)}o.callbacks.add(c),d&&o.errorCallbacks.add(d),h&&o.checkpointCallbacks.add(h);const l=Bs(o);if(l!==void 0)try{c(l)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const u=o;let p=!1;const v=()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",v),u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0)){this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(g.keyOf(u)),this.subscriptions.remove(u);const m=this.getConnection(u.shardKey);m&&this.settleSubscribeWatchdog(m,u.id),this.releaseIdleShard(u.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(u,!0)}};return i.signal?.addEventListener("abort",v,{once:!0}),i.signal?.aborted&&v(),v}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,r={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:k(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,r),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,a=t??{},{handle:o,iterable:c}=Ht({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const d=this.getConnection(r),h={id:i,query:{args:k(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:h,shardKey:r};this.streams.set(i,l);const u=d?.wsState==="open"&&E(d,h);if(!u&&d===void 0)return this.forgetStream(i),o.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!u){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=lt;){const v=d.pendingStreams.shift()?.id,m=v?this.streams.get(v):void 0;m&&(m.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(v))}d.pendingStreams.push(h)}return c}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Ct(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}async streamRpc(e,t={},s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const i=e.__lunoraRef,r=await this.fetchImpl(w(this.url,Te),{body:JSON.stringify({args:k(t,`args for '${i}'`),functionPath:i,shardKey:s.shardKey}),headers:{accept:"text/event-stream",...this.rpcRequestHeaders({},s.shardKey)},method:"POST",...s.signal?{signal:s.signal}:{}});if(!r.ok){const h=await r.json().catch(()=>{});if(h?.error)throw G(h.error);const l=r.statusText?` ${r.statusText}`:"";throw new y("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${l})`)}if(!r.body)throw new y("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");const{failure:a,terminal:o}=await ai(r.body,s.signal,s.onFrame);if(a!==void 0)throw a;if(o===void 0)throw new y("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let c;try{c=JSON.parse(o)}catch{throw new y("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof c!="object"||c===null||!("result"in c))throw new y("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return _(c.result)}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.stopOwnClaimsRetry(),this.suspendedFollowerValues.clear();for(const e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,t,s,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),Vs(e,t,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,t,s){return!this.authTokenOnUpgrade||t===null||e===t?"none":s?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[ms,vs(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),clearTimeout(e.revalidateTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0,e.revalidateTimer=void 0}shardInUse(e){const t=s=>f(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=f(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},ut))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=f(e.shardKey);for(const[i,r]of this.streams)f(r.shardKey)===t&&(r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,U(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),awaitLeaderAnswers:()=>{this.awaitLeaderAnswers()},broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,ownClaims:(s,i,r)=>this.followerClaims(s,i,r),queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,r)=>{this.ackAndAdvanceCursor(s,i,r)},settleAwaitedAnswer:(s,i)=>{this.settleAwaitedAnswer(s,i)},subscription:s=>this.subscriptions.get(s)};return new vt({channelName:e,onBecomeLeader:()=>{xs(t)},onStopBeingLeader:()=>{qs(t)},onConnectionStatus:(s,i)=>{Ks(t,s,i)},onSubscriptionData:(s,i,r,a,o,c)=>{qe(t,s,i,r,a,o,c)},onLeaderClaimAnswered:()=>{js(t)},onSubscriptionError:(s,i,r,a)=>{Ke(t,s,i,r,a)},onSubscriptionSettled:(s,i,r,a,o,c,d)=>{je(t,s,i,r,a,o,c,d)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,z),{body:JSON.stringify({calls:e.map((o,c)=>({args:k(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw A(new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=q(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?A(G(a),s.headers):A(new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`),s.headers);for(const o of r.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return bs(r.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=$s(e,s),r=t,a=i.mutationId??be();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,l,h);const u=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));u!==void 0&&await u;const{httpFirst:p,midReconnect:v,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),b=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),C=async(T=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,d,a,l,h,T?void 0:i.precondition,i.mutationId,c?.stamp,T,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),S||v||b)return C();let N;try{const T=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:d,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:P=>{N=P}});for(const P of h)P(N);return{committed:!0,value:T}}catch(T){const P=ii(T,r),$e=p&&m&&P,Je=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(T instanceof TypeError||T instanceof L)&&re(r)){const ze=C(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),ze}throw this.settleFailedDirectWrite(T,N,h,l,c?.flags.authToken),ni(i.onlineOnly,$e,P,Je)?Pe(e.__lunoraRef,T):T}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw F(s),Pe(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:r,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=r||o,d=this.WebSocketImpl!==void 0&&c,h=i||s;return{httpFirst:h,midReconnect:a==="connecting"&&c&&!h,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!h,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),x(e)){for(const a of s)a(t);return}F(i)}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,d,h,l,u){const p=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{F(a)}},shardKey:s})}catch(S){throw F(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const b={ambiguousSend:l,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:u,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:C=>{for(const N of o)N(C)},reject:C=>{this.queuedIdentities.delete(r),x(C)||F(a),S(C instanceof Error?C:new Error(String(C))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),b.id!==void 0&&this.queuedIdentities.set(b.id,p)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=f(e);return this.offlineQueue.hasPending(s=>f(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=this.queryCacheEpoch,t=await this.queryCache.load();if(e!==this.queryCacheEpoch)return;const s=new Map;for(const i of this.subscriptions.all())s.set(M(i.fn.__lunoraRef,i.argsKey,i.shardKey),i);for(const{key:i,...r}of t){if(kt(this.persistenceVersion,r.version)){this.queryCache.remove(i).catch(()=>{});continue}const a=s.get(i);if(a&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(a,r);continue}this.hydratedQueryCache.set(i,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,e.serverClaims=t.claims,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(M(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),R(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverBaseCommitted=!1,s.serverCursor=void 0,s.serverEpoch=void 0,R(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=M(e,t,s),r=this.hydratedQueryCache.get(i);if(!(r===void 0||!this.cachedQueryMatchesIdentity(r)))return this.hydratedQueryCache.delete(i),r}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=M(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=M(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,r=i===void 0?this.identityFingerprint():i;r===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverClaims===void 0?{}:{claims:e.serverClaims},...r===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},ft))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()],{queryCacheEpoch:s}=this;this.pendingCacheWrites.clear();const i=this.queryCacheChain.then(async()=>s===this.queryCacheEpoch?Promise.allSettled(t.map(async([r,a])=>e.put(r,a))):void 0);this.queryCacheChain=i.catch(()=>{}),await i}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=f(e);let s;for(const i of this.subscriptions.all())f(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=f(e),s=[];for(const o of this.subscriptions.all())f(o.shardKey)===t&&(re(o.args)?s.push(o):(this.markQueryRejected(o,!0),B(o,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=It(),r=this.identityFingerprint();let a;try{a=await Ie(async o=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),o))}catch(o){return!(o instanceof TypeError)}if(this.identityFingerprint()!==r)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){this.markQueryRejected(c,!0),B(c,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:ce(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Ie(async t=>e(w(this.url,z),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const r=[],a=[];if(!i)return{confirms:r,rollbacks:a};const o=g.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=At(c,i);d&&(r.push(d.confirm),a.push(d.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r){e&&this.applyOptimisticUpdate(e,t,s,i,r)}applyOptimisticUpdate(e,t,s,i,r){const{confirms:a,rollbacks:o,store:c}=gt(this.subscriptions,s);try{e(c,t)}catch{F(o);return}i.push(...o),r.push(...a)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!E(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(f(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:ks({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:we(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=we(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,a=!1;const o=()=>{a||this.closed||(r=setTimeout(u,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||Re(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:S=>{S?.code===4001&&this.notifyTokenExpired(),o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen},...t.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})};let d=0,h;const l=async m=>{const S=this.wsCredentialGeneration;d+=1;const b=d;let C;h=S;try{C=await ti(m,ei)}catch{b===d&&(h=void 0,o());return}if(b===d){if(h=void 0,S!==this.wsCredentialGeneration){u();return}c(C)}},u=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}c(m)};u();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),U(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const v=()=>{const{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,u());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),U(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(v),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(v)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=K(this.wsUrl),s=t.pathname.endsWith(Y)?t.pathname.slice(0,-Y.length):t.pathname;return t.pathname=w(s,e),Se(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=K(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const r=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!r.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),Se(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[ts]=ss(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const r=e.authToken===void 0?this.authToken:e.authToken;if(r&&(s.authorization=`Bearer ${r}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const a=this.bookmark.get();a&&(s["x-d1-bookmark"]=a)}return s}async rpc(e,t,s,i={}){const{fetchImpl:r}=this;if(!r)throw new L("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:k(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:h}=await H(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const v=await r(w(this.url,Te),{body:c,headers:a,method:"POST",signal:p});try{return{body:await v.json(),response:v}}catch{return{body:void 0,response:v}}});if(i.captureBookmark){const p=h.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw W(h.status,h.statusText,h.headers);const l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw W(h.status,h.statusText,h.headers);const u=q(d);if(u!==void 0)throw fe(u,h.headers);if(!h.ok)throw W(h.status,h.statusText,h.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(h,s),this.recordShardCursor(s,d.commitCursor);try{return _(d.result)}catch(p){throw A(de(p),h.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(r["content-type"]=i)):(o=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:o,headers:r,method:t});let d;try{d=await c.json()}catch{const l=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${l})`)}const h=q(d);if(h!==void 0)throw G({...h,message:h.message??"admin request failed"});if(!c.ok){const l=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${l})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(f(e.shardKey));E(e,{caps:Js,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let r;e.providerAttempt=i;try{r=await H(this.connectTimeoutMs,void 0,async()=>({session:await te(this.wsToken),ticket:await te(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,r)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),e.ticketed=s.ticket!==void 0,e.upgradeBearer=this.authTokenOnUpgrade?this.authToken??void 0:void 0,s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Re(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),r?.code===us&&r.reason===fs?e.retired!==!0&&!this.closed&&this.retireChangedClaims():r?.code===4001?this.notifyTokenExpired():r?.code===4003&&r.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.reauthPending=!1,e.claims=void 0,e.heldFrames=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},me),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())f(o.shardKey)===f(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:d}of o)E(e,{id:c,type:d});this.releaseIdleShard(t)}Cs(e);const r=f(t),a=this.whisperHandlers.get(r);if(this.dropWhisperJoinWaiters(r),this.whisperJoins.set(r,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,r,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})},protocols:this.upgradeProtocols()})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),E(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),U(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(f(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(f(r.shardKey)!==f(e.shardKey)||t.has(i))){if(r.durable){const a={...r.message,...r.generation===void 0?{}:{generation:r.generation},sinceChunk:r.lastSeq};r.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e,t=!1){const s=f(e);for(const i of this.subscriptions.all())f(i.shardKey)===s&&(I(i,"idle"),i.pendingDeltaRun=void 0,t&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(const i of this.shapeSubscriptions.values())f(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<pt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.ack==="acked"||!t&&e.ack==="inflight")return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,r=E(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverClaims!==void 0?{sinceClaims:e.serverClaims}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return r&&I(e,"inflight"),r&&!t&&this.armUnackedWatchdog(s,e),r}armUnackedWatchdog(e,t,s=!1){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{if(s){e.unackedWatchdogs.delete(t.id),J(t),this.settleAwaitedAnswer(t,!1);return}const i=t.ack!=="acked"&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0);this.settleSubscribeWatchdog(e,t.id),i?this.armUnackedWatchdog(e,t,!0):J(t)},ye))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&E(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverCursor===void 0||e.serverClaims===void 0?{}:{sinceClaims:e.serverClaims},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=gs(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}const r=this.getConnection(t);if(i.type!=="error"&&r?.reconnect.reset(),r&&typeof i.id=="string"&&this.settleSubscribeWatchdog(r,i.id),i.type==="batchStart")r&&(r.heldFrames=[]);else if(i.type==="batchEnd"){const a=r?.heldFrames;if(r&&a){const{socket:o}=r;r.heldFrames=void 0,_t(()=>{for(const c of a){if(r.retired===!0||r.socket!==o)break;this.dispatchServerMessage(c,t)}},()=>!this.closed)}}else r?.heldFrames&&zs(i)?r.heldFrames.push(i):this.dispatchServerMessage(i,t)}dispatchServerMessage(e,t){switch(e.type){case"ack":{const s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,void 0,void 0);return}case"chunk":{const{data:s,generation:i,id:r,seq:a}=e,o=this.streams.get(r);o&&typeof a=="number"&&(o.lastSeq=a,typeof i=="number"&&(o.generation=i),o.durable=!0),o?.handle.push(_(s));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.withFrameClaims(t,()=>{this.handleDataMessage(e)});return}case"error":{this.handleErrorMessage(e,t);break}case"identity":{this.handleIdentityFrame(e,t),this.adoptSocketConnectionId(e,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(e,t);break}case"pokeEnd":{this.withFrameClaims(t,()=>{this.handlePokeEnd(e,t)});break}case"pokePart":{this.pokeAssembler.part(t,e);break}case"pokeStart":{this.pokeAssembler.start(t,e);break}case"resume":{this.withFrameClaims(t,()=>{this.handleResumeMessage(e)});break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),e.topic);break}}}handleErrorMessage(e,t){const s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;const{id:i}=e,r=i===void 0?void 0:this.streams.get(i);if(r&&i!==void 0){r.handle.fail(it(e)),this.forgetStream(i);return}const a=i===void 0?void 0:this.subscriptions.getById(i);if(a){J(a);const c=pe(e),d=this.identityFingerprint(),h=g.keyOf(a),l=this.getConnection(t)?.claims;this.markQueryRejected(a),B(a,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,c,d,l);return}const o=i===void 0?void 0:this.shapeSubscriptions.get(i);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),he(o.errorCallbacks,pe(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(t?e.valueReceived:e.ack==="acked")&&(t?e.valueReceived=!0:I(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Ns(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const r=this.shapeSubscriptions.get(i);r&&!s.undecodable.has(i)&&this.applyPokePart(r,s,e)}}}applyPokePart(e,t,s){const i=e.answered,r=Us(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Le(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.serverClaims=this.frameClaims,e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){return I(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&Ds(i,e))return;let r;const a=i.pendingDeltaRun;try{r=Xe(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,B(i,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${c instanceof Error?c.message:String(c)}`}),this.settleAwaitedAnswer(i,!1);return}if(r===Ze){console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.resnapshotSubscription(i);return}if(Ws(e)){i.pendingDeltaRun={payload:r};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(g.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(xe(i,r,{claims:this.frameClaims,cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(oe(i,e.lastMutationId),ae(i,!0)),this.persistQueryValue(i),ie(i,i.serverCursor),t!==void 0&&Rt(i,t),R(i,r),this.tabCoordinator?.isLeader()){const c=g.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,r,i.serverCursor,i.serverEpoch,this.identityFingerprint(),i.serverClaims)}this.settleAwaitedAnswer(i,!0)}followerClaims(e,t,s){if(this.identityFingerprint()===null&&!this.identityUnresolved())return null;if(s==="")return(this.ownClaimsValue===void 0||this.ownClaimsValue!==null&&!this.claimsVerifiedAgainst.has(""))&&(this.claimsVerifiedAgainst.add(""),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims()),this.ownClaimsValue;if(this.ownClaimsValue===void 0)this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();else if(s!==void 0&&s!==this.ownClaimsValue&&!this.claimsVerifiedAgainst.has(s)){this.claimsVerifiedAgainst.add(s),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();return}return this.ownClaimsValue}isFollowerTab(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}resetOwnClaims(){this.ownClaimsValue=void 0,this.ownClaimsFetch=void 0,this.claimsVerifiedAgainst.clear(),this.stopOwnClaimsRetry(),this.suspendFollowerValues(),this.heldLeaderFrames.size>0&&queueMicrotask(()=>{this.fetchOwnClaims()})}suspendFollowerValues(){if(this.isFollowerTab())for(const e of this.subscriptions.all())e.serverClaims!==void 0&&e.serverBase!==void 0&&this.suspendedFollowerValues.set(e,{base:e.serverBase,claims:e.serverClaims,cursor:e.serverCursor,epoch:e.serverEpoch}),e.serverClaims!==void 0&&(e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverClaims=void 0,R(e,void 0))}applyOwnClaims(e){e!==this.ownClaimsValue&&this.claimsVerifiedAgainst.clear(),this.ownClaimsValue=e,this.ownClaimsFailures=0;for(const[t,s]of this.suspendedFollowerValues)s.claims===e&&t.serverBase===void 0&&(t.serverBase=s.base,t.serverCursor=s.cursor,t.serverEpoch=s.epoch,t.serverClaims=e,R(t,s.base));this.suspendedFollowerValues.clear();for(const t of this.subscriptions.all())t.serverClaims!==void 0&&t.serverClaims!==e&&(t.serverBase=void 0,t.serverBaseCommitted=!1,t.serverCursor=void 0,t.serverClaims=void 0,R(t,void 0));this.dropClaimedEntries(e),this.releaseHeldFrames()}releaseHeldFrames(){const e=[...this.heldLeaderFrames.values()];this.heldLeaderFrames.clear();for(const t of e)t()}dropClaimedEntries(e){for(const t of[this.hydratedQueryCache,this.cacheSeededQueries])for(const[s,i]of t)if(i.claims!==void 0&&i.claims!==e){t.delete(s),this.pendingCacheWrites.delete(s);const{queryCache:r}=this;r&&(this.queryCacheChain=this.queryCacheChain.then(async()=>r.remove(s)).catch(()=>{}))}}fetchOwnClaims(){const{authToken:e,fetchImpl:t}=this;if(t===void 0||this.ownClaimsFetch!==void 0)return;const s=se(t,w(this.url,ps),"{}",e===null||!this.authTokenOnUpgrade?{"content-type":"application/json"}:{authorization:`Bearer ${e}`,"content-type":"application/json"}).then(({status:i,text:r})=>{const{claims:a}=JSON.parse(r);this.ownClaimsFetch===s&&(typeof a=="string"?this.applyOwnClaims(a):i===200&&(this.ownClaimsValue=null,this.releaseHeldFrames()))}).catch(()=>{this.ownClaimsFetch===s&&this.scheduleOwnClaimsRetry()}).finally(()=>{this.ownClaimsFetch===s&&(this.ownClaimsFetch=void 0)});this.ownClaimsFetch=s}scheduleOwnClaimsRetry(){if(this.closed||this.heldLeaderFrames.size===0||this.ownClaimsRetryTimer!==void 0||this.ownClaimsFailures>=Xs)return;const e=Zs*2**this.ownClaimsFailures;this.ownClaimsFailures+=1,this.ownClaimsRetryTimer=setTimeout(()=>{this.ownClaimsRetryTimer=void 0,this.fetchOwnClaims()},e)}stopOwnClaimsRetry(){clearTimeout(this.ownClaimsRetryTimer),this.ownClaimsRetryTimer=void 0,this.ownClaimsFailures=0}withFrameClaims(e,t){this.frameClaims=this.getConnection(e)?.claims;try{t()}finally{this.frameClaims=void 0}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,t.serverClaims=this.frameClaims,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(g.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint(),t.serverClaims),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&oe(t,e.lastMutationId),ae(t),this.tabCoordinator?.isLeader())){const s=g.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint(),t.serverClaims)}}ackAndAdvanceCursor(e,t,s){const i=e.ack!=="acked";I(e,"acked"),i&&this.emitSyncStatus(),(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),ie(e,e.serverCursor)&&R(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(s===void 0||typeof e.connectionId!="string")return;const i=s.connectionId===e.connectionId;s.connectionId=e.connectionId,s.claims=e.claims,s.whisperAck=e.whisperAck===!0,(!i||s.revalidateTimer===void 0&&s.reauthPending!==!0)&&this.armSocketRevalidation(s,e.revalidateMs);for(const r of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,r,e.connectionId)}grantWhenJoined(e,t,s){const i=f(e),r=this.liveSocketGrants.get(i)?.get(t);if(r===void 0)return;const{stream:a,topic:o}=r,c=()=>{this.liveSocketGrants.get(i)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:s,stream:a,subscriptionId:t,topic:o},h=>{this.refuseLiveGrant(e,t,h,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,E(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const r of i.waiters.splice(0))clearTimeout(r.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const r={run:s,timer:void 0};r.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==r),s()},Ve),i.waiters.push(r)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const r=f(e),a=this.liveSocketGrants.get(r),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(r),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:r}=this;if(!r)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>se(r,w(this.url,e),a,o)).then(({status:c})=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(f(t));if(!s)return;const i=_(e.data);for(const r of s.values())if(!(r.stream!==e.stream||r.topic!==e.topic))try{r.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const i=_(e.data);for(const r of s)try{r(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(I(s,"idle"),this.emitSyncStatus(),B(s,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const r=e.charCodeAt(i);t^=r,t=Math.imul(t,16777619),s=Math.imul(s,33)+r}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()||e.claims!==void 0&&e.claims!==this.ownClaimsValue&&(this.ownClaimsValue!==void 0||this.isFollowerTab())?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&D(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),r=i!==void 0&&E(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),r}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(f(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const r=new Error("offline mutation discarded: auth identity changed before replay");r.code="OFFLINE_IDENTITY_CHANGED",i.reject(r),this.emitItemSettled(i,"rejected",r)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const r=t??"",a=this.clientWatermarks.get(r);if(a===void 0)this.clientWatermarks.set(r,i);else for(const[o,c]of i)a.set(o,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCacheEpoch+=1;const{queryCache:e}=this;e&&(this.queryCacheChain=this.queryCacheChain.then(async()=>e.clear()).catch(()=>{}))}evictPreviousIdentitySession(){this.resetOwnClaims(),this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}reconnectCold(){for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,I(e,"idle"),e.valueReceived=!1,R(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Le(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){const{authToken:t,fetchImpl:s}=this;for(const i of this.connections.values()){const{connectionId:r}=i;e&&t!==null&&s!==void 0&&i.socket!==void 0&&r!==void 0&&i.retired!==!0?this.reauthenticateShardSocket(i,r,t):this.bounceShardSocket(i)}for(const i of this.supplementaryBounces)i()}retireChangedClaims(){if(this.clearQueryCacheForIdentityChange(),this.evictPreviousIdentitySession(),this.tabCoordinator?.isLeader())for(const e of this.subscriptions.all())this.tabCoordinator.broadcastSubscriptionData(g.keyOf(e),void 0,void 0,void 0,this.identityFingerprint())}reauthenticateShardSocket(e,t,s){const{authToken:i,fetchImpl:r}=this,{socket:a}=e;if(r===void 0)return;const o=(e.reauthAttempt??0)+1;clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.reauthAttempt=o,e.reauthPending=!0,(e.ticketed===!0?H(this.connectTimeoutMs,void 0,async()=>te(this.wsTicket),()=>new Error("LunoraClient: ws ticket provider timed out")).catch(()=>{}):Promise.resolve(void 0)).then(async c=>se(r,w(this.url,si(e.shardKey,c)),JSON.stringify({connectionId:t}),s===null?{"content-type":"application/json"}:{authorization:`Bearer ${s}`,"content-type":"application/json"})).then(({text:c})=>{const d=JSON.parse(c);return d?.ok===!0?"ok":d?.error?.code==="IDENTITY_CHANGED"?"changed":"refused"}).catch(()=>"refused").then(c=>{e.reauthAttempt===o&&(e.reauthPending=!1,!(this.closed||s!==null&&this.authToken!==i||e.connectionId!==t||e.socket!==a||e.retired===!0)&&(c==="ok"?(e.upgradeBearer=s??e.upgradeBearer,this.armSocketRevalidation(e,e.revalidateMs)):c==="changed"?this.retireChangedClaims():this.bounceShardSocket(e)))}).catch(()=>{})}armSocketRevalidation(e,t){clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.revalidateMs=typeof t=="number"&&t>0?t:void 0,e.revalidateMs!==void 0&&(e.revalidateTimer=setTimeout(()=>{e.revalidateTimer=void 0;const s=e.upgradeBearer??(e.sessionToken===void 0?null:this.authToken??void 0);s!==void 0&&e.connectionId!==void 0&&e.socket!==void 0&&e.retired!==!0&&this.reauthenticateShardSocket(e,e.connectionId,s)},e.revalidateMs/2))}bounceShardSocket(e){if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:r}=this;try{await this.drainOfflineQueue(e,r)}catch{}!this.closed&&this.authToken!==r&&this.offlineQueue.size>0&&D(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}snapshotAnswer(e){const t=ge(e),s=t&&this.subscriptions.get(g.key(t.functionPath,t.args,t.shardKey));if(s!==void 0)return this.awaitingAnswer.has(s)?"awaiting":this.answeredUnreadable.has(s)?"unreadable":void 0}holdWhileUnanswered(e){const t=ge(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return Mt(s,t),s}awaitLeaderAnswers(){for(const e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*ye))}settleAwaitedAnswer(e,t){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),t&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(t||this.answeredUnreadable.add(e),this.answerHeldShards.delete(f(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,t){const s=t.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return s===-1?t:(this.offlineQueue.requeue(t.slice(s)),this.answerHeldShards.add(e),t.slice(0,s))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}const i=f(e),r=this.holdUndecidedWrites(i,this.offlineQueue.drain(h=>f(h.shardKey)===i));if(r.length===0)return;const a=[],o=[];for(const h of r){const l=this.replayGateVerdict(h);l==="send"?a.push(h):l==="hold"&&o.push(h)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let h=0;h<c.length;h+=X){const l=c.slice(h,h+X),u=await this.replayBatched(l,e,t);if(d.push(...u.requeue),u.stop||u.requeue.length>0){d.push(...c.slice(h+X));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=f(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,ne(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=Is(t,a)??(s===null&&j(t)?ne(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?r?.delayMs:Math.max(r?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=f(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const r=this.replayRetryTimers.get(t);r!==void 0&&clearTimeout(r),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{k(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Oe(e)}noteReplayAuthRefusal(e,t){if(!j(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...Z(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||j(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||(t instanceof TypeError||t instanceof L)&&ri()||!Oe(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=mt}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let a;try{const o=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...Z(r.identity,s),mutationId:r.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(r,o,a)}catch(o){if(x(o)){this.settleReplayUndecodable(r,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(r,o)){this.settleReplayTerminal(r,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,h)=>({args:k(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ls(i)>Os)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await H(this.rpcTimeoutMs,void 0,async d=>{const h=await r(w(this.url,z),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Z(e.find(l=>l.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);if(!o)return this.settleWholeBatchError(e,W(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=q(o),h=d===void 0?W(a.status,a.statusText,a.headers):fe(d,a.headers);return this.settleWholeBatchError(e,h,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof L||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const r of e)this.settleReplayTerminal(r,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),r=await this.replayBatched(e.slice(0,i),t,s);if(r.stop||r.requeue.length>0)return{requeue:[...r.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...r.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i,r){const a=Ps(t),o=[];let c=!1,d=!1;for(const[h,l]of e.entries()){const u=Fs(a.get(h),r);switch(u.kind){case"committed":{c=!0,this.settleReplaySuccess(l,u.value,u.commitCursor);break}case"errored":{d||=j(u.error),this.shouldRequeueReplayFailure(u.error,i)&&!this.spendsLastReplayAttempt(l,u.error)?(this.noteReplayRetryDelay(s,u.error,i),o.push(l)):this.settleReplayTerminal(l,u.error);break}case"unanswered":{const p=A(rt(),r);if(this.spendsLastReplayAttempt(l,p)){this.settleReplayTerminal(l,p);break}this.noteReplayRetryDelay(s,p,i),o.push(l);break}default:c=!0,this.settleReplayUndecodable(l,u.error,u.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{fr as $,Gi as A,en as B,Hi as C,tn as D,zi as E,Mi as F,Wi as G,Xi as H,Zi as I,er as J,Vi as K,Ge as L,tr as M,sr as N,Bi as O,ir as P,rr as Q,nr as R,Oi as S,or as T,ar as U,qi as V,cr as W,dr as X,hr as Y,lr as Z,ur as _,Ui as a,pr as a0,mr as a1,yr as a2,Cr as a3,wr as a4,gr as a5,vr as a6,Sr as a7,br as a8,Tr as a9,kr as aa,Er as ab,Ar as ac,_r as ad,Rr as ae,Ir as af,Or as ag,Lr as ah,Pr as ai,Fr as aj,Mr as ak,Hr as al,Ur as am,Nr as an,Br as ao,Dr as ap,Yi as aq,Ni as b,Di as c,Qi as d,xi as e,$i as f,Ji as g,ji as h,Li as i,Fi as j,Pi as k,Ki as l,Kr as m,Wr as n,Vr as o,Qr as p,xr as q,qr as r,jr as s,Gr as t,$r as u,Jr as v,zr as w,Yr as x,Xr as y,Zr as z};
|
|
@@ -1476,6 +1476,12 @@ interface SubscriptionState {
|
|
|
1476
1476
|
* every mutation.
|
|
1477
1477
|
*/
|
|
1478
1478
|
readonly argsKey: string;
|
|
1479
|
+
/**
|
|
1480
|
+
* Set by `LunoraClient.resnapshot` until the snapshot it asked for is committed: the
|
|
1481
|
+
* held `lastValue` is known to be stale, so a subscriber that joins meanwhile is not handed
|
|
1482
|
+
* it and waits for the fresh value. Subscribers already holding it keep it until then.
|
|
1483
|
+
*/
|
|
1484
|
+
awaitingSnapshot?: boolean;
|
|
1479
1485
|
readonly callbacks: Set<SubscriptionCallback>;
|
|
1480
1486
|
/**
|
|
1481
1487
|
* Notified when a `settled` frame advances this subscription's watermark — a
|
|
@@ -3336,6 +3342,21 @@ declare class LunoraClient {
|
|
|
3336
3342
|
* unsubscribe function that closes the socket and stops reconnecting.
|
|
3337
3343
|
*/
|
|
3338
3344
|
subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
|
|
3345
|
+
/**
|
|
3346
|
+
* Ask the server for a fresh, full snapshot of a live subscription, for when the value it
|
|
3347
|
+
* holds is known to be stale: a paginated feed restarting after `INVALID_CURSOR` resnapshots
|
|
3348
|
+
* its head page, whose `continueCursor` came from the same build as the cursor just refused.
|
|
3349
|
+
*
|
|
3350
|
+
* The subscription's resume position is dropped, so the server answers with a snapshot
|
|
3351
|
+
* rather than a `resume`. Subscribers already holding the value keep it until the snapshot
|
|
3352
|
+
* lands; one that joins meanwhile is not handed the stale value and waits for the fresh
|
|
3353
|
+
* one. A no-op when nothing subscribes to `(function_, args, shardKey)`. Without an open
|
|
3354
|
+
* socket (a cross-tab follower, or a dropped connection) the snapshot is taken when one
|
|
3355
|
+
* opens, and joiners are handed the held value meanwhile, since nothing else is coming.
|
|
3356
|
+
*/
|
|
3357
|
+
resnapshot<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
|
|
3358
|
+
shardKey?: string;
|
|
3359
|
+
}): void;
|
|
3339
3360
|
/**
|
|
3340
3361
|
* Subscribe to a live query. The callback fires with the current value (from
|
|
3341
3362
|
* the durable read cache, when one is hydrated) and again on every server
|
package/dist/packem_shared/{lunora-client.d-BKXjhLZZ.d.mts → lunora-client.d-Ezp1eG81.d.mts}
RENAMED
|
@@ -1476,6 +1476,12 @@ interface SubscriptionState {
|
|
|
1476
1476
|
* every mutation.
|
|
1477
1477
|
*/
|
|
1478
1478
|
readonly argsKey: string;
|
|
1479
|
+
/**
|
|
1480
|
+
* Set by `LunoraClient.resnapshot` until the snapshot it asked for is committed: the
|
|
1481
|
+
* held `lastValue` is known to be stale, so a subscriber that joins meanwhile is not handed
|
|
1482
|
+
* it and waits for the fresh value. Subscribers already holding it keep it until then.
|
|
1483
|
+
*/
|
|
1484
|
+
awaitingSnapshot?: boolean;
|
|
1479
1485
|
readonly callbacks: Set<SubscriptionCallback>;
|
|
1480
1486
|
/**
|
|
1481
1487
|
* Notified when a `settled` frame advances this subscription's watermark — a
|
|
@@ -3336,6 +3342,21 @@ declare class LunoraClient {
|
|
|
3336
3342
|
* unsubscribe function that closes the socket and stops reconnecting.
|
|
3337
3343
|
*/
|
|
3338
3344
|
subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
|
|
3345
|
+
/**
|
|
3346
|
+
* Ask the server for a fresh, full snapshot of a live subscription, for when the value it
|
|
3347
|
+
* holds is known to be stale: a paginated feed restarting after `INVALID_CURSOR` resnapshots
|
|
3348
|
+
* its head page, whose `continueCursor` came from the same build as the cursor just refused.
|
|
3349
|
+
*
|
|
3350
|
+
* The subscription's resume position is dropped, so the server answers with a snapshot
|
|
3351
|
+
* rather than a `resume`. Subscribers already holding the value keep it until the snapshot
|
|
3352
|
+
* lands; one that joins meanwhile is not handed the stale value and waits for the fresh
|
|
3353
|
+
* one. A no-op when nothing subscribes to `(function_, args, shardKey)`. Without an open
|
|
3354
|
+
* socket (a cross-tab follower, or a dropped connection) the snapshot is taken when one
|
|
3355
|
+
* opens, and joiners are handed the held value meanwhile, since nothing else is coming.
|
|
3356
|
+
*/
|
|
3357
|
+
resnapshot<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
|
|
3358
|
+
shardKey?: string;
|
|
3359
|
+
}): void;
|
|
3339
3360
|
/**
|
|
3340
3361
|
* Subscribe to a live query. The callback fires with the current value (from
|
|
3341
3362
|
* the durable read cache, when one is hydrated) and again on every server
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-Ezp1eG81.mjs";
|
|
2
2
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-DKfDdnjJ.js";
|
|
2
2
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
@@ -51,6 +51,8 @@ interface PaginatedCoreResult<T> {
|
|
|
51
51
|
pageResults: (PaginationResult<T> | undefined)[];
|
|
52
52
|
status: PaginationStatus;
|
|
53
53
|
}
|
|
54
|
+
/** The feed's head page: one open-ended range from the start of the feed. */
|
|
55
|
+
declare const headPage: (numberItems: number) => Page;
|
|
54
56
|
/** First-page seed: a single open-ended range starting at the feed head. */
|
|
55
57
|
declare const initialPages: (numberItems: number) => Page[];
|
|
56
58
|
/**
|
|
@@ -84,4 +86,26 @@ declare const derivePaginationStatus: <T>(skipped: boolean, pageResults: (Pagina
|
|
|
84
86
|
* valid (null or undefined — caller should no-op).
|
|
85
87
|
*/
|
|
86
88
|
declare const applyLoadMore: (pages: Page[], cursor: null | string | undefined, numberItems: number) => Page[] | undefined;
|
|
87
|
-
|
|
89
|
+
/**
|
|
90
|
+
* What a feed does with one page's failure.
|
|
91
|
+
*
|
|
92
|
+
* - `surface` — report it (the `error` value and `onError`), as before.
|
|
93
|
+
* - `restart` — reload the feed from its first page, silently: the page's cursor no longer decodes.
|
|
94
|
+
* - `ignore` — drop it: a page the feed no longer holds, still reporting from before a restart.
|
|
95
|
+
*/
|
|
96
|
+
type PageFailure = "ignore" | "restart" | "surface";
|
|
97
|
+
/** The feed's first page before any `loadMore`: `(null, null]`, the one page that carries no cursor. */
|
|
98
|
+
declare const isHeadPage: (page: Page) => boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Classify a page failure. Only `INVALID_CURSOR` changes the answer: the server refuses a cursor
|
|
101
|
+
* minted by an older build (a deploy changed the query's order or the engine's cursor encoding), and
|
|
102
|
+
* every bounded page the feed holds carries one, so the only way forward is page one.
|
|
103
|
+
*
|
|
104
|
+
* Two cases surface it instead. The head page has no cursor to be stale. And `restartedSinceLoad`
|
|
105
|
+
* (the feed restarted, and no page past the head has had a frame since) means the server is refusing
|
|
106
|
+
* the cursors it mints now, which a second restart would only repeat on every `loadMore`.
|
|
107
|
+
*/
|
|
108
|
+
declare const classifyPageFailure: (pages: Page[], isFailedPage: (page: Page) => boolean, error: {
|
|
109
|
+
code?: string;
|
|
110
|
+
}, restartedSinceLoad: boolean) => PageFailure;
|
|
111
|
+
export { JOIN_FACTOR, type Page, type PageFailure, type PaginatedCoreResult, type PaginationResult, type PaginationStatus, SPLIT_FACTOR, applyLoadMore, classifyPageFailure, derivePaginationStatus, headPage, initialPages, isHeadPage, rebalance };
|
|
@@ -51,6 +51,8 @@ interface PaginatedCoreResult<T> {
|
|
|
51
51
|
pageResults: (PaginationResult<T> | undefined)[];
|
|
52
52
|
status: PaginationStatus;
|
|
53
53
|
}
|
|
54
|
+
/** The feed's head page: one open-ended range from the start of the feed. */
|
|
55
|
+
declare const headPage: (numberItems: number) => Page;
|
|
54
56
|
/** First-page seed: a single open-ended range starting at the feed head. */
|
|
55
57
|
declare const initialPages: (numberItems: number) => Page[];
|
|
56
58
|
/**
|
|
@@ -84,4 +86,26 @@ declare const derivePaginationStatus: <T>(skipped: boolean, pageResults: (Pagina
|
|
|
84
86
|
* valid (null or undefined — caller should no-op).
|
|
85
87
|
*/
|
|
86
88
|
declare const applyLoadMore: (pages: Page[], cursor: null | string | undefined, numberItems: number) => Page[] | undefined;
|
|
87
|
-
|
|
89
|
+
/**
|
|
90
|
+
* What a feed does with one page's failure.
|
|
91
|
+
*
|
|
92
|
+
* - `surface` — report it (the `error` value and `onError`), as before.
|
|
93
|
+
* - `restart` — reload the feed from its first page, silently: the page's cursor no longer decodes.
|
|
94
|
+
* - `ignore` — drop it: a page the feed no longer holds, still reporting from before a restart.
|
|
95
|
+
*/
|
|
96
|
+
type PageFailure = "ignore" | "restart" | "surface";
|
|
97
|
+
/** The feed's first page before any `loadMore`: `(null, null]`, the one page that carries no cursor. */
|
|
98
|
+
declare const isHeadPage: (page: Page) => boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Classify a page failure. Only `INVALID_CURSOR` changes the answer: the server refuses a cursor
|
|
101
|
+
* minted by an older build (a deploy changed the query's order or the engine's cursor encoding), and
|
|
102
|
+
* every bounded page the feed holds carries one, so the only way forward is page one.
|
|
103
|
+
*
|
|
104
|
+
* Two cases surface it instead. The head page has no cursor to be stale. And `restartedSinceLoad`
|
|
105
|
+
* (the feed restarted, and no page past the head has had a frame since) means the server is refusing
|
|
106
|
+
* the cursors it mints now, which a second restart would only repeat on every `loadMore`.
|
|
107
|
+
*/
|
|
108
|
+
declare const classifyPageFailure: (pages: Page[], isFailedPage: (page: Page) => boolean, error: {
|
|
109
|
+
code?: string;
|
|
110
|
+
}, restartedSinceLoad: boolean) => PageFailure;
|
|
111
|
+
export { JOIN_FACTOR, type Page, type PageFailure, type PaginatedCoreResult, type PaginationResult, type PaginationStatus, SPLIT_FACTOR, applyLoadMore, classifyPageFailure, derivePaginationStatus, headPage, initialPages, isHeadPage, rebalance };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const c=2,p=.5,l=e=>({lower:null,numItems:e,upper:null}),m=e=>[l(e)],d=(e,r)=>{for(const[n,t]of e.entries()){if(t.upper===null)continue;const u=r[n];if(!u)continue;const i=u.page.length;if((i>2*t.numItems||u.splitRequired===!0)&&u.splitCursor){const o=u.splitCursor,s=[...e];return s.splice(n,1,{lower:t.lower,numItems:t.numItems,upper:o},{lower:o,numItems:t.numItems,upper:t.upper}),s}if(i<.5*t.numItems&&n+1<e.length&&r[n+1]?.splitRequired!==!0){const o=e[n+1];if(!o)continue;const s=[...e];return s.splice(n,2,{lower:t.lower,numItems:t.numItems,upper:o.upper}),s}}},f=(e,r)=>{if(e||!r[0])return{nextCursor:void 0,status:"LoadingFirstPage"};const n=r.at(-1);return n?n.isDone||n.continueCursor===null?{nextCursor:void 0,status:"Exhausted"}:{nextCursor:n.continueCursor,status:"CanLoadMore"}:{nextCursor:void 0,status:"LoadingMore"}},I=(e,r,n)=>{if(r==null)return;const t=[...e],u=t.at(-1);return u&&(t[t.length-1]={lower:u.lower,numItems:u.numItems,upper:r}),t.push({lower:r,numItems:n,upper:null}),t},a=e=>e.lower===null&&e.upper===null,C=(e,r,n,t)=>{if(n.code!=="INVALID_CURSOR")return"surface";const u=e.find(i=>r(i));return u===void 0?"ignore":a(u)||t?"surface":"restart"};export{p as JOIN_FACTOR,c as SPLIT_FACTOR,I as applyLoadMore,C as classifyPageFailure,f as derivePaginationStatus,l as headPage,m as initialPages,a as isHeadPage,d as rebalance};
|
package/dist/query/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
2
|
-
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-
|
|
2
|
+
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-Ezp1eG81.mjs";
|
|
3
3
|
export type {
|
|
4
4
|
/**
|
|
5
5
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -15,7 +15,7 @@ export type {
|
|
|
15
15
|
* `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
|
|
16
16
|
* the same way.
|
|
17
17
|
*/
|
|
18
|
-
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
18
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Ezp1eG81.mjs";
|
|
19
19
|
import '@lunora/errors';
|
|
20
20
|
/**
|
|
21
21
|
* The TanStack Query cache-key contract for Lunora queries. It lives here, not
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
2
|
-
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-
|
|
2
|
+
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-DKfDdnjJ.js";
|
|
3
3
|
export type {
|
|
4
4
|
/**
|
|
5
5
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -15,7 +15,7 @@ export type {
|
|
|
15
15
|
* `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
|
|
16
16
|
* the same way.
|
|
17
17
|
*/
|
|
18
|
-
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
18
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DKfDdnjJ.js";
|
|
19
19
|
import '@lunora/errors';
|
|
20
20
|
/**
|
|
21
21
|
* The TanStack Query cache-key contract for Lunora queries. It lives here, not
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-Ezp1eG81.mjs";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
3
3
|
export {
|
|
4
4
|
/**
|
|
@@ -20,7 +20,7 @@ p as preloadQuery,
|
|
|
20
20
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
21
21
|
* loader.
|
|
22
22
|
*/
|
|
23
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-qnL9TXVr.mjs";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
/**
|
|
26
26
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-DKfDdnjJ.js";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
3
3
|
export {
|
|
4
4
|
/**
|
|
@@ -20,7 +20,7 @@ p as preloadQuery,
|
|
|
20
20
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
21
21
|
* loader.
|
|
22
22
|
*/
|
|
23
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-wJ_ggZsg.js";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
/**
|
|
26
26
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-YR31uvMw.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.289",
|
|
4
4
|
"description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableWireKey as n}from"@lunora/wire";class y{static key(e,i,t){return`${e}::${n(i)}::${t??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(y.keyOf(e),e),this.byId.set(e.id,e)}remove(e){const i=y.keyOf(e);this.byKey.get(i)===e&&this.byKey.delete(i),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}}const s=(r,e)=>{r.ack=e},b=r=>{r.ack==="inflight"&&s(r,"idle")};function o(r){if(r!==void 0)return e=>{r(e)}}const d=(r,e)=>{for(const i of r)try{i(e)}catch{}};export{y as SubscriptionRegistry,d as fanSubscriptionError,b as releaseSubscribeFrame,s as setSubscriptionAck,o as wrapSubscriber};
|