spacewave 0.57.7 → 0.57.9
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/API.md +112 -15
- package/CHANGELOG.md +1 -1
- package/README.md +4 -4
- package/dist/THIRD_PARTY_NOTICES.txt +95 -166
- package/dist/build.json +2 -2
- package/dist/chunks/json-BuGtLL3Z.mjs +2 -0
- package/dist/chunks/node.pb-L2jxLJ0J.mjs +2 -0
- package/dist/engine-worker.mjs +99 -99
- package/dist/index.mjs +1 -1
- package/dist/react.mjs +1 -1
- package/dist/server.mjs +4 -5
- package/dist/types/core/sync/config.d.ts +4 -1
- package/dist/types/packages/spacewave/index.d.ts +4 -0
- package/dist/types/packages/spacewave/react.d.ts +3 -1
- package/dist/types/sdk/sync/app.d.ts +37 -0
- package/dist/types/sdk/sync/query.d.ts +71 -0
- package/dist/types/web/sync/app-hooks.d.ts +31 -0
- package/examples/task-board/package.json +1 -1
- package/examples/task-board/react.tsx +27 -27
- package/package.json +1 -1
- package/dist/chunks/errors-BHnASqFk.mjs +0 -2
- package/dist/chunks/node.pb-ChF26ESv.mjs +0 -2
- package/dist/types/web/sync/index.d.ts +0 -4
package/dist/server.mjs
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./chunks/rolldown-runtime-Csi-cuKc.mjs";import{$n as r,$r as i,$t as a,A as o,An as s,Ar as c,At as l,B as u,Br as d,Bt as f,Cn as p,Cr as m,Ct as h,D as g,Di as v,Dn as y,Dr as b,Dt as ee,Ei as x,En as S,Er as te,Et as C,Fn as w,Fr as ne,Ft as re,Gn as T,Gr as ie,Gt as ae,H as oe,Hn as se,Hr as E,Ht as ce,In as D,Ir as le,It as O,Ji as ue,Jn as de,Jr as k,Jt as A,Ki as j,Kn as fe,Kr as pe,Kt as me,L as he,Li as M,Lr as ge,Lt as _e,M as ve,Mr as ye,Mt as be,N as xe,Nn as Se,Nr as Ce,Nt as we,O as Te,On as Ee,Or as De,Ot as Oe,Pn as ke,Pr as Ae,Pt as je,Qn as Me,Qr as Ne,R as Pe,Rr as Fe,Rt as Ie,S as Le,Sr as Re,St as ze,T as Be,Tn as Ve,Tr as He,Tt as Ue,Un as We,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vr as Ye,Vt as Xe,Wn as Ze,Wr as Qe,Wt as $e,Xn as et,Xr as tt,Xt as nt,Yi as N,Yn as rt,Yr as it,Yt as at,Zr as ot,_ as P,_n as st,_r as ct,_t as lt,a as ut,ai as dt,an as ft,ar as pt,at as mt,b as ht,bi as gt,br as _t,bt as vt,c as yt,ci as bt,cn as xt,cr as St,ct as Ct,d as wt,di as Tt,dr as Et,dt as Dt,ei as Ot,en as kt,er as At,et as jt,f as Mt,fi as Nt,fn as Pt,ft as Ft,g as It,gn as Lt,gr as Rt,gt as zt,h as Bt,hn as Vt,hr as Ht,ht as Ut,i as Wt,ii as Gt,in as Kt,ir as qt,it as Jt,j as Yt,jr as Xt,jt as Zt,k as Qt,kn as $t,kr as en,l as tn,li as nn,ln as rn,lr as an,lt as on,m as F,mn as sn,mt as cn,n as ln,ni as un,nn as dn,nr as fn,nt as I,o as pn,oi as mn,on as hn,or as gn,ot as _n,p as vn,pn as yn,pt as bn,qi as L,qn as xn,qr as Sn,qt as Cn,r as wn,ri as Tn,rn as En,rr as Dn,rt as On,s as kn,si as An,sn as jn,sr as Mn,st as Nn,t as Pn,ti as Fn,tn as In,tr as Ln,tt as Rn,u as zn,ui as Bn,un as Vn,ur as Hn,ut as Un,v as Wn,vn as Gn,vr as Kn,w as qn,wn as Jn,wr as Yn,wt as Xn,x as Zn,xr as Qn,xt as $n,y as er,yi as tr,yn as nr,yr as rr,yt as ir,zr as ar,zt as or}from"./chunks/node.pb-ChF26ESv.mjs";import{MessageChannel as sr,Worker as cr}from"node:worker_threads";import{createHash as lr,randomUUID as ur}from"node:crypto";import{createServer as dr}from"node:http";const fr=Symbol(`server context parent`),pr=Symbol(`server context key`),mr=Symbol(`server context value`);function hr(){return{}}function gr(e,t,n){return{signal:e.signal,[fr]:e,[pr]:t,[mr]:n}}function _r(e,t){let n=e;for(;n;){if(n[pr]===t)return n[mr];n=n[fr]}}async function vr(e,t,n){let r=P({objectMode:!0}),i=t(r);r.push({body:{case:`init`,value:{componentId:e}}});let a=i[Symbol.asyncIterator]();if(n){let e=await a.next();if(e.done)throw Error(`rpcstream: closed before ack packet`);let t=e.value?.body;if(!t||t.case!==`ack`){let e=t?.case||`none`;throw Error(`rpcstream: expected ack packet but got ${e}`)}let n=t.value?.error;if(n)throw Error(`rpcstream: remote: ${n}`)}return new br(r,a,()=>tn(a))}async function*yr(e,t){let n=await e.next();if(n.done)throw Error(`closed before init received`);let r=n.value;if(r?.body?.case!==`init`)throw Error(`expected init packet`);let i=null,a;try{i=await t(r.body.value.componentId??``)}catch(e){a=e,a?a.message||(a=Error(`rpc getter failed: ${a}`)):a=Error(`rpc getter failed`)}if(!i&&!a&&(a=Error(`not implemented`)),yield*[{body:{case:`ack`,value:{error:a?.message||``}}}],a)throw a;let o=P({objectMode:!0}),s=new br(o,e,()=>tn(e));i(s).catch(e=>o.end(e)).then(()=>o.end());for await(let e of o)yield*[e]}var br=class{source;sink;_packetRx;_packetTx;_termination=new yt;_cancelRpc;constructor(e,t,n=()=>tn(t)){this._packetTx=e,this._packetRx=t,this._cancelRpc=n,this.sink=this._createSink(),this.source=this._createSource()}async close(){this._termination.terminate()&&(this._packetTx.end(),this._cancelRpc())}abort(e){this._termination.terminate(e)&&(this._packetTx.end(e),this._cancelRpc())}_createSink(){return async e=>{let t=zn(e);try{for(;;){let e=await this._termination.next(t);if(`terminated`in e){if(e.error)throw e.error;return}if(`error`in e)throw e.error;if(e.result.done){this._packetTx.end();return}if(this._termination.terminated)return;this._packetTx.push({body:{case:`data`,value:e.result.value}})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.abort(t),t}finally{tn(t)}}}_createSource(){let e=this._packetRx,t=this._termination;return(async function*(){try{for(;;){let n=await t.next(e);if(`terminated`in n){if(n.error)throw n.error;return}if(`error`in n)throw n.error;if(n.result.done)return;let r=n.result.value?.body;if(r)switch(r.case){case`ack`:if(r.value.error?.length)throw Error(r.value.error);break;case`data`:yield r.value}}}finally{tn(e)}})()}};const xr=Symbol.for(`spacewave.SyncError`);var R=class extends Error{code;requestId;name=`SyncError`;[xr]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&xr in e&&e[xr]===!0}constructor(e,t,n){super(t),this.code=e,this.requestId=n}};function Sr(e){return e instanceof R?e:new R(`STORAGE`,`The data operation could not complete`)}function z(e){return Cr(e,`$`,[])}function B(e){return new TextEncoder().encode(z(e))}function V(e){let t;try{t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw TypeError(`invalid JSON at $: data is not valid UTF-8`)}let n;try{n=JSON.parse(t)}catch{throw TypeError(`invalid JSON at $: data is not valid JSON`)}return z(n),n}function Cr(e,t,n){switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:if(!Number.isFinite(e))throw TypeError(`invalid JSON at ${t}: non-finite number`);return JSON.stringify(e);case`string`:return JSON.stringify(e);case`object`:if(e===null)return`null`;break;default:throw TypeError(`invalid JSON at ${t}: ${typeof e} is not a JSON value`)}for(let r of n)if(r===e)throw TypeError(`invalid JSON at ${t}: cycle`);n.push(e);let r=Array.isArray(e)?wr(e,t,n):Tr(e,t,n);return n.pop(),r}function wr(e,t,n){let r=e.length,i=Array(r),a=Array(r).fill(!1);for(let o of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,o);if(s.get!==void 0||s.set!==void 0)throw TypeError(`invalid JSON at ${t}[${String(o)}]: accessor property`);if(typeof o==`symbol`){if(s.enumerable)throw TypeError(`invalid JSON at ${t}: enumerable symbol key is not supported`);continue}let c=Number(o);if(Number.isInteger(c)&&c>=0&&c<r&&String(c)===o){a[c]=!0,i[c]=Cr(s.value,`${t}[${c}]`,n);continue}if(s.enumerable)throw TypeError(`invalid JSON at ${t}: extra enumerable array property ${JSON.stringify(o)}`)}for(let e=0;e<r;e++)if(!a[e])throw TypeError(`invalid JSON at ${t}[${e}]: array hole (missing index)`);return`[${i.join(`,`)}]`}function Tr(e,t,n){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`invalid JSON at ${t}: not a plain object`);let i=[];for(let r of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,r);if(a.get!==void 0||a.set!==void 0)throw TypeError(`invalid JSON at ${t}.${String(r)}: accessor property`);if(typeof r==`symbol`){if(a.enumerable)throw TypeError(`invalid JSON at ${t}: enumerable symbol key is not supported`);continue}a.enumerable&&i.push({key:r,json:Cr(a.value,`${t}.${r}`,n)})}return i.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),`{${i.map(e=>`${JSON.stringify(e.key)}:${e.json}`).join(`,`)}}`}function Er(e){return{collection:t=>({get:async(n,r)=>{let i=await e({kind:`get`,collection:t,key:n},r);return i.found?i.value:void 0},scan:async(n,r)=>await e({kind:`scan`,collection:t,prefix:n?.prefix??``},r),put:async(n,r,i)=>{await e({kind:`put`,collection:t,key:n,value:Dr(r)},i)},delete:async(n,r)=>{await e({kind:`delete`,collection:t,key:n},r)}}),mutate:async(t,n,r)=>await e({kind:`mutate`,name:t,input:Dr(n)},r)}}function Dr(e){try{return V(B(e))}catch{throw new R(`VALIDATION`,`Input must contain only JSON-compatible values`)}}var Or=class{opts;nonce;getSnapshot;listeners=new Set;errorListeners=new Set;constructor(e,t){this.opts=t,this.getSnapshot=e||(async()=>void 0)}get snapshot(){return this.getSnapshot()}getIterable(){return{[Symbol.asyncIterator]:()=>{let e=[],t=null,n=null,r=!1,i=null,a=n=>{if(this.opts?.mostRecentOnly){if(i={value:n,nonce:this.nonce},t){let e=t;t=null,e({value:i.value,done:!1}),i=null}}else if(t){let e=t;t=null,e({value:n,done:!1})}else e.push(n)},o=e=>{if(n){let t=n;n=null,t(e)}r=!0};return this.listeners.add(a),this.errorListeners.add(o),(async()=>{try{let e=await this.getSnapshot();e!==void 0&&a(e)}catch(e){o(e instanceof Error?e:Error(String(e)))}})(),{next:async()=>{if(r)return{value:void 0,done:!0};if(i){let{value:e}=i;return i=null,{value:e,done:!1}}return e.length>0?{value:e.shift(),done:!1}:new Promise((e,r)=>{t=e,n=r})},return:async()=>{if(this.listeners.delete(a),this.errorListeners.delete(o),r=!0,t){let e=t;t=null,e({value:void 0,done:!0})}return n=null,{value:void 0,done:!0}},throw:async()=>(this.listeners.delete(a),this.errorListeners.delete(o),r=!0,t=null,n=null,{value:void 0,done:!0})}}}}pushChangeEvent(e){this.opts?.mostRecentOnly?(this.nonce=(this.nonce??0)+1,Array.from(this.listeners).forEach(t=>t(e))):this.listeners.forEach(t=>t(e))}async pushSnapshot(){try{let e=await this.getSnapshot();e&&this.pushChangeEvent(e)}catch(e){this.errorListeners.forEach(t=>t(e instanceof Error?e:Error(String(e))))}}};for(let e of[`dispose`,`asyncDispose`])Symbol[e]||Object.defineProperty(Symbol,e,{value:Symbol.for(`Symbol.${e}`)});function kr(e=500){return()=>e}var Ar=class{fn;result;get canceled(){return this._canceled}_backoffFn;_errorCb;_abortSignal;_abortListener;_canceled;_resolve;_reject;_currError;_cancelRetry;_setTimeout;_clearTimeout;constructor(e,t){this.fn=e,this._abortSignal=t?.abortSignal,this._abortSignal&&(this._abortListener=()=>this.cancel(),this._abortSignal.addEventListener(`abort`,this._abortListener,{once:!0})),this._backoffFn=t?.backoffFn||kr(),this._errorCb=t?.errorCb??(e=>{console.warn(`Retry: retrying after error`,{error:e})}),this._setTimeout=t?.setTimeout||setTimeout.bind(globalThis),this._clearTimeout=t?.clearTimeout||clearTimeout.bind(globalThis),this.result=new Promise((e,t)=>{this._resolve=e,this._reject=t}),this.result.catch(()=>{}),queueMicrotask(this._execute.bind(this))}cancel(){this._canceled||(this._canceled=!0,this._clearAbortListener(),this._cancelRetry&&this._cancelRetry(),this._reject&&this._reject(this._currError))}async _execute(){do try{let e=this._abortSignal;if(this._canceled||e?.aborted){this.cancel();return}let t=await this.fn();this._resolve&&(this._clearAbortListener(),this._resolve(t));return}catch(e){let t=this._abortSignal;if(this._currError=e,this._canceled||t?.aborted){this._reject&&(this._clearAbortListener(),this._reject(e));return}this._errorCb&&this._errorCb(e),await new Promise(e=>{let n=null;if(t?.aborted){e();return}this._cancelRetry=()=>{n&&this._clearTimeout(n),e()},n=this._setTimeout(()=>{this._cancelRetry=void 0,e()},this._backoffFn())})}while(1)}_clearAbortListener(){this._abortSignal&&this._abortListener&&(this._abortSignal.removeEventListener(`abort`,this._abortListener),this._abortListener=void 0)}};function jr(e,t,n){return new Ar(t.bind(void 0,e),{...n,abortSignal:e}).result}N.STRING;const Mr=j(`web.runtime.RequestRuntimeQuitRequest`,!0),Nr=j(`web.runtime.RequestRuntimeQuitResponse`,!0),Pr=j(`web.runtime.WatchWebRuntimeStatusRequest`,!0),Fr=L({typeName:`web.runtime.WebDocumentStatus`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`deleted`,kind:`scalar`,T:N.BOOL},{no:3,name:`permanent`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),Ir=L({typeName:`web.runtime.WebRuntimeStatus`,fields:[{no:1,name:`snapshot`,kind:`scalar`,T:N.BOOL},{no:2,name:`web_documents`,kind:`message`,T:()=>Fr,repeated:!0},{no:3,name:`closed`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),Lr=L({typeName:`web.runtime.CreateWebDocumentRequest`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Rr=L({typeName:`web.runtime.CreateWebDocumentResponse`,fields:[{no:1,name:`created`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),zr=L({typeName:`web.runtime.RemoveWebDocumentRequest`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Br=L({typeName:`web.runtime.RemoveWebDocumentResponse`,fields:[{no:1,name:`removed`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),Vr=j(`web.runtime.FlushIndexCacheRequest`,!0),Hr=j(`web.runtime.FlushIndexCacheResponse`,!0);N.STRING,N.STRING,N.STRING,N.BOOL;const Ur=L({typeName:`rpcstream.RpcStreamInit`,fields:[{no:1,name:`component_id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Wr=L({typeName:`rpcstream.RpcAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),H=L({typeName:`rpcstream.RpcStreamPacket`,fields:[{no:1,name:`init`,kind:`message`,T:()=>Ur,oneof:`body`},{no:2,name:`ack`,kind:`message`,T:()=>Wr,oneof:`body`},{no:3,name:`data`,kind:`scalar`,T:N.BYTES,oneof:`body`}],packedByDefault:!0});({typeName:`web.runtime.WebRuntimeHost`,methods:{RequestRuntimeQuit:{name:`RequestRuntimeQuit`,I:Mr,O:Nr,kind:M.Unary},WebDocumentRpc:{name:`WebDocumentRpc`,I:H,O:H,kind:M.BiDiStreaming},ServiceWorkerRpc:{name:`ServiceWorkerRpc`,I:H,O:H,kind:M.BiDiStreaming},WebWorkerRpc:{name:`WebWorkerRpc`,I:H,O:H,kind:M.BiDiStreaming}}}).typeName,{typeName:`web.runtime.WebRuntime`,methods:{WatchWebRuntimeStatus:{name:`WatchWebRuntimeStatus`,I:Pr,O:Ir,kind:M.ServerStreaming},CreateWebDocument:{name:`CreateWebDocument`,I:Lr,O:Rr,kind:M.Unary},RemoveWebDocument:{name:`RemoveWebDocument`,I:zr,O:Br,kind:M.Unary},WebDocumentRpc:{name:`WebDocumentRpc`,I:H,O:H,kind:M.BiDiStreaming},WebWorkerRpc:{name:`WebWorkerRpc`,I:H,O:H,kind:M.BiDiStreaming},FlushIndexCache:{name:`FlushIndexCache`,I:Vr,O:Hr,kind:M.Unary}}}.typeName;const Gr=L({typeName:`bldr.frontend.Binding`,fields:[{no:1,name:`entrypoint`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Kr=L({typeName:`bldr.frontend.Session`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`route_prefix`,kind:`scalar`,T:N.STRING},{no:3,name:`entrypoints`,kind:`scalar`,T:N.STRING,repeated:!0},{no:4,name:`vite_version`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),qr=j(`bldr.frontend.WatchRequest`,!0),Jr=L({typeName:`bldr.frontend.Event`,fields:[{no:1,name:`session`,kind:`message`,T:()=>Kr},{no:2,name:`sequence`,kind:`scalar`,T:N.UINT64},{no:3,name:`payload`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Yr=L({typeName:`bldr.frontend.SendRequest`,fields:[{no:1,name:`session_id`,kind:`scalar`,T:N.STRING},{no:2,name:`payload`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Xr=j(`bldr.frontend.SendResponse`,!0),Zr=L({typeName:`web.fetch.FetchRequestInfo`,fields:[{no:1,name:`method`,kind:`scalar`,T:N.STRING},{no:2,name:`url`,kind:`scalar`,T:N.STRING},{no:3,name:`headers`,kind:`map`,K:N.STRING,V:{kind:`scalar`,T:N.STRING}},{no:4,name:`has_body`,kind:`scalar`,T:N.BOOL},{no:5,name:`client_id`,kind:`scalar`,T:N.STRING},{no:6,name:`destination`,kind:`scalar`,T:N.STRING},{no:7,name:`integrity`,kind:`scalar`,T:N.STRING},{no:8,name:`mode`,kind:`scalar`,T:N.STRING},{no:9,name:`redirect`,kind:`scalar`,T:N.STRING},{no:10,name:`referrer`,kind:`scalar`,T:N.STRING},{no:11,name:`referrer_policy`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Qr=L({typeName:`web.fetch.FetchRequestData`,fields:[{no:1,name:`data`,kind:`scalar`,T:N.BYTES},{no:2,name:`done`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),$r=L({typeName:`web.fetch.FetchRequest`,fields:[{no:1,name:`request_info`,kind:`message`,T:()=>Zr,oneof:`body`},{no:2,name:`request_data`,kind:`message`,T:()=>Qr,oneof:`body`}],packedByDefault:!0}),ei=L({typeName:`web.fetch.ResponseInfo`,fields:[{no:1,name:`headers`,kind:`map`,K:N.STRING,V:{kind:`scalar`,T:N.STRING}},{no:2,name:`ok`,kind:`scalar`,T:N.BOOL},{no:3,name:`redirected`,kind:`scalar`,T:N.BOOL},{no:4,name:`status`,kind:`scalar`,T:N.UINT32},{no:5,name:`status_text`,kind:`scalar`,T:N.STRING},{no:6,name:`response_type`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),ti=L({typeName:`web.fetch.ResponseData`,fields:[{no:1,name:`data`,kind:`scalar`,T:N.BYTES},{no:2,name:`done`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),ni=L({typeName:`web.fetch.FetchResponse`,fields:[{no:1,name:`response_info`,kind:`message`,T:()=>ei,oneof:`body`},{no:2,name:`response_data`,kind:`message`,T:()=>ti,oneof:`body`}],packedByDefault:!0});({typeName:`bldr.frontend.Frontend`,methods:{Watch:{name:`Watch`,I:qr,O:Jr,kind:M.ServerStreaming},Send:{name:`Send`,I:Yr,O:Xr,kind:M.Unary},Fetch:{name:`Fetch`,I:$r,O:ni,kind:M.BiDiStreaming}}}).typeName,n(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):r((n=typeof globalThis<`u`?globalThis:n||self).workbox={})})(e,(function(e){try{self[`workbox:window:7.4.0`]&&_()}catch{}function t(e,t){return new Promise((function(n){var r=new MessageChannel;r.port1.onmessage=function(e){n(e.data)},e.postMessage(t,[r.port2])}))}function n(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function r(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,o(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e,t){var r=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if(typeof e==`string`)return n(e,t);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}}(e))||t){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
2
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function a(e,t){return a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},a(e,t)}function o(e){var t=function(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e,`string`);return typeof t==`symbol`?t:t+``}try{self[`workbox:core:7.4.0`]&&_()}catch{}var s=function(){var e=this;this.promise=new Promise((function(t,n){e.resolve=t,e.reject=n}))};function c(e,t){var n=location.href;return new URL(e,n).href===new URL(t,n).href}var l=function(e,t){this.type=e,Object.assign(this,t)};function u(e,t,n){return e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e}function d(){}var f={type:`SKIP_WAITING`};function p(e,t){return e&&e.then?e.then(d):Promise.resolve()}e.Workbox=function(e){function n(t,n){var r,i;return n===void 0&&(n={}),(r=e.call(this)||this).nn={},r.tn=0,r.rn=new s,r.en=new s,r.on=new s,r.un=0,r.an=new Set,r.cn=function(){var e=r.fn,t=e.installing;r.tn>0||!c(t.scriptURL,r.sn.toString())||performance.now()>r.un+6e4?(r.vn=t,e.removeEventListener(`updatefound`,r.cn)):(r.hn=t,r.an.add(t),r.rn.resolve(t)),++r.tn,t.addEventListener(`statechange`,r.ln)},r.ln=function(e){var t=r.fn,n=e.target,i=n.state,a=n===r.vn,o={sw:n,isExternal:a,originalEvent:e};!a&&r.dn&&(o.isUpdate=!0),r.dispatchEvent(new l(i,o)),i===`installed`?r.mn=self.setTimeout((function(){i===`installed`&&t.waiting===n&&r.dispatchEvent(new l(`waiting`,o))}),200):i===`activating`&&(clearTimeout(r.mn),a||r.en.resolve(n))},r.yn=function(e){var t=r.hn,n=t!==navigator.serviceWorker.controller;r.dispatchEvent(new l(`controlling`,{isExternal:n,originalEvent:e,sw:t,isUpdate:r.dn})),n||r.on.resolve(t)},r.wn=(i=function(e){var t=e.data,n=e.ports,i=e.source;return u(r.getSW(),(function(){r.an.has(i)&&r.dispatchEvent(new l(`message`,{data:t,originalEvent:e,ports:n,sw:i}))}))},function(){var e=[...arguments];try{return Promise.resolve(i.apply(this,e))}catch(e){return Promise.reject(e)}}),r.sn=t,r.nn=n,navigator.serviceWorker.addEventListener(`message`,r.wn),r}var i,o=e;(i=n).prototype=Object.create(o.prototype),i.prototype.constructor=i,a(i,o);var d=n.prototype;return d.register=function(e){var t=(e===void 0?{}:e).immediate,n=t!==void 0&&t;try{var r=this;return u(function(e,t){var n=e();return n&&n.then?n.then(t):t(n)}((function(){if(!n&&document.readyState!==`complete`)return p(new Promise((function(e){return window.addEventListener(`load`,e)})))}),(function(){return r.dn=!!navigator.serviceWorker.controller,r.gn=r.pn(),u(r.bn(),(function(e){r.fn=e,r.gn&&(r.hn=r.gn,r.en.resolve(r.gn),r.on.resolve(r.gn),r.gn.addEventListener(`statechange`,r.ln,{once:!0}));var t=r.fn.waiting;return t&&c(t.scriptURL,r.sn.toString())&&(r.hn=t,Promise.resolve().then((function(){r.dispatchEvent(new l(`waiting`,{sw:t,wasWaitingBeforeRegister:!0}))})).then((function(){}))),r.hn&&(r.rn.resolve(r.hn),r.an.add(r.hn)),r.fn.addEventListener(`updatefound`,r.cn),navigator.serviceWorker.addEventListener(`controllerchange`,r.yn),r.fn}))})))}catch(e){return Promise.reject(e)}},d.update=function(){try{return this.fn?u(p(this.fn.update())):u()}catch(e){return Promise.reject(e)}},d.getSW=function(){return this.hn===void 0?this.rn.promise:Promise.resolve(this.hn)},d.messageSW=function(e){try{return u(this.getSW(),(function(n){return t(n,e)}))}catch(e){return Promise.reject(e)}},d.messageSkipWaiting=function(){this.fn&&this.fn.waiting&&t(this.fn.waiting,f)},d.pn=function(){var e=navigator.serviceWorker.controller;return e&&c(e.scriptURL,this.sn.toString())?e:void 0},d.bn=function(){try{var e=this;return u(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}((function(){return u(navigator.serviceWorker.register(e.sn,e.nn),(function(t){return e.un=performance.now(),t}))}),(function(e){throw e})))}catch(e){return Promise.reject(e)}},r(n,[{key:`active`,get:function(){return this.en.promise}},{key:`controlling`,get:function(){return this.on.promise}}])}(function(){function e(){this.Pn=new Map}var t=e.prototype;return t.addEventListener=function(e,t){this.jn(e).add(t)},t.removeEventListener=function(e,t){this.jn(e).delete(t)},t.dispatchEvent=function(e){e.target=this;for(var t,n=i(this.jn(e.type));!(t=n()).done;)(0,t.value)(e)},t.jn=function(e){return this.Pn.has(e)||this.Pn.set(e,new Set),this.Pn.get(e)},e}()),e.WorkboxEvent=l,e.messageSW=t}))}))();const ri=ue(`web.document.WebWorkerGenerationState`,[[0,`WEB_WORKER_GENERATION_STATE_UNKNOWN`],[1,`WEB_WORKER_GENERATION_STATE_WORKER_REQUESTED`],[2,`WEB_WORKER_GENERATION_STATE_WORKER_CREATED`],[3,`WEB_WORKER_GENERATION_STATE_STARTUP_RUNNING`],[4,`WEB_WORKER_GENERATION_STATE_FRONTEND_READY`],[5,`WEB_WORKER_GENERATION_STATE_CAPABILITY_READY`],[6,`WEB_WORKER_GENERATION_STATE_RUNNING`],[7,`WEB_WORKER_GENERATION_STATE_NORMAL_STOP`],[8,`WEB_WORKER_GENERATION_STATE_STARTUP_TIMEOUT`],[9,`WEB_WORKER_GENERATION_STATE_TERMINAL_FAILURE`],[10,`WEB_WORKER_GENERATION_STATE_LIFECYCLE_HIDDEN`],[11,`WEB_WORKER_GENERATION_STATE_CONTROLLED_STREAM_RESET`]]),ii=ue(`web.document.WebWorkerMode`,[[0,`WORKER_MODE_DEFAULT`],[1,`WORKER_MODE_SHARED`],[2,`WORKER_MODE_DEDICATED`]]),ai=j(`web.document.WatchWebDocumentStatusRequest`,!0),oi=L({typeName:`web.document.WebViewStatus`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`deleted`,kind:`scalar`,T:N.BOOL},{no:3,name:`parent_id`,kind:`scalar`,T:N.STRING},{no:4,name:`permanent`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),si=L({typeName:`web.document.WebWorkerStatus`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`deleted`,kind:`scalar`,T:N.BOOL},{no:3,name:`shared`,kind:`scalar`,T:N.BOOL},{no:4,name:`ready`,kind:`scalar`,T:N.BOOL},{no:5,name:`failed`,kind:`scalar`,T:N.BOOL},{no:6,name:`failure_reason`,kind:`scalar`,T:N.STRING},{no:7,name:`generation_state`,kind:`enum`,T:ri},{no:8,name:`generation`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),ci=L({typeName:`web.document.WebDocumentStatus`,fields:[{no:1,name:`snapshot`,kind:`scalar`,T:N.BOOL},{no:2,name:`hidden`,kind:`scalar`,T:N.BOOL},{no:3,name:`web_views`,kind:`message`,T:()=>oi,repeated:!0},{no:4,name:`web_workers`,kind:`message`,T:()=>si,repeated:!0},{no:5,name:`closed`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),li=L({typeName:`web.document.CreateWebViewRequest`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),ui=L({typeName:`web.document.CreateWebViewResponse`,fields:[{no:1,name:`created`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),di=L({typeName:`web.document.CreateWebWorkerRequest`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`path`,kind:`scalar`,T:N.STRING},{no:3,name:`worker_mode`,kind:`enum`,T:ii},{no:4,name:`init_data`,kind:`scalar`,T:N.BYTES},{no:6,name:`generation`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),fi=L({typeName:`web.document.CreateWebWorkerResponse`,fields:[{no:1,name:`created`,kind:`scalar`,T:N.BOOL},{no:2,name:`shared`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0}),pi=L({typeName:`web.document.RemoveWebWorkerRequest`,fields:[{no:1,name:`id`,kind:`scalar`,T:N.STRING},{no:2,name:`generation`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),mi=L({typeName:`web.document.RemoveWebWorkerResponse`,fields:[{no:1,name:`removed`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0});({typeName:`web.document.WebDocumentHost`,methods:{WebViewRpc:{name:`WebViewRpc`,I:H,O:H,kind:M.BiDiStreaming}}}).typeName,{typeName:`web.document.WebDocument`,methods:{WatchWebDocumentStatus:{name:`WatchWebDocumentStatus`,I:ai,O:ci,kind:M.ServerStreaming},CreateWebView:{name:`CreateWebView`,I:li,O:ui,kind:M.Unary},WebViewRpc:{name:`WebViewRpc`,I:H,O:H,kind:M.BiDiStreaming},CreateWebWorker:{name:`CreateWebWorker`,I:di,O:fi,kind:M.Unary},RemoveWebWorker:{name:`RemoveWebWorker`,I:pi,O:mi,kind:M.Unary}}}.typeName;const hi=L({typeName:`web.view.SetRenderModeRequest`,fields:[{no:1,name:`render_mode`,kind:`enum`,T:ue(`web.view.RenderMode`,[[0,`RenderMode_NONE`],[1,`RenderMode_REACT_COMPONENT`],[2,`RenderMode_FUNCTION`],[3,`RenderMode_REACT_CHILDREN`]])},{no:2,name:`script_path`,kind:`scalar`,T:N.STRING},{no:3,name:`props`,kind:`scalar`,T:N.BYTES},{no:4,name:`refresh`,kind:`scalar`,T:N.BOOL},{no:5,name:`frontend_binding`,kind:`message`,T:()=>Gr}],packedByDefault:!0}),gi=j(`web.view.SetRenderModeResponse`,!0),_i=L({typeName:`web.view.HtmlLink`,fields:[{no:1,name:`href`,kind:`scalar`,T:N.STRING},{no:2,name:`rel`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),vi=L({typeName:`web.view.SetHtmlLinksRequest`,fields:[{no:1,name:`clear`,kind:`scalar`,T:N.BOOL},{no:2,name:`remove`,kind:`scalar`,T:N.STRING,repeated:!0},{no:3,name:`set_links`,kind:`map`,K:N.STRING,V:{kind:`message`,T:()=>_i}}],packedByDefault:!0}),yi=j(`web.view.SetHtmlLinksResponse`,!0),bi=j(`web.view.ResetWebViewRequest`,!0),xi=j(`web.view.ResetWebViewResponse`,!0),Si=j(`web.view.RemoveWebViewRequest`,!0),Ci=L({typeName:`web.view.RemoveWebViewResponse`,fields:[{no:1,name:`removed`,kind:`scalar`,T:N.BOOL}],packedByDefault:!0});({typeName:`web.view.WebViewHost`,methods:{}}).typeName,{typeName:`web.view.WebView`,methods:{SetRenderMode:{name:`SetRenderMode`,I:hi,O:gi,kind:M.Unary},SetHtmlLinks:{name:`SetHtmlLinks`,I:vi,O:yi,kind:M.Unary},ResetWebView:{name:`ResetWebView`,I:bi,O:xi,kind:M.Unary},RemoveWebView:{name:`RemoveWebView`,I:Si,O:Ci,kind:M.Unary}}}.typeName,{typeName:`web.view.AccessWebViews`,methods:{WebViewRpc:{name:`WebViewRpc`,I:H,O:H,kind:M.BiDiStreaming}}}.typeName,navigator?.userAgentData?.platform,navigator?.userAgentData?.platform,navigator?.userAgentData?.platform,typeof BLDR_SAUCER<`u`||typeof window<`u`&&window.location?.protocol,import.meta.url||window.location.origin;function wi(e){let t=new AbortController;return e&&(e.aborted?t.abort():e.addEventListener(`abort`,()=>t.abort(),{once:!0})),t}var U=class{resourceRef;constructor(e){this.resourceRef=e}get id(){return this.resourceRef.resourceId}get client(){return this.resourceRef.client}get released(){return this.resourceRef.released}release(){this.resourceRef.release()}[Symbol.dispose](){this.release()}};const Ti={typeName:`kvtx.rpc.Kvtx`,methods:{KvtxTransaction:{name:`KvtxTransaction`,I:he,O:Pe,kind:M.BiDiStreaming},KvtxTransactionRpc:{name:`KvtxTransactionRpc`,I:H,O:H,kind:M.BiDiStreaming},Watch:{name:`Watch`,I:u,O:qe,kind:M.ServerStreaming}}},Ei=Ti.typeName;var Di=class{rpc;service;constructor(e,t){this.service=t?.service||Ei,this.rpc=e,this.KvtxTransaction=this.KvtxTransaction.bind(this),this.KvtxTransactionRpc=this.KvtxTransactionRpc.bind(this),this.Watch=this.Watch.bind(this)}KvtxTransaction(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Ti.methods.KvtxTransaction.name,Bt(he)(e),t||void 0);return F(Pe)(n)}KvtxTransactionRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Ti.methods.KvtxTransactionRpc.name,Bt(H)(e),t||void 0);return F(H)(n)}Watch(e,t){let n=u.create(e),r=this.rpc.serverStreamingRequest(this.service,Ti.methods.Watch.name,u.toBinary(n),t||void 0);return F(qe)(r)}};const W={typeName:`kvtx.rpc.KvtxOps`,methods:{KeyCount:{name:`KeyCount`,I:er,O:ht,kind:M.Unary},KeyData:{name:`KeyData`,I:Qt,O:g,kind:M.Unary},KeyExists:{name:`KeyExists`,I:Qt,O:Te,kind:M.Unary},SetKey:{name:`SetKey`,I:ve,O:xe,kind:M.Unary},DeleteKey:{name:`DeleteKey`,I:Zn,O:Le,kind:M.Unary},ScanPrefix:{name:`ScanPrefix`,I:o,O:Yt,kind:M.ServerStreaming},Iterate:{name:`Iterate`,I:qn,O:Be,kind:M.BiDiStreaming}}},Oi=W.typeName;var ki=class{rpc;service;constructor(e,t){this.service=t?.service||Oi,this.rpc=e,this.KeyCount=this.KeyCount.bind(this),this.KeyData=this.KeyData.bind(this),this.KeyExists=this.KeyExists.bind(this),this.SetKey=this.SetKey.bind(this),this.DeleteKey=this.DeleteKey.bind(this),this.ScanPrefix=this.ScanPrefix.bind(this),this.Iterate=this.Iterate.bind(this)}async KeyCount(e,t){let n=er.create(e),r=await this.rpc.request(this.service,W.methods.KeyCount.name,er.toBinary(n),t||void 0);return ht.fromBinary(r)}async KeyData(e,t){let n=Qt.create(e),r=await this.rpc.request(this.service,W.methods.KeyData.name,Qt.toBinary(n),t||void 0);return g.fromBinary(r)}async KeyExists(e,t){let n=Qt.create(e),r=await this.rpc.request(this.service,W.methods.KeyExists.name,Qt.toBinary(n),t||void 0);return Te.fromBinary(r)}async SetKey(e,t){let n=ve.create(e),r=await this.rpc.request(this.service,W.methods.SetKey.name,ve.toBinary(n),t||void 0);return xe.fromBinary(r)}async DeleteKey(e,t){let n=Zn.create(e),r=await this.rpc.request(this.service,W.methods.DeleteKey.name,Zn.toBinary(n),t||void 0);return Le.fromBinary(r)}ScanPrefix(e,t){let n=o.create(e),r=this.rpc.serverStreamingRequest(this.service,W.methods.ScanPrefix.name,o.toBinary(n),t||void 0);return F(Yt)(r)}Iterate(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,W.methods.Iterate.name,Bt(qn)(e),t||void 0);return F(Be)(n)}},Ai=class extends Error{constructor(){super(`The snapshot exceeds its record or byte limit; use a narrower prefix`),this.name=`KvScanLimitError`}},ji=class extends U{service;constructor(e){super(e),this.service=new Di(e.client)}async keyCount(e){return this.withTransaction(!1,async t=>t.keyCount(e),e)}async scanKeys(e,t){return this.withTransaction(!1,async n=>n.scanKeys(e,t),t)}async*watchKeys(e,t){let n=this.service.Watch({prefix:e,onlyKeys:!1},t);for await(let e of n){if(e.error)throw Error(e.error);yield(e.entries??[]).map(e=>({key:e.key??new Uint8Array,byteLength:e.value?.length??0}))}}async*watchRecords(e,t,n){let r=new AbortController,i=n?AbortSignal.any([r.signal,n]):r.signal;i.throwIfAborted();let a=new Or(void 0,{mostRecentOnly:!0}),o=a.getIterable()[Symbol.asyncIterator](),s=()=>{o.return?.()};i.addEventListener(`abort`,s,{once:!0});let c,l=(async()=>{try{for await(let n of this.service.Watch({prefix:e,maxRecords:BigInt(t.maxRecords),maxBytes:BigInt(t.maxBytes)},i)){if(n.limitExceeded)throw new Ai;if(n.error)throw Error(n.error);let e=(n.entries??[]).map(e=>({key:e.key??new Uint8Array,value:e.value??new Uint8Array})),r=e.reduce((e,t)=>e+t.key.length+t.value.length,0);if(e.length>t.maxRecords||r>t.maxBytes)throw new Ai;a.pushChangeEvent(e)}if(!i.aborted)throw Error(`kv/store: watch ended`)}catch(e){c=e}finally{await o.return?.()}})();try{for(;;){let e=await o.next();if(e.done)break;yield e.value}if(c&&!i.aborted)throw c}finally{r.abort(),i.removeEventListener(`abort`,s),await o.return?.(),await l}}async get(e,t){return this.withTransaction(!1,async n=>n.get(e,t),t)}async exists(e,t){return this.withTransaction(!1,async n=>n.exists(e,t),t)}async withTransaction(e,t,n){let r=await this.openTransaction(e,n);try{let i=await t(r);return e?await r.commit(n):await r.discard(),i}catch(e){throw await r.discard(),e}}async openTransaction(e,t){let n=P({objectMode:!0}),r=this.service.KvtxTransaction(n,t)[Symbol.asyncIterator]();n.push({body:{case:`init`,value:{write:e}}});let i=await Ni(r);if(i.body?.case!==`ack`)throw n.end(),Error(`kv/store: transaction did not return ack`);if(i.body.value.error)throw n.end(),Error(i.body.value.error);let a=i.body.value.transactionId??``;if(!a)throw n.end(),Error(`kv/store: transaction ack missing transaction id`);return new Mi(n,r,new ki(new vn(()=>vr(a,e=>this.service.KvtxTransactionRpc(e,t),!1))))}},Mi=class{requests;responses;ops;released=!1;constructor(e,t,n){this.requests=e,this.responses=t,this.ops=n}async keyCount(e){return(await this.ops.KeyCount({},e)).keyCount??0n}async scanKeys(e,t){let n=[],r=this.ops.ScanPrefix({prefix:e,onlyKeys:!1},t);for await(let e of r){if(e.error)throw Error(e.error);e.key&&n.push({key:e.key,byteLength:e.value?.length??0})}return n}async scanRecords(e,t,n){let r=[],i=0,a=new AbortController,o=n?AbortSignal.any([a.signal,n]):a.signal;try{let n=this.ops.ScanPrefix({prefix:e,onlyKeys:!1},o);for await(let e of n){if(e.error)throw Error(e.error);if(!e.key)continue;let n=e.value??new Uint8Array;if(i+=e.key.length+n.length,r.length>=t.maxRecords||i>t.maxBytes)throw new Ai;r.push({key:e.key,value:n})}return r}finally{a.abort()}}async get(e,t){let n=await this.ops.KeyData({key:e},t);if(n.error)throw Error(n.error);return{data:n.data??new Uint8Array,found:n.found??!1}}async exists(e,t){let n=await this.ops.KeyExists({key:e},t);if(n.error)throw Error(n.error);return n.found??!1}async set(e,t,n){let r=await this.ops.SetKey({key:e,value:t},n);if(r.error)throw Error(r.error)}async delete(e,t){let n=await this.ops.DeleteKey({key:e},t);if(n.error)throw Error(n.error)}async commit(e){if(this.released)throw Error(`kv/store: transaction already released`);this.released=!0,this.requests.push({body:{case:`commit`,value:!0}});try{let e=await Ni(this.responses),t=e.body?.case===`complete`?e.body.value:null;if(!t)throw Error(`kv/store: transaction did not complete`);if(t.error)throw Error(t.error);if(!t.committed)throw Error(`kv/store: transaction discarded`)}finally{this.requests.end(),e?.throwIfAborted()}}async discard(){if(!this.released){this.released=!0,this.requests.push({body:{case:`discard`,value:!0}});try{await Ni(this.responses)}finally{this.requests.end()}}}};async function Ni(e){let t=await e.next();if(t.done)throw Error(`kv/store: transaction stream closed`);return t.value}function Pi(e){return e?`<${e}>`:``}const Fi=`types/`,Ii=`<type>`;function Li(e){return e?Fi+e:``}function Ri(e,t){return{subject:Pi(e),predicate:Ii,obj:Pi(Li(t))}}async function zi(e,t,n){let r=await e.lookupGraphQuads(Pi(t),Ii,void 0,void 0,1,n);if(!r.quads||r.quads.length===0)return``;let i=r.quads[0].obj;if(!i)return Bi(e,t,n);let a;try{a=i.startsWith(`<`)?i.slice(1,-1):i}catch{return``}return a.startsWith(`types/`)?a.slice(6):``}async function Bi(e,t,n){let r=await e.iterateObjects(Fi,!1,n);try{let i=async()=>{if(!await r.next(n))return``;let a=await r.key(n);if(!a.startsWith(`types/`))return i();let o=a.slice(6),s=await e.listObjectsWithType(o,n);return new Set(s).has(t)?o:i()};return await i()}finally{await r.close(n)}}async function Vi(e,t,n,r){let i=!1,a=[];for(let o of t)o.obj===n?i=!0:a.push(e.deleteGraphQuad(o.subject??``,o.predicate??``,o.obj??``,o.label,r));return await Promise.all(a),i}async function Hi(e,t,n,r){if(!t||!n)throw Error(`empty object key or type ID`);let i=Ri(t,n),a=await e.lookupGraphQuads(Pi(t),Ii,void 0,void 0,void 0,r),o=!1;a.quads&&(o=await Vi(e,a.quads,i.obj,r)),await Ui(e,n,r),o||await e.setGraphQuad(i.subject??``,i.predicate??``,i.obj??``,i.label,r)}async function Ui(e,t,n){let r=Li(t),i=await e.getObject(r,n);return i?(i.release(),!1):((await e.createObject(r,{},n)).release(),!0)}var Wi=class extends Error{constructor(){super(`The existing object has a different ObjectType`),this.name=`KvObjectTypeError`}};async function Gi(e,t,n,r){let i=await e.getObject(t,r);if(i){if(i.release(),await zi(e,t,r)!==`kv/store`)throw new Wi}else{if(!n)return;let i=await e.buildStorageCursor(r);try{let n=await i.putBlock({data:oe.toBinary({implType:1})},r),a=await i.getRef(r);if(!n.ref)throw Error(`kv/store: missing initial root`);(await e.createObject(t,{...a.ref,rootRef:n.ref},r)).release(),await Hi(e,t,`kv/store`,r)}finally{i.release()}}let a=await e.accessTypedObject(t,r),o=e.resourceRef.createResource(a.resourceId,ji);if(a.typeId!==`kv/store`)throw o.release(),new Wi;return o}const G={typeName:`s4wave.world.EngineResourceService`,methods:{GetEngineInfo:{name:`GetEngineInfo`,I:be,O:we,kind:M.Unary},GetWorldRootSnapshot:{name:`GetWorldRootSnapshot`,I:nt,O:et,kind:M.Unary},WatchWorldRootSnapshots:{name:`WatchWorldRootSnapshots`,I:xn,O:et,kind:M.ServerStreaming},NewTransaction:{name:`NewTransaction`,I:sn,O:Vt,kind:M.Unary},Sync:{name:`Sync`,I:w,O:D,kind:M.Unary},GetSeqno:{name:`GetSeqno`,I:A,O:at,kind:M.Unary},WaitSeqno:{name:`WaitSeqno`,I:T,O:fe,kind:M.Unary},BuildStorageCursor:{name:`BuildStorageCursor`,I:Ct,O:on,kind:M.Unary},AccessWorldState:{name:`AccessWorldState`,I,O:On,kind:M.Unary}}},Ki=G.typeName;var qi=class{rpc;service;constructor(e,t){this.service=t?.service||Ki,this.rpc=e,this.GetEngineInfo=this.GetEngineInfo.bind(this),this.GetWorldRootSnapshot=this.GetWorldRootSnapshot.bind(this),this.WatchWorldRootSnapshots=this.WatchWorldRootSnapshots.bind(this),this.NewTransaction=this.NewTransaction.bind(this),this.Sync=this.Sync.bind(this),this.GetSeqno=this.GetSeqno.bind(this),this.WaitSeqno=this.WaitSeqno.bind(this),this.BuildStorageCursor=this.BuildStorageCursor.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this)}async GetEngineInfo(e,t){let n=be.create(e),r=await this.rpc.request(this.service,G.methods.GetEngineInfo.name,be.toBinary(n),t||void 0);return we.fromBinary(r)}async GetWorldRootSnapshot(e,t){let n=nt.create(e),r=await this.rpc.request(this.service,G.methods.GetWorldRootSnapshot.name,nt.toBinary(n),t||void 0);return et.fromBinary(r)}WatchWorldRootSnapshots(e,t){let n=xn.create(e),r=this.rpc.serverStreamingRequest(this.service,G.methods.WatchWorldRootSnapshots.name,xn.toBinary(n),t||void 0);return F(et)(r)}async NewTransaction(e,t){let n=sn.create(e),r=await this.rpc.request(this.service,G.methods.NewTransaction.name,sn.toBinary(n),t||void 0);return Vt.fromBinary(r)}async Sync(e,t){let n=w.create(e),r=await this.rpc.request(this.service,G.methods.Sync.name,w.toBinary(n),t||void 0);return D.fromBinary(r)}async GetSeqno(e,t){let n=A.create(e),r=await this.rpc.request(this.service,G.methods.GetSeqno.name,A.toBinary(n),t||void 0);return at.fromBinary(r)}async WaitSeqno(e,t){let n=T.create(e),r=await this.rpc.request(this.service,G.methods.WaitSeqno.name,T.toBinary(n),t||void 0);return fe.fromBinary(r)}async BuildStorageCursor(e,t){let n=Ct.create(e),r=await this.rpc.request(this.service,G.methods.BuildStorageCursor.name,Ct.toBinary(n),t||void 0);return on.fromBinary(r)}async AccessWorldState(e,t){let n=I.create(e),r=await this.rpc.request(this.service,G.methods.AccessWorldState.name,I.toBinary(n),t||void 0);return On.fromBinary(r)}};const K={typeName:`s4wave.world.WorldStateResourceService`,methods:{GetReadOnly:{name:`GetReadOnly`,I:$e,O:ae,kind:M.Unary},Sync:{name:`Sync`,I:w,O:D,kind:M.Unary},GetSeqno:{name:`GetSeqno`,I:A,O:at,kind:M.Unary},WaitSeqno:{name:`WaitSeqno`,I:T,O:fe,kind:M.Unary},BuildStorageCursor:{name:`BuildStorageCursor`,I:Ct,O:on,kind:M.Unary},AccessWorldState:{name:`AccessWorldState`,I,O:On,kind:M.Unary},CreateObject:{name:`CreateObject`,I:ir,O:vt,kind:M.Unary},GetObject:{name:`GetObject`,I:f,O:Xe,kind:M.Unary},IterateObjects:{name:`IterateObjects`,I:In,O:dn,kind:M.Unary},RenameObject:{name:`RenameObject`,I:Ve,O:S,kind:M.Unary},DeleteObject:{name:`DeleteObject`,I:Ue,O:C,kind:M.Unary},SetGraphQuad:{name:`SetGraphQuad`,I:$t,O:s,kind:M.Unary},DeleteGraphQuad:{name:`DeleteGraphQuad`,I:h,O:Xn,kind:M.Unary},LookupGraphQuads:{name:`LookupGraphQuads`,I:Pt,O:yn,kind:M.Unary},LookupGraphQuadsBatch:{name:`LookupGraphQuadsBatch`,I:rn,O:Vn,kind:M.Unary},ListGraphEdgeBuckets:{name:`ListGraphEdgeBuckets`,I:ft,O:hn,kind:M.Unary},ListObjectsWithType:{name:`ListObjectsWithType`,I:jn,O:xt,kind:M.Unary},GetObjectRootRefsBatch:{name:`GetObjectRootRefsBatch`,I:ce,O:Ke,kind:M.Unary},GetObjectMetadataBatch:{name:`GetObjectMetadataBatch`,I:Ie,O:or,kind:M.Unary},GetObjectBodiesBatch:{name:`GetObjectBodiesBatch`,I:O,O:_e,kind:M.Unary},QueryGraphPath:{name:`QueryGraphPath`,I:p,O:Jn,kind:M.Unary},DeleteGraphObject:{name:`DeleteGraphObject`,I:$n,O:ze,kind:M.Unary},ApplyWorldOp:{name:`ApplyWorldOp`,I:_n,O:Nn,kind:M.Unary}}},Ji=K.typeName;var Yi=class{rpc;service;constructor(e,t){this.service=t?.service||Ji,this.rpc=e,this.GetReadOnly=this.GetReadOnly.bind(this),this.Sync=this.Sync.bind(this),this.GetSeqno=this.GetSeqno.bind(this),this.WaitSeqno=this.WaitSeqno.bind(this),this.BuildStorageCursor=this.BuildStorageCursor.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this),this.CreateObject=this.CreateObject.bind(this),this.GetObject=this.GetObject.bind(this),this.IterateObjects=this.IterateObjects.bind(this),this.RenameObject=this.RenameObject.bind(this),this.DeleteObject=this.DeleteObject.bind(this),this.SetGraphQuad=this.SetGraphQuad.bind(this),this.DeleteGraphQuad=this.DeleteGraphQuad.bind(this),this.LookupGraphQuads=this.LookupGraphQuads.bind(this),this.LookupGraphQuadsBatch=this.LookupGraphQuadsBatch.bind(this),this.ListGraphEdgeBuckets=this.ListGraphEdgeBuckets.bind(this),this.ListObjectsWithType=this.ListObjectsWithType.bind(this),this.GetObjectRootRefsBatch=this.GetObjectRootRefsBatch.bind(this),this.GetObjectMetadataBatch=this.GetObjectMetadataBatch.bind(this),this.GetObjectBodiesBatch=this.GetObjectBodiesBatch.bind(this),this.QueryGraphPath=this.QueryGraphPath.bind(this),this.DeleteGraphObject=this.DeleteGraphObject.bind(this),this.ApplyWorldOp=this.ApplyWorldOp.bind(this)}async GetReadOnly(e,t){let n=$e.create(e),r=await this.rpc.request(this.service,K.methods.GetReadOnly.name,$e.toBinary(n),t||void 0);return ae.fromBinary(r)}async Sync(e,t){let n=w.create(e),r=await this.rpc.request(this.service,K.methods.Sync.name,w.toBinary(n),t||void 0);return D.fromBinary(r)}async GetSeqno(e,t){let n=A.create(e),r=await this.rpc.request(this.service,K.methods.GetSeqno.name,A.toBinary(n),t||void 0);return at.fromBinary(r)}async WaitSeqno(e,t){let n=T.create(e),r=await this.rpc.request(this.service,K.methods.WaitSeqno.name,T.toBinary(n),t||void 0);return fe.fromBinary(r)}async BuildStorageCursor(e,t){let n=Ct.create(e),r=await this.rpc.request(this.service,K.methods.BuildStorageCursor.name,Ct.toBinary(n),t||void 0);return on.fromBinary(r)}async AccessWorldState(e,t){let n=I.create(e),r=await this.rpc.request(this.service,K.methods.AccessWorldState.name,I.toBinary(n),t||void 0);return On.fromBinary(r)}async CreateObject(e,t){let n=ir.create(e),r=await this.rpc.request(this.service,K.methods.CreateObject.name,ir.toBinary(n),t||void 0);return vt.fromBinary(r)}async GetObject(e,t){let n=f.create(e),r=await this.rpc.request(this.service,K.methods.GetObject.name,f.toBinary(n),t||void 0);return Xe.fromBinary(r)}async IterateObjects(e,t){let n=In.create(e),r=await this.rpc.request(this.service,K.methods.IterateObjects.name,In.toBinary(n),t||void 0);return dn.fromBinary(r)}async RenameObject(e,t){let n=Ve.create(e),r=await this.rpc.request(this.service,K.methods.RenameObject.name,Ve.toBinary(n),t||void 0);return S.fromBinary(r)}async DeleteObject(e,t){let n=Ue.create(e),r=await this.rpc.request(this.service,K.methods.DeleteObject.name,Ue.toBinary(n),t||void 0);return C.fromBinary(r)}async SetGraphQuad(e,t){let n=$t.create(e),r=await this.rpc.request(this.service,K.methods.SetGraphQuad.name,$t.toBinary(n),t||void 0);return s.fromBinary(r)}async DeleteGraphQuad(e,t){let n=h.create(e),r=await this.rpc.request(this.service,K.methods.DeleteGraphQuad.name,h.toBinary(n),t||void 0);return Xn.fromBinary(r)}async LookupGraphQuads(e,t){let n=Pt.create(e),r=await this.rpc.request(this.service,K.methods.LookupGraphQuads.name,Pt.toBinary(n),t||void 0);return yn.fromBinary(r)}async LookupGraphQuadsBatch(e,t){let n=rn.create(e),r=await this.rpc.request(this.service,K.methods.LookupGraphQuadsBatch.name,rn.toBinary(n),t||void 0);return Vn.fromBinary(r)}async ListGraphEdgeBuckets(e,t){let n=ft.create(e),r=await this.rpc.request(this.service,K.methods.ListGraphEdgeBuckets.name,ft.toBinary(n),t||void 0);return hn.fromBinary(r)}async ListObjectsWithType(e,t){let n=jn.create(e),r=await this.rpc.request(this.service,K.methods.ListObjectsWithType.name,jn.toBinary(n),t||void 0);return xt.fromBinary(r)}async GetObjectRootRefsBatch(e,t){let n=ce.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectRootRefsBatch.name,ce.toBinary(n),t||void 0);return Ke.fromBinary(r)}async GetObjectMetadataBatch(e,t){let n=Ie.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectMetadataBatch.name,Ie.toBinary(n),t||void 0);return or.fromBinary(r)}async GetObjectBodiesBatch(e,t){let n=O.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectBodiesBatch.name,O.toBinary(n),t||void 0);return _e.fromBinary(r)}async QueryGraphPath(e,t){let n=p.create(e),r=await this.rpc.request(this.service,K.methods.QueryGraphPath.name,p.toBinary(n),t||void 0);return Jn.fromBinary(r)}async DeleteGraphObject(e,t){let n=$n.create(e),r=await this.rpc.request(this.service,K.methods.DeleteGraphObject.name,$n.toBinary(n),t||void 0);return ze.fromBinary(r)}async ApplyWorldOp(e,t){let n=_n.create(e),r=await this.rpc.request(this.service,K.methods.ApplyWorldOp.name,_n.toBinary(n),t||void 0);return Nn.fromBinary(r)}};const Xi={typeName:`s4wave.world.WatchWorldStateResourceService`,methods:{WatchWorldState:{name:`WatchWorldState`,I:de,O:rt,kind:M.ServerStreaming}}},Zi=Xi.typeName;var Qi=class{rpc;service;constructor(e,t){this.service=t?.service||Zi,this.rpc=e,this.WatchWorldState=this.WatchWorldState.bind(this)}WatchWorldState(e,t){let n=de.create(e),r=this.rpc.serverStreamingRequest(this.service,Xi.methods.WatchWorldState.name,de.toBinary(n),t||void 0);return F(rt)(r)}};const $i={typeName:`s4wave.world.TxResourceService`,methods:{CommitMutations:{name:`CommitMutations`,I:cn,O:Ut,kind:M.Unary},Commit:{name:`Commit`,I:zt,O:lt,kind:M.Unary},Discard:{name:`Discard`,I:ee,O:Oe,kind:M.Unary}}},ea=$i.typeName;var ta=class{rpc;service;constructor(e,t){this.service=t?.service||ea,this.rpc=e,this.CommitMutations=this.CommitMutations.bind(this),this.Commit=this.Commit.bind(this),this.Discard=this.Discard.bind(this)}async CommitMutations(e,t){let n=cn.create(e),r=await this.rpc.request(this.service,$i.methods.CommitMutations.name,cn.toBinary(n),t||void 0);return Ut.fromBinary(r)}async Commit(e,t){let n=zt.create(e),r=await this.rpc.request(this.service,$i.methods.Commit.name,zt.toBinary(n),t||void 0);return lt.fromBinary(r)}async Discard(e,t){let n=ee.create(e),r=await this.rpc.request(this.service,$i.methods.Discard.name,ee.toBinary(n),t||void 0);return Oe.fromBinary(r)}};const q={typeName:`s4wave.world.ObjectIteratorResourceService`,methods:{Err:{name:`Err`,I:l,O:Zt,kind:M.Unary},Valid:{name:`Valid`,I:Je,O:se,kind:M.Unary},Key:{name:`Key`,I:En,O:Kt,kind:M.Unary},Next:{name:`Next`,I:Gn,O:nr,kind:M.Unary},Seek:{name:`Seek`,I:y,O:Ee,kind:M.Unary},Close:{name:`Close`,I:Ft,O:bn,kind:M.Unary}}},na=q.typeName;var ra=class{rpc;service;constructor(e,t){this.service=t?.service||na,this.rpc=e,this.Err=this.Err.bind(this),this.Valid=this.Valid.bind(this),this.Key=this.Key.bind(this),this.Next=this.Next.bind(this),this.Seek=this.Seek.bind(this),this.Close=this.Close.bind(this)}async Err(e,t){let n=l.create(e),r=await this.rpc.request(this.service,q.methods.Err.name,l.toBinary(n),t||void 0);return Zt.fromBinary(r)}async Valid(e,t){let n=Je.create(e),r=await this.rpc.request(this.service,q.methods.Valid.name,Je.toBinary(n),t||void 0);return se.fromBinary(r)}async Key(e,t){let n=En.create(e),r=await this.rpc.request(this.service,q.methods.Key.name,En.toBinary(n),t||void 0);return Kt.fromBinary(r)}async Next(e,t){let n=Gn.create(e),r=await this.rpc.request(this.service,q.methods.Next.name,Gn.toBinary(n),t||void 0);return nr.fromBinary(r)}async Seek(e,t){let n=y.create(e),r=await this.rpc.request(this.service,q.methods.Seek.name,y.toBinary(n),t||void 0);return Ee.fromBinary(r)}async Close(e,t){let n=Ft.create(e),r=await this.rpc.request(this.service,q.methods.Close.name,Ft.toBinary(n),t||void 0);return bn.fromBinary(r)}};({typeName:`s4wave.world.GraphPathQueryResourceService`,methods:{Next:{name:`Next`,I:Lt,O:st,kind:M.Unary},Close:{name:`Close`,I:Un,O:Dt,kind:M.Unary}}}).typeName;const J={typeName:`s4wave.world.ObjectStateResourceService`,methods:{GetKey:{name:`GetKey`,I:je,O:re,kind:M.Unary},GetRootRef:{name:`GetRootRef`,I:me,O:Cn,kind:M.Unary},SetRootRef:{name:`SetRootRef`,I:Se,O:ke,kind:M.Unary},AccessWorldState:{name:`AccessWorldState`,I,O:On,kind:M.Unary},ApplyObjectOp:{name:`ApplyObjectOp`,I:Jt,O:mt,kind:M.Unary},IncrementRev:{name:`IncrementRev`,I:a,O:kt,kind:M.Unary},WaitRev:{name:`WaitRev`,I:We,O:Ze,kind:M.Unary}}},ia=J.typeName;var aa=class{rpc;service;constructor(e,t){this.service=t?.service||ia,this.rpc=e,this.GetKey=this.GetKey.bind(this),this.GetRootRef=this.GetRootRef.bind(this),this.SetRootRef=this.SetRootRef.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this),this.ApplyObjectOp=this.ApplyObjectOp.bind(this),this.IncrementRev=this.IncrementRev.bind(this),this.WaitRev=this.WaitRev.bind(this)}async GetKey(e,t){let n=je.create(e),r=await this.rpc.request(this.service,J.methods.GetKey.name,je.toBinary(n),t||void 0);return re.fromBinary(r)}async GetRootRef(e,t){let n=me.create(e),r=await this.rpc.request(this.service,J.methods.GetRootRef.name,me.toBinary(n),t||void 0);return Cn.fromBinary(r)}async SetRootRef(e,t){let n=Se.create(e),r=await this.rpc.request(this.service,J.methods.SetRootRef.name,Se.toBinary(n),t||void 0);return ke.fromBinary(r)}async AccessWorldState(e,t){let n=I.create(e),r=await this.rpc.request(this.service,J.methods.AccessWorldState.name,I.toBinary(n),t||void 0);return On.fromBinary(r)}async ApplyObjectOp(e,t){let n=Jt.create(e),r=await this.rpc.request(this.service,J.methods.ApplyObjectOp.name,Jt.toBinary(n),t||void 0);return mt.fromBinary(r)}async IncrementRev(e,t){let n=a.create(e),r=await this.rpc.request(this.service,J.methods.IncrementRev.name,a.toBinary(n),t||void 0);return kt.fromBinary(r)}async WaitRev(e,t){let n=We.create(e),r=await this.rpc.request(this.service,J.methods.WaitRev.name,We.toBinary(n),t||void 0);return Ze.fromBinary(r)}};const oa={typeName:`s4wave.world.TypedObjectResourceService`,methods:{AccessTypedObject:{name:`AccessTypedObject`,I:jt,O:Rn,kind:M.Unary}}},sa=oa.typeName;var ca=class{rpc;service;constructor(e,t){this.service=t?.service||sa,this.rpc=e,this.AccessTypedObject=this.AccessTypedObject.bind(this)}async AccessTypedObject(e,t){let n=jt.create(e),r=await this.rpc.request(this.service,oa.methods.AccessTypedObject.name,jt.toBinary(n),t||void 0);return Rn.fromBinary(r)}};const Y={typeName:`s4wave.bucket_lookup.BucketLookupCursorResourceService`,methods:{GetRef:{name:`GetRef`,I:Hn,O:Et,kind:M.Unary},FollowRef:{name:`FollowRef`,I:qt,O:pt,kind:M.Unary},GetBlock:{name:`GetBlock`,I:St,O:an,kind:M.Unary},PutBlock:{name:`PutBlock`,I:ct,O:Kn,kind:M.Unary},PutBlockBatch:{name:`PutBlockBatch`,I:Ht,O:Rt,kind:M.Unary},GetBlockExistsBatch:{name:`GetBlockExistsBatch`,I:gn,O:Mn,kind:M.Unary},BuildTransaction:{name:`BuildTransaction`,I:At,O:Ln,kind:M.Unary},BuildTransactionAtRef:{name:`BuildTransactionAtRef`,I:Me,O:r,kind:M.Unary},Clone:{name:`Clone`,I:fn,O:Dn,kind:M.Unary},Release:{name:`Release`,I:rr,O:_t,kind:M.Unary},Unmarshal:{name:`Unmarshal`,I:Qn,O:Re,kind:M.Unary}}},la=Y.typeName;var ua=class{rpc;service;constructor(e,t){this.service=t?.service||la,this.rpc=e,this.GetRef=this.GetRef.bind(this),this.FollowRef=this.FollowRef.bind(this),this.GetBlock=this.GetBlock.bind(this),this.PutBlock=this.PutBlock.bind(this),this.PutBlockBatch=this.PutBlockBatch.bind(this),this.GetBlockExistsBatch=this.GetBlockExistsBatch.bind(this),this.BuildTransaction=this.BuildTransaction.bind(this),this.BuildTransactionAtRef=this.BuildTransactionAtRef.bind(this),this.Clone=this.Clone.bind(this),this.Release=this.Release.bind(this),this.Unmarshal=this.Unmarshal.bind(this)}async GetRef(e,t){let n=Hn.create(e),r=await this.rpc.request(this.service,Y.methods.GetRef.name,Hn.toBinary(n),t||void 0);return Et.fromBinary(r)}async FollowRef(e,t){let n=qt.create(e),r=await this.rpc.request(this.service,Y.methods.FollowRef.name,qt.toBinary(n),t||void 0);return pt.fromBinary(r)}async GetBlock(e,t){let n=St.create(e),r=await this.rpc.request(this.service,Y.methods.GetBlock.name,St.toBinary(n),t||void 0);return an.fromBinary(r)}async PutBlock(e,t){let n=ct.create(e),r=await this.rpc.request(this.service,Y.methods.PutBlock.name,ct.toBinary(n),t||void 0);return Kn.fromBinary(r)}async PutBlockBatch(e,t){let n=Ht.create(e),r=await this.rpc.request(this.service,Y.methods.PutBlockBatch.name,Ht.toBinary(n),t||void 0);return Rt.fromBinary(r)}async GetBlockExistsBatch(e,t){let n=gn.create(e),r=await this.rpc.request(this.service,Y.methods.GetBlockExistsBatch.name,gn.toBinary(n),t||void 0);return Mn.fromBinary(r)}async BuildTransaction(e,t){let n=At.create(e),r=await this.rpc.request(this.service,Y.methods.BuildTransaction.name,At.toBinary(n),t||void 0);return Ln.fromBinary(r)}async BuildTransactionAtRef(e,t){let n=Me.create(e),i=await this.rpc.request(this.service,Y.methods.BuildTransactionAtRef.name,Me.toBinary(n),t||void 0);return r.fromBinary(i)}async Clone(e,t){let n=fn.create(e),r=await this.rpc.request(this.service,Y.methods.Clone.name,fn.toBinary(n),t||void 0);return Dn.fromBinary(r)}async Release(e,t){let n=rr.create(e),r=await this.rpc.request(this.service,Y.methods.Release.name,rr.toBinary(n),t||void 0);return _t.fromBinary(r)}async Unmarshal(e,t){let n=Qn.create(e),r=await this.rpc.request(this.service,Y.methods.Unmarshal.name,Qn.toBinary(n),t||void 0);return Re.fromBinary(r)}};const X={typeName:`s4wave.block.cursor.BlockCursorResourceService`,methods:{Fetch:{name:`Fetch`,I:ge,O:Fe,kind:M.Unary},SetBlock:{name:`SetBlock`,I:An,O:bt,kind:M.Unary},FollowRef:{name:`FollowRef`,I:ar,O:d,kind:M.Unary},GetRef:{name:`GetRef`,I:it,O:tt,kind:M.Unary},IsDirty:{name:`IsDirty`,I:ot,O:Ne,kind:M.Unary},MarkDirty:{name:`MarkDirty`,I:Fn,O:un,kind:M.Unary},GetBlock:{name:`GetBlock`,I:ie,O:pe,kind:M.Unary},Unmarshal:{name:`Unmarshal`,I:Tt,O:Nt,kind:M.Unary},IsSubBlock:{name:`IsSubBlock`,I:i,O:Ot,kind:M.Unary},FollowSubBlock:{name:`FollowSubBlock`,I:Ye,O:E,kind:M.Unary},SetAsSubBlock:{name:`SetAsSubBlock`,I:dt,O:mn,kind:M.Unary},ClearRef:{name:`ClearRef`,I:en,O:c,kind:M.Unary},ClearAllRefs:{name:`ClearAllRefs`,I:b,O:De,kind:M.Unary},SetRef:{name:`SetRef`,I:nn,O:Bn,kind:M.Unary},GetExistingRef:{name:`GetExistingRef`,I:Sn,O:k,kind:M.Unary},GetAllRefs:{name:`GetAllRefs`,I:Ge,O:Qe,kind:M.Unary},Detach:{name:`Detach`,I:Ce,O:Ae,kind:M.Unary},DetachTransaction:{name:`DetachTransaction`,I:ne,O:le,kind:M.Unary},DetachRecursive:{name:`DetachRecursive`,I:Xt,O:ye,kind:M.Unary},Parents:{name:`Parents`,I:Tn,O:Gt,kind:M.Unary}}},da=X.typeName;var fa=class{rpc;service;constructor(e,t){this.service=t?.service||da,this.rpc=e,this.Fetch=this.Fetch.bind(this),this.SetBlock=this.SetBlock.bind(this),this.FollowRef=this.FollowRef.bind(this),this.GetRef=this.GetRef.bind(this),this.IsDirty=this.IsDirty.bind(this),this.MarkDirty=this.MarkDirty.bind(this),this.GetBlock=this.GetBlock.bind(this),this.Unmarshal=this.Unmarshal.bind(this),this.IsSubBlock=this.IsSubBlock.bind(this),this.FollowSubBlock=this.FollowSubBlock.bind(this),this.SetAsSubBlock=this.SetAsSubBlock.bind(this),this.ClearRef=this.ClearRef.bind(this),this.ClearAllRefs=this.ClearAllRefs.bind(this),this.SetRef=this.SetRef.bind(this),this.GetExistingRef=this.GetExistingRef.bind(this),this.GetAllRefs=this.GetAllRefs.bind(this),this.Detach=this.Detach.bind(this),this.DetachTransaction=this.DetachTransaction.bind(this),this.DetachRecursive=this.DetachRecursive.bind(this),this.Parents=this.Parents.bind(this)}async Fetch(e,t){let n=ge.create(e),r=await this.rpc.request(this.service,X.methods.Fetch.name,ge.toBinary(n),t||void 0);return Fe.fromBinary(r)}async SetBlock(e,t){let n=An.create(e),r=await this.rpc.request(this.service,X.methods.SetBlock.name,An.toBinary(n),t||void 0);return bt.fromBinary(r)}async FollowRef(e,t){let n=ar.create(e),r=await this.rpc.request(this.service,X.methods.FollowRef.name,ar.toBinary(n),t||void 0);return d.fromBinary(r)}async GetRef(e,t){let n=it.create(e),r=await this.rpc.request(this.service,X.methods.GetRef.name,it.toBinary(n),t||void 0);return tt.fromBinary(r)}async IsDirty(e,t){let n=ot.create(e),r=await this.rpc.request(this.service,X.methods.IsDirty.name,ot.toBinary(n),t||void 0);return Ne.fromBinary(r)}async MarkDirty(e,t){let n=Fn.create(e),r=await this.rpc.request(this.service,X.methods.MarkDirty.name,Fn.toBinary(n),t||void 0);return un.fromBinary(r)}async GetBlock(e,t){let n=ie.create(e),r=await this.rpc.request(this.service,X.methods.GetBlock.name,ie.toBinary(n),t||void 0);return pe.fromBinary(r)}async Unmarshal(e,t){let n=Tt.create(e),r=await this.rpc.request(this.service,X.methods.Unmarshal.name,Tt.toBinary(n),t||void 0);return Nt.fromBinary(r)}async IsSubBlock(e,t){let n=i.create(e),r=await this.rpc.request(this.service,X.methods.IsSubBlock.name,i.toBinary(n),t||void 0);return Ot.fromBinary(r)}async FollowSubBlock(e,t){let n=Ye.create(e),r=await this.rpc.request(this.service,X.methods.FollowSubBlock.name,Ye.toBinary(n),t||void 0);return E.fromBinary(r)}async SetAsSubBlock(e,t){let n=dt.create(e),r=await this.rpc.request(this.service,X.methods.SetAsSubBlock.name,dt.toBinary(n),t||void 0);return mn.fromBinary(r)}async ClearRef(e,t){let n=en.create(e),r=await this.rpc.request(this.service,X.methods.ClearRef.name,en.toBinary(n),t||void 0);return c.fromBinary(r)}async ClearAllRefs(e,t){let n=b.create(e),r=await this.rpc.request(this.service,X.methods.ClearAllRefs.name,b.toBinary(n),t||void 0);return De.fromBinary(r)}async SetRef(e,t){let n=nn.create(e),r=await this.rpc.request(this.service,X.methods.SetRef.name,nn.toBinary(n),t||void 0);return Bn.fromBinary(r)}async GetExistingRef(e,t){let n=Sn.create(e),r=await this.rpc.request(this.service,X.methods.GetExistingRef.name,Sn.toBinary(n),t||void 0);return k.fromBinary(r)}async GetAllRefs(e,t){let n=Ge.create(e),r=await this.rpc.request(this.service,X.methods.GetAllRefs.name,Ge.toBinary(n),t||void 0);return Qe.fromBinary(r)}async Detach(e,t){let n=Ce.create(e),r=await this.rpc.request(this.service,X.methods.Detach.name,Ce.toBinary(n),t||void 0);return Ae.fromBinary(r)}async DetachTransaction(e,t){let n=ne.create(e),r=await this.rpc.request(this.service,X.methods.DetachTransaction.name,ne.toBinary(n),t||void 0);return le.fromBinary(r)}async DetachRecursive(e,t){let n=Xt.create(e),r=await this.rpc.request(this.service,X.methods.DetachRecursive.name,Xt.toBinary(n),t||void 0);return ye.fromBinary(r)}async Parents(e,t){let n=Tn.create(e),r=await this.rpc.request(this.service,X.methods.Parents.name,Tn.toBinary(n),t||void 0);return Gt.fromBinary(r)}},pa=class e extends U{service;constructor(e){super(e),this.service=new fa(e.client)}async fetch(e){return await this.service.Fetch({},e)}async setBlock(e,t){await this.service.SetBlock(e,t)}async followRef(t,n){let r=await this.service.FollowRef(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async getRef(e){return await this.service.GetRef({},e)}async isDirty(e){return await this.service.IsDirty({},e)}async markDirty(e){await this.service.MarkDirty({},e)}async getBlock(e){return await this.service.GetBlock({},e)}async unmarshal(e={},t){return await this.service.Unmarshal(e,t)}async isSubBlock(e){return await this.service.IsSubBlock({},e)}async followSubBlock(t,n){let r=await this.service.FollowSubBlock(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async setAsSubBlock(e,t){await this.service.SetAsSubBlock(e,t)}async clearRef(e,t){await this.service.ClearRef(e,t)}async clearAllRefs(e){await this.service.ClearAllRefs({},e)}async setRef(e,t){await this.service.SetRef(e,t)}async getExistingRef(t,n){let r=await this.service.GetExistingRef(t,n);return r.resourceId?this.resourceRef.createResource(r.resourceId,e):null}async getAllRefs(e,t){return await this.service.GetAllRefs(e,t)}async detach(t,n){let r=await this.service.Detach(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async detachTransaction(t){let n=await this.service.DetachTransaction({},t);return this.resourceRef.createResource(n.resourceId??0,e)}async detachRecursive(t,n){let r=await this.service.DetachRecursive(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async parents(e){return await this.service.Parents({},e)}};const ma={typeName:`s4wave.block.transaction.BlockTransactionResourceService`,methods:{Write:{name:`Write`,I:He,O:te,kind:M.Unary},GetRootCursor:{name:`GetRootCursor`,I:m,O:Yn,kind:M.Unary}}},ha=ma.typeName;var ga=class{rpc;service;constructor(e,t){this.service=t?.service||ha,this.rpc=e,this.Write=this.Write.bind(this),this.GetRootCursor=this.GetRootCursor.bind(this)}async Write(e,t){let n=He.create(e),r=await this.rpc.request(this.service,ma.methods.Write.name,He.toBinary(n),t||void 0);return te.fromBinary(r)}async GetRootCursor(e,t){let n=m.create(e),r=await this.rpc.request(this.service,ma.methods.GetRootCursor.name,m.toBinary(n),t||void 0);return Yn.fromBinary(r)}},_a=class extends U{service;constructor(e){super(e),this.service=new ga(e.client)}async write(e,t){return await this.service.Write(e,t)}async getRootCursor(e){let t=await this.service.GetRootCursor({},e);return this.resourceRef.createResource(t.resourceId??0,pa)}};function va(e){return!!e?.hash?.hash?.length}var ya=class e extends U{service;constructor(e){super(e),this.service=new ua(e.client)}async getRef(e){return await this.service.GetRef({},e)}async followRef(t,n){let r=await this.service.FollowRef(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async getBlock(e,t){if(!va(e.ref)){let n=await this.getRef(t);return await this.service.GetBlock({...e,ref:n.ref?.rootRef},t)}return await this.service.GetBlock(e,t)}async putBlock(e,t){return await this.service.PutBlock(e,t)}async putBlockBatch(e,t){return await this.service.PutBlockBatch(e,t)}async getBlockExistsBatch(e,t){return await this.service.GetBlockExistsBatch(e,t)}async buildTransaction(e,t){let n=await this.service.BuildTransaction(e,t);return{transaction:this.resourceRef.createResource(n.transactionResourceId??0,_a),cursor:this.resourceRef.createResource(n.cursorResourceId??0,pa)}}async buildTransactionAtRef(e,t){let n=await this.service.BuildTransactionAtRef(e,t);return{transaction:this.resourceRef.createResource(n.transactionResourceId??0,_a),cursor:this.resourceRef.createResource(n.cursorResourceId??0,pa)}}async clone(t,n){let r=await this.service.Clone(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}release(e){this.service.Release({},e).catch(()=>{}),super.release()}async unmarshal(e,t){return await this.service.Unmarshal(e,t)}},ba=class extends U{service;objectKey;constructor(e,t){super(e),this.service=new aa(e.client),this.objectKey=t?.objectKey??``}getKey(){return this.objectKey}async getRootRef(e){return await this.service.GetRootRef({},e)}async setRootRef(e,t){return await this.service.SetRootRef({rootRef:e},t)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ya)}async applyObjectOp(e,t,n,r){return await this.service.ApplyObjectOp({opTypeId:e,opData:t,opSender:n},r)}async incrementRev(e){return await this.service.IncrementRev({},e)}async waitRev(e,t,n){return await this.service.WaitRev({rev:e,ignoreNotFound:t},n)}getDebugInfo(){return{label:this.objectKey||void 0}}},xa=class extends U{service;constructor(e){super(e),this.service=new ra(e.client)}async err(e){return(await this.service.Err({},e)).error||null}async valid(e){return(await this.service.Valid({},e)).valid??!1}async key(e){return(await this.service.Key({},e)).objectKey??``}async next(e){return(await this.service.Next({},e)).valid??!1}async seek(e,t){await this.service.Seek({objectKey:e},t)}async close(e){await this.service.Close({},e)}},Sa=class extends U{service;readOnly;constructor(e,t){super(e),this.service=new Yi(e.client),this.readOnly=t?.readOnly??!1}getResourceRef(){return this.resourceRef}getReadOnly(){return this.readOnly}async getSeqno(e){return{seqno:(await this.service.GetSeqno({},e)).seqno??0n}}async waitSeqno(e,t){return{seqno:(await this.service.WaitSeqno({seqno:e},t)).seqno??0n}}async buildStorageCursor(e){let t=await this.service.BuildStorageCursor({},e);return this.resourceRef.createResource(t.resourceId??0,ya)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ya)}async createObject(e,t,n){let r=await this.service.CreateObject({objectKey:e,rootRef:t},n);return this.resourceRef.createResource(r.resourceId??0,ba,{objectKey:r.objectKey})}async getObject(e,t){let n=await this.service.GetObject({objectKey:e},t);return n.found?this.resourceRef.createResource(n.resourceId??0,ba,{objectKey:n.objectKey}):null}async iterateObjects(e,t,n){let r=await this.service.IterateObjects({prefix:e,reversed:t},n);return this.resourceRef.createResource(r.resourceId??0,xa)}async renameObject(e,t,n){let r=Ca(n),i=await this.service.RenameObject({oldObjectKey:e,newObjectKey:t,descendants:r.descendants},r.abortSignal);return this.resourceRef.createResource(i.resourceId??0,ba,{objectKey:i.objectKey})}async deleteObject(e,t){return{deleted:(await this.service.DeleteObject({objectKey:e},t)).deleted??!1}}async setGraphQuad(e,t,n,r,i){await this.service.SetGraphQuad({quad:{subject:e,predicate:t,obj:n,label:r}},i)}async deleteGraphQuad(e,t,n,r,i){await this.service.DeleteGraphQuad({quad:{subject:e,predicate:t,obj:n,label:r}},i)}async lookupGraphQuads(e,t,n,r,i,a){return await this.service.LookupGraphQuads({filter:{subject:e,predicate:t,obj:n,label:r},limit:i},a)}async listGraphEdgeBuckets(e,t,n={}){return await this.service.ListGraphEdgeBuckets({originObjectKeys:e,predicate:n.predicate,limitPerOrigin:t,direction:n.direction},n.abortSignal)}async listObjectsWithType(e,t){return(await this.service.ListObjectsWithType({typeId:e},t)).objectKeys??[]}async deleteGraphObject(e,t){await this.service.DeleteGraphObject({objectKey:e},t)}async applyWorldOp(e,t,n,r){let i=await this.service.ApplyWorldOp({opTypeId:e,opData:t,opSender:n},r);return{seqno:i.seqno??0n,sysErr:i.sysErr??!1}}async accessTypedObject(e,t){let n=await new ca(this.resourceRef.client).AccessTypedObject({objectKey:e},t);return{resourceId:n.resourceId??0,typeId:n.typeId??``}}getDebugInfo(){return{label:this.readOnly?`(read-only)`:void 0}}};function Ca(e){return e?e instanceof AbortSignal?{abortSignal:e}:e:{}}var wa=class extends Sa{txService;constructor(e,t){super(e,t),this.txService=new ta(e.client)}async commit(e){await this.txService.Commit({},e)}async discard(e){await this.txService.Discard({},e)}},Ta=class extends U{service;watchService;constructor(e){super(e),this.service=new qi(e.client),this.watchService=new Qi(e.client)}async getEngineInfo(e){return await this.service.GetEngineInfo({},e)}async sync(e){return(await this.service.Sync({},e)).fenced??!1}async getWorldRootSnapshot(e){return await this.service.GetWorldRootSnapshot({},e)}watchWorldRootSnapshots(e){return this.service.WatchWorldRootSnapshots({},e)}async newTransaction(e,t){let n=await this.service.NewTransaction({write:e},t);return this.resourceRef.createResource(n.resourceId??0,wa,{readOnly:n.readOnly})}async getSeqno(e){return await this.service.GetSeqno({},e)}async waitSeqno(e,t){return await this.service.WaitSeqno({seqno:e},t)}async buildStorageCursor(e){let t=await this.service.BuildStorageCursor({},e);return this.resourceRef.createResource(t.resourceId??0,ya)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ya)}async accessTypedObject(e,t){let n=await new ca(this.resourceRef.client).AccessTypedObject({objectKey:e},t);return{resourceId:n.resourceId??0,typeId:n.typeId??``}}watchWorldState(e){return Ea(this.watchService,this.resourceRef,e)}};function Ea(e,t,n){let r=!1,i=[],a=new AbortController,o=()=>{r=!0,a.abort(),i.forEach(e=>e[Symbol.dispose]()),i.length=0};return(async()=>{try{let o=e.WatchWorldState({},a.signal);for await(let e of o){if(r)break;i.forEach(e=>e[Symbol.dispose]()),i.length=0;let a=new AbortController,o=t.createResource(e.resourceId??0,Sa),s=e=>(e&&i.push(e),e);try{await n(o,a.signal,s)}catch(e){e instanceof Error&&e.name!==`AbortError`&&console.error(`Error in watchWorldState callback:`,e)}finally{o[Symbol.dispose]()}}}catch(e){!r&&!(e instanceof Error&&e.name===`AbortError`)&&console.error(`WatchWorldState stream error:`,e)}finally{o()}})(),o}const Da=`sync/v1/metadata`,Oa=`sync/v1/`,ka=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});function Aa(e,t,n){return`${Oa}${Na(`application`,e)}/${Na(`scope`,t)}/collections/${Na(`collection`,n)}`}function ja(e,t){return`${Oa}${Na(`application`,e)}/${Na(`scope`,t)}/receipts`}function Ma(e){return Pa(`record key`,e,1024)}function Na(e,t){return Fa(Pa(e,t,256))}function Pa(e,t,n){if(t.length===0)throw TypeError(`invalid ${e}: must be nonempty`);if(!t.isWellFormed())throw TypeError(`invalid ${e}: must be well-formed Unicode`);let r=ka.encode(t);if(r.length>n)throw TypeError(`invalid ${e}: exceeds ${n} UTF-8 bytes`);return r}function Fa(e){let t=``;for(let n of e)t+=(n>>4).toString(16)+(n&15).toString(16);return t}function Ia(e){if(!e.id||!Number.isSafeInteger(e.version)||e.version<1||e.version>4294967295)throw new R(`VALIDATION`,`Application ID and positive version are required`);return e}async function La(e,t,n){try{z(t);let r=await e[`~standard`].validate(t);if(r.issues)throw new R(`VALIDATION`,`${n} does not match its schema`);return z(r.value),r.value}catch(e){throw e instanceof R?e:new R(`VALIDATION`,`${n} must be a valid JSON value matching its schema`)}}const Ra=new TextEncoder,za=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),Ba=Ra.encode(`version`);var Va=class{options;schema;signal;limits;engine;controller=new AbortController;active=new Set;queries=new Map;closing;constructor(e){this.options=e,this.schema=Ia(e.schema);try{ja(this.schema.id,`schema`);for(let[e,t]of Object.entries(this.schema.collections))if(Aa(this.schema.id,`schema`,e),t[`~standard`]?.version!==1)throw Error(`invalid validator`);for(let[t,n]of Object.entries(this.schema.mutations))if(!Object.hasOwn(e.mutations,t)||n.input[`~standard`]?.version!==1||n.output[`~standard`]?.version!==1)throw Error(`invalid mutation`)}catch{throw new R(`VALIDATION`,`Schema requires valid names, Standard Schema v1 validators, and every mutation handler`)}this.signal=this.controller.signal,this.limits={maxRecords:e.limits?.maxRecords??1e4,maxSnapshotBytes:e.limits?.maxSnapshotBytes??8388608,maxRecordBytes:e.limits?.maxRecordBytes??262144};for(let e of Object.values(this.limits))if(!Number.isSafeInteger(e)||e<1)throw new R(`VALIDATION`,`Limits must be positive integers`);this.engine=new Ta(e.engine.resourceRef.createRef(e.engine.id))}async initialize(e){let t=new Ha(await this.engine.newTransaction(!0,this.signal),!0,this.signal);try{let n=await t.store(Da);if(!n)throw Error(`missing metadata store`);let r=await n.get(Ba,this.signal),i=r.found?V(r.data):void 0;if(i&&i.application!==this.schema.id)throw new R(`SCHEMA_MISMATCH`,`This dataset belongs to a different application`);if(i&&i.version!==this.schema.version){if(!e||e.from!==i.version)throw new R(`SCHEMA_MISMATCH`,`Stored version differs; supply an explicit maintenance migration`);await e.run({signal:this.signal,scopes:async()=>(await n.scanRecords(Ra.encode(`scope/`),{maxRecords:this.limits.maxRecords,maxBytes:this.limits.maxSnapshotBytes},this.signal)).map(e=>V(e.value)),scope:e=>this.collections(t,{subject:`admin`,scope:e},!0,[])})}if(await n.set(Ba,B({application:this.schema.id,version:this.schema.version}),this.signal),await t.commit(),!await this.engine.sync())throw new R(`STORAGE`,`Durable storage is unavailable`)}finally{await t.release()}}async authorize(e,t,n,r=!1){if(this.checkPrincipal(e),!Object.hasOwn(this.schema.collections,t))throw new R(`MISSING_COLLECTION`,`Collection is not declared`);if(!r&&!await this.options.authorize({principal:e,scope:e.scope,collection:t,action:n}))throw new R(`DENIED`,`Collection ${n} is not authorized`)}async openCollection(e,t){try{await this.authorize(e,t,`read`)}catch(n){if(!(n instanceof R)||n.code!==`DENIED`)throw n;await this.authorize(e,t,`write`)}}execute(e,t,n={},r=!1){if(this.closing)return Promise.reject(new R(`CLOSED`,`Server is closed`));let i=this.run(e,t,n,r);return this.active.add(i),i.finally(()=>this.active.delete(i)).catch(()=>{}),i}close(){return this.closing??=(async()=>{this.controller.abort(new R(`CLOSED`,`Server is closing`)),await Promise.allSettled(this.active),this.engine.release()})(),this.closing}async*watch(e,t,n,r){if(this.closing)throw new R(`CLOSED`,`Server is closed`);let i=AbortSignal.any([this.signal,r,...e.signal?[e.signal]:[]]),a=Promise.withResolvers();this.active.add(a.promise);let o,s,c=()=>{s?.return?.()},l=z([e.scope,t,n]);try{for(await this.authorize(e,t,`read`),i.throwIfAborted(),o=this.queries.get(l)??this.startQuery(l,e.scope,t,n),o.users++,s=o.state.getIterable()[Symbol.asyncIterator](),i.addEventListener(`abort`,c,{once:!0});;){let n=await s.next();if(n.done||i.aborted)break;if(await this.authorize(e,t,`read`),i.throwIfAborted(),`error`in n.value)throw n.value.error;yield n.value.entries}}finally{i.removeEventListener(`abort`,c),await s?.return?.(),o&&--o.users===0&&(this.queries.get(l)===o&&this.queries.delete(l),o.controller.abort()),a.resolve(),this.active.delete(a.promise)}}startQuery(e,t,n,r){let i,a={controller:new AbortController,state:new Or(async()=>i,{mostRecentOnly:!0}),users:0};this.queries.set(e,a);let o=AbortSignal.any([this.signal,a.controller.signal]),s=e=>{i=e,a.state.pushChangeEvent(e)},c=(async()=>{try{for await(let e of this.watchQuery(t,n,r,o))s({entries:e})}catch(e){o.aborted||s({error:Sr(e)})}finally{this.queries.get(e)===a&&this.queries.delete(e)}})();return this.active.add(c),c.finally(()=>this.active.delete(c)).catch(()=>{}),a}async*watchQuery(e,t,n,r){let i;try{let a=Aa(this.schema.id,e,t),o=n?this.recordKey(n):new Uint8Array,s=!1;for(;;){r.throwIfAborted();let e=await this.engine.getSeqno(r),t=await this.engine.newTransaction(!1,r),n=!1;try{let e=await t.getObject(a,r);if(n=e!==null,e?.release(),n&&await zi(t,a,r)!==`kv/store`)throw new Wi}finally{try{await t.discard()}finally{t.release()}}if(n)break;s||=(yield[],!0),await this.engine.waitSeqno((e.seqno??0n)+1n,r)}let c=await this.engine.accessTypedObject(a,r);i=this.engine.resourceRef.createResource(c.resourceId,ji);for await(let e of i.watchRecords(o,{maxRecords:this.limits.maxRecords,maxBytes:this.limits.maxSnapshotBytes},r))yield e.map(e=>({key:za.decode(e.key),value:V(e.value)}))}catch(e){if(e instanceof Ai)throw new R(`QUERY_LIMIT`,e.message);if(!r.aborted)throw Sr(e)}finally{i?.release()}}checkPrincipal(e){if(!e.subject||!e.scope||e.signal?.aborted||e.expiresAt!==void 0&&(!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()))throw new R(`AUTHENTICATION`,`Authentication is no longer valid`);try{if(ja(this.schema.id,e.scope),Ma(e.subject).length>256)throw Error(`invalid subject`)}catch{throw new R(`AUTHENTICATION`,`Principal subject and scope must be valid identities within 256 UTF-8 bytes`)}}async run(e,t,n,r){let i,a=!1,o=t.kind!==`get`&&t.kind!==`scan`,s=n.requestId??ur(),c=AbortSignal.any([this.signal,...[e.signal,n.signal].filter(e=>!!e)]);try{if(this.checkPrincipal(e),c.throwIfAborted(),!s||s.length>128)throw new R(`VALIDATION`,`Request ID must contain 1 to 128 characters`);let n=lr(`sha256`).update(z({version:this.schema.version,operation:t})).digest(`hex`);i=new Ha(await this.engine.newTransaction(o,c),o,c);let l=[],u=this.collections(i,e,r,l);`collection`in t&&await this.authorize(e,t.collection,o?`write`:`read`,r);let d=o?await i.store(ja(this.schema.id,e.scope)):void 0,f=Ra.encode(z([e.subject,s]));if(d){let t=await d.get(f,c);if(t.found){let a=V(t.data);if(a.fingerprint!==n)throw new R(`CONFLICT`,`Request ID was already used for different input`,s);if(await Promise.all(a.accesses.map(t=>this.authorize(e,t.collection,t.action,r))),await i.release(),i=void 0,!await this.engine.sync())throw new R(`STORAGE`,`Durable storage is unavailable`);return a.result}}let p;if(t.kind===`mutate`){let n=Object.hasOwn(this.schema.mutations,t.name)?this.schema.mutations[t.name]:void 0,r=Object.hasOwn(this.options.mutations,t.name)?this.options.mutations[t.name]:void 0;if(!n||!r)throw new R(`VALIDATION`,`Mutation is not declared and implemented`);let i=await La(n.input,t.input,`Mutation input`),a=await r({...u,principal:e,scope:e.scope,signal:c},i);p=await La(n.output,a,`Mutation output`)}else{let e=u.collection(t.collection);switch(t.kind){case`get`:{let n=await e.get(t.key);p=n===void 0?{found:!1}:{found:!0,value:n};break}case`scan`:p=await e.scan({prefix:t.prefix});break;case`put`:await e.put(t.key,t.value),p=null;break;case`delete`:await e.delete(t.key),p=null}}if(o&&(await(await i.store(Da)).set(Ra.encode(`scope/${z(e.scope)}`),B(e.scope),c),await d.set(f,B({fingerprint:n,result:p,accesses:l}),c),this.checkPrincipal(e),c.throwIfAborted(),await i.commit(()=>{a=!0}),!await this.engine.sync()))throw new R(`STORAGE`,`Durable storage is unavailable`);return p}catch(t){throw t instanceof Wi?new R(`SCHEMA_MISMATCH`,t.message):a?new R(`UNCERTAIN`,`Acceptance could not be confirmed; retry the same request ID and input`,s):t instanceof Ai?new R(`QUERY_LIMIT`,t.message):c.aborted?(this.checkPrincipal(e),new R(this.signal.aborted?`CLOSED`:`UNAVAILABLE`,`Operation was canceled`)):Sr(t)}finally{await i?.release()}}collections(e,t,n,r){return{collection:i=>{let a=this.schema.collections[i],o=async a=>(await this.authorize(t,i,a,n),r.some(e=>e.collection===i&&e.action===a)||r.push({collection:i,action:a}),e.store(Aa(this.schema.id,t.scope,i)));return{get:async t=>{let n=this.recordKey(t),r=await(await o(`read`))?.get(n,e.signal);return r?.found?V(r.data):void 0},scan:async(t={})=>{let n=t.prefix??``,r=n?this.recordKey(n):new Uint8Array,i=await o(`read`);return i?(await i.scanRecords(r,{maxRecords:this.limits.maxRecords,maxBytes:this.limits.maxSnapshotBytes},e.signal)).map(e=>({key:za.decode(e.key),value:V(e.value)})):[]},put:async(t,n)=>{let r=this.recordKey(t),i=await o(`write`);if(!e.write||!i)throw new R(`DENIED`,`Transaction is read-only`);let s=B(await La(a,n,`Record`));if(s.length>this.limits.maxRecordBytes)throw new R(`QUERY_LIMIT`,`Record exceeds the configured byte limit`);await i.set(r,s,e.signal)},delete:async t=>{let n=this.recordKey(t),r=await o(`write`);if(!e.write||!r)throw new R(`DENIED`,`Transaction is read-only`);await r.delete(n,e.signal)}}}}}recordKey(e){try{return Ma(e)}catch{throw new R(`VALIDATION`,`Record key must be nonempty UTF-8 within 1024 bytes`)}}},Ha=class{tx;write;signal;stores=new Map;released=!1;constructor(e,t,n){this.tx=e,this.write=t,this.signal=n}async store(e){if(this.released)throw new R(`CLOSED`,`Transaction is closed`);let t=this.stores.get(e);return t||(t=(async()=>{let t=await Gi(this.tx,e,this.write,this.signal);if(t)try{return{store:t,tx:await t.openTransaction(this.write,this.signal)}}catch(e){throw t.release(),e}})(),this.stores.set(e,t)),(await t)?.tx}async commit(e){let t=await Promise.all(this.stores.values());for(let e of t)await e?.tx.commit(this.signal);this.signal.throwIfAborted(),e?.(),await this.tx.commit()}async release(){if(this.released)return;this.released=!0;let e=await Promise.allSettled(this.stores.values());await Promise.all(e.map(async e=>{if(e.status===`fulfilled`&&e.value)try{await e.value.tx.discard()}catch{}finally{e.value.store.release()}}));try{await this.tx.discard()}catch{}finally{this.tx.release()}}};const Ua=new Proxy({released:!0},{get(e,t){if(t===`released`)return!0;if(t===`toJSON`)return()=>({released:!0});let n=String(t);if(!(typeof t==`symbol`||n.startsWith(`$$`)||n.startsWith(`@@__`)||t===`constructor`||t===`prototype`||t===`__proto__`||t===`then`||t===`asymmetricMatch`||t===`nodeType`||t===`tagName`))throw new Z(`Cannot access "${n}" on released resource`,`INVALID_RESOURCE`)}}),Wa=3e4,Ga=`ResourceClient stream did not initialize before timeout`;function Ka(e){return new Promise((t,n)=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(new Z(Ga,`CONNECTION_FAILED`)))},Wa);e.then(e=>{r||(r=!0,clearTimeout(i),t(e))}).catch(e=>{r||(r=!0,clearTimeout(i),n(e))})})}function qa(e){let t=e instanceof Error?e.message:String(e??``);return t.includes(`resource not found`)||t.includes(`invalid resource id`)||t.includes(`resource or client was released`)}var Z=class extends Error{code;cause;constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`ResourceClientError`}},Ja=class{listeners=[];on(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}emit(e){[...this.listeners].forEach(t=>{try{t(e)}catch(e){console.error(`Error in event listener:`,e)}})}clear(){this.listeners.length=0}},Ya=class extends vn{resourceClient;constructor(e,t){super(t),this.resourceClient=e}async request(e,t,n,r){return await this.resourceClient.waitForControls(r),super.request(e,t,n,r)}async clientStreamingRequest(e,t,n,r){return await this.resourceClient.waitForControls(r),super.clientStreamingRequest(e,t,n,r)}serverStreamingRequest(e,t,n,r){let i=P({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(r);for await(let a of super.serverStreamingRequest(e,t,n,r))i.push(a);i.end()})().catch(e=>i.end(e)),i}bidirectionalStreamingRequest(e,t,n,r){let i=P({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(r);for await(let a of super.bidirectionalStreamingRequest(e,t,n,r))i.push(a);i.end()})().catch(e=>i.end(e)),i}};function Xa(e,t,n,r){let i=!1,a=()=>{i||(i=!0,n(e,c))},o=null,s=()=>(o||=new Ya(t,async()=>Ka(vr(e.toString(),t.service.ResourceRpc.bind(t.service),!0)).catch(t=>{throw qa(t)&&r(e),t})),o),c={get resourceId(){return e},get released(){return i},get client(){return i?Ua:s()},createRef(n){if(i)throw new Z(`Cannot create ref from released resource ${e}`,`INVALID_RESOURCE`);return t.createResourceReference(n)},createResource(e,t,...n){return new t(this.createRef(e),...n)},release:a,[Symbol.dispose]:a,_markReleased(){i=!0}};return c}var Za=class{service;signal;initState=null;connectionController=null;resourceSession=null;resources=new Map;events=new Ja;connectionLostEvents=new Ja;initPromise=null;disposed=!1;_connectionGeneration=0;_reconnectResolve=null;_reconnectReject=null;attachSession=null;attachSessionInitPromise=null;constructor(e,t){this.service=e,this.signal=t,t.addEventListener(`abort`,()=>{this.dispose(`CLIENT_CANCELLED`)},{once:!0})}get connectionGeneration(){return this._connectionGeneration}onResourceReleased(e){return this.throwIfDisposed(),this.events.on(e)}onConnectionLost(e){return this.throwIfDisposed(),this.connectionLostEvents.on(e)}async accessRootResource(){let e=await this.ensureInitialized();return this.createResourceReference(e.rootResourceId)}async attachRawInvoker(e,t,n){return this.attachResource(e,t,n)}async attachResourceTree(e,t,n,r){return this.attachResource(e,t,n,r)}async attachResource(e,t,n,r){let i=0;for(;;){let a=await this.ensureAttachSession();try{let i=++a.attachIdCtr,o=new Promise((e,t)=>{a.pending.set(i,{resolve:e,reject:t}),n?.addEventListener(`abort`,()=>{let e=a.pending.get(i);e&&(e.canceled=!0),t(Error(`aborted`))},{once:!0})});a.outgoing.push({body:{case:`add`,value:{attachId:i,label:e}}});let s=await o;return a.muxes.set(s,t),r&&a.releaseFns.set(s,r),{resourceId:s,cleanup:()=>{this.releaseAttachedResource(a,s),a.outgoing.push({body:{case:`detach`,value:{resourceId:s}}})}}}catch(e){if(n?.aborted||i>=3||!this.shouldRetryAttachResource(e,a))throw e;i++}}}shouldRetryAttachResource(e,t){return e instanceof Error&&e.message===`attach session closed`&&this.attachSession!==t}async ensureAttachSession(){return this.attachSession?this.attachSession:(this.attachSessionInitPromise||=this.openAttachSession().finally(()=>{this.attachSessionInitPromise=null}),this.attachSessionInitPromise)}async openAttachSession(){let e=await this.ensureInitialized(),t=wi(this.signal),n=P({objectMode:!0}),r=this.service.ResourceAttach((async function*(){yield*n})(),t.signal)[Symbol.asyncIterator]();n.push({body:{case:`init`,value:{clientHandleId:e.clientHandleId}}});let i=await r.next();if(i.done)throw n.end(),t.abort(),Error(`stream closed before ack`);let a=i.value?.body;if(a?.case!==`ack`)throw n.end(),t.abort(),Error(`expected ack packet`);if(a.value.error){n.end(),t.abort();let e=Error(a.value.error);throw a.value.error===`client not found`?(this.resetConnection(),new Z(`Resource attach client was released`,`CONNECTION_FAILED`,e)):e}let o={controller:t,outgoing:n,attachIdCtr:0,closed:!1,muxes:new Map,releaseFns:new Map,pending:new Map},s=new Mt(async(e,t)=>{let n=e.indexOf(`/`);if(n<0)return null;let r=parseInt(e.substring(0,n),10);if(isNaN(r))return null;let i=o.muxes.get(r);return i?i(e.substring(n+1),t):null}),c=new kn(s,{direction:`inbound`,yamuxParams:{enableKeepAlive:!1}}),l=e=>this.releaseAttachedResource(o,e),u=(async function*(){for(;;){let e=await r.next();if(e.done)break;let t=e.value?.body;if(t?.case===`muxData`)yield t.value;else if(t?.case===`addAck`){let e=t.value,r=e.attachId??0,i=o.pending.get(r);if(o.pending.delete(r),!i)continue;if(i.canceled){e.error||n.push({body:{case:`detach`,value:{resourceId:e.resourceId??0}}});continue}e.error?i.reject(Error(e.error)):i.resolve(e.resourceId??0)}t?.case===`detachAck`&&l(t.value.resourceId??0)}})();return It(u,c,wt(),async e=>{for await(let t of e)n.push({body:{case:`muxData`,value:t}});n.end()}).catch(()=>{n.end()}).finally(()=>{this.clearAttachSession(o)}),this.attachSession=o,o}createResourceReference(e){return this.throwIfDisposed(),this.createRef(e)}dispose(e=`CLIENT_DISPOSED`){if(this.disposed)return;this.disposed=!0,this._reconnectReject?.(new Z(`Resource client is closed`,e)),this._reconnectResolve=null,this._reconnectReject=null;let t=e!==`CONNECTION_FAILED`;if(t)for(let e of this.resources.keys())this.queueControl({case:`release`,value:{resourceId:e}});this.clearAttachSession(),t?(this.finishResourceSession(),this.connectionController=null):(this.retireResourceSession(),this.connectionController?.abort(),this.connectionController=null);for(let[e,t]of this.resources.entries())t.forEach(e=>e._markReleased()),this.events.emit({resourceId:e,reason:`client-disposed`});this.resources.clear(),this.events.clear(),this.connectionLostEvents.clear(),this.initState=null,this.initPromise=null}async ensureInitialized(){return this.throwIfDisposed(),this.initState?this.initState:(this.initPromise||=this.performInitialization(),this.initPromise)}async performInitialization(){return this.throwIfDisposed(),this.connectionController=wi(this.signal),new Promise((e,t)=>{let n=!1,r=()=>{n||(this.connectionController=null,this.initPromise=null)},i=()=>{n||(r(),t(new Z(`Client initialization was cancelled`,`CLIENT_CANCELLED`)))};if(this.signal.aborted){i();return}this.signal.addEventListener(`abort`,i,{once:!0}),this.startConnection(e,t,()=>{n=!0,this.signal.removeEventListener(`abort`,i)}).catch(e=>{r(),n||t(new Z(`Failed to initialize client connection`,`CONNECTION_FAILED`,e instanceof Error?e:Error(String(e))))})})}async startConnection(e,t,n){let r=this.connectionController;if(!r)throw new Z(`No connection controller`,`CONNECTION_FAILED`);await jr(r.signal,async t=>{let i=wi(t),a=!1,o=!1,s=setTimeout(()=>{a||i.signal.aborted||(o=!0,i.abort())},Wa),c=P({objectMode:!0}),l={controller:i,outgoing:c,generation:this._connectionGeneration,initialized:!1,closed:!1,nextControlId:0,acknowledgedControlId:0,controlWaiters:new Set};this.resourceSession=l;let u=()=>{if(l.closed)return;l.closed=!0,c.end();let e=new Z(`ResourceClient control stream closed`,`CONNECTION_FAILED`);for(let t of l.controlWaiters)t.reject(e);l.controlWaiters.clear(),this.resourceSession===l&&(this.resourceSession=null)},d=()=>{throw new Z(Ga,`CONNECTION_FAILED`)};try{let r=this.service.ResourceClient((async function*(){yield*c})(),i.signal);c.push({body:{case:`init`,value:{}}});for await(let c of r){if(t.aborted)return;if(i.signal.aborted){o&&d();return}let r=c.body;if(r?.case===`init`){a=!0,l.initialized=!0,s&&clearTimeout(s),s=void 0;let t={clientHandleId:r.value.clientHandleId??0,rootResourceId:r.value.rootResourceId??0};this._reconnectResolve?(this.initState=t,this._reconnectResolve(t),this._reconnectResolve=null,this._reconnectReject=null):this.initState?this.initState=t:(this.initState=t,n(),e(t));continue}if(r?.case===`resourceReleased`){this.handleServerResourceRelease(r.value.resourceId??0);continue}r?.case===`controlAck`&&this.acknowledgeControl(l,r.value.controlId??0)}}catch(e){throw!t.aborted&&o&&d(),e}finally{s&&clearTimeout(s),s=void 0,u(),this.connectionController===r&&!this.disposed&&a&&this.releaseAllResources(`connection-lost`)}if(!this.disposed&&!t.aborted)throw o&&d(),Error(a?`ResourceClient stream closed`:`ResourceClient stream closed before init`)},{errorCb:e=>{this.shouldRetryResourceClientStreamSilently(e)||console.warn(`Retry: retrying after error`,{error:e})}})}throwIfDisposed(){if(this.disposed)throw new Z(`Client has been disposed`,`CLIENT_DISPOSED`)}createRef(e){this.throwIfDisposed();let t=this.resources.get(e),n=!t;t||(t=new Set,this.resources.set(e,t));let r=Xa(e,this,this.releaseRef.bind(this),this.handleServerResourceRelease.bind(this));return t.add(r),n&&this.queueControl({case:`adopt`,value:{resourceId:e}}),r}releaseRef(e,t){let n=this.resources.get(e);n&&(n.delete(t),n.size===0&&(this.resources.delete(e),this.queueControl({case:`release`,value:{resourceId:e}}),this.events.emit({resourceId:e,reason:`client-released`})))}queueControl(e){let t=this.resourceSession;if(!t||t.closed||!t.initialized)return;let n=++t.nextControlId;t.outgoing.push({controlId:n,body:e})}async waitForControls(e){if(e?.aborted)throw Error(Wn);let t=this.resourceSession;if(!t||t.closed||!t.initialized)throw new Z(`ResourceClient control stream is unavailable`,`CONNECTION_FAILED`);let n=t.nextControlId;n<=t.acknowledgedControlId||await new Promise((r,i)=>{let a=()=>{t.controller.signal.removeEventListener(`abort`,c),e?.removeEventListener(`abort`,l)},o={target:n,resolve:()=>{a(),r()},reject:e=>{a(),i(e)}},s=e=>{t.controlWaiters.delete(o)&&o.reject(e)},c=()=>s(new Z(`ResourceClient control stream closed`,`CONNECTION_FAILED`)),l=()=>s(Error(Wn));t.controlWaiters.add(o),t.controller.signal.addEventListener(`abort`,c,{once:!0}),e?.addEventListener(`abort`,l,{once:!0}),t.controller.signal.aborted&&c(),e?.aborted&&l()})}acknowledgeControl(e,t){if(t===0||t!==e.acknowledgedControlId+1||t>e.nextControlId)throw Error(`unexpected ResourceClient control acknowledgment ${t} after ${e.acknowledgedControlId}`);e.acknowledgedControlId=t;for(let n of e.controlWaiters)n.target>t||(e.controlWaiters.delete(n),n.resolve())}shouldRetryResourceClientStreamSilently(e){if(e instanceof Z&&e.message===Ga||String(e)===`StreamResetError: stream reset`)return!0;if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`),n=Reflect.get(e,`message`);return(typeof t==`string`?t:``)===`StreamResetError`||(typeof n==`string`?n:``)===`stream reset`}handleServerResourceRelease(e){let t=this.resources.get(e);t&&(t.forEach(e=>e._markReleased()),this.resources.delete(e),this.events.emit({resourceId:e,reason:`server-released`}))}releaseAllResources(e){this._connectionGeneration++,this.clearAttachSession();for(let[t,n]of this.resources.entries())n.forEach(e=>e._markReleased()),this.events.emit({resourceId:t,reason:e});this.resources.clear(),this.initState=null,this.initPromise=new Promise((e,t)=>{this._reconnectResolve=e,this._reconnectReject=t}),this.initPromise.catch(()=>{}),this.connectionLostEvents.emit(void 0)}resetConnection(){if(this.disposed)return;let e=this.connectionController;this.connectionController=null,this.clearAttachSession();for(let[e,t]of this.resources.entries())t.forEach(e=>e._markReleased()),this.events.emit({resourceId:e,reason:`connection-lost`});this.resources.clear(),this.initState=null,this.initPromise=null,this._reconnectReject?.(new Z(`Resource generation was replaced`,`CONNECTION_FAILED`)),this._reconnectResolve=null,this._reconnectReject=null,this.retireResourceSession(),e?.abort(),this._connectionGeneration++,this.connectionLostEvents.emit(void 0)}finishResourceSession(){let e=this.resourceSession;e&&(e.closed=!0,e.outgoing.end(),this.resourceSession=null)}retireResourceSession(){let e=this.resourceSession;e&&(e.closed=!0,e.outgoing.end(),e.controller.abort(),this.resourceSession=null)}clearAttachSession(e){let t=e??this.attachSession;if(t&&(this.attachSession===t&&(this.attachSession=null),!t.closed)){t.closed=!0,t.controller.abort(),t.outgoing.end();for(let[,e]of t.pending)e.reject(Error(`attach session closed`));t.pending.clear(),this.releaseAllAttachedResources(t)}}releaseAttachedResource(e,t){let n=e.releaseFns.get(t);e.releaseFns.delete(t),e.muxes.delete(t),n?.()}releaseAllAttachedResources(e){let t=[...e.releaseFns.values()];e.releaseFns.clear(),e.muxes.clear();for(let e of t)e()}};const Qa={typeName:`resource.ResourceService`,methods:{ResourceClient:{name:`ResourceClient`,I:x,O:v,kind:M.BiDiStreaming},ResourceRpc:{name:`ResourceRpc`,I:H,O:H,kind:M.BiDiStreaming},ResourceAttach:{name:`ResourceAttach`,I:tr,O:gt,kind:M.BiDiStreaming}}},$a=Qa.typeName;var eo=class{rpc;service;constructor(e,t){this.service=t?.service||$a,this.rpc=e,this.ResourceClient=this.ResourceClient.bind(this),this.ResourceRpc=this.ResourceRpc.bind(this),this.ResourceAttach=this.ResourceAttach.bind(this)}ResourceClient(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Qa.methods.ResourceClient.name,Bt(x)(e),t||void 0);return F(v)(n)}ResourceRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Qa.methods.ResourceRpc.name,Bt(H)(e),t||void 0);return F(H)(n)}ResourceAttach(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Qa.methods.ResourceAttach.name,Bt(tr)(e),t||void 0);return F(gt)(n)}};async function to(e){if(!e)throw Error(`A sync storage directory is required`);let t=new cr(new URL(`./engine-worker.mjs`,import.meta.url),{workerData:Pn.toBinary({directory:e}),execArgv:[]}),n=Promise.withResolvers(),r=Promise.withResolvers(),i=new AbortController,a=new Set,o,s,c,l=!1,u=!1,d=e=>{s??=e,n.reject(s),o?.dispose(`CONNECTION_FAILED`),i.abort(s);for(let e of a)e.abort(s);a.clear()};t.on(`error`,d),t.on(`exit`,e=>{u=!0,l||d(Error(`Sync engine Worker exited unexpectedly (${e})`)),i.abort(s),r.resolve()}),t.on(`message`,e=>{try{let t=ln.fromBinary(e);switch(t.kind){case 1:n.resolve();break;case 4:l=!0,t.error&&d(Error(t.error));break;case 5:d(Error(t.error||`Sync engine startup failed`));break;default:d(Error(`Sync engine returned an unsupported lifecycle message`))}}catch(e){d(e instanceof Error?e:Error(String(e)))}});let f=()=>(c??=(async()=>{if(o?.dispose(),!u){t.postMessage({message:ln.toBinary({kind:3})});let e=setTimeout(()=>{d(Error(`Sync engine shutdown timed out`)),t.terminate()},1e4);try{await r.promise}finally{clearTimeout(e)}}if(await Promise.all(Array.from(a,e=>e.close())),a.clear(),s)throw s})(),c),p=setTimeout(()=>{d(Error(`Sync engine startup timed out`)),t.terminate()},3e4);try{return await n.promise,o=new Za(new eo(new vn(async()=>{if(s)throw s;if(c||u)throw Error(`Sync engine is closed`);let{port1:e,port2:n}=new sr,r=wn(e),i=r.close.bind(r),o=r.abort.bind(r);return r.close=async()=>{a.delete(r),await i()},r.abort=e=>{a.delete(r),o(e)},a.add(r),t.postMessage({message:ln.toBinary({kind:2}),port:n},[n]),r})),i.signal),{engine:new Ta(await o.accessRootResource()),resources:o,signal:i.signal,close:f}}catch(e){try{await f()}catch{}throw e}finally{clearTimeout(p)}}var Q=n(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),no=n(((e,t)=>{let{EMPTY_BUFFER:n}=Q(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o}})),ro=n(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),io=n(((e,n)=>{let r=t(`zlib`),i=no(),a=ro(),{kStatusCode:o}=Q(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,v),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function v(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),ao=n(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=Q(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r&&(n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)})})),oo=n(((e,n)=>{let{Writable:r}=t(`stream`),i=io(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Q(),{concat:l,toArrayBuffer:u,unmask:d}=no(),{isValidStatusCode:f,isValidUTF8:p}=ao(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._state=this._masked?3:4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){t(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),so=n(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=io(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=Q(),{isBlob:u,isValidStatusCode:d}=ao(),{mask:f,toBuffer:p}=no(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8192,v,y=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(y===g&&(v===void 0&&(v=Buffer.alloc(g)),i(v,0,g),y=0),n[0]=v[y++],n[1]=v[y++],n[2]=v[y++],n[3]=v[y++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(b,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(ee,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);b(this,e,i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function b(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function ee(e,t,n){b(e,t,n),e.onerror(t)}})),co=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Q(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean!==void 0&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),lo=n(((e,t)=>{let{tokenChars:n}=ao();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`)}else if(l===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s){if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),uo=n(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=io(),m=oo(),h=so(),{isBlob:g}=ao(),{BINARY_TYPES:v,CLOSE_TIMEOUT:y,EMPTY_BUFFER:b,GUID:ee,kForOnEventAttribute:x,kListener:S,kStatusCode:te,kWebSocket:C,NOOP:w}=Q(),{EventTarget:{addEventListener:ne,removeEventListener:re}}=co(),{format:T,parse:ie}=lo(),{toBuffer:ae}=no(),oe=Symbol(`kAborted`),se=[8,13],E=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var D=class e extends r{constructor(t,n,r){super(),this._binaryType=v[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=b,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),le(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){v.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,j),i.on(`drain`,fe),i.on(`error`,pe),i.on(`message`,he),i.on(`ping`,M),i.on(`pong`,ge),a.onerror=ve,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,be),t.on(`data`,xe),t.on(`end`,Se),t.on(`error`,Ce),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ye(this)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||b,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||b,n,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){A(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||b,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(D,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(D.prototype,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(D,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(D.prototype,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(D,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(D.prototype,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(D,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),Object.defineProperty(D.prototype,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(D.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(D.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),D.prototype.addEventListener=ne,D.prototype.removeEventListener=re,n.exports=D;function le(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:y,protocolVersion:se[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!se.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${se.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;O(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),v=u?i.request:a.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?de:ue),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=T({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ce.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{k(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[oe]||(S=e._req=null,O(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){k(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{O(e,SyntaxError(`Invalid URL: ${a}`));return}le(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||k(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==D.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){k(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+ee).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){k(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?b.size&&(c=`Server sent no subprotocol`):b.size?b.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){k(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){k(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=ie(u)}catch{k(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){k(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{k(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function O(e,t){e._readyState=D.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ue(e){return e.path=e.socketPath,o.connect(e)}function de(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function k(e,t,n){e._readyState=D.CLOSING;let r=Error(n);Error.captureStackTrace(r,k),t.setHeader?(t[oe]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(O,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function A(e,t,n){if(t){let n=g(t)?t.size:ae(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${E[e.readyState]})`);process.nextTick(n,t)}}function j(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,xe),process.nextTick(_e,n._socket),e===1005?n.close():n.close(e,t))}function fe(){let e=this[C];e.isPaused||e._socket.resume()}function pe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,xe),process.nextTick(_e,t._socket),t.close(e[te])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function me(){this[C].emitClose()}function he(e,t){this[C].emit(`message`,e,t)}function M(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ge(e){this[C].emit(`pong`,e)}function _e(e){e.resume()}function ve(e){let t=this[C];t.readyState!==D.CLOSED&&(t.readyState===D.OPEN&&(t._readyState=D.CLOSING,ye(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ye(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function be(){let e=this[C];if(this.removeListener(`close`,be),this.removeListener(`data`,xe),this.removeListener(`end`,Se),e._readyState=D.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,me),e._receiver.on(`finish`,me))}function xe(e){this[C]._receiver.write(e)||this.pause()}function Se(){let e=this[C];e._readyState=D.CLOSING,e._receiver.end(),this.end()}function Ce(){let e=this[C];this.removeListener(`error`,Ce),this.on(`error`,w),e&&(e._readyState=D.CLOSING,this.destroy())}})),fo=n(((e,n)=>{uo();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),po=n(((e,t)=>{let{tokenChars:n}=ao();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),mo=n(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=lo(),c=io(),l=po(),u=uo(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=Q(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1){if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,v);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){b(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){b(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){b(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){b(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){y(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{b(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{b(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return y(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return y(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return y(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
1
|
+
import{i as e,r as t,t as n}from"./chunks/rolldown-runtime-Csi-cuKc.mjs";import{$n as r,$r as i,A as a,An as o,Ar as s,At as c,B as l,Br as u,Bt as d,Cr as f,Ct as p,D as m,Di as h,Dn as g,Dr as _,Dt as v,En as y,Er as ee,Et as b,Fi as x,Fn as te,Fr as S,Ft as ne,Gi as C,Gr as re,Gt as ie,H as ae,Hn as oe,Hr as se,Ht as w,In as T,Ir as ce,It as E,Jr as le,Jt as D,Kr as ue,Kt as de,L as O,Ln as k,Lr as fe,Lt as pe,M as me,Mn as he,Mr as ge,Mt as _e,N as ve,Nn as ye,Nr as be,Nt as xe,O as Se,Oi as Ce,On as we,Or as Te,Ot as Ee,Pi as De,Pn as Oe,Pr as ke,Pt as Ae,Qn as je,Qr as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,St as ze,T as Be,Tr as Ve,Tt as He,Un as Ue,Ur as We,Ut as Ge,V as Ke,Vn as qe,Vr as Je,Vt as Ye,Wn as Xe,Wr as Ze,Wt as Qe,Xn as $e,Xr as et,Xt as tt,Yn as nt,Yr as rt,Yt as it,Zn as at,Zr as ot,Zt as st,_ as A,_i as ct,_n as lt,_r as ut,_t as dt,a as ft,ai as pt,an as mt,at as ht,b as gt,bi as _t,bn as vt,c as yt,ci as bt,cn as xt,cr as St,ct as Ct,d as wt,di as Tt,dn as Et,dr as Dt,dt as Ot,ei as kt,er as At,et as jt,f as Mt,fi as Nt,fn as Pt,fr as Ft,ft as It,g as Lt,gi as Rt,gn as zt,gr as Bt,gt as Vt,h as Ht,hi as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,ii as Jt,in as Yt,ir as Xt,it as Zt,j as Qt,jn as $t,jr as en,k as tn,kn as nn,kr as rn,kt as an,l as on,li as sn,ln as cn,lr as ln,lt as un,m as j,mi as dn,mn as fn,mr as pn,mt as mn,n as hn,na as gn,ni as _n,nn as vn,nr as yn,nt as M,o as bn,oi as xn,on as Sn,or as Cn,ot as N,p as wn,pi as Tn,pr as En,pt as Dn,qr as On,qt as kn,r as An,ra as P,ri as jn,rn as Mn,rr as Nn,rt as F,s as Pn,si as Fn,sn as In,sr as Ln,st as Rn,t as zn,ta as I,ti as Bn,tn as Vn,tr as Hn,tt as Un,u as Wn,ui as Gn,un as Kn,ur as qn,ut as Jn,v as Yn,vi as Xn,vn as Zn,vr as Qn,vt as $n,w as er,wr as tr,wt as nr,x as rr,xn as ir,xt as ar,y as or,yi as sr,yn as cr,yr as lr,yt as ur,zr as dr,zt as fr}from"./chunks/node.pb-L2jxLJ0J.mjs";import{MessageChannel as pr,Worker as mr}from"node:worker_threads";import{randomUUID as hr}from"node:crypto";import{createServer as gr}from"node:http";const _r=Symbol(`server context parent`),vr=Symbol(`server context key`),yr=Symbol(`server context value`);function br(){return{}}function xr(e,t,n){return{signal:e.signal,[_r]:e,[vr]:t,[yr]:n}}function Sr(e,t){let n=e;for(;n;){if(n[vr]===t)return n[yr];n=n[_r]}}async function Cr(e,t,n){let r=A({objectMode:!0}),i=t(r);r.push({body:{case:`init`,value:{componentId:e}}});let a=i[Symbol.asyncIterator]();if(n){let e=await a.next();if(e.done)throw Error(`rpcstream: closed before ack packet`);let t=e.value?.body;if(!t||t.case!==`ack`){let e=t?.case||`none`;throw Error(`rpcstream: expected ack packet but got ${e}`)}let n=t.value?.error;if(n)throw Error(`rpcstream: remote: ${n}`)}return new Tr(r,a,()=>on(a))}async function*wr(e,t){let n=await e.next();if(n.done)throw Error(`closed before init received`);let r=n.value;if(r?.body?.case!==`init`)throw Error(`expected init packet`);let i=null,a;try{i=await t(r.body.value.componentId??``)}catch(e){a=e,a?a.message||(a=Error(`rpc getter failed: ${a}`)):a=Error(`rpc getter failed`)}if(!i&&!a&&(a=Error(`not implemented`)),yield*[{body:{case:`ack`,value:{error:a?.message||``}}}],a)throw a;let o=A({objectMode:!0}),s=new Tr(o,e,()=>on(e));i(s).catch(e=>o.end(e)).then(()=>o.end());for await(let e of o)yield*[e]}var Tr=class{source;sink;_packetRx;_packetTx;_termination=new yt;_cancelRpc;constructor(e,t,n=()=>on(t)){this._packetTx=e,this._packetRx=t,this._cancelRpc=n,this.sink=this._createSink(),this.source=this._createSource()}async close(){this._termination.terminate()&&(this._packetTx.end(),this._cancelRpc())}abort(e){this._termination.terminate(e)&&(this._packetTx.end(e),this._cancelRpc())}_createSink(){return async e=>{let t=Wn(e);try{for(;;){let e=await this._termination.next(t);if(`terminated`in e){if(e.error)throw e.error;return}if(`error`in e)throw e.error;if(e.result.done){this._packetTx.end();return}if(this._termination.terminated)return;this._packetTx.push({body:{case:`data`,value:e.result.value}})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.abort(t),t}finally{on(t)}}}_createSource(){let e=this._packetRx,t=this._termination;return(async function*(){try{for(;;){let n=await t.next(e);if(`terminated`in n){if(n.error)throw n.error;return}if(`error`in n)throw n.error;if(n.result.done)return;let r=n.result.value?.body;if(r)switch(r.case){case`ack`:if(r.value.error?.length)throw Error(r.value.error);break;case`data`:yield r.value}}}finally{on(e)}})()}};const Er=Symbol.for(`spacewave.SyncError`);var L=class extends Error{code;requestId;name=`SyncError`;[Er]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&Er in e&&e[Er]===!0}constructor(e,t,n){super(t),this.code=e,this.requestId=n}};function R(e){return e instanceof L?e:new L(`STORAGE`,`The data operation could not complete`)}function z(e){return Dr(e,`$`,[])}function B(e){return new TextEncoder().encode(z(e))}function V(e){let t;try{t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw TypeError(`invalid JSON at $: data is not valid UTF-8`)}let n;try{n=JSON.parse(t)}catch{throw TypeError(`invalid JSON at $: data is not valid JSON`)}return z(n),n}function Dr(e,t,n){switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:if(!Number.isFinite(e))throw TypeError(`invalid JSON at ${t}: non-finite number`);return JSON.stringify(e);case`string`:return JSON.stringify(e);case`object`:if(e===null)return`null`;break;default:throw TypeError(`invalid JSON at ${t}: ${typeof e} is not a JSON value`)}for(let r of n)if(r===e)throw TypeError(`invalid JSON at ${t}: cycle`);n.push(e);let r=Array.isArray(e)?Or(e,t,n):kr(e,t,n);return n.pop(),r}function Or(e,t,n){let r=e.length,i=Array.from({length:r}),a=Array.from({length:r},()=>!1);for(let o of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,o);if(s.get!==void 0||s.set!==void 0)throw TypeError(`invalid JSON at ${t}[${String(o)}]: accessor property`);if(typeof o==`symbol`){if(s.enumerable)throw TypeError(`invalid JSON at ${t}: enumerable symbol key is not supported`);continue}let c=Number(o);if(Number.isInteger(c)&&c>=0&&c<r&&String(c)===o){a[c]=!0,i[c]=Dr(s.value,`${t}[${c}]`,n);continue}if(s.enumerable)throw TypeError(`invalid JSON at ${t}: extra enumerable array property ${JSON.stringify(o)}`)}for(let e=0;e<r;e++)if(!a[e])throw TypeError(`invalid JSON at ${t}[${e}]: array hole (missing index)`);return`[${i.join(`,`)}]`}function kr(e,t,n){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`invalid JSON at ${t}: not a plain object`);let i=[];for(let r of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,r);if(a.get!==void 0||a.set!==void 0)throw TypeError(`invalid JSON at ${t}.${String(r)}: accessor property`);if(typeof r==`symbol`){if(a.enumerable)throw TypeError(`invalid JSON at ${t}: enumerable symbol key is not supported`);continue}a.enumerable&&i.push({key:r,json:Dr(a.value,`${t}.${r}`,n)})}return i.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),`{${i.map(e=>`${JSON.stringify(e.key)}:${e.json}`).join(`,`)}}`}function Ar(e){return{collection:t=>({get:async(n,r)=>{let i=await e({kind:`get`,collection:t,key:n},r);return i.found?i.value:void 0},scan:async(n,r)=>await e({kind:`scan`,collection:t,prefix:n?.prefix??``},r),put:async(n,r,i)=>{await e({kind:`put`,collection:t,key:n,value:jr(r)},i)},delete:async(n,r)=>{await e({kind:`delete`,collection:t,key:n},r)}}),mutate:async(t,n,r)=>await e({kind:`mutate`,name:t,input:jr(n)},r)}}function jr(e){try{return V(B(e))}catch{throw new L(`VALIDATION`,`Input must contain only JSON-compatible values`)}}var Mr=class{opts;nonce;getSnapshot;listeners=new Set;errorListeners=new Set;constructor(e,t){this.opts=t,this.getSnapshot=e||(async()=>void 0)}get snapshot(){return this.getSnapshot()}getIterable(){return{[Symbol.asyncIterator]:()=>{let e=[],t=null,n=null,r=!1,i=null,a=n=>{if(this.opts?.mostRecentOnly){if(i={value:n,nonce:this.nonce},t){let e=t;t=null,e({value:i.value,done:!1}),i=null}}else if(t){let e=t;t=null,e({value:n,done:!1})}else e.push(n)},o=e=>{if(n){let t=n;n=null,t(e)}r=!0};return this.listeners.add(a),this.errorListeners.add(o),(async()=>{try{let e=await this.getSnapshot();e!==void 0&&a(e)}catch(e){o(e instanceof Error?e:Error(String(e)))}})(),{next:async()=>{if(r)return{value:void 0,done:!0};if(i){let{value:e}=i;return i=null,{value:e,done:!1}}return e.length>0?{value:e.shift(),done:!1}:new Promise((e,r)=>{t=e,n=r})},return:async()=>{if(this.listeners.delete(a),this.errorListeners.delete(o),r=!0,t){let e=t;t=null,e({value:void 0,done:!0})}return n=null,{value:void 0,done:!0}},throw:async()=>(this.listeners.delete(a),this.errorListeners.delete(o),r=!0,t=null,n=null,{value:void 0,done:!0})}}}}pushChangeEvent(e){this.opts?.mostRecentOnly?(this.nonce=(this.nonce??0)+1,Array.from(this.listeners).forEach(t=>t(e))):this.listeners.forEach(t=>t(e))}async pushSnapshot(){try{let e=await this.getSnapshot();e&&this.pushChangeEvent(e)}catch(e){this.errorListeners.forEach(t=>t(e instanceof Error?e:Error(String(e))))}}};for(let e of[`dispose`,`asyncDispose`])Symbol[e]||Object.defineProperty(Symbol,e,{value:Symbol.for(`Symbol.${e}`)});var H=class{resourceRef;constructor(e){this.resourceRef=e}get id(){return this.resourceRef.resourceId}get client(){return this.resourceRef.client}get released(){return this.resourceRef.released}release(){this.resourceRef.release()}[Symbol.dispose](){this.release()}};const Nr=I({typeName:`rpcstream.RpcStreamInit`,fields:[{no:1,name:`component_id`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),Pr=I({typeName:`rpcstream.RpcAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),U=I({typeName:`rpcstream.RpcStreamPacket`,fields:[{no:1,name:`init`,kind:`message`,T:()=>Nr,oneof:`body`},{no:2,name:`ack`,kind:`message`,T:()=>Pr,oneof:`body`},{no:3,name:`data`,kind:`scalar`,T:P.BYTES,oneof:`body`}],packedByDefault:!0}),Fr={typeName:`kvtx.rpc.Kvtx`,methods:{KvtxTransaction:{name:`KvtxTransaction`,I:O,O:Pe,kind:C.BiDiStreaming},KvtxTransactionRpc:{name:`KvtxTransactionRpc`,I:U,O:U,kind:C.BiDiStreaming},Watch:{name:`Watch`,I:l,O:Ke,kind:C.ServerStreaming}}},Ir=Fr.typeName;var Lr=class{rpc;service;constructor(e,t){this.service=t?.service||Ir,this.rpc=e,this.KvtxTransaction=this.KvtxTransaction.bind(this),this.KvtxTransactionRpc=this.KvtxTransactionRpc.bind(this),this.Watch=this.Watch.bind(this)}KvtxTransaction(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Fr.methods.KvtxTransaction.name,Ht(O)(e),t||void 0);return j(Pe)(n)}KvtxTransactionRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Fr.methods.KvtxTransactionRpc.name,Ht(U)(e),t||void 0);return j(U)(n)}Watch(e,t){let n=l.create(e),r=this.rpc.serverStreamingRequest(this.service,Fr.methods.Watch.name,l.toBinary(n),t||void 0);return j(Ke)(r)}};const W={typeName:`kvtx.rpc.KvtxOps`,methods:{KeyCount:{name:`KeyCount`,I:or,O:gt,kind:C.Unary},KeyData:{name:`KeyData`,I:tn,O:m,kind:C.Unary},KeyExists:{name:`KeyExists`,I:tn,O:Se,kind:C.Unary},SetKey:{name:`SetKey`,I:me,O:ve,kind:C.Unary},DeleteKey:{name:`DeleteKey`,I:rr,O:Re,kind:C.Unary},ScanPrefix:{name:`ScanPrefix`,I:a,O:Qt,kind:C.ServerStreaming},Iterate:{name:`Iterate`,I:er,O:Be,kind:C.BiDiStreaming}}},Rr=W.typeName;var zr=class{rpc;service;constructor(e,t){this.service=t?.service||Rr,this.rpc=e,this.KeyCount=this.KeyCount.bind(this),this.KeyData=this.KeyData.bind(this),this.KeyExists=this.KeyExists.bind(this),this.SetKey=this.SetKey.bind(this),this.DeleteKey=this.DeleteKey.bind(this),this.ScanPrefix=this.ScanPrefix.bind(this),this.Iterate=this.Iterate.bind(this)}async KeyCount(e,t){let n=or.create(e),r=await this.rpc.request(this.service,W.methods.KeyCount.name,or.toBinary(n),t||void 0);return gt.fromBinary(r)}async KeyData(e,t){let n=tn.create(e),r=await this.rpc.request(this.service,W.methods.KeyData.name,tn.toBinary(n),t||void 0);return m.fromBinary(r)}async KeyExists(e,t){let n=tn.create(e),r=await this.rpc.request(this.service,W.methods.KeyExists.name,tn.toBinary(n),t||void 0);return Se.fromBinary(r)}async SetKey(e,t){let n=me.create(e),r=await this.rpc.request(this.service,W.methods.SetKey.name,me.toBinary(n),t||void 0);return ve.fromBinary(r)}async DeleteKey(e,t){let n=rr.create(e),r=await this.rpc.request(this.service,W.methods.DeleteKey.name,rr.toBinary(n),t||void 0);return Re.fromBinary(r)}ScanPrefix(e,t){let n=a.create(e),r=this.rpc.serverStreamingRequest(this.service,W.methods.ScanPrefix.name,a.toBinary(n),t||void 0);return j(Qt)(r)}Iterate(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,W.methods.Iterate.name,Ht(er)(e),t||void 0);return j(Be)(n)}},Br=class extends Error{constructor(){super(`The snapshot exceeds its record or byte limit; use a narrower prefix`),this.name=`KvScanLimitError`}},Vr=class extends H{service;constructor(e){super(e),this.service=new Lr(e.client)}async keyCount(e){return this.withTransaction(!1,async t=>t.keyCount(e),e)}async scanKeys(e,t){return this.withTransaction(!1,async n=>n.scanKeys(e,t),t)}async*watchKeys(e,t){let n=this.service.Watch({prefix:e,onlyKeys:!1},t);for await(let e of n){if(e.error)throw Error(e.error);yield(e.entries??[]).map(e=>({key:e.key??new Uint8Array,byteLength:e.value?.length??0}))}}async*watchRecords(e,t,n){let r=new AbortController,i=n?AbortSignal.any([r.signal,n]):r.signal;i.throwIfAborted();let a=new Mr(void 0,{mostRecentOnly:!0}),o=a.getIterable()[Symbol.asyncIterator](),s=()=>{o.return?.()};i.addEventListener(`abort`,s,{once:!0});let c,l=(async()=>{try{for await(let n of this.service.Watch({prefix:e,maxRecords:BigInt(t.maxRecords),maxBytes:BigInt(t.maxBytes)},i)){if(n.limitExceeded)throw new Br;if(n.error)throw Error(n.error);let e=(n.entries??[]).map(e=>({key:e.key??new Uint8Array,value:e.value??new Uint8Array})),r=e.reduce((e,t)=>e+t.key.length+t.value.length,0);if(e.length>t.maxRecords||r>t.maxBytes)throw new Br;a.pushChangeEvent(e)}if(!i.aborted)throw Error(`kv/store: watch ended`)}catch(e){c=e}finally{await o.return?.()}})();try{for(;;){let e=await o.next();if(e.done)break;yield e.value}if(c&&!i.aborted)throw c}finally{r.abort(),i.removeEventListener(`abort`,s),await o.return?.(),await l}}async get(e,t){return this.withTransaction(!1,async n=>n.get(e,t),t)}async exists(e,t){return this.withTransaction(!1,async n=>n.exists(e,t),t)}async withTransaction(e,t,n){let r=await this.openTransaction(e,n);try{let i=await t(r);return e?await r.commit(n):await r.discard(),i}catch(e){throw await r.discard(),e}}async openTransaction(e,t){let n=A({objectMode:!0}),r=this.service.KvtxTransaction(n,t)[Symbol.asyncIterator]();n.push({body:{case:`init`,value:{write:e}}});let i=await Ur(r);if(i.body?.case!==`ack`)throw n.end(),Error(`kv/store: transaction did not return ack`);if(i.body.value.error)throw n.end(),Error(i.body.value.error);let a=i.body.value.transactionId??``;if(!a)throw n.end(),Error(`kv/store: transaction ack missing transaction id`);return new Hr(n,r,new zr(new wn(()=>Cr(a,e=>this.service.KvtxTransactionRpc(e,t),!1))))}},Hr=class{requests;responses;ops;released=!1;constructor(e,t,n){this.requests=e,this.responses=t,this.ops=n}async keyCount(e){return(await this.ops.KeyCount({},e)).keyCount??0n}async scanKeys(e,t){let n=[],r=this.ops.ScanPrefix({prefix:e,onlyKeys:!1},t);for await(let e of r){if(e.error)throw Error(e.error);e.key&&n.push({key:e.key,byteLength:e.value?.length??0})}return n}async scanRecords(e,t,n){let r=[],i=0,a=new AbortController,o=n?AbortSignal.any([a.signal,n]):a.signal;try{let n=this.ops.ScanPrefix({prefix:e,onlyKeys:!1},o);for await(let e of n){if(e.error)throw Error(e.error);if(!e.key)continue;let n=e.value??new Uint8Array;if(i+=e.key.length+n.length,r.length>=t.maxRecords||i>t.maxBytes)throw new Br;r.push({key:e.key,value:n})}return r}finally{a.abort()}}async get(e,t){let n=await this.ops.KeyData({key:e},t);if(n.error)throw Error(n.error);return{data:n.data??new Uint8Array,found:n.found??!1}}async exists(e,t){let n=await this.ops.KeyExists({key:e},t);if(n.error)throw Error(n.error);return n.found??!1}async set(e,t,n){let r=await this.ops.SetKey({key:e,value:t},n);if(r.error)throw Error(r.error)}async delete(e,t){let n=await this.ops.DeleteKey({key:e},t);if(n.error)throw Error(n.error)}async commit(e){if(this.released)throw Error(`kv/store: transaction already released`);this.released=!0,this.requests.push({body:{case:`commit`,value:!0}});try{let e=await Ur(this.responses),t=e.body?.case===`complete`?e.body.value:null;if(!t)throw Error(`kv/store: transaction did not complete`);if(t.error)throw Error(t.error);if(!t.committed)throw Error(`kv/store: transaction discarded`)}finally{this.requests.end(),e?.throwIfAborted()}}async discard(){if(!this.released){this.released=!0,this.requests.push({body:{case:`discard`,value:!0}});try{await Ur(this.responses)}finally{this.requests.end()}}}};async function Ur(e){let t=await e.next();if(t.done)throw Error(`kv/store: transaction stream closed`);return t.value}function Wr(e){return e?`<${e}>`:``}const Gr=`types/`,Kr=`<type>`;function qr(e){return e?Gr+e:``}function Jr(e,t){return{subject:Wr(e),predicate:Kr,obj:Wr(qr(t))}}async function Yr(e,t,n){let r=await e.lookupGraphQuads(Wr(t),Kr,void 0,void 0,1,n);if(!r.quads||r.quads.length===0)return``;let i=r.quads[0].obj;if(!i)return Xr(e,t,n);let a;try{a=i.startsWith(`<`)?i.slice(1,-1):i}catch{return``}return a.startsWith(`types/`)?a.slice(6):``}async function Xr(e,t,n){let r=await e.iterateObjects(Gr,!1,n);try{let i=async()=>{if(!await r.next(n))return``;let a=await r.key(n);if(!a.startsWith(`types/`))return i();let o=a.slice(6),s=await e.listObjectsWithType(o,n);return new Set(s).has(t)?o:i()};return await i()}finally{await r.close(n)}}async function Zr(e,t,n,r){let i=!1,a=[];for(let o of t)o.obj===n?i=!0:a.push(e.deleteGraphQuad(o.subject??``,o.predicate??``,o.obj??``,o.label,r));return await Promise.all(a),i}async function Qr(e,t,n,r){if(!t||!n)throw Error(`empty object key or type ID`);let i=Jr(t,n),a=await e.lookupGraphQuads(Wr(t),Kr,void 0,void 0,void 0,r),o=!1;a.quads&&(o=await Zr(e,a.quads,i.obj,r)),await $r(e,n,r),o||await e.setGraphQuad(i.subject??``,i.predicate??``,i.obj??``,i.label,r)}async function $r(e,t,n){let r=qr(t),i=await e.getObject(r,n);return i?(i.release(),!1):((await e.createObject(r,{},n)).release(),!0)}var ei=class extends Error{constructor(){super(`The existing object has a different ObjectType`),this.name=`KvObjectTypeError`}};async function ti(e,t,n,r){let i=await e.getObject(t,r);if(i){if(i.release(),await Yr(e,t,r)!==`kv/store`)throw new ei}else{if(!n)return;let i=await e.buildStorageCursor(r);try{let n=await i.putBlock({data:ae.toBinary({implType:1})},r),a=await i.getRef(r);if(!n.ref)throw Error(`kv/store: missing initial root`);(await e.createObject(t,{...a.ref,rootRef:n.ref},r)).release(),await Qr(e,t,`kv/store`,r)}finally{i.release()}}let a=await e.accessTypedObject(t,r),o=e.resourceRef.createResource(a.resourceId,Vr);if(a.typeId!==`kv/store`)throw o.release(),new ei;return o}const G={typeName:`s4wave.world.EngineResourceService`,methods:{GetEngineInfo:{name:`GetEngineInfo`,I:Ae,O:ne,kind:C.Unary},GetWorldRootSnapshot:{name:`GetWorldRootSnapshot`,I:Ne,O:Xt,kind:C.Unary},WatchWorldRootSnapshots:{name:`WatchWorldRootSnapshots`,I:Hn,O:Xt,kind:C.ServerStreaming},NewTransaction:{name:`NewTransaction`,I:zt,O:lt,kind:C.Unary},ExecuteWorldOp:{name:`ExecuteWorldOp`,I:N,O:Rn,kind:C.Unary},Sync:{name:`Sync`,I:Ue,O:Xe,kind:C.Unary},GetSeqno:{name:`GetSeqno`,I:tt,O:st,kind:C.Unary},WaitSeqno:{name:`WaitSeqno`,I:r,O:At,kind:C.Unary},BuildStorageCursor:{name:`BuildStorageCursor`,I:Ct,O:un,kind:C.Unary},AccessWorldState:{name:`AccessWorldState`,I:M,O:F,kind:C.Unary}}},ni=G.typeName;var ri=class{rpc;service;constructor(e,t){this.service=t?.service||ni,this.rpc=e,this.GetEngineInfo=this.GetEngineInfo.bind(this),this.GetWorldRootSnapshot=this.GetWorldRootSnapshot.bind(this),this.WatchWorldRootSnapshots=this.WatchWorldRootSnapshots.bind(this),this.NewTransaction=this.NewTransaction.bind(this),this.ExecuteWorldOp=this.ExecuteWorldOp.bind(this),this.Sync=this.Sync.bind(this),this.GetSeqno=this.GetSeqno.bind(this),this.WaitSeqno=this.WaitSeqno.bind(this),this.BuildStorageCursor=this.BuildStorageCursor.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this)}async GetEngineInfo(e,t){let n=Ae.create(e),r=await this.rpc.request(this.service,G.methods.GetEngineInfo.name,Ae.toBinary(n),t||void 0);return ne.fromBinary(r)}async GetWorldRootSnapshot(e,t){let n=Ne.create(e),r=await this.rpc.request(this.service,G.methods.GetWorldRootSnapshot.name,Ne.toBinary(n),t||void 0);return Xt.fromBinary(r)}WatchWorldRootSnapshots(e,t){let n=Hn.create(e),r=this.rpc.serverStreamingRequest(this.service,G.methods.WatchWorldRootSnapshots.name,Hn.toBinary(n),t||void 0);return j(Xt)(r)}async NewTransaction(e,t){let n=zt.create(e),r=await this.rpc.request(this.service,G.methods.NewTransaction.name,zt.toBinary(n),t||void 0);return lt.fromBinary(r)}async ExecuteWorldOp(e,t){let n=N.create(e),r=await this.rpc.request(this.service,G.methods.ExecuteWorldOp.name,N.toBinary(n),t||void 0);return Rn.fromBinary(r)}async Sync(e,t){let n=Ue.create(e),r=await this.rpc.request(this.service,G.methods.Sync.name,Ue.toBinary(n),t||void 0);return Xe.fromBinary(r)}async GetSeqno(e,t){let n=tt.create(e),r=await this.rpc.request(this.service,G.methods.GetSeqno.name,tt.toBinary(n),t||void 0);return st.fromBinary(r)}async WaitSeqno(e,t){let n=r.create(e),i=await this.rpc.request(this.service,G.methods.WaitSeqno.name,r.toBinary(n),t||void 0);return At.fromBinary(i)}async BuildStorageCursor(e,t){let n=Ct.create(e),r=await this.rpc.request(this.service,G.methods.BuildStorageCursor.name,Ct.toBinary(n),t||void 0);return un.fromBinary(r)}async AccessWorldState(e,t){let n=M.create(e),r=await this.rpc.request(this.service,G.methods.AccessWorldState.name,M.toBinary(n),t||void 0);return F.fromBinary(r)}};const K={typeName:`s4wave.world.WorldStateResourceService`,methods:{CompareObjectRecords:{name:`CompareObjectRecords`,I:$n,O:ur,kind:C.Unary},GetReadOnly:{name:`GetReadOnly`,I:de,O:kn,kind:C.Unary},Sync:{name:`Sync`,I:Ue,O:Xe,kind:C.Unary},GetSeqno:{name:`GetSeqno`,I:tt,O:st,kind:C.Unary},WaitSeqno:{name:`WaitSeqno`,I:r,O:At,kind:C.Unary},BuildStorageCursor:{name:`BuildStorageCursor`,I:Ct,O:un,kind:C.Unary},AccessWorldState:{name:`AccessWorldState`,I:M,O:F,kind:C.Unary},OpenNestedWorld:{name:`OpenNestedWorld`,I:g,O:we,kind:C.Unary},OpenOuterWorld:{name:`OpenOuterWorld`,I:nn,O:o,kind:C.Unary},CreateObject:{name:`CreateObject`,I:ar,O:ze,kind:C.Unary},GetObject:{name:`GetObject`,I:w,O:Ge,kind:C.Unary},IterateObjects:{name:`IterateObjects`,I:Mn,O:Yt,kind:C.Unary},RenameObject:{name:`RenameObject`,I:ye,O:Oe,kind:C.Unary},DeleteObject:{name:`DeleteObject`,I:v,O:Ee,kind:C.Unary},SetGraphQuad:{name:`SetGraphQuad`,I:k,O:Fe,kind:C.Unary},DeleteGraphQuad:{name:`DeleteGraphQuad`,I:He,O:b,kind:C.Unary},LookupGraphQuads:{name:`LookupGraphQuads`,I:fn,O:Wt,kind:C.Unary},LookupGraphQuadsBatch:{name:`LookupGraphQuadsBatch`,I:Et,O:Pt,kind:C.Unary},ListGraphEdgeBuckets:{name:`ListGraphEdgeBuckets`,I:In,O:xt,kind:C.Unary},ListObjectsWithType:{name:`ListObjectsWithType`,I:cn,O:Kn,kind:C.Unary},GetObjectRootRefsBatch:{name:`GetObjectRootRefsBatch`,I:Qe,O:ie,kind:C.Unary},GetObjectMetadataBatch:{name:`GetObjectMetadataBatch`,I:d,O:Ye,kind:C.Unary},GetObjectBodiesBatch:{name:`GetObjectBodiesBatch`,I:Le,O:fr,kind:C.Unary},QueryGraphPath:{name:`QueryGraphPath`,I:$t,O:he,kind:C.Unary},DeleteGraphObject:{name:`DeleteGraphObject`,I:p,O:nr,kind:C.Unary},ApplyWorldOp:{name:`ApplyWorldOp`,I:N,O:Rn,kind:C.Unary}}},ii=K.typeName;var ai=class{rpc;service;constructor(e,t){this.service=t?.service||ii,this.rpc=e,this.CompareObjectRecords=this.CompareObjectRecords.bind(this),this.GetReadOnly=this.GetReadOnly.bind(this),this.Sync=this.Sync.bind(this),this.GetSeqno=this.GetSeqno.bind(this),this.WaitSeqno=this.WaitSeqno.bind(this),this.BuildStorageCursor=this.BuildStorageCursor.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this),this.OpenNestedWorld=this.OpenNestedWorld.bind(this),this.OpenOuterWorld=this.OpenOuterWorld.bind(this),this.CreateObject=this.CreateObject.bind(this),this.GetObject=this.GetObject.bind(this),this.IterateObjects=this.IterateObjects.bind(this),this.RenameObject=this.RenameObject.bind(this),this.DeleteObject=this.DeleteObject.bind(this),this.SetGraphQuad=this.SetGraphQuad.bind(this),this.DeleteGraphQuad=this.DeleteGraphQuad.bind(this),this.LookupGraphQuads=this.LookupGraphQuads.bind(this),this.LookupGraphQuadsBatch=this.LookupGraphQuadsBatch.bind(this),this.ListGraphEdgeBuckets=this.ListGraphEdgeBuckets.bind(this),this.ListObjectsWithType=this.ListObjectsWithType.bind(this),this.GetObjectRootRefsBatch=this.GetObjectRootRefsBatch.bind(this),this.GetObjectMetadataBatch=this.GetObjectMetadataBatch.bind(this),this.GetObjectBodiesBatch=this.GetObjectBodiesBatch.bind(this),this.QueryGraphPath=this.QueryGraphPath.bind(this),this.DeleteGraphObject=this.DeleteGraphObject.bind(this),this.ApplyWorldOp=this.ApplyWorldOp.bind(this)}async CompareObjectRecords(e,t){let n=$n.create(e),r=await this.rpc.request(this.service,K.methods.CompareObjectRecords.name,$n.toBinary(n),t||void 0);return ur.fromBinary(r)}async GetReadOnly(e,t){let n=de.create(e),r=await this.rpc.request(this.service,K.methods.GetReadOnly.name,de.toBinary(n),t||void 0);return kn.fromBinary(r)}async Sync(e,t){let n=Ue.create(e),r=await this.rpc.request(this.service,K.methods.Sync.name,Ue.toBinary(n),t||void 0);return Xe.fromBinary(r)}async GetSeqno(e,t){let n=tt.create(e),r=await this.rpc.request(this.service,K.methods.GetSeqno.name,tt.toBinary(n),t||void 0);return st.fromBinary(r)}async WaitSeqno(e,t){let n=r.create(e),i=await this.rpc.request(this.service,K.methods.WaitSeqno.name,r.toBinary(n),t||void 0);return At.fromBinary(i)}async BuildStorageCursor(e,t){let n=Ct.create(e),r=await this.rpc.request(this.service,K.methods.BuildStorageCursor.name,Ct.toBinary(n),t||void 0);return un.fromBinary(r)}async AccessWorldState(e,t){let n=M.create(e),r=await this.rpc.request(this.service,K.methods.AccessWorldState.name,M.toBinary(n),t||void 0);return F.fromBinary(r)}async OpenNestedWorld(e,t){let n=g.create(e),r=await this.rpc.request(this.service,K.methods.OpenNestedWorld.name,g.toBinary(n),t||void 0);return we.fromBinary(r)}async OpenOuterWorld(e,t){let n=nn.create(e),r=await this.rpc.request(this.service,K.methods.OpenOuterWorld.name,nn.toBinary(n),t||void 0);return o.fromBinary(r)}async CreateObject(e,t){let n=ar.create(e),r=await this.rpc.request(this.service,K.methods.CreateObject.name,ar.toBinary(n),t||void 0);return ze.fromBinary(r)}async GetObject(e,t){let n=w.create(e),r=await this.rpc.request(this.service,K.methods.GetObject.name,w.toBinary(n),t||void 0);return Ge.fromBinary(r)}async IterateObjects(e,t){let n=Mn.create(e),r=await this.rpc.request(this.service,K.methods.IterateObjects.name,Mn.toBinary(n),t||void 0);return Yt.fromBinary(r)}async RenameObject(e,t){let n=ye.create(e),r=await this.rpc.request(this.service,K.methods.RenameObject.name,ye.toBinary(n),t||void 0);return Oe.fromBinary(r)}async DeleteObject(e,t){let n=v.create(e),r=await this.rpc.request(this.service,K.methods.DeleteObject.name,v.toBinary(n),t||void 0);return Ee.fromBinary(r)}async SetGraphQuad(e,t){let n=k.create(e),r=await this.rpc.request(this.service,K.methods.SetGraphQuad.name,k.toBinary(n),t||void 0);return Fe.fromBinary(r)}async DeleteGraphQuad(e,t){let n=He.create(e),r=await this.rpc.request(this.service,K.methods.DeleteGraphQuad.name,He.toBinary(n),t||void 0);return b.fromBinary(r)}async LookupGraphQuads(e,t){let n=fn.create(e),r=await this.rpc.request(this.service,K.methods.LookupGraphQuads.name,fn.toBinary(n),t||void 0);return Wt.fromBinary(r)}async LookupGraphQuadsBatch(e,t){let n=Et.create(e),r=await this.rpc.request(this.service,K.methods.LookupGraphQuadsBatch.name,Et.toBinary(n),t||void 0);return Pt.fromBinary(r)}async ListGraphEdgeBuckets(e,t){let n=In.create(e),r=await this.rpc.request(this.service,K.methods.ListGraphEdgeBuckets.name,In.toBinary(n),t||void 0);return xt.fromBinary(r)}async ListObjectsWithType(e,t){let n=cn.create(e),r=await this.rpc.request(this.service,K.methods.ListObjectsWithType.name,cn.toBinary(n),t||void 0);return Kn.fromBinary(r)}async GetObjectRootRefsBatch(e,t){let n=Qe.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectRootRefsBatch.name,Qe.toBinary(n),t||void 0);return ie.fromBinary(r)}async GetObjectMetadataBatch(e,t){let n=d.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectMetadataBatch.name,d.toBinary(n),t||void 0);return Ye.fromBinary(r)}async GetObjectBodiesBatch(e,t){let n=Le.create(e),r=await this.rpc.request(this.service,K.methods.GetObjectBodiesBatch.name,Le.toBinary(n),t||void 0);return fr.fromBinary(r)}async QueryGraphPath(e,t){let n=$t.create(e),r=await this.rpc.request(this.service,K.methods.QueryGraphPath.name,$t.toBinary(n),t||void 0);return he.fromBinary(r)}async DeleteGraphObject(e,t){let n=p.create(e),r=await this.rpc.request(this.service,K.methods.DeleteGraphObject.name,p.toBinary(n),t||void 0);return nr.fromBinary(r)}async ApplyWorldOp(e,t){let n=N.create(e),r=await this.rpc.request(this.service,K.methods.ApplyWorldOp.name,N.toBinary(n),t||void 0);return Rn.fromBinary(r)}};const oi={typeName:`s4wave.world.WatchWorldStateResourceService`,methods:{WatchWorldState:{name:`WatchWorldState`,I:yn,O:Nn,kind:C.ServerStreaming}}},si=oi.typeName;var ci=class{rpc;service;constructor(e,t){this.service=t?.service||si,this.rpc=e,this.WatchWorldState=this.WatchWorldState.bind(this)}WatchWorldState(e,t){let n=yn.create(e),r=this.rpc.serverStreamingRequest(this.service,oi.methods.WatchWorldState.name,yn.toBinary(n),t||void 0);return j(Nn)(r)}};const li={typeName:`s4wave.world.TxResourceService`,methods:{CommitMutations:{name:`CommitMutations`,I:mn,O:Kt,kind:C.Unary},Commit:{name:`Commit`,I:Vt,O:dt,kind:C.Unary},Discard:{name:`Discard`,I:an,O:c,kind:C.Unary}}},ui=li.typeName;var di=class{rpc;service;constructor(e,t){this.service=t?.service||ui,this.rpc=e,this.CommitMutations=this.CommitMutations.bind(this),this.Commit=this.Commit.bind(this),this.Discard=this.Discard.bind(this)}async CommitMutations(e,t){let n=mn.create(e),r=await this.rpc.request(this.service,li.methods.CommitMutations.name,mn.toBinary(n),t||void 0);return Kt.fromBinary(r)}async Commit(e,t){let n=Vt.create(e),r=await this.rpc.request(this.service,li.methods.Commit.name,Vt.toBinary(n),t||void 0);return dt.fromBinary(r)}async Discard(e,t){let n=an.create(e),r=await this.rpc.request(this.service,li.methods.Discard.name,an.toBinary(n),t||void 0);return c.fromBinary(r)}};const q={typeName:`s4wave.world.ObjectIteratorResourceService`,methods:{Err:{name:`Err`,I:_e,O:xe,kind:C.Unary},Valid:{name:`Valid`,I:nt,O:$e,kind:C.Unary},Key:{name:`Key`,I:mt,O:Sn,kind:C.Unary},Next:{name:`Next`,I:vt,O:ir,kind:C.Unary},Seek:{name:`Seek`,I:te,O:T,kind:C.Unary},Close:{name:`Close`,I:It,O:Dn,kind:C.Unary}}},fi=q.typeName;var pi=class{rpc;service;constructor(e,t){this.service=t?.service||fi,this.rpc=e,this.Err=this.Err.bind(this),this.Valid=this.Valid.bind(this),this.Key=this.Key.bind(this),this.Next=this.Next.bind(this),this.Seek=this.Seek.bind(this),this.Close=this.Close.bind(this)}async Err(e,t){let n=_e.create(e),r=await this.rpc.request(this.service,q.methods.Err.name,_e.toBinary(n),t||void 0);return xe.fromBinary(r)}async Valid(e,t){let n=nt.create(e),r=await this.rpc.request(this.service,q.methods.Valid.name,nt.toBinary(n),t||void 0);return $e.fromBinary(r)}async Key(e,t){let n=mt.create(e),r=await this.rpc.request(this.service,q.methods.Key.name,mt.toBinary(n),t||void 0);return Sn.fromBinary(r)}async Next(e,t){let n=vt.create(e),r=await this.rpc.request(this.service,q.methods.Next.name,vt.toBinary(n),t||void 0);return ir.fromBinary(r)}async Seek(e,t){let n=te.create(e),r=await this.rpc.request(this.service,q.methods.Seek.name,te.toBinary(n),t||void 0);return T.fromBinary(r)}async Close(e,t){let n=It.create(e),r=await this.rpc.request(this.service,q.methods.Close.name,It.toBinary(n),t||void 0);return Dn.fromBinary(r)}};({typeName:`s4wave.world.GraphPathQueryResourceService`,methods:{Next:{name:`Next`,I:Zn,O:cr,kind:C.Unary},Close:{name:`Close`,I:Jn,O:Ot,kind:C.Unary}}}).typeName;const J={typeName:`s4wave.world.ObjectStateResourceService`,methods:{GetKey:{name:`GetKey`,I:E,O:pe,kind:C.Unary},GetRootRef:{name:`GetRootRef`,I:D,O:it,kind:C.Unary},SetRootRef:{name:`SetRootRef`,I:qe,O:oe,kind:C.Unary},AccessWorldState:{name:`AccessWorldState`,I:M,O:F,kind:C.Unary},ApplyObjectOp:{name:`ApplyObjectOp`,I:Zt,O:ht,kind:C.Unary},IncrementRev:{name:`IncrementRev`,I:Vn,O:vn,kind:C.Unary},WaitRev:{name:`WaitRev`,I:at,O:je,kind:C.Unary}}},mi=J.typeName;var hi=class{rpc;service;constructor(e,t){this.service=t?.service||mi,this.rpc=e,this.GetKey=this.GetKey.bind(this),this.GetRootRef=this.GetRootRef.bind(this),this.SetRootRef=this.SetRootRef.bind(this),this.AccessWorldState=this.AccessWorldState.bind(this),this.ApplyObjectOp=this.ApplyObjectOp.bind(this),this.IncrementRev=this.IncrementRev.bind(this),this.WaitRev=this.WaitRev.bind(this)}async GetKey(e,t){let n=E.create(e),r=await this.rpc.request(this.service,J.methods.GetKey.name,E.toBinary(n),t||void 0);return pe.fromBinary(r)}async GetRootRef(e,t){let n=D.create(e),r=await this.rpc.request(this.service,J.methods.GetRootRef.name,D.toBinary(n),t||void 0);return it.fromBinary(r)}async SetRootRef(e,t){let n=qe.create(e),r=await this.rpc.request(this.service,J.methods.SetRootRef.name,qe.toBinary(n),t||void 0);return oe.fromBinary(r)}async AccessWorldState(e,t){let n=M.create(e),r=await this.rpc.request(this.service,J.methods.AccessWorldState.name,M.toBinary(n),t||void 0);return F.fromBinary(r)}async ApplyObjectOp(e,t){let n=Zt.create(e),r=await this.rpc.request(this.service,J.methods.ApplyObjectOp.name,Zt.toBinary(n),t||void 0);return ht.fromBinary(r)}async IncrementRev(e,t){let n=Vn.create(e),r=await this.rpc.request(this.service,J.methods.IncrementRev.name,Vn.toBinary(n),t||void 0);return vn.fromBinary(r)}async WaitRev(e,t){let n=at.create(e),r=await this.rpc.request(this.service,J.methods.WaitRev.name,at.toBinary(n),t||void 0);return je.fromBinary(r)}};const gi={typeName:`s4wave.world.TypedObjectResourceService`,methods:{AccessTypedObject:{name:`AccessTypedObject`,I:jt,O:Un,kind:C.Unary}}},_i=gi.typeName;var vi=class{rpc;service;constructor(e,t){this.service=t?.service||_i,this.rpc=e,this.AccessTypedObject=this.AccessTypedObject.bind(this)}async AccessTypedObject(e,t){let n=jt.create(e),r=await this.rpc.request(this.service,gi.methods.AccessTypedObject.name,jt.toBinary(n),t||void 0);return Un.fromBinary(r)}};const Y={typeName:`s4wave.bucket_lookup.BucketLookupCursorResourceService`,methods:{GetRef:{name:`GetRef`,I:Qn,O:lr,kind:C.Unary},FollowRef:{name:`FollowRef`,I:Ft,O:En,kind:C.Unary},GetBlock:{name:`GetBlock`,I:Bt,O:ut,kind:C.Unary},PutBlock:{name:`PutBlock`,I:Ve,O:ee,kind:C.Unary},PutBlockBatch:{name:`PutBlockBatch`,I:f,O:tr,kind:C.Unary},GetBlockExistsBatch:{name:`GetBlockExistsBatch`,I:pn,O:Gt,kind:C.Unary},BuildTransaction:{name:`BuildTransaction`,I:St,O:ln,kind:C.Unary},BuildTransactionAtRef:{name:`BuildTransactionAtRef`,I:Cn,O:Ln,kind:C.Unary},Clone:{name:`Clone`,I:qn,O:Dt,kind:C.Unary},Release:{name:`Release`,I:_,O:Te,kind:C.Unary},Unmarshal:{name:`Unmarshal`,I:rn,O:s,kind:C.Unary}}},yi=Y.typeName;var bi=class{rpc;service;constructor(e,t){this.service=t?.service||yi,this.rpc=e,this.GetRef=this.GetRef.bind(this),this.FollowRef=this.FollowRef.bind(this),this.GetBlock=this.GetBlock.bind(this),this.PutBlock=this.PutBlock.bind(this),this.PutBlockBatch=this.PutBlockBatch.bind(this),this.GetBlockExistsBatch=this.GetBlockExistsBatch.bind(this),this.BuildTransaction=this.BuildTransaction.bind(this),this.BuildTransactionAtRef=this.BuildTransactionAtRef.bind(this),this.Clone=this.Clone.bind(this),this.Release=this.Release.bind(this),this.Unmarshal=this.Unmarshal.bind(this)}async GetRef(e,t){let n=Qn.create(e),r=await this.rpc.request(this.service,Y.methods.GetRef.name,Qn.toBinary(n),t||void 0);return lr.fromBinary(r)}async FollowRef(e,t){let n=Ft.create(e),r=await this.rpc.request(this.service,Y.methods.FollowRef.name,Ft.toBinary(n),t||void 0);return En.fromBinary(r)}async GetBlock(e,t){let n=Bt.create(e),r=await this.rpc.request(this.service,Y.methods.GetBlock.name,Bt.toBinary(n),t||void 0);return ut.fromBinary(r)}async PutBlock(e,t){let n=Ve.create(e),r=await this.rpc.request(this.service,Y.methods.PutBlock.name,Ve.toBinary(n),t||void 0);return ee.fromBinary(r)}async PutBlockBatch(e,t){let n=f.create(e),r=await this.rpc.request(this.service,Y.methods.PutBlockBatch.name,f.toBinary(n),t||void 0);return tr.fromBinary(r)}async GetBlockExistsBatch(e,t){let n=pn.create(e),r=await this.rpc.request(this.service,Y.methods.GetBlockExistsBatch.name,pn.toBinary(n),t||void 0);return Gt.fromBinary(r)}async BuildTransaction(e,t){let n=St.create(e),r=await this.rpc.request(this.service,Y.methods.BuildTransaction.name,St.toBinary(n),t||void 0);return ln.fromBinary(r)}async BuildTransactionAtRef(e,t){let n=Cn.create(e),r=await this.rpc.request(this.service,Y.methods.BuildTransactionAtRef.name,Cn.toBinary(n),t||void 0);return Ln.fromBinary(r)}async Clone(e,t){let n=qn.create(e),r=await this.rpc.request(this.service,Y.methods.Clone.name,qn.toBinary(n),t||void 0);return Dt.fromBinary(r)}async Release(e,t){let n=_.create(e),r=await this.rpc.request(this.service,Y.methods.Release.name,_.toBinary(n),t||void 0);return Te.fromBinary(r)}async Unmarshal(e,t){let n=rn.create(e),r=await this.rpc.request(this.service,Y.methods.Unmarshal.name,rn.toBinary(n),t||void 0);return s.fromBinary(r)}};const X={typeName:`s4wave.block.cursor.BlockCursorResourceService`,methods:{Fetch:{name:`Fetch`,I:re,O:ue,kind:C.Unary},SetBlock:{name:`SetBlock`,I:Ut,O:Rt,kind:C.Unary},FollowRef:{name:`FollowRef`,I:On,O:le,kind:C.Unary},GetRef:{name:`GetRef`,I:jn,O:Jt,kind:C.Unary},IsDirty:{name:`IsDirty`,I:pt,O:xn,kind:C.Unary},MarkDirty:{name:`MarkDirty`,I:sn,O:Gn,kind:C.Unary},GetBlock:{name:`GetBlock`,I:i,O:kt,kind:C.Unary},Unmarshal:{name:`Unmarshal`,I:sr,O:_t,kind:C.Unary},IsSubBlock:{name:`IsSubBlock`,I:Fn,O:bt,kind:C.Unary},FollowSubBlock:{name:`FollowSubBlock`,I:rt,O:et,kind:C.Unary},SetAsSubBlock:{name:`SetAsSubBlock`,I:Tn,O:dn,kind:C.Unary},ClearRef:{name:`ClearRef`,I:fe,O:Ie,kind:C.Unary},ClearAllRefs:{name:`ClearAllRefs`,I:S,O:ce,kind:C.Unary},SetRef:{name:`SetRef`,I:ct,O:Xn,kind:C.Unary},GetExistingRef:{name:`GetExistingRef`,I:Bn,O:_n,kind:C.Unary},GetAllRefs:{name:`GetAllRefs`,I:ot,O:Me,kind:C.Unary},Detach:{name:`Detach`,I:Je,O:se,kind:C.Unary},DetachTransaction:{name:`DetachTransaction`,I:We,O:Ze,kind:C.Unary},DetachRecursive:{name:`DetachRecursive`,I:dr,O:u,kind:C.Unary},Parents:{name:`Parents`,I:Tt,O:Nt,kind:C.Unary}}},xi=X.typeName;var Si=class{rpc;service;constructor(e,t){this.service=t?.service||xi,this.rpc=e,this.Fetch=this.Fetch.bind(this),this.SetBlock=this.SetBlock.bind(this),this.FollowRef=this.FollowRef.bind(this),this.GetRef=this.GetRef.bind(this),this.IsDirty=this.IsDirty.bind(this),this.MarkDirty=this.MarkDirty.bind(this),this.GetBlock=this.GetBlock.bind(this),this.Unmarshal=this.Unmarshal.bind(this),this.IsSubBlock=this.IsSubBlock.bind(this),this.FollowSubBlock=this.FollowSubBlock.bind(this),this.SetAsSubBlock=this.SetAsSubBlock.bind(this),this.ClearRef=this.ClearRef.bind(this),this.ClearAllRefs=this.ClearAllRefs.bind(this),this.SetRef=this.SetRef.bind(this),this.GetExistingRef=this.GetExistingRef.bind(this),this.GetAllRefs=this.GetAllRefs.bind(this),this.Detach=this.Detach.bind(this),this.DetachTransaction=this.DetachTransaction.bind(this),this.DetachRecursive=this.DetachRecursive.bind(this),this.Parents=this.Parents.bind(this)}async Fetch(e,t){let n=re.create(e),r=await this.rpc.request(this.service,X.methods.Fetch.name,re.toBinary(n),t||void 0);return ue.fromBinary(r)}async SetBlock(e,t){let n=Ut.create(e),r=await this.rpc.request(this.service,X.methods.SetBlock.name,Ut.toBinary(n),t||void 0);return Rt.fromBinary(r)}async FollowRef(e,t){let n=On.create(e),r=await this.rpc.request(this.service,X.methods.FollowRef.name,On.toBinary(n),t||void 0);return le.fromBinary(r)}async GetRef(e,t){let n=jn.create(e),r=await this.rpc.request(this.service,X.methods.GetRef.name,jn.toBinary(n),t||void 0);return Jt.fromBinary(r)}async IsDirty(e,t){let n=pt.create(e),r=await this.rpc.request(this.service,X.methods.IsDirty.name,pt.toBinary(n),t||void 0);return xn.fromBinary(r)}async MarkDirty(e,t){let n=sn.create(e),r=await this.rpc.request(this.service,X.methods.MarkDirty.name,sn.toBinary(n),t||void 0);return Gn.fromBinary(r)}async GetBlock(e,t){let n=i.create(e),r=await this.rpc.request(this.service,X.methods.GetBlock.name,i.toBinary(n),t||void 0);return kt.fromBinary(r)}async Unmarshal(e,t){let n=sr.create(e),r=await this.rpc.request(this.service,X.methods.Unmarshal.name,sr.toBinary(n),t||void 0);return _t.fromBinary(r)}async IsSubBlock(e,t){let n=Fn.create(e),r=await this.rpc.request(this.service,X.methods.IsSubBlock.name,Fn.toBinary(n),t||void 0);return bt.fromBinary(r)}async FollowSubBlock(e,t){let n=rt.create(e),r=await this.rpc.request(this.service,X.methods.FollowSubBlock.name,rt.toBinary(n),t||void 0);return et.fromBinary(r)}async SetAsSubBlock(e,t){let n=Tn.create(e),r=await this.rpc.request(this.service,X.methods.SetAsSubBlock.name,Tn.toBinary(n),t||void 0);return dn.fromBinary(r)}async ClearRef(e,t){let n=fe.create(e),r=await this.rpc.request(this.service,X.methods.ClearRef.name,fe.toBinary(n),t||void 0);return Ie.fromBinary(r)}async ClearAllRefs(e,t){let n=S.create(e),r=await this.rpc.request(this.service,X.methods.ClearAllRefs.name,S.toBinary(n),t||void 0);return ce.fromBinary(r)}async SetRef(e,t){let n=ct.create(e),r=await this.rpc.request(this.service,X.methods.SetRef.name,ct.toBinary(n),t||void 0);return Xn.fromBinary(r)}async GetExistingRef(e,t){let n=Bn.create(e),r=await this.rpc.request(this.service,X.methods.GetExistingRef.name,Bn.toBinary(n),t||void 0);return _n.fromBinary(r)}async GetAllRefs(e,t){let n=ot.create(e),r=await this.rpc.request(this.service,X.methods.GetAllRefs.name,ot.toBinary(n),t||void 0);return Me.fromBinary(r)}async Detach(e,t){let n=Je.create(e),r=await this.rpc.request(this.service,X.methods.Detach.name,Je.toBinary(n),t||void 0);return se.fromBinary(r)}async DetachTransaction(e,t){let n=We.create(e),r=await this.rpc.request(this.service,X.methods.DetachTransaction.name,We.toBinary(n),t||void 0);return Ze.fromBinary(r)}async DetachRecursive(e,t){let n=dr.create(e),r=await this.rpc.request(this.service,X.methods.DetachRecursive.name,dr.toBinary(n),t||void 0);return u.fromBinary(r)}async Parents(e,t){let n=Tt.create(e),r=await this.rpc.request(this.service,X.methods.Parents.name,Tt.toBinary(n),t||void 0);return Nt.fromBinary(r)}},Ci=class e extends H{service;constructor(e){super(e),this.service=new Si(e.client)}async fetch(e){return await this.service.Fetch({},e)}async setBlock(e,t){await this.service.SetBlock(e,t)}async followRef(t,n){let r=await this.service.FollowRef(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async getRef(e){return await this.service.GetRef({},e)}async isDirty(e){return await this.service.IsDirty({},e)}async markDirty(e){await this.service.MarkDirty({},e)}async getBlock(e){return await this.service.GetBlock({},e)}async unmarshal(e={},t){return await this.service.Unmarshal(e,t)}async isSubBlock(e){return await this.service.IsSubBlock({},e)}async followSubBlock(t,n){let r=await this.service.FollowSubBlock(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async setAsSubBlock(e,t){await this.service.SetAsSubBlock(e,t)}async clearRef(e,t){await this.service.ClearRef(e,t)}async clearAllRefs(e){await this.service.ClearAllRefs({},e)}async setRef(e,t){await this.service.SetRef(e,t)}async getExistingRef(t,n){let r=await this.service.GetExistingRef(t,n);return r.resourceId?this.resourceRef.createResource(r.resourceId,e):null}async getAllRefs(e,t){return await this.service.GetAllRefs(e,t)}async detach(t,n){let r=await this.service.Detach(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async detachTransaction(t){let n=await this.service.DetachTransaction({},t);return this.resourceRef.createResource(n.resourceId??0,e)}async detachRecursive(t,n){let r=await this.service.DetachRecursive(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async parents(e){return await this.service.Parents({},e)}};const wi={typeName:`s4wave.block.transaction.BlockTransactionResourceService`,methods:{Write:{name:`Write`,I:be,O:ke,kind:C.Unary},GetRootCursor:{name:`GetRootCursor`,I:en,O:ge,kind:C.Unary}}},Ti=wi.typeName;var Ei=class{rpc;service;constructor(e,t){this.service=t?.service||Ti,this.rpc=e,this.Write=this.Write.bind(this),this.GetRootCursor=this.GetRootCursor.bind(this)}async Write(e,t){let n=be.create(e),r=await this.rpc.request(this.service,wi.methods.Write.name,be.toBinary(n),t||void 0);return ke.fromBinary(r)}async GetRootCursor(e,t){let n=en.create(e),r=await this.rpc.request(this.service,wi.methods.GetRootCursor.name,en.toBinary(n),t||void 0);return ge.fromBinary(r)}},Di=class extends H{service;constructor(e){super(e),this.service=new Ei(e.client)}async write(e,t){return await this.service.Write(e,t)}async getRootCursor(e){let t=await this.service.GetRootCursor({},e);return this.resourceRef.createResource(t.resourceId??0,Ci)}};function Oi(e){return!!e?.hash?.hash?.length}var ki=class e extends H{service;constructor(e){super(e),this.service=new bi(e.client)}async getRef(e){return await this.service.GetRef({},e)}async followRef(t,n){let r=await this.service.FollowRef(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}async getBlock(e,t){if(!Oi(e.ref)){let n=await this.getRef(t);return await this.service.GetBlock({...e,ref:n.ref?.rootRef},t)}return await this.service.GetBlock(e,t)}async putBlock(e,t){return await this.service.PutBlock(e,t)}async putBlockBatch(e,t){return await this.service.PutBlockBatch(e,t)}async getBlockExistsBatch(e,t){return await this.service.GetBlockExistsBatch(e,t)}async buildTransaction(e,t){let n=await this.service.BuildTransaction(e,t);return{transaction:this.resourceRef.createResource(n.transactionResourceId??0,Di),cursor:this.resourceRef.createResource(n.cursorResourceId??0,Ci)}}async buildTransactionAtRef(e,t){let n=await this.service.BuildTransactionAtRef(e,t);return{transaction:this.resourceRef.createResource(n.transactionResourceId??0,Di),cursor:this.resourceRef.createResource(n.cursorResourceId??0,Ci)}}async clone(t,n){let r=await this.service.Clone(t,n);return this.resourceRef.createResource(r.resourceId??0,e)}release(e){this.service.Release({},e).catch(()=>{}),super.release()}async unmarshal(e,t){return await this.service.Unmarshal(e,t)}},Ai=class extends H{service;objectKey;constructor(e,t){super(e),this.service=new hi(e.client),this.objectKey=t?.objectKey??``}getKey(){return this.objectKey}async getRootRef(e){return await this.service.GetRootRef({},e)}async setRootRef(e,t){return await this.service.SetRootRef({rootRef:e},t)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ki)}async applyObjectOp(e,t,n,r){return await this.service.ApplyObjectOp({opTypeId:e,opData:t,opSender:n},r)}async incrementRev(e){return await this.service.IncrementRev({},e)}async waitRev(e,t,n){return await this.service.WaitRev({rev:e,ignoreNotFound:t},n)}getDebugInfo(){return{label:this.objectKey||void 0}}},ji=class extends H{service;constructor(e){super(e),this.service=new pi(e.client)}async err(e){return(await this.service.Err({},e)).error||null}async valid(e){return(await this.service.Valid({},e)).valid??!1}async key(e){return(await this.service.Key({},e)).objectKey??``}async next(e){return(await this.service.Next({},e)).valid??!1}async seek(e,t){await this.service.Seek({objectKey:e},t)}async close(e){await this.service.Close({},e)}},Mi=class e extends H{service;readOnly;constructor(e,t){super(e),this.service=new ai(e.client),this.readOnly=t?.readOnly??!1}getResourceRef(){return this.resourceRef}getReadOnly(){return this.readOnly}async getSeqno(e){return{seqno:(await this.service.GetSeqno({},e)).seqno??0n}}async waitSeqno(e,t){return{seqno:(await this.service.WaitSeqno({seqno:e},t)).seqno??0n}}async compareObjectRecords(e,t){return this.service.CompareObjectRecords({bases:e},t)}async getObjectRootRefs(e,t){return(await this.service.GetObjectRootRefsBatch({objectKeys:e},t)).rootRefs??[]}async buildStorageCursor(e){let t=await this.service.BuildStorageCursor({},e);return this.resourceRef.createResource(t.resourceId??0,ki)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ki)}async openNestedWorld(t,n){let r=await this.service.OpenNestedWorld({objectKey:t},n);return this.resourceRef.createResource(r.resourceId??0,e,{readOnly:!0})}async openOuterWorld(t){let n=await this.service.OpenOuterWorld({},t);return this.resourceRef.createResource(n.resourceId??0,e,{readOnly:!0})}async createObject(e,t,n){let r=await this.service.CreateObject({objectKey:e,rootRef:t},n);return this.resourceRef.createResource(r.resourceId??0,Ai,{objectKey:r.objectKey})}async getObject(e,t){let n=await this.service.GetObject({objectKey:e},t);return n.found?this.resourceRef.createResource(n.resourceId??0,Ai,{objectKey:n.objectKey}):null}async iterateObjects(e,t,n){let r=await this.service.IterateObjects({prefix:e,reversed:t},n);return this.resourceRef.createResource(r.resourceId??0,ji)}async renameObject(e,t,n){let r=Ni(n),i=await this.service.RenameObject({oldObjectKey:e,newObjectKey:t,descendants:r.descendants},r.abortSignal);return this.resourceRef.createResource(i.resourceId??0,Ai,{objectKey:i.objectKey})}async deleteObject(e,t){return{deleted:(await this.service.DeleteObject({objectKey:e},t)).deleted??!1}}async setGraphQuad(e,t,n,r,i){await this.service.SetGraphQuad({quad:{subject:e,predicate:t,obj:n,label:r}},i)}async deleteGraphQuad(e,t,n,r,i){await this.service.DeleteGraphQuad({quad:{subject:e,predicate:t,obj:n,label:r}},i)}async lookupGraphQuads(e,t,n,r,i,a){return await this.service.LookupGraphQuads({filter:{subject:e,predicate:t,obj:n,label:r},limit:i},a)}async listGraphEdgeBuckets(e,t,n={}){return await this.service.ListGraphEdgeBuckets({originObjectKeys:e,predicate:n.predicate,limitPerOrigin:t,direction:n.direction},n.abortSignal)}async listObjectsWithType(e,t){return(await this.service.ListObjectsWithType({typeId:e},t)).objectKeys??[]}async deleteGraphObject(e,t){await this.service.DeleteGraphObject({objectKey:e},t)}async applyWorldOp(e,t,n,r){let i=await this.service.ApplyWorldOp({opTypeId:e,opData:t,opSender:n},r);return{seqno:i.seqno??0n,sysErr:i.sysErr??!1}}async accessTypedObject(e,t){let n=await new vi(this.resourceRef.client).AccessTypedObject({objectKey:e},t);return{resourceId:n.resourceId??0,typeId:n.typeId??``}}getDebugInfo(){return{label:this.readOnly?`(read-only)`:void 0}}};function Ni(e){return e?e instanceof AbortSignal?{abortSignal:e}:e:{}}var Pi=class extends Mi{txService;constructor(e,t){super(e,t),this.txService=new di(e.client)}async commit(e){await this.txService.Commit({},e)}async discard(e){await this.txService.Discard({},e)}},Fi=class extends H{service;watchService;constructor(e){super(e),this.service=new ri(e.client),this.watchService=new ci(e.client)}async getEngineInfo(e){return await this.service.GetEngineInfo({},e)}async sync(e){return(await this.service.Sync({},e)).fenced??!1}async getWorldRootSnapshot(e){return await this.service.GetWorldRootSnapshot({},e)}watchWorldRootSnapshots(e){return this.service.WatchWorldRootSnapshots({},e)}async newTransaction(e,t){let n=await this.service.NewTransaction({write:e},t);return this.resourceRef.createResource(n.resourceId??0,Pi,{readOnly:n.readOnly})}async executeWorldOp(e,t,n){return this.service.ExecuteWorldOp({opTypeId:e,opData:t},n)}async getSeqno(e){return await this.service.GetSeqno({},e)}async waitSeqno(e,t){return await this.service.WaitSeqno({seqno:e},t)}async buildStorageCursor(e){let t=await this.service.BuildStorageCursor({},e);return this.resourceRef.createResource(t.resourceId??0,ki)}async accessWorldState(e,t){let n=await this.service.AccessWorldState({ref:e},t);return this.resourceRef.createResource(n.resourceId??0,ki)}async accessTypedObject(e,t){let n=await new vi(this.resourceRef.client).AccessTypedObject({objectKey:e},t);return{resourceId:n.resourceId??0,typeId:n.typeId??``}}watchWorldState(e){return Ii(this.watchService,this.resourceRef,e)}};function Ii(e,t,n){let r=!1,i=[],a=new AbortController,o=()=>{r=!0,a.abort(),i.forEach(e=>e[Symbol.dispose]()),i.length=0};return(async()=>{try{let o=e.WatchWorldState({},a.signal);for await(let e of o){if(r)break;i.forEach(e=>e[Symbol.dispose]()),i.length=0;let a=new AbortController,o=t.createResource(e.resourceId??0,Mi),s=e=>(e&&i.push(e),e);try{await n(o,a.signal,s)}catch(e){e instanceof Error&&e.name!==`AbortError`&&console.error(`Error in watchWorldState callback:`,e)}finally{o[Symbol.dispose]()}}}catch(e){!r&&!(e instanceof Error&&e.name===`AbortError`)&&console.error(`WatchWorldState stream error:`,e)}finally{o()}})(),o}function Li(e){return`${Ri}${Ui(`application`,e)}/metadata`}const Ri=`sync/v1/`,zi=new TextEncoder;new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});function Bi(e,t,n){return`${Ri}${Ui(`application`,e)}/${Ui(`scope`,t)}/collections/${Ui(`collection`,n)}`}function Vi(e,t){return`${Ri}${Ui(`application`,e)}/${Ui(`scope`,t)}/receipts`}function Hi(e){return Wi(`record key`,e,1024)}function Ui(e,t){return Gi(Wi(e,t,256))}function Wi(e,t,n){if(t.length===0)throw TypeError(`invalid ${e}: must be nonempty`);if(!t.isWellFormed())throw TypeError(`invalid ${e}: must be well-formed Unicode`);let r=zi.encode(t);if(r.length>n)throw TypeError(`invalid ${e}: exceeds ${n} UTF-8 bytes`);return r}function Gi(e){let t=``;for(let n of e)t+=(n>>4).toString(16)+(n&15).toString(16);return t}function Ki(e){if(!e.id||!Number.isSafeInteger(e.version)||e.version<1||e.version>4294967295)throw new L(`VALIDATION`,`Application ID and positive version are required`);return e}async function qi(e,t,n){try{z(t);let r=await e[`~standard`].validate(t);if(r.issues)throw new L(`VALIDATION`,`${n} does not match its schema`);return z(r.value),r.value}catch(e){throw e instanceof L?e:new L(`VALIDATION`,`${n} must be a valid JSON value matching its schema`)}}const Ji=new TextEncoder,Yi=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});var Xi=class{state;options;stores=new Map;released=!1;writeCount=0;writeBytes=0;constructor(e,t){this.state=e,this.options=t}async store(e){this.checkOpen();let t=this.stores.get(e);return t||(t=(async()=>{let t=await ti(this.state,e,this.options.write,this.options.signal);if(t)try{return{store:t,tx:await t.openTransaction(this.options.write,this.options.signal)}}catch(e){throw t.release(),e}})(),this.stores.set(e,t)),(await t)?.tx}collections(e,t=[]){return{collection:n=>{let{schema:r,instance:i,limits:a,signal:o}=this.options;if(!Object.hasOwn(r.collections,n))throw new L(`MISSING_COLLECTION`,`Collection is not declared`);let s=r.collections[n],c=async r=>(this.checkOpen(),await this.options.authorize(e,n,r),t.some(e=>e.collection===n&&e.action===r)||t.push({collection:n,action:r}),this.store(Bi(i,e.scope,n)));return{get:async e=>{let t=$i(e),n=await(await c(`read`))?.get(t,o);if(n?.found&&n.data.length>a.maxRecordBytes)throw new L(`QUERY_LIMIT`,`Record exceeds the configured byte limit`);return n?.found?V(n.data):void 0},scan:async(e={})=>{let t=e.prefix??``,n=t?$i(t):new Uint8Array,r=await c(`read`);return r?(await r.scanRecords(n,{maxRecords:a.maxRecords,maxBytes:a.maxSnapshotBytes},o)).map(e=>({key:Yi.decode(e.key),value:V(e.value)})):[]},put:async(e,t)=>{let n=$i(e),r=await c(`write`);if(!this.options.write||!r)throw new L(`DENIED`,`Transaction is read-only`);let i=B(await qi(s,t,`Record`));if(i.length>a.maxRecordBytes)throw new L(`QUERY_LIMIT`,`Record exceeds the configured byte limit`);this.trackWrite(n.length+i.length),await r.set(n,i,o)},delete:async e=>{let t=$i(e),n=await c(`write`);if(!this.options.write||!n)throw new L(`DENIED`,`Transaction is read-only`);this.trackWrite(t.length),await n.delete(t,o)}}}}}async execute(e,t,n){if(this.checkOpen(),!n||n.length>128)throw new L(`VALIDATION`,`Request ID must contain 1 to 128 characters`);let{schema:r,instance:i,signal:a}=this.options,o=t.kind!==`get`&&t.kind!==`scan`;if(o&&!this.options.write)throw new L(`DENIED`,`Transaction is read-only`);let s=this.fingerprint(t);if(Ji.encode(s).length>this.options.limits.maxRecordBytes)throw new L(`QUERY_LIMIT`,`Operation exceeds the configured byte limit`);let c=[],l=this.collections(e,c);`collection`in t&&await this.options.authorize(e,t.collection,o?`write`:`read`);let u=o?await this.readAcceptance(e,t,n):void 0;if(u)return{value:u.value,duplicate:!0};let d=o?await this.store(Vi(i,e.scope)):void 0,f;if(t.kind===`mutate`){let n=Object.hasOwn(r.mutations,t.name)?r.mutations[t.name]:void 0,i=Object.hasOwn(this.options.mutations,t.name)?this.options.mutations[t.name]:void 0;if(!n||!i)throw new L(`VALIDATION`,`Mutation is not declared and implemented`);let o=await qi(n.input,t.input,`Mutation input`),s=await Zi({...l,principal:e,scope:e.scope,signal:a},e=>i(e,o));if(f=await qi(n.output,s,`Mutation output`),B(f).length>this.options.limits.maxRecordBytes)throw new L(`QUERY_LIMIT`,`Mutation result exceeds the configured byte limit`)}else{let e=l.collection(t.collection);switch(t.kind){case`get`:{let n=await e.get(t.key);f=n===void 0?{found:!1}:{found:!0,value:n};break}case`scan`:f=await e.scan({prefix:t.prefix});break;case`put`:await e.put(t.key,t.value),f=null;break;case`delete`:await e.delete(t.key),f=null}}return d&&await this.recordAcceptance(e,t,n,f,c),{value:f,duplicate:!1}}async upgrade(e,t,n,r){if(this.checkOpen(),!n||n.length>128)throw new L(`VALIDATION`,`Request ID must contain 1 to 128 characters`);if(Ji.encode(this.fingerprint(t)).length>this.options.limits.maxRecordBytes)throw new L(`QUERY_LIMIT`,`Upgrade exceeds the input byte limit`);if(!this.options.write)throw new L(`DENIED`,`Transaction is read-only`);if(await this.readAcceptance(e,t,n))return;let i=[];await r(this.collections(e,i)),await this.recordAcceptance(e,t,n,null,i)}async recordAcceptance(e,t,n,r,i){let{instance:a,signal:o}=this.options;await(await this.store(Li(a))).set(Ji.encode(`scope/${z(e.scope)}`),B(e.scope),o),await(await this.store(Vi(a,e.scope))).set(Ji.encode(z([e.subject,n])),B({fingerprint:this.fingerprint(t),result:r,accesses:i}),o)}async readAcceptance(e,t,n){this.checkOpen();let r=await this.store(Vi(this.options.instance,e.scope)),i=Ji.encode(z([e.subject,n])),a=await r?.get(i,this.options.signal);if(!a?.found)return;let o=V(a.data);if(o.fingerprint!==this.fingerprint(t))throw new L(`CONFLICT`,`Request ID was already used for different input`,n);for(let t of o.accesses)await this.options.authorize(e,t.collection,t.action);return{value:o.result}}fingerprint(e){return z({application:this.options.schema.id,version:this.options.schema.version,revision:this.options.revision??``,operation:e})}async flush(){this.checkOpen();let e=await Promise.all(this.stores.values());for(let t of e)await t?.tx.commit(this.options.signal)}async release(){if(this.released)return;this.released=!0;let e=await Promise.allSettled(this.stores.values());await Promise.all(e.map(async e=>{if(e.status===`fulfilled`&&e.value)try{await e.value.tx.discard()}catch{}finally{e.value.store.release()}}))}trackWrite(e){if(this.writeCount++,this.writeBytes+=e,this.writeCount>this.options.limits.maxRecords||this.writeBytes>this.options.limits.maxSnapshotBytes)throw new L(`QUERY_LIMIT`,`Mutation exceeds the transaction data limit`)}checkOpen(){if(this.released)throw new L(`CLOSED`,`Transaction is closed`);this.options.signal.throwIfAborted()}};async function Zi(e,t){return Qi(n=>t({...e,...n(e)}))}async function Qi(e){let t=!0,n=new Set,r=e=>{if(!t)return Promise.reject(new L(`CLOSED`,`Mutation has ended`));let r=e();return n.add(r),r.then(()=>n.delete(r),()=>n.delete(r)),r};try{let t=await e(e=>({collection:t=>{let n=e.collection(t);return{get:e=>r(()=>n.get(e)),scan:e=>r(()=>n.scan(e)),put:(e,t)=>r(()=>n.put(e,t)),delete:e=>r(()=>n.delete(e))}}}));if(n.size)throw new L(`VALIDATION`,`Await every collection operation before returning`);return t}finally{t=!1,await Promise.allSettled(n)}}function $i(e){try{return Hi(e)}catch{throw new L(`VALIDATION`,`Record key must be nonempty UTF-8 within 1024 bytes`)}}async function ea(e,t){let n=new Map,r=new Set,i=!0,a=(e,t,r)=>{let i=n.get(e),a=i.records.get(t);a||(a={paths:new Map,shapes:new Map},i.records.set(t,a));let o=(e,t=!0)=>{(t?a.paths:a.shapes).set(JSON.stringify(e),e)};if(r!==void 0)return na(V(B(r)),[],o)},o={collection:t=>{if(!i)throw new L(`CLOSED`,`Query evaluation has ended`);let o=e.collection(t);n.has(t)||n.set(t,{prefixes:new Set,records:new Map});let s=e=>{if(!i)return Promise.reject(new L(`CLOSED`,`Query evaluation has ended`));let t=e();return r.add(t),t.finally(()=>r.delete(t)).catch(()=>{}),t};return{get:e=>s(async()=>a(t,e,await o.get(e))),scan:(e={})=>s(async()=>(n.get(t).prefixes.add(e.prefix??``),(await o.scan(e)).map(e=>({key:e.key,value:a(t,e.key,e.value)}))))}}};try{let e=await t(o);if(r.size)throw new L(`VALIDATION`,`Query must await every snapshot read`);return{value:V(B(e)),dependencies:[...n].map(([e,t])=>({collection:e,prefixes:[...t.prefixes],records:[...t.records].map(([e,{paths:t,shapes:n}])=>({key:e,paths:[...t.values()],shapes:[...n.values()]}))}))}}finally{i=!1,await Promise.allSettled(r)}}var ta=class{collections;constructor(e){this.collections=new Map(e.map(e=>[e.collection,{prefixes:e.prefixes,records:new Map(e.records.map(e=>[e.key,e]))}]))}watchesKey(e,t){let n=this.collections.get(e);return!!n&&(n.records.has(t)||n.prefixes.some(e=>t.startsWith(e)))}affected(e){let t=this.collections.get(e.collection);if(!t)return!1;let n=e.before===void 0!=(e.after===void 0);if(n&&t.prefixes.some(t=>e.key.startsWith(t)))return!0;let r=t.records.get(e.key);return r?n?!0:r.paths.some(t=>!ia(ra(e.before,t),ra(e.after,t)))||r.shapes.some(t=>aa(ra(e.before,t))!==aa(ra(e.after,t))):!1}unknown(e){return this.collections.has(e)}};function na(e,t,n){return typeof e!=`object`||!e?(n(t),e):(n(t,!1),new Proxy(e,{get(e,r,i){if(typeof r!=`string`)return Reflect.get(e,r,i);let a=[...t,r],o=Reflect.get(e,r,i);return typeof o==`function`?o:na(o,a,n)},has(e,r){return n(t),Reflect.has(e,r)},ownKeys(e){return n(t),Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,r){typeof r==`string`&&n([...t,r]);let i=Reflect.getOwnPropertyDescriptor(e,r);return i&&`value`in i&&typeof r==`string`?{...i,value:na(i.value,[...t,r],n)}:i},set(){throw new L(`VALIDATION`,`Queries cannot mutate snapshot values`)},deleteProperty(){throw new L(`VALIDATION`,`Queries cannot mutate snapshot values`)},defineProperty(){throw new L(`VALIDATION`,`Queries cannot mutate snapshot values`)},setPrototypeOf(){throw new L(`VALIDATION`,`Queries cannot mutate snapshot values`)},preventExtensions(){throw new L(`VALIDATION`,`Queries cannot mutate snapshot values`)}}))}function ra(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function ia(e,t){return e===void 0||t===void 0?e===t:z(e)===z(t)}function aa(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}var oa=class{options;engine;controller=new AbortController;producers=new Map;active=new Set;closing;counts={snapshots:0,processedSeqno:0n,evaluations:0,keyReads:0,rangeScans:0};diagnostics(){return{...this.counts}}measureReads(e){return{collection:t=>{let n=e.collection(t);return{get:async e=>(this.counts.keyReads++,n.get(e)),scan:async e=>(this.counts.rangeScans++,n.scan(e))}}}}constructor(e){this.options=e,this.engine=new Fi(e.engine.resourceRef.createRef(e.engine.id))}async*watch(e,t,n){let r=AbortSignal.any([this.controller.signal,...[n,this.options.signal,this.options.principal.signal].filter(e=>e!==void 0)]);r.throwIfAborted();let i=await qi(e.input,V(B(t)),`Query input`);r.throwIfAborted();let a=z(i),o=this.producers.get(e);o||(o=new Map,this.producers.set(e,o));let s=o.get(a);s||(s=this.start(e,i,()=>{o.get(a)===s&&o.delete(a),!o.size&&this.producers.get(e)===o&&this.producers.delete(e)}),o.set(a,s)),s.users++;let c=s.state.getIterable()[Symbol.asyncIterator](),l=()=>{c.return?.()};r.addEventListener(`abort`,l,{once:!0});try{for(;;){let e=await c.next();if(e.done||r.aborted)break;this.checkPrincipal();for(let t of e.value.collections)await this.options.authorize(this.options.principal,t,`read`);r.throwIfAborted();let t=e.value.snapshot;if(t.status===`error`){yield t;break}yield{...t,value:V(B(t.value))}}}finally{r.removeEventListener(`abort`,l),await c.return?.(),--s.users===0&&(o.get(a)===s&&o.delete(a),!o.size&&this.producers.get(e)===o&&this.producers.delete(e),s.controller.abort(),await s.done)}}close(){return this.closing??=(async()=>{this.controller.abort(),await Promise.allSettled(this.active),this.engine.release()})()}start(e,t,n){let r,i=new Mr(async()=>r,{mostRecentOnly:!0}),a=new AbortController,o=AbortSignal.any([this.controller.signal,a.signal,...[this.options.signal,this.options.principal.signal].filter(e=>e!==void 0)]),s=(async()=>{try{for await(let n of this.evaluate(e,t,o))r=n,i.pushChangeEvent(n)}catch(e){o.aborted||(r={snapshot:{status:`error`,error:R(e)},collections:[]},i.pushChangeEvent(r))}finally{n()}})();return this.active.add(s),s.finally(()=>this.active.delete(s)),{controller:a,state:i,done:s,users:0}}async*evaluate(e,t,n){let r,i,a=new Map,o=[],s=0n;for(;;){n.throwIfAborted(),this.checkPrincipal();let c=await this.engine.newTransaction(!1,n),l=new Xi(c,{...this.options,write:!1,signal:n}),u;try{await this.options.checkState?.(c,n),s=(await c.getSeqno(n)).seqno,this.counts.snapshots++;let d=this.measureReads(l.collections(this.options.principal)),f=!r;if(r){let e=await this.roots(c,r.dependencies,n),t=r.dependencies.filter((t,n)=>e[n].signature!==o[n].signature);if(t.length){f=e.some((e,t)=>e.type!==o[t].type);let s=f?{}:await c.compareObjectRecords(t.map(({collection:e})=>{let t=r.dependencies.findIndex(t=>t.collection===e);return{objectKey:Bi(this.options.instance,this.options.principal.scope,e),rootRef:o[t].ref}}),n);for(let e=0;!f&&e<t.length;e++){let n=t[e],r=s.changes?.[e];if(!r||r.unknown){f=!0;break}let o=d.collection(n.collection),c=a.get(n.collection),l=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),u=new Set(r.keys?.map(e=>l.decode(e)));for(let e of u){if(!i.watchesKey(n.collection,e))continue;let t=await o.get(e);if(i.affected({collection:n.collection,key:e,before:c.get(e),after:t})){f=!0;break}c.set(e,t)}}}o=e}if(f){if(a=new Map,this.counts.evaluations++,r=await ea(sa(d,a,this.options.limits.maxSnapshotBytes,this.options.limits.maxRecords),n=>e.evaluate(n,V(B(t)))),i=new ta(r.dependencies),o=await this.roots(c,r.dependencies,n),B(r.value).length>this.options.limits.maxSnapshotBytes)throw new L(`QUERY_LIMIT`,`Query result exceeds the configured byte limit`);u={snapshot:{status:`current`,value:r.value,seqno:s},collections:r.dependencies.map(({collection:e})=>e)}}}finally{await l.release();try{await c.discard()}finally{c.release()}}this.counts.processedSeqno=s,u&&(yield u),await this.engine.waitSeqno(s+1n,n)}}async roots(e,t,n){let r=t.map(({collection:e})=>Bi(this.options.instance,this.options.principal.scope,e));for(let e of t)await this.options.authorize(this.options.principal,e.collection,`read`);let i=await e.getObjectRootRefs(r,n);return Promise.all(i.map(async(t,i)=>{let a=t.exists?await Yr(e,r[i],n):``;return{type:a,ref:t.rootRef,signature:`${a}:${Array.from(y.toBinary(t)).join(`,`)}`}}))}checkPrincipal(){let e=this.options.principal;if(!e.subject||!e.scope||e.signal?.aborted||e.expiresAt!==void 0&&(!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()))throw new L(`AUTHENTICATION`,`Authentication is no longer valid`)}};function sa(e,t,n,r){let i=0,a=0,o=(e,o,s)=>{let c=t.get(e);if(c||(c=new Map,t.set(e,c)),!c.has(o)&&(i+=B([e,o,s??null]).length,++a>r||i>n))throw new L(`QUERY_LIMIT`,`Query reads exceed the configured byte limit`);c.set(o,s)};return{collection(n){let r=e.collection(n);return t.has(n)||t.set(n,new Map),{async get(e){let t=await r.get(e);return o(n,e,t),t},async scan(e){let t=await r.scan(e);for(let e of t)o(n,e.key,e.value);return t}}}}}const ca=new TextEncoder,la=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),ua=ca.encode(`version`);var da=class{options;schema;instance;signal;limits;engine;controller=new AbortController;active=new Set;queries=new Map;functionQueries=new Set;closing;constructor(e){this.options=e,this.schema=Ki(e.schema),this.instance=e.instance??this.schema.id;try{Vi(this.instance,`schema`);for(let[e,t]of Object.entries(this.schema.collections))if(Bi(this.instance,`schema`,e),t[`~standard`]?.version!==1)throw Error(`invalid validator`);for(let[t,n]of Object.entries(this.schema.mutations))if(!Object.hasOwn(e.mutations,t)||n.input[`~standard`]?.version!==1||n.output[`~standard`]?.version!==1)throw Error(`invalid mutation`)}catch{throw new L(`VALIDATION`,`Schema requires valid names, Standard Schema v1 validators, and every mutation handler`)}this.signal=this.controller.signal,this.limits={maxRecords:e.limits?.maxRecords??1e4,maxSnapshotBytes:e.limits?.maxSnapshotBytes??8388608,maxRecordBytes:e.limits?.maxRecordBytes??262144};for(let e of Object.values(this.limits))if(!Number.isSafeInteger(e)||e<1)throw new L(`VALIDATION`,`Limits must be positive integers`);this.engine=new Fi(e.engine.resourceRef.createRef(e.engine.id))}async initialize(e){let t=await this.engine.newTransaction(!0,this.signal),n=this.transaction(t,!0,this.signal,!0);try{let r=await n.store(Li(this.instance));if(!r)throw Error(`missing metadata store`);let i=await r.get(ua,this.signal),a=i.found?V(i.data):void 0;if(a&&a.application!==this.schema.id)throw new L(`SCHEMA_MISMATCH`,`This dataset belongs to a different application`);if(a&&a.version!==this.schema.version){if(!e||e.from!==a.version)throw new L(`SCHEMA_MISMATCH`,`Stored version differs; supply an explicit maintenance migration`);await e.run({signal:this.signal,scopes:async()=>(await r.scanRecords(ca.encode(`scope/`),{maxRecords:this.limits.maxRecords,maxBytes:this.limits.maxSnapshotBytes},this.signal)).map(e=>V(e.value)),scope:e=>n.collections({subject:`admin`,scope:e})})}await r.set(ua,B({application:this.schema.id,version:this.schema.version}),this.signal),await n.flush(),await t.commit(),await this.engine.sync()}finally{await n.release();try{await t.discard()}finally{t.release()}}}async authorize(e,t,n,r=!1){if(this.checkPrincipal(e),!Object.hasOwn(this.schema.collections,t))throw new L(`MISSING_COLLECTION`,`Collection is not declared`);if(!r&&!await this.options.authorize({principal:e,scope:e.scope,collection:t,action:n}))throw new L(`DENIED`,`Collection ${n} is not authorized`)}async openCollection(e,t){try{await this.authorize(e,t,`read`)}catch(n){if(!(n instanceof L)||n.code!==`DENIED`)throw n;await this.authorize(e,t,`write`)}}execute(e,t,n={},r=!1){if(this.closing)return Promise.reject(new L(`CLOSED`,`Server is closed`));let i=this.run(e,t,n,r);return this.active.add(i),i.finally(()=>this.active.delete(i)).catch(()=>{}),i}access(e){let t={...e},n=this,r,i=0;return{...Ar((e,n)=>this.execute(t,e,n)),async*watch(e,a,o){if(n.closing)throw new L(`CLOSED`,`Server is closed`);let s=r??=new oa({schema:n.schema,instance:n.instance,mutations:n.options.mutations,engine:n.engine,limits:n.limits,principal:t,signal:n.signal,authorize:(e,t,r)=>n.authorize(e,t,r)});n.functionQueries.add(s),i++;try{yield*s.watch(e,a,o)}finally{--i===0&&(r=void 0,n.functionQueries.delete(s),await s.close())}}}}close(){return this.closing??=(async()=>{this.controller.abort(new L(`CLOSED`,`Server is closing`)),await Promise.all(Array.from(this.functionQueries,e=>e.close())),await Promise.allSettled(this.active),this.engine.release()})(),this.closing}async*watch(e,t,n,r){if(this.closing)throw new L(`CLOSED`,`Server is closed`);let i=AbortSignal.any([this.signal,r,...e.signal?[e.signal]:[]]),a=Promise.withResolvers();this.active.add(a.promise);let o,s,c=()=>{s?.return?.()},l=z([e.scope,t,n]);try{for(await this.authorize(e,t,`read`),i.throwIfAborted(),o=this.queries.get(l)??this.startQuery(l,e.scope,t,n),o.users++,s=o.state.getIterable()[Symbol.asyncIterator](),i.addEventListener(`abort`,c,{once:!0});;){let n=await s.next();if(n.done||i.aborted)break;if(await this.authorize(e,t,`read`),i.throwIfAborted(),`error`in n.value)throw n.value.error;yield n.value.entries}}finally{i.removeEventListener(`abort`,c),await s?.return?.(),o&&--o.users===0&&(this.queries.get(l)===o&&this.queries.delete(l),o.controller.abort()),a.resolve(),this.active.delete(a.promise)}}startQuery(e,t,n,r){let i,a={controller:new AbortController,state:new Mr(async()=>i,{mostRecentOnly:!0}),users:0};this.queries.set(e,a);let o=AbortSignal.any([this.signal,a.controller.signal]),s=e=>{i=e,a.state.pushChangeEvent(e)},c=(async()=>{try{for await(let e of this.watchQuery(t,n,r,o))s({entries:e})}catch(e){o.aborted||s({error:R(e)})}finally{this.queries.get(e)===a&&this.queries.delete(e)}})();return this.active.add(c),c.finally(()=>this.active.delete(c)).catch(()=>{}),a}async*watchQuery(e,t,n,r){let i;try{let a=Bi(this.instance,e,t),o=n?this.recordKey(n):new Uint8Array,s=!1;for(;;){r.throwIfAborted();let e=await this.engine.getSeqno(r),t=await this.engine.newTransaction(!1,r),n=!1;try{let e=await t.getObject(a,r);if(n=e!==null,e?.release(),n&&await Yr(t,a,r)!==`kv/store`)throw new ei}finally{try{await t.discard()}finally{t.release()}}if(n)break;s||=(yield[],!0),await this.engine.waitSeqno((e.seqno??0n)+1n,r)}let c=await this.engine.accessTypedObject(a,r);i=this.engine.resourceRef.createResource(c.resourceId,Vr);for await(let e of i.watchRecords(o,{maxRecords:this.limits.maxRecords,maxBytes:this.limits.maxSnapshotBytes},r))yield e.map(e=>({key:la.decode(e.key),value:V(e.value)}))}catch(e){if(e instanceof Br)throw new L(`QUERY_LIMIT`,e.message);if(!r.aborted)throw R(e)}finally{i?.release()}}checkPrincipal(e){if(!e.subject||!e.scope||e.signal?.aborted||e.expiresAt!==void 0&&(!Number.isFinite(e.expiresAt)||e.expiresAt<=Date.now()))throw new L(`AUTHENTICATION`,`Authentication is no longer valid`);try{if(Vi(this.instance,e.scope),Hi(e.subject).length>256)throw Error(`invalid subject`)}catch{throw new L(`AUTHENTICATION`,`Principal subject and scope must be valid identities within 256 UTF-8 bytes`)}}async run(e,t,n,r){let i,a,o=!1,s=t.kind!==`get`&&t.kind!==`scan`,c=n.requestId??hr(),l=AbortSignal.any([this.signal,...[e.signal,n.signal].filter(e=>!!e)]);try{this.checkPrincipal(e),l.throwIfAborted(),i=await this.engine.newTransaction(s,l),a=this.transaction(i,s,l,r);let n=await a.execute(e,t,c);return this.checkPrincipal(e),l.throwIfAborted(),s&&!n.duplicate&&(await a.flush(),l.throwIfAborted(),o=!0,await i.commit()),s&&(await a.release(),a=void 0,await i.discard(),i.release(),i=void 0,await this.engine.sync()),n.value}catch(t){throw t instanceof ei?new L(`SCHEMA_MISMATCH`,t.message):o?new L(`UNCERTAIN`,`Acceptance could not be confirmed; retry the same request ID and input`,c):t instanceof Br?new L(`QUERY_LIMIT`,t.message):l.aborted?(this.checkPrincipal(e),new L(this.signal.aborted?`CLOSED`:`UNAVAILABLE`,`Operation was canceled`)):R(t)}finally{if(await a?.release(),i)try{await i.discard()}catch{}finally{i.release()}}}transaction(e,t,n,r){return new Xi(e,{schema:this.schema,instance:this.instance,mutations:this.options.mutations,limits:this.limits,write:t,signal:n,authorize:(e,t,n)=>this.authorize(e,t,n,r)})}recordKey(e){try{return Hi(e)}catch{throw new L(`VALIDATION`,`Record key must be nonempty UTF-8 within 1024 bytes`)}}};function fa(e){let t=new AbortController;return e&&(e.aborted?t.abort():e.addEventListener(`abort`,()=>t.abort(),{once:!0})),t}function pa(e=500){return()=>e}var ma=class{fn;result;get canceled(){return this._canceled}_backoffFn;_errorCb;_abortSignal;_abortListener;_canceled;_resolve;_reject;_currError;_cancelRetry;_setTimeout;_clearTimeout;constructor(e,t){this.fn=e,this._abortSignal=t?.abortSignal,this._abortSignal&&(this._abortListener=()=>this.cancel(),this._abortSignal.addEventListener(`abort`,this._abortListener,{once:!0})),this._backoffFn=t?.backoffFn||pa(),this._errorCb=t?.errorCb??(e=>{console.warn(`Retry: retrying after error`,{error:e})}),this._setTimeout=t?.setTimeout||setTimeout.bind(globalThis),this._clearTimeout=t?.clearTimeout||clearTimeout.bind(globalThis),this.result=new Promise((e,t)=>{this._resolve=e,this._reject=t}),this.result.catch(()=>{}),queueMicrotask(this._execute.bind(this))}cancel(){this._canceled||(this._canceled=!0,this._clearAbortListener(),this._cancelRetry&&this._cancelRetry(),this._reject&&this._reject(this._currError))}async _execute(){do try{let e=this._abortSignal;if(this._canceled||e?.aborted){this.cancel();return}let t=await this.fn();this._resolve&&(this._clearAbortListener(),this._resolve(t));return}catch(e){let t=this._abortSignal;if(this._currError=e,this._canceled||t?.aborted){this._reject&&(this._clearAbortListener(),this._reject(e));return}this._errorCb&&this._errorCb(e),await new Promise(e=>{let n=null;if(t?.aborted){e();return}this._cancelRetry=()=>{n&&this._clearTimeout(n),e()},n=this._setTimeout(()=>{this._cancelRetry=void 0,e()},this._backoffFn())})}while(1)}_clearAbortListener(){this._abortSignal&&this._abortListener&&(this._abortSignal.removeEventListener(`abort`,this._abortListener),this._abortListener=void 0)}};function ha(e,t,n){return new ma(t.bind(void 0,e),{...n,abortSignal:e}).result}const ga=new Proxy({released:!0},{get(e,t){if(t===`released`)return!0;if(t===`toJSON`)return()=>({released:!0});let n=String(t);if(!(typeof t==`symbol`||n.startsWith(`$$`)||n.startsWith(`@@__`)||t===`constructor`||t===`prototype`||t===`__proto__`||t===`then`||t===`asymmetricMatch`||t===`nodeType`||t===`tagName`))throw new Z(`Cannot access "${n}" on released resource`,`INVALID_RESOURCE`)}}),_a=3e4,va=`ResourceClient stream did not initialize before timeout`;function ya(e){return new Promise((t,n)=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(new Z(va,`CONNECTION_FAILED`)))},_a);e.then(e=>{r||(r=!0,clearTimeout(i),t(e))}).catch(e=>{r||(r=!0,clearTimeout(i),n(e))})})}function ba(e){let t=e instanceof Error?e.message:String(e??``);return t.includes(`resource not found`)||t.includes(`invalid resource id`)||t.includes(`resource or client was released`)}var Z=class extends Error{code;cause;constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`ResourceClientError`}},xa=class{listeners=[];on(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}emit(e){[...this.listeners].forEach(t=>{try{t(e)}catch(e){console.error(`Error in event listener:`,e)}})}clear(){this.listeners.length=0}},Sa=class extends wn{resourceClient;constructor(e,t){super(t),this.resourceClient=e}async request(e,t,n,r){return await this.resourceClient.waitForControls(r),super.request(e,t,n,r)}async clientStreamingRequest(e,t,n,r){return await this.resourceClient.waitForControls(r),super.clientStreamingRequest(e,t,n,r)}serverStreamingRequest(e,t,n,r){let i=A({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(r);for await(let a of super.serverStreamingRequest(e,t,n,r))i.push(a);i.end()})().catch(e=>i.end(e)),i}bidirectionalStreamingRequest(e,t,n,r){let i=A({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(r);for await(let a of super.bidirectionalStreamingRequest(e,t,n,r))i.push(a);i.end()})().catch(e=>i.end(e)),i}};function Ca(e,t,n,r){let i=!1,a=()=>{i||(i=!0,n(e,c))},o=null,s=()=>(o||=new Sa(t,async()=>ya(Cr(e.toString(),t.service.ResourceRpc.bind(t.service),!0)).catch(t=>{throw ba(t)&&r(e),t})),o),c={get resourceId(){return e},get released(){return i},get client(){return i?ga:s()},createRef(n){if(i)throw new Z(`Cannot create ref from released resource ${e}`,`INVALID_RESOURCE`);return t.createResourceReference(n)},createResource(e,t,...n){return new t(this.createRef(e),...n)},release:a,[Symbol.dispose]:a,_markReleased(){i=!0}};return c}var wa=class{service;signal;initState=null;connectionController=null;resourceSession=null;resources=new Map;events=new xa;connectionLostEvents=new xa;initPromise=null;disposed=!1;_connectionGeneration=0;_reconnectResolve=null;_reconnectReject=null;attachSession=null;attachSessionInitPromise=null;constructor(e,t){this.service=e,this.signal=t,t.addEventListener(`abort`,()=>{this.dispose(`CLIENT_CANCELLED`)},{once:!0})}get connectionGeneration(){return this._connectionGeneration}onResourceReleased(e){return this.throwIfDisposed(),this.events.on(e)}onConnectionLost(e){return this.throwIfDisposed(),this.connectionLostEvents.on(e)}async accessRootResource(){let e=await this.ensureInitialized();return this.createResourceReference(e.rootResourceId)}async attachRawInvoker(e,t,n){return this.attachResource(e,t,n)}async attachResourceTree(e,t,n,r){return this.attachResource(e,t,n,r)}async attachResource(e,t,n,r){let i=0;for(;;){let a=await this.ensureAttachSession();try{let i=++a.attachIdCtr,o=new Promise((e,t)=>{a.pending.set(i,{resolve:e,reject:t}),n?.addEventListener(`abort`,()=>{let e=a.pending.get(i);e&&(e.canceled=!0),t(Error(`aborted`))},{once:!0})});a.outgoing.push({body:{case:`add`,value:{attachId:i,label:e}}});let s=await o;return a.muxes.set(s,t),r&&a.releaseFns.set(s,r),{resourceId:s,cleanup:()=>{this.releaseAttachedResource(a,s),a.outgoing.push({body:{case:`detach`,value:{resourceId:s}}})}}}catch(e){if(n?.aborted||i>=3||!this.shouldRetryAttachResource(e,a))throw e;i++}}}shouldRetryAttachResource(e,t){return e instanceof Error&&e.message===`attach session closed`&&this.attachSession!==t}async ensureAttachSession(){return this.attachSession?this.attachSession:(this.attachSessionInitPromise||=this.openAttachSession().finally(()=>{this.attachSessionInitPromise=null}),this.attachSessionInitPromise)}async openAttachSession(){let e=await this.ensureInitialized(),t=fa(this.signal),n=A({objectMode:!0}),r=this.service.ResourceAttach((async function*(){yield*n})(),t.signal)[Symbol.asyncIterator]();n.push({body:{case:`init`,value:{clientHandleId:e.clientHandleId}}});let i=await r.next();if(i.done)throw n.end(),t.abort(),Error(`stream closed before ack`);let a=i.value?.body;if(a?.case!==`ack`)throw n.end(),t.abort(),Error(`expected ack packet`);if(a.value.error){n.end(),t.abort();let e=Error(a.value.error);throw a.value.error===`client not found`?(this.resetConnection(),new Z(`Resource attach client was released`,`CONNECTION_FAILED`,e)):e}let o={controller:t,outgoing:n,attachIdCtr:0,closed:!1,muxes:new Map,releaseFns:new Map,pending:new Map},s=new Mt(async(e,t)=>{let n=e.indexOf(`/`);if(n<0)return null;let r=parseInt(e.substring(0,n),10);if(isNaN(r))return null;let i=o.muxes.get(r);return i?i(e.substring(n+1),t):null}),c=new Pn(s,{direction:`inbound`,yamuxParams:{enableKeepAlive:!1}}),l=e=>this.releaseAttachedResource(o,e),u=(async function*(){for(;;){let e=await r.next();if(e.done)break;let t=e.value?.body;if(t?.case===`muxData`)yield t.value;else if(t?.case===`addAck`){let e=t.value,r=e.attachId??0,i=o.pending.get(r);if(o.pending.delete(r),!i)continue;if(i.canceled){e.error||n.push({body:{case:`detach`,value:{resourceId:e.resourceId??0}}});continue}e.error?i.reject(Error(e.error)):i.resolve(e.resourceId??0)}t?.case===`detachAck`&&l(t.value.resourceId??0)}})();return Lt(u,c,wt(),async e=>{for await(let t of e)n.push({body:{case:`muxData`,value:t}});n.end()}).catch(()=>{n.end()}).finally(()=>{this.clearAttachSession(o)}),this.attachSession=o,o}createResourceReference(e){return this.throwIfDisposed(),this.createRef(e)}dispose(e=`CLIENT_DISPOSED`){if(this.disposed)return;this.disposed=!0,this._reconnectReject?.(new Z(`Resource client is closed`,e)),this._reconnectResolve=null,this._reconnectReject=null;let t=e!==`CONNECTION_FAILED`;if(t)for(let e of this.resources.keys())this.queueControl({case:`release`,value:{resourceId:e}});this.clearAttachSession(),t?(this.finishResourceSession(),this.connectionController=null):(this.retireResourceSession(),this.connectionController?.abort(),this.connectionController=null);for(let[e,t]of this.resources.entries())t.forEach(e=>e._markReleased()),this.events.emit({resourceId:e,reason:`client-disposed`});this.resources.clear(),this.events.clear(),this.connectionLostEvents.clear(),this.initState=null,this.initPromise=null}async ensureInitialized(){return this.throwIfDisposed(),this.initState?this.initState:(this.initPromise||=this.performInitialization(),this.initPromise)}async performInitialization(){return this.throwIfDisposed(),this.connectionController=fa(this.signal),new Promise((e,t)=>{let n=!1,r=()=>{n||(this.connectionController=null,this.initPromise=null)},i=()=>{n||(r(),t(new Z(`Client initialization was cancelled`,`CLIENT_CANCELLED`)))};if(this.signal.aborted){i();return}this.signal.addEventListener(`abort`,i,{once:!0}),this.startConnection(e,t,()=>{n=!0,this.signal.removeEventListener(`abort`,i)}).catch(e=>{r(),n||t(new Z(`Failed to initialize client connection`,`CONNECTION_FAILED`,e instanceof Error?e:Error(String(e))))})})}async startConnection(e,t,n){let r=this.connectionController;if(!r)throw new Z(`No connection controller`,`CONNECTION_FAILED`);await ha(r.signal,async t=>{let i=fa(t),a=!1,o=!1,s=setTimeout(()=>{a||i.signal.aborted||(o=!0,i.abort())},_a),c=A({objectMode:!0}),l={controller:i,outgoing:c,generation:this._connectionGeneration,initialized:!1,closed:!1,nextControlId:0,acknowledgedControlId:0,controlWaiters:new Set};this.resourceSession=l;let u=()=>{if(l.closed)return;l.closed=!0,c.end();let e=new Z(`ResourceClient control stream closed`,`CONNECTION_FAILED`);for(let t of l.controlWaiters)t.reject(e);l.controlWaiters.clear(),this.resourceSession===l&&(this.resourceSession=null)},d=()=>{throw new Z(va,`CONNECTION_FAILED`)};try{let r=this.service.ResourceClient((async function*(){yield*c})(),i.signal);c.push({body:{case:`init`,value:{}}});for await(let c of r){if(t.aborted)return;if(i.signal.aborted){o&&d();return}let r=c.body;if(r?.case===`init`){a=!0,l.initialized=!0,s&&clearTimeout(s),s=void 0;let t={clientHandleId:r.value.clientHandleId??0,rootResourceId:r.value.rootResourceId??0};this._reconnectResolve?(this.initState=t,this._reconnectResolve(t),this._reconnectResolve=null,this._reconnectReject=null):this.initState?this.initState=t:(this.initState=t,n(),e(t));continue}if(r?.case===`resourceReleased`){this.handleServerResourceRelease(r.value.resourceId??0);continue}r?.case===`controlAck`&&this.acknowledgeControl(l,r.value.controlId??0)}}catch(e){throw!t.aborted&&o&&d(),e}finally{s&&clearTimeout(s),s=void 0,u(),this.connectionController===r&&!this.disposed&&a&&this.releaseAllResources(`connection-lost`)}if(!this.disposed&&!t.aborted)throw o&&d(),Error(a?`ResourceClient stream closed`:`ResourceClient stream closed before init`)},{errorCb:e=>{this.shouldRetryResourceClientStreamSilently(e)||console.warn(`Retry: retrying after error`,{error:e})}})}throwIfDisposed(){if(this.disposed)throw new Z(`Client has been disposed`,`CLIENT_DISPOSED`)}createRef(e){this.throwIfDisposed();let t=this.resources.get(e),n=!t;t||(t=new Set,this.resources.set(e,t));let r=Ca(e,this,this.releaseRef.bind(this),this.handleServerResourceRelease.bind(this));return t.add(r),n&&this.queueControl({case:`adopt`,value:{resourceId:e}}),r}releaseRef(e,t){let n=this.resources.get(e);n&&(n.delete(t),n.size===0&&(this.resources.delete(e),this.queueControl({case:`release`,value:{resourceId:e}}),this.events.emit({resourceId:e,reason:`client-released`})))}queueControl(e){let t=this.resourceSession;if(!t||t.closed||!t.initialized)return;let n=++t.nextControlId;t.outgoing.push({controlId:n,body:e})}async waitForControls(e){if(e?.aborted)throw Error(Yn);let t=this.resourceSession;if(!t||t.closed||!t.initialized)throw new Z(`ResourceClient control stream is unavailable`,`CONNECTION_FAILED`);let n=t.nextControlId;n<=t.acknowledgedControlId||await new Promise((r,i)=>{let a=()=>{t.controller.signal.removeEventListener(`abort`,c),e?.removeEventListener(`abort`,l)},o={target:n,resolve:()=>{a(),r()},reject:e=>{a(),i(e)}},s=e=>{t.controlWaiters.delete(o)&&o.reject(e)},c=()=>s(new Z(`ResourceClient control stream closed`,`CONNECTION_FAILED`)),l=()=>s(Error(Yn));t.controlWaiters.add(o),t.controller.signal.addEventListener(`abort`,c,{once:!0}),e?.addEventListener(`abort`,l,{once:!0}),t.controller.signal.aborted&&c(),e?.aborted&&l()})}acknowledgeControl(e,t){if(t===0||t!==e.acknowledgedControlId+1||t>e.nextControlId)throw Error(`unexpected ResourceClient control acknowledgment ${t} after ${e.acknowledgedControlId}`);e.acknowledgedControlId=t;for(let n of e.controlWaiters)n.target>t||(e.controlWaiters.delete(n),n.resolve())}shouldRetryResourceClientStreamSilently(e){if(e instanceof Z&&e.message===va||String(e)===`StreamResetError: stream reset`)return!0;if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`),n=Reflect.get(e,`message`);return(typeof t==`string`?t:``)===`StreamResetError`||(typeof n==`string`?n:``)===`stream reset`}handleServerResourceRelease(e){let t=this.resources.get(e);t&&(t.forEach(e=>e._markReleased()),this.resources.delete(e),this.events.emit({resourceId:e,reason:`server-released`}))}releaseAllResources(e){this._connectionGeneration++,this.clearAttachSession();for(let[t,n]of this.resources.entries())n.forEach(e=>e._markReleased()),this.events.emit({resourceId:t,reason:e});this.resources.clear(),this.initState=null,this.initPromise=new Promise((e,t)=>{this._reconnectResolve=e,this._reconnectReject=t}),this.initPromise.catch(()=>{}),this.connectionLostEvents.emit(void 0)}resetConnection(){if(this.disposed)return;let e=this.connectionController;this.connectionController=null,this.clearAttachSession();for(let[e,t]of this.resources.entries())t.forEach(e=>e._markReleased()),this.events.emit({resourceId:e,reason:`connection-lost`});this.resources.clear(),this.initState=null,this.initPromise=null,this._reconnectReject?.(new Z(`Resource generation was replaced`,`CONNECTION_FAILED`)),this._reconnectResolve=null,this._reconnectReject=null,this.retireResourceSession(),e?.abort(),this._connectionGeneration++,this.connectionLostEvents.emit(void 0)}finishResourceSession(){let e=this.resourceSession;e&&(e.closed=!0,e.outgoing.end(),this.resourceSession=null)}retireResourceSession(){let e=this.resourceSession;e&&(e.closed=!0,e.outgoing.end(),e.controller.abort(),this.resourceSession=null)}clearAttachSession(e){let t=e??this.attachSession;if(t&&(this.attachSession===t&&(this.attachSession=null),!t.closed)){t.closed=!0,t.controller.abort(),t.outgoing.end();for(let[,e]of t.pending)e.reject(Error(`attach session closed`));t.pending.clear(),this.releaseAllAttachedResources(t)}}releaseAttachedResource(e,t){let n=e.releaseFns.get(t);e.releaseFns.delete(t),e.muxes.delete(t),n?.()}releaseAllAttachedResources(e){let t=[...e.releaseFns.values()];e.releaseFns.clear(),e.muxes.clear();for(let e of t)e()}};const Ta={typeName:`resource.ResourceService`,methods:{ResourceClient:{name:`ResourceClient`,I:De,O:x,kind:C.BiDiStreaming},ResourceRpc:{name:`ResourceRpc`,I:U,O:U,kind:C.BiDiStreaming},ResourceAttach:{name:`ResourceAttach`,I:h,O:Ce,kind:C.BiDiStreaming}}},Ea=Ta.typeName;var Da=class{rpc;service;constructor(e,t){this.service=t?.service||Ea,this.rpc=e,this.ResourceClient=this.ResourceClient.bind(this),this.ResourceRpc=this.ResourceRpc.bind(this),this.ResourceAttach=this.ResourceAttach.bind(this)}ResourceClient(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Ta.methods.ResourceClient.name,Ht(De)(e),t||void 0);return j(x)(n)}ResourceRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Ta.methods.ResourceRpc.name,Ht(U)(e),t||void 0);return j(U)(n)}ResourceAttach(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,Ta.methods.ResourceAttach.name,Ht(h)(e),t||void 0);return j(Ce)(n)}};async function Oa(e){if(!e)throw Error(`A sync storage directory is required`);let t=new mr(new URL(`./engine-worker.mjs`,import.meta.url),{workerData:zn.toBinary({directory:e}),execArgv:[]}),n=Promise.withResolvers(),r=Promise.withResolvers(),i=new AbortController,a=new Set,o,s,c,l=!1,u=!1,d=e=>{s??=e,n.reject(s),o?.dispose(`CONNECTION_FAILED`),i.abort(s);for(let e of a)e.abort(s);a.clear()};t.on(`error`,d),t.on(`exit`,e=>{u=!0,l||d(Error(`Sync engine Worker exited unexpectedly (${e})`)),i.abort(s),r.resolve()}),t.on(`message`,e=>{try{let t=hn.fromBinary(e);switch(t.kind){case 1:n.resolve();break;case 4:l=!0,t.error&&d(Error(t.error));break;case 5:d(Error(t.error||`Sync engine startup failed`));break;default:d(Error(`Sync engine returned an unsupported lifecycle message`))}}catch(e){d(e instanceof Error?e:Error(String(e)))}});let f=()=>(c??=(async()=>{if(o?.dispose(),!u){t.postMessage({message:hn.toBinary({kind:3})});let e=setTimeout(()=>{d(Error(`Sync engine shutdown timed out`)),t.terminate()},1e4);try{await r.promise}finally{clearTimeout(e)}}if(await Promise.all(Array.from(a,e=>e.close())),a.clear(),s)throw s})(),c),p=setTimeout(()=>{d(Error(`Sync engine startup timed out`)),t.terminate()},3e4);try{return await n.promise,o=new wa(new Da(new wn(async()=>{if(s)throw s;if(c||u)throw Error(`Sync engine is closed`);let{port1:e,port2:n}=new pr,r=An(e),i=r.close.bind(r),o=r.abort.bind(r);return r.close=async()=>{a.delete(r),await i()},r.abort=e=>{a.delete(r),o(e)},a.add(r),t.postMessage({message:hn.toBinary({kind:2}),port:n},[n]),r})),i.signal),{engine:new Fi(await o.accessRootResource()),resources:o,signal:i.signal,close:f}}catch(e){try{await f()}catch{}throw e}finally{clearTimeout(p)}}var Q=n(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),ka=n(((e,t)=>{let{EMPTY_BUFFER:n}=Q(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o}})),Aa=n(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),ja=n(((e,n)=>{let r=t(`zlib`),i=ka(),a=Aa(),{kStatusCode:o}=Q(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&(typeof e.client_max_window_bits==`number`?t.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),Ma=n(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=Q(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r&&(n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)})})),Na=n(((e,n)=>{let{Writable:r}=t(`stream`),i=ja(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Q(),{concat:l,toArrayBuffer:u,unmask:d}=ka(),{isValidStatusCode:f,isValidUTF8:p}=Ma(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._state=this._masked?3:4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),Pa=n(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=ja(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=Q(),{isBlob:u,isValidStatusCode:d}=Ma(),{mask:f,toBuffer:p}=ka(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8192,_,v=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(ee,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);y(this,e,i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function y(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function ee(e,t,n){y(e,t,n),e.onerror(t)}})),Fa=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Q(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean!==void 0&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Ia=n(((e,t)=>{let{tokenChars:n}=Ma();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`)}else if(l===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s){if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),La=n(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=ja(),m=Na(),h=Pa(),{isBlob:g}=Ma(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:ee,kForOnEventAttribute:b,kListener:x,kStatusCode:te,kWebSocket:S,NOOP:ne}=Q(),{EventTarget:{addEventListener:C,removeEventListener:re}}=Fa(),{format:ie,parse:ae}=Ia(),{toBuffer:oe}=ka(),se=Symbol(`kAborted`),w=[8,13],T=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var E=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),le(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,fe),i.on(`drain`,pe),i.on(`error`,me),i.on(`message`,ge),i.on(`ping`,_e),i.on(`pong`,ve),a.onerror=be,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,Se),t.on(`data`,Ce),t.on(`end`,we),t.on(`error`,Te),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){O(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xe(this)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){k(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){k(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){k(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){O(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:T.indexOf(`CONNECTING`)}),Object.defineProperty(E.prototype,"CONNECTING",{enumerable:!0,value:T.indexOf(`CONNECTING`)}),Object.defineProperty(E,"OPEN",{enumerable:!0,value:T.indexOf(`OPEN`)}),Object.defineProperty(E.prototype,"OPEN",{enumerable:!0,value:T.indexOf(`OPEN`)}),Object.defineProperty(E,"CLOSING",{enumerable:!0,value:T.indexOf(`CLOSING`)}),Object.defineProperty(E.prototype,"CLOSING",{enumerable:!0,value:T.indexOf(`CLOSING`)}),Object.defineProperty(E,"CLOSED",{enumerable:!0,value:T.indexOf(`CLOSED`)}),Object.defineProperty(E.prototype,"CLOSED",{enumerable:!0,value:T.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(E.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(E.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),E.prototype.addEventListener=C,E.prototype.removeEventListener=re,n.exports=E;function le(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:w[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!w.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${w.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;D(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?de:ue),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=ie({[p.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ce.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{O(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[se]||(x=e._req=null,D(e,t))}),x.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){O(e,x,`Maximum redirects exceeded`);return}x.abort();let i;try{i=new f(a,t)}catch{D(e,SyntaxError(`Invalid URL: ${a}`));return}le(e,i,n,r)}else e.emit(`unexpected-response`,x,i)||O(e,x,`Unexpected server response: ${i.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==E.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){O(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+ee).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){O(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){O(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){O(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=ae(u)}catch{O(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){O(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[p.extensionName])}catch{O(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function D(e,t){e._readyState=E.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ue(e){return e.path=e.socketPath,o.connect(e)}function de(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function O(e,t,n){e._readyState=E.CLOSING;let r=Error(n);Error.captureStackTrace(r,O),t.setHeader?(t[se]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function k(e,t,n){if(t){let n=g(t)?t.size:oe(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${T[e.readyState]})`);process.nextTick(n,t)}}function fe(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,Ce),process.nextTick(ye,n._socket),e===1005?n.close():n.close(e,t))}function pe(){let e=this[S];e.isPaused||e._socket.resume()}function me(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,Ce),process.nextTick(ye,t._socket),t.close(e[te])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function he(){this[S].emitClose()}function ge(e,t){this[S].emit(`message`,e,t)}function _e(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,ne),t.emit(`ping`,e)}function ve(e){this[S].emit(`pong`,e)}function ye(e){e.resume()}function be(e){let t=this[S];t.readyState!==E.CLOSED&&(t.readyState===E.OPEN&&(t._readyState=E.CLOSING,xe(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function xe(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Se(){let e=this[S];if(this.removeListener(`close`,Se),this.removeListener(`data`,Ce),this.removeListener(`end`,we),e._readyState=E.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,he),e._receiver.on(`finish`,he))}function Ce(e){this[S]._receiver.write(e)||this.pause()}function we(){let e=this[S];e._readyState=E.CLOSING,e._receiver.end(),this.end()}function Te(){let e=this[S];this.removeListener(`error`,Te),this.on(`error`,ne),e&&(e._readyState=E.CLOSING,this.destroy())}})),Ra=n(((e,n)=>{La();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),za=n(((e,t)=>{let{tokenChars:n}=Ma();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Ba=n(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=Ia(),c=ja(),l=za(),u=La(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=Q(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1){if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
3
2
|
`).join(`\r
|
|
4
|
-
`)),i.removeListener(`error`,
|
|
3
|
+
`)),i.removeListener(`error`,_),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(g,this)})),l(d,r)}};function h(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function g(e){e._state=2,e.emit(`close`)}function _(){this.destroy()}function v(e,t,n,r){n||=i.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
|
|
5
4
|
`)+`\r
|
|
6
5
|
\r
|
|
7
|
-
`+n)}function b(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,b),e.emit(`wsClientError`,r,n,t)}else y(n,r,i,a)}}));fo(),lo(),io(),oo(),so(),po(),uo();var ho=e(mo(),1);let go=function(e){return e[e.ERROR_CODE_UNSPECIFIED=0]=`ERROR_CODE_UNSPECIFIED`,e[e.VALIDATION=1]=`VALIDATION`,e[e.AUTHENTICATION=2]=`AUTHENTICATION`,e[e.DENIED=3]=`DENIED`,e[e.MISSING_COLLECTION=4]=`MISSING_COLLECTION`,e[e.SCHEMA_MISMATCH=5]=`SCHEMA_MISMATCH`,e[e.QUERY_LIMIT=6]=`QUERY_LIMIT`,e[e.CONFLICT=7]=`CONFLICT`,e[e.UNAVAILABLE=8]=`UNAVAILABLE`,e[e.UNCERTAIN=9]=`UNCERTAIN`,e[e.STORAGE=10]=`STORAGE`,e[e.CLOSED=11]=`CLOSED`,e}({});const _o=L({typeName:`sdk.sync.Failure`,fields:[{no:1,name:`code`,kind:`enum`,T:ue(`sdk.sync.ErrorCode`,[[0,`ERROR_CODE_UNSPECIFIED`],[1,`VALIDATION`],[2,`AUTHENTICATION`],[3,`DENIED`],[4,`MISSING_COLLECTION`],[5,`SCHEMA_MISMATCH`],[6,`QUERY_LIMIT`],[7,`CONFLICT`],[8,`UNAVAILABLE`],[9,`UNCERTAIN`],[10,`STORAGE`],[11,`CLOSED`]])},{no:2,name:`message`,kind:`scalar`,T:N.STRING},{no:3,name:`request_id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),vo=L({typeName:`sdk.sync.HandshakeRequest`,fields:[{no:1,name:`wire_version`,kind:`scalar`,T:N.UINT32},{no:2,name:`application_id`,kind:`scalar`,T:N.STRING},{no:3,name:`application_version`,kind:`scalar`,T:N.UINT32},{no:4,name:`token`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),yo=L({typeName:`sdk.sync.HandshakeResponse`,fields:[{no:1,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0}),bo=L({typeName:`sdk.sync.OpenCollectionRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),xo=L({typeName:`sdk.sync.OpenCollectionResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:N.UINT32},{no:2,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0}),So=L({typeName:`sdk.sync.GetRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Co=L({typeName:`sdk.sync.GetResponse`,fields:[{no:1,name:`found`,kind:`scalar`,T:N.BOOL},{no:2,name:`data`,kind:`scalar`,T:N.BYTES},{no:3,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0}),wo=L({typeName:`sdk.sync.QueryRequest`,fields:[{no:1,name:`prefix`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),To=L({typeName:`sdk.sync.RecordEntry`,fields:[{no:1,name:`key`,kind:`scalar`,T:N.STRING},{no:2,name:`data`,kind:`scalar`,T:N.BYTES}],packedByDefault:!0}),Eo=L({typeName:`sdk.sync.Snapshot`,fields:[{no:1,name:`entries`,kind:`message`,T:()=>To,repeated:!0},{no:2,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0}),Do=L({typeName:`sdk.sync.PutRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:N.STRING},{no:2,name:`data`,kind:`scalar`,T:N.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),Oo=L({typeName:`sdk.sync.DeleteRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:N.STRING},{no:2,name:`request_id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),ko=L({typeName:`sdk.sync.Acceptance`,fields:[{no:1,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0}),Ao=L({typeName:`sdk.sync.MutationRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:N.STRING},{no:2,name:`input`,kind:`scalar`,T:N.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:N.STRING}],packedByDefault:!0}),jo=L({typeName:`sdk.sync.MutationResponse`,fields:[{no:1,name:`result`,kind:`scalar`,T:N.BYTES},{no:2,name:`error`,kind:`message`,T:()=>_o}],packedByDefault:!0});function $(e){let t=Sr(e);return{code:go[t.code],message:t.message,requestId:t.requestId}}function Mo(e){try{return V(e??new Uint8Array)}catch{throw new R(`VALIDATION`,`Input must be valid UTF-8 JSON`)}}const No={typeName:`sdk.sync.Gateway`,methods:{Authenticate:{name:`Authenticate`,I:vo,O:yo,kind:M.Unary}}},Po=No.typeName,Fo={typeName:`sdk.sync.Application`,methods:{OpenCollection:{name:`OpenCollection`,I:bo,O:xo,kind:M.Unary},Mutate:{name:`Mutate`,I:Ao,O:jo,kind:M.Unary}}};Fo.typeName;const Io={typeName:`sdk.sync.Collection`,methods:{Get:{name:`Get`,I:So,O:Co,kind:M.Unary},Scan:{name:`Scan`,I:wo,O:Eo,kind:M.Unary},Put:{name:`Put`,I:Do,O:ko,kind:M.Unary},Delete:{name:`Delete`,I:Oo,O:ko,kind:M.Unary},Watch:{name:`Watch`,I:wo,O:Eo,kind:M.ServerStreaming}}};Io.typeName;const Lo=new Proxy({released:!0},{get(e,t){if(t===`released`)return!0;if(t===`toJSON`)return()=>({released:!0});if(typeof t!=`symbol`&&t!==`constructor`&&t!==`prototype`&&t!==`__proto__`&&t!==`then`&&t!==`asymmetricMatch`&&t!==`nodeType`&&t!==`tagName`)throw Error(`Cannot access "${String(t)}" on released attached resource`)}});function Ro(e,t){let n=!1,r=()=>{n=!0};return{get resourceId(){return e},get released(){return n||t.signal.aborted},get client(){return n||t.signal.aborted?Lo:t.client},createRef(){throw Error(`Cannot create child ref from raw attached resource ${e}`)},createResource(){throw Error(`Cannot create child resource from raw attached resource ${e}`)},release:r,[Symbol.dispose]:r}}function zo(e,t){let n=!1,r=()=>{n||(n=!0,t.releaseResource(e))};return{get resourceId(){return e},get released(){let r=t.attachedResources.get(e);return n||!r||r.signal.aborted},get client(){let r=t.attachedResources.get(e);return n||!r||r.signal.aborted?Lo:r.client},createRef(r){let i=t.attachedResources.get(e);if(n||!i||i.signal.aborted)throw Error(`Cannot create ref from released attached resource ${e}`);if(!t.attachedResources.has(r))throw Error(`attached child resource ${r} not found`);return zo(r,t)},createResource(e,t,...n){return new t(this.createRef(e),...n)},release:r,[Symbol.dispose]:r}}var Bo=class{clientID;controller;released=!1;resources=new Map;attachedResources=new Map;tombstones=new Set;retainedRootResourceID;txQueue=[];notifyCallbacks=new Set;nextResourceID;pendingChildren=new Map;warnedPending=new Set;warningTimer;now;onPendingWarning;constructor(e,t,n,r={}){this.nextResourceID=e,this.clientID=t,this.controller=new AbortController,this.now=r.now??Date.now,this.onPendingWarning=r.onPendingWarning??(e=>console.warn(`Resource remains pending adoption`,e)),n?.addEventListener(`abort`,()=>this.controller.abort(),{once:!0})}get signal(){return this.controller.signal}setRetainedRootResourceID(e){this.retainedRootResourceID=e}addResource(e,t,n,r,i){if(this.released)throw Error(`client was released`);let a=this.nextResourceID();if(this.resources.set(a,{mux:e,ownerClientID:this.clientID,releaseFn:t,parentResourceID:n,pendingSince:n===void 0?void 0:this.now(),serviceID:r,methodID:i,adopted:!1}),n!==void 0){let e=this.pendingChildren.get(n);e||(e=new Set,this.pendingChildren.set(n,e)),e.add(a),this.schedulePendingWarning()}return a}adoptResource(e){if(this.tombstones.has(e))return this.pushReleased(e),`released`;let t=this.resources.get(e);return t?(t.adopted=!0,t.pendingSince=void 0,this.warnedPending.delete(e),this.schedulePendingWarning(),`adopted`):this.attachedResources.has(e)?`adopted`:`invalid`}getAttachedRef(e){if(!this.attachedResources.has(e))throw Error(`attached resource ${e} not found`);return zo(e,this)}getRawAttachedRef(e){let t=this.attachedResources.get(e);if(!t)throw Error(`attached resource ${e} not found`);return Ro(e,t)}getRawAttachedClient(e){let t=this.attachedResources.get(e);if(!t)throw Error(`attached resource ${e} not found`);return t.client}releaseResource(e,t=!0){if(this.released)return!1;let n=this.resources.get(e);if(!n){let n=this.attachedResources.get(e);return n?(this.attachedResources.delete(e),this.tombstones.add(e),n.controller.abort(),t&&this.pushReleased(e),n.release?.(),!0):this.tombstones.has(e)}return e===this.retainedRootResourceID?(this.releasePendingChildren(e),!0):(this.releasePendingChildren(e),n.parentResourceID!==void 0&&this.pendingChildren.get(n.parentResourceID)?.delete(e),this.resources.delete(e),this.tombstones.add(e),t&&this.pushReleased(e),n.releaseFn?.(),this.warnedPending.delete(e),this.schedulePendingWarning(),!0)}releaseAll(){this.warningTimer!==void 0&&(clearTimeout(this.warningTimer),this.warningTimer=void 0);for(let[e,t]of this.resources)t.parentResourceID===void 0&&this.releaseResourceTree(e);for(;this.resources.size>0;){let e=this.resources.keys().next().value;if(e===void 0)break;this.releaseResourceTree(e)}for(let e of[...this.attachedResources.keys()])this.releaseResource(e,!1);this.released=!0,this.resources.clear(),this.pendingChildren.clear(),this.controller.abort(),this.notify()}pushMessage(e){this.txQueue.push(e),this.notify()}drainQueue(){let e=this.txQueue;return this.txQueue=[],e}waitForNotify(e){return this.txQueue.length>0||this.released||e?.aborted?Promise.resolve():new Promise(t=>{let n=()=>{e?.removeEventListener(`abort`,r),t()},r=()=>{this.notifyCallbacks.delete(n),t()};this.notifyCallbacks.add(n),e?.addEventListener(`abort`,r,{once:!0})})}rootResourceID(){for(let[e,t]of this.resources)if(t.parentResourceID===void 0)return e;return 0}releaseResourceTree(e){for(let t of this.pendingChildren.get(e)??[])this.releaseResourceTree(t);let t=this.resources.get(e);t&&(this.resources.delete(e),this.tombstones.add(e),t.releaseFn?.())}releasePendingChildren(e){let t=[...this.pendingChildren.get(e)??[]];for(let e of t)this.resources.get(e)?.adopted||this.releaseResource(e)}pushReleased(e){this.pushMessage({body:{case:`resourceReleased`,value:{resourceId:e}}})}scanPending(){if(this.released)return;let e=this.now();for(let[t,n]of this.resources)!n.adopted&&n.pendingSince!==void 0&&e-n.pendingSince>=1e4&&!this.warnedPending.has(t)&&(this.warnedPending.add(t),this.onPendingWarning({clientHandleId:this.clientID,parentResourceID:n.parentResourceID??0,resourceID:t,ageMS:e-n.pendingSince,serviceID:n.serviceID,methodID:n.methodID}));this.schedulePendingWarning()}schedulePendingWarning(){if(this.warningTimer!==void 0&&(clearTimeout(this.warningTimer),this.warningTimer=void 0),this.released)return;let e=this.now(),t;for(let[n,r]of this.resources){if(r.adopted||r.pendingSince===void 0||this.warnedPending.has(n))continue;let i=Math.max(0,r.pendingSince+1e4-e);t=t===void 0?i:Math.min(t,i)}t!==void 0&&(this.warningTimer=setTimeout(()=>{this.warningTimer=void 0,this.scanPending()},t))}notify(){for(let e of this.notifyCallbacks)this.notifyCallbacks.delete(e),e()}},Vo=class{init;constructor(e){this.init=e}constructChildResource(e){let{client:t}=this.init,n=new AbortController,r=()=>n.abort();t.signal.addEventListener(`abort`,r,{once:!0});let i;try{i=e(n.signal)}catch(e){throw t.signal.removeEventListener(`abort`,r),n.abort(),e}let a=()=>{t.signal.removeEventListener(`abort`,r);try{i.releaseFn?.()}finally{n.abort()}};try{let e=t.addResource(i.mux,a,this.init.parentResourceId,this.init.serviceId,this.init.methodId);return{result:i.result,resourceId:e}}catch(e){throw a(),e}}getAttachedRef(e){return this.init.client.getAttachedRef(e)}};const Ho=hr();function Uo(e,t){return gr(e,Ho,new Vo(t))}function Wo(e){let t=_r(e,Ho);if(!t)throw Error(`no resource call in server context`);return t}async function Go(e,t){return t?t.aborted?{value:void 0,done:!0}:await new Promise((n,r)=>{let i=()=>t.removeEventListener(`abort`,a),a=()=>{i(),n({value:void 0,done:!0})};if(t.addEventListener(`abort`,a,{once:!0}),t.aborted){a();return}e.next().then(e=>{i(),n(e)},e=>{i(),r(e)})}):await e.next()}var Ko=class{rootResourceMux;clientHandleIDCtr=0;resourceIDCtr=0;clients=new Map;constructor(e){this.rootResourceMux=e??Wt()}register(e){e.register(ut(Qa,this))}nextResourceID(){return++this.resourceIDCtr}ResourceClient(e,t){let n=P({objectMode:!0}),r=e[Symbol.asyncIterator]();return(async()=>{let e=await Go(r,t);if(e.done||e.value.body?.case!==`init`)throw Error(`expected ResourceClient init`);let i=++this.clientHandleIDCtr,a=new Bo(()=>this.nextResourceID(),i,t);this.clients.set(i,a);let o=a.addResource(this.rootResourceMux);a.setRetainedRootResourceID(o),n.push({body:{case:`init`,value:{clientHandleId:i,rootResourceId:o}}});let s=(async()=>{for(;;){await a.waitForNotify(t);let e=a.drainQueue();for(let t of e)n.push(t);if(a.released&&e.length===0)return}})(),c=0;try{for(;!a.released;){let e=await Go(r,t);if(e.done)break;let n=e.value.controlId??0;if(n===0||n!==c+1)throw Error(`unexpected ResourceClient control ID ${n} after ${c}`);let i=e.value.body;if(i?.case===`adopt`){if(a.adoptResource(i.value.resourceId??0)===`invalid`)throw Error(`invalid resource id`)}else if(i?.case===`release`){let e=i.value.resourceId??0;if(!a.releaseResource(e,!1))throw Error(`invalid resource id`)}else throw Error(`invalid ResourceClient control`);c=n,a.pushMessage({body:{case:`controlAck`,value:{controlId:n}}})}}finally{this.clients.delete(i),a.releaseAll(),await s,n.end()}})().catch(e=>n.end(e)),n}findResource(e){for(let[,t]of this.clients){if(t.released)continue;let n=t.resources.get(e);if(n)return{mux:n.mux,client:t}}}ResourceRpc(e,t){return yr(e[Symbol.asyncIterator](),async e=>{let t=parseInt(e,10);if(isNaN(t)||t<=0)throw Error(`invalid component id format`);let n=this.findResource(t);if(!n)throw Error(`resource or client was released`);let{mux:r,client:i}=n;return new Mt(async(e,n)=>{let a=await r.lookupMethod(e,n);return a?async(r,o,s)=>{let c=Uo(s,{client:i,parentResourceId:t,serviceId:e,methodId:n});await a(r,o,c)}:null}).rpcStreamHandler})}ResourceAttach(e,t){let n,r=P({objectMode:!0,onEnd:()=>{n?.()}});return this.runResourceAttach(e,r,t,e=>{n=e}).catch(e=>{r.end(e)}).finally(()=>{r.end()}),r}async runResourceAttach(e,t,n,r){let i=e[Symbol.asyncIterator](),a=await i.next();if(a.done)throw Error(`stream closed before init`);let o=a.value?.body;if(o?.case!==`init`)throw Error(`expected init packet`);let s=o.value.clientHandleId??0,c=this.clients.get(s);if(!c||c.released){t.push({body:{case:`ack`,value:{error:`client not found`}}});return}t.push({body:{case:`ack`,value:{}}});let l=new AbortController,u=new kn(void 0,{direction:`outbound`,yamuxParams:{enableKeepAlive:!1}}),d=u.buildClient(),f=[],p=e=>{if(c.released)throw Error(`resource client generation was released`);let n=e.body;if(n?.case===`add`){let e=n.value.attachId??0,r=n.value.label??``,i=this.nextResourceID(),a=new AbortController,o=qo(d,i,a.signal);l.signal.addEventListener(`abort`,()=>a.abort(),{once:!0}),c.attachedResources.set(i,{label:r,client:o,signal:a.signal,controller:a,release:()=>{t.push({body:{case:`detachAck`,value:{resourceId:i}}})}}),f.push(i),t.push({body:{case:`addAck`,value:{attachId:e,resourceId:i}}})}else if(n?.case===`detach`){let e=n.value.resourceId??0,r=c.attachedResources.has(e);c.releaseResource(e,!1);let i=f.indexOf(e);i>=0&&f.splice(i,1),r||t.push({body:{case:`detachAck`,value:{resourceId:e}}})}},m=(async function*(){for(;;){let e=await i.next();if(e.done)break;let t=e.value?.body;t?.case===`muxData`?yield t.value:(t?.case===`add`||t?.case===`detach`)&&p(e.value)}})(),h=It(m,u,wt(),async e=>{for await(let n of e)t.push({body:{case:`muxData`,value:n}});t.end()}).catch(e=>{t.end(e)}),g=!1,v=()=>{if(!g){g=!0,l.abort(),u.close();for(let e of f)c.releaseResource(e,!1)}};r(v),n?.addEventListener(`abort`,v,{once:!0});try{await h}finally{n?.removeEventListener(`abort`,v),v()}}};function qo(e,t,n){let r=`${t}/`,i=e=>e?AbortSignal.any([n,e]):n;return{request(t,n,a,o){return e.request(r+t,n,a,i(o))},clientStreamingRequest(t,n,a,o){return e.clientStreamingRequest(r+t,n,a,i(o))},serverStreamingRequest(t,n,a,o){return e.serverStreamingRequest(r+t,n,a,i(o))},bidirectionalStreamingRequest(t,n,a,o){return e.bidirectionalStreamingRequest(r+t,n,a,i(o))}}}function Jo(e,t){let n=Wt();n.register(ut(Fo,{OpenCollection:async(n,r,i)=>{try{let r=n.name??``;return await e.openCollection(t,r),{resourceId:Wo(i).constructChildResource(n=>({mux:Yo(e,t,r,n),result:void 0})).resourceId}}catch(e){return{error:$(e)}}},Mutate:async(n,r)=>{try{return{result:B(await e.execute(t,{kind:`mutate`,name:n.name??``,input:Mo(n.input)},{signal:r,requestId:n.requestId}))}}catch(e){return{error:$(e)}}}}));let r=Wt();return new Ko(n).register(r),r}function Yo(e,t,n,r){let i={Get:async(i,a)=>{try{let o=await e.execute(t,{kind:`get`,collection:n,key:i.key??``},{signal:AbortSignal.any([r,a])});return{found:o.found,data:o.found?B(o.value):void 0}}catch(e){return{error:$(e)}}},Scan:async(i,a)=>{try{return Xo(await e.execute(t,{kind:`scan`,collection:n,prefix:i.prefix??``},{signal:AbortSignal.any([r,a])}))}catch(e){return{error:$(e)}}},Put:async(i,a)=>{try{return await e.execute(t,{kind:`put`,collection:n,key:i.key??``,value:Mo(i.data)},{signal:AbortSignal.any([r,a]),requestId:i.requestId}),{}}catch(e){return{error:$(e)}}},Delete:async(i,a)=>{try{return await e.execute(t,{kind:`delete`,collection:n,key:i.key??``},{signal:AbortSignal.any([r,a]),requestId:i.requestId}),{}}catch(e){return{error:$(e)}}},Watch:async function*(i,a){try{for await(let o of e.watch(t,n,i.prefix??``,AbortSignal.any([r,a])))yield Xo(o)}catch(e){yield{error:$(e)}}}},a=Wt();return a.register(ut(Io,i)),a}function Xo(e){return{entries:e.map(e=>({key:e.key,data:B(e.value)}))}}function Zo(e,t,n,r={}){let i=r.path??`/sync`,a=new ho.default({noServer:!0,maxPayload:r.maxRequestBytes??1048576}),o=new Set,s,c=(e,c,l)=>{let u=new URL(e.url??`/`,`http://sync.local`);if(u.pathname!==i)return;let d=e.headers.origin,f=!d||(r.allowedOrigins?r.allowedOrigins.includes(d):d===`http://${e.headers.host}`||d===`https://${e.headers.host}`);if(s||!f||u.search){c.end(`HTTP/1.1 403 Forbidden\r
|
|
6
|
+
`+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));Ra(),Ia(),ja(),Na(),Pa(),za(),La();var Va=e(Ba(),1);let Ha=function(e){return e[e.ERROR_CODE_UNSPECIFIED=0]=`ERROR_CODE_UNSPECIFIED`,e[e.VALIDATION=1]=`VALIDATION`,e[e.AUTHENTICATION=2]=`AUTHENTICATION`,e[e.DENIED=3]=`DENIED`,e[e.MISSING_COLLECTION=4]=`MISSING_COLLECTION`,e[e.SCHEMA_MISMATCH=5]=`SCHEMA_MISMATCH`,e[e.QUERY_LIMIT=6]=`QUERY_LIMIT`,e[e.CONFLICT=7]=`CONFLICT`,e[e.UNAVAILABLE=8]=`UNAVAILABLE`,e[e.UNCERTAIN=9]=`UNCERTAIN`,e[e.STORAGE=10]=`STORAGE`,e[e.CLOSED=11]=`CLOSED`,e}({});const Ua=I({typeName:`sdk.sync.Failure`,fields:[{no:1,name:`code`,kind:`enum`,T:gn(`sdk.sync.ErrorCode`,[[0,`ERROR_CODE_UNSPECIFIED`],[1,`VALIDATION`],[2,`AUTHENTICATION`],[3,`DENIED`],[4,`MISSING_COLLECTION`],[5,`SCHEMA_MISMATCH`],[6,`QUERY_LIMIT`],[7,`CONFLICT`],[8,`UNAVAILABLE`],[9,`UNCERTAIN`],[10,`STORAGE`],[11,`CLOSED`]])},{no:2,name:`message`,kind:`scalar`,T:P.STRING},{no:3,name:`request_id`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),Wa=I({typeName:`sdk.sync.HandshakeRequest`,fields:[{no:1,name:`wire_version`,kind:`scalar`,T:P.UINT32},{no:2,name:`application_id`,kind:`scalar`,T:P.STRING},{no:3,name:`application_version`,kind:`scalar`,T:P.UINT32},{no:4,name:`token`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),Ga=I({typeName:`sdk.sync.HandshakeResponse`,fields:[{no:1,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0}),Ka=I({typeName:`sdk.sync.OpenCollectionRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),qa=I({typeName:`sdk.sync.OpenCollectionResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:P.UINT32},{no:2,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0}),Ja=I({typeName:`sdk.sync.GetRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),Ya=I({typeName:`sdk.sync.GetResponse`,fields:[{no:1,name:`found`,kind:`scalar`,T:P.BOOL},{no:2,name:`data`,kind:`scalar`,T:P.BYTES},{no:3,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0}),Xa=I({typeName:`sdk.sync.QueryRequest`,fields:[{no:1,name:`prefix`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),Za=I({typeName:`sdk.sync.RecordEntry`,fields:[{no:1,name:`key`,kind:`scalar`,T:P.STRING},{no:2,name:`data`,kind:`scalar`,T:P.BYTES}],packedByDefault:!0}),Qa=I({typeName:`sdk.sync.Snapshot`,fields:[{no:1,name:`entries`,kind:`message`,T:()=>Za,repeated:!0},{no:2,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0}),$a=I({typeName:`sdk.sync.PutRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:P.STRING},{no:2,name:`data`,kind:`scalar`,T:P.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),eo=I({typeName:`sdk.sync.DeleteRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:P.STRING},{no:2,name:`request_id`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),to=I({typeName:`sdk.sync.Acceptance`,fields:[{no:1,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0}),no=I({typeName:`sdk.sync.MutationRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:P.STRING},{no:2,name:`input`,kind:`scalar`,T:P.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:P.STRING}],packedByDefault:!0}),ro=I({typeName:`sdk.sync.MutationResponse`,fields:[{no:1,name:`result`,kind:`scalar`,T:P.BYTES},{no:2,name:`error`,kind:`message`,T:()=>Ua}],packedByDefault:!0});function $(e){let t=R(e);return{code:Ha[t.code],message:t.message,requestId:t.requestId}}function io(e){try{return V(e??new Uint8Array)}catch{throw new L(`VALIDATION`,`Input must be valid UTF-8 JSON`)}}const ao={typeName:`sdk.sync.Gateway`,methods:{Authenticate:{name:`Authenticate`,I:Wa,O:Ga,kind:C.Unary}}},oo=ao.typeName,so={typeName:`sdk.sync.Application`,methods:{OpenCollection:{name:`OpenCollection`,I:Ka,O:qa,kind:C.Unary},Mutate:{name:`Mutate`,I:no,O:ro,kind:C.Unary}}};so.typeName;const co={typeName:`sdk.sync.Collection`,methods:{Get:{name:`Get`,I:Ja,O:Ya,kind:C.Unary},Scan:{name:`Scan`,I:Xa,O:Qa,kind:C.Unary},Put:{name:`Put`,I:$a,O:to,kind:C.Unary},Delete:{name:`Delete`,I:eo,O:to,kind:C.Unary},Watch:{name:`Watch`,I:Xa,O:Qa,kind:C.ServerStreaming}}};co.typeName;const lo=new Proxy({released:!0},{get(e,t){if(t===`released`)return!0;if(t===`toJSON`)return()=>({released:!0});if(typeof t!=`symbol`&&t!==`constructor`&&t!==`prototype`&&t!==`__proto__`&&t!==`then`&&t!==`asymmetricMatch`&&t!==`nodeType`&&t!==`tagName`)throw Error(`Cannot access "${String(t)}" on released attached resource`)}});function uo(e,t){let n=!1,r=()=>{n=!0};return{get resourceId(){return e},get released(){return n||t.signal.aborted},get client(){return n||t.signal.aborted?lo:t.client},createRef(){throw Error(`Cannot create child ref from raw attached resource ${e}`)},createResource(){throw Error(`Cannot create child resource from raw attached resource ${e}`)},release:r,[Symbol.dispose]:r}}function fo(e,t){let n=!1,r=()=>{n||(n=!0,t.releaseResource(e))};return{get resourceId(){return e},get released(){let r=t.attachedResources.get(e);return n||!r||r.signal.aborted},get client(){let r=t.attachedResources.get(e);return n||!r||r.signal.aborted?lo:r.client},createRef(r){let i=t.attachedResources.get(e);if(n||!i||i.signal.aborted)throw Error(`Cannot create ref from released attached resource ${e}`);if(!t.attachedResources.has(r))throw Error(`attached child resource ${r} not found`);return fo(r,t)},createResource(e,t,...n){return new t(this.createRef(e),...n)},release:r,[Symbol.dispose]:r}}var po=class{clientID;controller;released=!1;resources=new Map;attachedResources=new Map;tombstones=new Set;retainedRootResourceID;txQueue=[];notifyCallbacks=new Set;nextResourceID;pendingChildren=new Map;warnedPending=new Set;warningTimer;now;onPendingWarning;constructor(e,t,n,r={}){this.nextResourceID=e,this.clientID=t,this.controller=new AbortController,this.now=r.now??Date.now,this.onPendingWarning=r.onPendingWarning??(e=>console.warn(`Resource remains pending adoption`,e)),n?.addEventListener(`abort`,()=>this.controller.abort(),{once:!0})}get signal(){return this.controller.signal}setRetainedRootResourceID(e){this.retainedRootResourceID=e}addResource(e,t,n,r,i){if(this.released)throw Error(`client was released`);let a=this.nextResourceID();if(this.resources.set(a,{mux:e,ownerClientID:this.clientID,releaseFn:t,parentResourceID:n,pendingSince:n===void 0?void 0:this.now(),serviceID:r,methodID:i,adopted:!1}),n!==void 0){let e=this.pendingChildren.get(n);e||(e=new Set,this.pendingChildren.set(n,e)),e.add(a),this.schedulePendingWarning()}return a}adoptResource(e){if(this.tombstones.has(e))return this.pushReleased(e),`released`;let t=this.resources.get(e);return t?(t.adopted=!0,t.pendingSince=void 0,this.warnedPending.delete(e),this.schedulePendingWarning(),`adopted`):this.attachedResources.has(e)?`adopted`:`invalid`}getAttachedRef(e){if(!this.attachedResources.has(e))throw Error(`attached resource ${e} not found`);return fo(e,this)}getRawAttachedRef(e){let t=this.attachedResources.get(e);if(!t)throw Error(`attached resource ${e} not found`);return uo(e,t)}getRawAttachedClient(e){let t=this.attachedResources.get(e);if(!t)throw Error(`attached resource ${e} not found`);return t.client}releaseResource(e,t=!0){if(this.released)return!1;let n=this.resources.get(e);if(!n){let n=this.attachedResources.get(e);return n?(this.attachedResources.delete(e),this.tombstones.add(e),n.controller.abort(),t&&this.pushReleased(e),n.release?.(),!0):this.tombstones.has(e)}return e===this.retainedRootResourceID?(this.releasePendingChildren(e),!0):(this.releasePendingChildren(e),n.parentResourceID!==void 0&&this.pendingChildren.get(n.parentResourceID)?.delete(e),this.resources.delete(e),this.tombstones.add(e),t&&this.pushReleased(e),n.releaseFn?.(),this.warnedPending.delete(e),this.schedulePendingWarning(),!0)}releaseAll(){this.warningTimer!==void 0&&(clearTimeout(this.warningTimer),this.warningTimer=void 0);for(let[e,t]of this.resources)t.parentResourceID===void 0&&this.releaseResourceTree(e);for(;this.resources.size>0;){let e=this.resources.keys().next().value;if(e===void 0)break;this.releaseResourceTree(e)}for(let e of Array.from(this.attachedResources.keys()))this.releaseResource(e,!1);this.released=!0,this.resources.clear(),this.pendingChildren.clear(),this.controller.abort(),this.notify()}pushMessage(e){this.txQueue.push(e),this.notify()}drainQueue(){let e=this.txQueue;return this.txQueue=[],e}waitForNotify(e){return this.txQueue.length>0||this.released||e?.aborted?Promise.resolve():new Promise(t=>{let n=()=>{e?.removeEventListener(`abort`,r),t()},r=()=>{this.notifyCallbacks.delete(n),t()};this.notifyCallbacks.add(n),e?.addEventListener(`abort`,r,{once:!0})})}rootResourceID(){for(let[e,t]of this.resources)if(t.parentResourceID===void 0)return e;return 0}releaseResourceTree(e){for(let t of this.pendingChildren.get(e)??[])this.releaseResourceTree(t);let t=this.resources.get(e);t&&(this.resources.delete(e),this.tombstones.add(e),t.releaseFn?.())}releasePendingChildren(e){let t=[...this.pendingChildren.get(e)??[]];for(let e of t)this.resources.get(e)?.adopted||this.releaseResource(e)}pushReleased(e){this.pushMessage({body:{case:`resourceReleased`,value:{resourceId:e}}})}scanPending(){if(this.released)return;let e=this.now();for(let[t,n]of this.resources)!n.adopted&&n.pendingSince!==void 0&&e-n.pendingSince>=1e4&&!this.warnedPending.has(t)&&(this.warnedPending.add(t),this.onPendingWarning({clientHandleId:this.clientID,parentResourceID:n.parentResourceID??0,resourceID:t,ageMS:e-n.pendingSince,serviceID:n.serviceID,methodID:n.methodID}));this.schedulePendingWarning()}schedulePendingWarning(){if(this.warningTimer!==void 0&&(clearTimeout(this.warningTimer),this.warningTimer=void 0),this.released)return;let e=this.now(),t;for(let[n,r]of this.resources){if(r.adopted||r.pendingSince===void 0||this.warnedPending.has(n))continue;let i=Math.max(0,r.pendingSince+1e4-e);t=t===void 0?i:Math.min(t,i)}t!==void 0&&(this.warningTimer=setTimeout(()=>{this.warningTimer=void 0,this.scanPending()},t))}notify(){for(let e of this.notifyCallbacks)this.notifyCallbacks.delete(e),e()}},mo=class{init;constructor(e){this.init=e}constructChildResource(e){let{client:t}=this.init,n=new AbortController,r=()=>n.abort();t.signal.addEventListener(`abort`,r,{once:!0});let i;try{i=e(n.signal)}catch(e){throw t.signal.removeEventListener(`abort`,r),n.abort(),e}let a=()=>{t.signal.removeEventListener(`abort`,r);try{i.releaseFn?.()}finally{n.abort()}};try{let e=t.addResource(i.mux,a,this.init.parentResourceId,this.init.serviceId,this.init.methodId);return{result:i.result,resourceId:e}}catch(e){throw a(),e}}getAttachedRef(e){return this.init.client.getAttachedRef(e)}};const ho=br();function go(e,t){return xr(e,ho,new mo(t))}function _o(e){let t=Sr(e,ho);if(!t)throw Error(`no resource call in server context`);return t}async function vo(e,t){return t?t.aborted?{value:void 0,done:!0}:await new Promise((n,r)=>{let i=()=>t.removeEventListener(`abort`,a),a=()=>{i(),n({value:void 0,done:!0})};if(t.addEventListener(`abort`,a,{once:!0}),t.aborted){a();return}e.next().then(e=>{i(),n(e)},e=>{i(),r(e)})}):await e.next()}var yo=class{rootResourceMux;clientHandleIDCtr=0;resourceIDCtr=0;clients=new Map;constructor(e){this.rootResourceMux=e??qt()}register(e){e.register(ft(Ta,this))}nextResourceID(){return++this.resourceIDCtr}ResourceClient(e,t){let n=A({objectMode:!0}),r=e[Symbol.asyncIterator]();return(async()=>{let e=await vo(r,t);if(e.done||e.value.body?.case!==`init`)throw Error(`expected ResourceClient init`);let i=++this.clientHandleIDCtr,a=new po(()=>this.nextResourceID(),i,t);this.clients.set(i,a);let o=a.addResource(this.rootResourceMux);a.setRetainedRootResourceID(o),n.push({body:{case:`init`,value:{clientHandleId:i,rootResourceId:o}}});let s=(async()=>{for(;;){await a.waitForNotify(t);let e=a.drainQueue();for(let t of e)n.push(t);if(a.released&&e.length===0)return}})(),c=0;try{for(;!a.released;){let e=await vo(r,t);if(e.done)break;let n=e.value.controlId??0;if(n===0||n!==c+1)throw Error(`unexpected ResourceClient control ID ${n} after ${c}`);let i=e.value.body;if(i?.case===`adopt`){if(a.adoptResource(i.value.resourceId??0)===`invalid`)throw Error(`invalid resource id`)}else if(i?.case===`release`){let e=i.value.resourceId??0;if(!a.releaseResource(e,!1))throw Error(`invalid resource id`)}else throw Error(`invalid ResourceClient control`);c=n,a.pushMessage({body:{case:`controlAck`,value:{controlId:n}}})}}finally{this.clients.delete(i),a.releaseAll(),await s,n.end()}})().catch(e=>n.end(e)),n}findResource(e){for(let[,t]of this.clients){if(t.released)continue;let n=t.resources.get(e);if(n)return{mux:n.mux,client:t}}}ResourceRpc(e,t){return wr(e[Symbol.asyncIterator](),async e=>{let t=parseInt(e,10);if(isNaN(t)||t<=0)throw Error(`invalid component id format`);let n=this.findResource(t);if(!n)throw Error(`resource or client was released`);let{mux:r,client:i}=n;return new Mt(async(e,n)=>{let a=await r.lookupMethod(e,n);return a?async(r,o,s)=>{let c=go(s,{client:i,parentResourceId:t,serviceId:e,methodId:n});await a(r,o,c)}:null}).rpcStreamHandler})}ResourceAttach(e,t){let n,r=A({objectMode:!0,onEnd:()=>{n?.()}});return this.runResourceAttach(e,r,t,e=>{n=e}).catch(e=>{r.end(e)}).finally(()=>{r.end()}),r}async runResourceAttach(e,t,n,r){let i=e[Symbol.asyncIterator](),a=await i.next();if(a.done)throw Error(`stream closed before init`);let o=a.value?.body;if(o?.case!==`init`)throw Error(`expected init packet`);let s=o.value.clientHandleId??0,c=this.clients.get(s);if(!c||c.released){t.push({body:{case:`ack`,value:{error:`client not found`}}});return}t.push({body:{case:`ack`,value:{}}});let l=new AbortController,u=new Pn(void 0,{direction:`outbound`,yamuxParams:{enableKeepAlive:!1}}),d=u.buildClient(),f=[],p=e=>{if(c.released)throw Error(`resource client generation was released`);let n=e.body;if(n?.case===`add`){let e=n.value.attachId??0,r=n.value.label??``,i=this.nextResourceID(),a=new AbortController,o=bo(d,i,a.signal);l.signal.addEventListener(`abort`,()=>a.abort(),{once:!0}),c.attachedResources.set(i,{label:r,client:o,signal:a.signal,controller:a,release:()=>{t.push({body:{case:`detachAck`,value:{resourceId:i}}})}}),f.push(i),t.push({body:{case:`addAck`,value:{attachId:e,resourceId:i}}})}else if(n?.case===`detach`){let e=n.value.resourceId??0,r=c.attachedResources.has(e);c.releaseResource(e,!1);let i=f.indexOf(e);i>=0&&f.splice(i,1),r||t.push({body:{case:`detachAck`,value:{resourceId:e}}})}},m=(async function*(){for(;;){let e=await i.next();if(e.done)break;let t=e.value?.body;t?.case===`muxData`?yield t.value:(t?.case===`add`||t?.case===`detach`)&&p(e.value)}})(),h=Lt(m,u,wt(),async e=>{for await(let n of e)t.push({body:{case:`muxData`,value:n}});t.end()}).catch(e=>{t.end(e)}),g=!1,_=()=>{if(!g){g=!0,l.abort(),u.close();for(let e of f)c.releaseResource(e,!1)}};r(_),n?.addEventListener(`abort`,_,{once:!0});try{await h}finally{n?.removeEventListener(`abort`,_),_()}}};function bo(e,t,n){let r=`${t}/`,i=e=>e?AbortSignal.any([n,e]):n;return{request(t,n,a,o){return e.request(r+t,n,a,i(o))},clientStreamingRequest(t,n,a,o){return e.clientStreamingRequest(r+t,n,a,i(o))},serverStreamingRequest(t,n,a,o){return e.serverStreamingRequest(r+t,n,a,i(o))},bidirectionalStreamingRequest(t,n,a,o){return e.bidirectionalStreamingRequest(r+t,n,a,i(o))}}}function xo(e,t){let n=qt();n.register(ft(so,{OpenCollection:async(n,r,i)=>{try{let r=n.name??``;return await e.openCollection(t,r),{resourceId:_o(i).constructChildResource(n=>({mux:So(e,t,r,n),result:void 0})).resourceId}}catch(e){return{error:$(e)}}},Mutate:async(n,r)=>{try{return{result:B(await e.execute(t,{kind:`mutate`,name:n.name??``,input:io(n.input)},{signal:r,requestId:n.requestId}))}}catch(e){return{error:$(e)}}}}));let r=qt();return new yo(n).register(r),r}function So(e,t,n,r){let i={Get:async(i,a)=>{try{let o=await e.execute(t,{kind:`get`,collection:n,key:i.key??``},{signal:AbortSignal.any([r,a])});return{found:o.found,data:o.found?B(o.value):void 0}}catch(e){return{error:$(e)}}},Scan:async(i,a)=>{try{return Co(await e.execute(t,{kind:`scan`,collection:n,prefix:i.prefix??``},{signal:AbortSignal.any([r,a])}))}catch(e){return{error:$(e)}}},Put:async(i,a)=>{try{return await e.execute(t,{kind:`put`,collection:n,key:i.key??``,value:io(i.data)},{signal:AbortSignal.any([r,a]),requestId:i.requestId}),{}}catch(e){return{error:$(e)}}},Delete:async(i,a)=>{try{return await e.execute(t,{kind:`delete`,collection:n,key:i.key??``},{signal:AbortSignal.any([r,a]),requestId:i.requestId}),{}}catch(e){return{error:$(e)}}},Watch:async function*(i,a){try{for await(let o of e.watch(t,n,i.prefix??``,AbortSignal.any([r,a])))yield Co(o)}catch(e){yield{error:$(e)}}}},a=qt();return a.register(ft(co,i)),a}function Co(e){return{entries:e.map(e=>({key:e.key,data:B(e.value)}))}}function wo(e,t,n,r={}){let i=r.path??`/sync`,a=new Va.default({noServer:!0,maxPayload:r.maxRequestBytes??1048576}),o=new Set,s,c=(e,c,l)=>{let u=new URL(e.url??`/`,`http://sync.local`);if(u.pathname!==i)return;let d=e.headers.origin,f=!d||(r.allowedOrigins?r.allowedOrigins.includes(d):d===`http://${e.headers.host}`||d===`https://${e.headers.host}`);if(s||!f||u.search){c.end(`HTTP/1.1 403 Forbidden\r
|
|
8
7
|
Connection: close\r
|
|
9
8
|
\r
|
|
10
|
-
`);return}a.handleUpgrade(e,c,l,r=>{let i
|
|
9
|
+
`);return}a.handleUpgrade(e,c,l,r=>{let i=Eo(r,e,t,n);o.add(i),i.finally(()=>o.delete(i)).catch(()=>r.terminate())})};e.on(`upgrade`,c);let l=()=>(s??=(async()=>{e.off(`upgrade`,c);for(let e of a.clients)e.close(1001,`Server closed`);let t=setTimeout(()=>{for(let e of a.clients)e.terminate()},1e3);try{await Promise.allSettled(o),await new Promise((e,t)=>a.close(n=>n?t(n):e()))}finally{clearTimeout(t)}})(),s);return{close:l,[Symbol.asyncDispose]:l}}async function To(e,t,n={}){let r=gr((e,t)=>{t.writeHead(404),t.end()}),i=wo(r,e,t,n);try{await new Promise((e,t)=>{let i=e=>t(e);r.once(`error`,i),r.listen(n.port??8787,n.host??`127.0.0.1`,()=>{r.off(`error`,i),e()})})}catch(e){throw await i.close(),e}let a=r.address();if(!a||typeof a==`string`)throw Error(`Listener has no TCP address`);let o=a.address.includes(`:`)?`[${a.address}]`:a.address,s,c=()=>s??=(async()=>{await i.close(),await new Promise((e,t)=>r.close(n=>n?t(n):e()))})();return{url:`ws://${o}:${a.port}${n.path??`/sync`}`,close:c,[Symbol.asyncDispose]:c}}async function Eo(e,t,n,r){let i=new AbortController,a=Promise.withResolvers(),o,s=!1,c,l,u=new Set,d=()=>{i.abort(),e.close(4001,`Authentication ended`)},f=qt();f.register(ft(ao,{Authenticate:async(e,t)=>{try{if(s)throw new L(`AUTHENTICATION`,`This connection already attempted authentication`);if(s=!0,e.wireVersion!==1||e.applicationId!==n.schema.id||e.applicationVersion!==n.schema.version)throw new L(`SCHEMA_MISMATCH`,`Client and server contracts are incompatible`);let a=await r(e.token??``,AbortSignal.any([i.signal,t]));n.checkPrincipal(a),l={...a},o=xo(n,l),l.signal?.addEventListener(`abort`,d,{once:!0}),l.signal?.aborted&&d();let u=()=>{let e=(l?.expiresAt??1/0)-Date.now();e<=0?d():Number.isFinite(e)&&(c=setTimeout(u,Math.min(e,2147483647)))};return u(),{}}catch(e){return{error:$(e instanceof L?e:new L(`AUTHENTICATION`,`Authentication failed`))}}}}));let p=new Mt(async(e,t)=>{let n=e===oo?await f.lookupMethod(e,t):o&&e===Ta.typeName&&t!==`ResourceAttach`?await o.lookupMethod(e,t):null;return n?(e,t,r)=>{let a=n(e,t,{...r,signal:AbortSignal.any([r.signal,i.signal])});return u.add(a),a.finally(()=>u.delete(a)).catch(()=>{}),a}:null}),m=new Pn(p,{direction:`inbound`}),h=bn(e,{remoteAddress:t.socket.remoteAddress,remotePort:t.socket.remotePort}),g=Lt(h,m,wt(),h).catch(e=>m.close(e)).finally(()=>e.close()),_=()=>{i.abort(),m.close(Error(`WebSocket connection ended`)),a.resolve()};e.once(`close`,_),e.once(`error`,_),n.signal.addEventListener(`abort`,d,{once:!0});let v=setTimeout(()=>{o||d()},1e4);try{await a.promise,await Promise.allSettled(u)}finally{clearTimeout(v),c&&clearTimeout(c),l?.signal?.removeEventListener(`abort`,d),n.signal.removeEventListener(`abort`,d),e.off(`close`,_),e.off(`error`,_),i.abort(),await m.muxer.close(),await g}}var Do=class{application;options;owner;closing;attachments=new Set;constructor(e,t,n){this.application=e,this.options=t,this.owner=n}as(e){return this.application.access(e)}admin(e){let t={subject:`admin`,scope:e};return Ar((e,n)=>this.application.execute(t,e,n,!0))}attach(e,t){if(this.closing)throw new L(`CLOSED`,`Server is closed`);let n=wo(e,this.application,this.options.authenticate,t);return this.attachments.add(n),this.track(n)}async listen(e){if(this.closing)throw new L(`CLOSED`,`Server is closed`);let t=await To(this.application,this.options.authenticate,e);if(this.closing)throw await t.close(),new L(`CLOSED`,`Server is closed`);return this.attachments.add(t),{...this.track(t),url:t.url}}close(){return this.closing??=(async()=>{await Promise.all(Array.from(this.attachments,e=>e.close())),await this.application.close(),await this.owner?.close()})(),this.closing}[Symbol.asyncDispose](){return this.close()}track(e){let t=async()=>{try{await e.close()}finally{this.attachments.delete(e)}};return{close:t,[Symbol.asyncDispose]:t}}};async function Oo(e){let t,n;try{e.directory!==void 0&&(t=await Oa(e.directory));let r=e.engine??t?.engine;if(!r)throw new L(`VALIDATION`,`A directory or supplied engine is required`);return n=new da({...e,engine:r}),await n.initialize(e.migration),new Do(n,e,t)}catch(e){throw await n?.close(),await t?.close().catch(()=>{}),R(e)}}const ko=Oo;export{ko as createServer};
|