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/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as ee,v as g,y as _}from"./chunks/errors-BHnASqFk.mjs";async function te(e,t,n){let r=g({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 ne(r,a,()=>d(a))}var ne=class{source;sink;_packetRx;_packetTx;_termination=new t;_cancelRpc;constructor(e,t,n=()=>d(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=m(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{d(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{d(e)}})()}};for(let e of[`dispose`,`asyncDispose`])Symbol[e]||Object.defineProperty(Symbol,e,{value:Symbol.for(`Symbol.${e}`)});function v(e){let t=new AbortController;return e&&(e.aborted?t.abort():e.addEventListener(`abort`,()=>t.abort(),{once:!0})),t}function re(e=500){return()=>e}var ie=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||re(),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 ae(e,t,n){return new ie(t.bind(void 0,e),{...n,abortSignal:e}).result}const oe=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 x(`Cannot access "${n}" on released resource`,`INVALID_RESOURCE`)}}),y=3e4,b=`ResourceClient stream did not initialize before timeout`;function se(e){return new Promise((t,n)=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(new x(b,`CONNECTION_FAILED`)))},y);e.then(e=>{r||(r=!0,clearTimeout(i),t(e))}).catch(e=>{r||(r=!0,clearTimeout(i),n(e))})})}function ce(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 x=class extends Error{code;cause;constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`ResourceClientError`}},S=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}},le=class extends ee{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=g({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=g({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 ue(e,t,n,r){let i=!1,a=()=>{i||(i=!0,n(e,c))},o=null,s=()=>(o||=new le(t,async()=>se(te(e.toString(),t.service.ResourceRpc.bind(t.service),!0)).catch(t=>{throw ce(t)&&r(e),t})),o),c={get resourceId(){return e},get released(){return i},get client(){return i?oe:s()},createRef(n){if(i)throw new x(`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 de=class{service;signal;initState=null;connectionController=null;resourceSession=null;resources=new Map;events=new S;connectionLostEvents=new S;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 t=await this.ensureInitialized(),r=v(this.signal),i=g({objectMode:!0}),a=this.service.ResourceAttach((async function*(){yield*i})(),r.signal)[Symbol.asyncIterator]();i.push({body:{case:`init`,value:{clientHandleId:t.clientHandleId}}});let o=await a.next();if(o.done)throw i.end(),r.abort(),Error(`stream closed before ack`);let l=o.value?.body;if(l?.case!==`ack`)throw i.end(),r.abort(),Error(`expected ack packet`);if(l.value.error){i.end(),r.abort();let e=Error(l.value.error);throw l.value.error===`client not found`?(this.resetConnection(),new x(`Resource attach client was released`,`CONNECTION_FAILED`,e)):e}let u={controller:r,outgoing:i,attachIdCtr:0,closed:!1,muxes:new Map,releaseFns:new Map,pending:new Map},d=new c(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=u.muxes.get(r);return i?i(e.substring(n+1),t):null}),f=new s(d,{direction:`inbound`,yamuxParams:{enableKeepAlive:!1}}),p=e=>this.releaseAttachedResource(u,e),m=(async function*(){for(;;){let e=await a.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,n=e.attachId??0,r=u.pending.get(n);if(u.pending.delete(n),!r)continue;if(r.canceled){e.error||i.push({body:{case:`detach`,value:{resourceId:e.resourceId??0}}});continue}e.error?r.reject(Error(e.error)):r.resolve(e.resourceId??0)}t?.case===`detachAck`&&p(t.value.resourceId??0)}})();return e(m,f,n(),async e=>{for await(let t of e)i.push({body:{case:`muxData`,value:t}});i.end()}).catch(()=>{i.end()}).finally(()=>{this.clearAttachSession(u)}),this.attachSession=u,u}createResourceReference(e){return this.throwIfDisposed(),this.createRef(e)}dispose(e=`CLIENT_DISPOSED`){if(this.disposed)return;this.disposed=!0,this._reconnectReject?.(new x(`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=v(this.signal),new Promise((e,t)=>{let n=!1,r=()=>{n||(this.connectionController=null,this.initPromise=null)},i=()=>{n||(r(),t(new x(`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 x(`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 x(`No connection controller`,`CONNECTION_FAILED`);await ae(r.signal,async t=>{let i=v(t),a=!1,o=!1,s=setTimeout(()=>{a||i.signal.aborted||(o=!0,i.abort())},y),c=g({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 x(`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 x(b,`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 x(`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=ue(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(_);let t=this.resourceSession;if(!t||t.closed||!t.initialized)throw new x(`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 x(`ResourceClient control stream closed`,`CONNECTION_FAILED`)),l=()=>s(Error(_));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 x&&e.message===b||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 x(`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 fe=f(`resource.ResourceClientInitRequest`,!0),pe=l({typeName:`resource.ResourceClientAdopt`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),me=l({typeName:`resource.ResourceClientRelease`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),C=l({typeName:`resource.ResourceClientRequest`,fields:[{no:5,name:`control_id`,kind:`scalar`,T:a.UINT32},{no:2,name:`init`,kind:`message`,T:()=>fe,oneof:`body`},{no:3,name:`adopt`,kind:`message`,T:()=>pe,oneof:`body`},{no:4,name:`release`,kind:`message`,T:()=>me,oneof:`body`}],packedByDefault:!0}),he=l({typeName:`resource.ResourceClientInit`,fields:[{no:1,name:`client_handle_id`,kind:`scalar`,T:a.UINT32},{no:2,name:`root_resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),ge=l({typeName:`resource.ResourceReleasedResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),_e=l({typeName:`resource.ResourceClientControlAck`,fields:[{no:1,name:`control_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),w=l({typeName:`resource.ResourceClientResponse`,fields:[{no:1,name:`init`,kind:`message`,T:()=>he,oneof:`body`},{no:2,name:`resource_released`,kind:`message`,T:()=>ge,oneof:`body`},{no:4,name:`control_ack`,kind:`message`,T:()=>_e,oneof:`body`}],packedByDefault:!0}),ve=l({typeName:`resource.ResourceAttachInit`,fields:[{no:1,name:`client_handle_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),ye=l({typeName:`resource.ResourceAttachAdd`,fields:[{no:1,name:`attach_id`,kind:`scalar`,T:a.UINT32},{no:2,name:`label`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),be=l({typeName:`resource.ResourceAttachDetach`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),T=l({typeName:`resource.ResourceAttachRequest`,fields:[{no:1,name:`init`,kind:`message`,T:()=>ve,oneof:`body`},{no:2,name:`add`,kind:`message`,T:()=>ye,oneof:`body`},{no:3,name:`detach`,kind:`message`,T:()=>be,oneof:`body`},{no:4,name:`mux_data`,kind:`scalar`,T:a.BYTES,oneof:`body`}],packedByDefault:!0}),xe=l({typeName:`resource.ResourceAttachAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),Se=l({typeName:`resource.ResourceAttachAddAck`,fields:[{no:1,name:`attach_id`,kind:`scalar`,T:a.UINT32},{no:2,name:`error`,kind:`scalar`,T:a.STRING},{no:3,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),Ce=l({typeName:`resource.ResourceAttachDetachAck`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32}],packedByDefault:!0}),E=l({typeName:`resource.ResourceAttachResponse`,fields:[{no:1,name:`ack`,kind:`message`,T:()=>xe,oneof:`body`},{no:2,name:`add_ack`,kind:`message`,T:()=>Se,oneof:`body`},{no:3,name:`detach_ack`,kind:`message`,T:()=>Ce,oneof:`body`},{no:4,name:`mux_data`,kind:`scalar`,T:a.BYTES,oneof:`body`}],packedByDefault:!0}),we=l({typeName:`rpcstream.RpcStreamInit`,fields:[{no:1,name:`component_id`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),Te=l({typeName:`rpcstream.RpcAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),D=l({typeName:`rpcstream.RpcStreamPacket`,fields:[{no:1,name:`init`,kind:`message`,T:()=>we,oneof:`body`},{no:2,name:`ack`,kind:`message`,T:()=>Te,oneof:`body`},{no:3,name:`data`,kind:`scalar`,T:a.BYTES,oneof:`body`}],packedByDefault:!0}),O={typeName:`resource.ResourceService`,methods:{ResourceClient:{name:`ResourceClient`,I:C,O:w,kind:u.BiDiStreaming},ResourceRpc:{name:`ResourceRpc`,I:D,O:D,kind:u.BiDiStreaming},ResourceAttach:{name:`ResourceAttach`,I:T,O:E,kind:u.BiDiStreaming}}},Ee=O.typeName;var De=class{rpc;service;constructor(e,t){this.service=t?.service||Ee,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,O.methods.ResourceClient.name,i(C)(e),t||void 0);return r(w)(n)}ResourceRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,O.methods.ResourceRpc.name,i(D)(e),t||void 0);return r(D)(n)}ResourceAttach(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,O.methods.ResourceAttach.name,i(T)(e),t||void 0);return r(E)(n)}},Oe=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))))}}};function k(e){return M(e,`$`,[])}function A(e){return new TextEncoder().encode(k(e))}function j(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 k(n),n}function M(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)?ke(e,t,n):Ae(e,t,n);return n.pop(),r}function ke(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]=M(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 Ae(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:M(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 je(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:N(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:N(n)},r)}}function N(e){try{return j(A(e))}catch{throw new h(`VALIDATION`,`Input must contain only JSON-compatible values`)}}let Me=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 P=l({typeName:`sdk.sync.Failure`,fields:[{no:1,name:`code`,kind:`enum`,T:o(`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:a.STRING},{no:3,name:`request_id`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),F=l({typeName:`sdk.sync.HandshakeRequest`,fields:[{no:1,name:`wire_version`,kind:`scalar`,T:a.UINT32},{no:2,name:`application_id`,kind:`scalar`,T:a.STRING},{no:3,name:`application_version`,kind:`scalar`,T:a.UINT32},{no:4,name:`token`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),I=l({typeName:`sdk.sync.HandshakeResponse`,fields:[{no:1,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),L=l({typeName:`sdk.sync.OpenCollectionRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),R=l({typeName:`sdk.sync.OpenCollectionResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:a.UINT32},{no:2,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),z=l({typeName:`sdk.sync.GetRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),B=l({typeName:`sdk.sync.GetResponse`,fields:[{no:1,name:`found`,kind:`scalar`,T:a.BOOL},{no:2,name:`data`,kind:`scalar`,T:a.BYTES},{no:3,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),V=l({typeName:`sdk.sync.QueryRequest`,fields:[{no:1,name:`prefix`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),Ne=l({typeName:`sdk.sync.RecordEntry`,fields:[{no:1,name:`key`,kind:`scalar`,T:a.STRING},{no:2,name:`data`,kind:`scalar`,T:a.BYTES}],packedByDefault:!0}),H=l({typeName:`sdk.sync.Snapshot`,fields:[{no:1,name:`entries`,kind:`message`,T:()=>Ne,repeated:!0},{no:2,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),U=l({typeName:`sdk.sync.PutRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:a.STRING},{no:2,name:`data`,kind:`scalar`,T:a.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),W=l({typeName:`sdk.sync.DeleteRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:a.STRING},{no:2,name:`request_id`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),G=l({typeName:`sdk.sync.Acceptance`,fields:[{no:1,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),K=l({typeName:`sdk.sync.MutationRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:a.STRING},{no:2,name:`input`,kind:`scalar`,T:a.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:a.STRING}],packedByDefault:!0}),q=l({typeName:`sdk.sync.MutationResponse`,fields:[{no:1,name:`result`,kind:`scalar`,T:a.BYTES},{no:2,name:`error`,kind:`message`,T:()=>P}],packedByDefault:!0}),J={typeName:`sdk.sync.Gateway`,methods:{Authenticate:{name:`Authenticate`,I:F,O:I,kind:u.Unary}}},Pe=J.typeName;var Fe=class{rpc;service;constructor(e,t){this.service=t?.service||Pe,this.rpc=e,this.Authenticate=this.Authenticate.bind(this)}async Authenticate(e,t){let n=F.create(e),r=await this.rpc.request(this.service,J.methods.Authenticate.name,F.toBinary(n),t||void 0);return I.fromBinary(r)}};const Y={typeName:`sdk.sync.Application`,methods:{OpenCollection:{name:`OpenCollection`,I:L,O:R,kind:u.Unary},Mutate:{name:`Mutate`,I:K,O:q,kind:u.Unary}}},Ie=Y.typeName;var Le=class{rpc;service;constructor(e,t){this.service=t?.service||Ie,this.rpc=e,this.OpenCollection=this.OpenCollection.bind(this),this.Mutate=this.Mutate.bind(this)}async OpenCollection(e,t){let n=L.create(e),r=await this.rpc.request(this.service,Y.methods.OpenCollection.name,L.toBinary(n),t||void 0);return R.fromBinary(r)}async Mutate(e,t){let n=K.create(e),r=await this.rpc.request(this.service,Y.methods.Mutate.name,K.toBinary(n),t||void 0);return q.fromBinary(r)}};const X={typeName:`sdk.sync.Collection`,methods:{Get:{name:`Get`,I:z,O:B,kind:u.Unary},Scan:{name:`Scan`,I:V,O:H,kind:u.Unary},Put:{name:`Put`,I:U,O:G,kind:u.Unary},Delete:{name:`Delete`,I:W,O:G,kind:u.Unary},Watch:{name:`Watch`,I:V,O:H,kind:u.ServerStreaming}}},Re=X.typeName;var ze=class{rpc;service;constructor(e,t){this.service=t?.service||Re,this.rpc=e,this.Get=this.Get.bind(this),this.Scan=this.Scan.bind(this),this.Put=this.Put.bind(this),this.Delete=this.Delete.bind(this),this.Watch=this.Watch.bind(this)}async Get(e,t){let n=z.create(e),r=await this.rpc.request(this.service,X.methods.Get.name,z.toBinary(n),t||void 0);return B.fromBinary(r)}async Scan(e,t){let n=V.create(e),r=await this.rpc.request(this.service,X.methods.Scan.name,V.toBinary(n),t||void 0);return H.fromBinary(r)}async Put(e,t){let n=U.create(e),r=await this.rpc.request(this.service,X.methods.Put.name,U.toBinary(n),t||void 0);return G.fromBinary(r)}async Delete(e,t){let n=W.create(e),r=await this.rpc.request(this.service,X.methods.Delete.name,W.toBinary(n),t||void 0);return G.fromBinary(r)}Watch(e,t){let n=V.create(e),i=this.rpc.serverStreamingRequest(this.service,X.methods.Watch.name,V.toBinary(n),t||void 0);return r(H)(i)}};function Z(e){if(!e)return;let t=e.code?Me[e.code]:void 0;throw new h(t??`UNAVAILABLE`,e.message||`The operation failed`,e.requestId||void 0)}async function Be(e){let t=new Ve(e);try{return await t.initialize(),t}catch(e){throw await t.close(),e}}var Ve=class{options;connection;mutate;controller=new AbortController;resources;transport;access;connections=new Set;state={status:`reconnecting`};collections=new Map;work=new Set;readiness=Promise.withResolvers();closing;failure;onAbort=()=>{this.close()};constructor(e){this.options=e;let t=()=>this.state;this.connection={get current(){return t()},subscribe:e=>(this.connections.add(e),e(this.state),()=>this.connections.delete(e))},this.readiness.promise.catch(()=>{}),this.transport=new He(e,this.controller.signal,()=>{this.closing||this.retireRoot()},e=>{this.failure=e,this.readiness.reject(e),this.close()});let n=new ee(async()=>(await this.transport.ensure()).openStream());this.resources=new de(new De(n),this.controller.signal),this.resources.onConnectionLost(()=>{this.retireRoot(),this.refreshRoot()}),this.access=je((e,t)=>{let n=this.dispatch(e,t);return this.track(n),n}),this.mutate=this.access.mutate,e.signal?.addEventListener(`abort`,this.onAbort,{once:!0})}async initialize(){this.options.signal?.throwIfAborted(),await this.transport.ensure(),this.refreshRoot(),await $(this.readiness.promise,AbortSignal.any([this.controller.signal,AbortSignal.timeout(this.options.requestTimeoutMs??15e3)]))}collection(e){let t=this.access.collection(e),n=(t,n)=>this.watch(e,t??{},n);return{...t,watch:n,subscribe:(e,t,r)=>{let i=new AbortController,a=r?.signal?AbortSignal.any([r.signal,i.signal]):i.signal,o=(async()=>{try{for await(let i of n(e,{...r,signal:a}))await t.next(i),i.error&&t.error?.(i.error)}catch(e){a.aborted||t.error?.(Q(e))}})();return this.track(o),()=>i.abort()}}}close(){return this.closing??=(async()=>{let e=this.failure??new h(`CLOSED`,`Client is closed`);this.readiness.reject(e),this.setConnection({status:`closed`,error:this.failure}),this.controller.abort(e),this.resources.dispose(),await this.transport.close(),await Promise.allSettled(this.work),this.collections.clear(),this.connections.clear(),this.options.signal?.removeEventListener(`abort`,this.onAbort)})(),this.closing}[Symbol.asyncDispose](){return this.close()}setConnection(e){this.state=e;for(let t of this.connections)t(e)}retireRoot(){this.closing||(this.state.status===`ready`&&(this.readiness=Promise.withResolvers(),this.readiness.promise.catch(()=>{})),this.collections.clear(),this.setConnection({status:`reconnecting`}))}track(e){this.work.add(e),e.finally(()=>this.work.delete(e)).catch(()=>{})}refreshRoot(){let e=this.resources.connectionGeneration,t=this.readiness,n=(async()=>{let n=await this.resources.accessRootResource();if(this.controller.signal.aborted||n.released||e!==this.resources.connectionGeneration||!this.transport.connected){n.release();return}t.resolve({ref:n,client:new Le(n.client)}),this.setConnection({status:`ready`})})().catch(e=>{this.controller.signal.aborted&&t.reject(this.failure??Q(e))});this.track(n)}async root(e){if(this.closing)throw this.failure??new h(`CLOSED`,`Client is closed`);return $(this.readiness.promise,e)}async remoteCollection(e,t){await this.root(t);let n=this.collections.get(e);if(!n){let t=this.resources.connectionGeneration;n=(async()=>{let n=await this.root(this.controller.signal),r=await n.client.OpenCollection({name:e},this.controller.signal);if(Z(r.error),t!==this.resources.connectionGeneration||n.ref.released)throw new h(`UNAVAILABLE`,`Collection connection was replaced`);let i=this.resources.createResourceReference(r.resourceId??0);return{ref:i,client:new ze(i.client)}})(),this.collections.set(e,n),n.catch(()=>{this.collections.get(e)===n&&this.collections.delete(e)})}return $(n,t)}async dispatch(e,t={}){let n=e.kind!==`get`&&e.kind!==`scan`,r=t.requestId??crypto.randomUUID(),i=AbortSignal.any([this.controller.signal,AbortSignal.timeout(this.options.requestTimeoutMs??15e3),...t.signal?[t.signal]:[]]),a=!1;for(let t=0;t<2;t++)try{if(i.throwIfAborted(),e.kind===`mutate`){let t=await this.root(i);a=!0;let n=await t.client.Mutate({name:e.name,input:A(e.input),requestId:r},i);return Z(n.error),j(n.result??new Uint8Array)}let{client:t}=await this.remoteCollection(e.collection,i);switch(e.kind){case`get`:{let n=await t.Get({key:e.key},i);return Z(n.error),n.found?{found:!0,value:j(n.data??new Uint8Array)}:{found:!1}}case`scan`:{let n=await t.Scan({prefix:e.prefix},i);return Z(n.error),(n.entries??[]).map(e=>({key:e.key??``,value:j(e.data??new Uint8Array)}))}case`put`:return a=!0,Z((await t.Put({key:e.key,data:A(e.value),requestId:r},i)).error),null;case`delete`:return a=!0,Z((await t.Delete({key:e.key,requestId:r},i)).error),null}}catch(e){if(e instanceof h&&![`UNAVAILABLE`,`UNCERTAIN`].includes(e.code))throw e;if(t===1||i.aborted)throw n&&a?new h(`UNCERTAIN`,`Acceptance could not be confirmed; retain this request ID and input for recovery`,r):this.failure??new h(this.closing?`CLOSED`:`UNAVAILABLE`,`The connection is unavailable`);await $(this.readiness.promise,i).catch(()=>{})}throw new h(`UNAVAILABLE`,`The connection is unavailable`)}async*watch(e,t,n){let r=new AbortController,i=AbortSignal.any([this.controller.signal,r.signal,...n?.signal?[n.signal]:[]]);i.throwIfAborted();let a={status:`loading`,data:[]},o=new Oe(async()=>a,{mostRecentOnly:!0}),s=o.getIterable()[Symbol.asyncIterator](),c=e=>{a=e,o.pushChangeEvent(e)},l=()=>{s.return?.()};i.addEventListener(`abort`,l,{once:!0});let u=this.connection.subscribe(e=>{e.status===`reconnecting`&&a.status!==`loading`&&c({status:`stale`,data:a.data}),e.status===`closed`&&e.error&&c({status:`error`,data:a.data,error:e.error})}),d=(async()=>{for(;!i.aborted;){let n=this.resources.connectionGeneration;try{let{client:n}=await this.remoteCollection(e,i);for await(let e of n.Watch({prefix:t.prefix??``},i))Z(e.error),c({status:`current`,data:(e.entries??[]).map(e=>({key:e.key??``,value:j(e.data??new Uint8Array)}))});if(!i.aborted)throw new h(`UNAVAILABLE`,`Subscription connection ended`)}catch(e){if(i.aborted)break;let t=Q(e);if(![`UNAVAILABLE`,`CLOSED`].includes(t.code)||this.state.status!==`reconnecting`&&n===this.resources.connectionGeneration){c({status:`error`,data:a.data,error:t});return}c({status:`stale`,data:a.data}),await $(this.readiness.promise,i).catch(()=>{})}}})();this.track(d);try{for(;;){let e=await s.next();if(e.done||(yield e.value,e.value.status===`error`))break}}finally{r.abort(),u(),i.removeEventListener(`abort`,l),await s.return?.(),await d}}},He=class{options;signal;onClose;onFatal;pending;connection;socket;closed;ended;constructor(e,t,n,r){this.options=e,this.signal=t,this.onClose=n,this.onFatal=r}get connected(){return this.socket?.readyState===WebSocket.OPEN&&this.connection!==void 0}ensure(){return this.signal.aborted?Promise.reject(new h(`CLOSED`,`Client is closed`)):(this.pending??=this.open().catch(e=>{throw this.pending=void 0,e}),this.pending)}close(){return this.closed??=(async()=>{let e=this.connection;this.socket?.close(1e3,`Client closed`),await e?.muxer.close(),await this.ended})(),this.closed}async open(){let e=new URL(this.options.url);if(![`ws:`,`wss:`].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new h(`VALIDATION`,`Use a WebSocket URL without credentials, query, or fragment`);let t=new WebSocket(e),n=AbortSignal.any([this.signal,AbortSignal.timeout(1e4)]);this.socket=t;let r=Promise.withResolvers();this.ended=r.promise;let i=()=>t.close();this.signal.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`close`,()=>{this.signal.removeEventListener(`abort`,i),this.socket===t&&(this.connection?.close(Error(`WebSocket connection ended`)),this.connection=void 0,this.pending=void 0,this.onClose()),r.resolve()},{once:!0});try{await $(new Promise((e,n)=>{t.addEventListener(`open`,()=>e(),{once:!0}),t.addEventListener(`error`,()=>n(new h(`UNAVAILABLE`,`WebSocket connection failed`)),{once:!0})}),n);let e=new p(t,`outbound`);this.connection=e;let r=await $(Promise.resolve().then(()=>this.options.getAccessToken(n)),n);return Z((await new Fe(e.buildClient()).Authenticate({wireVersion:1,applicationId:this.options.schema.id,applicationVersion:this.options.schema.version,token:r},n)).error),e}catch(e){throw t.close(),e instanceof h&&[`AUTHENTICATION`,`SCHEMA_MISMATCH`,`VALIDATION`].includes(e.code)&&this.onFatal(e),e}}};function Q(e){return e instanceof h?e:new h(`UNAVAILABLE`,`The connection is unavailable`)}async function $(e,t){t.throwIfAborted();let n;try{return await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()})])}finally{n&&t.removeEventListener(`abort`,n)}}function Ue(e){if(!e.id||!Number.isSafeInteger(e.version)||e.version<1||e.version>4294967295)throw new h(`VALIDATION`,`Application ID and positive version are required`);return e}export{h as SyncError,Be as connect,Ue as defineSchema};
|
|
1
|
+
import{C as e,S as t,_ as n,b as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as ee,r as m,s as te,u as h,v as g,x as _,y as ne}from"./chunks/json-BuGtLL3Z.mjs";async function re(e,n,r){let i=t({objectMode:!0}),a=n(i);i.push({body:{case:`init`,value:{componentId:e}}});let o=a[Symbol.asyncIterator]();if(r){let e=await o.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 ie(i,o,()=>h(o))}var ie=class{source;sink;_packetRx;_packetTx;_termination=new u;_cancelRpc;constructor(e,t,n=()=>h(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=a(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{h(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{h(e)}})()}};function v(e){let t=new AbortController;return e&&(e.aborted?t.abort():e.addEventListener(`abort`,()=>t.abort(),{once:!0})),t}function ae(e=500){return()=>e}var oe=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||ae(),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 se(e,t,n){return new oe(t.bind(void 0,e),{...n,abortSignal:e}).result}const ce=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 x(`Cannot access "${n}" on released resource`,`INVALID_RESOURCE`)}}),y=3e4,b=`ResourceClient stream did not initialize before timeout`;function le(e){return new Promise((t,n)=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(new x(b,`CONNECTION_FAILED`)))},y);e.then(e=>{r||(r=!0,clearTimeout(i),t(e))}).catch(e=>{r||(r=!0,clearTimeout(i),n(e))})})}function ue(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 x=class extends Error{code;cause;constructor(e,t,n){super(e),this.code=t,this.cause=n,this.name=`ResourceClientError`}},S=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}},C=class extends d{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,n,r,i){let a=t({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(i);for await(let t of super.serverStreamingRequest(e,n,r,i))a.push(t);a.end()})().catch(e=>a.end(e)),a}bidirectionalStreamingRequest(e,n,r,i){let a=t({objectMode:!0});return(async()=>{await this.resourceClient.waitForControls(i);for await(let t of super.bidirectionalStreamingRequest(e,n,r,i))a.push(t);a.end()})().catch(e=>a.end(e)),a}};function de(e,t,n,r){let i=!1,a=()=>{i||(i=!0,n(e,c))},o=null,s=()=>(o||=new C(t,async()=>le(re(e.toString(),t.service.ResourceRpc.bind(t.service),!0)).catch(t=>{throw ue(t)&&r(e),t})),o),c={get resourceId(){return e},get released(){return i},get client(){return i?ce:s()},createRef(n){if(i)throw new x(`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 fe=class{service;signal;initState=null;connectionController=null;resourceSession=null;resources=new Map;events=new S;connectionLostEvents=new S;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(),n=v(this.signal),r=t({objectMode:!0}),a=this.service.ResourceAttach((async function*(){yield*r})(),n.signal)[Symbol.asyncIterator]();r.push({body:{case:`init`,value:{clientHandleId:e.clientHandleId}}});let s=await a.next();if(s.done)throw r.end(),n.abort(),Error(`stream closed before ack`);let c=s.value?.body;if(c?.case!==`ack`)throw r.end(),n.abort(),Error(`expected ack packet`);if(c.value.error){r.end(),n.abort();let e=Error(c.value.error);throw c.value.error===`client not found`?(this.resetConnection(),new x(`Resource attach client was released`,`CONNECTION_FAILED`,e)):e}let l={controller:n,outgoing:r,attachIdCtr:0,closed:!1,muxes:new Map,releaseFns:new Map,pending:new Map},u=new ee(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=l.muxes.get(r);return i?i(e.substring(n+1),t):null}),d=new i(u,{direction:`inbound`,yamuxParams:{enableKeepAlive:!1}}),f=e=>this.releaseAttachedResource(l,e),p=(async function*(){for(;;){let e=await a.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,n=e.attachId??0,i=l.pending.get(n);if(l.pending.delete(n),!i)continue;if(i.canceled){e.error||r.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`&&f(t.value.resourceId??0)}})();return _(p,d,o(),async e=>{for await(let t of e)r.push({body:{case:`muxData`,value:t}});r.end()}).catch(()=>{r.end()}).finally(()=>{this.clearAttachSession(l)}),this.attachSession=l,l}createResourceReference(e){return this.throwIfDisposed(),this.createRef(e)}dispose(e=`CLIENT_DISPOSED`){if(this.disposed)return;this.disposed=!0,this._reconnectReject?.(new x(`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=v(this.signal),new Promise((e,t)=>{let n=!1,r=()=>{n||(this.connectionController=null,this.initPromise=null)},i=()=>{n||(r(),t(new x(`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 x(`Failed to initialize client connection`,`CONNECTION_FAILED`,e instanceof Error?e:Error(String(e))))})})}async startConnection(e,n,r){let i=this.connectionController;if(!i)throw new x(`No connection controller`,`CONNECTION_FAILED`);await se(i.signal,async n=>{let a=v(n),o=!1,s=!1,c=setTimeout(()=>{o||a.signal.aborted||(s=!0,a.abort())},y),l=t({objectMode:!0}),u={controller:a,outgoing:l,generation:this._connectionGeneration,initialized:!1,closed:!1,nextControlId:0,acknowledgedControlId:0,controlWaiters:new Set};this.resourceSession=u;let d=()=>{if(u.closed)return;u.closed=!0,l.end();let e=new x(`ResourceClient control stream closed`,`CONNECTION_FAILED`);for(let t of u.controlWaiters)t.reject(e);u.controlWaiters.clear(),this.resourceSession===u&&(this.resourceSession=null)},f=()=>{throw new x(b,`CONNECTION_FAILED`)};try{let t=this.service.ResourceClient((async function*(){yield*l})(),a.signal);l.push({body:{case:`init`,value:{}}});for await(let i of t){if(n.aborted)return;if(a.signal.aborted){s&&f();return}let t=i.body;if(t?.case===`init`){o=!0,u.initialized=!0,c&&clearTimeout(c),c=void 0;let n={clientHandleId:t.value.clientHandleId??0,rootResourceId:t.value.rootResourceId??0};this._reconnectResolve?(this.initState=n,this._reconnectResolve(n),this._reconnectResolve=null,this._reconnectReject=null):this.initState?this.initState=n:(this.initState=n,r(),e(n));continue}if(t?.case===`resourceReleased`){this.handleServerResourceRelease(t.value.resourceId??0);continue}t?.case===`controlAck`&&this.acknowledgeControl(u,t.value.controlId??0)}}catch(e){throw!n.aborted&&s&&f(),e}finally{c&&clearTimeout(c),c=void 0,d(),this.connectionController===i&&!this.disposed&&o&&this.releaseAllResources(`connection-lost`)}if(!this.disposed&&!n.aborted)throw s&&f(),Error(o?`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 x(`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=de(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(t){if(t?.aborted)throw Error(e);let n=this.resourceSession;if(!n||n.closed||!n.initialized)throw new x(`ResourceClient control stream is unavailable`,`CONNECTION_FAILED`);let r=n.nextControlId;r<=n.acknowledgedControlId||await new Promise((i,a)=>{let o=()=>{n.controller.signal.removeEventListener(`abort`,l),t?.removeEventListener(`abort`,u)},s={target:r,resolve:()=>{o(),i()},reject:e=>{o(),a(e)}},c=e=>{n.controlWaiters.delete(s)&&s.reject(e)},l=()=>c(new x(`ResourceClient control stream closed`,`CONNECTION_FAILED`)),u=()=>c(Error(e));n.controlWaiters.add(s),n.controller.signal.addEventListener(`abort`,l,{once:!0}),t?.addEventListener(`abort`,u,{once:!0}),n.controller.signal.aborted&&l(),t?.aborted&&u()})}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 x&&e.message===b||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 x(`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 pe=n(`resource.ResourceClientInitRequest`,!0),me=g({typeName:`resource.ResourceClientAdopt`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),he=g({typeName:`resource.ResourceClientRelease`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),w=g({typeName:`resource.ResourceClientRequest`,fields:[{no:5,name:`control_id`,kind:`scalar`,T:r.UINT32},{no:2,name:`init`,kind:`message`,T:()=>pe,oneof:`body`},{no:3,name:`adopt`,kind:`message`,T:()=>me,oneof:`body`},{no:4,name:`release`,kind:`message`,T:()=>he,oneof:`body`}],packedByDefault:!0}),ge=g({typeName:`resource.ResourceClientInit`,fields:[{no:1,name:`client_handle_id`,kind:`scalar`,T:r.UINT32},{no:2,name:`root_resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),_e=g({typeName:`resource.ResourceReleasedResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),ve=g({typeName:`resource.ResourceClientControlAck`,fields:[{no:1,name:`control_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),T=g({typeName:`resource.ResourceClientResponse`,fields:[{no:1,name:`init`,kind:`message`,T:()=>ge,oneof:`body`},{no:2,name:`resource_released`,kind:`message`,T:()=>_e,oneof:`body`},{no:4,name:`control_ack`,kind:`message`,T:()=>ve,oneof:`body`}],packedByDefault:!0}),ye=g({typeName:`resource.ResourceAttachInit`,fields:[{no:1,name:`client_handle_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),be=g({typeName:`resource.ResourceAttachAdd`,fields:[{no:1,name:`attach_id`,kind:`scalar`,T:r.UINT32},{no:2,name:`label`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),xe=g({typeName:`resource.ResourceAttachDetach`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),E=g({typeName:`resource.ResourceAttachRequest`,fields:[{no:1,name:`init`,kind:`message`,T:()=>ye,oneof:`body`},{no:2,name:`add`,kind:`message`,T:()=>be,oneof:`body`},{no:3,name:`detach`,kind:`message`,T:()=>xe,oneof:`body`},{no:4,name:`mux_data`,kind:`scalar`,T:r.BYTES,oneof:`body`}],packedByDefault:!0}),Se=g({typeName:`resource.ResourceAttachAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),Ce=g({typeName:`resource.ResourceAttachAddAck`,fields:[{no:1,name:`attach_id`,kind:`scalar`,T:r.UINT32},{no:2,name:`error`,kind:`scalar`,T:r.STRING},{no:3,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),we=g({typeName:`resource.ResourceAttachDetachAck`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32}],packedByDefault:!0}),D=g({typeName:`resource.ResourceAttachResponse`,fields:[{no:1,name:`ack`,kind:`message`,T:()=>Se,oneof:`body`},{no:2,name:`add_ack`,kind:`message`,T:()=>Ce,oneof:`body`},{no:3,name:`detach_ack`,kind:`message`,T:()=>we,oneof:`body`},{no:4,name:`mux_data`,kind:`scalar`,T:r.BYTES,oneof:`body`}],packedByDefault:!0}),O=g({typeName:`rpcstream.RpcStreamInit`,fields:[{no:1,name:`component_id`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),k=g({typeName:`rpcstream.RpcAck`,fields:[{no:1,name:`error`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),A=g({typeName:`rpcstream.RpcStreamPacket`,fields:[{no:1,name:`init`,kind:`message`,T:()=>O,oneof:`body`},{no:2,name:`ack`,kind:`message`,T:()=>k,oneof:`body`},{no:3,name:`data`,kind:`scalar`,T:r.BYTES,oneof:`body`}],packedByDefault:!0}),j={typeName:`resource.ResourceService`,methods:{ResourceClient:{name:`ResourceClient`,I:w,O:T,kind:p.BiDiStreaming},ResourceRpc:{name:`ResourceRpc`,I:A,O:A,kind:p.BiDiStreaming},ResourceAttach:{name:`ResourceAttach`,I:E,O:D,kind:p.BiDiStreaming}}},Te=j.typeName;var Ee=class{rpc;service;constructor(e,t){this.service=t?.service||Te,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,j.methods.ResourceClient.name,s(w)(e),t||void 0);return c(T)(n)}ResourceRpc(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,j.methods.ResourceRpc.name,s(A)(e),t||void 0);return c(A)(n)}ResourceAttach(e,t){let n=this.rpc.bidirectionalStreamingRequest(this.service,j.methods.ResourceAttach.name,s(E)(e),t||void 0);return c(D)(n)}},De=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))))}}};function Oe(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:M(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:M(n)},r)}}function M(e){try{return f(m(e))}catch{throw new l(`VALIDATION`,`Input must contain only JSON-compatible values`)}}let ke=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 N=g({typeName:`sdk.sync.Failure`,fields:[{no:1,name:`code`,kind:`enum`,T:ne(`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:r.STRING},{no:3,name:`request_id`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),P=g({typeName:`sdk.sync.HandshakeRequest`,fields:[{no:1,name:`wire_version`,kind:`scalar`,T:r.UINT32},{no:2,name:`application_id`,kind:`scalar`,T:r.STRING},{no:3,name:`application_version`,kind:`scalar`,T:r.UINT32},{no:4,name:`token`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),F=g({typeName:`sdk.sync.HandshakeResponse`,fields:[{no:1,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),I=g({typeName:`sdk.sync.OpenCollectionRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),L=g({typeName:`sdk.sync.OpenCollectionResponse`,fields:[{no:1,name:`resource_id`,kind:`scalar`,T:r.UINT32},{no:2,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),R=g({typeName:`sdk.sync.GetRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),z=g({typeName:`sdk.sync.GetResponse`,fields:[{no:1,name:`found`,kind:`scalar`,T:r.BOOL},{no:2,name:`data`,kind:`scalar`,T:r.BYTES},{no:3,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),B=g({typeName:`sdk.sync.QueryRequest`,fields:[{no:1,name:`prefix`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),Ae=g({typeName:`sdk.sync.RecordEntry`,fields:[{no:1,name:`key`,kind:`scalar`,T:r.STRING},{no:2,name:`data`,kind:`scalar`,T:r.BYTES}],packedByDefault:!0}),V=g({typeName:`sdk.sync.Snapshot`,fields:[{no:1,name:`entries`,kind:`message`,T:()=>Ae,repeated:!0},{no:2,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),H=g({typeName:`sdk.sync.PutRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:r.STRING},{no:2,name:`data`,kind:`scalar`,T:r.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),U=g({typeName:`sdk.sync.DeleteRequest`,fields:[{no:1,name:`key`,kind:`scalar`,T:r.STRING},{no:2,name:`request_id`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),W=g({typeName:`sdk.sync.Acceptance`,fields:[{no:1,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),G=g({typeName:`sdk.sync.MutationRequest`,fields:[{no:1,name:`name`,kind:`scalar`,T:r.STRING},{no:2,name:`input`,kind:`scalar`,T:r.BYTES},{no:3,name:`request_id`,kind:`scalar`,T:r.STRING}],packedByDefault:!0}),K=g({typeName:`sdk.sync.MutationResponse`,fields:[{no:1,name:`result`,kind:`scalar`,T:r.BYTES},{no:2,name:`error`,kind:`message`,T:()=>N}],packedByDefault:!0}),q={typeName:`sdk.sync.Gateway`,methods:{Authenticate:{name:`Authenticate`,I:P,O:F,kind:p.Unary}}},je=q.typeName;var Me=class{rpc;service;constructor(e,t){this.service=t?.service||je,this.rpc=e,this.Authenticate=this.Authenticate.bind(this)}async Authenticate(e,t){let n=P.create(e),r=await this.rpc.request(this.service,q.methods.Authenticate.name,P.toBinary(n),t||void 0);return F.fromBinary(r)}};const J={typeName:`sdk.sync.Application`,methods:{OpenCollection:{name:`OpenCollection`,I,O:L,kind:p.Unary},Mutate:{name:`Mutate`,I:G,O:K,kind:p.Unary}}},Ne=J.typeName;var Pe=class{rpc;service;constructor(e,t){this.service=t?.service||Ne,this.rpc=e,this.OpenCollection=this.OpenCollection.bind(this),this.Mutate=this.Mutate.bind(this)}async OpenCollection(e,t){let n=I.create(e),r=await this.rpc.request(this.service,J.methods.OpenCollection.name,I.toBinary(n),t||void 0);return L.fromBinary(r)}async Mutate(e,t){let n=G.create(e),r=await this.rpc.request(this.service,J.methods.Mutate.name,G.toBinary(n),t||void 0);return K.fromBinary(r)}};const Y={typeName:`sdk.sync.Collection`,methods:{Get:{name:`Get`,I:R,O:z,kind:p.Unary},Scan:{name:`Scan`,I:B,O:V,kind:p.Unary},Put:{name:`Put`,I:H,O:W,kind:p.Unary},Delete:{name:`Delete`,I:U,O:W,kind:p.Unary},Watch:{name:`Watch`,I:B,O:V,kind:p.ServerStreaming}}},Fe=Y.typeName;var Ie=class{rpc;service;constructor(e,t){this.service=t?.service||Fe,this.rpc=e,this.Get=this.Get.bind(this),this.Scan=this.Scan.bind(this),this.Put=this.Put.bind(this),this.Delete=this.Delete.bind(this),this.Watch=this.Watch.bind(this)}async Get(e,t){let n=R.create(e),r=await this.rpc.request(this.service,Y.methods.Get.name,R.toBinary(n),t||void 0);return z.fromBinary(r)}async Scan(e,t){let n=B.create(e),r=await this.rpc.request(this.service,Y.methods.Scan.name,B.toBinary(n),t||void 0);return V.fromBinary(r)}async Put(e,t){let n=H.create(e),r=await this.rpc.request(this.service,Y.methods.Put.name,H.toBinary(n),t||void 0);return W.fromBinary(r)}async Delete(e,t){let n=U.create(e),r=await this.rpc.request(this.service,Y.methods.Delete.name,U.toBinary(n),t||void 0);return W.fromBinary(r)}Watch(e,t){let n=B.create(e),r=this.rpc.serverStreamingRequest(this.service,Y.methods.Watch.name,B.toBinary(n),t||void 0);return c(V)(r)}};function X(e){if(!e)return;let t=e.code?ke[e.code]:void 0;throw new l(t??`UNAVAILABLE`,e.message||`The operation failed`,e.requestId||void 0)}async function Le(e){let t=new Re(e);try{return await t.initialize(),t}catch(e){throw await t.close(),e}}var Re=class{options;connection;mutate;controller=new AbortController;resources;transport;access;connections=new Set;state={status:`reconnecting`};collections=new Map;work=new Set;readiness=Promise.withResolvers();closing;failure;onAbort=()=>{this.close()};constructor(e){this.options=e;let t=()=>this.state;this.connection={get current(){return t()},subscribe:e=>(this.connections.add(e),e(this.state),()=>this.connections.delete(e))},this.readiness.promise.catch(()=>{}),this.transport=new ze(e,this.controller.signal,()=>{this.closing||this.retireRoot()},e=>{this.failure=e,this.readiness.reject(e),this.close()});let n=new d(async()=>(await this.transport.ensure()).openStream());this.resources=new fe(new Ee(n),this.controller.signal),this.resources.onConnectionLost(()=>{this.retireRoot(),this.refreshRoot()}),this.access=Oe((e,t)=>{let n=this.dispatch(e,t);return this.track(n),n}),this.mutate=this.access.mutate,e.signal?.addEventListener(`abort`,this.onAbort,{once:!0})}async initialize(){this.options.signal?.throwIfAborted(),await this.transport.ensure(),this.refreshRoot(),await Q(this.readiness.promise,AbortSignal.any([this.controller.signal,AbortSignal.timeout(this.options.requestTimeoutMs??15e3)]))}collection(e){let t=this.access.collection(e),n=(t,n)=>this.watch(e,t??{},n);return{...t,watch:n,subscribe:(e,t,r)=>{let i=new AbortController,a=r?.signal?AbortSignal.any([r.signal,i.signal]):i.signal,o=(async()=>{try{for await(let i of n(e,{...r,signal:a}))await t.next(i),i.error&&t.error?.(i.error)}catch(e){a.aborted||t.error?.(Z(e))}})();return this.track(o),()=>i.abort()}}}close(){return this.closing??=(async()=>{let e=this.failure??new l(`CLOSED`,`Client is closed`);this.readiness.reject(e),this.setConnection({status:`closed`,error:this.failure}),this.controller.abort(e),this.resources.dispose(),await this.transport.close(),await Promise.allSettled(this.work),this.collections.clear(),this.connections.clear(),this.options.signal?.removeEventListener(`abort`,this.onAbort)})(),this.closing}[Symbol.asyncDispose](){return this.close()}setConnection(e){this.state=e;for(let t of this.connections)t(e)}retireRoot(){this.closing||(this.state.status===`ready`&&(this.readiness=Promise.withResolvers(),this.readiness.promise.catch(()=>{})),this.collections.clear(),this.setConnection({status:`reconnecting`}))}track(e){this.work.add(e),e.finally(()=>this.work.delete(e)).catch(()=>{})}refreshRoot(){let e=this.resources.connectionGeneration,t=this.readiness,n=(async()=>{let n=await this.resources.accessRootResource();if(this.controller.signal.aborted||n.released||e!==this.resources.connectionGeneration||!this.transport.connected){n.release();return}t.resolve({ref:n,client:new Pe(n.client)}),this.setConnection({status:`ready`})})().catch(e=>{this.controller.signal.aborted&&t.reject(this.failure??Z(e))});this.track(n)}async root(e){if(this.closing)throw this.failure??new l(`CLOSED`,`Client is closed`);return Q(this.readiness.promise,e)}async remoteCollection(e,t){await this.root(t);let n=this.collections.get(e);if(!n){let t=this.resources.connectionGeneration;n=(async()=>{let n=await this.root(this.controller.signal),r=await n.client.OpenCollection({name:e},this.controller.signal);if(X(r.error),t!==this.resources.connectionGeneration||n.ref.released)throw new l(`UNAVAILABLE`,`Collection connection was replaced`);let i=this.resources.createResourceReference(r.resourceId??0);return{ref:i,client:new Ie(i.client)}})(),this.collections.set(e,n),n.catch(()=>{this.collections.get(e)===n&&this.collections.delete(e)})}return Q(n,t)}async dispatch(e,t={}){let n=e.kind!==`get`&&e.kind!==`scan`,r=t.requestId??crypto.randomUUID(),i=AbortSignal.any([this.controller.signal,AbortSignal.timeout(this.options.requestTimeoutMs??15e3),...t.signal?[t.signal]:[]]),a=!1;for(let t=0;t<2;t++)try{if(i.throwIfAborted(),e.kind===`mutate`){let t=await this.root(i);a=!0;let n=await t.client.Mutate({name:e.name,input:m(e.input),requestId:r},i);return X(n.error),f(n.result??new Uint8Array)}let{client:t}=await this.remoteCollection(e.collection,i);switch(e.kind){case`get`:{let n=await t.Get({key:e.key},i);return X(n.error),n.found?{found:!0,value:f(n.data??new Uint8Array)}:{found:!1}}case`scan`:{let n=await t.Scan({prefix:e.prefix},i);return X(n.error),(n.entries??[]).map(e=>({key:e.key??``,value:f(e.data??new Uint8Array)}))}case`put`:return a=!0,X((await t.Put({key:e.key,data:m(e.value),requestId:r},i)).error),null;case`delete`:return a=!0,X((await t.Delete({key:e.key,requestId:r},i)).error),null}}catch(e){if(e instanceof l&&![`UNAVAILABLE`,`UNCERTAIN`].includes(e.code))throw e;if(t===1||i.aborted)throw n&&a?new l(`UNCERTAIN`,`Acceptance could not be confirmed; retain this request ID and input for recovery`,r):this.failure??new l(this.closing?`CLOSED`:`UNAVAILABLE`,`The connection is unavailable`);await Q(this.readiness.promise,i).catch(()=>{})}throw new l(`UNAVAILABLE`,`The connection is unavailable`)}async*watch(e,t,n){let r=new AbortController,i=AbortSignal.any([this.controller.signal,r.signal,...n?.signal?[n.signal]:[]]);i.throwIfAborted();let a={status:`loading`,data:[]},o=new De(async()=>a,{mostRecentOnly:!0}),s=o.getIterable()[Symbol.asyncIterator](),c=e=>{a=e,o.pushChangeEvent(e)},u=()=>{s.return?.()};i.addEventListener(`abort`,u,{once:!0});let d=this.connection.subscribe(e=>{e.status===`reconnecting`&&a.status!==`loading`&&c({status:`stale`,data:a.data}),e.status===`closed`&&e.error&&c({status:`error`,data:a.data,error:e.error})}),p=(async()=>{for(;!i.aborted;){let n=this.resources.connectionGeneration;try{let{client:n}=await this.remoteCollection(e,i);for await(let e of n.Watch({prefix:t.prefix??``},i))X(e.error),c({status:`current`,data:(e.entries??[]).map(e=>({key:e.key??``,value:f(e.data??new Uint8Array)}))});if(!i.aborted)throw new l(`UNAVAILABLE`,`Subscription connection ended`)}catch(e){if(i.aborted)break;let t=Z(e);if(![`UNAVAILABLE`,`CLOSED`].includes(t.code)||this.state.status!==`reconnecting`&&n===this.resources.connectionGeneration){c({status:`error`,data:a.data,error:t});return}c({status:`stale`,data:a.data}),await Q(this.readiness.promise,i).catch(()=>{})}}})();this.track(p);try{for(;;){let e=await s.next();if(e.done||(yield e.value,e.value.status===`error`))break}}finally{r.abort(),d(),i.removeEventListener(`abort`,u),await s.return?.(),await p}}},ze=class{options;signal;onClose;onFatal;pending;connection;socket;closed;ended;constructor(e,t,n,r){this.options=e,this.signal=t,this.onClose=n,this.onFatal=r}get connected(){return this.socket?.readyState===WebSocket.OPEN&&this.connection!==void 0}ensure(){return this.signal.aborted?Promise.reject(new l(`CLOSED`,`Client is closed`)):(this.pending??=this.open().catch(e=>{throw this.pending=void 0,e}),this.pending)}close(){return this.closed??=(async()=>{let e=this.connection;this.socket?.close(1e3,`Client closed`),await e?.muxer.close(),await this.ended})(),this.closed}async open(){let e=new URL(this.options.url);if(![`ws:`,`wss:`].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new l(`VALIDATION`,`Use a WebSocket URL without credentials, query, or fragment`);let t=new WebSocket(e),n=AbortSignal.any([this.signal,AbortSignal.timeout(1e4)]);this.socket=t;let r=Promise.withResolvers();this.ended=r.promise;let i=()=>t.close();this.signal.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`close`,()=>{this.signal.removeEventListener(`abort`,i),this.socket===t&&(this.connection?.close(Error(`WebSocket connection ended`)),this.connection=void 0,this.pending=void 0,this.onClose()),r.resolve()},{once:!0});try{await Q(new Promise((e,n)=>{t.addEventListener(`open`,()=>e(),{once:!0}),t.addEventListener(`error`,()=>n(new l(`UNAVAILABLE`,`WebSocket connection failed`)),{once:!0})}),n);let e=new te(t,`outbound`);this.connection=e;let r=await Q(Promise.resolve().then(()=>this.options.getAccessToken(n)),n);return X((await new Me(e.buildClient()).Authenticate({wireVersion:1,applicationId:this.options.schema.id,applicationVersion:this.options.schema.version,token:r},n)).error),e}catch(e){throw t.close(),e instanceof l&&[`AUTHENTICATION`,`SCHEMA_MISMATCH`,`VALIDATION`].includes(e.code)&&this.onFatal(e),e}}};function Z(e){return e instanceof l?e:new l(`UNAVAILABLE`,`The connection is unavailable`)}async function Q(e,t){t.throwIfAborted();let n;try{return await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()})])}finally{n&&t.removeEventListener(`abort`,n)}}function $(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}function Be(e,t,n={}){return Object.freeze({schema:$(e),mutations:t,migrations:n})}function Ve(e,t){return Object.freeze({...t})}export{l as SyncError,Le as connect,Be as defineApp,Ve as defineQuery,$ as defineSchema};
|
package/dist/react.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{T as e,a as t,i as n,n as r,r as i,t as a,w as o}from"./chunks/json-BuGtLL3Z.mjs";import{createContext as s,use as c,useCallback as l,useEffect as u,useEffectEvent as d,useMemo as f,useRef as p,useState as m}from"react";import{jsx as h}from"react/jsx-runtime";function g(e){let t=p(null),n=p(0);return(t.current===null||!(t.current.length===e.length&&t.current.every((t,n)=>t===e[n])))&&(t.current=[...e],n.current+=1),n.current}function _(e){let[t,n]=m({value:null,loading:e,error:null}),r=p(0),i=p(0),a=l(e=>i.current!==e,[]),o=l(e=>!e.signal.aborted&&e.generation===r.current,[]),s=l(()=>{n(e=>e.loading&&e.error===null?e:{value:e.value,loading:!0,error:null})},[]);return{state:t,isPending:a,isCurrent:o,setLoading:s,resetForRetry:l(()=>{n({value:null,loading:!0,error:null})},[]),settleNull:l((e,t)=>{i.current=e,r.current+=1,n(e=>e.value===null&&e.loading===t&&e.error===null?e:{value:null,loading:t,error:null})},[]),begin:l(e=>{let t=new AbortController;return r.current+=1,i.current=e,s(),{generation:r.current,signal:t.signal,abort:()=>t.abort()}},[s]),complete:l((e,t)=>o(e)?(n({value:t,loading:!1,error:null}),!0):!1,[o]),fail:l((e,t)=>o(e)?(n({value:null,loading:!1,error:t}),!0):!1,[o])}}function v(t,n,r){let i=g([t.value]),[a,o]=m(0),s=p(null),c=l(n,r),d=g([c,i]),{state:h,begin:v,complete:y,fail:b,isCurrent:x,isPending:S,setLoading:C,settleNull:w}=_(!0),T=t.loading||S(d)||h.loading;u(()=>{let n=t.value;if(n===null){w(d,t.loading);return}if(t.loading){C();return}let r=v(d);return(async()=>{let t=!1;try{for await(let e of c(n,r.signal)){if(!x(r))break;t=!0,s.current===i&&(s.current=null),y(r,e)}if(!x(r))return;t||y(r,null)}catch(t){if(!x(r))return;let n=t instanceof Error?t:Error(String(t));if(e(t)||n.name===`AbortError`){if(s.current!==i){s.current=i,o(e=>e+1);return}b(r,n);return}b(r,n)}})(),()=>r.abort()},[t.loading,t.value,i,a,d,v,y,b,x,C,w,c]);let E=l(()=>{o(e=>e+1)},[]);return f(()=>({value:h.value,loading:T,error:t.error??h.error,retry:t.error?t.retry:E}),[h.value,T,h.error,E,t.error,t.retry])}function y(e){let t=s(null);function r({db:e,children:n}){return h(t.Provider,{value:e,children:n})}function i(){let e=c(t);if(!e)throw Error(`useDatabase must be called within the SyncProvider returned by createSyncContext`);return e}function a(e,t={}){let r=i(),a=t.prefix??``,o=v(f(()=>({value:r,loading:!1,error:null,retry:()=>{}}),[r]),(t,n)=>t.collection(e).watch({prefix:a},{signal:n}),[r,e,a]);return o.loading?{status:`loading`,data:[]}:o.value?o.value:o.error?{status:`error`,data:[],error:o.error instanceof n?o.error:new n(`UNAVAILABLE`,`The collection subscription failed`)}:{status:`loading`,data:[]}}return{SyncProvider:r,useDatabase:i,useCollection:a}}var b=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 x=s(null);function S(){return c(x)}const C=s(void 0);function w(){return c(C)}function T(){return w()?.client??null}let E=1;function D(){let e=p(null);return e.current===null&&(e.current=`_r_${E++}_`),e.current}function O(e){let[t,n,r,i]=e;if(typeof t==`function`){if(!Array.isArray(n))throw Error(`useResource: deps array is required as second argument`);return{type:`no-parent`,factory:t,deps:n,options:r,parents:[]}}if(Array.isArray(t)){if(!Array.isArray(r))throw Error(`useResource: deps array is required as third argument`);return{type:`multi-parent`,factory:n,deps:r,options:i,parents:t}}if(!Array.isArray(r))throw Error(`useResource: deps array is required as third argument`);return{type:`single-parent`,factory:n,deps:r,options:i,parents:[t]}}function k(e){let t=e.map(e=>e.value),n=f(()=>t,t),r=e.some(e=>e.loading),i=e.find(e=>e.error)?.error??null,a=e.map(e=>e.retry);return{values:n,loading:r,error:i,retries:f(()=>a,a)}}async function A(e,t,n,r){return e.type===`no-parent`?e.factory(n,r):e.type===`single-parent`?e.factory(t[0],n,r):e.factory(t,n,r)}function j(e){let t=e?.retryOnReleasedResource;return t===!1?[]:t===void 0||t===!0?[`server-released`]:t.reasons??[`server-released`]}function M(e,t){let n=t?.retryOnReleasedResource;return n===!1?[]:n&&n!==!0&&n.getResourceIds?n.getResourceIds(e):e instanceof b?[e.id]:[]}function N(...e){let[t,n,r,i]=e,a=D(),s=S(),c=T(),h=f(()=>O(e),[t,n,r,i]),v=h.options?.enabled??!0,y=k(h.parents),x=g(y.values),C=g([l(h.factory,h.deps),x]),{state:w,begin:E,complete:N,fail:P,isPending:F,resetForRetry:I,settleNull:L}=_(v&&!y.loading),R=F(C)||w.loading,[z,B]=m(0),V=d(e=>{e!==null&&h.options?.onSuccess?.(e)}),H=d(e=>{h.options?.onError?.(e)}),U=l(()=>{y.retries.forEach(e=>e()),I(),B(e=>e+1)},[y.retries,I]),W=f(()=>j(h.options),[h.options]),G=f(()=>!v||w.value===null?[]:M(w.value,h.options),[v,w.value,h.options]),K=p(!1),q=p(null),J=f(()=>y.values.flatMap(e=>e instanceof b?[e.id]:[]),[y.values]);u(()=>{K.current=!1},[z,w.value]),u(()=>{if(c&&J.length!==0)return c.onResourceReleased(e=>{(e.reason===`server-released`||e.reason===`connection-lost`||e.reason===`client-released`)&&J.includes(e.resourceId)&&q.current?.abort()})},[J,c]);let Y=h.parents.flatMap(e=>{let t=e.__devtools?.id;return t==null?[]:[t]}),X=f(()=>Y,Y),Z=p(U);Z.current=U;let Q=p(w);Q.current=w,u(()=>{if(!s)return;s.register(a,X,()=>Z.current());let e=Q.current,t=e.loading?`loading`:e.error?`error`:`ready`;return s.update(a,t,e.value,e.error),()=>{s.unregister(a)}},[s,a,X]);let $=p({loading:w.loading,error:w.error,value:w.value});return u(()=>{if(!s)return;let e=$.current;if(e.loading===w.loading&&e.error===w.error&&e.value===w.value)return;$.current={loading:w.loading,error:w.error,value:w.value};let t=w.loading?`loading`:w.error?`error`:`ready`;s.update(a,t,w.value,w.error)},[s,a,w.loading,w.error,w.value]),u(()=>{if(!v){L(C,!1);return}if(y.values.some(e=>e===null)){L(C,y.loading);return}if(y.loading)return;if(y.values.some(e=>e instanceof b&&e.released)){L(C,!0);return}let e=[],t=E(C);q.current=t;let n=!1,r=t=>t&&(n?(queueMicrotask(()=>t[Symbol.dispose]()),t):(e.push(t),t)),i=()=>{n=!0,e.forEach(e=>e[Symbol.dispose]())};async function a(){try{let e=await A(h,y.values,t.signal,r);if(!N(t,e)){i();return}V(e)}catch(e){i();let n=o(e);P(t,n)&&H(n)}finally{q.current===t&&(q.current=null)}}return a(),()=>{t.abort(),q.current===t&&(q.current=null),i()}},[z,v,y.loading,C,E,N,P,L]),u(()=>{if(c&&!w.loading&&W.length!==0&&G.length!==0)return c.onResourceReleased(e=>{W.includes(e.reason)&&G.includes(e.resourceId)&&(K.current||(K.current=!0,U()))})},[G,W,c,U,w.loading]),f(()=>({value:v?w.value:null,loading:v&&(y.loading||R),error:v?y.error||w.error:null,retry:U,__devtools:s?{id:a}:void 0}),[v,w.value,R,w.error,y.loading,y.error,U,s,a])}function P(e,n,r){let i=a(r),o=v(f(()=>({value:e,loading:!1,error:null,retry:()=>{}}),[e]),(e,t)=>e.watch(n,JSON.parse(i),t),[e,n,i]);return!e||o.loading?{status:`pending`}:o.error?{status:`error`,error:t(o.error)}:o.value??{status:`pending`}}function F(e,a){let[o,s]=m(null),c=p(o),l=e&&o?.source===e&&o.name===a?o:null,u=N(async e=>l?l.source.mutate(l.name,l.input,{signal:e,requestId:l.requestId}):null,[l]),d=t=>{if(!e)throw new n(`UNAVAILABLE`,`Application is not ready`);if(c.current?.source===e&&c.current.name===a&&(c.current!==l||u.loading))throw new n(`CONFLICT`,`An operation is still pending`);let o={source:e,name:a,input:r(i(t)),requestId:crypto.randomUUID()};c.current=o,s(o)},f={status:`idle`};if(l){let e=l.requestId;f=u.loading?{status:`pending`,requestId:e}:u.error?{status:`error`,requestId:e,error:t(u.error)}:{status:`accepted`,requestId:e,value:u.value}}return{submit:d,state:f,retry:u.retry}}export{y as createSyncContext,F as useAppMutation,P as useAppQuery};
|